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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a34e43aece70e2d5d62873b1908597e3e32cda4
| 57,180 |
ipynb
|
Jupyter Notebook
|
Cat2.ipynb
|
uditmaherwal/CatClassifier
|
2b3a5cb31c6384aa7bfba8b1ce0c5a6ad2042c99
|
[
"MIT"
] | 1 |
2020-04-25T05:01:31.000Z
|
2020-04-25T05:01:31.000Z
|
Cat2.ipynb
|
uditmaherwal/CatClassifier
|
2b3a5cb31c6384aa7bfba8b1ce0c5a6ad2042c99
|
[
"MIT"
] | null | null | null |
Cat2.ipynb
|
uditmaherwal/CatClassifier
|
2b3a5cb31c6384aa7bfba8b1ce0c5a6ad2042c99
|
[
"MIT"
] | 1 |
2020-05-08T10:01:37.000Z
|
2020-05-08T10:01:37.000Z
| 37.767503 | 562 | 0.514271 |
[
[
[
"# Building your Deep Neural Network: Step by Step\n\nWelcome to your week 4 assignment (part 1 of 2)! You have previously trained a 2-layer Neural Network (with a single hidden layer). This week, you will build a deep neural network, with as many layers as you want!\n\n- In this notebook, you will implement all the functions required to build a deep neural network.\n- In the next assignment, you will use these functions to build a deep neural network for image classification.\n\n**After this assignment you will be able to:**\n- Use non-linear units like ReLU to improve your model\n- Build a deeper neural network (with more than 1 hidden layer)\n- Implement an easy-to-use neural network class\n\n**Notation**:\n- Superscript $[l]$ denotes a quantity associated with the $l^{th}$ layer. \n - Example: $a^{[L]}$ is the $L^{th}$ layer activation. $W^{[L]}$ and $b^{[L]}$ are the $L^{th}$ layer parameters.\n- Superscript $(i)$ denotes a quantity associated with the $i^{th}$ example. \n - Example: $x^{(i)}$ is the $i^{th}$ training example.\n- Lowerscript $i$ denotes the $i^{th}$ entry of a vector.\n - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the $l^{th}$ layer's activations).\n\nLet's get started!",
"_____no_output_____"
],
[
"### <font color='darkblue'> Updates to Assignment <font>\n\n#### If you were working on a previous version\n* The current notebook filename is version \"4a\". \n* You can find your work in the file directory as version \"4\".\n* To see the file directory, click on the Coursera logo at the top left of the notebook.\n\n#### List of Updates\n* compute_cost unit test now includes tests for Y = 0 as well as Y = 1. This catches a possible bug before students get graded.\n* linear_backward unit test now has a more complete unit test that catches a possible bug before students get graded.\n",
"_____no_output_____"
],
[
"## 1 - Packages\n\nLet's first import all the packages that you will need during this assignment. \n- [numpy](www.numpy.org) is the main package for scientific computing with Python.\n- [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.\n- dnn_utils provides some necessary functions for this notebook.\n- testCases provides some test cases to assess the correctness of your functions\n- np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work. Please don't change the seed. ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nfrom testCases_v4a import *\nfrom dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n%load_ext autoreload\n%autoreload 2\n\nnp.random.seed(1)",
"_____no_output_____"
]
],
[
[
"## 2 - Outline of the Assignment\n\nTo build your neural network, you will be implementing several \"helper functions\". These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. Each small helper function you will implement will have detailed instructions that will walk you through the necessary steps. Here is an outline of this assignment, you will:\n\n- Initialize the parameters for a two-layer network and for an $L$-layer neural network.\n- Implement the forward propagation module (shown in purple in the figure below).\n - Complete the LINEAR part of a layer's forward propagation step (resulting in $Z^{[l]}$).\n - We give you the ACTIVATION function (relu/sigmoid).\n - Combine the previous two steps into a new [LINEAR->ACTIVATION] forward function.\n - Stack the [LINEAR->RELU] forward function L-1 time (for layers 1 through L-1) and add a [LINEAR->SIGMOID] at the end (for the final layer $L$). This gives you a new L_model_forward function.\n- Compute the loss.\n- Implement the backward propagation module (denoted in red in the figure below).\n - Complete the LINEAR part of a layer's backward propagation step.\n - We give you the gradient of the ACTIVATE function (relu_backward/sigmoid_backward) \n - Combine the previous two steps into a new [LINEAR->ACTIVATION] backward function.\n - Stack [LINEAR->RELU] backward L-1 times and add [LINEAR->SIGMOID] backward in a new L_model_backward function\n- Finally update the parameters.\n\n<img src=\"images/final outline.png\" style=\"width:800px;height:500px;\">\n<caption><center> **Figure 1**</center></caption><br>\n\n\n**Note** that for every forward function, there is a corresponding backward function. That is why at every step of your forward module you will be storing some values in a cache. The cached values are useful for computing gradients. In the backpropagation module you will then use the cache to calculate the gradients. This assignment will show you exactly how to carry out each of these steps. ",
"_____no_output_____"
],
[
"## 3 - Initialization\n\nYou will write two helper functions that will initialize the parameters for your model. The first function will be used to initialize parameters for a two layer model. The second one will generalize this initialization process to $L$ layers.\n\n### 3.1 - 2-layer Neural Network\n\n**Exercise**: Create and initialize the parameters of the 2-layer neural network.\n\n**Instructions**:\n- The model's structure is: *LINEAR -> RELU -> LINEAR -> SIGMOID*. \n- Use random initialization for the weight matrices. Use `np.random.randn(shape)*0.01` with the correct shape.\n- Use zero initialization for the biases. Use `np.zeros(shape)`.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_parameters\n\ndef initialize_parameters(n_x, n_h, n_y):\n \"\"\"\n Argument:\n n_x -- size of the input layer\n n_h -- size of the hidden layer\n n_y -- size of the output layer\n \n Returns:\n parameters -- python dictionary containing your parameters:\n W1 -- weight matrix of shape (n_h, n_x)\n b1 -- bias vector of shape (n_h, 1)\n W2 -- weight matrix of shape (n_y, n_h)\n b2 -- bias vector of shape (n_y, 1)\n \"\"\"\n \n np.random.seed(1)\n \n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = np.random.randn(n_h,n_x) * 0.01\n b1 = np.zeros(shape=(n_h,1))\n W2 = np.random.randn(n_y,n_h) * 0.01\n b2 = np.zeros(shape=(n_y,1))\n ### END CODE HERE ###\n \n assert(W1.shape == (n_h, n_x))\n assert(b1.shape == (n_h, 1))\n assert(W2.shape == (n_y, n_h))\n assert(b2.shape == (n_y, 1))\n \n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2}\n \n return parameters ",
"_____no_output_____"
],
[
"parameters = initialize_parameters(3,2,1)\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"W1 = [[ 0.01624345 -0.00611756 -0.00528172]\n [-0.01072969 0.00865408 -0.02301539]]\nb1 = [[ 0.]\n [ 0.]]\nW2 = [[ 0.01744812 -0.00761207]]\nb2 = [[ 0.]]\n"
]
],
[
[
"**Expected output**:\n \n<table style=\"width:80%\">\n <tr>\n <td> **W1** </td>\n <td> [[ 0.01624345 -0.00611756 -0.00528172]\n [-0.01072969 0.00865408 -0.02301539]] </td> \n </tr>\n\n <tr>\n <td> **b1**</td>\n <td>[[ 0.]\n [ 0.]]</td> \n </tr>\n \n <tr>\n <td>**W2**</td>\n <td> [[ 0.01744812 -0.00761207]]</td>\n </tr>\n \n <tr>\n <td> **b2** </td>\n <td> [[ 0.]] </td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"### 3.2 - L-layer Neural Network\n\nThe initialization for a deeper L-layer neural network is more complicated because there are many more weight matrices and bias vectors. When completing the `initialize_parameters_deep`, you should make sure that your dimensions match between each layer. Recall that $n^{[l]}$ is the number of units in layer $l$. Thus for example if the size of our input $X$ is $(12288, 209)$ (with $m=209$ examples) then:\n\n<table style=\"width:100%\">\n\n\n <tr>\n <td> </td> \n <td> **Shape of W** </td> \n <td> **Shape of b** </td> \n <td> **Activation** </td>\n <td> **Shape of Activation** </td> \n <tr>\n \n <tr>\n <td> **Layer 1** </td> \n <td> $(n^{[1]},12288)$ </td> \n <td> $(n^{[1]},1)$ </td> \n <td> $Z^{[1]} = W^{[1]} X + b^{[1]} $ </td> \n \n <td> $(n^{[1]},209)$ </td> \n <tr>\n \n <tr>\n <td> **Layer 2** </td> \n <td> $(n^{[2]}, n^{[1]})$ </td> \n <td> $(n^{[2]},1)$ </td> \n <td>$Z^{[2]} = W^{[2]} A^{[1]} + b^{[2]}$ </td> \n <td> $(n^{[2]}, 209)$ </td> \n <tr>\n \n <tr>\n <td> $\\vdots$ </td> \n <td> $\\vdots$ </td> \n <td> $\\vdots$ </td> \n <td> $\\vdots$</td> \n <td> $\\vdots$ </td> \n <tr>\n \n <tr>\n <td> **Layer L-1** </td> \n <td> $(n^{[L-1]}, n^{[L-2]})$ </td> \n <td> $(n^{[L-1]}, 1)$ </td> \n <td>$Z^{[L-1]} = W^{[L-1]} A^{[L-2]} + b^{[L-1]}$ </td> \n <td> $(n^{[L-1]}, 209)$ </td> \n <tr>\n \n \n <tr>\n <td> **Layer L** </td> \n <td> $(n^{[L]}, n^{[L-1]})$ </td> \n <td> $(n^{[L]}, 1)$ </td>\n <td> $Z^{[L]} = W^{[L]} A^{[L-1]} + b^{[L]}$</td>\n <td> $(n^{[L]}, 209)$ </td> \n <tr>\n\n</table>\n\nRemember that when we compute $W X + b$ in python, it carries out broadcasting. For example, if: \n\n$$ W = \\begin{bmatrix}\n j & k & l\\\\\n m & n & o \\\\\n p & q & r \n\\end{bmatrix}\\;\\;\\; X = \\begin{bmatrix}\n a & b & c\\\\\n d & e & f \\\\\n g & h & i \n\\end{bmatrix} \\;\\;\\; b =\\begin{bmatrix}\n s \\\\\n t \\\\\n u\n\\end{bmatrix}\\tag{2}$$\n\nThen $WX + b$ will be:\n\n$$ WX + b = \\begin{bmatrix}\n (ja + kd + lg) + s & (jb + ke + lh) + s & (jc + kf + li)+ s\\\\\n (ma + nd + og) + t & (mb + ne + oh) + t & (mc + nf + oi) + t\\\\\n (pa + qd + rg) + u & (pb + qe + rh) + u & (pc + qf + ri)+ u\n\\end{bmatrix}\\tag{3} $$",
"_____no_output_____"
],
[
"**Exercise**: Implement initialization for an L-layer Neural Network. \n\n**Instructions**:\n- The model's structure is *[LINEAR -> RELU] $ \\times$ (L-1) -> LINEAR -> SIGMOID*. I.e., it has $L-1$ layers using a ReLU activation function followed by an output layer with a sigmoid activation function.\n- Use random initialization for the weight matrices. Use `np.random.randn(shape) * 0.01`.\n- Use zeros initialization for the biases. Use `np.zeros(shape)`.\n- We will store $n^{[l]}$, the number of units in different layers, in a variable `layer_dims`. For example, the `layer_dims` for the \"Planar Data classification model\" from last week would have been [2,4,1]: There were two inputs, one hidden layer with 4 hidden units, and an output layer with 1 output unit. This means `W1`'s shape was (4,2), `b1` was (4,1), `W2` was (1,4) and `b2` was (1,1). Now you will generalize this to $L$ layers! \n- Here is the implementation for $L=1$ (one layer neural network). It should inspire you to implement the general case (L-layer neural network).\n```python\n if L == 1:\n parameters[\"W\" + str(L)] = np.random.randn(layer_dims[1], layer_dims[0]) * 0.01\n parameters[\"b\" + str(L)] = np.zeros((layer_dims[1], 1))\n```",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_parameters_deep\n\ndef initialize_parameters_deep(layer_dims):\n \"\"\"\n Arguments:\n layer_dims -- python array (list) containing the dimensions of each layer in our network\n \n Returns:\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", ..., \"WL\", \"bL\":\n Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])\n bl -- bias vector of shape (layer_dims[l], 1)\n \"\"\"\n \n np.random.seed(3)\n parameters = {}\n L = len(layer_dims) # number of layers in the network\n\n for l in range(1, L):\n ### START CODE HERE ### (≈ 2 lines of code)\n parameters['W' + str(l)] = np.random.randn(layer_dims[l],layer_dims[l-1]) * 0.01\n parameters['b' + str(l)] = np.zeros((layer_dims[l],1))\n ### END CODE HERE ###\n \n assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))\n assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))\n\n \n return parameters",
"_____no_output_____"
],
[
"parameters = initialize_parameters_deep([5,4,3])\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))",
"W1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]\n [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]\n [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]\n [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]\nb1 = [[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]]\nW2 = [[-0.01185047 -0.0020565 0.01486148 0.00236716]\n [-0.01023785 -0.00712993 0.00625245 -0.00160513]\n [-0.00768836 -0.00230031 0.00745056 0.01976111]]\nb2 = [[ 0.]\n [ 0.]\n [ 0.]]\n"
]
],
[
[
"**Expected output**:\n \n<table style=\"width:80%\">\n <tr>\n <td> **W1** </td>\n <td>[[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]\n [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]\n [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]\n [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]</td> \n </tr>\n \n <tr>\n <td>**b1** </td>\n <td>[[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]]</td> \n </tr>\n \n <tr>\n <td>**W2** </td>\n <td>[[-0.01185047 -0.0020565 0.01486148 0.00236716]\n [-0.01023785 -0.00712993 0.00625245 -0.00160513]\n [-0.00768836 -0.00230031 0.00745056 0.01976111]]</td> \n </tr>\n \n <tr>\n <td>**b2** </td>\n <td>[[ 0.]\n [ 0.]\n [ 0.]]</td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"## 4 - Forward propagation module\n\n### 4.1 - Linear Forward \nNow that you have initialized your parameters, you will do the forward propagation module. You will start by implementing some basic functions that you will use later when implementing the model. You will complete three functions in this order:\n\n- LINEAR\n- LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid. \n- [LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID (whole model)\n\nThe linear forward module (vectorized over all the examples) computes the following equations:\n\n$$Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}\\tag{4}$$\n\nwhere $A^{[0]} = X$. \n\n**Exercise**: Build the linear part of forward propagation.\n\n**Reminder**:\nThe mathematical representation of this unit is $Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}$. You may also find `np.dot()` useful. If your dimensions don't match, printing `W.shape` may help.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: linear_forward\n\ndef linear_forward(A, W, b):\n \"\"\"\n Implement the linear part of a layer's forward propagation.\n\n Arguments:\n A -- activations from previous layer (or input data): (size of previous layer, number of examples)\n W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n b -- bias vector, numpy array of shape (size of the current layer, 1)\n\n Returns:\n Z -- the input of the activation function, also called pre-activation parameter \n cache -- a python tuple containing \"A\", \"W\" and \"b\" ; stored for computing the backward pass efficiently\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n Z = (np.dot(W,A) + b)\n ### END CODE HERE ###\n \n assert(Z.shape == (W.shape[0], A.shape[1]))\n cache = (A, W, b)\n \n return Z, cache",
"_____no_output_____"
],
[
"A, W, b = linear_forward_test_case()\n\nZ, linear_cache = linear_forward(A, W, b)\nprint(\"Z = \" + str(Z))",
"Z = [[ 3.26295337 -1.23429987]]\n"
]
],
[
[
"**Expected output**:\n\n<table style=\"width:35%\">\n \n <tr>\n <td> **Z** </td>\n <td> [[ 3.26295337 -1.23429987]] </td> \n </tr>\n \n</table>",
"_____no_output_____"
],
[
"### 4.2 - Linear-Activation Forward\n\nIn this notebook, you will use two activation functions:\n\n- **Sigmoid**: $\\sigma(Z) = \\sigma(W A + b) = \\frac{1}{ 1 + e^{-(W A + b)}}$. We have provided you with the `sigmoid` function. This function returns **two** items: the activation value \"`a`\" and a \"`cache`\" that contains \"`Z`\" (it's what we will feed in to the corresponding backward function). To use it you could just call: \n``` python\nA, activation_cache = sigmoid(Z)\n```\n\n- **ReLU**: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. We have provided you with the `relu` function. This function returns **two** items: the activation value \"`A`\" and a \"`cache`\" that contains \"`Z`\" (it's what we will feed in to the corresponding backward function). To use it you could just call:\n``` python\nA, activation_cache = relu(Z)\n```",
"_____no_output_____"
],
[
"For more convenience, you are going to group two functions (Linear and Activation) into one function (LINEAR->ACTIVATION). Hence, you will implement a function that does the LINEAR forward step followed by an ACTIVATION forward step.\n\n**Exercise**: Implement the forward propagation of the *LINEAR->ACTIVATION* layer. Mathematical relation is: $A^{[l]} = g(Z^{[l]}) = g(W^{[l]}A^{[l-1]} +b^{[l]})$ where the activation \"g\" can be sigmoid() or relu(). Use linear_forward() and the correct activation function.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: linear_activation_forward\n\ndef linear_activation_forward(A_prev, W, b, activation):\n \"\"\"\n Implement the forward propagation for the LINEAR->ACTIVATION layer\n\n Arguments:\n A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)\n W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n b -- bias vector, numpy array of shape (size of the current layer, 1)\n activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n\n Returns:\n A -- the output of the activation function, also called the post-activation value \n cache -- a python tuple containing \"linear_cache\" and \"activation_cache\";\n stored for computing the backward pass efficiently\n \"\"\"\n \n if activation == \"sigmoid\":\n # Inputs: \"A_prev, W, b\". Outputs: \"A, activation_cache\".\n ### START CODE HERE ### (≈ 2 lines of code)\n Z, linear_cache = linear_forward(A_prev,W,b)\n A, activation_cache = sigmoid(Z)\n ### END CODE HERE ###\n \n elif activation == \"relu\":\n # Inputs: \"A_prev, W, b\". Outputs: \"A, activation_cache\".\n ### START CODE HERE ### (≈ 2 lines of code)\n Z, linear_cache = linear_forward(A_prev,W,b)\n A, activation_cache = relu(Z)\n ### END CODE HERE ###\n \n assert (A.shape == (W.shape[0], A_prev.shape[1]))\n cache = (linear_cache, activation_cache)\n\n return A, cache",
"_____no_output_____"
],
[
"A_prev, W, b = linear_activation_forward_test_case()\n\nA, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = \"sigmoid\")\nprint(\"With sigmoid: A = \" + str(A))\n\nA, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = \"relu\")\nprint(\"With ReLU: A = \" + str(A))",
"With sigmoid: A = [[ 0.96890023 0.11013289]]\nWith ReLU: A = [[ 3.43896131 0. ]]\n"
]
],
[
[
"**Expected output**:\n \n<table style=\"width:35%\">\n <tr>\n <td> **With sigmoid: A ** </td>\n <td > [[ 0.96890023 0.11013289]]</td> \n </tr>\n <tr>\n <td> **With ReLU: A ** </td>\n <td > [[ 3.43896131 0. ]]</td> \n </tr>\n</table>\n",
"_____no_output_____"
],
[
"**Note**: In deep learning, the \"[LINEAR->ACTIVATION]\" computation is counted as a single layer in the neural network, not two layers. ",
"_____no_output_____"
],
[
"### d) L-Layer Model \n\nFor even more convenience when implementing the $L$-layer Neural Net, you will need a function that replicates the previous one (`linear_activation_forward` with RELU) $L-1$ times, then follows that with one `linear_activation_forward` with SIGMOID.\n\n<img src=\"images/model_architecture_kiank.png\" style=\"width:600px;height:300px;\">\n<caption><center> **Figure 2** : *[LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID* model</center></caption><br>\n\n**Exercise**: Implement the forward propagation of the above model.\n\n**Instruction**: In the code below, the variable `AL` will denote $A^{[L]} = \\sigma(Z^{[L]}) = \\sigma(W^{[L]} A^{[L-1]} + b^{[L]})$. (This is sometimes also called `Yhat`, i.e., this is $\\hat{Y}$.) \n\n**Tips**:\n- Use the functions you had previously written \n- Use a for loop to replicate [LINEAR->RELU] (L-1) times\n- Don't forget to keep track of the caches in the \"caches\" list. To add a new value `c` to a `list`, you can use `list.append(c)`.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: L_model_forward\n\ndef L_model_forward(X, parameters):\n \"\"\"\n Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation\n \n Arguments:\n X -- data, numpy array of shape (input size, number of examples)\n parameters -- output of initialize_parameters_deep()\n \n Returns:\n AL -- last post-activation value\n caches -- list of caches containing:\n every cache of linear_activation_forward() (there are L-1 of them, indexed from 0 to L-1)\n \"\"\"\n\n caches = []\n A = X\n L = len(parameters) // 2 # number of layers in the neural network\n \n # Implement [LINEAR -> RELU]*(L-1). Add \"cache\" to the \"caches\" list.\n for l in range(1, L):\n A_prev = A \n ### START CODE HERE ### (≈ 2 lines of code)\n A, cache = linear_activation_forward(A_prev,\n parameters['W' + str(l)],\n parameters['b' + str(l)],\n activation='relu')\n caches.append(cache)\n ### END CODE HERE ###\n \n # Implement LINEAR -> SIGMOID. Add \"cache\" to the \"caches\" list.\n ### START CODE HERE ### (≈ 2 lines of code)\n AL, cache = linear_activation_forward(A,\n parameters['W' + str(L)],\n parameters['b' + str(L)],\n activation='sigmoid')\n caches.append(cache)\n ### END CODE HERE ###\n \n assert(AL.shape == (1,X.shape[1]))\n \n return AL, caches",
"_____no_output_____"
],
[
"X, parameters = L_model_forward_test_case_2hidden()\nAL, caches = L_model_forward(X, parameters)\nprint(\"AL = \" + str(AL))\nprint(\"Length of caches list = \" + str(len(caches)))",
"AL = [[ 0.03921668 0.70498921 0.19734387 0.04728177]]\nLength of caches list = 3\n"
]
],
[
[
"<table style=\"width:50%\">\n <tr>\n <td> **AL** </td>\n <td > [[ 0.03921668 0.70498921 0.19734387 0.04728177]]</td> \n </tr>\n <tr>\n <td> **Length of caches list ** </td>\n <td > 3 </td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"Great! Now you have a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in \"caches\". Using $A^{[L]}$, you can compute the cost of your predictions.",
"_____no_output_____"
],
[
"## 5 - Cost function\n\nNow you will implement forward and backward propagation. You need to compute the cost, because you want to check if your model is actually learning.\n\n**Exercise**: Compute the cross-entropy cost $J$, using the following formula: $$-\\frac{1}{m} \\sum\\limits_{i = 1}^{m} (y^{(i)}\\log\\left(a^{[L] (i)}\\right) + (1-y^{(i)})\\log\\left(1- a^{[L](i)}\\right)) \\tag{7}$$\n",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: compute_cost\n\ndef compute_cost(AL, Y):\n \"\"\"\n Implement the cost function defined by equation (7).\n\n Arguments:\n AL -- probability vector corresponding to your label predictions, shape (1, number of examples)\n Y -- true \"label\" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)\n\n Returns:\n cost -- cross-entropy cost\n \"\"\"\n \n m = Y.shape[1]\n\n # Compute loss from aL and y.\n ### START CODE HERE ### (≈ 1 lines of code)\n cost = -(1/m) * (np.sum(np.multiply(Y,np.log(AL)) + np.multiply((1 - Y),np.log(1 - AL))))\n ### END CODE HERE ###\n \n cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).\n assert(cost.shape == ())\n \n return cost",
"_____no_output_____"
],
[
"Y, AL = compute_cost_test_case()\n\nprint(\"cost = \" + str(compute_cost(AL, Y)))",
"cost = 0.279776563579\n"
]
],
[
[
"**Expected Output**:\n\n<table>\n\n <tr>\n <td>**cost** </td>\n <td> 0.2797765635793422</td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"## 6 - Backward propagation module\n\nJust like with forward propagation, you will implement helper functions for backpropagation. Remember that back propagation is used to calculate the gradient of the loss function with respect to the parameters. \n\n**Reminder**: \n<img src=\"images/backprop_kiank.png\" style=\"width:650px;height:250px;\">\n<caption><center> **Figure 3** : Forward and Backward propagation for *LINEAR->RELU->LINEAR->SIGMOID* <br> *The purple blocks represent the forward propagation, and the red blocks represent the backward propagation.* </center></caption>\n\n<!-- \nFor those of you who are expert in calculus (you don't need to be to do this assignment), the chain rule of calculus can be used to derive the derivative of the loss $\\mathcal{L}$ with respect to $z^{[1]}$ in a 2-layer network as follows:\n\n$$\\frac{d \\mathcal{L}(a^{[2]},y)}{{dz^{[1]}}} = \\frac{d\\mathcal{L}(a^{[2]},y)}{{da^{[2]}}}\\frac{{da^{[2]}}}{{dz^{[2]}}}\\frac{{dz^{[2]}}}{{da^{[1]}}}\\frac{{da^{[1]}}}{{dz^{[1]}}} \\tag{8} $$\n\nIn order to calculate the gradient $dW^{[1]} = \\frac{\\partial L}{\\partial W^{[1]}}$, you use the previous chain rule and you do $dW^{[1]} = dz^{[1]} \\times \\frac{\\partial z^{[1]} }{\\partial W^{[1]}}$. During the backpropagation, at each step you multiply your current gradient by the gradient corresponding to the specific layer to get the gradient you wanted.\n\nEquivalently, in order to calculate the gradient $db^{[1]} = \\frac{\\partial L}{\\partial b^{[1]}}$, you use the previous chain rule and you do $db^{[1]} = dz^{[1]} \\times \\frac{\\partial z^{[1]} }{\\partial b^{[1]}}$.\n\nThis is why we talk about **backpropagation**.\n!-->\n\nNow, similar to forward propagation, you are going to build the backward propagation in three steps:\n- LINEAR backward\n- LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the ReLU or sigmoid activation\n- [LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID backward (whole model)",
"_____no_output_____"
],
[
"### 6.1 - Linear backward\n\nFor layer $l$, the linear part is: $Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}$ (followed by an activation).\n\nSuppose you have already calculated the derivative $dZ^{[l]} = \\frac{\\partial \\mathcal{L} }{\\partial Z^{[l]}}$. You want to get $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$.\n\n<img src=\"images/linearback_kiank.png\" style=\"width:250px;height:300px;\">\n<caption><center> **Figure 4** </center></caption>\n\nThe three outputs $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$ are computed using the input $dZ^{[l]}$.Here are the formulas you need:\n$$ dW^{[l]} = \\frac{\\partial \\mathcal{J} }{\\partial W^{[l]}} = \\frac{1}{m} dZ^{[l]} A^{[l-1] T} \\tag{8}$$\n$$ db^{[l]} = \\frac{\\partial \\mathcal{J} }{\\partial b^{[l]}} = \\frac{1}{m} \\sum_{i = 1}^{m} dZ^{[l](i)}\\tag{9}$$\n$$ dA^{[l-1]} = \\frac{\\partial \\mathcal{L} }{\\partial A^{[l-1]}} = W^{[l] T} dZ^{[l]} \\tag{10}$$\n",
"_____no_output_____"
],
[
"**Exercise**: Use the 3 formulas above to implement linear_backward().",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: linear_backward\n\ndef linear_backward(dZ, cache):\n \"\"\"\n Implement the linear portion of backward propagation for a single layer (layer l)\n\n Arguments:\n dZ -- Gradient of the cost with respect to the linear output (of current layer l)\n cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer\n\n Returns:\n dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n db -- Gradient of the cost with respect to b (current layer l), same shape as b\n \"\"\"\n A_prev, W, b = cache\n m = A_prev.shape[1]\n\n ### START CODE HERE ### (≈ 3 lines of code)\n dW = 1/m * (np.dot(dZ,A_prev.T))\n db = 1/m * (np.sum(dZ,axis = 1,keepdims = True))\n dA_prev = np.dot(W.T,dZ)\n ### END CODE HERE ###\n \n assert (dA_prev.shape == A_prev.shape)\n assert (dW.shape == W.shape)\n assert (db.shape == b.shape)\n \n return dA_prev, dW, db",
"_____no_output_____"
],
[
"# Set up some test inputs\ndZ, linear_cache = linear_backward_test_case()\n\ndA_prev, dW, db = linear_backward(dZ, linear_cache)\nprint (\"dA_prev = \"+ str(dA_prev))\nprint (\"dW = \" + str(dW))\nprint (\"db = \" + str(db))",
"dA_prev = [[-1.15171336 0.06718465 -0.3204696 2.09812712]\n [ 0.60345879 -3.72508701 5.81700741 -3.84326836]\n [-0.4319552 -1.30987417 1.72354705 0.05070578]\n [-0.38981415 0.60811244 -1.25938424 1.47191593]\n [-2.52214926 2.67882552 -0.67947465 1.48119548]]\ndW = [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716]\n [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808]\n [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]]\ndb = [[-0.14713786]\n [-0.11313155]\n [-0.13209101]]\n"
]
],
[
[
"** Expected Output**:\n \n```\ndA_prev = \n [[-1.15171336 0.06718465 -0.3204696 2.09812712]\n [ 0.60345879 -3.72508701 5.81700741 -3.84326836]\n [-0.4319552 -1.30987417 1.72354705 0.05070578]\n [-0.38981415 0.60811244 -1.25938424 1.47191593]\n [-2.52214926 2.67882552 -0.67947465 1.48119548]]\ndW = \n [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716]\n [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808]\n [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]]\ndb = \n [[-0.14713786]\n [-0.11313155]\n [-0.13209101]]\n```",
"_____no_output_____"
],
[
"### 6.2 - Linear-Activation backward\n\nNext, you will create a function that merges the two helper functions: **`linear_backward`** and the backward step for the activation **`linear_activation_backward`**. \n\nTo help you implement `linear_activation_backward`, we provided two backward functions:\n- **`sigmoid_backward`**: Implements the backward propagation for SIGMOID unit. You can call it as follows:\n\n```python\ndZ = sigmoid_backward(dA, activation_cache)\n```\n\n- **`relu_backward`**: Implements the backward propagation for RELU unit. You can call it as follows:\n\n```python\ndZ = relu_backward(dA, activation_cache)\n```\n\nIf $g(.)$ is the activation function, \n`sigmoid_backward` and `relu_backward` compute $$dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}) \\tag{11}$$. \n\n**Exercise**: Implement the backpropagation for the *LINEAR->ACTIVATION* layer.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: linear_activation_backward\n\ndef linear_activation_backward(dA, cache, activation):\n \"\"\"\n Implement the backward propagation for the LINEAR->ACTIVATION layer.\n \n Arguments:\n dA -- post-activation gradient for current layer l \n cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently\n activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n \n Returns:\n dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n db -- Gradient of the cost with respect to b (current layer l), same shape as b\n \"\"\"\n linear_cache, activation_cache = cache\n \n if activation == \"relu\":\n ### START CODE HERE ### (≈ 2 lines of code)\n dZ = relu_backward(dA,activation_cache)\n dA_prev, dW, db = linear_backward(dZ,linear_cache)\n ### END CODE HERE ###\n \n elif activation == \"sigmoid\":\n ### START CODE HERE ### (≈ 2 lines of code)\n dZ = sigmoid_backward(dA,activation_cache)\n dA_prev, dW, db = linear_backward(dZ,linear_cache)\n ### END CODE HERE ###\n \n return dA_prev, dW, db",
"_____no_output_____"
],
[
"dAL, linear_activation_cache = linear_activation_backward_test_case()\n\ndA_prev, dW, db = linear_activation_backward(dAL, linear_activation_cache, activation = \"sigmoid\")\nprint (\"sigmoid:\")\nprint (\"dA_prev = \"+ str(dA_prev))\nprint (\"dW = \" + str(dW))\nprint (\"db = \" + str(db) + \"\\n\")\n\ndA_prev, dW, db = linear_activation_backward(dAL, linear_activation_cache, activation = \"relu\")\nprint (\"relu:\")\nprint (\"dA_prev = \"+ str(dA_prev))\nprint (\"dW = \" + str(dW))\nprint (\"db = \" + str(db))",
"sigmoid:\ndA_prev = [[ 0.11017994 0.01105339]\n [ 0.09466817 0.00949723]\n [-0.05743092 -0.00576154]]\ndW = [[ 0.10266786 0.09778551 -0.01968084]]\ndb = [[-0.05729622]]\n\nrelu:\ndA_prev = [[ 0.44090989 -0. ]\n [ 0.37883606 -0. ]\n [-0.2298228 0. ]]\ndW = [[ 0.44513824 0.37371418 -0.10478989]]\ndb = [[-0.20837892]]\n"
]
],
[
[
"**Expected output with sigmoid:**\n\n<table style=\"width:100%\">\n <tr>\n <td > dA_prev </td> \n <td >[[ 0.11017994 0.01105339]\n [ 0.09466817 0.00949723]\n [-0.05743092 -0.00576154]] </td> \n\n </tr> \n \n <tr>\n <td > dW </td> \n <td > [[ 0.10266786 0.09778551 -0.01968084]] </td> \n </tr> \n \n <tr>\n <td > db </td> \n <td > [[-0.05729622]] </td> \n </tr> \n</table>\n\n",
"_____no_output_____"
],
[
"**Expected output with relu:**\n\n<table style=\"width:100%\">\n <tr>\n <td > dA_prev </td> \n <td > [[ 0.44090989 0. ]\n [ 0.37883606 0. ]\n [-0.2298228 0. ]] </td> \n\n </tr> \n \n <tr>\n <td > dW </td> \n <td > [[ 0.44513824 0.37371418 -0.10478989]] </td> \n </tr> \n \n <tr>\n <td > db </td> \n <td > [[-0.20837892]] </td> \n </tr> \n</table>\n\n",
"_____no_output_____"
],
[
"### 6.3 - L-Model Backward \n\nNow you will implement the backward function for the whole network. Recall that when you implemented the `L_model_forward` function, at each iteration, you stored a cache which contains (X,W,b, and z). In the back propagation module, you will use those variables to compute the gradients. Therefore, in the `L_model_backward` function, you will iterate through all the hidden layers backward, starting from layer $L$. On each step, you will use the cached values for layer $l$ to backpropagate through layer $l$. Figure 5 below shows the backward pass. \n\n\n<img src=\"images/mn_backward.png\" style=\"width:450px;height:300px;\">\n<caption><center> **Figure 5** : Backward pass </center></caption>\n\n** Initializing backpropagation**:\nTo backpropagate through this network, we know that the output is, \n$A^{[L]} = \\sigma(Z^{[L]})$. Your code thus needs to compute `dAL` $= \\frac{\\partial \\mathcal{L}}{\\partial A^{[L]}}$.\nTo do so, use this formula (derived using calculus which you don't need in-depth knowledge of):\n```python\ndAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # derivative of cost with respect to AL\n```\n\nYou can then use this post-activation gradient `dAL` to keep going backward. As seen in Figure 5, you can now feed in `dAL` into the LINEAR->SIGMOID backward function you implemented (which will use the cached values stored by the L_model_forward function). After that, you will have to use a `for` loop to iterate through all the other layers using the LINEAR->RELU backward function. You should store each dA, dW, and db in the grads dictionary. To do so, use this formula : \n\n$$grads[\"dW\" + str(l)] = dW^{[l]}\\tag{15} $$\n\nFor example, for $l=3$ this would store $dW^{[l]}$ in `grads[\"dW3\"]`.\n\n**Exercise**: Implement backpropagation for the *[LINEAR->RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID* model.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: L_model_backward\n\ndef L_model_backward(AL, Y, caches):\n \"\"\"\n Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group\n \n Arguments:\n AL -- probability vector, output of the forward propagation (L_model_forward())\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat)\n caches -- list of caches containing:\n every cache of linear_activation_forward() with \"relu\" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)\n the cache of linear_activation_forward() with \"sigmoid\" (it's caches[L-1])\n \n Returns:\n grads -- A dictionary with the gradients\n grads[\"dA\" + str(l)] = ... \n grads[\"dW\" + str(l)] = ...\n grads[\"db\" + str(l)] = ... \n \"\"\"\n grads = {}\n L = len(caches) # the number of layers\n m = AL.shape[1]\n Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL\n \n # Initializing the backpropagation\n ### START CODE HERE ### (1 line of code)\n dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))\n ### END CODE HERE ###\n \n # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: \"dAL, current_cache\". Outputs: \"grads[\"dAL-1\"], grads[\"dWL\"], grads[\"dbL\"]\n ### START CODE HERE ### (approx. 2 lines)\n current_cache = caches[L-1]\n grads[\"dA\" + str(L-1)], grads[\"dW\" + str(L)], grads[\"db\" + str(L)] = linear_activation_backward(dAL,current_cache,activation=\"sigmoid\")\n ### END CODE HERE ###\n \n # Loop from l=L-2 to l=0\n for l in reversed(range(L-1)):\n # lth layer: (RELU -> LINEAR) gradients.\n # Inputs: \"grads[\"dA\" + str(l + 1)], current_cache\". Outputs: \"grads[\"dA\" + str(l)] , grads[\"dW\" + str(l + 1)] , grads[\"db\" + str(l + 1)] \n ### START CODE HERE ### (approx. 5 lines)\n current_cache = caches[l]\n dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads[\"dA\" + str(l+1)],current_cache,activation='relu')\n grads[\"dA\" + str(l)] = dA_prev_temp\n grads[\"dW\" + str(l + 1)] = dW_temp\n grads[\"db\" + str(l + 1)] = db_temp\n ### END CODE HERE ###\n\n return grads",
"_____no_output_____"
],
[
"AL, Y_assess, caches = L_model_backward_test_case()\ngrads = L_model_backward(AL, Y_assess, caches)\nprint_grads(grads)",
"dW1 = [[ 0.41010002 0.07807203 0.13798444 0.10502167]\n [ 0. 0. 0. 0. ]\n [ 0.05283652 0.01005865 0.01777766 0.0135308 ]]\ndb1 = [[-0.22007063]\n [ 0. ]\n [-0.02835349]]\ndA1 = [[ 0.12913162 -0.44014127]\n [-0.14175655 0.48317296]\n [ 0.01663708 -0.05670698]]\n"
]
],
[
[
"**Expected Output**\n\n<table style=\"width:60%\">\n \n <tr>\n <td > dW1 </td> \n <td > [[ 0.41010002 0.07807203 0.13798444 0.10502167]\n [ 0. 0. 0. 0. ]\n [ 0.05283652 0.01005865 0.01777766 0.0135308 ]] </td> \n </tr> \n \n <tr>\n <td > db1 </td> \n <td > [[-0.22007063]\n [ 0. ]\n [-0.02835349]] </td> \n </tr> \n \n <tr>\n <td > dA1 </td> \n <td > [[ 0.12913162 -0.44014127]\n [-0.14175655 0.48317296]\n [ 0.01663708 -0.05670698]] </td> \n\n </tr> \n</table>\n\n",
"_____no_output_____"
],
[
"### 6.4 - Update Parameters\n\nIn this section you will update the parameters of the model, using gradient descent: \n\n$$ W^{[l]} = W^{[l]} - \\alpha \\text{ } dW^{[l]} \\tag{16}$$\n$$ b^{[l]} = b^{[l]} - \\alpha \\text{ } db^{[l]} \\tag{17}$$\n\nwhere $\\alpha$ is the learning rate. After computing the updated parameters, store them in the parameters dictionary. ",
"_____no_output_____"
],
[
"**Exercise**: Implement `update_parameters()` to update your parameters using gradient descent.\n\n**Instructions**:\nUpdate parameters using gradient descent on every $W^{[l]}$ and $b^{[l]}$ for $l = 1, 2, ..., L$. \n",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: update_parameters\n\ndef update_parameters(parameters, grads, learning_rate):\n \"\"\"\n Update parameters using gradient descent\n \n Arguments:\n parameters -- python dictionary containing your parameters \n grads -- python dictionary containing your gradients, output of L_model_backward\n \n Returns:\n parameters -- python dictionary containing your updated parameters \n parameters[\"W\" + str(l)] = ... \n parameters[\"b\" + str(l)] = ...\n \"\"\"\n \n L = len(parameters) // 2 # number of layers in the neural network\n\n # Update rule for each parameter. Use a for loop.\n ### START CODE HERE ### (≈ 3 lines of code)\n for l in range(L):\n parameters[\"W\" + str(l+1)] -= (learning_rate * grads[\"dW\" + str(l+1)])\n parameters[\"b\" + str(l+1)] -= (learning_rate * grads[\"db\" + str(l+1)])\n ### END CODE HERE ###\n return parameters",
"_____no_output_____"
],
[
"parameters, grads = update_parameters_test_case()\nparameters = update_parameters(parameters, grads, 0.1)\n\nprint (\"W1 = \"+ str(parameters[\"W1\"]))\nprint (\"b1 = \"+ str(parameters[\"b1\"]))\nprint (\"W2 = \"+ str(parameters[\"W2\"]))\nprint (\"b2 = \"+ str(parameters[\"b2\"]))",
"W1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008]\n [-1.76569676 -0.80627147 0.51115557 -1.18258802]\n [-1.0535704 -0.86128581 0.68284052 2.20374577]]\nb1 = [[-0.04659241]\n [-1.28888275]\n [ 0.53405496]]\nW2 = [[-0.55569196 0.0354055 1.32964895]]\nb2 = [[-0.84610769]]\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:100%\"> \n <tr>\n <td > W1 </td> \n <td > [[-0.59562069 -0.09991781 -2.14584584 1.82662008]\n [-1.76569676 -0.80627147 0.51115557 -1.18258802]\n [-1.0535704 -0.86128581 0.68284052 2.20374577]] </td> \n </tr> \n \n <tr>\n <td > b1 </td> \n <td > [[-0.04659241]\n [-1.28888275]\n [ 0.53405496]] </td> \n </tr> \n <tr>\n <td > W2 </td> \n <td > [[-0.55569196 0.0354055 1.32964895]]</td> \n </tr> \n \n <tr>\n <td > b2 </td> \n <td > [[-0.84610769]] </td> \n </tr> \n</table>\n",
"_____no_output_____"
],
[
"\n## 7 - Conclusion\n\nCongrats on implementing all the functions required for building a deep neural network! \n\nWe know it was a long assignment but going forward it will only get better. The next part of the assignment is easier. \n\nIn the next assignment you will put all these together to build two models:\n- A two-layer neural network\n- An L-layer neural network\n\nYou will in fact use these models to classify cat vs non-cat images!",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
4a34f487e1b5dee0518d24c1d85da494f7d109f8
| 476,069 |
ipynb
|
Jupyter Notebook
|
AnnMaryPaul (2).ipynb
|
annmarypaul/Prediction-using-Decision-Tree-Algorithm
|
302c6ab2fffad0111e5f58f80e8e950b60744479
|
[
"Unlicense"
] | null | null | null |
AnnMaryPaul (2).ipynb
|
annmarypaul/Prediction-using-Decision-Tree-Algorithm
|
302c6ab2fffad0111e5f58f80e8e950b60744479
|
[
"Unlicense"
] | null | null | null |
AnnMaryPaul (2).ipynb
|
annmarypaul/Prediction-using-Decision-Tree-Algorithm
|
302c6ab2fffad0111e5f58f80e8e950b60744479
|
[
"Unlicense"
] | null | null | null | 432.004537 | 195,762 | 0.924744 |
[
[
[
"# Decision Tree",
"_____no_output_____"
],
[
"## ANN MARY PAUL\n\n## Task 2\n\n## Prediction using Decision Tree Algorithm",
"_____no_output_____"
],
[
"# Importing the necessary libraries",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"from google.colab import files \n \n \nuploaded = files.upload()",
"_____no_output_____"
],
[
"import io \n \ndf = pd.read_csv(io.BytesIO(uploaded['Iris.csv'])) \nprint(df)",
" Id SepalLengthCm ... PetalWidthCm Species\n0 1 5.1 ... 0.2 Iris-setosa\n1 2 4.9 ... 0.2 Iris-setosa\n2 3 4.7 ... 0.2 Iris-setosa\n3 4 4.6 ... 0.2 Iris-setosa\n4 5 5.0 ... 0.2 Iris-setosa\n.. ... ... ... ... ...\n145 146 6.7 ... 2.3 Iris-virginica\n146 147 6.3 ... 1.9 Iris-virginica\n147 148 6.5 ... 2.0 Iris-virginica\n148 149 6.2 ... 2.3 Iris-virginica\n149 150 5.9 ... 1.8 Iris-virginica\n\n[150 rows x 6 columns]\n"
],
[
"df.head(10)",
"_____no_output_____"
],
[
"df.info() #datatype checking",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 150 entries, 0 to 149\nData columns (total 6 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Id 150 non-null int64 \n 1 SepalLengthCm 150 non-null float64\n 2 SepalWidthCm 150 non-null float64\n 3 PetalLengthCm 150 non-null float64\n 4 PetalWidthCm 150 non-null float64\n 5 Species 150 non-null object \ndtypes: float64(4), int64(1), object(1)\nmemory usage: 7.2+ KB\n"
],
[
"df.shape ",
"_____no_output_____"
],
[
"df1=df.drop('Id',axis=1)",
"_____no_output_____"
],
[
"df1.describe()",
"_____no_output_____"
]
],
[
[
"## Performing Exploratory Data Analysis",
"_____no_output_____"
]
],
[
[
"sns.pairplot(df1, hue='Species',palette='gist_ncar')",
"_____no_output_____"
],
[
"sns.heatmap(df1.corr())",
"_____no_output_____"
],
[
"plt.figure(figsize=(12,10))\nplt.subplot(2,2,1)\nsns.boxplot(x=\"Species\",y=\"SepalLengthCm\",data=df1)\nplt.subplot(2,2,2)\nsns.boxplot(x=\"Species\",y=\"SepalWidthCm\",data=df1)\nplt.subplot(2,2,3)\nsns.boxplot(x=\"Species\",y=\"PetalLengthCm\",data=df1)\nplt.subplot(2,2,4)\nsns.boxplot(x=\"Species\",y=\"PetalWidthCm\",data=df1)",
"_____no_output_____"
]
],
[
[
"## Train and Test",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\n",
"_____no_output_____"
],
[
"X=df.drop(['Species','Id'],axis=1)\ny=df['Species']",
"_____no_output_____"
],
[
"X.head()",
"_____no_output_____"
],
[
"# Splitting the data - 80:20 ratio\nX_train, X_test, y_train, y_test = train_test_split(X , y, test_size = 0.2, random_state=1)",
"_____no_output_____"
]
],
[
[
"## Decision Tree Model",
"_____no_output_____"
]
],
[
[
"from sklearn.tree import DecisionTreeClassifier\ndt=DecisionTreeClassifier()\ndt.fit(X_train,y_train)\ny_pred = dt.predict(X_test)\nprint(\"Decision Tree is ready\")\n\n",
"Decision Tree is ready\n"
],
[
"from sklearn.metrics import classification_report, confusion_matrix",
"_____no_output_____"
],
[
"print(\"Classification report - \\n\", classification_report(y_test,y_pred))",
"Classification report - \n precision recall f1-score support\n\n Iris-setosa 1.00 1.00 1.00 11\nIris-versicolor 1.00 0.92 0.96 13\n Iris-virginica 0.86 1.00 0.92 6\n\n accuracy 0.97 30\n macro avg 0.95 0.97 0.96 30\n weighted avg 0.97 0.97 0.97 30\n\n"
],
[
"print(confusion_matrix(y_test,y_pred))",
"[[11 0 0]\n [ 0 12 1]\n [ 0 0 6]]\n"
],
[
"from sklearn.metrics import accuracy_score\nprint(accuracy_score(y_test,y_pred))",
"0.9666666666666667\n"
],
[
"cm = confusion_matrix(y_test, y_pred)\nplt.figure(figsize=(8,8))\n\nsns.heatmap(cm, annot=True, fmt=\".3f\", linewidths=.5, square = True, cmap = 'coolwarm');\n\nplt.ylabel('Actual label');\nplt.xlabel('Predicted label');\n\nall_sample_title = 'Accuracy Score: {0}'.format(dt.score(X_test, y_test))\nplt.title(all_sample_title, size = 15)",
"_____no_output_____"
]
],
[
[
"## Visualization of Decsion Tree",
"_____no_output_____"
]
],
[
[
"!pip install pydotplus\n!pip install graphviz ",
"Requirement already satisfied: pydotplus in /usr/local/lib/python3.6/dist-packages (2.0.2)\nRequirement already satisfied: pyparsing>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from pydotplus) (2.4.7)\nRequirement already satisfied: graphviz in /usr/local/lib/python3.6/dist-packages (0.10.1)\n"
],
[
"# Import necessary libraries for graph viz\nfrom six import StringIO \nfrom IPython.display import Image \nfrom sklearn.tree import export_graphviz\nimport pydotplus",
"_____no_output_____"
],
[
"dot_data = StringIO()\n\nexport_graphviz(dt, out_file=dot_data, feature_names=['SepalLengthCm','SepalWidthCm','PetalLengthCm','PetalWidthCm'] , \n filled=True, rounded=True,special_characters=True)\n\n",
"_____no_output_____"
],
[
"graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) \nImage(graph.create_png())",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4a3501f3c112add59ba3c03114c913a3bb686ef3
| 14,586 |
ipynb
|
Jupyter Notebook
|
intro_to_pytorch/Part 6 - Saving and Loading Models.ipynb
|
Hammania689/pytorch_udacity_challenge
|
0c4b0b87260ebf9de275a10ab1bbea5d262ecd82
|
[
"MIT"
] | null | null | null |
intro_to_pytorch/Part 6 - Saving and Loading Models.ipynb
|
Hammania689/pytorch_udacity_challenge
|
0c4b0b87260ebf9de275a10ab1bbea5d262ecd82
|
[
"MIT"
] | null | null | null |
intro_to_pytorch/Part 6 - Saving and Loading Models.ipynb
|
Hammania689/pytorch_udacity_challenge
|
0c4b0b87260ebf9de275a10ab1bbea5d262ecd82
|
[
"MIT"
] | null | null | null | 49.612245 | 4,876 | 0.720485 |
[
[
[
"# Saving and Loading Models\n\nIn this notebook, I'll show you how to save and load models with PyTorch. This is important because you'll often want to load previously trained models to use in making predictions or to continue training on new data.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\n\nimport helper\nimport fc_model",
"_____no_output_____"
],
[
"# Define a transform to normalize the data\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))])\n# Download and load the training data\ntrainset = datasets.FashionMNIST('F_MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n\n# Download and load the test data\ntestset = datasets.FashionMNIST('F_MNIST_data/', download=True, train=False, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)",
"_____no_output_____"
]
],
[
[
"Here we can see one of the images.",
"_____no_output_____"
]
],
[
[
"image, label = next(iter(trainloader))\nhelper.imshow(image[0,:]);",
"_____no_output_____"
]
],
[
[
"# Train a network\n\nTo make things more concise here, I moved the model architecture and training code from the last part to a file called `fc_model`. Importing this, we can easily create a fully-connected network with `fc_model.Network`, and train the network using `fc_model.train`. I'll use this model (once it's trained) to demonstrate how we can save and load models.",
"_____no_output_____"
]
],
[
[
"# Create the network, define the criterion and optimizer\nmodel = fc_model.Network(784, 10, [512, 256, 128])\ncriterion = nn.NLLLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)",
"_____no_output_____"
],
[
"fc_model.train(model, trainloader, testloader, criterion, optimizer, epochs=2)",
"_____no_output_____"
]
],
[
[
"## Saving and loading networks\n\nAs you can imagine, it's impractical to train a network every time you need to use it. Instead, we can save trained networks then load them later to train more or use them for predictions.\n\nThe parameters for PyTorch networks are stored in a model's `state_dict`. We can see the state dict contains the weight and bias matrices for each of our layers.",
"_____no_output_____"
]
],
[
[
"print(\"Our model: \\n\\n\", model, '\\n')\nprint(\"The state dict keys: \\n\\n\", model.state_dict().keys())",
"_____no_output_____"
]
],
[
[
"The simplest thing to do is simply save the state dict with `torch.save`. For example, we can save it to a file `'checkpoint.pth'`.",
"_____no_output_____"
]
],
[
[
"torch.save(model.state_dict(), 'checkpoint.pth')",
"_____no_output_____"
]
],
[
[
"Then we can load the state dict with `torch.load`.",
"_____no_output_____"
]
],
[
[
"state_dict = torch.load('checkpoint.pth')\nprint(state_dict.keys())",
"_____no_output_____"
]
],
[
[
"And to load the state dict in to the network, you do `model.load_state_dict(state_dict)`.",
"_____no_output_____"
]
],
[
[
"model.load_state_dict(state_dict)",
"_____no_output_____"
]
],
[
[
"Seems pretty straightforward, but as usual it's a bit more complicated. Loading the state dict works only if the model architecture is exactly the same as the checkpoint architecture. If I create a model with a different architecture, this fails.",
"_____no_output_____"
]
],
[
[
"# Try this\nmodel = fc_model.Network(784, 10, [400, 200, 100])\n# This will throw an error because the tensor sizes are wrong!\nmodel.load_state_dict(state_dict)",
"_____no_output_____"
]
],
[
[
"This means we need to rebuild the model exactly as it was when trained. Information about the model architecture needs to be saved in the checkpoint, along with the state dict. To do this, you build a dictionary with all the information you need to compeletely rebuild the model.",
"_____no_output_____"
]
],
[
[
"checkpoint = {'input_size': 784,\n 'output_size': 10,\n 'hidden_layers': [each.out_features for each in model.hidden_layers],\n 'state_dict': model.state_dict()}\n\ntorch.save(checkpoint, 'checkpoint.pth')",
"_____no_output_____"
]
],
[
[
"Now the checkpoint has all the necessary information to rebuild the trained model. You can easily make that a function if you want. Similarly, we can write a function to load checkpoints. ",
"_____no_output_____"
]
],
[
[
"def load_checkpoint(filepath):\n checkpoint = torch.load(filepath)\n model = fc_model.Network(checkpoint['input_size'],\n checkpoint['output_size'],\n checkpoint['hidden_layers'])\n \n model.load_state_dict(checkpoint['state_dict'])\n \n return model",
"_____no_output_____"
],
[
"model = load_checkpoint('checkpoint.pth')\nprint(model)",
"_____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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a35026570c0500644254a6f7b417364ec36b318
| 6,332 |
ipynb
|
Jupyter Notebook
|
Projects/Cifar10/0000000026646942_notebook_0000000018575699_notebook_Cifar10.ipynb
|
SaiPrasanth212/Coding-Ninjas-Data-Science-and-Machine-Learning
|
4de6bf926b6d523c8c4fe3bfe90a1ad29e5893b0
|
[
"MIT"
] | 2 |
2022-03-01T07:53:24.000Z
|
2022-03-01T07:53:25.000Z
|
Projects/Cifar10/0000000026646942_notebook_0000000018575699_notebook_Cifar10.ipynb
|
SaiPrasanth212/Coding-Ninjas-Data-Science-and-Machine-Learning
|
4de6bf926b6d523c8c4fe3bfe90a1ad29e5893b0
|
[
"MIT"
] | null | null | null |
Projects/Cifar10/0000000026646942_notebook_0000000018575699_notebook_Cifar10.ipynb
|
SaiPrasanth212/Coding-Ninjas-Data-Science-and-Machine-Learning
|
4de6bf926b6d523c8c4fe3bfe90a1ad29e5893b0
|
[
"MIT"
] | 1 |
2022-03-31T14:09:47.000Z
|
2022-03-31T14:09:47.000Z
| 24.638132 | 336 | 0.573437 |
[
[
[
"import cifar10\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nimport tarfile",
"_____no_output_____"
],
[
"cifar10.data_path=r\"C:\\Users\\m\\Project-Cifar10\"",
"_____no_output_____"
],
[
"cifar10.maybe_download_and_extract()",
"_____no_output_____"
],
[
"class_names=cifar10.load_class_names()\nclass_names",
"_____no_output_____"
],
[
"images_train, cls_train, labels_train = cifar10.load_training_data()\nimages_test, cls_test, labels_test = cifar10.load_test_data()",
"_____no_output_____"
],
[
"print(images_train.shape)\nprint(cls_train.shape)\nprint(labels_train.shape)",
"_____no_output_____"
],
[
"images_train_reshaped = images_train.reshape((50000,32*32*3))\nimages_train_reshaped.shape",
"_____no_output_____"
],
[
"fig=plt.figure(figsize=(8,8))\nfor i in range(100):\n ax=fig.add_subplot(10,10,i+1)\n ax.imshow(images_train[i])\nplt.show()",
"_____no_output_____"
],
[
"pca=PCA()\npca.fit(images_train_reshaped)",
"_____no_output_____"
],
[
"k=0\ntotal=sum(pca.explained_variance_)\ncurrentsum=0\nwhile currentsum/total < 0.99:\n currentsum+=pca.explained_variance_[k]\n k=k+1\nk",
"_____no_output_____"
],
[
"pca=PCA(n_components=k)\nimages_train_reshaped=pca.fit_transform(images_train_reshaped)\nimages_train_reshaped.shape",
"_____no_output_____"
],
[
"images_approx=pca.inverse_transform(images_train_reshaped)\nimages_approx=images_approx.reshape((50000,32,32,3))\nimages_approx.shape",
"_____no_output_____"
],
[
"fig=plt.figure(figsize=(8,8))\nfor i in range(100):\n ax=fig.add_subplot(10,10,i+1)\n ax.imshow(images_approx[i])\nplt.show()",
"_____no_output_____"
],
[
"images_test_reshaped=images.test_reshape((10000*32*32*3))\nimages_test_reshaped.shape",
"_____no_output_____"
],
[
"images_test_transformed = pca.transform(images_test_reshaped)\nimages_test_transformed.shape",
"_____no_output_____"
],
[
"rf_clf=RandomForestClassifier()\nrf_clf.fit(images_train_transfored,cls_train)\ncls_pred=tf_clf.predict(images_test_transformed)\nprint(classification_report(cls_test,cls_pred))",
"_____no_output_____"
],
[
"clf=SVC()\ngrid={'C':[1e2,1e4,1e1,5e3,1e3,5e2],\n 'gamma':[1e-3,1e-2,5e-3,5e-2,1e-4,1e-5]}\n\nsvm=GridSearchcv(clf,grid,n_jobs=-1)\nsvm.fit(images_train_transformed)\nprint(svm.score(cls_test,y_pred))",
"_____no_output_____"
],
[
"predictions=[]\nfor i in range(len(cls_pred)):\n predictions.append(class_names[cls_pred[i]])\npredictions",
"_____no_output_____"
],
[
"np.savetxt(\"predictions.csv\", predictions, delimiter=',', fmt=\"%s\")",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a35044377aa82d2e246a8138b20ffd3144d35b6
| 34,698 |
ipynb
|
Jupyter Notebook
|
site/en-snapshot/agents/tutorials/7_SAC_minitaur_tutorial.ipynb
|
leeyspaul/docs-l10n
|
0e2f1a4d1c507b8a71be6b506b275ab2c83ca359
|
[
"Apache-2.0"
] | null | null | null |
site/en-snapshot/agents/tutorials/7_SAC_minitaur_tutorial.ipynb
|
leeyspaul/docs-l10n
|
0e2f1a4d1c507b8a71be6b506b275ab2c83ca359
|
[
"Apache-2.0"
] | null | null | null |
site/en-snapshot/agents/tutorials/7_SAC_minitaur_tutorial.ipynb
|
leeyspaul/docs-l10n
|
0e2f1a4d1c507b8a71be6b506b275ab2c83ca359
|
[
"Apache-2.0"
] | null | null | null | 34.698 | 504 | 0.553894 |
[
[
[
"**Copyright 2020 The TF-Agents Authors.**",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# SAC minitaur with the Actor-Learner API\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/agents/tutorials/7_SAC_minitaur_tutorial\">\n <img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />\n View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/agents/blob/master/docs/tutorials/7_SAC_minitaur_tutorial.ipynb\">\n <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/agents/blob/master/docs/tutorials/7_SAC_minitaur_tutorial.ipynb\">\n <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/agents/docs/tutorials/7_SAC_minitaur_tutorial.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>\n",
"_____no_output_____"
],
[
"## Introduction",
"_____no_output_____"
],
[
"This example shows how to train a [Soft Actor Critic](https://arxiv.org/abs/1812.05905) agent on the [Minitaur](https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/bullet/minitaur.py) environment.\n\nIf you've worked through the [DQN Colab](https://github.com/tensorflow/agents/blob/master/docs/tutorials/1_dqn_tutorial.ipynb) this should feel very familiar. Notable changes include:\n\n * Changing the agent from DQN to SAC.\n * Training on Minitaur which is a much more complex environment than CartPole. The Minitaur environment aims to train a quadruped robot to move forward.\n * Using the TF-Agents Actor-Learner API for distributed Reinforcement Learning.\n\nThe API supports both distributed data collection using an experience replay buffer and variable container (parameter server) and distributed training across multiple devices. The API is designed to be very simple and modular. We utilize [Reverb](https://deepmind.com/research/open-source/Reverb) for both replay buffer and variable container and [TF DistributionStrategy API](https://www.tensorflow.org/guide/distributed_training) for distributed training on GPUs and TPUs.",
"_____no_output_____"
],
[
"If you haven't installed the following dependencies, run:",
"_____no_output_____"
]
],
[
[
"!sudo apt-get install -y xvfb ffmpeg\n!pip install gym\n!pip install 'imageio==2.4.0'\n!pip install matplotlib\n!pip install PILLOW\n!pip install tf-agents[reverb]\n!pip install pybullet",
"_____no_output_____"
]
],
[
[
"## Setup",
"_____no_output_____"
],
[
"First we will import the different tools that we need.",
"_____no_output_____"
]
],
[
[
"import base64\nimport imageio\nimport IPython\nimport matplotlib.pyplot as plt\nimport os\nimport reverb\nimport tempfile\nimport PIL.Image\n\nimport tensorflow as tf\n\nfrom tf_agents.agents.ddpg import critic_network\nfrom tf_agents.agents.sac import sac_agent\nfrom tf_agents.agents.sac import tanh_normal_projection_network\nfrom tf_agents.environments import suite_pybullet\nfrom tf_agents.experimental.train import actor\nfrom tf_agents.experimental.train import learner\nfrom tf_agents.experimental.train import triggers\nfrom tf_agents.experimental.train.utils import spec_utils\nfrom tf_agents.experimental.train.utils import strategy_utils\nfrom tf_agents.experimental.train.utils import train_utils\nfrom tf_agents.metrics import py_metrics\nfrom tf_agents.networks import actor_distribution_network\nfrom tf_agents.policies import greedy_policy\nfrom tf_agents.policies import py_tf_eager_policy\nfrom tf_agents.policies import random_py_policy\nfrom tf_agents.replay_buffers import reverb_replay_buffer\nfrom tf_agents.replay_buffers import reverb_utils\n\ntempdir = tempfile.gettempdir()",
"_____no_output_____"
]
],
[
[
"## Hyperparameters",
"_____no_output_____"
]
],
[
[
"env_name = \"MinitaurBulletEnv-v0\" # @param {type:\"string\"}\n\n# Use \"num_iterations = 1e6\" for better results (2 hrs)\n# 1e5 is just so this doesn't take too long (1 hr)\nnum_iterations = 100000 # @param {type:\"integer\"}\n\ninitial_collect_steps = 10000 # @param {type:\"integer\"}\ncollect_steps_per_iteration = 1 # @param {type:\"integer\"}\nreplay_buffer_capacity = 10000 # @param {type:\"integer\"}\n\nbatch_size = 256 # @param {type:\"integer\"}\n\ncritic_learning_rate = 3e-4 # @param {type:\"number\"}\nactor_learning_rate = 3e-4 # @param {type:\"number\"}\nalpha_learning_rate = 3e-4 # @param {type:\"number\"}\ntarget_update_tau = 0.005 # @param {type:\"number\"}\ntarget_update_period = 1 # @param {type:\"number\"}\ngamma = 0.99 # @param {type:\"number\"}\nreward_scale_factor = 1.0 # @param {type:\"number\"}\n\nactor_fc_layer_params = (256, 256)\ncritic_joint_fc_layer_params = (256, 256)\n\nlog_interval = 5000 # @param {type:\"integer\"}\n\nnum_eval_episodes = 20 # @param {type:\"integer\"}\neval_interval = 10000 # @param {type:\"integer\"}\n\npolicy_save_interval = 5000 # @param {type:\"integer\"}",
"_____no_output_____"
]
],
[
[
"## Environment\n\nEnvironments in RL represent the task or problem that we are trying to solve. Standard environments can be easily created in TF-Agents using `suites`. We have different `suites` for loading environments from sources such as the OpenAI Gym, Atari, DM Control, etc., given a string environment name.\n\nNow let's load the Minituar environment from the Pybullet suite.",
"_____no_output_____"
]
],
[
[
"env = suite_pybullet.load(env_name)\nenv.reset()\nPIL.Image.fromarray(env.render())",
"_____no_output_____"
]
],
[
[
"In this environment the goal is for the agent to train a policy that will control the Minitaur robot and have it move forward as fast as possible. Episodes last 1000 steps and the return will be the sum of rewards throughout the episode.\n\nLet's look at the information the environment provides as an `observation` which the policy will use to generate `actions`.",
"_____no_output_____"
]
],
[
[
"print('Observation Spec:')\nprint(env.time_step_spec().observation)\nprint('Action Spec:')\nprint(env.action_spec())",
"_____no_output_____"
]
],
[
[
"As we can see the observation is fairly complex. We recieve 28 values representing the angles, velocities and torques for all the motors. In return the environment expects 8 values for the actions between `[-1, 1]`. These are the desired motor angles.\n\nUsually we create two environments: one for collecting data during training and one for evaluation. The environments are written in pure python and use numpy arrays, which the Actor Learner API directly consumes.",
"_____no_output_____"
]
],
[
[
"collect_env = suite_pybullet.load(env_name)\neval_env = suite_pybullet.load(env_name)",
"_____no_output_____"
]
],
[
[
"## Distribution Strategy\nWe use the DistributionStrategy API to enable running the train step computation across multiple devices such as multiple GPUs or TPUs using data parallelism. The train step:\n* Receives a batch of training data\n* Splits it across the devices\n* Computes the forward step\n* Aggregates and computes the MEAN of the loss\n* Computes the backward step and performs a gradient variable update\n\nWith TF-Agents Learner API and DistributionStrategy API it is quite easy to switch between running the train step on GPUs (using MirroredStrategy) to TPUs (using TPUStrategy) without changing any of the training logic below.",
"_____no_output_____"
],
[
"### Enabling the GPU\nIf you want to try running on a GPU, you'll first need to enable GPUs for the notebook:\n\n* Navigate to Edit→Notebook Settings\n* Select GPU from the Hardware Accelerator drop-down",
"_____no_output_____"
],
[
"### Picking a strategy\nUse `strategy_utils` to generate a strategy. Under the hood, passing the parameter:\n* `use_gpu = False` returns `tf.distribute.get_strategy()`, which uses CPU\n* `use_gpu = True` returns `tf.distribute.MirroredStrategy()`, which uses all GPUs that are visible to TensorFlow on one machine",
"_____no_output_____"
]
],
[
[
"use_gpu = True #@param {type:\"boolean\"}\n\nstrategy = strategy_utils.get_strategy(tpu=False, use_gpu=use_gpu)",
"_____no_output_____"
]
],
[
[
"All variables and Agents need to be created under `strategy.scope()`, as you'll see below.",
"_____no_output_____"
],
[
"## Agent\n\nTo create an SAC Agent, we first need to create the networks that it will train. SAC is an actor-critic agent, so we will need two networks.\n\nThe critic will give us value estimates for `Q(s,a)`. That is, it will recieve as input an observation and an action, and it will give us an estimate of how good that action was for the given state.\n",
"_____no_output_____"
]
],
[
[
"observation_spec, action_spec, time_step_spec = (\n spec_utils.get_tensor_specs(collect_env))\n\nwith strategy.scope():\n critic_net = critic_network.CriticNetwork(\n (observation_spec, action_spec),\n observation_fc_layer_params=None,\n action_fc_layer_params=None,\n joint_fc_layer_params=critic_joint_fc_layer_params,\n kernel_initializer='glorot_uniform',\n last_kernel_initializer='glorot_uniform')",
"_____no_output_____"
]
],
[
[
"We will use this critic to train an `actor` network which will allow us to generate actions given an observation.\n\nThe `ActorNetwork` will predict parameters for a tanh-squashed [MultivariateNormalDiag](https://www.tensorflow.org/probability/api_docs/python/tfp/distributions/MultivariateNormalDiag) distribution. This distribution will then be sampled, conditioned on the current observation, whenever we need to generate actions.",
"_____no_output_____"
]
],
[
[
"with strategy.scope():\n actor_net = actor_distribution_network.ActorDistributionNetwork(\n observation_spec,\n action_spec,\n fc_layer_params=actor_fc_layer_params,\n continuous_projection_net=(\n tanh_normal_projection_network.TanhNormalProjectionNetwork))",
"_____no_output_____"
]
],
[
[
"With these networks at hand we can now instantiate the agent.\n",
"_____no_output_____"
]
],
[
[
"with strategy.scope():\n train_step = train_utils.create_train_step()\n\n tf_agent = sac_agent.SacAgent(\n time_step_spec,\n action_spec,\n actor_network=actor_net,\n critic_network=critic_net,\n actor_optimizer=tf.compat.v1.train.AdamOptimizer(\n learning_rate=actor_learning_rate),\n critic_optimizer=tf.compat.v1.train.AdamOptimizer(\n learning_rate=critic_learning_rate),\n alpha_optimizer=tf.compat.v1.train.AdamOptimizer(\n learning_rate=alpha_learning_rate),\n target_update_tau=target_update_tau,\n target_update_period=target_update_period,\n td_errors_loss_fn=tf.math.squared_difference,\n gamma=gamma,\n reward_scale_factor=reward_scale_factor,\n train_step_counter=train_step)\n\n tf_agent.initialize()",
"_____no_output_____"
]
],
[
[
"## Replay Buffer\n\nIn order to keep track of the data collected from the environment, we will use [Reverb](https://deepmind.com/research/open-source/Reverb), an efficient, extensible, and easy-to-use replay system by Deepmind. It stores experience data collected by the Actors and consumed by the Learner during training.\n\nIn this tutorial, this is less important than `max_size` -- but in a distributed setting with async collection and training, you will probably want to experiment with `rate_limiters.SampleToInsertRatio`, using a samples_per_insert somewhere between 2 and 1000. For example:\n```\nrate_limiter=reverb.rate_limiters.SampleToInsertRatio(samples_per_insert=3.0, min_size_to_sample=3, error_buffer=3.0))\n```\n",
"_____no_output_____"
]
],
[
[
"table_name = 'uniform_table'\ntable = reverb.Table(\n table_name,\n max_size=replay_buffer_capacity,\n sampler=reverb.selectors.Uniform(),\n remover=reverb.selectors.Fifo(),\n rate_limiter=reverb.rate_limiters.MinSize(1))\n\nreverb_server = reverb.Server([table])",
"_____no_output_____"
]
],
[
[
"The replay buffer is constructed using specs describing the tensors that are to be stored, which can be obtained from the agent using `tf_agent.collect_data_spec`.\n\nSince the SAC Agent needs both the current and next observation to compute the loss, we set `sequence_length=2`.",
"_____no_output_____"
]
],
[
[
"reverb_replay = reverb_replay_buffer.ReverbReplayBuffer(\n tf_agent.collect_data_spec,\n sequence_length=2,\n table_name=table_name,\n local_server=reverb_server)",
"_____no_output_____"
]
],
[
[
"Now we generate a TensorFlow dataset from the Reverb replay buffer. We will pass this to the Learner to sample experiences for training.",
"_____no_output_____"
]
],
[
[
"dataset = reverb_replay.as_dataset(\n sample_batch_size=batch_size, num_steps=2).prefetch(50)\nexperience_dataset_fn = lambda: dataset",
"_____no_output_____"
]
],
[
[
"## Policies\n\nIn TF-Agents, policies represent the standard notion of policies in RL: given a `time_step` produce an action or a distribution over actions. The main method is `policy_step = policy.step(time_step)` where `policy_step` is a named tuple `PolicyStep(action, state, info)`. The `policy_step.action` is the `action` to be applied to the environment, `state` represents the state for stateful (RNN) policies and `info` may contain auxiliary information such as log probabilities of the actions.\n\nAgents contain two policies:\n\n- `agent.policy` — The main policy that is used for evaluation and deployment.\n- `agent.collect_policy` — A second policy that is used for data collection.",
"_____no_output_____"
]
],
[
[
"tf_eval_policy = tf_agent.policy\neval_policy = py_tf_eager_policy.PyTFEagerPolicy(\n tf_eval_policy, use_tf_function=True)",
"_____no_output_____"
],
[
"tf_collect_policy = tf_agent.collect_policy\ncollect_policy = py_tf_eager_policy.PyTFEagerPolicy(\n tf_collect_policy, use_tf_function=True)",
"_____no_output_____"
]
],
[
[
"Policies can be created independently of agents. For example, use `tf_agents.policies.random_py_policy` to create a policy which will randomly select an action for each time_step.",
"_____no_output_____"
]
],
[
[
"random_policy = random_py_policy.RandomPyPolicy(\n collect_env.time_step_spec(), collect_env.action_spec())",
"_____no_output_____"
]
],
[
[
"## Actors\nThe actor manages interactions between a policy and an environment.\n * The Actor components contain an instance of the environment (as `py_environment`) and a copy of the policy variables.\n * Each Actor worker runs a sequence of data collection steps given the local values of the policy variables.\n * Variable updates are done explicitly using the variable container client instance in the training script before calling `actor.run()`.\n * The observed experience is written into the replay buffer in each data collection step.",
"_____no_output_____"
],
[
"As the Actors run data collection steps, they pass trajectories of (state, action, reward) to the observer, which caches and writes them to the Reverb replay system. \n\nWe're storing trajectories for frames [(t0,t1) (t1,t2) (t2,t3), ...] because `stride_length=1`.",
"_____no_output_____"
]
],
[
[
"rb_observer = reverb_utils.ReverbAddTrajectoryObserver(\n reverb_replay.py_client,\n table_name,\n sequence_length=2,\n stride_length=1)",
"_____no_output_____"
]
],
[
[
"We create an Actor with the random policy and collect experiences to seed the replay buffer with.",
"_____no_output_____"
]
],
[
[
"initial_collect_actor = actor.Actor(\n collect_env,\n random_policy,\n train_step,\n steps_per_run=initial_collect_steps,\n observers=[rb_observer])\ninitial_collect_actor.run()",
"_____no_output_____"
]
],
[
[
"Instantiate an Actor with the collect policy to gather more experiences during training.",
"_____no_output_____"
]
],
[
[
"env_step_metric = py_metrics.EnvironmentSteps()\ncollect_actor = actor.Actor(\n collect_env,\n collect_policy,\n train_step,\n steps_per_run=1,\n metrics=actor.collect_metrics(10),\n summary_dir=os.path.join(tempdir, learner.TRAIN_DIR),\n observers=[rb_observer, env_step_metric])",
"_____no_output_____"
]
],
[
[
"Create an Actor which will be used to evaluate the policy during training. We pass in `actor.eval_metrics(num_eval_episodes)` to log metrics later.",
"_____no_output_____"
]
],
[
[
"eval_actor = actor.Actor(\n eval_env,\n eval_policy,\n train_step,\n episodes_per_run=num_eval_episodes,\n metrics=actor.eval_metrics(num_eval_episodes),\n summary_dir=os.path.join(tempdir, 'eval'),\n)",
"_____no_output_____"
]
],
[
[
"## Learners\nThe Learner component contains the agent and performs gradient step updates to the policy variables using experience data from the replay buffer. After one or more training steps, the Learner can push a new set of variable values to the variable container.",
"_____no_output_____"
]
],
[
[
"saved_model_dir = os.path.join(tempdir, learner.POLICY_SAVED_MODEL_DIR)\n\n# Triggers to save the agent's policy checkpoints.\nlearning_triggers = [\n triggers.PolicySavedModelTrigger(\n saved_model_dir,\n tf_agent,\n train_step,\n interval=policy_save_interval),\n triggers.StepPerSecondLogTrigger(train_step, interval=1000),\n]\n\nagent_learner = learner.Learner(\n tempdir,\n train_step,\n tf_agent,\n experience_dataset_fn,\n triggers=learning_triggers)",
"_____no_output_____"
]
],
[
[
"## Metrics and Evaluation\n\nWe instantiated the eval Actor with `actor.eval_metrics` above, which creates most commonly used metrics during policy evaluation:\n* Average return. The return is the sum of rewards obtained while running a policy in an environment for an episode, and we usually average this over a few episodes.\n* Average episode length.\n\nWe run the Actor to generate these metrics.",
"_____no_output_____"
]
],
[
[
"def get_eval_metrics():\n eval_actor.run()\n results = {}\n for metric in eval_actor.metrics:\n results[metric.name] = metric.result()\n return results\n\nmetrics = get_eval_metrics()",
"_____no_output_____"
],
[
"def log_eval_metrics(step, metrics):\n eval_results = (', ').join(\n '{} = {:.6f}'.format(name, result) for name, result in metrics.items())\n print('step = {0}: {1}'.format(step, eval_results))\n\nlog_eval_metrics(0, metrics)",
"_____no_output_____"
]
],
[
[
"Check out the [metrics module](https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/tf_metrics.py) for other standard implementations of different metrics.",
"_____no_output_____"
],
[
"## Training the agent\n\nThe training loop involves both collecting data from the environment and optimizing the agent's networks. Along the way, we will occasionally evaluate the agent's policy to see how we are doing.",
"_____no_output_____"
]
],
[
[
"#@test {\"skip\": true}\ntry:\n %%time\nexcept:\n pass\n\n# Reset the train step\ntf_agent.train_step_counter.assign(0)\n\n# Evaluate the agent's policy once before training.\navg_return = get_eval_metrics()[\"AverageReturn\"]\nreturns = [avg_return]\n\nfor _ in range(num_iterations):\n # Training.\n collect_actor.run()\n loss_info = agent_learner.run(iterations=1)\n\n # Evaluating.\n step = agent_learner.train_step_numpy\n\n if eval_interval and step % eval_interval == 0:\n metrics = get_eval_metrics()\n log_eval_metrics(step, metrics)\n returns.append(metrics[\"AverageReturn\"])\n\n if log_interval and step % log_interval == 0:\n print('step = {0}: loss = {1}'.format(step, loss_info.loss.numpy()))\n\nrb_observer.close()\nreverb_server.stop()",
"_____no_output_____"
]
],
[
[
"## Visualization\n",
"_____no_output_____"
],
[
"### Plots\n\nWe can plot average return vs global steps to see the performance of our agent. In `Minitaur`, the reward function is based on how far the minitaur walks in 1000 steps and penalizes the energy expenditure.",
"_____no_output_____"
]
],
[
[
"#@test {\"skip\": true}\n\nsteps = range(0, num_iterations + 1, eval_interval)\nplt.plot(steps, returns)\nplt.ylabel('Average Return')\nplt.xlabel('Step')\nplt.ylim()",
"_____no_output_____"
]
],
[
[
"### Videos",
"_____no_output_____"
],
[
"It is helpful to visualize the performance of an agent by rendering the environment at each step. Before we do that, let us first create a function to embed videos in this colab.",
"_____no_output_____"
]
],
[
[
"def embed_mp4(filename):\n \"\"\"Embeds an mp4 file in the notebook.\"\"\"\n video = open(filename,'rb').read()\n b64 = base64.b64encode(video)\n tag = '''\n <video width=\"640\" height=\"480\" controls>\n <source src=\"data:video/mp4;base64,{0}\" type=\"video/mp4\">\n Your browser does not support the video tag.\n </video>'''.format(b64.decode())\n\n return IPython.display.HTML(tag)",
"_____no_output_____"
]
],
[
[
"The following code visualizes the agent's policy for a few episodes:",
"_____no_output_____"
]
],
[
[
"num_episodes = 3\nvideo_filename = 'sac_minitaur.mp4'\nwith imageio.get_writer(video_filename, fps=60) as video:\n for _ in range(num_episodes):\n time_step = eval_env.reset()\n video.append_data(eval_env.render())\n while not time_step.is_last():\n action_step = eval_actor.policy.action(time_step)\n time_step = eval_env.step(action_step.action)\n video.append_data(eval_env.render())\n\nembed_mp4(video_filename)",
"_____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",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a35047aa79dfa659e9f380fe376e68ef1ed0f77
| 50,561 |
ipynb
|
Jupyter Notebook
|
lab_2/colab_02.ipynb
|
HSG-AIML-Teaching/ML2022-Lab
|
c1931988a4af8eac5a953bc1b9ec5aa137a3957d
|
[
"BSD-3-Clause"
] | 9 |
2022-02-25T03:59:25.000Z
|
2022-03-28T14:29:47.000Z
|
lab_2/colab_02.ipynb
|
HSG-AIML-Teaching/ML2022-Lab
|
c1931988a4af8eac5a953bc1b9ec5aa137a3957d
|
[
"BSD-3-Clause"
] | null | null | null |
lab_2/colab_02.ipynb
|
HSG-AIML-Teaching/ML2022-Lab
|
c1931988a4af8eac5a953bc1b9ec5aa137a3957d
|
[
"BSD-3-Clause"
] | 1 |
2022-02-17T08:31:39.000Z
|
2022-02-17T08:31:39.000Z
| 29.970954 | 620 | 0.602282 |
[
[
[
"<img align=\"center\" style=\"max-width: 1000px\" src=\"banner.png\">",
"_____no_output_____"
],
[
"<img align=\"right\" style=\"max-width: 200px; height: auto\" src=\"hsg_logo.png\">\n\n## Lab 02 - \"Artificial Neural Networks\"\n\nMachine Learning, University of St. Gallen, Spring Term 2022",
"_____no_output_____"
],
[
"The lab environment of the \"Coding and Artificial Intelligence\" IEMBA course at the University of St. Gallen (HSG) is based on Jupyter Notebooks (https://jupyter.org), which allow to perform a variety of statistical evaluations and data analyses.",
"_____no_output_____"
],
[
"In this lab, we will learn how to implement, train, and apply our first **Artificial Neural Network (ANN)** using a Python library named `PyTorch`. The `PyTorch` library is an open-source machine learning library for Python, used for a variety of applications such as image classification and natural language processing. We will use the implemented neural network to learn to again classify images of fashion articles from the **Fashion-MNIST** dataset.\n\nThe figure below illustrates a high-level view of the machine learning process we aim to establish in this lab:",
"_____no_output_____"
],
[
"<img align=\"center\" style=\"max-width: 700px\" src=\"classification.png\">",
"_____no_output_____"
],
[
"As always, pls. don't hesitate to ask all your questions either during the lab, post them in our CANVAS (StudyNet) forum (https://learning.unisg.ch), or send us an email (using the course email).",
"_____no_output_____"
],
[
"## 1. Lab Objectives:",
"_____no_output_____"
],
[
"After today's lab, you should be able to:\n\n> 1. Understand the basic concepts, intuitions and major building blocks of **Artificial Neural Networks (ANNs)**.\n> 2. Know how to use Python's **PyTorch library** to train and evaluate neural network based models.\n> 3. Understand how to apply neural networks to **classify images** of handwritten digits.\n> 4. Know how to **interpret the detection results** of the network as well as its **reconstruction loss**.",
"_____no_output_____"
],
[
"Before we start let's watch a motivational video:",
"_____no_output_____"
]
],
[
[
"from IPython.display import YouTubeVideo\n# Official Intro | GTC 2017 | I AM AI\"\n# YouTubeVideo('SUNPrR4o5ZA', width=800, height=400)",
"_____no_output_____"
]
],
[
[
"## 2. Setup of the Jupyter Notebook Environment",
"_____no_output_____"
],
[
"Similar to the previous labs, we need to import a couple of Python libraries that allow for data analysis and data visualization. We will mostly use the `PyTorch`, `Numpy`, `Scikit-Learn`, `Matplotlib` and the `Seaborn` and a few utility libraries throughout this lab:",
"_____no_output_____"
]
],
[
[
"# import standard python libraries\nimport os, urllib, io\nfrom datetime import datetime\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"Import the Python machine / deep learning libraries:",
"_____no_output_____"
]
],
[
[
"# import the PyTorch deep learning libary\nimport torch, torchvision\nimport torch.nn.functional as F\nfrom torch import nn, optim",
"_____no_output_____"
]
],
[
[
"Import the sklearn classification metrics:",
"_____no_output_____"
]
],
[
[
"# import sklearn classification evaluation library\nfrom sklearn import metrics\nfrom sklearn.metrics import classification_report, confusion_matrix",
"_____no_output_____"
]
],
[
[
"Import Python plotting libraries:",
"_____no_output_____"
]
],
[
[
"# import matplotlib, seaborn, and PIL data visualization libary\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom PIL import Image",
"_____no_output_____"
]
],
[
[
"Enable notebook matplotlib inline plotting:",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"Import `Google's GDrive` connector and mount your `GDrive` directories:",
"_____no_output_____"
]
],
[
[
"# import the Google Colab GDrive connector\nfrom google.colab import drive\n\n# mount GDrive inside the Colab notebook\ndrive.mount('/content/drive')",
"_____no_output_____"
]
],
[
[
"Create a structure of `Colab` Notebook sub-directories inside of `GDrive` to to store the data and the trained neural network models:",
"_____no_output_____"
]
],
[
[
"# create Colab Notebooks directory\nnotebook_directory = '/content/drive/MyDrive/Colab Notebooks'\nif not os.path.exists(notebook_directory): os.makedirs(notebook_directory)\n\n # create data sub-directory inside the Colab Notebooks directory\ndata_directory = '/content/drive/MyDrive/Colab Notebooks/data_fmnist'\nif not os.path.exists(data_directory): os.makedirs(data_directory)\n\n # create models sub-directory inside the Colab Notebooks directory\nmodels_directory = '/content/drive/MyDrive/Colab Notebooks/models_fmnist'\nif not os.path.exists(models_directory): os.makedirs(models_directory)",
"_____no_output_____"
]
],
[
[
"Set a random `seed` value to obtain reproducable results:",
"_____no_output_____"
]
],
[
[
"# init deterministic seed\nseed_value = 1234\nnp.random.seed(seed_value) # set numpy seed\ntorch.manual_seed(seed_value) # set pytorch seed CPU",
"_____no_output_____"
]
],
[
[
"Google Colab provides the use of free GPUs for running notebooks. However, if you just execute this notebook as is, it will use your device's CPU. To run the lab on a GPU, got to `Runtime` > `Change runtime type` and set the Runtime type to `GPU` in the drop-down. Running this lab on a CPU is fine, but you will find that GPU computing is faster. *CUDA* indicates that the lab is being run on GPU.\n\nEnable GPU computing by setting the device flag and init a CUDA seed:",
"_____no_output_____"
]
],
[
[
"# set cpu or gpu enabled device\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu').type\n\n# init deterministic GPU seed\ntorch.cuda.manual_seed(seed_value)\n\n# log type of device enabled\nprint('[LOG] notebook with {} computation enabled'.format(str(device)))",
"_____no_output_____"
]
],
[
[
"Let's determine if we have access to a GPU provided by e.g. `Google's Colab` environment:",
"_____no_output_____"
]
],
[
[
"!nvidia-smi",
"_____no_output_____"
]
],
[
[
"## 3. Dataset Download and Data Assessment",
"_____no_output_____"
],
[
"The **Fashion-MNIST database** is a large database of Zalando articles that is commonly used for training various image processing systems. The database is widely used for training and testing in the field of machine learning. Let's have a brief look into a couple of sample images contained in the dataset:",
"_____no_output_____"
],
[
"<img align=\"center\" style=\"max-width: 700px; height: 300px\" src=\"FashionMNIST.png\">\n\nSource: https://www.kaggle.com/c/insar-fashion-mnist-challenge",
"_____no_output_____"
],
[
"Further details on the dataset can be obtained via Zalando research's [github page](https://github.com/zalandoresearch/fashion-mnist).",
"_____no_output_____"
],
[
"The **Fashion-MNIST database** is an image dataset of Zalando's article images, consisting of in total 70,000 images.\n\nThe dataset is divided into a set of **60,000 training examples** and a set of **10,000 evaluation examples**. Each example is a **28x28 grayscale image**, associated with a **label from 10 classes**. Zalando created this dataset with the intention of providing a replacement for the popular **MNIST** handwritten digits dataset. It is a useful addition as it is a bit more complex, but still very easy to use. It shares the same image size and train/test split structure as MNIST, and can therefore be used as a drop-in replacement. It requires minimal efforts on preprocessing and formatting the distinct images.",
"_____no_output_____"
],
[
"Let's download, transform and inspect the training images of the dataset. Therefore, let's first define the directory in which we aim to store the training data:",
"_____no_output_____"
]
],
[
[
"train_path = data_directory + '/train_fmnist'",
"_____no_output_____"
]
],
[
[
"Now, let's download the training data accordingly:",
"_____no_output_____"
]
],
[
[
"# define pytorch transformation into tensor format\ntransf = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])\n\n# download and transform training images\nfashion_mnist_train_data = torchvision.datasets.FashionMNIST(root=train_path, train=True, transform=transf, download=True)",
"_____no_output_____"
]
],
[
[
"Verify the number of training images downloaded:",
"_____no_output_____"
]
],
[
[
"# determine the number of training data images\nlen(fashion_mnist_train_data)",
"_____no_output_____"
]
],
[
[
"Furthermore, let's inspect a couple of the downloaded training images:",
"_____no_output_____"
]
],
[
[
"# select and set a (random) image id\nimage_id = 3000\n\n# retrieve image exhibiting the image id\nfashion_mnist_train_data[image_id]",
"_____no_output_____"
]
],
[
[
"Ok, that doesn't seem right :). Let's now seperate the image from its label information:",
"_____no_output_____"
]
],
[
[
"fashion_mnist_train_image, fashion_mnist_train_label = fashion_mnist_train_data[image_id]",
"_____no_output_____"
]
],
[
[
"We can verify the label that our selected image has:",
"_____no_output_____"
]
],
[
[
"fashion_mnist_train_label",
"_____no_output_____"
]
],
[
[
"Ok, we know that the numerical label is 6. Each image is associated with a label from 0 to 9, and this number represents one of the fashion items. So what does 6 mean? Is 6 a bag? A pullover? The order of the classes can be found on Zalando research's [github page](https://github.com/zalandoresearch/fashion-mnist). We need to map each numerical label to its fashion item, which will be useful throughout the lab:",
"_____no_output_____"
]
],
[
[
"fashion_classes = {0: 'T-shirt/top',\n 1: 'Trouser',\n 2: 'Pullover',\n 3: 'Dress',\n 4: 'Coat',\n 5: 'Sandal',\n 6: 'Shirt',\n 7: 'Sneaker',\n 8: 'Bag',\n 9: 'Ankle boot'}",
"_____no_output_____"
]
],
[
[
"So, we can determine the fashion item that the label represents:",
"_____no_output_____"
]
],
[
[
"fashion_classes[fashion_mnist_train_label]",
"_____no_output_____"
]
],
[
[
"Great, let's now visually inspect our sample image: ",
"_____no_output_____"
]
],
[
[
"# define tensor to image transformation\ntrans = torchvision.transforms.ToPILImage()\n\n# set image plot title \nplt.title('Example: {}, Label: {}'.format(str(image_id), fashion_classes[fashion_mnist_train_label]))\n\n# plot mnist handwritten digit sample\nplt.imshow(trans(fashion_mnist_train_image), cmap='gray')",
"_____no_output_____"
]
],
[
[
"Fantastic, right? Let's now define the directory in which we aim to store the evaluation data:",
"_____no_output_____"
]
],
[
[
"eval_path = data_directory + '/eval_fmnist'",
"_____no_output_____"
]
],
[
[
"And download the evaluation data accordingly:",
"_____no_output_____"
]
],
[
[
"# define pytorch transformation into tensor format\ntransf = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])\n\n# download and transform training images\nfashion_mnist_eval_data = torchvision.datasets.FashionMNIST(root=eval_path, train=False, transform=transf, download=True)",
"_____no_output_____"
]
],
[
[
"Let's also verify the number of evaluation images downloaded:",
"_____no_output_____"
]
],
[
[
"# determine the number of evaluation data images\nlen(fashion_mnist_eval_data)",
"_____no_output_____"
]
],
[
[
"## 4. Neural Network Implementation",
"_____no_output_____"
],
[
"In this section we, will implement the architecture of the **neural network** we aim to utilize to learn a model that is capable to classify the 28x28 pixel FashionMNIST images of fashion items. However, before we start the implementation let's briefly revisit the process to be established. The following cartoon provides a birds-eye view:",
"_____no_output_____"
],
[
"<img align=\"center\" style=\"max-width: 1000px\" src=\"https://github.com/HSG-AIML/LabGSERM/blob/main/lab_04/process.png?raw=1\">",
"_____no_output_____"
],
[
"### 4.1 Implementation of the Neural Network Architecture",
"_____no_output_____"
],
[
"The neural network, which we name **'FashionMNISTNet'** consists of three **fully-connected layers** (including an “input layer” and two hidden layers). Furthermore, the **FashionMNISTNet** should encompass the following number of neurons per layer: 100 (layer 1), 50 (layer 2) and 10 (layer 3). Meaning the first layer consists of 100 neurons, the second layer of 50 neurons and third layer of 10 neurons (the number of digit classes we aim to classify.",
"_____no_output_____"
],
[
"We will now start implementing the network architecture as a separate Python class. Implementing the network architectures as a **separate class** in Python is good practice in deep learning projects. It will allow us to create and train several instances of the same neural network architecture. This provides us, for example, the opportunity to evaluate different initializations of the network parameters or train models using distinct datasets. ",
"_____no_output_____"
]
],
[
[
"# implement the MNISTNet network architecture\nclass FashionMNISTNet(nn.Module):\n \n # define the class constructor\n def __init__(self):\n \n # call super class constructor\n super(FashionMNISTNet, self).__init__()\n \n # specify fully-connected (fc) layer 1 - in 28*28, out 100\n self.linear1 = nn.Linear(28*28, 100, bias=True) # the linearity W*x+b\n self.relu1 = nn.ReLU(inplace=True) # the non-linearity \n \n # specify fc layer 2 - in 100, out 50\n self.linear2 = nn.Linear(100, 50, bias=True) # the linearity W*x+b\n self.relu2 = nn.ReLU(inplace=True) # the non-linarity\n \n # specify fc layer 3 - in 50, out 10\n self.linear3 = nn.Linear(50, 10) # the linearity W*x+b\n \n # add a softmax to the last layer\n self.logsoftmax = nn.LogSoftmax(dim=1) # the softmax\n \n # define network forward pass\n def forward(self, images):\n \n # reshape image pixels\n x = images.view(-1, 28*28)\n \n # define fc layer 1 forward pass\n x = self.relu1(self.linear1(x))\n \n # define fc layer 2 forward pass\n x = self.relu2(self.linear2(x))\n \n # define layer 3 forward pass\n x = self.logsoftmax(self.linear3(x))\n \n # return forward pass result\n return x",
"_____no_output_____"
]
],
[
[
"You may have noticed, when reviewing the implementation above, that we applied an additional operator, referred to as **'Softmax'** to the third layer of our neural network.\n\nThe **softmax function**, also known as the normalized exponential function, is a function that takes as input a vector of K real numbers, and normalizes it into a probability distribution consisting of K probabilities. \n\nThat is, prior to applying softmax, some vector components could be negative, or greater than one; and might not sum to 1; but after application of the softmax, each component will be in the interval $(0,1)$, and the components will add up to 1, so that they can be interpreted as probabilities. In general, the softmax function $\\sigma :\\mathbb {R} ^{K}\\to \\mathbb {R} ^{K}$ is defined by the formula:",
"_____no_output_____"
],
[
"<center> $\\sigma (\\mathbf {z} )_{i}=\\ln ({e^{z_{i}} / \\sum _{j=1}^{K}e^{z_{j}}})$ </center>",
"_____no_output_____"
],
[
"for $i = 1, …, K$ and ${\\mathbf {z}}=(z_{1},\\ldots ,z_{K})\\in \\mathbb {R} ^{K}$ (Source: https://en.wikipedia.org/wiki/Softmax_function ). \n\nLet's have a look at the simplified three-class example below. The scores of the distinct predicted classes $c_i$ are computed from the forward propagation of the network. We then take the softmax and obtain the probabilities as shown:",
"_____no_output_____"
],
[
"<img align=\"center\" style=\"max-width: 800px\" src=\"https://github.com/HSG-AIML/LabGSERM/blob/main/lab_04/softmax.png?raw=1\">",
"_____no_output_____"
],
[
"The output of the softmax describes the probability (or if you may, the confidence) of the neural network that a particular sample belongs to a certain class. Thus, for the first example above, the neural network assigns a confidence of 0.49 that it is a 'three', 0.49 that it is a 'four', and 0.03 that it is an 'eight'. The same goes for each of the samples above.\n\nNow, that we have implemented our first neural network we are ready to instantiate a network model to be trained:",
"_____no_output_____"
]
],
[
[
"model = FashionMNISTNet()",
"_____no_output_____"
]
],
[
[
"Let's push the initialized `FashionMNISTNet` model to the computing `device` that is enabled:",
"_____no_output_____"
]
],
[
[
"model = model.to(device)",
"_____no_output_____"
]
],
[
[
"Let's double check if our model was deployed to the GPU if available:",
"_____no_output_____"
]
],
[
[
"!nvidia-smi",
"_____no_output_____"
]
],
[
[
"Once the model is initialized, we can visualize the model structure and review the implemented network architecture by execution of the following cell:",
"_____no_output_____"
]
],
[
[
"# print the initialized architectures\nprint('[LOG] FashionMNISTNet architecture:\\n\\n{}\\n'.format(model))",
"_____no_output_____"
]
],
[
[
"Looks like intended? Brilliant! Finally, let's have a look into the number of model parameters that we aim to train in the next steps of the notebook:",
"_____no_output_____"
]
],
[
[
"# init the number of model parameters\nnum_params = 0\n\n# iterate over the distinct parameters\nfor param in model.parameters():\n\n # collect number of parameters\n num_params += param.numel()\n \n# print the number of model paramters\nprint('[LOG] Number of to be trained FashionMNISTNet model parameters: {}.'.format(num_params))",
"_____no_output_____"
]
],
[
[
"Ok, our \"simple\" FashionMNISTNet model already encompasses an impressive number 84'060 model parameters to be trained.",
"_____no_output_____"
],
[
"### 4.2 Specification of the Neural Network Loss Function",
"_____no_output_____"
],
[
"Now that we have implemented the **FashionMNISTNet** we are ready to train the network. However, prior to starting the training, we need to define an appropriate loss function. Remember, we aim to train our model to learn a set of model parameters $\\theta$ that minimize the classification error of the true class $c^{i}$ of a given handwritten digit image $x^{i}$ and its predicted class $\\hat{c}^{i} = f_\\theta(x^{i})$ as faithfully as possible. \n\nThereby, the training objective is to learn a set of optimal model parameters $\\theta^*$ that optimize $\\arg\\min_{\\theta} \\|C - f_\\theta(X)\\|$ over all training images in the FashionMNIST dataset. To achieve this optimization objective, one typically minimizes a loss function $\\mathcal{L_{\\theta}}$ as part of the network training. In this lab we use the **'Negative Log Likelihood (NLL)'** loss, defined by:\n\n<center> $\\mathcal{L}^{NLL}_{\\theta} (c_i, \\hat c_i) = - \\frac{1}{N} \\sum_{i=1}^N \\log (\\hat{c}_i) $, </center>",
"_____no_output_____"
],
[
"for a set of $n$-FashionMNIST images $x^{i}$, $i=1,...,n$ and their respective predicted class labels $\\hat{c}^{i}$. This is summed for all the correct classes. \n\nLet's have a look at a brief example:",
"_____no_output_____"
],
[
"<img align=\"center\" style=\"max-width: 900px\" src=\"./loss.png\">",
"_____no_output_____"
],
[
"As we see in the example, we first compute class predictions for each class. We normalize the predictions with a softmax over all classes, so that we end up with 'probabilities' (that's what comes out of the NN). \nTo compute the loss, we pick the predicted probability of the true class $\\hat{c}_i$ and take the log of it. As the probabilities are on [0,1], the log of them are on [-$\\infty$,0]. To maximize the probability of the true class $\\hat{c}_i$, we have to maximize $log(\\hat{c}_i)$. Due to the softmax, the predicted probabilties of all classes $c_i$ sum to 1: $\\sum_i c_i = 1$. Therefore, by maximizing the probability of the true class $\\hat{c}_i$, we minimize the probabilities of all the other (wrong) classes. \nIn ML, it has become common to minimize an 'error' or 'loss' term. Therfore, we sum over the log-likelihoods and take the negative of it. Small values (close to $0$) here translate to high values in true class probability. ",
"_____no_output_____"
],
[
"During training the **NLL** loss will penalize models that result in a high classification error between the predicted class labels $\\hat{c}^{i}$ and their respective true class label $c^{i}$. Luckily, an implementation of the NLL loss is already available in PyTorch! It can be instantiated \"off-the-shelf\" via the execution of the following PyTorch command:",
"_____no_output_____"
]
],
[
[
"# define the optimization criterion / loss function\nnll_loss = nn.NLLLoss()",
"_____no_output_____"
]
],
[
[
"Let's also push the initialized `nll_loss` computation to the computing `device` that is enabled:",
"_____no_output_____"
]
],
[
[
"nll_loss = nll_loss.to(device)",
"_____no_output_____"
]
],
[
[
"## 5. Neural Network Model Training",
"_____no_output_____"
],
[
"In this section, we will train our neural network model (as implemented in the section above) using the transformed images of fashion items. More specifically, we will have a detailed look into the distinct training steps as well as how to monitor the training progress.",
"_____no_output_____"
],
[
"### 5.1. Preparing the Network Training",
"_____no_output_____"
],
[
"So far, we have pre-processed the dataset, implemented the ANN and defined the classification error. Let's now start to train a corresponding model for **20 epochs** and a **mini-batch size of 128** FashionMNIST images per batch. This implies that the whole dataset will be fed to the ANN 20 times in chunks of 128 images yielding to **469 mini-batches** (60.000 images / 128 images per mini-batch) per epoch.",
"_____no_output_____"
]
],
[
[
"# specify the training parameters\nnum_epochs = 20 # number of training epochs\nmini_batch_size = 128 # size of the mini-batches",
"_____no_output_____"
]
],
[
[
"Based on the loss magnitude of a certain mini-batch PyTorch automatically computes the gradients. But even better, based on the gradient, the library also helps us in the optimization and update of the network parameters $\\theta$.\n\nWe will use the **Stochastic Gradient Descent (SGD) optimization** and set the learning-rate $l = 0.001$. Each mini-batch step the optimizer will update the model parameters $\\theta$ values according to the degree of classification error (the MSE loss).",
"_____no_output_____"
]
],
[
[
"# define learning rate and optimization strategy\nlearning_rate = 0.001\noptimizer = optim.SGD(params=model.parameters(), lr=learning_rate)",
"_____no_output_____"
]
],
[
[
"Now that we have successfully implemented and defined the three ANN building blocks let's take some time to review the `FashionMNISTNet` model definition as well as the `loss`. Please, read the above code and comments carefully and don't hesitate to let us know any questions you might have.",
"_____no_output_____"
],
[
"Furthermore, lets specify and instantiate a corresponding PyTorch data loader that feeds the image tensors to our neural network:",
"_____no_output_____"
]
],
[
[
"fashion_mnist_train_dataloader = torch.utils.data.DataLoader(fashion_mnist_train_data, batch_size=mini_batch_size, shuffle=True)",
"_____no_output_____"
]
],
[
[
"### 5.2. Running the Network Training",
"_____no_output_____"
],
[
"Finally, we start training the model. The detailed training procedure for each mini-batch is performed as follows: \n\n>1. do a forward pass through the FashionMNISTNet network, \n>2. compute the negative log likelihood classification error $\\mathcal{L}^{NLL}_{\\theta}(c^{i};\\hat{c}^{i})$, \n>3. do a backward pass through the FashionMNISTNet network, and \n>4. update the parameters of the network $f_\\theta(\\cdot)$.\n\nTo ensure learning while training our ANN model, we will monitor whether the loss decreases with progressing training. Therefore, we obtain and evaluate the classification performance of the entire training dataset after each training epoch. Based on this evaluation, we can conclude on the training progress and whether the loss is converging (indicating that the model might not improve any further).\n\nThe following elements of the network training code below should be given particular attention:\n \n>- `loss.backward()` computes the gradients based on the magnitude of the reconstruction loss,\n>- `optimizer.step()` updates the network parameters based on the gradient.",
"_____no_output_____"
]
],
[
[
"# init collection of training epoch losses\ntrain_epoch_losses = []\n\n# set the model in training mode\nmodel.train()\n\n# train the MNISTNet model\nfor epoch in range(num_epochs):\n \n # init collection of mini-batch losses\n train_mini_batch_losses = []\n \n # iterate over all-mini batches\n for i, (images, labels) in enumerate(fashion_mnist_train_dataloader):\n \n # push mini-batch data to computation device\n images = images.to(device)\n labels = labels.to(device)\n\n # run forward pass through the network\n output = model(images)\n \n # reset graph gradients\n model.zero_grad()\n \n # determine classification loss\n loss = nll_loss(output, labels)\n \n # run backward pass\n loss.backward()\n \n # update network paramaters\n optimizer.step()\n \n # collect mini-batch reconstruction loss\n train_mini_batch_losses.append(loss.data.item())\n \n # determine mean min-batch loss of epoch\n train_epoch_loss = np.mean(train_mini_batch_losses)\n \n # print epoch loss\n now = datetime.utcnow().strftime(\"%Y%m%d-%H:%M:%S\")\n print('[LOG {}] epoch: {} train-loss: {}'.format(str(now), str(epoch), str(train_epoch_loss)))\n \n # set filename of actual model\n model_name = 'fashion_mnist_model_epoch_{}.pth'.format(str(epoch))\n\n # save current model to GDrive models directory\n torch.save(model.state_dict(), os.path.join(models_directory, model_name))\n \n # determine mean min-batch loss of epoch\n train_epoch_losses.append(train_epoch_loss)",
"_____no_output_____"
]
],
[
[
"Upon successfull training let's visualize and inspect the training loss per epoch:",
"_____no_output_____"
]
],
[
[
"# prepare plot\nfig = plt.figure()\nax = fig.add_subplot(111)\n\n# add grid\nax.grid(linestyle='dotted')\n\n# plot the training epochs vs. the epochs' classification error\nax.plot(np.array(range(1, len(train_epoch_losses)+1)), train_epoch_losses, label='epoch loss (blue)')\n\n# add axis legends\nax.set_xlabel(\"[training epoch $e_i$]\", fontsize=10)\nax.set_ylabel(\"[Classification Error $\\mathcal{L}^{NLL}$]\", fontsize=10)\n\n# set plot legend\nplt.legend(loc=\"upper right\", numpoints=1, fancybox=True)\n\n# add plot title\nplt.title('Training Epochs $e_i$ vs. Classification Error $L^{NLL}$', fontsize=10);",
"_____no_output_____"
]
],
[
[
"Ok, fantastic. The training error is nicely going down. We could train the network a couple more epochs until the error converges. But let's stay with the 20 training epochs for now and continue with evaluating our trained model.",
"_____no_output_____"
],
[
"## 6. Neural Network Model Evaluation",
"_____no_output_____"
],
[
"Before evaluating our model let's load the best performing model. Remember, that we stored a snapshot of the model after each training epoch to our local model directory. We will now load the last snapshot saved.",
"_____no_output_____"
]
],
[
[
"### load state_dict from some url\n# # restore pre-trained model snapshot \n# best_model_name = 'https://raw.githubusercontent.com/HSG-AIML-Teaching/ML2022-Lab/main/lab_02/models/fashion_mnist_model_epoch_19.pth'\n\n# # read stored model from the remote location\n# model_bytes = urllib.request.urlopen(best_model_name)\n\n# # load model tensor from io.BytesIO object\n# model_buffer = io.BytesIO(model_bytes.read())\n\n# # init pre-trained model class\n# best_model = FashionMNISTNet()\n\n# # load pre-trained models\n# best_model.load_state_dict(torch.load(model_buffer, map_location=torch.device('cpu')))",
"_____no_output_____"
],
[
"## load state_dict from local path\n# restore pre-trained model snapshot\nbest_model_name = models_directory +'/fashion_mnist_model_epoch_19.pth'\n\n# load state_dict from path\nstate_dict_best = torch.load(best_model_name)\n\n# init pre-trained model class\nbest_model = FashionMNISTNet()\n\n# load pre-trained state_dict to model\nbest_model.load_state_dict(state_dict_best)",
"_____no_output_____"
]
],
[
[
"Let's inspect if the model was loaded successfully: ",
"_____no_output_____"
]
],
[
[
"# set model in evaluation mode\nbest_model.eval()",
"_____no_output_____"
]
],
[
[
"To evaluate our trained model, we need to feed the FashionMNIST images reserved for evaluation (the images that we didn't use as part of the training process) through the model. Therefore, let's again define a corresponding PyTorch data loader that feeds the image tensors to our neural network: ",
"_____no_output_____"
]
],
[
[
"fashion_mnist_eval_dataloader = torch.utils.data.DataLoader(fashion_mnist_eval_data, batch_size=10000, shuffle=True)",
"_____no_output_____"
]
],
[
[
"We will now evaluate the trained model using the same mini-batch approach as we did throughout the network training and derive the mean negative log-likelihood loss of the mini-batches:",
"_____no_output_____"
]
],
[
[
"# init collection of mini-batch losses\neval_mini_batch_losses = []\n\n# iterate over all-mini batches\nfor i, (images, labels) in enumerate(fashion_mnist_eval_dataloader):\n\n # run forward pass through the network\n output = best_model(images)\n\n # determine classification loss\n loss = nll_loss(output, labels)\n\n # collect mini-batch reconstruction loss\n eval_mini_batch_losses.append(loss.data.item())\n\n# determine mean min-batch loss of epoch\neval_loss = np.mean(eval_mini_batch_losses)\n\n# print epoch loss\nnow = datetime.utcnow().strftime(\"%Y%m%d-%H:%M:%S\")\nprint('[LOG {}] eval-loss: {}'.format(str(now), str(eval_loss)))",
"_____no_output_____"
]
],
[
[
"Ok, great. The evaluation loss looks in-line with our training loss. Let's now inspect a few sample predictions to get an impression of the model quality. Therefore, we will again pick a random image of our evaluation dataset and retrieve its PyTorch tensor as well as the corresponding label:",
"_____no_output_____"
]
],
[
[
"# set (random) image id\nimage_id = 2000\n\n# retrieve image exhibiting the image id\nfashion_mnist_eval_image, fashion_mnist_eval_label = fashion_mnist_eval_data[image_id]",
"_____no_output_____"
]
],
[
[
"Let's now inspect the true class of the image we selected:",
"_____no_output_____"
]
],
[
[
"fashion_classes[fashion_mnist_eval_label]",
"_____no_output_____"
]
],
[
[
"Ok, the randomly selected image should contain a bag. Let's inspect the image accordingly:",
"_____no_output_____"
]
],
[
[
"# define tensor to image transformation\ntrans = torchvision.transforms.ToPILImage()\n\n# set image plot title \nplt.title('Example: {}, Label: {}'.format(str(image_id), fashion_classes[fashion_mnist_eval_label]))\n\n# plot mnist handwritten digit sample\nplt.imshow(trans(fashion_mnist_eval_image), cmap='gray')",
"_____no_output_____"
]
],
[
[
"Let's compare the true label with the prediction of our model:",
"_____no_output_____"
]
],
[
[
"best_model(fashion_mnist_eval_image)",
"_____no_output_____"
]
],
[
[
"We can even determine the likelihood of the most probable class:",
"_____no_output_____"
]
],
[
[
"most_probable = torch.argmax(best_model(fashion_mnist_eval_image), dim=1).item()\nprint('Most probable class: {}'.format(most_probable))\nprint('This class represents the following fashion article: {}'.format(fashion_classes[most_probable]))",
"_____no_output_____"
]
],
[
[
"Let's now obtain the predictions for all the fashion item images of the evaluation data:",
"_____no_output_____"
]
],
[
[
"predictions = torch.argmax(best_model(fashion_mnist_eval_data.data.float()), dim=1)",
"_____no_output_____"
]
],
[
[
"Furthermore, let's obtain the overall classifcation accuracy:",
"_____no_output_____"
]
],
[
[
"metrics.accuracy_score(fashion_mnist_eval_data.targets, predictions.detach())",
"_____no_output_____"
]
],
[
[
"Let's also inspect the confusion matrix to determine major sources of misclassification:",
"_____no_output_____"
]
],
[
[
"# determine classification matrix of the predicted and target classes\nmat = confusion_matrix(fashion_mnist_eval_data.targets, predictions.detach())\n\n# initialize the plot and define size\nplt.figure(figsize=(8, 8))\n\n# plot corresponding confusion matrix\nsns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False, cmap='YlOrRd_r', xticklabels=fashion_classes.values(), yticklabels=fashion_classes.values())\nplt.tick_params(axis='both', which='major', labelsize=8, labelbottom = False, bottom=False, top = False, left = False, labeltop=True)\n\n# set plot title\nplt.title('Fashion MNIST classification matrix')\n\n# set axis labels\nplt.xlabel('[true label]')\nplt.ylabel('[predicted label]');",
"_____no_output_____"
]
],
[
[
"Ok, we can easily see that our current model confuses sandals with either sneakers or ankle boots. However, the inverse does not really hold. The model sometimes confuses sneakers with ankle boots, and only very rarely with sandals. The same holds ankle boots. Our model also has issues distinguishing shirts from coats (and, to a lesser degree, from T-shirts and pullovers).\n\nThese mistakes are not very surprising, as these items exhibit a high similarity.",
"_____no_output_____"
],
[
"## 7. Lab Summary:",
"_____no_output_____"
],
[
"In this lab, a step by step introduction into the **design, implementation, training and evaluation** of neural networks to classify images of fashion items is presented. The code and exercises presented in this lab may serves as a starting point for developing more complex, more deep and tailored **neural networks**.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
4a35075073f187eaf2591d3f2cb713bdb483f161
| 20,714 |
ipynb
|
Jupyter Notebook
|
site/en/tutorials/estimator/premade.ipynb
|
BlazerYoo/docs
|
37094bf40829f515e1acf683fdc452cdb02738e9
|
[
"Apache-2.0"
] | 7 |
2021-05-08T18:25:43.000Z
|
2021-09-30T13:41:26.000Z
|
site/en/tutorials/estimator/premade.ipynb
|
BlazerYoo/docs
|
37094bf40829f515e1acf683fdc452cdb02738e9
|
[
"Apache-2.0"
] | 1 |
2021-02-23T20:17:39.000Z
|
2021-02-23T20:17:39.000Z
|
site/en/tutorials/estimator/premade.ipynb
|
BlazerYoo/docs
|
37094bf40829f515e1acf683fdc452cdb02738e9
|
[
"Apache-2.0"
] | 2 |
2021-07-16T15:00:29.000Z
|
2021-08-22T08:20:34.000Z
| 35.652324 | 470 | 0.550111 |
[
[
[
"##### Copyright 2019 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Premade Estimators",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/estimator/premade\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/estimator/premade.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/tutorials/estimator/premade.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/estimator/premade.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"This tutorial shows you\nhow to solve the Iris classification problem in TensorFlow using Estimators. An Estimator is TensorFlow's high-level representation of a complete model, and it has been designed for easy scaling and asynchronous training. For more details see\n[Estimators](https://www.tensorflow.org/guide/estimator).\n\nNote that in TensorFlow 2.0, the [Keras API](https://www.tensorflow.org/guide/keras) can accomplish many of these same tasks, and is believed to be an easier API to learn. If you are starting fresh, we would recommend you start with Keras. For more information about the available high level APIs in TensorFlow 2.0, see [Standardizing on Keras](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a).\n",
"_____no_output_____"
],
[
"## First things first\n\nIn order to get started, you will first import TensorFlow and a number of libraries you will need.",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\n\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"## The data set\n\nThe sample program in this document builds and tests a model that\nclassifies Iris flowers into three different species based on the size of their\n[sepals](https://en.wikipedia.org/wiki/Sepal) and\n[petals](https://en.wikipedia.org/wiki/Petal).\n\n\nYou will train a model using the Iris data set. The Iris data set contains four features and one\n[label](https://developers.google.com/machine-learning/glossary/#label).\nThe four features identify the following botanical characteristics of\nindividual Iris flowers:\n\n* sepal length\n* sepal width\n* petal length\n* petal width\n\nBased on this information, you can define a few helpful constants for parsing the data:\n",
"_____no_output_____"
]
],
[
[
"CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth', 'Species']\nSPECIES = ['Setosa', 'Versicolor', 'Virginica']",
"_____no_output_____"
]
],
[
[
"Next, download and parse the Iris data set using Keras and Pandas. Note that you keep distinct datasets for training and testing.",
"_____no_output_____"
]
],
[
[
"train_path = tf.keras.utils.get_file(\n \"iris_training.csv\", \"https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv\")\ntest_path = tf.keras.utils.get_file(\n \"iris_test.csv\", \"https://storage.googleapis.com/download.tensorflow.org/data/iris_test.csv\")\n\ntrain = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)\ntest = pd.read_csv(test_path, names=CSV_COLUMN_NAMES, header=0)",
"_____no_output_____"
]
],
[
[
"You can inspect your data to see that you have four float feature columns and one int32 label.",
"_____no_output_____"
]
],
[
[
"train.head()",
"_____no_output_____"
]
],
[
[
"For each of the datasets, split out the labels, which the model will be trained to predict.",
"_____no_output_____"
]
],
[
[
"train_y = train.pop('Species')\ntest_y = test.pop('Species')\n\n# The label column has now been removed from the features.\ntrain.head()",
"_____no_output_____"
]
],
[
[
"## Overview of programming with Estimators\n\nNow that you have the data set up, you can define a model using a TensorFlow Estimator. An Estimator is any class derived from `tf.estimator.Estimator`. TensorFlow\nprovides a collection of\n`tf.estimator`\n(for example, `LinearRegressor`) to implement common ML algorithms. Beyond\nthose, you may write your own\n[custom Estimators](https://www.tensorflow.org/guide/custom_estimators).\nWe recommend using pre-made Estimators when just getting started.\n\nTo write a TensorFlow program based on pre-made Estimators, you must perform the\nfollowing tasks:\n\n* Create one or more input functions.\n* Define the model's feature columns.\n* Instantiate an Estimator, specifying the feature columns and various\n hyperparameters.\n* Call one or more methods on the Estimator object, passing the appropriate\n input function as the source of the data.\n\nLet's see how those tasks are implemented for Iris classification.",
"_____no_output_____"
],
[
"## Create input functions\n\nYou must create input functions to supply data for training,\nevaluating, and prediction.\n\nAn **input function** is a function that returns a `tf.data.Dataset` object\nwhich outputs the following two-element tuple:\n\n* [`features`](https://developers.google.com/machine-learning/glossary/#feature) - A Python dictionary in which:\n * Each key is the name of a feature.\n * Each value is an array containing all of that feature's values.\n* `label` - An array containing the values of the\n [label](https://developers.google.com/machine-learning/glossary/#label) for\n every example.\n\nJust to demonstrate the format of the input function, here's a simple\nimplementation:",
"_____no_output_____"
]
],
[
[
"def input_evaluation_set():\n features = {'SepalLength': np.array([6.4, 5.0]),\n 'SepalWidth': np.array([2.8, 2.3]),\n 'PetalLength': np.array([5.6, 3.3]),\n 'PetalWidth': np.array([2.2, 1.0])}\n labels = np.array([2, 1])\n return features, labels",
"_____no_output_____"
]
],
[
[
"Your input function may generate the `features` dictionary and `label` list any\nway you like. However, we recommend using TensorFlow's [Dataset API](https://www.tensorflow.org/guide/datasets), which can\nparse all sorts of data.\n\nThe Dataset API can handle a lot of common cases for you. For example,\nusing the Dataset API, you can easily read in records from a large collection\nof files in parallel and join them into a single stream.\n\nTo keep things simple in this example you are going to load the data with\n[pandas](https://pandas.pydata.org/), and build an input pipeline from this\nin-memory data:\n",
"_____no_output_____"
]
],
[
[
"def input_fn(features, labels, training=True, batch_size=256):\n \"\"\"An input function for training or evaluating\"\"\"\n # Convert the inputs to a Dataset.\n dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))\n\n # Shuffle and repeat if you are in training mode.\n if training:\n dataset = dataset.shuffle(1000).repeat()\n \n return dataset.batch(batch_size)\n",
"_____no_output_____"
]
],
[
[
"## Define the feature columns\n\nA [**feature column**](https://developers.google.com/machine-learning/glossary/#feature_columns)\nis an object describing how the model should use raw input data from the\nfeatures dictionary. When you build an Estimator model, you pass it a list of\nfeature columns that describes each of the features you want the model to use.\nThe `tf.feature_column` module provides many options for representing data\nto the model.\n\nFor Iris, the 4 raw features are numeric values, so we'll build a list of\nfeature columns to tell the Estimator model to represent each of the four\nfeatures as 32-bit floating-point values. Therefore, the code to create the\nfeature column is:",
"_____no_output_____"
]
],
[
[
"# Feature columns describe how to use the input.\nmy_feature_columns = []\nfor key in train.keys():\n my_feature_columns.append(tf.feature_column.numeric_column(key=key))",
"_____no_output_____"
]
],
[
[
"Feature columns can be far more sophisticated than those we're showing here. You can read more about Feature Columns in [this guide](https://www.tensorflow.org/guide/feature_columns).\n\nNow that you have the description of how you want the model to represent the raw\nfeatures, you can build the estimator.",
"_____no_output_____"
],
[
"## Instantiate an estimator\n\nThe Iris problem is a classic classification problem. Fortunately, TensorFlow\nprovides several pre-made classifier Estimators, including:\n\n* `tf.estimator.DNNClassifier` for deep models that perform multi-class\n classification.\n* `tf.estimator.DNNLinearCombinedClassifier` for wide & deep models.\n* `tf.estimator.LinearClassifier` for classifiers based on linear models.\n\nFor the Iris problem, `tf.estimator.DNNClassifier` seems like the best choice.\nHere's how you instantiated this Estimator:",
"_____no_output_____"
]
],
[
[
"# Build a DNN with 2 hidden layers with 30 and 10 hidden nodes each.\nclassifier = tf.estimator.DNNClassifier(\n feature_columns=my_feature_columns,\n # Two hidden layers of 30 and 10 nodes respectively.\n hidden_units=[30, 10],\n # The model must choose between 3 classes.\n n_classes=3)",
"_____no_output_____"
]
],
[
[
"## Train, Evaluate, and Predict\n\nNow that you have an Estimator object, you can call methods to do the following:\n\n* Train the model.\n* Evaluate the trained model.\n* Use the trained model to make predictions.",
"_____no_output_____"
],
[
"### Train the model\n\nTrain the model by calling the Estimator's `train` method as follows:",
"_____no_output_____"
]
],
[
[
"# Train the Model.\nclassifier.train(\n input_fn=lambda: input_fn(train, train_y, training=True),\n steps=5000)",
"_____no_output_____"
]
],
[
[
"Note that you wrap up your `input_fn` call in a\n[`lambda`](https://docs.python.org/3/tutorial/controlflow.html)\nto capture the arguments while providing an input function that takes no\narguments, as expected by the Estimator. The `steps` argument tells the method\nto stop training after a number of training steps.\n",
"_____no_output_____"
],
[
"### Evaluate the trained model\n\nNow that the model has been trained, you can get some statistics on its\nperformance. The following code block evaluates the accuracy of the trained\nmodel on the test data:\n",
"_____no_output_____"
]
],
[
[
"eval_result = classifier.evaluate(\n input_fn=lambda: input_fn(test, test_y, training=False))\n\nprint('\\nTest set accuracy: {accuracy:0.3f}\\n'.format(**eval_result))",
"_____no_output_____"
]
],
[
[
"Unlike the call to the `train` method, you did not pass the `steps`\nargument to evaluate. The `input_fn` for eval only yields a single\n[epoch](https://developers.google.com/machine-learning/glossary/#epoch) of data.\n\n\nThe `eval_result` dictionary also contains the `average_loss` (mean loss per sample), the `loss` (mean loss per mini-batch) and the value of the estimator's `global_step` (the number of training iterations it underwent).\n",
"_____no_output_____"
],
[
"### Making predictions (inferring) from the trained model\n\nYou now have a trained model that produces good evaluation results.\nYou can now use the trained model to predict the species of an Iris flower\nbased on some unlabeled measurements. As with training and evaluation, you make\npredictions using a single function call:",
"_____no_output_____"
]
],
[
[
"# Generate predictions from the model\nexpected = ['Setosa', 'Versicolor', 'Virginica']\npredict_x = {\n 'SepalLength': [5.1, 5.9, 6.9],\n 'SepalWidth': [3.3, 3.0, 3.1],\n 'PetalLength': [1.7, 4.2, 5.4],\n 'PetalWidth': [0.5, 1.5, 2.1],\n}\n\ndef input_fn(features, batch_size=256):\n \"\"\"An input function for prediction.\"\"\"\n # Convert the inputs to a Dataset without labels.\n return tf.data.Dataset.from_tensor_slices(dict(features)).batch(batch_size)\n\npredictions = classifier.predict(\n input_fn=lambda: input_fn(predict_x))",
"_____no_output_____"
]
],
[
[
"The `predict` method returns a Python iterable, yielding a dictionary of\nprediction results for each example. The following code prints a few\npredictions and their probabilities:",
"_____no_output_____"
]
],
[
[
"for pred_dict, expec in zip(predictions, expected):\n class_id = pred_dict['class_ids'][0]\n probability = pred_dict['probabilities'][class_id]\n\n print('Prediction is \"{}\" ({:.1f}%), expected \"{}\"'.format(\n SPECIES[class_id], 100 * probability, expec))",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a350b8c72124538d26eedf74087e7f96de81b93
| 13,791 |
ipynb
|
Jupyter Notebook
|
LeNet-Lab/LeNet-Lab-Solution.ipynb
|
vbrichzin/udacity-ND-SDCE-TrafficSignClassifier-P3
|
af3bee20feaca3704675ecddee3c602d2e6ebb45
|
[
"MIT"
] | null | null | null |
LeNet-Lab/LeNet-Lab-Solution.ipynb
|
vbrichzin/udacity-ND-SDCE-TrafficSignClassifier-P3
|
af3bee20feaca3704675ecddee3c602d2e6ebb45
|
[
"MIT"
] | null | null | null |
LeNet-Lab/LeNet-Lab-Solution.ipynb
|
vbrichzin/udacity-ND-SDCE-TrafficSignClassifier-P3
|
af3bee20feaca3704675ecddee3c602d2e6ebb45
|
[
"MIT"
] | null | null | null | 31.486301 | 310 | 0.560075 |
[
[
[
"# LeNet Lab Solution\n\nSource: Yan LeCun",
"_____no_output_____"
],
[
"## Load Data\n\nLoad the MNIST data, which comes pre-loaded with TensorFlow.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"from tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", reshape=False)\nX_train, y_train = mnist.train.images, mnist.train.labels\nX_validation, y_validation = mnist.validation.images, mnist.validation.labels\nX_test, y_test = mnist.test.images, mnist.test.labels\n\nassert(len(X_train) == len(y_train))\nassert(len(X_validation) == len(y_validation))\nassert(len(X_test) == len(y_test))\n\nprint()\nprint(\"Image Shape: {}\".format(X_train[0].shape))\nprint()\nprint(\"Training Set: {} samples\".format(len(X_train)))\nprint(\"Validation Set: {} samples\".format(len(X_validation)))\nprint(\"Test Set: {} samples\".format(len(X_test)))",
"_____no_output_____"
]
],
[
[
"The MNIST data that TensorFlow pre-loads comes as 28x28x1 images.\n\nHowever, the LeNet architecture only accepts 32x32xC images, where C is the number of color channels.\n\nIn order to reformat the MNIST data into a shape that LeNet will accept, we pad the data with two rows of zeros on the top and bottom, and two columns of zeros on the left and right (28+2+2 = 32).\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\n# Pad images with 0s\nX_train = np.pad(X_train, ((0,0),(2,2),(2,2),(0,0)), 'constant')\nX_validation = np.pad(X_validation, ((0,0),(2,2),(2,2),(0,0)), 'constant')\nX_test = np.pad(X_test, ((0,0),(2,2),(2,2),(0,0)), 'constant')\n \nprint(\"Updated Image Shape: {}\".format(X_train[0].shape))",
"_____no_output_____"
]
],
[
[
"## Visualize Data\n\nView a sample from the dataset.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"import random\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nindex = random.randint(0, len(X_train))\nimage = X_train[index].squeeze()\n\nplt.figure(figsize=(1,1))\nplt.imshow(image, cmap=\"gray\")\nprint(y_train[index])",
"_____no_output_____"
]
],
[
[
"## Preprocess Data\n\nShuffle the training data.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"from sklearn.utils import shuffle\n\nX_train, y_train = shuffle(X_train, y_train)",
"_____no_output_____"
]
],
[
[
"## Setup TensorFlow\nThe `EPOCH` and `BATCH_SIZE` values affect the training speed and model accuracy.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\n\nEPOCHS = 10\nBATCH_SIZE = 128",
"_____no_output_____"
]
],
[
[
"## SOLUTION: Implement LeNet-5\nImplement the [LeNet-5](http://yann.lecun.com/exdb/lenet/) neural network architecture.\n\nThis is the only cell you need to edit.\n### Input\nThe LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case.\n\n### Architecture\n**Layer 1: Convolutional.** The output shape should be 28x28x6.\n\n**Activation.** Your choice of activation function.\n\n**Pooling.** The output shape should be 14x14x6.\n\n**Layer 2: Convolutional.** The output shape should be 10x10x16.\n\n**Activation.** Your choice of activation function.\n\n**Pooling.** The output shape should be 5x5x16.\n\n**Flatten.** Flatten the output shape of the final pooling layer such that it's 1D instead of 3D. The easiest way to do is by using `tf.contrib.layers.flatten`, which is already imported for you.\n\n**Layer 3: Fully Connected.** This should have 120 outputs.\n\n**Activation.** Your choice of activation function.\n\n**Layer 4: Fully Connected.** This should have 84 outputs.\n\n**Activation.** Your choice of activation function.\n\n**Layer 5: Fully Connected (Logits).** This should have 10 outputs.\n\n### Output\nReturn the result of the 3rd fully connected layer.",
"_____no_output_____"
]
],
[
[
"from tensorflow.contrib.layers import flatten\n\ndef LeNet(x): \n # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer\n mu = 0\n sigma = 0.1\n \n # Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.\n conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean = mu, stddev = sigma))\n conv1_b = tf.Variable(tf.zeros(6))\n conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b\n\n # Activation.\n conv1 = tf.nn.relu(conv1)\n\n # Pooling. Input = 28x28x6. Output = 14x14x6.\n conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # Layer 2: Convolutional. Output = 10x10x16.\n conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))\n conv2_b = tf.Variable(tf.zeros(16))\n conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b\n \n # Activation.\n conv2 = tf.nn.relu(conv2)\n\n # Pooling. Input = 10x10x16. Output = 5x5x16.\n conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # Flatten. Input = 5x5x16. Output = 400.\n fc0 = flatten(conv2)\n \n # Layer 3: Fully Connected. Input = 400. Output = 120.\n fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))\n fc1_b = tf.Variable(tf.zeros(120))\n fc1 = tf.matmul(fc0, fc1_W) + fc1_b\n \n # Activation.\n fc1 = tf.nn.relu(fc1)\n\n # Layer 4: Fully Connected. Input = 120. Output = 84.\n fc2_W = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))\n fc2_b = tf.Variable(tf.zeros(84))\n fc2 = tf.matmul(fc1, fc2_W) + fc2_b\n \n # Activation.\n fc2 = tf.nn.relu(fc2)\n\n # Layer 5: Fully Connected. Input = 84. Output = 10.\n fc3_W = tf.Variable(tf.truncated_normal(shape=(84, 10), mean = mu, stddev = sigma))\n fc3_b = tf.Variable(tf.zeros(10))\n logits = tf.matmul(fc2, fc3_W) + fc3_b\n \n return logits",
"_____no_output_____"
]
],
[
[
"## Features and Labels\nTrain LeNet to classify [MNIST](http://yann.lecun.com/exdb/mnist/) data.\n\n`x` is a placeholder for a batch of input images.\n`y` is a placeholder for a batch of output labels.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"x = tf.placeholder(tf.float32, (None, 32, 32, 1))\ny = tf.placeholder(tf.int32, (None))\none_hot_y = tf.one_hot(y, 10)",
"_____no_output_____"
]
],
[
[
"## Training Pipeline\nCreate a training pipeline that uses the model to classify MNIST data.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"rate = 0.001\n\nlogits = LeNet(x)\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)\nloss_operation = tf.reduce_mean(cross_entropy)\noptimizer = tf.train.AdamOptimizer(learning_rate = rate)\ntraining_operation = optimizer.minimize(loss_operation)",
"_____no_output_____"
]
],
[
[
"## Model Evaluation\nEvaluate how well the loss and accuracy of the model for a given dataset.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))\naccuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nsaver = tf.train.Saver()\n\ndef evaluate(X_data, y_data):\n num_examples = len(X_data)\n total_accuracy = 0\n sess = tf.get_default_session()\n for offset in range(0, num_examples, BATCH_SIZE):\n batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]\n accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})\n total_accuracy += (accuracy * len(batch_x))\n return total_accuracy / num_examples",
"_____no_output_____"
]
],
[
[
"## Train the Model\nRun the training data through the training pipeline to train the model.\n\nBefore each epoch, shuffle the training set.\n\nAfter each epoch, measure the loss and accuracy of the validation set.\n\nSave the model after training.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n num_examples = len(X_train)\n \n print(\"Training...\")\n print()\n for i in range(EPOCHS):\n X_train, y_train = shuffle(X_train, y_train)\n for offset in range(0, num_examples, BATCH_SIZE):\n end = offset + BATCH_SIZE\n batch_x, batch_y = X_train[offset:end], y_train[offset:end]\n sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})\n \n validation_accuracy = evaluate(X_validation, y_validation)\n print(\"EPOCH {} ...\".format(i+1))\n print(\"Validation Accuracy = {:.3f}\".format(validation_accuracy))\n print()\n \n saver.save(sess, './lenet')\n print(\"Model saved\")",
"_____no_output_____"
]
],
[
[
"## Evaluate the Model\nOnce you are completely satisfied with your model, evaluate the performance of the model on the test set.\n\nBe sure to only do this once!\n\nIf you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model on the test set again, that would invalidate your test results. You wouldn't get a true measure of how well your model would perform against real data.\n\nYou do not need to modify this section.",
"_____no_output_____"
]
],
[
[
"with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n test_accuracy = evaluate(X_test, y_test)\n print(\"Test Accuracy = {:.3f}\".format(test_accuracy))",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a350d4c8704e193c0c0aa3074441d405c624067
| 157,370 |
ipynb
|
Jupyter Notebook
|
Regression/Support Vector Machine/SVR_Scale_QuantileTransformer.ipynb
|
shreepad-nade/ds-seed
|
93ddd3b73541f436b6832b94ca09f50872dfaf10
|
[
"Apache-2.0"
] | 53 |
2021-08-28T07:41:49.000Z
|
2022-03-09T02:20:17.000Z
|
Regression/Support Vector Machine/SVR_Scale_QuantileTransformer.ipynb
|
shreepad-nade/ds-seed
|
93ddd3b73541f436b6832b94ca09f50872dfaf10
|
[
"Apache-2.0"
] | 142 |
2021-07-27T07:23:10.000Z
|
2021-08-25T14:57:24.000Z
|
Regression/Support Vector Machine/SVR_Scale_QuantileTransformer.ipynb
|
shreepad-nade/ds-seed
|
93ddd3b73541f436b6832b94ca09f50872dfaf10
|
[
"Apache-2.0"
] | 38 |
2021-07-27T04:54:08.000Z
|
2021-08-23T02:27:20.000Z
| 194.04439 | 71,022 | 0.87265 |
[
[
[
"# SVR with Scale & Quantile Transformer",
"_____no_output_____"
],
[
"This Code template is for regression analysis using the SVR Regressor where rescaling method used is Scale and feature transformation is done via Quantile Transformer.",
"_____no_output_____"
],
[
"### Required Packages",
"_____no_output_____"
]
],
[
[
"import warnings\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport seaborn as se\nfrom sklearn.model_selection import train_test_split \nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import QuantileTransformer, scale\nfrom sklearn.svm import SVR \nfrom sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error \nwarnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"### Initialization\nFilepath of CSV file",
"_____no_output_____"
]
],
[
[
"#filepath\nfile_path= \"\"",
"_____no_output_____"
]
],
[
[
"List of features which are required for model training.",
"_____no_output_____"
]
],
[
[
"#x_values\nfeatures=[]",
"_____no_output_____"
]
],
[
[
"Target feature for prediction.",
"_____no_output_____"
]
],
[
[
"#y_value\ntarget=''",
"_____no_output_____"
]
],
[
[
"### Data Fetching\n\nPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.\n\nWe will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.",
"_____no_output_____"
]
],
[
[
"df=pd.read_csv(file_path)\ndf.head()",
"_____no_output_____"
]
],
[
[
"### Feature Selections\n\nIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.\n\nWe will assign all the required input features to X and target/outcome to Y.",
"_____no_output_____"
]
],
[
[
"X=df[features]\nY=df[target]",
"_____no_output_____"
]
],
[
[
"### Data Preprocessing\n\nSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes.\n",
"_____no_output_____"
]
],
[
[
"def NullClearner(df):\n if(isinstance(df, pd.Series) and (df.dtype in [\"float64\",\"int64\"])):\n df.fillna(df.mean(),inplace=True)\n return df\n elif(isinstance(df, pd.Series)):\n df.fillna(df.mode()[0],inplace=True)\n return df\n else:return df\ndef EncodeX(df):\n return pd.get_dummies(df)",
"_____no_output_____"
]
],
[
[
"Calling preprocessing functions on the feature and target set.\n",
"_____no_output_____"
]
],
[
[
"x=X.columns.to_list()\nfor i in x:\n X[i]=NullClearner(X[i])\nX=EncodeX(X)\nY=NullClearner(Y)\nX.head()",
"_____no_output_____"
]
],
[
[
"#### Correlation Map\n\nIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns.",
"_____no_output_____"
]
],
[
[
"f,ax = plt.subplots(figsize=(18, 18))\nmatrix = np.triu(X.corr())\nse.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Data Splitting\n\nThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data.",
"_____no_output_____"
]
],
[
[
"x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=123)",
"_____no_output_____"
]
],
[
[
"###Data Rescaling\n####Scale\n\nIt is a step of Data Pre Processing which is applied to independent variables or features of data. It basically helps to normalise the data within a particular range. Sometimes, it also helps in speeding up the calculations in an algorithm.",
"_____no_output_____"
]
],
[
[
"x_train =scale(x_train)\nx_test = scale(x_test)",
"_____no_output_____"
]
],
[
[
"### Quantile Transformer\n\nThis method transforms the features to follow a uniform or a normal distribution. Therefore, for a given feature, this transformation tends to spread out the most frequent values. It also reduces the impact of (marginal) outliers: this is therefore a robust preprocessing scheme.\n\nTransform features using quantiles information.",
"_____no_output_____"
],
[
"####Epsilon-Support Vector Regression.\n\nSupport vector machines (SVMs) are a set of supervised learning methods used for classification, regression and outliers detection.\n\nA Support Vector Machine is a discriminative classifier formally defined by a separating hyperplane. In other terms, for a given known/labelled data points, the SVM outputs an appropriate hyperplane that classifies the inputted new cases based on the hyperplane. In 2-Dimensional space, this hyperplane is a line separating a plane into two segments where each class or group occupied on either side.\n\nHere we will use SVR, the svr implementation is based on libsvm. The fit time scales at least quadratically with the number of samples and maybe impractical beyond tens of thousands of samples.\n\n#### Parameters:\n\n**kernel: {‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’** ->\nSpecifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to precompute the kernel matrix.\n\n**degree: int, default=3** ->\nDegree of the polynomial kernel function (‘poly’). Ignored by all other kernels.\n\n**gamma: {‘scale’, ‘auto’} or float, default=’scale’** ->\nKernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’.\n\n**coef0: float, default=0.0** ->\nIndependent term in kernel function. It is only significant in ‘poly’ and ‘sigmoid’.\n\n**tol: float, default=1e-3** ->\nTolerance for stopping criterion.\n\n**C: float, default=1.0** ->\nRegularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive. The penalty is a squared l2 penalty.\n\n**epsilon: float, default=0.1** ->\nEpsilon in the epsilon-SVR model. It specifies the epsilon-tube within which no penalty is associated in the training loss function with points predicted within a distance epsilon from the actual value.\n\n**shrinking: bool, default=True** ->\nWhether to use the shrinking heuristic. See the User Guide.\n\n**cache_size: float, default=200** ->\nSpecify the size of the kernel cache (in MB).\n\n**verbose: bool, default=False** ->\nEnable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context.\n\n**max_iter: int, default=-1** ->\nHard limit on iterations within solver, or -1 for no limit.",
"_____no_output_____"
]
],
[
[
"model=make_pipeline(QuantileTransformer(), SVR(kernel='poly', degree=13))\nmodel.fit(x_train, y_train)",
"_____no_output_____"
]
],
[
[
"#### Model Accuracy\n\nWe will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model.\n\nscore: The score function returns the coefficient of determination R2 of the prediction.\n\n",
"_____no_output_____"
]
],
[
[
"print(\"Accuracy score {:.2f} %\\n\".format(model.score(x_test,y_test)*100))",
"Accuracy score 31.40 %\n\n"
]
],
[
[
"> **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. \n\n> **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our model. \n\n> **mse**: The **mean squared error** function squares the error(penalizes the model for large errors) by our model. ",
"_____no_output_____"
]
],
[
[
"y_pred=model.predict(x_test)\nprint(\"R2 Score: {:.2f} %\".format(r2_score(y_test,y_pred)*100))\nprint(\"Mean Absolute Error {:.2f}\".format(mean_absolute_error(y_test,y_pred)))\nprint(\"Mean Squared Error {:.2f}\".format(mean_squared_error(y_test,y_pred)))",
"R2 Score: 31.40 %\nMean Absolute Error 5989.05\nMean Squared Error 104883016.67\n"
]
],
[
[
"#### Prediction Plot\n\nFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.\nFor the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis.",
"_____no_output_____"
]
],
[
[
"n=len(x_test) if len(x_test)<20 else 20\nplt.figure(figsize=(14,10))\nplt.plot(range(n),y_test[0:n], color = \"green\")\nplt.plot(range(n),model.predict(x_test[0:n]), color = \"red\")\nplt.legend([\"Actual\",\"prediction\"]) \nplt.title(\"Predicted vs True Value\")\nplt.xlabel(\"Record number\")\nplt.ylabel(target)\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### Creator: Ayush Gupta , Github: [Profile](https://github.com/guptayush179)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"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"
]
] |
4a351d373c5bb263f5784bf6fa677c3e30608a53
| 8,699 |
ipynb
|
Jupyter Notebook
|
torchmm/test.ipynb
|
pytorch-duo/torchmm
|
0e44f8599d26a29c345e7cc85e2885813346dc0b
|
[
"MIT"
] | null | null | null |
torchmm/test.ipynb
|
pytorch-duo/torchmm
|
0e44f8599d26a29c345e7cc85e2885813346dc0b
|
[
"MIT"
] | 3 |
2021-06-08T22:22:40.000Z
|
2022-03-12T00:47:40.000Z
|
torchmm/test.ipynb
|
pytorch-duo/torchmm
|
0e44f8599d26a29c345e7cc85e2885813346dc0b
|
[
"MIT"
] | null | null | null | 35.798354 | 381 | 0.611909 |
[
[
[
"from Datasets import TextDataset\nfrom transformers import AutoTokenizer, BertModel\nfrom datasets import load_dataset, list_datasets",
"_____no_output_____"
],
[
"BertModel?",
"\u001b[0;31mInit signature:\u001b[0m \u001b[0mBertModel\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mconfig\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0madd_pooling_layer\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;31mDocstring:\u001b[0m \nThe bare Bert Model transformer outputting raw hidden-states without any specific head on top.\n\nThis model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic\nmethods the library implements for all its model (such as downloading or saving, resizing the input embeddings,\npruning heads etc.)\n\nThis model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__ subclass.\nUse it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general\nusage and behavior.\n\nParameters:\n config (:class:`~transformers.BertConfig`): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the configuration.\n Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.\n\n\nThe model can behave as an encoder (with only self-attention) as well\nas a decoder, in which case a layer of cross-attention is added between\nthe self-attention layers, following the architecture described in `Attention is all you need\n<https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones,\nAidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.\n\nTo behave as an decoder the model needs to be initialized with the\n:obj:`is_decoder` argument of the configuration set to :obj:`True`.\nTo be used in a Seq2Seq model, the model needs to initialized with both :obj:`is_decoder`\nargument and :obj:`add_cross_attention` set to :obj:`True`; an\n:obj:`encoder_hidden_states` is then expected as an input to the forward pass.\n\u001b[0;31mInit docstring:\u001b[0m Initializes internal Module state, shared by both nn.Module and ScriptModule.\n\u001b[0;31mFile:\u001b[0m ~/miniconda3/lib/python3.7/site-packages/transformers/modeling_bert.py\n\u001b[0;31mType:\u001b[0m type\n\u001b[0;31mSubclasses:\u001b[0m \n"
],
[
"tokenizer = AutoTokenizer.from_pretrained(\"bert-base-cased\")",
"_____no_output_____"
],
[
"data = load_dataset(\"ag_news\")",
"Using custom data configuration default\nReusing dataset ag_news (/home/macab/.cache/huggingface/datasets/ag_news/default/0.0.0/fb5c5e74a110037311ef5e904583ce9f8b9fbc1354290f97b4929f01b3f48b1a)\n"
],
[
"datasets = TextDataset?",
"\u001b[0;31mType:\u001b[0m module\n\u001b[0;31mString form:\u001b[0m <module 'Datasets.TextDataset' from '/home/macab/research/torchmm/torchmm/Datasets/TextDataset.py'>\n\u001b[0;31mFile:\u001b[0m ~/research/torchmm/torchmm/Datasets/TextDataset.py\n\u001b[0;31mDocstring:\u001b[0m <no docstring>\n"
],
[
"AutoTokenizer?",
"\u001b[0;31mInit signature:\u001b[0m \u001b[0mAutoTokenizer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;31mDocstring:\u001b[0m \nThis is a generic tokenizer class that will be instantiated as one of the tokenizer classes of the library\nwhen created with the :meth:`AutoTokenizer.from_pretrained` class method.\n\nThis class cannot be instantiated directly using ``__init__()`` (throws an error).\n\u001b[0;31mFile:\u001b[0m ~/miniconda3/lib/python3.7/site-packages/transformers/tokenization_auto.py\n\u001b[0;31mType:\u001b[0m type\n\u001b[0;31mSubclasses:\u001b[0m \n"
],
[
"class Demo:\n '''demo class'''\n\n def __init__(self):\n pass\n ",
"_____no_output_____"
],
[
"Demo?",
"\u001b[0;31mInit signature:\u001b[0m \u001b[0mDemo\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;31mDocstring:\u001b[0m demo class\n\u001b[0;31mType:\u001b[0m type\n\u001b[0;31mSubclasses:\u001b[0m \n"
],
[
"import torch",
"_____no_output_____"
],
[
"torch.split?",
"\u001b[0;31mSignature:\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msplit\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtensor\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msplit_size_or_sections\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdim\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;31mDocstring:\u001b[0m\nSplits the tensor into chunks. Each chunk is a view of the original tensor.\n\nIf :attr:`split_size_or_sections` is an integer type, then :attr:`tensor` will\nbe split into equally sized chunks (if possible). Last chunk will be smaller if\nthe tensor size along the given dimension :attr:`dim` is not divisible by\n:attr:`split_size`.\n\nIf :attr:`split_size_or_sections` is a list, then :attr:`tensor` will be split\ninto ``len(split_size_or_sections)`` chunks with sizes in :attr:`dim` according\nto :attr:`split_size_or_sections`.\n\nArguments:\n tensor (Tensor): tensor to split.\n split_size_or_sections (int) or (list(int)): size of a single chunk or\n list of sizes for each chunk\n dim (int): dimension along which to split the tensor.\n\u001b[0;31mFile:\u001b[0m ~/miniconda3/lib/python3.7/site-packages/torch/functional.py\n\u001b[0;31mType:\u001b[0m function\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a351efe74940f78bf5eb93d54563b04962a4214
| 32,363 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/climate_starter-checkpoint.ipynb
|
spearjen/sqlalch-challenge
|
acf8ca43201392ddb3487a353ea55fdfc125af24
|
[
"ADSL"
] | 1 |
2020-08-24T15:29:29.000Z
|
2020-08-24T15:29:29.000Z
|
.ipynb_checkpoints/climate_starter-checkpoint.ipynb
|
spearjen/sqlalch-challenge
|
acf8ca43201392ddb3487a353ea55fdfc125af24
|
[
"ADSL"
] | null | null | null |
.ipynb_checkpoints/climate_starter-checkpoint.ipynb
|
spearjen/sqlalch-challenge
|
acf8ca43201392ddb3487a353ea55fdfc125af24
|
[
"ADSL"
] | null | null | null | 37.675204 | 1,995 | 0.551154 |
[
[
[
"%matplotlib inline\nfrom matplotlib import style\nstyle.use('fivethirtyeight')\nimport matplotlib.pyplot as plt\nfrom datetime import datetime",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"import datetime as dt",
"_____no_output_____"
]
],
[
[
"# Reflect Tables into SQLAlchemy ORM",
"_____no_output_____"
]
],
[
[
"# Python SQL toolkit and Object Relational Mapper\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func, MetaData, Table, Column, ForeignKey, Integer, String, Float, DateTime, inspect, distinct, desc, and_",
"_____no_output_____"
],
[
"# Create Database Connection\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\nBase.metadata.create_all(engine)",
"_____no_output_____"
],
[
"# reflect an existing database into a new model\nBase=automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n# save refernece to the table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\nsession = Session(engine)",
"_____no_output_____"
],
[
"# We can view all of the classes that automap found\nBase.classes.keys()",
"_____no_output_____"
],
[
"# Save references to each table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station",
"_____no_output_____"
],
[
"# Create our session (link) from Python to the DB\nsession = Session(bind=engine)",
"_____no_output_____"
],
[
"inspector = inspect(engine)\ncolumns = inspector.get_columns('measurement')\nfor c in columns:\n print(c['name'], c[\"type\"])",
"id INTEGER\nstation TEXT\ndate TEXT\nprcp FLOAT\ntobs FLOAT\n"
],
[
"engine.execute('SELECT * FROM measurement LIMIT 5').fetchall()",
"_____no_output_____"
],
[
"columns = inspector.get_columns('station')\nfor c in columns:\n print(c['name'], c[\"type\"])",
"id INTEGER\nstation TEXT\nname TEXT\nlatitude FLOAT\nlongitude FLOAT\nelevation FLOAT\n"
],
[
"engine.execute('SELECT * FROM station LIMIT 5').fetchall()",
"_____no_output_____"
]
],
[
[
"# Exploratory Climate Analysis",
"_____no_output_____"
]
],
[
[
"# Design a query to retrieve the last 12 months of precipitation data and plot the results\n\n# Calculate the date 1 year ago from the last data point in the database\nend_date, = session.query(Measurement.date).order_by(Measurement.date.desc()).first()\nbegin_date=dt.datetime.strptime(end_date, '%Y-%m-%d')-dt.timedelta(days=365)\nend_date = dt.datetime.strptime(end_date, '%Y-%m-%d')\nprint(end_date,begin_date)\n\n# Perform a query to retrieve the data and precipitation scores\n# data = session.query(Measurement.id,Measurement.station,Measurement.date, Measurement.prcp, Measurement.tobs)\\\n# .filter(and_(Measurement.date>=begin_date, Measurement.date<=end_date)).all()\ndata = session.query(Measurement.id,Measurement.station,Measurement.date, Measurement.prcp, Measurement.tobs)\\\n.filter(Measurement.date>=begin_date).filter(Measurement.date<=end_date).all()\n\n# Save the query results as a Pandas DataFrame and set the index to the date column\n# Sort the dataframe by date\nprcp_data = pd.DataFrame(data).set_index('date').sort_values(by='date', ascending=False)\n\n# Use Pandas Plotting with Matplotlib to plot the data\nprcp_data",
"2017-08-23 00:00:00 2016-08-23 00:00:00\n"
],
[
"# Use Pandas to calcualte the summary statistics for the precipitation data\nprcp_data[\"prcp\"].agg([\"mean\",\"median\", \"sum\", \"count\", \"max\", \"min\", \"std\", \"var\"])",
"_____no_output_____"
],
[
"# Design a query to show how many stations are available in this dataset.\nstations_lastyr = prcp_data.station.nunique()\nstations, = session.query(func.count(distinct(Measurement.station))).order_by\n(f'There are {stations_lastyr} unique weather stations with measurments taken in the last year of data. There are {stations} unique weather stations in the entire dataset.')",
"_____no_output_____"
],
[
"# What are the most active stations? (i.e. what stations have the most rows)?\n# List the stations and the counts in descending order.\nactive_all = session.query(Measurement.station, func.count(Measurement.station)).group_by(Measurement.station) \\\n.order_by(desc(func.count(Measurement.station))).all()\nactive = prcp_data[\"station\"].value_counts() #Returns descending by default\nactive = pd.DataFrame(active)\n# prcp_data[\"station\"].value_counts(normalize=True) #returns percentages of whole instead of count!\nprint('This is the dataset filtered for the last year of data.')\nactive",
"This is the dataset filtered for the last year of data.\n"
],
[
"print('This is the whole dataset.')\nactive_all = [[ i for i, j in active_all ], \n [ j for i, j in active_all ]] \n\nactive_all",
"This is the whole dataset.\n"
],
[
"# Using the station id from the previous query, calculate the lowest temperature recorded, \n# highest temperature recorded, and average temperature of the most active station?\nmost_active = active.index[0]\nactive_agg = prcp_data.loc[prcp_data[\"station\"] == most_active]\nactive_agg[\"tobs\"].agg([\"mean\", \"max\", \"min\"])",
"_____no_output_____"
],
[
"most_active_all = ",
"_____no_output_____"
],
[
"# Choose the station with the highest number of temperature observations.\n# Query the last 12 months of temperature observation data for this station and plot the results as a histogram\n",
"_____no_output_____"
]
],
[
[
"## Bonus Challenge Assignment",
"_____no_output_____"
]
],
[
[
"# This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d' \n# and return the minimum, average, and maximum temperatures for that range of dates\ndef calc_temps(start_date, end_date):\n \"\"\"TMIN, TAVG, and TMAX for a list of dates.\n \n Args:\n start_date (string): A date string in the format %Y-%m-%d\n end_date (string): A date string in the format %Y-%m-%d\n \n Returns:\n TMIN, TAVE, and TMAX\n \"\"\"\n \n return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()\n\n# function usage example\nprint(calc_temps('2012-02-28', '2012-03-05'))",
"_____no_output_____"
],
[
"# Use your previous function `calc_temps` to calculate the tmin, tavg, and tmax \n# for your trip using the previous year's data for those same dates.\n",
"_____no_output_____"
],
[
"# Plot the results from your previous query as a bar chart. \n# Use \"Trip Avg Temp\" as your Title\n# Use the average temperature for the y value\n# Use the peak-to-peak (tmax-tmin) value as the y error bar (yerr)\n",
"_____no_output_____"
],
[
"# Calculate the total amount of rainfall per weather station for your trip dates using the previous year's matching dates.\n# Sort this in descending order by precipitation amount and list the station, name, latitude, longitude, and elevation\n\n",
"_____no_output_____"
],
[
"# Create a query that will calculate the daily normals \n# (i.e. the averages for tmin, tmax, and tavg for all historic data matching a specific month and day)\n\ndef daily_normals(date):\n \"\"\"Daily Normals.\n \n Args:\n date (str): A date string in the format '%m-%d'\n \n Returns:\n A list of tuples containing the daily normals, tmin, tavg, and tmax\n \n \"\"\"\n \n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n return session.query(*sel).filter(func.strftime(\"%m-%d\", Measurement.date) == date).all()\n \ndaily_normals(\"01-01\")",
"_____no_output_____"
],
[
"# calculate the daily normals for your trip\n# push each tuple of calculations into a list called `normals`\n\n# Set the start and end date of the trip\n\n# Use the start and end date to create a range of dates\n\n# Stip off the year and save a list of %m-%d strings\n\n# Loop through the list of %m-%d strings and calculate the normals for each date\n",
"_____no_output_____"
],
[
"# Load the previous query results into a Pandas DataFrame and add the `trip_dates` range as the `date` index\n",
"_____no_output_____"
],
[
"# Plot the daily normals as an area plot with `stacked=False`\n",
"_____no_output_____"
],
[
"# class Measurement_two(Base):\n# __tablename__= \"measurement\"\n# id = Column(Integer, primary_key=True)\n# station = Column(String(200))\n# date = Column(DateTime)\n# prcp = Column(Float)\n# tobs = Column(Float)\n\n# class Station_two(Base):\n# __tablename__= \"station\"\n# id = Column(Integer, primary_key=True)\n# station = Column(String(200))\n# name = Column(String(200))\n# latitude = Column(Float)\n# longitude = Column(Float)\n# elevation = Column(Float)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a351f0c767bdf8aaeddcf05cf32e5ac2c0bfcbf
| 930 |
ipynb
|
Jupyter Notebook
|
content/lectures/lecture7/notebook/.ipynb_checkpoints/lecture7-checkpoint.ipynb
|
hopesummer/2020-AC295
|
6464dcb5b37a2c2e858fb6f76835aa608f2dae7f
|
[
"MIT"
] | 5 |
2020-03-27T00:22:43.000Z
|
2020-09-06T20:23:30.000Z
|
content/lectures/lecture7/notebook/.ipynb_checkpoints/lecture7-checkpoint.ipynb
|
hopesummer/2020-AC295
|
6464dcb5b37a2c2e858fb6f76835aa608f2dae7f
|
[
"MIT"
] | null | null | null |
content/lectures/lecture7/notebook/.ipynb_checkpoints/lecture7-checkpoint.ipynb
|
hopesummer/2020-AC295
|
6464dcb5b37a2c2e858fb6f76835aa608f2dae7f
|
[
"MIT"
] | 9 |
2020-02-18T22:17:17.000Z
|
2021-01-28T17:09:46.000Z
| 16.034483 | 34 | 0.484946 |
[
[
[
"import numpy as np",
"_____no_output_____"
],
[
"a = [1,2,3,5]\nsummation = np.sum(a)\nprint(summation)",
"11\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
4a353c608a6a8840082af2174f84ac07676f58ea
| 42,568 |
ipynb
|
Jupyter Notebook
|
Notebooks/Binomial_MGWR_module_GAM.ipynb
|
mehak-sachdeva/MGWR_book
|
d702a04c7e5f9101e0f04b6d84295bce86579059
|
[
"MIT-0"
] | 1 |
2021-01-21T08:29:53.000Z
|
2021-01-21T08:29:53.000Z
|
Notebooks/Binomial_MGWR_module_GAM.ipynb
|
TaylorOshan/MGWR_book
|
c59db902b34d625af4d0e1b90fbc95018a3de579
|
[
"MIT-0"
] | null | null | null |
Notebooks/Binomial_MGWR_module_GAM.ipynb
|
TaylorOshan/MGWR_book
|
c59db902b34d625af4d0e1b90fbc95018a3de579
|
[
"MIT-0"
] | 1 |
2021-06-07T20:57:56.000Z
|
2021-06-07T20:57:56.000Z
| 63.724551 | 14,184 | 0.805981 |
[
[
[
"import sys\nsys.path.append(\"/Users/msachde1/Downloads/Research/Development/mgwr/\")",
"_____no_output_____"
],
[
"import warnings\nwarnings.filterwarnings(\"ignore\")",
"_____no_output_____"
],
[
"from mgwr.gwr import GWR\nimport pandas as pd\nimport numpy as np\nfrom spglm.family import Gaussian, Binomial, Poisson\nfrom mgwr.gwr import MGWR\nfrom mgwr.sel_bw import Sel_BW\nimport multiprocessing as mp\npool = mp.Pool()\nfrom scipy import linalg\nimport numpy.linalg as la\nfrom scipy import sparse as sp\nfrom scipy.sparse import linalg as spla\nfrom spreg.utils import spdot, spmultiply\nfrom scipy import special\nimport libpysal as ps\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom copy import deepcopy\nimport copy\nfrom collections import namedtuple",
"_____no_output_____"
]
],
[
[
"<img src=\"image.png\">",
"_____no_output_____"
],
[
"### IWLS convergence loop",
"_____no_output_____"
]
],
[
[
"data_p = pd.read_csv(\"C:/Users/msachde1/Downloads/logistic_mgwr_data/landslides.csv\") \ncoords = list(zip(data_p['X'],data_p['Y']))\ny = np.array(data_p['Landslid']).reshape((-1,1)) \nelev = np.array(data_p['Elev']).reshape((-1,1))\nslope = np.array(data_p['Slope']).reshape((-1,1))\nSinAspct = np.array(data_p['SinAspct']).reshape(-1,1)\nCosAspct = np.array(data_p['CosAspct']).reshape(-1,1)\nX = np.hstack([elev,slope,SinAspct,CosAspct])\nx = CosAspct\n\nX_std = (X-X.mean(axis=0))/X.std(axis=0)\nx_std = (x-x.mean(axis=0))/x.std(axis=0)\ny_std = (y-y.mean(axis=0))/y.std(axis=0)",
"_____no_output_____"
]
],
[
[
"### Initialization with GWPR",
"_____no_output_____"
]
],
[
[
"sel=Sel_BW(coords,y,x,family=Binomial(),constant=False)\nbw_in=sel.search()\ndef gwr_func(y,X,bw):\n return GWR(coords,y,X,bw,family=Binomial(),fixed=False,kernel='bisquare',constant=False).fit()\noptim_model = gwr_func(y=y,X=x,bw=bw_in)\nom_p=optim_model.params",
"_____no_output_____"
],
[
"bw_in",
"_____no_output_____"
]
],
[
[
"### Starting values",
"_____no_output_____"
]
],
[
[
"n_iter=0\nn=x.shape[0]",
"_____no_output_____"
],
[
"diff = 1.0e+06\ntol = 1.0e-06\nmax_iter=200\nbetas=om_p",
"_____no_output_____"
],
[
"XB =np.sum( np.multiply(optim_model.params,optim_model.X),axis=1)\nmu = 1 / ( 1 + np.exp (-1 * XB))\nni_old = np.log((mu)/(1-mu))",
"_____no_output_____"
],
[
"while diff> tol and n_iter < max_iter:\n n_iter +=1\n w = mu*(1-mu)\n z = (ni_old + ((optim_model.y - mu)/mu*(1-mu))).reshape(-1,1)\n\n wx = spmultiply(x.reshape(-1),w.reshape(-1),array_out=False)\n \n x_std=((wx-wx.mean(axis=0))/wx.std(axis=0)).reshape(-1,1)\n print(x_std.shape)\n \n selector=Sel_BW(coords,z,x_std,multi=True,constant=False)\n selector.search(pool=pool)\n print(selector.bw[0])\n mgwr_model=MGWR(coords,z,x_std,selector,family=Gaussian(),constant=False).fit()\n \n n_betas=mgwr_model.params \n\n XB =np.sum( np.multiply(n_betas,mgwr_model.X),axis=1)\n mu = 1 / ( 1 + np.exp (-1 * XB))\n ni_old = np.log((mu)/(1-mu))\n\n \n diff=min(min(abs(betas-n_betas).reshape(1,-1).tolist()))\n print(\"diff = \"+str(diff))\n betas = n_betas\n\n#print (betas, w, z, n_iter)",
"(239, 1)\n[43.]\n"
],
[
"bw=Sel_BW(coords,y,x_std,family=Binomial(),constant=False)",
"_____no_output_____"
],
[
"bw=bw.search()",
"_____no_output_____"
],
[
"bw",
"_____no_output_____"
],
[
"gwr_mod = GWR(coords,y,x_std,bw,family=Binomial(),constant=False).fit()",
"_____no_output_____"
],
[
"gwr_mod.aic",
"_____no_output_____"
],
[
"sns.distplot(z)",
"_____no_output_____"
],
[
"sns.distplot(x_std)",
"_____no_output_____"
],
[
"mgwr_model.aic",
"_____no_output_____"
],
[
"optim_model.aic",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a355762ece7b6f1086e8b2c919cac89ea45fdcf
| 96,233 |
ipynb
|
Jupyter Notebook
|
ComputerScience/EthereumPricePrediction/EthereumPricePrediction.ipynb
|
vladiant/AlgorithmicTrading
|
117f47ca2c69a9d6fdba57bb895df10633d5c13d
|
[
"MIT"
] | null | null | null |
ComputerScience/EthereumPricePrediction/EthereumPricePrediction.ipynb
|
vladiant/AlgorithmicTrading
|
117f47ca2c69a9d6fdba57bb895df10633d5c13d
|
[
"MIT"
] | null | null | null |
ComputerScience/EthereumPricePrediction/EthereumPricePrediction.ipynb
|
vladiant/AlgorithmicTrading
|
117f47ca2c69a9d6fdba57bb895df10633d5c13d
|
[
"MIT"
] | null | null | null | 107.522905 | 69,692 | 0.815573 |
[
[
[
"# Ethereum Price Prediction",
"_____no_output_____"
],
[
"Based on [Ethereum (ETH) Price Prediction using Machine Learning (SVR) & Python](https://www.youtube.com/watch?v=HiDEAWdAif0) from [Computer Science](https://www.youtube.com/channel/UCbmb5IoBtHZTpYZCDBOC1CA)",
"_____no_output_____"
],
[
"**Disclaimer:** _Investing in the stock market involves risk and can lead to monetary loss. This material is purely for educational purposes and should not be taken as professional investment advice. Invest at your own discretion._",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nfrom sklearn.svm import SVR\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"plt.style.use('fivethirtyeight')",
"_____no_output_____"
]
],
[
[
"Load the Bitcoin data",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(\"ETH.csv\")",
"_____no_output_____"
]
],
[
[
"Set the date as index",
"_____no_output_____"
]
],
[
[
"df = df.set_index(pd.DatetimeIndex(df['Date']))",
"_____no_output_____"
]
],
[
[
"Show the data",
"_____no_output_____"
]
],
[
[
"df",
"_____no_output_____"
],
[
"future_days = 5",
"_____no_output_____"
]
],
[
[
"Create a new column",
"_____no_output_____"
]
],
[
[
"df[str(future_days)+\"_Day_Price_Forecast\"] = df[['Close']].shift(-future_days)",
"_____no_output_____"
]
],
[
[
"Show the data",
"_____no_output_____"
]
],
[
[
"df[['Close', str(future_days)+\"_Day_Price_Forecast\"]]",
"_____no_output_____"
],
[
"X = np.array(df[['Close']])",
"_____no_output_____"
],
[
"X = X[:df.shape[0] - future_days]",
"_____no_output_____"
],
[
"X",
"_____no_output_____"
],
[
"y = np.array(df[str(future_days)+\"_Day_Price_Forecast\"])",
"_____no_output_____"
],
[
"y = y[:-future_days]",
"_____no_output_____"
],
[
"y",
"_____no_output_____"
]
],
[
[
"Split the data",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)",
"_____no_output_____"
],
[
"from sklearn.svm import SVR",
"_____no_output_____"
],
[
"svr_rbf = SVR(kernel='rbf', C=5e3, gamma=0.00001)",
"_____no_output_____"
],
[
"svr_rbf.fit(x_train, y_train)",
"_____no_output_____"
],
[
"svr_rbf_confidendce = svr_rbf.score(x_test, y_test)",
"_____no_output_____"
],
[
"svr_rbf_confidendce",
"_____no_output_____"
],
[
"svm_predicition = svr_rbf.predict(x_test)",
"_____no_output_____"
],
[
"svm_predicition",
"_____no_output_____"
],
[
"print(y_test)",
"[3484.72900391 2330.2109375 1492.60876465 1575.85314941 1746.61682129\n 3253.62939453 3902.64770508 1744.2434082 1677.84680176 1446.03369141\n 2211.62573242 2166.1887207 1262.2467041 1854.56433105 2237.13696289\n 1570.20397949 1935.60107422 1654.74157715 2088.57373047 2403.53515625\n 4168.70117188 1224.19714355 1416.0489502 2952.05615234 2534.48168945\n 2756.87695312]\n"
],
[
"plt.figure(figsize=(12,4))\nplt.plot(svm_predicition, label=\"Prediciton\", lw=2, alpha=0.7)\nplt.plot(y_test, label=\"Actual\", lw=2, alpha=0.7)\nplt.title(\"Prediction vs Actual\")\nplt.ylabel(\"Price in USD\")\nplt.xlabel(\"Time\")\nplt.legend()\nplt.xticks(rotation=45)\nplt.show()",
"_____no_output_____"
]
],
[
[
"**THIS IS NOT AN INVESTMENT ADVICE!**",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
4a355add942f1f7ac9c5d47ae5d838857cad3e1c
| 22,430 |
ipynb
|
Jupyter Notebook
|
HMM.ipynb
|
AjinkyaZ/Hidden-Markov-Models
|
79048f6b16f2ef9c98f2ba8e8d08d1b5ba8b6621
|
[
"MIT"
] | 2 |
2018-08-16T09:48:04.000Z
|
2020-09-23T02:16:58.000Z
|
HMM.ipynb
|
AjinkyaZ/Hidden-Markov-Models
|
79048f6b16f2ef9c98f2ba8e8d08d1b5ba8b6621
|
[
"MIT"
] | null | null | null |
HMM.ipynb
|
AjinkyaZ/Hidden-Markov-Models
|
79048f6b16f2ef9c98f2ba8e8d08d1b5ba8b6621
|
[
"MIT"
] | 1 |
2019-03-20T02:35:40.000Z
|
2019-03-20T02:35:40.000Z
| 42.241055 | 484 | 0.474944 |
[
[
[
"# Hidden Markov Models",
"_____no_output_____"
],
[
"### Problem Statement \nThe following problem is from the Udacity course on Artificial Intelligence (Thrun and Norvig), chapter 11 (HMMs and filters). It involves a simple scenario where a person's current emotional state is determined by the weather on that particular day. The task is to find the underlying hidden sequence of states (in this case, the weather), given only a set of observations (moods) and information about state/observation changes.",
"_____no_output_____"
]
],
[
[
"#import required libraries\nimport numpy as np\nimport warnings\nfrom pprint import pprint",
"_____no_output_____"
]
],
[
[
"$P(\\;Rainy\\;) = P(R_{0}) = 0.5$ (initial probabilites) \n$P(\\;Sunny\\;) = P(S_{0}) = 0.5$ \n\nThe chances of weather changing are given as follows: \nFor rainy weather, $P(S_{tomorrow}|R_{today}) = 0.4$, and $P(R_{tomorrow}|R_{today}) = 0.6$ \nFor sunny weather, $P(R_{tomorrow}|S_{today}) = 0.2$, therefore $P(S_{tomorrow}| S_{today}) = 0.8$ \nFor the purpose of formulating an HMM, we call the above ***Transition Probabilities.*** \n\nThe corresponding mood changes, given the weather are : \n$P(H|R) = 0.4$, therefore $P(G|R) = 0.6$ \n$P(H|S) = 0.9$, and $P(G|S) = 0.1$ \nWe call these ***Emission Probabilities***",
"_____no_output_____"
]
],
[
[
"S = np.array([0, 1]) # 0 Rainy, 1 Sunny\nS_names = ('Rainy', 'Sunny') \npi = np.array([0.5, 0.5]) # Initial Probabilities\nO = np.array(['Happy', 'Grumpy']) # Set of observations\nA = np.array([[0.6, 0.4], [0.2, 0.8]]) # {R:{R, S}, S:{R, S}} Transition Matrix\nB = np.array([[0.4, 0.6], [0.9, 0.1]]) # {R: {H, G}, S: {H, G}} Emission Matrix\nY = np.array([0, 0, 1]) # 0 Happy, 1 Grumpy -- Observation sequence",
"_____no_output_____"
]
],
[
[
"### Hidden Markov Models\n\n[HMMs](https://en.wikipedia.org/wiki/Hidden_Markov_model) are a class of probabilistic graphical models that can predict the sequence of states, given a sequence of observations that are dependent on those states, and when the states themselves are unobservable. HMMs have seen widespread success in a variety of applications, from Speech processing and Robotics to DNA Sequencing. An HMM operates according to a set of assumptions, which are : \n1. ** Markov Assumption ** \nCurrent state is dependent on only the previous state. \n2. ** Stationarity Assumption ** \nTransition probabilities are independent of time of transition. \n3. ** Independence Assumption ** \nEach observation depends solely on the current underlying state (which in turn depends on the previous one), and is independent of other observations. \n\nAn HMM is a **Generative model**, in that it attempts to find the probability of a set of observations being produced or *generated* by a class. The parameters that we pass to the HMM class, defined below, are: \n*O* = a set of observations \n*S* = a set of states \n*A* = transition probabilities, represented as a matrix \n*B* = emission probabilities, represented as a matrix \n*pi* = initial state probabilties \n*Y* = sequence observed ",
"_____no_output_____"
],
[
"### Viterbi Algorithm\n\nThe Viterbi algorithm is a Dynamic Programming algorithm for decoding the observation sequence to uncover the most probable state sequence. Given the required parameters, it starts from the initial state and uses the transition/emission information to calculate probabilities of subsequent states. Information from the previous step is passed along to the next, similar to a belief propagation mechanism (such as one used in the Forward-Backward algorithm explained later). \n\nWe store the results of each step in a table or matrix of size $k * t$, where k is the number of possible states, and t is the length of the observation sequence. The idea here is to find the path through possible states that has the maximum probability. Since initially we do not have a transition from state to state, we multiply the initial probabilities (from pi) and $P(\\;observation\\;|\\;state\\;)$ (from emission matrix B). \nEg. For the first day, we have the observation as Happy, so : \n$P(R_{1}) = P(R_{0}) * P(H|R_{1}) = 0.5 * 0.4 = 0.2$ \n$P(S_{1}) = P(S_{0}) * P(H|S_{1}) \\;= 0.5 * 0.9 = 0.45$ \nWe log both these results in the table, since we are starting from an initial state. For the following observations, however, each state has only its maximum probability of moving to the next state logged. \n\n#### On Day 2 : (observation - Happy) : \nIf current state = Rainy: \n$P(R_{1}) * P(R_{2}|R_{1}) = 0.20 * 0.6 = 0.12$ (given Rainy was previous state) \n$P(S_{1}) * P(R_{2}|S_{1}) = 0.45 * 0.2 = 0.09$ (Given Sunny was previous state) \nSince $0.12>0.09$, We choose $P(R_{2}|H)$ as the most probable transition from $R_{1}$, and update the table with \n$P(R_{2}|H) = P(R_{1}) * P(R_{2}|R_{1}) * P(H|R_{2}) = 0.12 * 0.4 = 0.048$ \n\nIf current state = Sunny: \n$P(R_{1}) * P(S_{2}|R_{1}) = 0.20 * 0.4 = 0.08$ (given Rainy was previous state) \n$P(S_{1}) * P(S_{2}|S_{1}) = 0.45 * 0.8 = 0.36$ (given Sunny was previous state) \nHere too, we choose $P(S_{2}|H)$ as the most probable transition from $S_{1}$, and add it to the table. \n$P(S_{2}|H) = P(S_{1}) * P(S_{2}|S_{1}) * P(H|S_{2}) = 0.36 * 0.9 = 0.324$ \n\n \n#### On Day 3: (observation - Grumpy) : \nIf current state = Rainy: \n$P(R_{2}) * P(R_{3}|R_{2}) = 0.048 * 0.6 = 0.0288$ (given Rainy was previous state) \n$P(S_{2}) * P(R_{3}|S_{2}) = 0.324 * 0.2 = 0.0648$ (given Sunny was previous state) \nAs $0.0648>0.0288$, We choose $P(R_{3}|G)$ as the most probable transition from $R_{2}$, and update the table with \n$P(R_{3}|G) = P(R_{2}) * P(R_{3}|R_{2}) * P(G|R_{3}) = 0.0648 * 0.6 = 0.03888$ \n\nIf current state = Sunny: \n$P(R_{2}) * P(S_{3}|R_{2}) = 0.048 * 0.4 = 0.0192$ (given Rainy was previous state) \n$P(S_{2}) * P(S_{3}|S_{2}) = 0.324 * 0.8 = 0.2592$ (given Sunny was previous state) \nHere too, we choose $P(S_{3}|G)$ as the most probable transition from $S_{1}$, and add it to the table. \n$P(S_{3}|G) = P(S_{2}) * P(S_{3}|S_{2}) * P(G|S_{3}) = 0.2592 * 0.1 = 0.02592$ \n\nSince now the table is completely filled, we work in reverse from probability of the last observation and its inferred state (in this case, $0.0388$ i.e Rainy) finding which state had the maximum probability upto that point. In this way, we find the most probable sequence of states corresponding to our observations!",
"_____no_output_____"
]
],
[
[
"class HMM:\n\n def __init__(self, observations, states, start_probs, trans_probs, emm_probs, obs_sequence):\n self.O = observations\n self.S = states\n self.state_names = None\n self.pi = start_probs\n self.A = trans_probs\n self.B = emm_probs\n self.Y = obs_sequence\n self.k = np.array(self.S).shape[0]\n self.t = self.Y.shape[0]\n self.table_1 = np.zeros((self.k, self.t))\n self.output_sequence = np.zeros((self.t,))\n self.fwds = None\n self.bwds = None\n self.smoothened = None\n\n def viterbi(self):\n # loop through states, but only for first observation\n print \"Day 1 : Observation was\", self.Y[0], \"i.e\", self.O[self.Y[0]]\n for i in range(self.k):\n self.table_1[i, 0] = self.pi[i] * self.B[i, self.Y[0]]\n print \"Probability of state\", i, \"-->\", self.table_1[i, 0]\n print \"-------------------------------------------\"\n print \"=========================================\"\n # loop through second to last observation\n for i in range(1, self.t):\n print \"Day\", i + 1, \": Observation was\", self.Y[i], \"i.e\", self.O[self.Y[i]]\n for j in range(self.k): # loop through states\n print \"If current state\", j, \"i.e\", self.state_names[j]\n max_t1_A = 0.0\n for d in range(self.k): # loop through states*states\n print \"probability of the previous state i.e\", d, \"-->\", self.table_1[d, i - 1]\n val = self.table_1[d, i - 1] * self.A[d, j]\n print \"State\", d, \"to State\", j, \"-->\", self.A[d, j]\n print self.table_1[d, i - 1], \"*\", self.A[d, j], \"=\", val\n if val > max_t1_A:\n max_t1_A = val\n else:\n continue\n self.table_1[j, i] = max_t1_A\n tmp = self.table_1[j, i]\n self.table_1[j, i] = self.table_1[j, i] * self.B[j, self.Y[i]]\n print \"Probability of next state given previous state, transition and observation :\"\n print tmp, \"*\", self.B[j, self.Y[i]], \"=\", self.table_1[j, i]\n print \"-------------------------------------------\"\n print \"===========================================\"\n print \"\"\n # work backwards from the last day, comparing probabilities\n # from observations and transitions up to that day.\n for i in range(self.t - 1, -1, -1):\n max_at_i = 0.0\n max_j = 0.0\n for j in range(self.k):\n if self.table_1[j][i] > max_at_i:\n max_at_i = self.table_1[j][i]\n max_j = j\n else:\n continue\n self.output_sequence[i] = j\n print \"State\", self.state_names[int(self.output_sequence[i])], \"was most likely on day\", i+1\n print \"\"\n return self.output_sequence\n\n def get_obs(self, obs_val, emm_prob):\n ob_mat = np.zeros((self.k, self.k))\n for i in self.S:\n for j in self.S:\n if i == j:\n ob_mat[i, j] = emm_prob[i, obs_val]\n return ob_mat\n\n def get_diagonal(self, mat_A, mat_B):\n x = np.transpose(mat_A).shape[1]\n mat_C = np.dot(mat_A, np.transpose(mat_B))\n mat_D = np.zeros((self.k, 1))\n for i in range(x):\n for j in range(x):\n if i == j:\n mat_D[i][0] = mat_C[i][j]\n return mat_D\n\n def forward_backward(self):\n self.m = self.O.shape[0]\n # print self.m\n obs_mats = [None for i in range(self.t)]\n for i in range(self.t):\n obs_mats[i] = self.get_obs(self.Y[i], self.B)\n\n print \"Observation matrices :\"\n pprint(obs_mats)\n print \"\"\n\n # forward probability calculation\n f = [[] for i in range(self.t + 1)]\n f[0] = self.pi.reshape(self.k, 1)\n csum = 0.0\n for j in f[0]:\n csum += j\n for j in range(f[0].shape[0]):\n f[0][j] = f[0][j] / csum\n for i in range(1, self.t + 1):\n # print \"obs\", obs_mats[i-1]\n # print \"prev f\", f[i-1]\n f[i] = np.dot(np.dot(obs_mats[i - 1], self.A),\n f[i - 1]).reshape(self.k, 1)\n # scaling done here\n csum = 0.0\n for j in f[i]:\n csum += j\n for j in range(f[i].shape[0]):\n f[i][j] = f[i][j] / csum\n # print \"new f\", f[i]\n f = np.array(f)\n print \"Forward probabilities :\"\n pprint(f)\n print \"\"\n\n # backward probability calculation\n b = [[] for i in range(self.t + 1)]\n b[-1] = np.array([[1.0] for i in range(self.k)])\n for i in range(self.t - 1, -1, -1):\n b[i] = np.dot(np.dot(self.A, obs_mats[i]),\n b[i + 1]).reshape(self.k, 1)\n # scaling done here\n csum = 0.0\n for j in b[i]:\n csum += j\n for j in range(b[i].shape[0]):\n b[i][j] = b[i][j] / csum\n b = np.array(b)\n print \"Backward probabilities :\"\n pprint(b)\n print \"\"\n\n # smoothed values\n smooth = [[] for i in range(self.t + 1)]\n for i in range(self.t + 1):\n smooth[i] = self.get_diagonal(f[i], b[i])\n csum = 0.0\n for j in smooth[i]:\n csum += j\n for j in range(smooth[i].shape[0]):\n smooth[i][j] = smooth[i][j] / csum\n smooth = np.array(smooth)\n print \"Smoothed probabilities :\"\n pprint(smooth)\n\n self.fwds = f\n self.bwds = b\n self.smoothened = smooth\n for i in range(1, smooth.shape[0]):\n max_prob = max(smooth[i].tolist())\n print \"Day\", i, \"probability was max for state\", smooth[i].tolist().index(max_prob), \"-->\", max_prob[0]\n self.output_sequence[i - 1] = smooth[i].tolist().index(max_prob)\n return self.output_sequence",
"_____no_output_____"
],
[
"weather_hmm = HMM(O, S, pi, A, B, Y)\nweather_hmm.state_names = S_names\nobs_states = [O[i] for i in Y]\nprint \"Observations :\"\nprint obs_states, \"\\n\"\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n print \"Using Viterbi Algorithm:\\n\"\n op1 = weather_hmm.viterbi()\n print \"Table of state probabilities :\"\n for i in weather_hmm.table_1:\n print \"----------------------------\"\n print \"|\",\n for j in i:\n print \"{0:.4f} |\".format(j),\n print \"\"\n print \"----------------------------\\n\"\n op_states1 = [S_names[int(i)] for i in op1]\nprint op_states1",
"Observations :\n['Happy', 'Happy', 'Grumpy'] \n\nUsing Viterbi Algorithm:\n\nDay 1 : Observation was 0 i.e Happy\nProbability of state 0 --> 0.2\n-------------------------------------------\nProbability of state 1 --> 0.45\n-------------------------------------------\n=========================================\nDay 2 : Observation was 0 i.e Happy\nIf current state 0 i.e Rainy\nprobability of the previous state i.e 0 --> 0.2\nState 0 to State 0 --> 0.6\n0.2 * 0.6 = 0.12\nprobability of the previous state i.e 1 --> 0.45\nState 1 to State 0 --> 0.2\n0.45 * 0.2 = 0.09\nProbability of next state given previous state, transition and observation :\n0.12 * 0.4 = 0.048\n-------------------------------------------\nIf current state 1 i.e Sunny\nprobability of the previous state i.e 0 --> 0.2\nState 0 to State 1 --> 0.4\n0.2 * 0.4 = 0.08\nprobability of the previous state i.e 1 --> 0.45\nState 1 to State 1 --> 0.8\n0.45 * 0.8 = 0.36\nProbability of next state given previous state, transition and observation :\n0.36 * 0.9 = 0.324\n-------------------------------------------\n===========================================\nDay 3 : Observation was 1 i.e Grumpy\nIf current state 0 i.e Rainy\nprobability of the previous state i.e 0 --> 0.048\nState 0 to State 0 --> 0.6\n0.048 * 0.6 = 0.0288\nprobability of the previous state i.e 1 --> 0.324\nState 1 to State 0 --> 0.2\n0.324 * 0.2 = 0.0648\nProbability of next state given previous state, transition and observation :\n0.0648 * 0.6 = 0.03888\n-------------------------------------------\nIf current state 1 i.e Sunny\nprobability of the previous state i.e 0 --> 0.048\nState 0 to State 1 --> 0.4\n0.048 * 0.4 = 0.0192\nprobability of the previous state i.e 1 --> 0.324\nState 1 to State 1 --> 0.8\n0.324 * 0.8 = 0.2592\nProbability of next state given previous state, transition and observation :\n0.2592 * 0.1 = 0.02592\n-------------------------------------------\n===========================================\n\nState Rainy was most likely on day 3\nState Sunny was most likely on day 2\nState Sunny was most likely on day 1\n\nTable of state probabilities :\n----------------------------\n| 0.2000 | 0.0480 | 0.0389 | \n----------------------------\n| 0.4500 | 0.3240 | 0.0259 | \n----------------------------\n\n['Sunny', 'Sunny', 'Rainy']\n"
]
],
[
[
"### Forward-Backward Algorithm\n\nExplanation : **TO-DO**",
"_____no_output_____"
]
],
[
[
"#reset output sequence values to zero\nweather_hmm.output_sequence = np.zeros((weather_hmm.t,))\nprint \"Using Forward-Backward Algorithm:\"\nop2 = weather_hmm.forward_backward()\nop_states2 = [S_names[int(i)] for i in op2]\nprint op_states2",
"Using Forward-Backward Algorithm:\nObservation matrices :\n[array([[ 0.4, 0. ],\n [ 0. , 0.9]]),\n array([[ 0.4, 0. ],\n [ 0. , 0.9]]),\n array([[ 0.6, 0. ],\n [ 0. , 0.1]])]\n\nForward probabilities :\narray([[[ 0.5 ],\n [ 0.5 ]],\n\n [[ 0.30769231],\n [ 0.69230769]],\n\n [[ 0.25 ],\n [ 0.75 ]],\n\n [[ 0.80597015],\n [ 0.19402985]]])\n\nBackward probabilities :\narray([[[ 0.42519685],\n [ 0.57480315]],\n\n [[ 0.48837209],\n [ 0.51162791]],\n\n [[ 0.66666667],\n [ 0.33333333]],\n\n [[ 1. ],\n [ 1. ]]])\n\nSmoothed probabilities :\narray([[[ 0.42519685],\n [ 0.57480315]],\n\n [[ 0.29787234],\n [ 0.70212766]],\n\n [[ 0.4 ],\n [ 0.6 ]],\n\n [[ 0.80597015],\n [ 0.19402985]]])\nDay 1 probability was max for state 1 --> 0.702127659574\nDay 2 probability was max for state 1 --> 0.6\nDay 3 probability was max for state 0 --> 0.805970149254\n['Sunny', 'Sunny', 'Rainy']\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a3562667dedf9aecb75bb7a8bb2b5ab3da1fc29
| 217,863 |
ipynb
|
Jupyter Notebook
|
03.2 Domain specific ranking using word2vec cosine distance.ipynb
|
bartbroere/deep_learning_cookbook
|
e40a95185c9e3e22031855b432e5e874f3d6edfc
|
[
"Apache-2.0"
] | 1 |
2019-05-08T00:01:34.000Z
|
2019-05-08T00:01:34.000Z
|
03.2 Domain specific ranking using word2vec cosine distance.ipynb
|
CyberMonitor/deep_learning_cookbook
|
e09c72de5c9114aed3e8f59bf478a97d84bf3dd6
|
[
"Apache-2.0"
] | null | null | null |
03.2 Domain specific ranking using word2vec cosine distance.ipynb
|
CyberMonitor/deep_learning_cookbook
|
e09c72de5c9114aed3e8f59bf478a97d84bf3dd6
|
[
"Apache-2.0"
] | 1 |
2020-04-29T12:40:18.000Z
|
2020-04-29T12:40:18.000Z
| 333.633997 | 70,024 | 0.927496 |
[
[
[
"## Finding entity classes in embeddings\n\nIn this notebook we're going to use embeddings to find entity classes and how they correlate with other things",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nfrom sklearn import svm\nfrom keras.utils import get_file\nimport os\nimport gensim\nimport numpy as np\nimport random\nimport requests\nimport geopandas as gpd\nfrom IPython.core.pylabtools import figsize\nfigsize(12, 8)\nimport pycountry\nimport csv",
"Using TensorFlow backend.\n"
]
],
[
[
"as before, let's load up the model",
"_____no_output_____"
]
],
[
[
"MODEL = 'GoogleNews-vectors-negative300.bin'\npath = get_file(MODEL + '.gz', 'https://s3.amazonaws.com/dl4j-distribution/%s.gz' % MODEL)\nunzipped = os.path.join('generated', MODEL)\nif not os.path.isfile(unzipped):\n with open(unzipped, 'wb') as fout:\n zcat = subprocess.Popen(['zcat'],\n stdin=open(path),\n stdout=fout\n )\n zcat.wait()",
"_____no_output_____"
]
],
[
[
"Most similar to a bunch of countries are some other countries!",
"_____no_output_____"
]
],
[
[
"model = gensim.models.KeyedVectors.load_word2vec_format(unzipped, binary=True)\nmodel.most_similar(positive=['Germany'])",
"_____no_output_____"
],
[
"model.most_similar(positive=['Annita_Kirsten'])",
"_____no_output_____"
]
],
[
[
"No we'll create a training set with countries and non countries and get a support vector machine to learn the difference.",
"_____no_output_____"
]
],
[
[
"countries = list(csv.DictReader(open('data/countries.csv')))\ncountries[:10]",
"_____no_output_____"
],
[
"positive = [x['name'] for x in random.sample(countries, 40)]\nnegative = random.sample(model.vocab.keys(), 5000)\nnegative[:4]",
"_____no_output_____"
],
[
"labelled = [(p, 1) for p in positive] + [(n, 0) for n in negative]\nrandom.shuffle(labelled)\nX = np.asarray([model[w] for w, l in labelled])\ny = np.asarray([l for w, l in labelled])\nX.shape, y.shape",
"_____no_output_____"
],
[
"TRAINING_FRACTION = 0.3\ncut_off = int(TRAINING_FRACTION * len(labelled))\nclf = svm.SVC(kernel='linear')\nclf.fit(X[:cut_off], y[:cut_off]) ",
"_____no_output_____"
]
],
[
[
"We did alright, 99.9% precision:",
"_____no_output_____"
]
],
[
[
"res = clf.predict(X[cut_off:])\n\nmissed = [country for (pred, truth, country) in \n zip(res, y[cut_off:], labelled[cut_off:]) if pred != truth]\n\n100 - 100 * float(len(missed)) / len(res), missed",
"_____no_output_____"
],
[
"all_predictions = clf.predict(model.syn0)",
"_____no_output_____"
],
[
"res = []\nfor word, pred in zip(model.index2word, all_predictions):\n if pred:\n res.append(word)\n if len(res) == 150:\n break\nrandom.sample(res, 10)",
"_____no_output_____"
],
[
"country_to_idx = {country['name']: idx for idx, country in enumerate(countries)}\ncountry_vecs = np.asarray([model[c['name']] for c in countries])\ncountry_vecs.shape",
"_____no_output_____"
]
],
[
[
"Quick sanity check to see what is similar to Canada:",
"_____no_output_____"
]
],
[
[
"dists = np.dot(country_vecs, country_vecs[country_to_idx['Canada']])\nfor idx in reversed(np.argsort(dists)[-10:]):\n print(countries[idx]['name'], dists[idx])",
"Canada 7.5440245\nNew_Zealand 3.9619699\nFinland 3.9392405\nPuerto_Rico 3.838145\nJamaica 3.8102934\nSweden 3.8042784\nSlovakia 3.7038736\nAustralia 3.6711009\nBahamas 3.6240418\nUnited_States 3.537434\n"
]
],
[
[
"Ranking countries for a specific term:",
"_____no_output_____"
]
],
[
[
"def rank_countries(term, topn=10, field='name'):\n if not term in model:\n return []\n vec = model[term]\n dists = np.dot(country_vecs, vec)\n return [(countries[idx][field], float(dists[idx])) \n for idx in reversed(np.argsort(dists)[-topn:])]",
"_____no_output_____"
],
[
"rank_countries('cricket')",
"_____no_output_____"
]
],
[
[
"Now let's visualize this on a world map:",
"_____no_output_____"
]
],
[
[
"world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))\nworld.head()",
"_____no_output_____"
]
],
[
[
"We can now plot some maps!",
"_____no_output_____"
]
],
[
[
"def map_term(term):\n d = {k.upper(): v for k, v in rank_countries(term, topn=0, field='cc3')}\n world[term] = world['iso_a3'].map(d)\n world[term] /= world[term].max()\n world.dropna().plot(term, cmap='OrRd')\n\nmap_term('coffee')",
"_____no_output_____"
],
[
"map_term('cricket')",
"_____no_output_____"
],
[
"map_term('China')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4a356644df6f982ba770815e3ca1236c36e271d3
| 71,192 |
ipynb
|
Jupyter Notebook
|
exercises/autoencoder/denoising-autoencoder/Denoising_Autoencoder_Solution.ipynb
|
Andrewzh112/Udacity-Deep-Learning-Nanodegree
|
20e284560bf617b2614d35682f8f28f128f770f9
|
[
"MIT"
] | null | null | null |
exercises/autoencoder/denoising-autoencoder/Denoising_Autoencoder_Solution.ipynb
|
Andrewzh112/Udacity-Deep-Learning-Nanodegree
|
20e284560bf617b2614d35682f8f28f128f770f9
|
[
"MIT"
] | null | null | null |
exercises/autoencoder/denoising-autoencoder/Denoising_Autoencoder_Solution.ipynb
|
Andrewzh112/Udacity-Deep-Learning-Nanodegree
|
20e284560bf617b2614d35682f8f28f128f770f9
|
[
"MIT"
] | null | null | null | 177.98 | 51,568 | 0.87028 |
[
[
[
"# Denoising Autoencoder\n\nSticking with the MNIST dataset, let's add noise to our data and see if we can define and train an autoencoder to _de_-noise the images.\n\n<img src='notebook_ims/autoencoder_denoise.png' width=70%/>\n\nLet's get started by importing our libraries and getting the dataset.",
"_____no_output_____"
]
],
[
[
"import torch\nimport numpy as np\nfrom torchvision import datasets\nimport torchvision.transforms as transforms\n\n# convert data to torch.FloatTensor\ntransform = transforms.ToTensor()\n\n# load the training and test datasets\ntrain_data = datasets.MNIST(root='data', train=True,\n download=True, transform=transform)\ntest_data = datasets.MNIST(root='data', train=False,\n download=True, transform=transform)\n\n# Create training and test dataloaders\nnum_workers = 0\n# how many samples per batch to load\nbatch_size = 20\n\n# prepare data loaders\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, num_workers=num_workers)",
"_____no_output_____"
]
],
[
[
"### Visualize the Data",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline\n \n# obtain one batch of training images\ndataiter = iter(train_loader)\nimages, labels = dataiter.next()\nimages = images.numpy()\n\n# get one image from the batch\nimg = np.squeeze(images[0])\n\nfig = plt.figure(figsize = (5,5)) \nax = fig.add_subplot(111)\nax.imshow(img, cmap='gray')",
"_____no_output_____"
]
],
[
[
"---\n# Denoising\n\nAs I've mentioned before, autoencoders like the ones you've built so far aren't too useful in practive. However, they can be used to denoise images quite successfully just by training the network on noisy images. We can create the noisy images ourselves by adding Gaussian noise to the training images, then clipping the values to be between 0 and 1.\n\n>**We'll use noisy images as input and the original, clean images as targets.** \n\nBelow is an example of some of the noisy images I generated and the associated, denoised images.\n\n<img src='notebook_ims/denoising.png' />\n\n\nSince this is a harder problem for the network, we'll want to use _deeper_ convolutional layers here; layers with more feature maps. You might also consider adding additional layers. I suggest starting with a depth of 32 for the convolutional layers in the encoder, and the same depths going backward through the decoder.\n\n#### TODO: Build the network for the denoising autoencoder. Add deeper and/or additional layers compared to the model above.",
"_____no_output_____"
]
],
[
[
"import torch.nn as nn\nimport torch.nn.functional as F\n\n# define the NN architecture\nclass ConvDenoiser(nn.Module):\n def __init__(self):\n super(ConvDenoiser, self).__init__()\n ## encoder layers ##\n # conv layer (depth from 1 --> 32), 3x3 kernels\n self.conv1 = nn.Conv2d(1, 32, 3, padding=1) \n # conv layer (depth from 32 --> 16), 3x3 kernels\n self.conv2 = nn.Conv2d(32, 16, 3, padding=1)\n # conv layer (depth from 16 --> 8), 3x3 kernels\n self.conv3 = nn.Conv2d(16, 8, 3, padding=1)\n # pooling layer to reduce x-y dims by two; kernel and stride of 2\n self.pool = nn.MaxPool2d(2, 2)\n \n ## decoder layers ##\n # transpose layer, a kernel of 2 and a stride of 2 will increase the spatial dims by 2\n self.t_conv1 = nn.ConvTranspose2d(8, 8, 3, stride=2) # kernel_size=3 to get to a 7x7 image output\n # two more transpose layers with a kernel of 2\n self.t_conv2 = nn.ConvTranspose2d(8, 16, 2, stride=2)\n self.t_conv3 = nn.ConvTranspose2d(16, 32, 2, stride=2)\n # one, final, normal conv layer to decrease the depth\n self.conv_out = nn.Conv2d(32, 1, 3, padding=1)\n\n\n def forward(self, x):\n ## encode ##\n # add hidden layers with relu activation function\n # and maxpooling after\n x = F.relu(self.conv1(x))\n x = self.pool(x)\n # add second hidden layer\n x = F.relu(self.conv2(x))\n x = self.pool(x)\n # add third hidden layer\n x = F.relu(self.conv3(x))\n x = self.pool(x) # compressed representation\n \n ## decode ##\n # add transpose conv layers, with relu activation function\n x = F.relu(self.t_conv1(x))\n x = F.relu(self.t_conv2(x))\n x = F.relu(self.t_conv3(x))\n # transpose again, output should have a sigmoid applied\n x = F.sigmoid(self.conv_out(x))\n \n return x\n\n# initialize the NN\nmodel = ConvDenoiser()\nprint(model)",
"ConvDenoiser(\n (conv1): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (conv2): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (conv3): Conv2d(16, 8, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (t_conv1): ConvTranspose2d(8, 8, kernel_size=(3, 3), stride=(2, 2))\n (t_conv2): ConvTranspose2d(8, 16, kernel_size=(2, 2), stride=(2, 2))\n (t_conv3): ConvTranspose2d(16, 32, kernel_size=(2, 2), stride=(2, 2))\n (conv_out): Conv2d(32, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n)\n"
]
],
[
[
"---\n## Training\n\nWe are only concerned with the training images, which we can get from the `train_loader`.\n\n>In this case, we are actually **adding some noise** to these images and we'll feed these `noisy_imgs` to our model. The model will produce reconstructed images based on the noisy input. But, we want it to produce _normal_ un-noisy images, and so, when we calculate the loss, we will still compare the reconstructed outputs to the original images!\n\nBecause we're comparing pixel values in input and output images, it will be best to use a loss that is meant for a regression task. Regression is all about comparing quantities rather than probabilistic values. So, in this case, I'll use `MSELoss`. And compare output images and input images as follows:\n```\nloss = criterion(outputs, images)\n```",
"_____no_output_____"
]
],
[
[
"# specify loss function\ncriterion = nn.MSELoss()\n\n# specify loss function\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)",
"_____no_output_____"
],
[
"# number of epochs to train the model\nn_epochs = 20\n\n# for adding noise to images\nnoise_factor=0.5\n\nfor epoch in range(1, n_epochs+1):\n # monitor training loss\n train_loss = 0.0\n \n ###################\n # train the model #\n ###################\n for data in train_loader:\n # _ stands in for labels, here\n # no need to flatten images\n images, _ = data\n \n ## add random noise to the input images\n noisy_imgs = images + noise_factor * torch.randn(*images.shape)\n # Clip the images to be between 0 and 1\n noisy_imgs = np.clip(noisy_imgs, 0., 1.)\n \n # clear the gradients of all optimized variables\n optimizer.zero_grad()\n ## forward pass: compute predicted outputs by passing *noisy* images to the model\n outputs = model(noisy_imgs)\n # calculate the loss\n # the \"target\" is still the original, not-noisy images\n loss = criterion(outputs, images)\n # backward pass: compute gradient of the loss with respect to model parameters\n loss.backward()\n # perform a single optimization step (parameter update)\n optimizer.step()\n # update running training loss\n train_loss += loss.item()*images.size(0)\n \n # print avg training statistics \n train_loss = train_loss/len(train_loader)\n print('Epoch: {} \\tTraining Loss: {:.6f}'.format(\n epoch, \n train_loss\n ))",
"Epoch: 1 \tTraining Loss: 0.977538\nEpoch: 2 \tTraining Loss: 0.690527\nEpoch: 3 \tTraining Loss: 0.640184\nEpoch: 4 \tTraining Loss: 0.613912\nEpoch: 5 \tTraining Loss: 0.595001\nEpoch: 6 \tTraining Loss: 0.582570\nEpoch: 7 \tTraining Loss: 0.572466\nEpoch: 8 \tTraining Loss: 0.564127\nEpoch: 9 \tTraining Loss: 0.556832\nEpoch: 10 \tTraining Loss: 0.549967\nEpoch: 11 \tTraining Loss: 0.544791\nEpoch: 12 \tTraining Loss: 0.541313\nEpoch: 13 \tTraining Loss: 0.537340\nEpoch: 14 \tTraining Loss: 0.534824\nEpoch: 15 \tTraining Loss: 0.531550\nEpoch: 16 \tTraining Loss: 0.529537\nEpoch: 17 \tTraining Loss: 0.527350\nEpoch: 18 \tTraining Loss: 0.525628\nEpoch: 19 \tTraining Loss: 0.523231\nEpoch: 20 \tTraining Loss: 0.522199\n"
]
],
[
[
"## Checking out the results\n\nHere I'm adding noise to the test images and passing them through the autoencoder. It does a suprising great job of removing the noise, even though it's sometimes difficult to tell what the original number is.",
"_____no_output_____"
]
],
[
[
"# obtain one batch of test images\ndataiter = iter(test_loader)\nimages, labels = dataiter.next()\n\n# add noise to the test images\nnoisy_imgs = images + noise_factor * torch.randn(*images.shape)\nnoisy_imgs = np.clip(noisy_imgs, 0., 1.)\n\n# get sample outputs\noutput = model(noisy_imgs)\n# prep images for display\nnoisy_imgs = noisy_imgs.numpy()\n\n# output is resized into a batch of iages\noutput = output.view(batch_size, 1, 28, 28)\n# use detach when it's an output that requires_grad\noutput = output.detach().numpy()\n\n# plot the first ten input images and then reconstructed images\nfig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(25,4))\n\n# input images on top row, reconstructions on bottom\nfor noisy_imgs, row in zip([noisy_imgs, output], axes):\n for img, ax in zip(noisy_imgs, row):\n ax.imshow(np.squeeze(img), cmap='gray')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a356a9ba826a59e37fdbd4f97ce485060d28996
| 161,039 |
ipynb
|
Jupyter Notebook
|
Crawdad_Extracell_Intracell_Simultaneous.ipynb
|
neurologic/NeurophysiologyModules
|
97ad7adb3de54377666a2e90303f024370d167c8
|
[
"CC0-1.0"
] | null | null | null |
Crawdad_Extracell_Intracell_Simultaneous.ipynb
|
neurologic/NeurophysiologyModules
|
97ad7adb3de54377666a2e90303f024370d167c8
|
[
"CC0-1.0"
] | null | null | null |
Crawdad_Extracell_Intracell_Simultaneous.ipynb
|
neurologic/NeurophysiologyModules
|
97ad7adb3de54377666a2e90303f024370d167c8
|
[
"CC0-1.0"
] | null | null | null | 227.135402 | 32,491 | 0.889666 |
[
[
[
"<a href=\"https://colab.research.google.com/github/neurologic/NeurophysiologyModules/blob/main/Crawdad_Extracell_Intracell_Simultaneous.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Arthropod skeletal muscle compared to vertebrate skeletal muscle:\n> Arthropod muscles are innervated by relatively few excitatory motor neurons (sometimes only one).\nArthropod motor neurons innervate each muscle fiber at multiple points (multiterminal innervation).\nMore than one motor neuron may innervate one muscle fiber (polyneuronal innervation).\nInhibitory motor neurons may innervate muscle fibers (and sometimes the terminals of the excitatory motor nerve endings).\nThe tonic superficial flexor does not have “all-or-none” propagated action potentials, but instead has graded electrical responses dependent upon the level of the excitation and inhibition. The degree of depolarization determines the amount of Ca2+ that enters the cell through voltage-gated channels; the amount of Ca2+ entry in turn determines the strength of muscle contraction. Unlike the superficial flexor, fast phasic crayfish muscles may fire Ca2+-based action potentials.",
"_____no_output_____"
]
],
[
[
"#@markdown Sketch of skeletal muscle innervation\n#@markdown in arthoropods versus vertebrates.\nfrom IPython import display\nfrom base64 import b64decode\nbase64_data = \"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\"\ndisplay.Image(b64decode(base64_data))",
"_____no_output_____"
]
],
[
[
"# Arthropod skeletal muscle compared to dendritic integration at cortical synapses:\n> As in human brains, glutamate is an excitatory transmitter and GABA is an inhibitory transmitter. In addition, crayfish neuromuscular synapses show the types of synaptic plasticity thought to be involved in vertebrate learning and memory and in altering the efficacy of central synaptic transmission in normal and pathological brain network function. The multiterminal, polyneuronal, and inhibitory innervation of crustacean muscle, the use of glutamate and GABA as transmitters, and the extensive synaptic plasticity make the crayfish neuromuscular junction a good simplified model for the complex mix of synaptic interactions that occur in our own brains.",
"_____no_output_____"
]
],
[
[
"#@markdown Sketch of skeletal muscle innervation\n#@markdown in arthoropods versus dendritic innervation in neurons.\n\nfrom IPython import display\nfrom base64 import b64decode\nbase64_data = \"iVBORw0KGgoAAAANSUhEUgAAA0gAAAGkCAMAAAA8IPU5AAAAA3NCSVQICAjb4U/gAAADAFBMVEUAAADl5eV1dXXwAAAnNSz/7+/tfX2ysrKc065PTE36MjINDg+Hi43j4+PMzMzr6+vAAACjpaZGTE5eZGbsrq98gYOZmZnyEhI/RUf0ZWV4eXkbHh+AAACTx6TCwsI5P0FnbW5WXF7v7+/Y2doICAicn6HvkZHpy8x/rI5scXPqS0vOTk5+hIZFXUz2BwcxNzjo2dqAQEAgAAAoKChihG2eoaL///91n4OqqqoYGBi6urqSkpLrvL3Hx8dOalfX19fzdHToiYk9REb/mZl6LzD/399paWlSWFr4Q0T7JSb/wsJNTU1BSEpYd2KJuZl9fX26HR4zMzNcYmTwjY4fIiNsknj2Vld9HR3/v7/f39/O0NGOjo66vL05OTlVVVUsLS07T0LYiotwAACmqquNXl7z8/NJT1H/r69wICCvr6/mmJn/bW2yEhKRlpdhYWGmenv5Njb/TEzb3t8SExMZGxxQAAD/X1/n5+cMDAzwICBVVVn7EBCcHBwEBARfRUfGycpxdXXZGxvKvL2io6PEp6i2travIiP/AAA7QUPS0tIxQjePkZLRo6QjHyCVlZWfn59mZmaJioszMzPdDg+9vr+BgoMQAABtbW15OTniEhKtX2HBYWGwAACgREUkJSVZWVr/Cgr8HBw9PT3Gxsr3LS3GGBz3SEja3NywkJCxlZaqra5FRUVxd3iytLX7CwvSExT/zMwUGhbiYmL7OztBQUH/QUH/Dw8MEAyWNjaSJieRcnNQUVGgAAD/f3+Fiot5fn/9Fxfhs7MzAADxgoNITlBmMzPNLS3/Hx/MAABsampJSUlBPUEzMzMIDAzMzMxdXl41Oz1UWlz/T09hZ2nMzMzh0dH/j4/GGBn/dHTzo6MUFBQ5OT22srLpCQr8GRmPLy/YqKj/n58cHBwjJyj/KSnvz8/5OTru3t4QEBDhIiMqLC2mpqb2UVEdKCHun6D/8/OQAACvQ0P3DAz/qKj/MzOGhob7ICDysrL4WFj8LCxBRUlgZmggICCkFBQuMzTwwMA9tXtWAAAACXBIWXMAABcRAAAXEQHKJvM/AAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M1cbXjNgAAIABJREFUeJztvX90HFeW39fqISPNkgA82mHb6gm5XDRJSc5qrVhSSwTVstwOwV3XiFgykkw2gAIdpsV0GLS9zVk2c04YxN7IdIvRgHMMLBw7oSScPUMbJDeUR8RJwpCzXiGhxX+wYk64zpwTJ6TtWQS9lJMTI14eMePU+1X1XtWreq+6X/1A433/kIju6ur69el733333pcpamlpda1M0gegpdUL0iBpaSmQBkkrZo212+1cHqiR9KEolAZJK2blDUvZbHbYaCV9KAqlQdKKWfnhAag+o530oSiUBkkrZrUNBNKABklLq3NpkLS0FMgGqZ5P+lAUSoOkFbNskLIaJC2tjtU2+jRIWlrdqmWUEEgjZtKHolAaJK2YZYOUM5I+FIXSIGnFLA2SlpYCUSBVkz4WdVII0o4P3WoXix9+uKzuG7SClXcu/Rc5mQ8kcndskEq9lCOkQeoh5emLPy/xlCZyd6pGToMUJA1S0mJA+nB+UPiBZO6OBklO8x/OO39okGKUBVIf/mfOIimX5LEEiIBUMGpJH4o6rX+Qqj++FPE3rBtRIAH/4JtJHkuACEg9lWy37kG69GX5PU0SEg1ScYK+DamSBklOHpAGgZ/xTeeitcDfH/5gh71Jvjj4A/AKcOrb85Z3n5P+sqGlpd1LS5okKAakeWyRwFDVemMeXv82uM4fTuTw4AT9zPWBO/D+F+Am5eI4zLmsBklGbpBaE2jwS0xTjoyGf0A2yeNNvjlY/ILdVqTJ8uGp5tTS0pDKE1i3crl2OfgPCyR4Ua2/+r5Jx4GKNEgkThHHiDZPQBruoWS76EH65jy5eTn4yg+cuFIeb/IF2ST3A/ZGC1R9vnyl0Ww2pw6UNUlFGiTgBOAhkgUHtEKDxcF559KjDW2QHOViOEwCUi9lrUYPknWzLCduh/VjOAFeAEHyL6wXoDP3Ptkk3wcJm4ceCNj2C4kvsoZHk02oxmFNUtEV/v4CR78/JNcZuALffB//AwFDgfRFC134GAZWGiQ5uUFCTIC7BW7tF/aP3g7sSNhOnvXLOQF/KFtSESdreHS12bRJmlR3ButVDEiIGXh5sXn/pm2wctgbcEBCd4DcpIgP0wZpLvLvik0xgITvzDK8jYPUb94X6D17k5w9bJKJOL0Chke2GjvLt5SdwXoVOyFrj5G8bOzwgIQ3+SYdrohKo+ZA72WtRg8S+QM58C0blmKx/eGHO+Am2PzkiA/C7oKr6o/LOxtNWts0SVSwoQ0GRjAu6vHWcnAkyoJEHIDlOECyS2Q3Bkj/otNd+swjobvsyiNq05vk8K2XAKn5dXlr06Vt5R/3UDZxJ2LC319gp5qOxLW/YAM9NkhkEw1Sp/IH6cjt0yc62mUMIFXeKx93c9Rsbi1/vbFJYkBq4eiOcwcGYfR7Ipdre1y7pEDqnfsVANI5S3fv7w+9SxFIOdf24UEaKi9NeTlqNo9vcJIYkMDIB/zfuQNOnOf9dIDUS1mrApAsPbp3LdwuA0Ea9M75hQbpVvlwg8cRJGkjJzkwIO1wWyRqePoDxu2LG6SaUdiIIFm6fTKMkxcIErhVOfzKF+iVkCBVny9v8+HIImlpIyfeMSAtu8dIO+iJBzLzkARIPVnZ5w/S5tO3HZTOLd69v1lyl8EgvY8nZGFcaZnZRAqkS1+TWViupjZy4h0F0vtU1M6xSPBfLRgl1yCpVWD4+9rNRxRL567fkxowBYNET3ZM9DGbyIB06b0lTpiBJWmHz2d7Xq55JDQT7twBOkMIXeCEQeqlNvqieaT99+/SLN0+KR4wCUByku1wMXQYkPzCDAxJGzZdKM/hiLoDJHv4w/kdE2QuPFGQein9W2ZC9sTpRdrJE0XFRSDhMorlnHsTMUiT5cMtAUcbOfGOAmmeVErQ80h98MJ/0YZbvl9MDqShjQmSpWsnGSdPfsCkUtVb7mwGX5JeSeDwtGTVi5V98ilC++9d72DApFDVr8vbJDBCJG34dKE0ywbJHE36UJQpVK7d5vuMk/foZsgZpq506evybjmOmjrxLt2yQeqhOorQSasnTtJRcZnggxoJw3UekjZ0kkOqpUFCYgdMwuCDEkmE69wk/bwmKaXSINnafy9elhZkwnWMpg48vbET71KsuR4ske28HmkzM8O0eDrKQJ5/dp2fri4t/VL562Z0h6TVuewS2bXeWSGpq8K+zewMU1RB8eot2XCdrcnyganmcd3xLp2yQeqhgqSuK2SjZ0k+7E3UuIImnKY2dApreqVB4uuIK5CnlqXm17wiviBNHSbls1NLSxWlB6OlQhokX11jWPrd0+omay9xi2GDZA2P7E9s4MS7FGu2rkHyF8vS4q+rmWC6tBQy7I2GR7ZaGzbxLsWyS2StfyR9LKqktIsQy9LHv36iaycv9PRRY5srH69xuLyg4ty01KkXa81Vt+P6C/+MTsjrNiNviOldJyHLALkDEzrxLnXSIEnp//mXH9Ms/bPOs4gWwk4fWUMi74CqoRPvUiYNkqz+4o8Yu9Rh5kPoadjjPo6gJild0iCF0InrjF3qoLHXrYAmJ1xt9c0j2rbB+3SlTKUebNoQGUiW7jMFTGHLLsKmMzSuoDVeuNqtSUqR7FrzijGW9LGoUpQgFYubmdzWcyEae4VOZ2gd9jYxprTRe0emSr3YtCFakCztZ0Li5yQbe1WDm255xQ0zsCTpdKG0SIPUmU6cPueSKCpeDZsW5BdmoDSjE+/SIg1Sp/K4eNaAKSAqHpqjSZn5pg3dOzJV0iB1oWtMlnjggOlSWI7c2Qy+JOl0oVSo2oNthGIDCVQC3najxK0HDJum2vBmM/iRpBPv0iENUpc64hktnfPUMF16L1x6nUWHdHehjds7Ml1yQMolfSiqFC9IxeL+mx4PDwyYnOBDaI5E4To3Sc/HfMZaXvVg95O4QWI8vI+9LIXl6HjIMovWgfKV2E9ZyyUNkhqdICkPH/9Leth0++S1sOVHx0Omh08dKP/POvEucWmQVOkIQWnxHzNLx/xvf+O/CMPFtpBprZb9ump96Hmd5JCserAfV0IgUSg9OsI2yfvkmdflOQqX1roV2a9JnS6UsPIaJIWyUTq52dUkT44l+bA33t7OatWJdwlLg6RWJ/AIaRFMzG7+838QiqVGiLA30BSV1Xq8/KVOckhQGwqkyujR6L/+3qJtlC4tLf31PT+UZilc2JvtLQT+0ol3CWpDgbQjk3k8NxP192/GU7SP/iGK1724511qounR58/6crQ0E4YjtreQTrxLVhsNJEsry9OD0R7BEeTf/fLfth/0r2i79GjPixwuQk4fNbzhPYskneSQlPLDGw4koPlonbzNJxEye5yn/EXGx/vhVx6OXPZFxBEvLDF1QKcLJaWcsYFAqmQoRevknfgdN0kulhbfZYZLx8NNH/kMp3TiXWKyu5+M1JM+FFUKiNoNTi+vUCxF6ORd+k//lpckwBI1v/SJM1wKOQ173G84ZZE0GdEZaQXKBql3ehYLwt8zc49pwxSNk1f9uvzXfwpp8fhwz35OsYRdvG0BTU44Cij6a+zU6UKJaOOBZOno6Dzj5F1+X/EhoHrYd6ELxwnSvf7MJ46L98yzIJ0hBEaeFsasdMe7RLQhQSp6nLzMS7MKnTxSVw6HRI+4j/tX7zpm6a/9O6E4EmU/bCv/WCc5xK6NChKQy8l7UFfU2s/uz/DiI84wiYgeLn3yJi8gzpXErO1WnS4Uv+wOkRsQpKLHydt1Q4WT97z9qL8OZmIXfSF59hlnpvZdubzWqzKztjrxLn61NjZIReDk7aVZOntotMvvv0X1r/s8wCRB/fm/ZqP0U09cgoeI1GyTRZJOcohXGiRLg3MvZRgnb66LARPbl/gT31ESVOtw+e87ZumTIOSApKPkx3XiXczSIGHlxnfRLJ2q7+js2139vf8IAPJH/ul10At0RkuBKDWuyBcr6cS7mKVBcrTjBuPk7br8rfD7GCpfoR7nF//qOU+uEPu0X0X/+rYdxFv83Jej4Fbgnn0/3eFPgVYnahg1DZKjo3MP2AHT98M5eUOs7/VH9gCIF0qYotNUn31zMdgqTR0IV2Qx+d33dLpQjCJNGzRIRKMvnWUGTGsV6Y9WWI5ed+aKfk7AkaUX3yTTtJ9wwg6O9ZLT1vLhX9SJdzGKgLRmJn0kqqSgQvb9eXbANFyT+tilpSVmDPOmA9I5TwzczRHQHoLST90WTKKlPq3GzvKVhuULvtL9tdCSEwFpI2R/h1HFOMMMmO6I81s9Dex+SoH0bQmOaJSeYcg77rtyH1eWGwhC8HrR5hilQfJV5QITfMhMBOe3Vr92o/FDf5B8OLL0OR4rfUJ9Inxy+FXyQU1STNIgBenoCBN8CCpi4izc4u/a+XMExkpuoxSyR9dWKjncIkknOcQiDZJAR9d+wrC0slzjOnk/9gbVnnU4+hVpjsDnsCl7BEdKIXt0weGR86detDkmaZDEqsyxPl7mxrTHyeMutPwM4ehjZkpWwJGlr9BQaXFP6B5dU4ddK2zqxLt4pEGSUmX5DMvSxCgTFR/iWw08z/oxE4QTc2T5d5jBN0NOH7EtughJzSguiRYjDZKsasssStaAyWZpyC8a8O13/9+Pf44tkpDhyNJXKOjwax4wgrSbl9SqF22OQxokeQ1OT7hYsgZM4I1LS/JRNUmOrJESysD70/IY+UX3pnQKa/QiIJndVg+kRpG2LK6whbWQpelCiBWQpDmy3Lt3A/L0OPKPSlhfKp+eodWRCEh66UtJec1SJvOTCwXJhz0ER5ZP9mvcuVy/XR/wj0roRZsjlwYpvGbcoyVLe288KfGwW0YjBEflwzDr9ROpOvSrgcl4Ld3xLmJpkDrR0Tm3h2dp12ffEnMkHzrYCgY8cEbpTYmtuWEG9qsXYrgwG1cYpIoxlvSRqFI8y7oMjmCUztK54mcP/UAVR6jp1ovBXR+orUXhDp14F60wSCVDUQud5BXX+kiDxMG7vMzkir800q+EIxQ4+AqYJN9iP7LnnRLJDw2deBehqhqkznX0BkJntf9bnzEs7b0wxnmSd3bAUbMJguABXR+AWu5sBt+dapKiEik1zxkDSR+KKsW5Yt/7KN9hi8XNkzeY3IeVG9Oex1jqaXdx1NwDTFLgxvILlOnEu8jkgJT0kShTnCDd+oU7NknNZv9Hp5jow+Xz/fRDLJ16ykwIwczXfzdg6zALK+3WJEUkAlLvFMjGCdIr1gM/vQUw8wBPJPUPs/mtq7NjnXBEdTlB9eq/69v0brd/R32OdAprRGobfT2WIRQjSDvKO61ncwySNG4/q/357zEsPbgwDR7gK/5Pt4cjylN7/WOcQO6T4BCy5q/5LZ14F4lI7+/6bNJHokyxgXRp6QB8hhFJs9TT2j/7HYalLfOrvyj7uLMcvUg44ic4gFZ3YTACXbqe1iRFoFGz1+ZjYwPJKS2HJG1hs4T6s64apjuzPlHxII5Qz2NebSDZOESruybsoTKje0dGIbwYc8GQ65OzHhQXSFRJ7CwgJet+ascuuGqYVrO8qHgQR82fo6rVPRtPhZmYAtoGe6joxLsIVB/ptWmkuEBaoI3BODBJnCd32mRRQgMmeY6ajwJAmvIW8QUKBAOhgzmlE++UC8/HtntnGikmkCrlwzQwABIuIoXz4y6WtpjTfrni3tyH3/YH6WqYRPImNEQkO1wv2qxapGNxD00jxQNS9T22FyRoNnTDB47fNx+4WMrcOc9jiZND9IzD0a+y70iu8EJtT62spBPvFIusM5adS/pI1CkWkL52lUOsQjx4dFwBcHhcvExm3BN84OXiUY2I2Pj37pBh761si8nGFU2SSpHo93DvTCPFAtKkq4YOc7LqJWkbHkoVZj1mKbPKsMTPabXDdmzQLuT0katHF9qDJkmdZus9F/2OA6QdrulV2954SNpNzfMseM1S5oGd3uqXG74HzSQ946Ig1PQRbmHsJul5neSgSjhoV9AghRGZifVwRCc4QB1nQhLN/uwWP5b8ayxe3PPmm58zffGkqiYocXp0AU3qdCFV6sEiihhAcjf5Pk9jcYF+Z8rbXej8qhcli6WrIaaEGpJVE0S+xbM68U6VSKxhSIMUQrfYZ76ftTILzjstboB6wY6H06OmXXeEk7VYoeoDm4HDqePlL3WSgwqRlNVein5HDpK7qapr5OM4d76dTsbsj8xf5o6XghSy9Wpw5/CruuOdEuWHe225vmLkIDXd7pp7wtV+44r/E99PUNqydt7cEoalkOkMQT268O40Sd3LWNMghZV7BokdIlGDpG2BCaU2SuP9zS/37pJlKVRfPFGPLrxDneTQrVpkJeZ9GiRZuWeQLBWms9nsuKUL2ey0PTN0XBRZGyOm7DNQHkjbpbOH/Pp6heRIZsFMy2ZpkrpU2yj0WuPvYsQguWeQfDUjMWO6gKMNj+Hsk4slXl+vMFXlTdlZW51417XyeDq2pzKEIgWp+t4BuYSClmtdZh/heaUtONTHsJSZWHMlEYVLrwNFf1IHC8LpEV6z3lfV2Degx0ih9Hx5RvxgNkO0Ju5/CUFzHv9dOH+HHnA9oCuYjodKCwpR9NfYqdOFulHJGNIghdKC7ExoQMCO1Uz5z7AkgV5ETG3tGRNniofjSL5HF5BOvOtGozhjdcOA9C+63PMlNuHHX5OyxmDK8gDHHrhIsuzSR2xr8dULCyE5mllakrOdWNvK23SSQ6cyRwhINaOR9MGokz9IR26fPtHFjqtfL7XEj6Slq7C7kIRQEK4w7iHJskvLrrS8lZ99i1elUViwNJtlNbvtZ98NVaxk+YHf1elCHcoOfm+YXLsjII367v39He54UtJZmlqSjEg0DuAgHJpTcs8fjRm7WJYyq2Z2YQGgY8FyZ3ycl7bnaNw8L9VupYmKZ3XiXafK4fygjZP9fQSX9jy6ea2D/cpGvhuHJWPUlhkgs6WQpFXvJmzoIbweXJBhCRXPWiTpJIdOVM8O2OqdhS9lQLIU3smTjnxLBxro5FNoXDx9iJqgRZ63IDCUxMmw23Dx7HGdeNeJGo5n11sTSf4gbT59m+olYjl5m0Ps9seSkW/pQMM2OkeiAFvj8Tccmz8rgOXBOKW9KxfZ4dUF/m6x7N5COvGuM406nh0I2/WOfxwY/r52k25wde7RPVknb0iSjxnZQIOryBVm7PFbdR0v/+IPXMOh1fHxO9Y4adoaLrk2xsnhhYXzF+zPcCrgne2XKJ4tknYouAMbS07MDhYklZI+HmUSzSPtv3+XZun2SRknz5Pz7SPJjAZOM3DgwZn8LcFXjzlJD6vneZvZKDj+ot0KzJ8kpreQ7h3ZgUq0ZzfQZ+SSPiBlkpmQPcE4eYunhU7e85KZCrIZDVc9s0Jg/b8VTmjAnj+i2qc84HbzanJ63fWjaMU4f3N3byGdeBdeoybl2VmDpHrSB6RMkpkNLifv7r2gqLhsSsO24OofW94I+RgMdW/xRAaYedgFO4i3JctDiZftfR5ashWeFeP0FgIkvaLkNmwQVUkpElYPtVqVTxHaf49x8h6d9BswWY6dDB7i0gksbw36GHHcXA+8O5+h3/bwOCjxkx9qaHuv2zjF7f2ge0eGUg13ayCq9E4X/VC5dptPnF6kB0z8qLikY8fpdcKVN6V1zImzMdEDDhoFuxPRlln2HX7VhL1rN0kzfrW2OvEuhOr1AVb1ngmAh05aPXJSMGCSdOykZ2I9qzIXqLmiLeJ87/Nk8we0/drm9dPYXbMkBRT9WST1ThA3WrWMtgukfT3j23WS/b3/XsCASdax2yY5E+tdlZlp++AkOPjnqdoojdsGzKdnJB03pyd8A4v+9KLNsmImkbBv1ytZQh2WUWxmo+KPHJYkHTvZAZJ3O1fXB/K8eyN79GcIShfgUMmvZ2SW2bNt7MDmQV6oTryTkzvUADTcK3G7LuqRXAMmFHyQdOxkB0gcPFx9iLaQHQZPSZ3Hg58t0/5VfP3snomx44cZaFkkNVXdkB5W2xVqQHG7HskA766w7xozYLp9+oSkYyc7QOKlhnNBEvc5scMOdyp+PSNZg0QiGTItvY7rRZslVB/2cDTQZ/RI4mrXFbLXmAHTL//aXxbS0QRTm1IDJC5v/fQCSltQlqlUvyA83Zo5+zOfL591gQQnfGV6C4ED0CSJNMZkNRCt9Ui+nYpSc3aGafGHe14UPHZXJWssPAE7Iligt7BAUhv43Y69Io2IeInjQOfvOIyumtAgTbqzGXxkoVxRcCl7WXmTw9FAqUemkhT1bNh8/y49YApmqSVZy+cN2PEl3TzF9t64i5zxD2GnZMm6TrwTqIXXoHCr3hvhBoXNT06c/mWGpWf9nrmdagN7YfrkT/0CqqMNSvFm9iy/IkxLJ94Fyhv77qlwg8ouQjvKf+eZT+ig+OdcliYlA3uS/UtCcbS0NHZHmqSpw5LJgPhAdBfWAA1wYt8o3GDOJn1sKqQQpOqXwGN7XcTSlFwNUmNJsnmKbOprk8QkZiVJCtejC/xA6GVf/DVKGhVzwg29kN2gEKRJ0lTh9Tcf+bPUOCAHyGHJGtsQ61qS2B6a0uWWM1EK2fG4sVMvjhkgX4MEeqD0QgRcHUiX6FDcs5/7sbStLFjxgWwmZ2cmw3NESJoN3Dpcx2NQa6sLKgLEm4wlGjF74BdIHUjuPnZ8lq7KPfjyGUSStersXBMkaUtQz6Ct4RZCP67LzgNVNbO+HA2UeiHhThlICxwTwrIEYuINuci3bKAhMMHOtUvGU8sKnDt+criv1A+PBtXuLmkFGaSBgWEz6ePrXqpA8ssNcrH0X1+WGfnIjqOkm0t6cx9gnrdfvCHkQuiNK+qHR8sry7XegSnQIIHexWNJH2HXUgXSj/3nhliW3v1K/GTulBtHhVhIzLPpbwZkOIRYmgLuO4qFXh6D47sx3SMsBRuknpiUVQTSjuBHj2Fp8d1vBz+ZkhNN0qWBHI7GUOURt8PQVLiF0GeiWA6zQjKVeoIlgUHqCZOkBqTql8K+WgxLnzzzuv+Wsl315Z93L0c+TR/QxqE42h1J4vcIlTu7/lkSGaReMElqQHpFyhf7K3/jTwrTHsJk4slOxPpzxCEp5MKzUZXH1uYeUywtr+vETqFBAnlC690kKQGpKWVDQEoDk/fwwz28zSQzULdKxwM8aBToinJX89Vw07CRNhGqzE04h7kyt36Ty3NCgzTQZ66jhZlbs3mjPupa20kJSM+XZYJsh1Eo7qt3F6nhksfF2ypnaDy9V33lNTEmXXS0hQndHS8fDsHR1IHygorr56ujoxRLE6Pr08UbMIQGCbQBXz+pq20ju2/EcNlQFSDtkAoOTDqE7PkhNVxiXTzJUiXZiSYeRwts+R49mxRuob+rcczCHh2hfLzlmci/T71GjYoYpPVkktpg8c7CMLveoAKQULKq8IFm3L8X6dAD5eJJDpCmZDNaeUMe9ypKzjvh0hl2x5WkWplz1vacWHeRh4Asu3VqknImB30FIMlFGg67H/1nqeHS4jPYLMkNkOQD37yaPxdIzvIw8lV8aOsYewfVlp3R0sjR2L5WhWZ9077Xq0nKI1eV7cnXPUhykYZJ3tDn29Rw6afALEkOkHxL0N3i1ioVLlDBhi3O0mIh8shh8kO8HVYHRx0Xb3kdBR5axj4ZjtaTSZpDIJWYUVL3IElFGlo+tL245xFllv5zuQGSbAl6UM3fGGz6wO41BEetJLrnzzhmaX7dDJbyJr8wdh2bJFIzz+Tadg1SRSqdZqc/bbSL99/8hxL7ks0MD1U727gShqOkGjRQZmmdoDTm06mBa5LWx7Jj9uqdzBK4XYMkzmlognF5oA35yoniffKmqAWRfMBOen3akN0ZEl0/tja/rlCq1yUNEjBJ6yO9oUSmxbK0Ce0WpFdkHtaWsG3ks286Zsk7t8TuSzZgF8JXa4TqzrA72RXNHQ8v/Si1ub3sfE3SukhvgNFv1SBVpTqrSrUN+st/4AQe/DPE5VtvheMoRHpd8k3zj9oo7Up3CK9qcpqr+mt9ZNzlyTmZOerVLkG6JdNZ4apMcKBxeOkfPmMH8T7hZg815RexCFODHoojazCVggWRHJQyd1KchyeRHERrfSSB22FIhcGGSzJPq1xVLOpi7ATxFrmDpd2yeBwvy60u0wzLURTFR52IQunxSEonaQeMkTAcrQ+T1DKG0MEWmB6x3YH0vMx4ZZuc1cKR72+/G4DSjCweIXJ9QnE0laLedRRKmYupzMPLy83Fri+T1CaNLkvMxFdXIEkl2c2EtVrP2h6eG6WWYO0W53mXXDWmGZajdPU4ab1EZWgcmk7bcKkkH/q2TVL6GwrNkSFSjmn/3xVIUkl2B2Qe/iuM1Xrx8094KEkHGkLUFIXiKMmwN18ze+lsp4nRVLFUl52LdTSU+oZCA/bynSOMH9oNSFKh70mZjXZ7ZnX3cFCSDTQ0DkTEUbJhb75GttAoZR6np24pVOibKJt2k1Szc9nZVstdgFRdkkiy88sNYjfiBdHtuMPiHvIcSzfVl+qd0gzJ0dbEw95cHb3BJuGmhaUBcV0sR6nvcTdHFmavsOvRdAGSVOg7IDeI3ohrQb79U1KWDrqlSGc0SKe0huNoW2pbEtceZzwsJe/jzcqUIfFMUqo7gTueXZttWe4P0o7x1wJ32ZTJMJWaQvJPIPqKOHg/fFa21518Smu4XLxtaZg+8tHgnJuk5MdL0lnfLlXS3Qk8ZwciXctIB4CUyZx9KSAhVybrW2oKaSoopk3GSov/t6S/Jj8RG4qjKJszKFBtxYtSZj7JIsAOIg1I6V6cwhzBh1kwcswbgSDBGYo5/t2QyvreKuP9eUr+WL2Jg+H/p+/CZbTkm4GH5Cg100d8Dc5zSEqw/VBHkQb8hKZ4vaQxMhtreXZs9xMhSJYe8DzuryWi2lMy3h+35I/Wi++yQYfgb5SdQAq1PlnqOSqyrfDo4VIi2XidRRqISUqHUbrsAAAgAElEQVRvhZ8davAkYciAZOlU1nU7hmRGIjslhjUy6459+7dxXriwxEI6NTzcOn/rgKNicQa5dxc9LN2I3yzlO4s0QKW4wq9l29mKew1pf5D+nMvtXqnTUdUvD4gfwOMysAkcO6Sd/93voPBdsHsXoomxfGgP0Jm+6SOejqLeXZexl7fLuYFxm6VSh5EGpPQWnTvlvp6RXFD4uzIywbJ0xmZJZi62sSQBm9CxQxtNPotmlRYDa5Xk6dgm3yZ/KnXpDL4aRNl3y9MYoUOmw1KcnbyqIcr5uCYppbmrzsLsfZ7YomAeaXB6eRfD0i4DJJtV35MY0stEGniOHeymMObZ6E0hSfKB7xC1Sscj6e0t1L279/Z38DFMEomHr9SmnSDExLTyo/RRzh6Sd6a05q7W7RGS12hKTMhWRh6wLI2/9ooUIxKRBnYU1X/eHLe/5sGdWbSkHplB+moxmCTpXg7hOEomLei2daq3T5/YHPZzo4ik4gx2JpYHjzpd8VbiqbdohK2e8KheT+Pcd80eIXGGcXKZDYPfH2dYypzKBq0bCSUTaaCnYqdNllegVdDj/oq9yDMiyWecNCMdsJNvGw44SuSW7ie1JNfvXQv3yWlMEoniTVjeuGOWVuJIeZgzRdUT1pUNfD+VuatUuS+nKF4+Rej9y2dZlj5aCHoEZXIanBy7sQts7qVjl85TCa0vwoHST7n7mpItsQjRNjwxjor3zzm6ffJEmI8ikuYsTwIZpRXg0VWWbbO0HDVKNTuLxoeiJ/qAnghiKY25q6N2uS9vEBcq1+5bq+xTvuvyrJ9hahyQyGkgOXbnXfaO0Zb3nA+8CG0Sbz5JPmAXouYvMY6K+2/SqxyeWzwdgiVE0rSTOTQHXh10eohHi9KAoE+DhdETzv98VEpfohCV88Tr0hIyaZWuysQm48I07xmclMjoweHx85RLt3rh/AJkc2wha9NFrWH0OmzowNmXdOutEBwlm+69+cTJ2wxLR2Q/ifgBAVacOXQDDY2mHZQiHCsJppCe6HtisAo0+EQQSWuuxIHEVTXtSGSfOed9P3T29yBnBv2OxzC1JEosUHjcwWiLOc2ujlyYxe9RC0Z8zjdJk7Lh7BC1s8l3Cyruv3eX8fEkA3nw124FwIKnliYwODNksBRd2EFQFmvRUyUKIqmQtlnZWaePyz7ePFcHZRQ/vzfjlcswXZGoZQVVsdM2Rne4hm3nWTdJIIn1Xfdm0sOeELWz28q3kuYIaPOJ006D9HPX70t9COIzD/6Fp5ZWyASgg1I0wXDqh5unJsURIMl/nJRzpw4kq5rz+1AweIyHB6lSnlxAjz87w5TJ7L1BguIyfRpmylvHiPe2xScI2Fgqj7tIAk1Z/4lrNWdpM9MKxVH3l1+RaJYWZczSIHTp0DBjlCXJQWkiiina2eAGXE/0DVAgDfYFQJeq9g0tarG0LDc9PTxIoEdx4QK8FYcufM/F0q7xHHgKD4sjaI0D360Ta5Yt+GwEjBZaXy+LXnjxr6LH6Rl2V5J4NA7LZKNDpYkjIJqlj39dOL8EV0VfQUEFNFBySLLnmCIYKgmqkJp9zSqtZoBJKqUoC7xB2Vmf0HxokIZQTs95/HhPmxm3Ls7JJNlNTuwl1sgPI8tj22p/FYy1v/ir5GGivbsrkqVKIRJV08YR0H16vCRKfBixnTuLKjdJdthhRbH7VBVUIfX1DTIgBZqkfalpql+dM+0ASp/JnywODRLJVkULSI5RIQHaMH0k+uUf+wne1B8jMM0EDRs0f3Ct1zedJ8nx7qQDDdJdWlPJUREExek43qNAlqADh8dBlcdukoojeF7phlKjJMoNchmkYJPUZ6bEuavOUac14pNRGxakIfthhIZiHP5zwb2aJND38gFP6jQeX40HJUjYrRzg7u9Y//hd5zGyTdJV2VI++cSglHIEdOL6OTmWjkJ2MCaDEx6ScBRCqVFqCXKDnnAZJGCSAkLgQ+lw7iyOatQx5fhbhQSpSpVP3MEmCaifm5nwkzzf3OAhVuYBN1JH5OQPFR5g5456hn4bvye56myIbsdp5sjSNQYlf5agczeC/8AkMTOxM9i/UzZSEjl2lmdXdeuJoE/sS0PyKsNRwcexCw0SXT5RAOzY4bRClpvk85O61+aQmPcFf6+uybZygH7kKgPSI/yWbNNI+YnYdHNkaf/JjxmW7t7nxh4eUyYJkzTBMkOl46mQMOmbCdkhDQSB1FdPvqUQw9FA1rdUKhxI1ffoPiUGGA05f/qglNl1+Tfp55TkAz0ITNVzVfzBkMb5JvUA/Qp56uXGPfITsannyNLmkwxJ5xZPc1Jba7RJwhHxeXYTko6nxL0TOXau2DcBKcC3G6gYnByCWNVgONrnn0wbDiSmfAKNcyYos2KjdNHdae3xjd9cAHk/s3cIbMHmyF3xB63froU/cp4dlN0gWzohPxG7HjiytP80i9K5R16zNE+bJBy7cz2YJB1vxP3Z8BI6dpwhkqVAkAbaCefctUyTsrI17lQsUiiQmN6q5zERqzQR/TjssDozy29rg3UmcHTU9FT8FVCQ77+3TdKvYj7k7EyYlNbnu7768ejIIxdKi6ddo6UZFhE4t5RxJzTgdLzlro9HXM3HGSJZIAXTN5LoMKlmmFTiYMV3gFQMCRJtkM7bUDAkNf/mLvJiYdpgCy9snb0hMEfuVg4Fknb+32KSfvf1UHxI16Anl+/dge6hOdrFf2KzdJ1NEgd+wWPnT5gWvuIeEOF0vG5DDkLHzgLpCQ5IgdEG6zPDZmLZq9VZY5g6uj4z6FDCgEQbpDFqPDTOPIm7TQqvsRtnPBjt/ae/KHygXY6dU77x7/+K9bx8jNsJyQ6QpGvQ1xVHln+HAniLf8FJe7hNJ+NBcqjxD/TjJtx7wYHwia5IEjt2nFkkNJMU/KFKYrNJLZNJ0+gbDpwgDgPSpGOQCswkbNZ+EmFG93kGr/6PTrn9OnPM/QS75HLs6HKl883XSVMu2QFSiGX+1hVHlm4ifO5vvn/b9vBuOoOlFZfTBt1t7/gdDZQ8hIWRTJsGLkiBYTugkjGXxE2pjhp1Om3Q4ijQyQwBUpN6ui+waNghbsQaMlcOXjM33PmtnpIJVqxjl2U+aX+X7ADpqvwyf+uNI2ukhGyRZYeOnPaiBAhZobZGoTtvsqpdn96pJBy7gSYnaAdACq46B0P8BEJ3Y5Y5YhBfE2SjhwCJXn3CxQWZTSJlSIgk2u5Muzp7ZXhVTESsY9fPfoxYOtkB0pTsjO3UOuTIcu9QzAGEv/ffXHShBOML9AMAQ+KPvU5clyTJOHYdg5RA6K6VZ80R4EhwDPIgMatPuJnAL9vLxZ6nH3mkMW96a2b1As/Jczl2WdeH8Ee2yg2QpFPDp5bea3Z5/RPRZkjSIpxIcjw8jNJjNx7Qi+MEu+369I40K9N/q2OQxE+xWlkYmWx1Yl9WeATyIN2iV5+YZro33MGmpeUMRuj8IaJ+Dko8J8/Vf8gNEvqyq5K1fLKrjq2jPpAuIZIeYXfOQQmEHQA3j+mNB+EMH6dpA8xy8IT05FQy1sQccRMb5ECKlSSIEWtfrfGRsKuRNEhN94h9bAHLcdCuOKzBOYzHbkS4KLmdPPdySYUsRe0WXEkrm2K3TaaTa3Md9SXmCJF0mvxpo3T7CHLlGGzgK/OefeD69I5Cd4KqWOd57CRqZ5MUj9s9NufBaKAiiDNASYN0S7wcElUXi6Pjq+5R0NTvr3owcjl53HUwm/2QWQdMn0X+3AqxXOa65ahYvAbHRk5zFBul6/u9DhtcKZNXHDvh4/UJJaiKVQGSRVIMsbtGzjTqbowGSqYpMSksC5LHIHG0066LtWeZtrhI2lluLeBg9oo7/PDAnJZGZFJuZkh2lZf0r38UrBPQAFEv2Cj9f7/ljiEc9TNJR2FIL7xzNybbMb+TCVlbNWMu2pnZgdqcYYx4V3XKGXWZL5YFScogkYe735mtZdMeUNfI8/jttfPuOqYtd85LLWEhsxZME7ZokFvlZZ1zVCzCJNab9Cs47eHcN37DTQ0cDfFiub5eX6AGzGFJFjpJEaJIMs3oFqlo5eqGMdz2dojtyxp5KVMoCZKMQTpADFKBdt+Y0B3uGlnAAJnNwrTpThn/3oiwG7LserKyJRbbygvd3IUUaDPAZpF9CU/WnvsTf5bdFk4mcXmZ9/P6giS/FBIvaTWwso9VxYymkXGrnTf4FA0MDEl/pyRIEgbJMSXsbO2ss8mkHbGeRviMA3vlZWnVd4aJPPhSkTjZQMM6SfgO1H08LUtrP27y8I1/g319xI8XX68vQO3gPna0ePFvqaAdFrAOiuuTGrVZ0zDqazWuXSxk5f1JOZCkDBKpnXVNoG6xnbsGlavXv0p7fl6WHnBnmJCuykUQ5DOI1j9HaPmKR+4Xj9wmQQf6VX+TtBx6lNQwQqxxyRkkScYasHKGqa4yfmBsFEHk0/K/L2eEMIFyIEkZJGJt3PM+dgHfNqYZFp3b2gzDktRS6fKBhuPlrzu9FWnSPZLfwIj4d4v36FfhrCyvATg0SWHyG6rilSfoR9M7SJIeIiFVhtUYpWpp1BoUmSNtX7e0L2casyG+SgokCYNELc+34LJIxE2bcu3lPEsSYMmdksdlaadUc7qGZKBhZl0mBnm1GfByz/v6//gnEEp3qbo/yAs3gQ2YpBXeGz7KhVq83FsiG1wgy5P1fOe6vGGt3Jw1KMrmAsZ2hTXTyIeKbUiBJGGQJqmEnf7snfHx8S2ZLdZ/TWe4s9O9F0TSHeeF1tLTnhlbD0vu+VofyeEGEhp6gqNiEQyIrntfns/8e99ARolqwn/Djxc4jy7vPcnkqtLy+HaywW/6GR8xzHbH9wxHFvYFpTT11YYNYzZkiFAGJCmDJIxHz3gBQCRdoB7+qWbBu8YLwxJ/vtYjyYmmxjpOaHAJhhu8L1vM/Nn/EhklJzxe8+XFk5wXpKopkatKyx23CxGzo1TKgly48FcIQVRfGwpsuFIbsbYJv3sZkKQMkvD3/wCnjTEiiZSdk7XJ+rOelpMOS3IpDZLN7hqHy4o66CSv/Wx2AxEI0c3jkdJ1270DvNzg7cWTnBck2ZQGW02XSQrqoi9AyZgNU4NeLWGI/CILSIW2tWNztJMOrxIgqTFIx7nJ2pAkHNej1yZb8CblPYBOopxjJ5uJd2W9T8TSWuQOkiBIxWsofHebRCNguIGXV+dNzvNXTTalwRE7Sgo/QnIe+X0meOJlXLxWDQQWLHcuGKK+obU6sEUd9kmWAEmJQaKCEYwgMON4J/TsEK8T8ur5MbkiPcmZ2G3lyc6uWip13Z3cAIVAKm6+66SEFzmFSkSD4A25OdmGYGk+/uNKOXeBnb/FAj6YkW8HwNQotWcBQ2Y2VwruST60bxjsrNZ5FpIYJAmD1BI7Ur6orRLnzruTBc6KmN85z9uJS1vlZmKP98QEkq3T3GgDBgnHx23UfMdC4A2pzFW6s7y8mg5JFkedOXaO0PNv5nPtUssJDrRarVp7NA8QMurZ3FBwgL5QgzuZ69QUYYlBkjBI24QGyX8FP5jf+qDACeo1+WUXDy6IUogkS5Wu9kjgm+hmMEikKv00/MN3LATShKRKu2dDRb5tWSQNYL+ua46A+kq5EQCCW2Z2JFcTDeGszwLc8jkpHzFQQpCkDJLwwQ1ADc7fZv1WQbdROkUli48HmiXJAdLU0pc9xREE6bbnVQckUpUOQw5wLMQLtMxl5LKERsMPkJCacEVzsLK5Co6w+kqlWo5oqFQSzhL3ldprgL/6bFtNKqwQJCmDJNqkFUQjGAttqfiugm6j9J/NOq29tgSYJbkBUuNAzwS+sY5w498USMXNqD8KKKaFYyFe2emIHEhjckWxXAGUlGIUToUhZIdMa3ylLnVPBJKUQRJuwnPbbMF2AXcC8lDJWGm+PEvlEd3x6R0uOUA6XN6h7CKmQ2KQcLkFJAkYeF4AHGwvbsw1ZsjWTqRJwAxl4chJKUNQIpCUGCTOXCwtwMnZwHDFLOLnO9Y/qRqmB+c5Lb1m5AZI679ywiMZkNC07blH+30HSXDJWdFXrTuOKqUcQsjIj9ZaUbj0gmumyCAFLykLJ5Nmg7Zo9lNrMlPztd5lMxtL4uVrm72S8c2KD9Kyy/Igkhb3w0ESZyZpRgKk3PrhqFBq57LDGKF2K7pVYgTX7JY4Y0FskIRFrwCMO8Gb4JxynE40bQfG3YMluRS7q72R8c2KD9K4O5yNgneP/hdw9TgTRmKQqqPGSPo5qjgEWY5cNFaIVvA1a4oniCQMkm8cgQhCIghqt34GwSHpRNQSgSZlleQSH3ouYAfFBQl6anuZ8BxqlfLot/jRBiFIA3NdxBmiV6VUs7w4ExI0l8+1WzH14A8G6RU1BknUyfGXwM0TzLReKcPCzgc2NU7qg+PgTUklPjQOr+OAXQMFnCw3xf1bwAOJLBTLIelv/RZ3wqgmAKlkdjZ/FLH6SqVcbgQDZOZn22MRunE8BYJUFafQuYuMOI+tT3IQvcUpoW93tbwVlbBnqRfPk+YQW2YJITI1SOs6w27WzOXwT+7cKJPS8o8BHuwSScvEavNI+kfcOHdw+LuaM+od5DNEpkppKJfLZusG9uFGLScumWVgAkGSMEiBgW2oSWGDhW1leMODNkFVsXDGiXndziJaBcFwuS7Gk+s6w27UQI9QYSgHacpj04S6RNrJdFAjdoCTWrkP6Brc9n/gxbkDQSrV0zA8KgHr4+Bj8TPbbrciHwUFKwgkCYM0I2GQRDuxjNoYuNdBa8puhUhPc1xAG6ULBbnUoKvrZk0+rtoG9UhVaiBjGeSJDdhrnTvl5jMZSiwcKHb3b3LuPgiLj/O/eiBv1CV6fEeryj6cEDSXz7ctBy66Fl3hFASSIoMk2glo9e122lwik0Pc8B5ZJP3B78ukBq33QEPbcKW/oMzlv004OneXbDnILuTLZqIikn7Ds3u4MPBZXl74wKhheLqQJqIC/PkwZ7vI1VavAJCq7ykwSP7ZqkQwyW48eJB0GE8OXfD4dlB4vjazLPiq5joPNAC1uGP90r9lg2THG0YZjlzOHcpx+Mb/4dr7NN7YsywFwGgtRJ+TqFWojZipgikAJCUGSZwYDoPjIAD+wHcTe72kBZ84ud1xUrg27bby3kwyUrBwOJTJ7X/1pgMSCUHccB2Aa9Loh2Db/5hdCn3a3pglqWVhNBKuGrZQKkUdlai0AUzG+GN3/6nYRF0if5DUGCThFqhrCkxu8N2JbdUKYDPuWGoaJbSuCkjaXfZp4h+9VIGU49Z3UyDBWfzcWKPCunbu6qPN/8gpqsCapjZ3sBuo1UNZo0JtHw5DC1r1qBCB6aJ7fdVYRF07f5BeEbczlTFIgi0aqJcJNDV+0QaqTQPYbJq70dc/gacWTNJU+feTuN5QqkCqcntt/yubox+CEAQckOez2eERrBlv+fjvwe5CVJSvskIdLvYEYWv5elt6bFTZV0fZOLVWq9XO5Q3O8g6qhUMun108dTbmeyoF0nui6R8lBmkrdv3AYfmARFUqFcCVGudttLs8iZKIuO9iNZbK7s558UkVSMUxI8t5NH9EQPrX6G+S6Dw32y7xxxGZ30BZd/YL7PIgN4rVEmgAV98nbVQKgKI5tsBnLG+YMczgFtCPx+XVvXHeYfpq+t2uIfGcjNggXRFtYdcEgsPih+2onihjKD437rU6U8Cwubt7cQ54xf+iRC1lIIHca6+j9Yd4HmkP/WKllkOzLTDdzDXVn8n8X+footpp1wF/BDqGyLtmsBvcXM2bT9DKh5h8glNESO1ScKMF7xEM7QO/HXcOxTZooq+m3936UoFBEm9hkwbCdnyQnAlde9Ulr/+GUhoQSb7zUZPlt2O6wDypA8kiyeR0rt/zox/96Jl/zns4a0765iiYuhzAIGXgMOke3uuI64DNfQEN4CyDt0YzVloL6AZXM4YleCy0R8gUq6PhbK4WaphVysFB02cX98bg51Hn6AeSEoO0U5SxM1Peiv8FQOLaEmcppAK16pIHERTW46wBTX/Zn4n+0vpLIUjFxlyYcQt+TkttOxkNIJW3jun3AEi/8/faUGvfYY53/KjPjio1+MNPodzXtggI6gbXMkWNUvraAPX5iw9O2a7ZrlOnLl6cvwNjFmvtMNYJDxIt0xRxCEICJLFBEmfZCer5mnShEohfcwlwcKXjbSxzDmwwDM43SdYAKe6xKCOVIFlGqW6Yax2lGRRKFlEWUnBI+Z8Akv6AhNgumB8ZZr2ezWa//yQXo1J7XxZv64AB+mTXa8Gz3I3g1cgKlj27s+rjkJ16sPoZaQgkb5z6SiiF6vKhB9E5etQZ+oAkYZDEad+Cej6mUAncVh5IfqsuMaE7J1cVWi2TfzRJDpAyqkEqFkuzhsUSf2EfKYGDehKOrP6V1HOJQ4G52qxhtu03hrJSfbJLQcu/5AzjkMB27Np78RA0TsNrgh51tArIeBqXVx9EYpuoE/QBSWyQxAE5sUGiCpV8QHKWcHGtukTP3k5SXRpApxRO7kPSA6SMepCKxerYrAEbwneWcQAO6kkYNv8kcDswxDJRs5CxhuWm1Y2s/YW1umwbbv8FySrDxryk0SDGyczuE7bacvZPaDqkPD5OnR8fpHgM0m7qW3xAciINvqsusZ0l4YQUt5VDogOkTBQgAbXAVA1oJRqeJnBQTw78MSBpD3+LyhDuGTc3S6q0qznDJB5lX64u9Okc5X1WUqqZxmPRtWO069TFQ5ehrzci7+tVyCzxZ6uP1eFEnR4fpK+FjQ8UGCS6UAkG5E55AKAYOe86BydRiAl6/CZ4z/DsKOkBUiYqkIBaqDGvNSTPiRu6uUH6w0WeSbIDfXVkhohKph3KBitx1UM0sh/gO3c143JHY5gtD+xAhPRZF4h/CqwTFdboWNTpcUGqiAu2FRgkKi8cU+IJa9OMLJjjJNwwPk51amCqy/12dCXhAVImSpCAqq0atE0wYNyWebJg++8ncXKRbZJKQ6RQGyDkGvtUZ416ycEoH67JLze3qWYY3fzCnXqMfD0ju086rgc7CuHo5Z35QxcvXjxlqSOaqbPjgvS8AoPk0znVEVWoZFsbFwDCfTRd6yX57Wh3+Z92cbfUKFqQkCyc2qjntcXTvlwpaBzxJDgo6/9/+AkwSaDVAQmO50f5yRCWE7avz8EobCVQlZNuWzHmPuv6yp4lvp4ZAifYHWWfUx3o1R2kz8bHLdj49os6Ox5ISgwSbzkk1y6IQaLWymQBEHZNabLrJVHuHzPTNPV0cil2tuIACasBeJpDj8OFz8Zfmjhkff/E+PgdKmiNQAKdfv8uMEn/u4E6QYz5FpoO5I1hDGbNGht1UFCXM9wjmr66OTCv6Pru6ggnqJKloRyjLCXSWvzy6gOX9aROjgeSCoMkbMHl7KKftqp0UdKkROU4bbTG6B1RM02Nwwmm2NmKESSsaqvUXnOd+RfoOVnLZuGUG3xAfhnUU4haHbRNEnYr1UONjRwNeNoPjRitoiqQkGicQo0YhayhKbR5ZrEh6uQ4IMVlkMgu2MVbnAkicU2ga4VztkLCCettTawGiVb8IAHNuI7iIvpxNfN58AC/1AL8wPX8vGv90WrMkSnYQtYw5ReZZTXrWimzZOSKikFCsnECoYgQs7hCnEBWLhVjpM6NA1IsBslJw3OF45xJIHFNILuNa0f2TNPV8s8iuFehlQxIg64gi1Nm5Cw7sXnRXZjkUrVNpmD79hlG5yshl1zVvVmzGg1ISBZOOBQBMvZCZsD6aShLhRmpc/OCJNGlWMIgiSZ0nTQ8vwkiccaraxv3smR41dnG0t9MOvINlQxIroJzqpEdtRASWKRicTP/80V6CrZmGvlu2sWZI8zvu9EuRgkS0tlTJFAOzVPIVW85spxc4t9Rp+YFSdw2X8YgCUY31CSTK3vf7gApDJ/DpVmobVwWiYQbUhD5hkoIJKbifILq2zDhHNM1V4UfI2cK1vLq6t0tazdq0GYBGqTIQcLaYnl7yDyZonimSJVhQhJ1ah6QquUl0fJCMn0YBBvQlPTPZsex7mTtBSaEzmHT0zKvf/aCsyMy1kpD5BsqAZA237x97tyj/8A+BKZNJHiBDHZu092HWDlTsDmzC68O78yg8mwLYIQUG0hYlnnCoycT2qeO/L2+Op78oi+n52QvvbcUbE7EneqEBkk8QdQQskgnffurlYbIN1T8IOGekef+I3wEDEfMqsugpdAibxfOFKz1M5zvumNPlY7b7TOglxgvSEhnHZ6MbDYX2kCVcMSBOjVOsOHSl8EciDvVCSEQxvSkQt/igiiwzRnBRY1L8YNk94z8S/AA2LbFMJxHPL1rPnE7Zwo213msjla+7jyNdTRCSwIkolN7L67i8ZMF1D7LQskFzCtSIBWrXwc9xQoMkritvvhLZJ2/hHO+HcUO0jW7H8qfBN+/yrY/YRcUA3G7m+4dOFOwheHuggy2qPaWBQORmSRIWGdpoCyi1oCN8g+al/aZBpqeo86MmyJkkeT/jKowSEK3TSL0LW7OD5y/pHO+HcUO0k2nQ9dvZTJnXO+yPb7vnvOuiN62q2Atw9RWc0wtZ5DUNpCnmAKQbJ069fjiIZsowFR2BE5g10DyAyiIzGXhtCwOgFNnxs/+tkjyC8zFYpDE1bdO/6EgpSKlAStJkH7Pu4ILeH6dVnf3PIMkZwq2b8SYU9XPtOpUJY2YzoGkTmdPWaOoi6vjn91xqMIZeJ+tPrAfKurM/ErNb/k9yrEYJInRj8xasZPl7wRdrXgVO0gnHZCsr3f3tXvMHBJcW4maSQIxb1wFW6kbo+q6pdftxNX6LHollSC5tQUkiHvrmKgT8+0iZJHECwgoMEjiOIK4ttZpBx6gNDl2YUG6fu76yfvXxNv56sh1h6P/irOAOTgkqokxG21o1Y2RAnHrzI4S63w0a2KO+oi3uC5A8qq+AGIAABtwSURBVBF9PX1P+Vb5MOdRFa92dGAp+H2JsY04qNfcTZWX+ylNjl1YkBYRAtdP3zyyX7y1W/vBBJKtb/yed7VYGLSjrBTY7gT+d3XUqYJdU+fWQbXJlGzJwHO7PQ9ScYFHkpACYSxN7BseF0PSWBKvcZkqxy4kSPvP0bp+9+aJ4KRSSptPnLzNfBpw5Fk6DOaTUH9fd8J2JdNYI1WwwyrdOrhzUt1HYg0bAKTikJckcZxAZE3EvqHMXKxEVC9djl1IkE6c4+j69ZsWUAH+3pETN+/SEJ3+izfvnvxLYNVlz/Ll7oX5AEjXge0Dq4mR6UlreKRi8ohWw8BDr5yBX9kAIFkkudOFhM+4AoMkMRcrk9CaLscurGt35N7pRzyYoBavX7d8Plonr193b754GvqEcL7IvRKFO2hX3P+r8DMnwRSs3fR+yDS7S63jiYTtsnXqSNarqPMKXtW8ssSSJDZIolRTCYMkMRcrkdCaMseuo6jdtfs3r9/2YCSlu/dRDA6uMLHiXYqCDdptJt/yP1HNhWtGPYJVvEjYLpvHL2wIkIqXWJKEBkkYbxMbJIn5IYmchlbKHLsuwt9HLJz8rRNHt0/fJ5HsQbjCxKh3p+Blx21zppz+ij1/v8+Yi2KN0DwGaXhjgcSmsMZhkFriTFSZnIadKXPsup5H2m/xdFoI1KPrN0/QUT64XDxnkXLYQsjJvbtt7+BNwtGaMRvJWrujOP6NUr+LGwak4iUq8S4OgyQuGpSxWbvTk2NHpGpC9tqRI/esUdHd64xugjiEJ1AOF5jgOHYo+u386ZD4I5sjjhlTIbIqu510tFFAolJYxWHp7g2SRHKQhM1KT/GEowTqkVDNJC/wBkIQK86fDkh/HDFHdtrqxgPJSWEVDvGFBklsSySSgyQ2uZKa4glH8YOEOOISAdZ0oTy+X7dB2hMxR8UWnkjagCAVq89DMxFmlRa+xLZEIjlIYpOraamKpRU7SKhbgzfybWkaDCBX7Lrz2r9NOFr8w4g52tAg4RTW7g2SeBpVIq4tzh9KS7sTVnGDBOMMfI7m0BFNoMETKDv6B5ijfx01R8UG7iS0MUGySLryfgwGSaJH8W7xdO3WlLQ7YRUvSIPo+eRytEwOCdokVHb0v4J44B//88g5smdkNyhIFklPPx29QZKxNsIku5l09LFzK1aQauinhO/XOcc0Mdiao1Y7inp8BLXBQSq+UhY14hYFAcQGSTxPJRP6Ppz4Ci5cxQjSILY57mI+KKb36iF68T2cAxctRxsepOLu8uFAUITd7hR08bK+RFjOl7rcIKz4QBpF5mhlmvfmILuq1w1XP6qaked9SqHmRjY4SJwUVhcn3RokieGPOPSdxikkqLhAmsakTFS4b7OdVzNbWI5K0eQF0cI5QhsYJE8Kq4uTbg2SRObPTHmraJM0TiFBhQOpNSjehqNBglFmzmcH7ud2B81RxTSj5kiDVISJd74kdW+QxMW3EvXlqZxCggoH0tuZU0YtLEyVZRKunPAUIBHV2IjmOM1R37AZQb63SxgkM4f/3oggWST5eV8qDJIw80eco9Q4kM5IQyYsSOgzey+P+hLhVmXOHv2sBMULKsOHLj5+sAraOme/z9ijgRFDZXsGH2GQNlgZhVuX/HpHqjBIoliEROnsZPknSV9cP4UCiR7JfO9yfoaTd0prZvSGY2hWRvwtWSNXN4zhNhPwLpB4Q87OyI5SbVODVPTtwhqLQRL7fumrQnIUCiTv0/WTx5eXZ0fdAYTKzPTIjQl6u8ejvhiVRr0UDQyN2CvxRR6wg8Lp3xsdJEASZ8AvMkhiTCQMkhi19FUhOQrn2uXG/WMmZ1eQgr/v8fz8jZFRYssGxmYNwxhxUVRZA8svI5D6Ygg0AGGQ1nB/yA0LUrH6Y6/1aYgcNyEmEutciuehrqavCslR6PB3ZeSQip+FlRujQ7k5wzDXauycUQG4ebMWYAiurNHB+sodCIO0oZqf+MjbhVXEidiYiCkRz8WmONKQ6XAeqTL90UsKaDp1I+fqCV9oDxvGXG2gOIoNUk5Ve2+RNEiObpWvMGFoISdigyQu1rsinItNcaQh082E7ODM9LLxeG9XPxLjFTdF9RxYX2IUr1hUiWeAVLRBqm2gvnb+mmQ73qkwSCJKxB24Wk+nN9KQUZPZMJgbHR1dvjGPdHl5eXnE0vQMT6P1y9+hulVv2cFSBB/jKuFoYNhUsmyLhMZQr9US8SQ3NEhs70gVBklYYC6uVPLLaXB+anOm/Vo/+Dt/2XU9GvnoCjDiLaNojZowtnD0ySwO6kGS4Pr2mCKLoznCUU55J0j/I0OVfd21LObc08tr4M+hvO8GEYg6rQ5BAiTZNiQegySqVJrxy2mgfRZ0mS/bEeLX3NejEVm4Ik6QGhYuI3ZsofIRPICXaiBGN1drUFvhyHd8jp23RLZLkMg9fY38OXiZv0EUor6kU5CoFNZYDJK4Usk30pAvDqF/rOSKRXCVVwaL/eBn6m3rN2wNXQ9smswG2Va9YgSpZdbbTIRux0vgCA6Zs2OUAzdmmrWBuB07ZSC57qkFzhrwJi70Fwff5m0QiajT6hgkp3ekKGlbhUESJwft9q2eyDtwDEETlC827LeKKxkKpMzlYvFQRBc9RpBMk8aoUlsb/gz8yHzGbNQ26iQA0Y7PsXNAIh0iuwOJ3NPB4gX050oD/jh6NohE1Gl1DhJIYYWWRpS4o8QgiZKDGku+1RPUNTXhYt45ZIeABotmhgYp0x+ZIxAjSGNg0gis1ZjLjQyDZebybXCCZylcqnkjS2jrM7kVgBGJgJRVBBK8p2+jX0T0Vj9ng2hEnVYXIOEUVlFZqwqDJO6rH9Cngbqml2E2aM7tv1EgDUGQLgxZp9evFqk4x0itWbJSYz3fHmvY5eX2MTjDowFQXB7PVCzSAF6PYq2bpS/d9/Rtt//muemR3FPqtLoBqdgEiXcxGCRxpVIroE+D58fJuoOvMQ6c2yLl8Pn1q7zoMXcRarQskZwfu00DbuJgDY/sRZEHSlEXl7tkzwCjP5VYJOu+DeYDN8jhb1d6T6mz6gokkHj3S0KDJIJAxiCJ+0r6z/8z7nIuQy5qPm8H6Jgx0tvgP9AsFYsqI6cJdFolmmaPojpqDMO0IOTbZWOMNABhkGrdrGruuaeHQCB2KH/Bb4No7il1Vt2BZJH09HvBj7iwoYmMQRL3lQyIWtvX9PIQCSVcwPFvzJINUh4GxPORONXJgVShD6NWHJgz9qFHGQbthuLKDSLCIJEZ2e5Asu/p2zj+PXSBu0E095Q6qy5B4qawMhKGCVQYpMAkO3pKwf7FOpRHF950XY/+FeT6qZ/FSwwktt3JyhCJeleG4f/q8SR9O8IYV3AVYdfzSI4VysPfx6EVzgbR3FPqS7oFiZfCSkuBQZLpmrJX5qIP5tnQ9iHwziH6eryG/Ox+9G+1WQ6JgTTCHscDvJRYBfFUi6MqlhFZIQlbwu5Act/T/FART3G4NojknlJn1T1IFkk7/SdLFRikbeWg5kVN4Pr9QvBF951kfRtNOnim7NBPW/E1lZc9MZDcT2of5qiODFJdvAe1IiCZo9zDk1LAPUVzg94Norin1FkpAMmdwkpLiUESbTEZ3KLYfU0vUO4yeo8z930oD6Olii44UGIgLbPHMY45MhIySDZIeCJJCUgNavoP3k0eaervKXVWKkDiLX+OpcQgCbYQ1Ze7r+khihtfkIDWQAhPmZILNkwvz8+jn5pTe43vHwUPccE0kjJIxTwamw2MoK9WAtJr1N++IAGpvafUWSkBCZDEdb9iMUjbBJ3sPNd0qNjAJmwF/ZK5QCJ35VCPgIRVzRsjOJmhbxgXmCdgkOw1+/BEkhKQLjupqSg+50ea2ntKnZUakIpD/N6RCgySsJ5vprwafLYekA6BISgM7TQQUi6QrLuSs14+1G/n5KlQ0iBRyQyAI5SON2yKP6haBCTr/+BPNWOk13BU7lAOIcUhLYJ7Sp2VIpDcy58jCVcfF5sbcT3fzj8lqMX2WnmnjKL/bXQ9WNcuh98d5CSwPnzhjTfeeGFT+IueMEhjpllyOGqjQqRS3HNIQAQkPJGkKNhgl1Eg0+TZIIff5d3TTdYtfePYp+EPgzorVSDZKazMMy6qfRAbJGGz78C5WJ+Lbr0Gr/trF8j1cI2RTPD2ICdWeuzgU0jbXw573ZMFKYeTGRBHY6Oo48lI3HNIQGQV2RJyK1VF7S7DsNwgnmP3buB3T8+8sR3f04MvhO12TZ2VMpA4XViFxXgyBklUzxdnw5Mzrz5FKSRKSYJkDY/W+iiOquYIDDnEnGWHRNK/8URSwqXmDw9St3T7G+FQos5KHUje3pEqDJJoF8cD52LV6uH2p1iFuuwJgtSYM+xVkABHxZoBc1b3GfFm2SE5IOXAn8mCdMx1S7d/EObT1FkpBAmQRJffxWGQGgcC52KVinD06quv2s5AiLFSciC1qFzvAuCoWEexbzO+AnP6cAhIqLQvUZAwR9ute0pQejXEryN1VipBAiRRaMRhkCbjM0hnDlJWaNM7xChJfz4xkMYM0+7FVTEBR63kYt9FpyAJz8gmCdImhNEx8O8zZPwbwihRZ6UUpGKVSryLxSD518UqF/zJ2v6Q/PkQ/4Q9JztSSgqkmjHc53BkAnbsUEMyR0TC8Ki0L0GQzkDP4jnbBBGU3pLdAXVSakGiU1h3luMwSLGtX/4Cy5GlY8jB2y7p3iUE0ijLEagBSjTUUHRAQjOyCYL0KsuRRdZb4X4dqZNSDZJFEkoXEtobcQtiCZsWW0vITyE1D5nXzrwTxr1LBqRRO5vB5sjy9YbQhGj0q4px5YAEgu/JgQR/Gw+yQ6JNB8O4d9RJKQep+AoiSWhvxN2+JQZZsS1zCX+8XnC/+sJ2+fFpIiDZnVThkAivxzeLVigajj/NDmkOZ60OwRnZxEA6w/lttF59OcSvI3VS6kFCKaxCgyRcwELGIPk3alAsOCp91fv6w+ek3bskQGI5mkMcVdGLhViWFeOJpH+XkgXpLR9ejsn/OlInFQFIFkkHpoQGSaIPg8ggXYlvNaSDvB8vIPkfsARAGjOyNkf77PXKbc8uiUkkoHSA9Cl07HjvyP86UicVBUjFoaWnhQZJog+DwCAJs1U705lNlly/RscCYjnHJKcf4gep5cQZ+taMWZINRDy7OJvZMZqt4zkt2JcyDpA+BffU9Rr8BeSzIv3rSJ1UJCAVL323/H4wBQoM0s4/FUFy0CYS1T5GvwoM0nY/UnCSiegHLHaQqk7D1b5hJ0KXuGdnZ62iHKHIQTrzAo5qv0PfoU99nHUk8usoiN5RJxUNSMWp95YC13tVYpDU97unk+kOHrNf/iD454lE794KNEqxgzRKMghgOaz9cinhmF3cIG2ikuledbzzAIME9FAqekedVEQgFS99GVjTp8Igqc9WdSXT2d7aq0EGCegFbMZ4oyiiuEEasAMNbcOkWqmO4sWQk4rZxQySK5mO/ByeCTRIGefX8Z2g+06dVFQg+S1/jqTAIEWwXqwnKRXPvz4U+8skhzjAKMUNUg5XK/SNGHN0WKEOh/p9yXl2xTGjEhtIhCP71uJfxzeCDRIQnttACUR8UScVGUjuFFZGCgyS+vIJKpnuU+xWo4sIvQCBt0x+wA76+gJxg4RjY6U6i0yV5NmVYj4eR2wdRaQgbXK89Icv027DQYFBAsLRu4CREnVS0YHkSmGl1Vg6LOBIaJCO+67i0rHeoYxQ5swb6CIew17Ay8KPf0CSw338u0RAKowYJktMCT3Fa4bPx2JQfCCxyXSfvmP7GcfwvRUIZwz5OhrUSUUIkn/vSNGKSlIGSd3lRvqA5ihjO3rH0ABIYsaVGCWfir/4Xbtaac0wcq4a2DZawrU+G/PhULJBggcRJUgv0xxlyFjWuslw1CuxAxKp8Kn4o04qUpD8SBL2RJEwSKrLJ5BjR/NyBll2eC2fk9rHBwcDUIobpEbeMIxRz6QrmkWqxLm0mFtsHUWEIEHHjkmmQ7+Oz0mMeoneeCoAJeqkogXJTmF1UdC9QVJez/eG99oikrbLeQHoE+SyP/WqZ6wU/4Rso8XpyICGTgkGv4tO1mrUIL3q9SUQSdslRr1En5Ipke0ve5x26pwiBqm4wCEplQZpu/vHK2PbJEvSybGfEv/uqYNvsdc96XZcWAikBIPfxdhA2sQb3NqhWVGogdqPPRP13AssfdQ5RQ0Spwtr9wZJ0Oy7E73BtTuEJHGowdEmZ1L34MtUj6eUgIQe4qRKkehjiBwkOBDy2B1C0rEQezrmTOo+9xaVP0adU+QgUcufY3VvkCIoMAdXipPBiMqQngrVEcOpQ3+K3mlKQILTSEMJBr+L9sIuEYPkNxBCU0uBE+ycDz1H3VP7d5U6p+hBKu5ge0eqMEjKC8x9w6HwbsjEdxh9+pY9AWh/NiUgQdduzUign53rGCIHyXf6742wTgbUppeTBsnVhfXAkoAjCYOkvMD8HV9cAGLSNfyUPnh5O+uKpwSkURD+NhMMfhdjAgmOevm4vBPayUB7fAGbJbvAkzqnOEACXVhtK3RV2PIxAYMEU4F9cHmZX4gkoQ/eeo7yLVICUstYS6p9kK1YQDrmDdkRnTkY3snAnzwGfh/tvVLnFAtIdAqrMLKdhEF6ISAceuY5bvWXnM5ssiFMCUiWScqaSXQqphQLSO/wR71QD8N7do4+dYwZdU7xgOSksIp7ECdgkDLAZPvOuT70tGroSGkBqdg2zURDDfGA9Cnjg7l1rEMnwyXqnGICCZA0mSaDxJif4IuuSKkBKXmRpcYUg8TE4Y4FOBnKRJ1TXCDhFFYJgyRoh9d4umuD9ME7YBy6/R3bRAd5dsqkQbJFCpLUgXTmhVddk+DvBDkZqkSdU2wgocQ7oUGaEjV76NogURWTpHX3q3FcdA2SLeUgveBUkuGahzNxOBkJgWSR9Hx5q8AgiboPNZ7usieknQ2HZgSAOxDPRdcg2VIMErvaznZ4J2Euv5qBUICoc4oTpOKt75a5S806ErbD69YgvfwUK5BjH89F1yDZUguSkxFJzZe+HBCzUyfqnGIFqfr0d/2WP4/JICGOtr+x6dNNOPng4MOYLroGyZZSkDBHB489fPjByzZJBzucRw8n6pxiBalYfZJXVhGfQUKFXbifBe6YfhBWInUxryApDZItpSC9SicbfIqoehnGYTtIXggp6pziBYmTwhqnQdpkW34k1Jz2uXguugbJlkqQ0Jj3mP03MkowoBR9Y3jqnOIGqVjhLX8ej0FCRbC07XH6BkV/0TVIthSC9NDFEdV/S77gqGNR5xQ7SCDxzo8koUFa6sogveW9vISkyIPfGiRKCkF6zhtxJSTJL6bYsahzih8kJoU1ToME/WZ3GcoHsV10DZItdSDBQe87rhdxyCHE+r6dijqnBEAqXvLpHSlaMamx9PPdnPWr3LHQC3FddA2SLQJS112EYKmEt0QPrVLaxX5lRZ1TEiD5dGEVtl+dLL/SxUlv4v14ZYJKkdRKg2SLgNR1X7s3vI4dEOSLc6uVizqnREACJHlTHETtVxtLz890cdLwZ4qTUAeuehwXXYNkSxVIEBje8HbTU+F6MnQq6pySAalYfd4zHpIwSJUuQIIGiTtFtymei65BsqUKJP8G3m9Fn4QMRJ1TQiBxekdKGKRiFyAFrCjxViwXXYNkSxFI0CDxg9xnnoshDpsOkCySrjQYTsQGqQuQPnVPIVE6E31aQ0aDREkRSEG9pB9Gnx+USQlIri6sMgapC5BkVpSIVhokW4pA8mmhFqOoc0oQJKZ3pHCBCmCQOgcptjiOvzRIttSA9IE7pyF+UeeUJEiAJJLKIOp211j6utgFSAEtZeKSBsmWGpDe8R/1xiXqnBIFiUphFbVfnSwPFbsA6bnEvQANkiMlIJ3xDcPGJ+qckgXJTmEVtl898CXYvFOQYuluIpAGydZsXQFIsTTaEIg6p4RBIimsIoN0HBqkjkF6KwUXXYNkC7fjqsA+lZ2C9Fw8ucaBos4paZAskixjJGmQOgbpYOKhBg0SJbK8rQEWW+8QpDQ4GakCqdj8unxc0iB1CtLD5OM7GiRKKkB6I54qsmBR55Q8SCDxTtIgdQrSW2m46BokWypAei4FTkbKQCpWD3z3lpRB6hSkNHh2GiRHCkD6NA1ORtpAKlZ/HFzSRwxShyClwrPTIDky17oG6YU0OBmpA8l3+XOXQeoQpHRcdA2SLbz0ZTcgpcKzSyFI7hRWvkHqEKR0XHQNkq3uQYqnOa5Q1DmlBaTipG/Hu+PlV8hGHYGUkouuQbKFQcrBBTg7AimWtSbEos4pNSBxlj/H2vmevSxWRyCl5KJrkGzZIIE/OgLp5RTMxmZSChIgidena8YxSJ2BlJKLrkEiahlD3YK0Pfk8OyDqpFIEkk8XVsogdQZSSi66BomoZZS6BOlh8sn8UNRJpQkk1/LnXoPUEUgPuV244pcGiah7kGBag/I7FF7USaUKJJDC6q6T3blELRzcCUgvpOSia5CIugfp1VTEYVMMEkph9TVIHYH0TjxtoIXSIBGVMEhrHYOUjjhsmkGCKay+BqkjkLbH05FYKA0SEdOxuBOQYGu1yFeGkxB1UmkDydWFdap8i36zA5BSc9E1SERdg/RGTM1xhaJOKnUg4eXPsbaVm/R7HYD0QlouugaJqGuQ0jJESjdIxaqTeNdiDVInIL2TlouuQSLqGqS0DJFSDhKVwuoySAxIT8krDUMkDZKtfN0HpE0h7mkavPXUg2SRtLPBMUidgpSCqTsNkiNcjoRWdekQpFR46+kHqfgKTLxzG6ROQUrsQtPSIBERkGAToQ5BSoW3vg5AgimsHoPUIUhpmEXSIDlSAVIqvPX1ABIg6Ur5kutFGqRN0ko+8xtIg0RUH/EB6Yz8PU28ThOKOqnUglQcWio/736tm4XGkpYGiQhXUXhBWneiTiq9IBUvvVdxv6RB6gVpkGJW0/OKBqkXZFeal8BfGqQEpEHqAVWZlg0apCSkQeoBkSoKDVJy0iD1gDRIyUuD1APSICUvDVIPyCmQhaVmGqQEpEHqAbWNAlVprkFKQhqkHhCpotAgJScNUg9Ig5S8NEg9IALSPg1SYtIg9YBmmbo+DVIS0iD1gEgVhQYpOWmQekAapOSlQeoBaZCSlwapB0Tq+sxR+KcGKQFpkHpAbDmSBikJaZB6QBqk5KVB6gFpkJKXBmn9i9T1FYwa/FuDlIA0SOtfrioKDVIS0iCtf2mQUiAN0vpXy2iXgNoapOSkQVr/KhlEDfi3BklLqwO1ai2spI9EqTRIWloKpEHS0lIgDZKWlgJpkLS0FEiDpKWlQBokLS0F0iBpaSmQBklLS4E0SFpaCvT/A6eIrPWauOezAAAAAElFTkSuQmCC\"\ndisplay.Image(b64decode(base64_data))",
"_____no_output_____"
]
],
[
[
"# With the data you collected in lab you will use this analysis notebook to investigate synaptic connectivity and physiology. \n\n> This analysis notebook is a different interface than you have been used to working with so far. But it is necessary to explore more complex datasets. As your physiology experimental skillset expands, so must your analytic skillsets. \n\n<a id=\"one\"></a>\n## Part I. About Jupyter Notebooks\n\n\nJupyter notebooks are a way to combine executable code, code outputs, and text into one connected file. They run using a <b>'kernel'</b>, which is the thing that executes your code. It is what connects the notebook (as you see it) with the part of your computer, or the DataHub computers, that runs code.\n\n### Menu Options & Shortcuts\nThere are also a large number of useful keyboard shortcuts. Some common oens can be found at: https://towardsdatascience.com/jypyter-notebook-shortcuts-bf0101a98330.\n\n\n### Types of Cells\nJupyter Notebooks have two types of cells, a <b>Markdown</b> (like this one) and <b>Code</b>. Most of the time you won't need to run the Markdown cells, just read through them. However, when we get to a code cell, you need to tell Jupyter to run the lines of code that it contains.\n\nCode cells will be read by the kernel, which will run whatever it recognizes as code within the cell.\n\n<span style=\"color:blue\">When you're in <b>Command mode</b>, cells are outlined in blue</span>. <span style=\"color:green\">When you're in <b>Edit mode</b>, blocks are either popped out (shadowed) or outlined in green</span>.\n\n<div class=\"alert alert-success\"><b>Task:</b> Run the cell below to import necessary packages and set up the coding environment.</div>\n",
"_____no_output_____"
]
],
[
[
"# In Python, anything with a \"#\" in front of it is code annotation,\n# and is not read by the computer.\n# You can run a cell (this box) by pressing ctrl-enter or shift-enter.\n# You can also run a cell by clicking the play button in the menu bar \n# at the top of the page (single right arrow, not double).\n# Click in this cell and then press shift and enter simultaneously.\n# This print function below allows us to generate a message.\nprint('Nice work!')\n\n# No need to edit anything in this code cell\n#################################\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom scipy import ndimage\nfrom scipy.signal import find_peaks\nfrom copy import deepcopy\nimport math\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import KMeans\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport csv\nfrom scipy.signal import hilbert,medfilt,resample\nfrom sklearn.decomposition import PCA\nimport scipy\nimport seaborn as sns\ncolors = ['cyan','gray','red','green','blue','purple','orange']\nmerge_cluster_list = [[]]\n%matplotlib widget",
"_____no_output_____"
]
],
[
[
"<a id=\"two\"></a>\n## Part II. Import raw data ('.bin' file)\n### Edit the code cell below with the appropriate information, then play/execute the cell\n- **filepath** is the path to your \".bin\" data file that has simultaneous recording of muscle and nerve. \n - filepath needs to be in quotation marks.\n - ***if you are on a windows operating system computer, you need an \"r\" before the first quote of the filepath***\n- **number_channels** = the number of inputs to the analog to digital converter were recorded.\n- **nerve_channel** and **muscle_channel** which analog input channel was the nerve amplifier hooked up to? This is \"nerve_channel\" and the same logic applies to \"muscle_channel\"\n- **sampling_rate** is the sampling rate that you recorded data at\n\n### You will also get a plot of your raw data from both channels (nerve in blue and muscle in green).\n- You can interact with the plot by zooming in and panning. <br>\n- You can make the plot bigger or smaller by dragging its bottom right corner (gray triangle). Note that when it gets smaller the axis labels might disappear.\n- You can save the current plot view at any time by hitting the \"save\" icon - it will save to your Downloads folder. <br>\n\n<div class=\"alert alert-success\"><b>Task:</b> Run the cell below after editing the variables to match your data parameters.</div>",
"_____no_output_____"
]
],
[
[
"filepath = \"your file path\"\nnumber_channels = \nnerve_channel = \nmuscle_channel = \nsampling_rate = \n\n\n# No need to edit below this line\n#################################\nfilepath = Path(filepath)\ny_data = np.fromfile(Path(filepath), dtype = np.float64)\ny_data = y_data.reshape(-1,number_channels)\nnerve = y_data[:,nerve_channel] - np.median(y_data[:,nerve_channel],0)\ntime = np.linspace(0,np.shape(y_data)[0]/sampling_rate,np.shape(y_data)[0])\nmuscle = y_data[:,muscle_channel]\nhfig,ax = plt.subplots(1)\nax.plot(time, nerve, color = 'blue')\nax.plot(time, muscle, color = 'green')\nax.set_ylabel('Volts (recorded)')\nax.set_xlabel('seconds')",
"_____no_output_____"
]
],
[
[
"<a id=\"three\"></a>\n## Part III. Detect spiking events in the raw signal from the motor nerve.\n> If you ever need to restore your \"df\" dataframe, start here again and re-run the next two cells below (for example if you merge clusters you did not mean to. \n### Edit the code cell below with the appropriate information, then play/execute the cell\n- **spike_detection_threshold** is the Voltage value that peaks need to cross to be counted/detected as spikes. </br> \n- **polarity** controls whether you are detecting spikes based on the positive peaks (polarity = 1) or negative peaks (polarity = -1) </br> \n - what this does is multiply the nerve voltage trace by the value of polarity before detecting peaks based on spike threshold.\n\n### You will also get a plot of the histogram (distribution) of peak heights for all peaks (putative spikes) detected (peaks larger than the threshold you set).\n\n<div class=\"alert alert-success\"><b>Task:</b> Run the cell below after editing the variables as needed based on your raw data signal.</div>",
"_____no_output_____"
]
],
[
[
"spike_detection_threshold = \npolarity = \n\n\n\n# No need to edit below this line\n#################################\npeaks,props = find_peaks(polarity * nerve,height=spike_detection_threshold, \n prominence = spike_detection_threshold, distance=(0.00075*sampling_rate))\npeaks_t = peaks/sampling_rate\ndf = pd.DataFrame({\n 'height': props['peak_heights'],\n 'r_prom' : -nerve[peaks]+nerve[props['right_bases']],\n 'l_prom' : -nerve[peaks]+nerve[props['left_bases']]\n # 'widths' : props['widths']/fs\n })\nn,bins = np.histogram(df['height'],bins = 100) # calculate the histogram\nbins = bins[1:]\nhfig,ax = plt.subplots(1)\nax.step(bins,n)\nax.set_ylabel('count')\nax.set_xlabel('Volts')",
"_____no_output_____"
]
],
[
[
"<a id=\"four\"></a>\n## Part IV. Cluster peaks by waveform shape into putative neuron classes.\n\n### Edit the code cell below with the appropriate information, then play/execute the cell\n- **number_of_clusters** is the number of clusters you want the algorithm to make. Look at both your raw data and the histogram to decide what number you think this should be. *You will be able to combine clusters later, so it is better to over-estimate here*. </br> \n\n<div class=\"alert alert-success\"><b>Task:</b> Run the cell below after editing the variables as needed to control the clustering analyisis.</div>",
"_____no_output_____"
]
],
[
[
"number_of_clusters = \n\n\n# No need to edit below this line\n#################################\ndf_normalized=(df - df.mean()) / df.std() #normalize data in dataframe for PCA\npca = PCA(n_components=df.shape[1])\npca.fit(df_normalized)\nX_pca=pca.transform(df_normalized)\nkmeans = KMeans(n_clusters=number_of_clusters).fit(X_pca[:,0:2])\ndf['peaks_t'] = peaks_t\ndf['cluster'] = kmeans.labels_\n",
"_____no_output_____"
]
],
[
[
"<a id=\"five\"></a>\n## Part V. Plot the results of clustering to determine how many neurons you recorded.\n\n### You will get a plot of the raw voltage trace recorded from the nerve. \n- This plot incorporates your \"polarity\" to show you what happens when this value changes (with respect to the peak finding algorithm). \n- The overlaid scatter plot shows the height of each peak at the time of the peak. \n - The scatter is colored according to which cluster the spike was assigned.\n \n### You will get a plot of the mean spike waveform associated with each cluster. \n- you can change **windur** to change the amount of time before and after each spike to plot.\n \n### With these two plots, you can determine how many distinguishable (unique) neurons you think there actually are in your recording. \n\n<div class=\"alert alert-success\"><b>Task:</b> Run the cell below to plot the clustering results.</div>",
"_____no_output_____"
]
],
[
[
"windur = 0.002\n\n\n# No need to edit below this line\n#################################\nhfig,ax = plt.subplots(1)\nax.plot(time, polarity * nerve, color = 'blue')\nax.plot(time, muscle, color = 'green')\nfor i,k in enumerate(np.unique(df['cluster'])):\n df_ = df[df['cluster']==k]\n ax.scatter(df_['peaks_t'],df_['height'],color = colors[i],zorder = 3)\nax.set_ylabel('Voltage recorded (V)')\nax.set_xlabel('seconds')\nwinsamps = int(windur * sampling_rate)\nx = np.linspace(-windur,windur,winsamps*2)*1000\nhfig,ax = plt.subplots(1)\nax.set_ylabel('Volts recorded')\nax.set_xlabel('milliseconds')\nfor k in np.unique(df['cluster']):\n spkt = df.loc[df['cluster']==k]['peaks_t'].values\n spkt = spkt[(spkt>windur) & (spkt<(len((muscle)/sampling_rate)-windur))]\n print(str(len(spkt)) + \" spikes in cluster number \" + str(k))\n spkwav = np.asarray([nerve[(int(t*sampling_rate)-winsamps):(int(t*sampling_rate)+winsamps)] for t in spkt])\n wav_u = np.mean(spkwav,0)\n wav_std = np.std(spkwav,0)\n ax.plot(x,wav_u,linewidth = 3,color = colors[k])",
"_____no_output_____"
]
],
[
[
"## If there are multiple spike clusters you want to merge into a single cell class, *edit and run* the cell below.\n\n- **merge_cluster_list** = a list of the clusters (identified by numbers associated with the following colors).\n> cyan = 0,\n> gray = 1,\n> red = 2,\n> green = 3,\n> blue = 4,\n> purple = 5,\n> orange = 6\n - **For example**, the folowing list would merge clusters 0 and 2 together and 1 and 3 together: <br>\n **merge_cluster_list = [[0,2],[1,3]]**\n - For each merge group, the first cluster number listed will be the re-asigned cluster number for that group (for example, in this case you would end up with a cluster number 0 and a cluster number 1). \n \n## After running the cell below, go back up and re-plot the mean waveform for your new clusters. ",
"_____no_output_____"
]
],
[
[
"merge_cluster_list = \n\n\n\n# No need to edit below this line\n#################################\nfor k_group in merge_cluster_list:\n for k in k_group:\n df.loc[df['cluster']==k,'cluster'] = k_group[0]\nprint('you now have the following clusters: ' + str(np.unique(df['cluster'])))",
"_____no_output_____"
]
],
[
[
"<a id=\"six\"></a>\n## Part VI. Analyze the post-synaptic activity associated with pre-synaptic spikes.\n\n### Edit the code cell below with the appropriate information, then play/execute the cell.\n- **k** is the cluster number (according to the following colors list) </br> \n> cyan = 0,\n> gray = 1,\n> red = 2,\n> green = 3,\n> blue = 4,\n> purple = 5,\n> orange = 6\n\n### With this plot, you can determine which neurons have a synapse close enough to your electrode to detect the psp. \n- The mean and standard deviation are also plotted in addition to every spike-triggered membrane potential overlaid.\n\n<div class=\"alert alert-success\"><b>Task:</b> Run the cell below to plot the post-synaptic potentials triggered by spikes from cluster *k*.</div>\n",
"_____no_output_____"
]
],
[
[
"k = \n\n\n\n# No need to edit below this line\n#################################\nwindur = 0.1\nwinsamps = int(windur * sampling_rate)\nx = np.linspace(0,windur,winsamps)*1000\n# colors = ['brown','black','red','green','blue','purple','orange']\nhfig,ax = plt.subplots(1)\nax.set_ylabel('Volts recorded')\nax.set_xlabel('milliseconds')\n\nspkt = df.loc[df['cluster']==k]['peaks_t'].values\nspkt = spkt[(spkt<((len(muscle)/sampling_rate)-windur))]\nsynwav = np.asarray([muscle[(int(t*sampling_rate)):(int(t*sampling_rate)+winsamps)] - muscle[int(t*sampling_rate)] for t in spkt])\nwav_u = np.mean(synwav,0)\nwav_std = np.std(synwav,0)\nax.plot(x,synwav.T,linewidth = 0.5, alpha = 0.5,color = colors[k]);\nax.plot(x,wav_u,linewidth = 3,color = 'black')\nax.fill_between(x, wav_u-wav_std, wav_u+wav_std, alpha = 0.25, color = 'black',zorder=3);",
"_____no_output_____"
]
],
[
[
"<div class=\"alert alert-success\"><b>Task:</b> Run the cell below to plot the mean post-synaptic potentials triggered by spikes from each cluster overlaid.</div> \nYou can edit the value of windur in the first line of the code cell to change the amount of time after the spike that is plotted. \n",
"_____no_output_____"
]
],
[
[
"windur = 0.1\n\n\n\n# No need to edit below this line\n#################################\nwinsamps = int(windur * sampling_rate)\nx = np.linspace(0,windur,winsamps)*1000\nhfig,ax = plt.subplots(1)\nax.set_ylabel('Volts recorded')\nax.set_xlabel('milliseconds')\nfor k in np.unique(df['cluster']):\n spkt = df.loc[df['cluster']==k]['peaks_t'].values\n spkt = spkt[(spkt<((len(muscle)/sampling_rate)-windur))]\n synwav = np.asarray([muscle[(int(t*sampling_rate)):(int(t*sampling_rate)+winsamps)] for t in spkt])\n wav_u = np.mean(synwav,0)\n wav_std = np.std(synwav,0)\n ax.plot(x,wav_u,linewidth = 3,color = colors[k])\n# ax.fill_between(x, wav_u-wav_std, wav_u+wav_std, alpha = 0.25, color = colors[k])",
"_____no_output_____"
]
],
[
[
"### Edit the code cell below with the appropriate information, depending on which spike cluster you want to use to plot the average spike waveform and the average spike-triggered post-synaptic potential. Then play/execute the cell.\n- **k** is the cluster number (according to the following colors list) </br> \n> cyan = 0,\n> gray = 1,\n> red = 2,\n> green = 3,\n> blue = 4,\n> purple = 5,\n> orange = 6\n- **offset** is the amount of time plotted before the spike time.\n- **windur** is the amount of time plotted after the spike time. \n\n### With this plot, you can determine the average delay between the spike and the post-synaptic resposne for each neuron. \n\n<div class=\"alert alert-success\"><b>Task:</b> Run the cell below to plot the average pre- and post-synaptic potentials triggered by spikes from cluster *k*.</div>",
"_____no_output_____"
]
],
[
[
"k = \n\n# Optional parameters to change: offset (time before spike to plot) and windur (time after spike to plot)\noffset = 0.002\nwindur = 0.1\n\n\n\n# No need to edit below this line\n#################################\nwinsamps = int(windur * sampling_rate)\nhfig,ax = plt.subplots(1)\nax.set_ylabel('Volts recorded')\nax.set_xlabel('milliseconds')\nx = np.linspace(-offset,windur,(winsamps + int(offset*sampling_rate)))*1000\nspkt = df.loc[df['cluster']==k]['peaks_t'].values\nspkt = spkt[(spkt>offset)&(spkt<((len(muscle)/sampling_rate)-windur))]\nspkwav = np.asarray([nerve[(int(t*sampling_rate)-int(offset*sampling_rate)):(int(t*sampling_rate)+winsamps)] for t in spkt if (int(t*sampling_rate)+winsamps < len(muscle))])\nsynwav = np.asarray([muscle[(int(t*sampling_rate)-int(offset*sampling_rate)):(int(t*sampling_rate)+winsamps)] for t in spkt if (int(t*sampling_rate)+winsamps < len(muscle))])\nspk_u = np.mean(spkwav,0)\nspk_std = np.std(spkwav,0)\nsyn_u = np.mean(synwav,0)\nsyn_std = np.std(synwav,0)\nax.plot(x,spk_u,linewidth = 1,color = colors[k])\nax.plot(x,syn_u,linewidth = 1,color = colors[k])",
"_____no_output_____"
]
],
[
[
"<div class=\"alert alert-success\"><b>Task:</b> Celebrate your new analysis skills by running the cell below.</div>",
"_____no_output_____"
]
],
[
[
"from IPython.display import HTML\nHTML('<img src=\"https://media.giphy.com/media/l0MYt5jPR6QX5pnqM/giphy.gif\">')",
"_____no_output_____"
]
],
[
[
"<a id=\"six\"></a>\n## Take Home: Answer the following questions in a separate document to turn in.\n> *When asked to report amplitudes of events (spikes or PSPs), correct for the amplifier gain (1000x for the extracellular amplifier and 10x for the intracellular amplifier).*\n\n### Figure 1. *Synaptic connections between pre- and post-synaptic cells*\nOnly compare intracellular recordings using the same motor nerve. \n- How many motor neurons did you record spikes from?\n- Which of these neurons evoked synaptic potentials that you recorded intracellularly from the muscle cell?\n - Make note of different intracellular recording locations as needed.\n- We know that all of the 6 motor neurons in Nerve 3 synapse on the superficial flexor muscle. Were your results for each intracellular recording location consistent with this? If not, how do you explain the inconsistency? Did you see responses to different motor neurons at different intracellular recording locations?\n\n### Figure 2. *Synaptic **dynamics** - the timecourse of synaptic connectivity*\nOnly compare intracellular recordings using the same motor nerve. \n- How many motor neurons did you record spikes from? *only do this if it is different than in Figure 1, otherwise refer to Figure 1)*\n- For each panel of the figure (each PSP), annotate the following:\n - the delay between the pre-synaptic spike time and the psp\n - the psp rise time (the time from the onset of the psp to the peak of the psp)\n - the psp amplitude \n- Make it clear which panels are from the same intracellular recording and which are from different.\n\n### Figure 3. *Stereotypy of Pre to Post synaptic transformations - Does synaptic summation effect post-synaptic potential amplitude?*\nBecause you will *\"normalize\"* your data, you can combine data using different motor nerves. \n- Use recordings with distinct PSPs associated with a distinct neuron (identified by waveform amplitude).\n- Quantitative procedure for each intracellular recording:<br>\n - Measure the amplitude of 5 solitary PSPs associated with that pre-synaptic neuron. \n - Find examples of synaptic summation. Measure the amplitude of the second PSP (from PSP onset, not from resting membrane potential). Measure the latency between the onset of the first PSP and the onset of the second PSP. If there are more than two PSPs in a row, compare sequentially.\n- Analysis: \n - Within each intracellular recording, divide all amplitudes by the mean solitary PSP amplitude. This enables you to plot data from different recordings together.\n- Visualization: \n - Use a program such as google sheets or excell to make a plot of PSP amplitude versus latency (the solitary PSPs will have a latency of 100ms). \n\n### Figure 4. *Pre to post-synaptic transformations* \nIn any of your recordings *from the same motor nerve recordings*, did you see PSPs in repsponse to different neurons? (If not, then you won't have a figure - instead you will just answer the second bullet point.\n- Did either psp onset slope correlate with spike amplitude?\n - To answer this question (are they correlated) use a spreadsheet program to make a scatter plot of psp onset slope (rise time / amplitude) against spike amplitude. \n- Use what you have learned in your neuroscience courses (and what we have learned this semester in lab) to name two reasons why:\n - the PSP amplitude could be different in response to different pre-synaptic neurons\n - the PSP amplitude could be different at different intracellular recording locations (different muscle cells or different locations along the same muscle cell)\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"
] |
[
[
"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"
]
] |
4a356dc3c30742e9e3e55748cc083760c38609a6
| 57,312 |
ipynb
|
Jupyter Notebook
|
TASK 1.ipynb
|
Coder1102/TASK-1
|
1fd9071e2a4c06f971610a92e87103c1e6c5d0f3
|
[
"MIT"
] | null | null | null |
TASK 1.ipynb
|
Coder1102/TASK-1
|
1fd9071e2a4c06f971610a92e87103c1e6c5d0f3
|
[
"MIT"
] | null | null | null |
TASK 1.ipynb
|
Coder1102/TASK-1
|
1fd9071e2a4c06f971610a92e87103c1e6c5d0f3
|
[
"MIT"
] | null | null | null | 98.643718 | 31,288 | 0.84211 |
[
[
[
"# TASK 1: PREDICTION USING SUPERVISED ML",
"_____no_output_____"
],
[
"# AUTHOR: ROMAISA TARIQ",
"_____no_output_____"
]
],
[
[
"#Importing the required libraries\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline ",
"_____no_output_____"
]
],
[
[
"## Loading the dataset",
"_____no_output_____"
]
],
[
[
"\nurl= \"http://bit.ly/w-data\"\ndataset=pd.read_csv(url)\ndataset.head(5) ",
"_____no_output_____"
],
[
"dataset.describe() ",
"_____no_output_____"
],
[
"#plotting the graph\ndf=pd.DataFrame(dataset)\nax = df.plot(x='Hours', y=\"Scores\",color='green', ylabel='Percentage', xlabel='Hours Studied', \n figsize=(10, 7),style='^')\nax.xaxis.label.set_color('white')\nax.yaxis.label.set_color('white')\nax.tick_params(colors='yellow', which='both')\n\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"# # Dividing the data into features and labels",
"_____no_output_____"
]
],
[
[
"\nX=dataset.iloc[:,:-1].values #all values from the rows and values from the first column.\ny=dataset.iloc[:,1].values #all values from th row and values from the second column.",
"_____no_output_____"
]
],
[
[
"# #splitting in training and test data",
"_____no_output_____"
]
],
[
[
"\n#splitting the data into 80-20 ratio.\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, \n test_size=0.2, random_state=0) \n",
"_____no_output_____"
]
],
[
[
"# # Training the Model",
"_____no_output_____"
]
],
[
[
"\nfrom sklearn.linear_model import LinearRegression\nregress=LinearRegression()\nregress.fit(X_train,y_train)\n",
"_____no_output_____"
]
],
[
[
"# #Training and Testing Score",
"_____no_output_____"
]
],
[
[
"\nprint('Training Score',regress.score(X_train,y_train))\nprint('Testing Score',regress.score(X_test,y_test))",
"Training Score 0.9515510725211552\nTesting Score 0.9454906892105354\n"
]
],
[
[
"# #To plot the regression line",
"_____no_output_____"
]
],
[
[
"\nimport seaborn as sns\nsns.set_style('darkgrid') \nplt.figure(figsize=(10,7))\nsns.set_context('paper',font_scale=1.4) \nsns.jointplot(x='Hours',y='Scores',data=df,kind='reg')\nsns.despine(left=False)",
"_____no_output_____"
]
],
[
[
"# # Prediction",
"_____no_output_____"
]
],
[
[
"\ny_preds=regress.predict(X_test)\nprint(y_preds)\n",
"[16.88414476 33.73226078 75.357018 26.79480124 60.49103328]\n"
]
],
[
[
"# # Building comparison between actual and predicted",
"_____no_output_____"
]
],
[
[
"\ndf_2=pd.DataFrame({'Actual':y_test,'Predicted':y_preds})\ndf_2\n",
"_____no_output_____"
]
],
[
[
"# Predicting Score with given data",
"_____no_output_____"
]
],
[
[
"\nhrs=9.25\npreds_score=regress.predict([[hrs]])\nprint(\"Predicted Score if a students is studying for {}hours is: {}\".format(hrs,preds_score[0]))",
"Predicted Score if a students is studying for 9.25hours is: 93.69173248737539\n"
]
],
[
[
"# Evalutaion of the Model",
"_____no_output_____"
]
],
[
[
"\nfrom sklearn import metrics\nprint(\"Mean Absolute Error:\",metrics.mean_absolute_error(y_test,y_preds))\nprint(\"Mean Squared Error:\",metrics.mean_squared_error(y_test,y_preds))\n\n",
"Mean Absolute Error: 4.183859899002982\nMean Squared Error: 21.598769307217456\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a3578b8fbcc1aa4de7cccb9ceefbb8e99875064
| 8,335 |
ipynb
|
Jupyter Notebook
|
Chapter01/Exercise 1.05/Exercise 1.05.ipynb
|
arifmudi/The-Data-Wrangling-Workshop
|
c325f6fa1c6daf8dd22e9705df48ce2644217a73
|
[
"MIT"
] | 22 |
2020-06-27T04:21:49.000Z
|
2022-03-08T04:39:44.000Z
|
Chapter01/Exercise 1.05/Exercise 1.05.ipynb
|
arifmudi/The-Data-Wrangling-Workshop
|
c325f6fa1c6daf8dd22e9705df48ce2644217a73
|
[
"MIT"
] | 2 |
2021-02-02T22:49:16.000Z
|
2021-06-02T02:09:21.000Z
|
Chapter01/Exercise 1.05/Exercise 1.05.ipynb
|
Hubertus444/The-Data-Wrangling-Workshop
|
ddad20f8676602ac6624e72e802769fcaff45b0f
|
[
"MIT"
] | 46 |
2020-04-20T13:04:11.000Z
|
2022-03-22T05:23:52.000Z
| 21.04798 | 66 | 0.382603 |
[
[
[
"import random ",
"_____no_output_____"
],
[
"list_1 = [random.randint(0, 30) for x in range (0, 100)] \nlist_1",
"_____no_output_____"
],
[
"list_2 = [x**2 for x in list_1]\nlist_2\n",
"_____no_output_____"
],
[
"import math \nlist_2 = [math.log(x+1,10) for x in list_2]\nlist_2",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4a357c1eeda39fde211b53bdd08d03fc6a6b5411
| 658,436 |
ipynb
|
Jupyter Notebook
|
run_forecast_api.ipynb
|
janbrus/px-api-prophet
|
d118625c1a10527302339ad052aae4f753e28232
|
[
"Apache-2.0"
] | null | null | null |
run_forecast_api.ipynb
|
janbrus/px-api-prophet
|
d118625c1a10527302339ad052aae4f753e28232
|
[
"Apache-2.0"
] | null | null | null |
run_forecast_api.ipynb
|
janbrus/px-api-prophet
|
d118625c1a10527302339ad052aae4f753e28232
|
[
"Apache-2.0"
] | null | null | null | 156.509627 | 230,952 | 0.836529 |
[
[
[
"## Running Facebook Prophet model for forecasting Statistics Norway data via Statbank API",
"_____no_output_____"
],
[
"Inspired by [`Eurostat/Prophet`](https://github.com/eurostat/prophet) and [`stats_to_pandas`](https://github.com/hmelberg/stats-to-pandas). Result of internal hackathon at SSB.\n\n---------\n\nFacebook has open sourced [`Prophet`](https://facebookincubator.github.io/prophet/), a forecasting project available in `Python` and `R`.\n\nAt its core, the `Prophet` procedure is an **additive regression model** with four main components (based on [`Stan`](http://mc-stan.org) Bayesian approach):\n1. a piecewise linear (or logistic) growth curve trend: `Prophet` automatically detects changes in trends by selecting changepoints from the data,\n2. a yearly seasonal component modeled using Fourier series,\n3. a weekly seasonal component using dummy variables,\n4. a user-provided list of important holidays.\n\nWe (**make no assumption whatsoever here**, beyond the obvious seasonality of the data) use the features 1. and 2. of the model to **build forecast estimates of Statistics Norway timeseries using [*PX-API*](https://www.ssb.no/en/omssb/tjenester-og-verktoy/api/px-api) **:\n\n<img src=\"\">",
"_____no_output_____"
],
[
"We suppose here that all required packages have been already install (see `Prophet` original webpage for `Prophet`'s dependencies). Let us first import everything we need:",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\n# needed for display in notebook:\n%matplotlib notebook \nfrom matplotlib import pyplot as plt\nimport APIdata as apid #separate file\n\nimport warnings\nwarnings.filterwarnings('ignore')\n",
"_____no_output_____"
]
],
[
[
"## Testing datasets from API:",
"_____no_output_____"
]
],
[
[
"statbank = apid.API_to_data(language='en')\nstatbank.search('macro*')",
"_____no_output_____"
]
],
[
[
"Select table_id from the list above, and type between ' '",
"_____no_output_____"
]
],
[
[
"statbank = apid.API_to_data(language='en')\ntablenr = '09190' #måned eksempel: 11721, uke eksempel: 03024, kvartal eksempel: 09190, år eksempel 05803\nbox_info = statbank.select(tablenr)\nbox_info",
"_____no_output_____"
]
],
[
[
"Run next cell when info is saved.",
"_____no_output_____"
]
],
[
[
"[df, label] = statbank.read_box(box_info)\ndf",
"_____no_output_____"
]
],
[
[
"The table contains exactly the data we need, let us store it into a `pandas.DataFrame` object as desired. As already mentioned, the input to `Prophet` is always a `pandas.DataFrame` object, and it must contain two columns: `ds` and `y`. ",
"_____no_output_____"
]
],
[
[
"[df, f, periods] = statbank.prepare_dataframe(df=df)\ndf.head()",
"_____no_output_____"
],
[
"type(df)",
"_____no_output_____"
],
[
"df.sort_values('ds', inplace=True)\nds_last = df['ds'].values[-1]\nxlabel = \"Time\"\nylabel = \"Value\" \nplt.plot(df['ds'], df['y'], 'k.')\nplt.plot(df['ds'], df['y'], ls='-', c='#0072B2')\nplt.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)\nplt.xlabel(xlabel, fontsize=10); #plt.ylabel(ylabel, fontsize=10)\nplt.suptitle(\" {}, Table: {} (last: {})\".format(label, tablenr, ds_last), fontsize=14, y=1.03)\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"Considering the trend observed in the data, we define the regression model for `Prophet` by instantiating a new `Prophet` model as follows:",
"_____no_output_____"
],
[
"Growth can be set to 'linear' eller 'logistic'. \nPossible to add parameter: seasonality_mode='additive' (default) or 'multiplicative'.\nPossible to set Markov chain Monte Carlo (MCMC), e.g. mcmc_samples=300",
"_____no_output_____"
]
],
[
[
"from fbprophet import Prophet\nnyears=4\nm = Prophet(growth = 'linear', weekly_seasonality=False, yearly_seasonality=True, daily_seasonality=False) ",
"_____no_output_____"
]
],
[
[
"We then call its `fit` method and pass in the historical dataframe built earlier:",
"_____no_output_____"
],
[
"We extend the data into the future by a specified number periods using the `make_future_dataframe` method. Say that we consider to predict the time-series over the 4 next years:",
"_____no_output_____"
]
],
[
[
"m.fit(df)\nfuture = m.make_future_dataframe(periods=periods*nyears, freq=f)\nfcst = m.predict(future)",
"_____no_output_____"
]
],
[
[
"Let us plot the forecast estimates calculated by the `Prophet` model:",
"_____no_output_____"
]
],
[
[
"m.plot(fcst, uncertainty=True)\nxlabel = \"Time\"\nylabel = \"Value\" \nplt.axvline(pd.to_datetime(ds_last), color='r', linestyle='--', lw=2)\nplt.xlabel(xlabel, fontsize=10); plt.ylabel(ylabel, fontsize=10)\nplt.suptitle(\" {} {} forecast data ({} years)\".format(tablenr, label, nyears), fontsize=14, y=1.05)\nplt.legend()\nplt.show()\nplt.savefig(\"{}_{}y.svg\".format(tablenr, nyears))",
"_____no_output_____"
]
],
[
[
"`Prophet` also provides with the components (overall trend and yearly profile) of the time-series:",
"_____no_output_____"
]
],
[
[
"fig = m.plot_components(fcst, uncertainty=True)\nfig.suptitle(\"Forecast components\", fontsize=16, y=1.02)\nplt.show()",
"_____no_output_____"
],
[
"result = pd.concat([fcst[['ds', 'yhat', 'yhat_lower', 'yhat_upper']], df['y']], axis=1)\nresult",
"_____no_output_____"
],
[
"result.tail()",
"_____no_output_____"
],
[
"result.to_csv(\"{}_{}y.csv\".format(tablenr, nyears), sep = ';', decimal = ',')",
"_____no_output_____"
],
[
"# result.to_excel(\"{}_{}y.xlsx\".format(tablenr, nyears))",
"_____no_output_____"
]
],
[
[
"**-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------**",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
4a35989a0ead398b2646f6fe7494fa534d699cda
| 471,687 |
ipynb
|
Jupyter Notebook
|
nbs/output.ipynb
|
gidden/cyclopts
|
e346b1721c8d8722af2862823844ab2e7864141b
|
[
"BSD-3-Clause"
] | null | null | null |
nbs/output.ipynb
|
gidden/cyclopts
|
e346b1721c8d8722af2862823844ab2e7864141b
|
[
"BSD-3-Clause"
] | 6 |
2015-01-26T18:31:36.000Z
|
2015-02-24T18:28:41.000Z
|
nbs/output.ipynb
|
gidden/cyclopts
|
e346b1721c8d8722af2862823844ab2e7864141b
|
[
"BSD-3-Clause"
] | null | null | null | 530.581552 | 58,649 | 0.925747 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4a35b108c6c20651966028c9612a63294c0df2bf
| 588,942 |
ipynb
|
Jupyter Notebook
|
assignment1/two_layer_net.ipynb
|
vinx13/CS231n
|
7d6cbc6322d7f0c84487a90c69d92218823dd6a4
|
[
"MIT"
] | null | null | null |
assignment1/two_layer_net.ipynb
|
vinx13/CS231n
|
7d6cbc6322d7f0c84487a90c69d92218823dd6a4
|
[
"MIT"
] | null | null | null |
assignment1/two_layer_net.ipynb
|
vinx13/CS231n
|
7d6cbc6322d7f0c84487a90c69d92218823dd6a4
|
[
"MIT"
] | null | null | null | 856.020349 | 265,752 | 0.940385 |
[
[
[
"# Implementing a Neural Network\nIn this exercise we will develop a neural network with fully-connected layers to perform classification, and test it out on the CIFAR-10 dataset.",
"_____no_output_____"
]
],
[
[
"# A bit of setup\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom cs231n.classifiers.neural_net import TwoLayerNet\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n# for auto-reloading external modules\n# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n%load_ext autoreload\n%autoreload 2\n\ndef rel_error(x, y):\n \"\"\" returns relative error \"\"\"\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))",
"_____no_output_____"
]
],
[
[
"We will use the class `TwoLayerNet` in the file `cs231n/classifiers/neural_net.py` to represent instances of our network. The network parameters are stored in the instance variable `self.params` where keys are string parameter names and values are numpy arrays. Below, we initialize toy data and a toy model that we will use to develop your implementation.",
"_____no_output_____"
]
],
[
[
"# Create a small net and some toy data to check your implementations.\n# Note that we set the random seed for repeatable experiments.\n\ninput_size = 4\nhidden_size = 10\nnum_classes = 3\nnum_inputs = 5\n\ndef init_toy_model():\n np.random.seed(0)\n return TwoLayerNet(input_size, hidden_size, num_classes, std=1e-1)\n\ndef init_toy_data():\n np.random.seed(1)\n X = 10 * np.random.randn(num_inputs, input_size)\n y = np.array([0, 1, 2, 2, 1])\n return X, y\n\nnet = init_toy_model()\nX, y = init_toy_data()",
"_____no_output_____"
]
],
[
[
"# Forward pass: compute scores\nOpen the file `cs231n/classifiers/neural_net.py` and look at the method `TwoLayerNet.loss`. This function is very similar to the loss functions you have written for the SVM and Softmax exercises: It takes the data and weights and computes the class scores, the loss, and the gradients on the parameters. \n\nImplement the first part of the forward pass which uses the weights and biases to compute the scores for all inputs.",
"_____no_output_____"
]
],
[
[
"scores = net.loss(X)\nprint 'Your scores:'\nprint scores\nprint\nprint 'correct scores:'\ncorrect_scores = np.asarray([\n [-0.81233741, -1.27654624, -0.70335995],\n [-0.17129677, -1.18803311, -0.47310444],\n [-0.51590475, -1.01354314, -0.8504215 ],\n [-0.15419291, -0.48629638, -0.52901952],\n [-0.00618733, -0.12435261, -0.15226949]])\nprint correct_scores\nprint\n\n# The difference should be very small. We get < 1e-7\nprint 'Difference between your scores and correct scores:'\nprint np.sum(np.abs(scores - correct_scores))",
"Your scores:\n[[-0.81233741 -1.27654624 -0.70335995]\n [-0.17129677 -1.18803311 -0.47310444]\n [-0.51590475 -1.01354314 -0.8504215 ]\n [-0.15419291 -0.48629638 -0.52901952]\n [-0.00618733 -0.12435261 -0.15226949]]\n\ncorrect scores:\n[[-0.81233741 -1.27654624 -0.70335995]\n [-0.17129677 -1.18803311 -0.47310444]\n [-0.51590475 -1.01354314 -0.8504215 ]\n [-0.15419291 -0.48629638 -0.52901952]\n [-0.00618733 -0.12435261 -0.15226949]]\n\nDifference between your scores and correct scores:\n3.68027207103e-08\n"
]
],
[
[
"# Forward pass: compute loss\nIn the same function, implement the second part that computes the data and regularizaion loss.",
"_____no_output_____"
]
],
[
[
"loss, _ = net.loss(X, y, reg=0.1)\ncorrect_loss = 1.30378789133\n\n# should be very small, we get < 1e-12\nprint 'Difference between your loss and correct loss:'\nprint np.sum(np.abs(loss - correct_loss))",
"Difference between your loss and correct loss:\n1.79856129989e-13\n"
]
],
[
[
"# Backward pass\nImplement the rest of the function. This will compute the gradient of the loss with respect to the variables `W1`, `b1`, `W2`, and `b2`. Now that you (hopefully!) have a correctly implemented forward pass, you can debug your backward pass using a numeric gradient check:",
"_____no_output_____"
]
],
[
[
"from cs231n.gradient_check import eval_numerical_gradient\n\n# Use numeric gradient checking to check your implementation of the backward pass.\n# If your implementation is correct, the difference between the numeric and\n# analytic gradients should be less than 1e-8 for each of W1, W2, b1, and b2.\n\nloss, grads = net.loss(X, y, reg=0.1)\n\n# these should all be less than 1e-8 or so\nfor param_name in grads:\n f = lambda W: net.loss(X, y, reg=0.1)[0]\n param_grad_num = eval_numerical_gradient(f, net.params[param_name], verbose=False)\n print '%s max relative error: %e' % (param_name, rel_error(param_grad_num, grads[param_name]))",
"b2 max relative error: 1.674230e-10\nW2 max relative error: 4.791408e-09\nW1 max relative error: 1.580785e-09\nb1 max relative error: 1.055518e-08\n"
]
],
[
[
"# Train the network\nTo train the network we will use stochastic gradient descent (SGD), similar to the SVM and Softmax classifiers. Look at the function `TwoLayerNet.train` and fill in the missing sections to implement the training procedure. This should be very similar to the training procedure you used for the SVM and Softmax classifiers. You will also have to implement `TwoLayerNet.predict`, as the training process periodically performs prediction to keep track of accuracy over time while the network trains.\n\nOnce you have implemented the method, run the code below to train a two-layer network on toy data. You should achieve a training loss less than 0.2.",
"_____no_output_____"
]
],
[
[
"net = init_toy_model()\nstats = net.train(X, y, X, y,\n learning_rate=1e-1, reg=1e-5,\n num_iters=100, verbose=False)\n\nprint 'Final training loss: ', stats['loss_history'][-1]\n\n# plot the loss history\nplt.plot(stats['loss_history'])\nplt.xlabel('iteration')\nplt.ylabel('training loss')\nplt.title('Training Loss history')\nplt.show()",
"Final training loss: 0.0171496079387\n"
]
],
[
[
"# Load the data\nNow that you have implemented a two-layer network that passes gradient checks and works on toy data, it's time to load up our favorite CIFAR-10 data so we can use it to train a classifier on a real dataset.",
"_____no_output_____"
]
],
[
[
"from cs231n.data_utils import load_CIFAR10\n\ndef get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000):\n \"\"\"\n Load the CIFAR-10 dataset from disk and perform preprocessing to prepare\n it for the two-layer neural net classifier. These are the same steps as\n we used for the SVM, but condensed to a single function. \n \"\"\"\n # Load the raw CIFAR-10 data\n cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'\n X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)\n \n # Subsample the data\n mask = range(num_training, num_training + num_validation)\n X_val = X_train[mask]\n y_val = y_train[mask]\n mask = range(num_training)\n X_train = X_train[mask]\n y_train = y_train[mask]\n mask = range(num_test)\n X_test = X_test[mask]\n y_test = y_test[mask]\n\n # Normalize the data: subtract the mean image\n mean_image = np.mean(X_train, axis=0)\n X_train -= mean_image\n X_val -= mean_image\n X_test -= mean_image\n\n # Reshape data to rows\n X_train = X_train.reshape(num_training, -1)\n X_val = X_val.reshape(num_validation, -1)\n X_test = X_test.reshape(num_test, -1)\n\n return X_train, y_train, X_val, y_val, X_test, y_test\n\n\n# Invoke the above function to get our data.\nX_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data()\nprint 'Train data shape: ', X_train.shape\nprint 'Train labels shape: ', y_train.shape\nprint 'Validation data shape: ', X_val.shape\nprint 'Validation labels shape: ', y_val.shape\nprint 'Test data shape: ', X_test.shape\nprint 'Test labels shape: ', y_test.shape",
"Train data shape: (49000, 3072)\nTrain labels shape: (49000,)\nValidation data shape: (1000, 3072)\nValidation labels shape: (1000,)\nTest data shape: (1000, 3072)\nTest labels shape: (1000,)\n"
]
],
[
[
"# Train a network\nTo train our network we will use SGD with momentum. In addition, we will adjust the learning rate with an exponential learning rate schedule as optimization proceeds; after each epoch, we will reduce the learning rate by multiplying it by a decay rate.",
"_____no_output_____"
]
],
[
[
"input_size = 32 * 32 * 3\nhidden_size = 50\nnum_classes = 10\nnet = TwoLayerNet(input_size, hidden_size, num_classes)\n\n# Train the network\nstats = net.train(X_train, y_train, X_val, y_val,\n num_iters=1000, batch_size=200,\n learning_rate=1e-4, learning_rate_decay=0.95,\n reg=0.5, verbose=True)\n\n# Predict on the validation set\nval_acc = (net.predict(X_val) == y_val).mean()\nprint 'Validation accuracy: ', val_acc\n\n",
"iteration 0 / 1000: loss 2.302954\niteration 100 / 1000: loss 2.302550\niteration 200 / 1000: loss 2.297648\niteration 300 / 1000: loss 2.259602\niteration 400 / 1000: loss 2.204170\niteration 500 / 1000: loss 2.118565\niteration 600 / 1000: loss 2.051535\niteration 700 / 1000: loss 1.988466\niteration 800 / 1000: loss 2.006591\niteration 900 / 1000: loss 1.951473\nValidation accuracy: 0.287\n"
]
],
[
[
"# Debug the training\nWith the default parameters we provided above, you should get a validation accuracy of about 0.29 on the validation set. This isn't very good.\n\nOne strategy for getting insight into what's wrong is to plot the loss function and the accuracies on the training and validation sets during optimization.\n\nAnother strategy is to visualize the weights that were learned in the first layer of the network. In most neural networks trained on visual data, the first layer weights typically show some visible structure when visualized.",
"_____no_output_____"
]
],
[
[
"# Plot the loss function and train / validation accuracies\nplt.subplot(2, 1, 1)\nplt.plot(stats['loss_history'])\nplt.title('Loss history')\nplt.xlabel('Iteration')\nplt.ylabel('Loss')\n\nplt.subplot(2, 1, 2)\nplt.plot(stats['train_acc_history'], label='train')\nplt.plot(stats['val_acc_history'], label='val')\nplt.title('Classification accuracy history')\nplt.xlabel('Epoch')\nplt.ylabel('Clasification accuracy')\nplt.show()",
"_____no_output_____"
],
[
"from cs231n.vis_utils import visualize_grid\n\n# Visualize the weights of the network\n\ndef show_net_weights(net):\n W1 = net.params['W1']\n W1 = W1.reshape(32, 32, 3, -1).transpose(3, 0, 1, 2)\n plt.imshow(visualize_grid(W1, padding=3).astype('uint8'))\n plt.gca().axis('off')\n plt.show()\n\nshow_net_weights(net)",
"_____no_output_____"
]
],
[
[
"# Tune your hyperparameters\n\n**What's wrong?**. Looking at the visualizations above, we see that the loss is decreasing more or less linearly, which seems to suggest that the learning rate may be too low. Moreover, there is no gap between the training and validation accuracy, suggesting that the model we used has low capacity, and that we should increase its size. On the other hand, with a very large model we would expect to see more overfitting, which would manifest itself as a very large gap between the training and validation accuracy.\n\n**Tuning**. Tuning the hyperparameters and developing intuition for how they affect the final performance is a large part of using Neural Networks, so we want you to get a lot of practice. Below, you should experiment with different values of the various hyperparameters, including hidden layer size, learning rate, numer of training epochs, and regularization strength. You might also consider tuning the learning rate decay, but you should be able to get good performance using the default value.\n\n**Approximate results**. You should be aim to achieve a classification accuracy of greater than 48% on the validation set. Our best network gets over 52% on the validation set.\n\n**Experiment**: You goal in this exercise is to get as good of a result on CIFAR-10 as you can, with a fully-connected Neural Network. For every 1% above 52% on the Test set we will award you with one extra bonus point. Feel free implement your own techniques (e.g. PCA to reduce dimensionality, or adding dropout, or adding features to the solver, etc.).",
"_____no_output_____"
]
],
[
[
"best_net = None # store the best model into this \n\n#################################################################################\n# TODO: Tune hyperparameters using the validation set. Store your best trained #\n# model in best_net. #\n# #\n# To help debug your network, it may help to use visualizations similar to the #\n# ones we used above; these visualizations will have significant qualitative #\n# differences from the ones we saw above for the poorly tuned network. #\n# #\n# Tweaking hyperparameters by hand can be fun, but you might find it useful to #\n# write code to sweep through possible combinations of hyperparameters #\n# automatically like we did on the previous exercises. #\n#################################################################################\n\nlearning_rates = [50e-5, 52e-5, 54e-5, 56e-5, 58e-5, 60e-5]\nregs = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\nbest_lr = -1\nbest_reg = -1\nbest_acc = -1\nfor lr in learning_rates:\n for reg in regs:\n net = TwoLayerNet(input_size, hidden_size, num_classes)\n # Train the network\n stats = net.train(X_train, y_train, X_val, y_val,\n num_iters=1000, batch_size=200,\n learning_rate=lr, learning_rate_decay=0.95,\n reg=reg, verbose=False)\n # Predict on the validation set\n val_acc = (net.predict(X_val) == y_val).mean()\n print 'Validation accuracy: ', val_acc\n if val_acc > best_acc:\n best_acc = val_acc\n best_lr = lr\n best_reg = reg\n best_net = net\n print \"\"\n#################################################################################\n# END OF YOUR CODE #\n#################################################################################",
"Validation accuracy: 0.451\nValidation accuracy: 0.447\nValidation accuracy: 0.46\nValidation accuracy: 0.455\nValidation accuracy: 0.45\nValidation accuracy: 0.445\nValidation accuracy: 0.454\nValidation accuracy: 0.446\nValidation accuracy: 0.44\n\nValidation accuracy: 0.443\nValidation accuracy: 0.45\nValidation accuracy: 0.455\nValidation accuracy: 0.447\nValidation accuracy: 0.46\nValidation accuracy: 0.447\nValidation accuracy: 0.453\nValidation accuracy: 0.449\nValidation accuracy: 0.454\n\nValidation accuracy: 0.451\nValidation accuracy: 0.457\nValidation accuracy: 0.458\nValidation accuracy: 0.443\nValidation accuracy: 0.452\nValidation accuracy: 0.443\nValidation accuracy: 0.452\nValidation accuracy: 0.448\nValidation accuracy: 0.448\n\nValidation accuracy: 0.45\nValidation accuracy: 0.465\nValidation accuracy: 0.453\nValidation accuracy: 0.46\nValidation accuracy: 0.439\nValidation accuracy: 0.448\nValidation accuracy: 0.445\nValidation accuracy: 0.44\nValidation accuracy: 0.454\n\nValidation accuracy: 0.448\nValidation accuracy: 0.452\nValidation accuracy: 0.471\nValidation accuracy: 0.458\nValidation accuracy: 0.441\nValidation accuracy: 0.453\nValidation accuracy: 0.448\nValidation accuracy: 0.453\nValidation accuracy: 0.455\n\nValidation accuracy: 0.452\nValidation accuracy: 0.442\nValidation accuracy: 0.457\nValidation accuracy: 0.461\nValidation accuracy: 0.465\nValidation accuracy: 0.462\nValidation accuracy: 0.469\nValidation accuracy: 0.457\nValidation accuracy: 0.455\n\n"
],
[
"# visualize the weights of the best network\nshow_net_weights(best_net)",
"_____no_output_____"
]
],
[
[
"# Run on the test set\nWhen you are done experimenting, you should evaluate your final trained network on the test set; you should get above 48%.\n\n**We will give you extra bonus point for every 1% of accuracy above 52%.**",
"_____no_output_____"
]
],
[
[
"test_acc = (best_net.predict(X_test) == y_test).mean()\nprint 'Test accuracy: ', test_acc",
"Test accuracy: 0.455\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a35b30656f7e8ca96308a7d7300f4a85ba6f998
| 19,677 |
ipynb
|
Jupyter Notebook
|
site/en/r2/guide/keras/masking_and_padding.ipynb
|
crypdra/docs
|
41ab06fd14b3a3dff933bb80b19ce46c7c5781cf
|
[
"Apache-2.0"
] | 2 |
2019-10-25T18:51:16.000Z
|
2019-10-25T18:51:18.000Z
|
site/en/r2/guide/keras/masking_and_padding.ipynb
|
crypdra/docs
|
41ab06fd14b3a3dff933bb80b19ce46c7c5781cf
|
[
"Apache-2.0"
] | null | null | null |
site/en/r2/guide/keras/masking_and_padding.ipynb
|
crypdra/docs
|
41ab06fd14b3a3dff933bb80b19ce46c7c5781cf
|
[
"Apache-2.0"
] | null | null | null | 35.32675 | 405 | 0.527215 |
[
[
[
"##### Copyright 2019 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Masking and padding in Keras\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/beta/guide/keras/masking_and_padding\">\n <img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />\n View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/guide/keras/masking_and_padding.ipynb\">\n <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/r2/guide/keras/masking_and_padding.ipynb\">\n <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n View source on GitHub</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/r2/guide/keras/masking_and_padding.ipynb\">\n <img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />\n Download notebook</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport numpy as np\n\ntry:\n # %tensorflow_version only exists in Colab.\n %tensorflow_version 2.x\nexcept Exception:\n pass\nimport tensorflow as tf\n\nfrom tensorflow.keras import layers",
"_____no_output_____"
]
],
[
[
"## Padding sequence data\n\nWhen processing sequence data, it is very common for individual samples to have different lengths. Consider the following example (text tokenized as words):\n\n```\n[\n [\"The\", \"weather\", \"will\", \"be\", \"nice\", \"tomorrow\"],\n [\"How\", \"are\", \"you\", \"doing\", \"today\"],\n [\"Hello\", \"world\", \"!\"]\n]\n```\n\nAfter vocabulary lookup, the data might be vectorized as integers, e.g.:\n\n```\n[\n [83, 91, 1, 645, 1253, 927],\n [73, 8, 3215, 55, 927],\n [71, 1331, 4231]\n]\n```\n\nThe data is a 2D list where individual samples have length 6, 5, and 3 respectively. Since the input data for a deep learning model must be a single tensor (of shape e.g. `(batch_size, 6, vocab_size)` in this case), samples that are shorter than the longest item need to be padded with some placeholder value (alternatively, one might also truncate long samples before padding short samples).\n\nKeras provides an API to easily truncate and pad sequences to a common length: `tf.keras.preprocessing.sequence.pad_sequences`.",
"_____no_output_____"
]
],
[
[
"raw_inputs = [\n [83, 91, 1, 645, 1253, 927],\n [73, 8, 3215, 55, 927],\n [711, 632, 71]\n]\n\n# By default, this will pad using 0s; it is configurable via the\n# \"value\" parameter.\n# Note that you could \"pre\" padding (at the beginning) or\n# \"post\" padding (at the end).\n# We recommend using \"post\" padding when working with RNN layers\n# (in order to be able to use the \n# CuDNN implementation of the layers).\npadded_inputs = tf.keras.preprocessing.sequence.pad_sequences(raw_inputs,\n padding='post')\n\nprint(padded_inputs)",
"_____no_output_____"
]
],
[
[
"## Masking",
"_____no_output_____"
],
[
"Now that all samples have a uniform length, the model must be informed that some part of the data is actually padding and should be ignored. That mechanism is <b>masking</b>.\n\nThere are three ways to introduce input masks in Keras models:\n- Add a `keras.layers.Masking` layer.\n- Configure a `keras.layers.Embedding` layer with `mask_zero=True`.\n- Pass a `mask` argument manually when calling layers that support this argument (e.g. RNN layers).",
"_____no_output_____"
],
[
"## Mask-generating layers: `Embedding` and `Masking`\n\nUnder the hood, these layers will create a mask tensor (2D tensor with shape `(batch, sequence_length)`), and attach it to the tensor output returned by the `Masking` or `Embedding` layer.",
"_____no_output_____"
]
],
[
[
"embedding = layers.Embedding(input_dim=5000, output_dim=16, mask_zero=True)\nmasked_output = embedding(padded_inputs)\n\nprint(masked_output._keras_mask)\n",
"_____no_output_____"
],
[
"masking_layer = layers.Masking()\n# Simulate the embedding lookup by expanding the 2D input to 3D,\n# with embedding dimension of 10.\nunmasked_embedding = tf.cast(\n tf.tile(tf.expand_dims(padded_inputs, axis=-1), [1, 1, 10]),\n tf.float32)\n\nmasked_embedding = masking_layer(unmasked_embedding)\nprint(masked_embedding._keras_mask)",
"_____no_output_____"
]
],
[
[
"As you can see from the printed result, the mask is a 2D boolean tensor with shape `(batch_size, sequence_length)`, where each individual `False` entry indicates that the corresponding timestep should be ignored during processing.",
"_____no_output_____"
],
[
"## Mask propagation in the Functional API and Sequential API",
"_____no_output_____"
],
[
"When using the Functional API or the Sequential API, a mask generated by an `Embedding` or `Masking` layer will be propagated through the network for any layer that is capable of using them (for example, RNN layers). Keras will automatically fetch the mask corresponding to an input and pass it to any layer that knows how to use it.\n\nNote that in the `call` method of a subclassed model or layer, masks aren't automatically propagated, so you will need to manually pass a `mask` argument to any layer that needs one. See the section below for details.\n\nFor instance, in the following Sequential model, the `LSTM` layer will automatically receive a mask, which means it will ignore padded values:",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential([\n layers.Embedding(input_dim=5000, output_dim=16, mask_zero=True),\n layers.LSTM(32),\n])",
"_____no_output_____"
]
],
[
[
"This is also the case for the following Functional API model:",
"_____no_output_____"
]
],
[
[
"inputs = tf.keras.Input(shape=(None,), dtype='int32')\nx = layers.Embedding(input_dim=5000, output_dim=16, mask_zero=True)(inputs)\noutputs = layers.LSTM(32)(x)\n\nmodel = tf.keras.Model(inputs, outputs)",
"_____no_output_____"
]
],
[
[
"## Passing mask tensors directly to layers",
"_____no_output_____"
],
[
"Layers that can handle masks (such as the `LSTM` layer) have a `mask` argument in their `__call__` method.\n\nMeanwhile, layers that produce a mask (e.g. `Embedding`) expose a `compute_mask(input, previous_mask)` method which you can call.\n\nThus, you can do something like this:\n\n",
"_____no_output_____"
]
],
[
[
"class MyLayer(layers.Layer):\n \n def __init__(self, **kwargs):\n super(MyLayer, self).__init__(**kwargs)\n self.embedding = layers.Embedding(input_dim=5000, output_dim=16, mask_zero=True)\n self.lstm = layers.LSTM(32)\n \n def call(self, inputs):\n x = self.embedding(inputs)\n # Note that you could also prepare a `mask` tensor manually.\n # It only needs to be a boolean tensor\n # with the right shape, i.e. (batch_size, timesteps).\n mask = self.embedding.compute_mask(inputs)\n output = self.lstm(x, mask=mask) # The layer will ignore the masked values\n return output\n\nlayer = MyLayer()\nx = np.random.random((32, 10)) * 100\nx = x.astype('int32')\nlayer(x)",
"_____no_output_____"
]
],
[
[
"## Supporting masking in your custom layers",
"_____no_output_____"
],
[
"Sometimes you may need to write layers that generate a mask (like `Embedding`), or layers that need to modify the current mask.\n\nFor instance, any layer that produces a tensor with a different time dimension than its input, such as a `Concatenate` layer that concatenates on the time dimension, will need to modify the current mask so that downstream layers will be able to properly take masked timesteps into account.\n\nTo do this, your layer should implement the `layer.compute_mask()` method, which produces a new mask given the input and the current mask. \n\nMost layers don't modify the time dimension, so don't need to worry about masking. The default behavior of `compute_mask()` is just pass the current mask through in such cases.\n\nHere is an example of a `TemporalSplit` layer that needs to modify the current mask.",
"_____no_output_____"
]
],
[
[
"class TemporalSplit(tf.keras.layers.Layer):\n \"\"\"Split the input tensor into 2 tensors along the time dimension.\"\"\"\n\n def call(self, inputs):\n # Expect the input to be 3D and mask to be 2D, split the input tensor into 2\n # subtensors along the time axis (axis 1).\n return tf.split(inputs, 2, axis=1)\n \n def compute_mask(self, inputs, mask=None):\n # Also split the mask into 2 if it presents.\n if mask is None:\n return None\n return tf.split(mask, 2, axis=1)\n\nfirst_half, second_half = TemporalSplit()(masked_embedding)\nprint(first_half._keras_mask)\nprint(second_half._keras_mask)\n",
"_____no_output_____"
]
],
[
[
"Here is another example of a `CustomEmbedding` layer that is capable of generating a mask from input values:",
"_____no_output_____"
]
],
[
[
"class CustomEmbedding(tf.keras.layers.Layer):\n \n def __init__(self, input_dim, output_dim, mask_zero=False, **kwargs):\n super(CustomEmbedding, self).__init__(**kwargs)\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.mask_zero = mask_zero\n \n def build(self, input_shape):\n self.embeddings = self.add_weight(\n shape=(self.input_dim, self.output_dim),\n initializer='random_normal',\n dtype='float32')\n \n def call(self, inputs):\n return tf.nn.embedding_lookup(self.embeddings, inputs)\n \n def compute_mask(self, inputs, mask=None):\n if not self.mask_zero:\n return None\n return tf.not_equal(inputs, 0)\n \n \nlayer = CustomEmbedding(10, 32, mask_zero=True)\nx = np.random.random((3, 10)) * 9\nx = x.astype('int32')\n\ny = layer(x)\nmask = layer.compute_mask(x)\n\nprint(mask)",
"_____no_output_____"
]
],
[
[
"## Writing layers that need mask information\n\nSome layers are mask *consumers*: they accept a `mask` argument in `call` and use it to dertermine whether to skip certain time steps.\n\nTo write such a layer, you can simply add a `mask=None` argument in your `call` signature. The mask associated with the inputs will be passed to your layer whenever it is available.\n\n```python\n\nclass MaskConsumer(tf.keras.layers.Layer):\n \n def call(self, inputs, mask=None):\n ...\n\n\n```",
"_____no_output_____"
],
[
"## Recap\n\nThat is all you need to know about masking in Keras. To recap:\n\n- \"Masking\" is how layers are able to know when to skip / ignore certain timesteps in sequence inputs.\n- Some layers are mask-generators: `Embedding` can generate a mask from input values (if `mask_zero=True`), and so can the `Masking` layer.\n- Some layers are mask-consumers: they expose a `mask` argument in their `__call__` method. This is the case for RNN layers.\n- In the Functional API and Sequential API, mask information is propagated automatically.\n- When writing subclassed models or when using layers in a standalone way, pass the `mask` arguments to layers manually.\n- You can easily write layers that modify the current mask, that generate a new mask, or that consume the mask associated with the inputs.\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4a35c8b35761e4c7c8e1676ec0bbd3d025e5451f
| 261,620 |
ipynb
|
Jupyter Notebook
|
Workshop/MLP_104.ipynb
|
ShepherdCode/ShepherdML
|
fd8d71c63f7bd788ea0052294d93e43246254a12
|
[
"MIT"
] | null | null | null |
Workshop/MLP_104.ipynb
|
ShepherdCode/ShepherdML
|
fd8d71c63f7bd788ea0052294d93e43246254a12
|
[
"MIT"
] | 4 |
2020-03-24T18:05:09.000Z
|
2020-12-22T17:42:54.000Z
|
Workshop/MLP_104.ipynb
|
ShepherdCode/ShepherdML
|
fd8d71c63f7bd788ea0052294d93e43246254a12
|
[
"MIT"
] | null | null | null | 121.008326 | 47,340 | 0.723893 |
[
[
[
"# MLP 104",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\nPATH='/content/drive/'\ndrive.mount(PATH)\nDATAPATH=PATH+'My Drive/data/'\nPC_FILENAME = DATAPATH+'pcRNA.fasta'\nNC_FILENAME = DATAPATH+'ncRNA.fasta'\n",
"Drive already mounted at /content/drive/; to attempt to forcibly remount, call drive.mount(\"/content/drive/\", force_remount=True).\n"
],
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import RepeatedKFold\nfrom sklearn.model_selection import StratifiedKFold\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom keras.models import Sequential\nfrom keras.layers import Bidirectional\nfrom keras.layers import GRU\nfrom keras.layers import Dense\nfrom keras.layers import LayerNormalization\nimport time\n\ndt='float32'\ntf.keras.backend.set_floatx(dt)\n\nEPOCHS=200\nSPLITS=1\nK=4\nVOCABULARY_SIZE=4**K+1 # e.g. K=3 => 64 DNA K-mers + 'NNN'\nEMBED_DIMEN=16\nFILENAME='MLP104'",
"_____no_output_____"
]
],
[
[
"## Load and partition sequences",
"_____no_output_____"
]
],
[
[
"# Assume file was preprocessed to contain one line per seq.\n# Prefer Pandas dataframe but df does not support append.\n# For conversion to tensor, must avoid python lists.\ndef load_fasta(filename,label):\n DEFLINE='>'\n labels=[]\n seqs=[]\n lens=[]\n nums=[]\n num=0\n with open (filename,'r') as infile:\n for line in infile:\n if line[0]!=DEFLINE:\n seq=line.rstrip()\n num += 1 # first seqnum is 1\n seqlen=len(seq)\n nums.append(num)\n labels.append(label)\n seqs.append(seq)\n lens.append(seqlen)\n df1=pd.DataFrame(nums,columns=['seqnum'])\n df2=pd.DataFrame(labels,columns=['class'])\n df3=pd.DataFrame(seqs,columns=['sequence'])\n df4=pd.DataFrame(lens,columns=['seqlen'])\n df=pd.concat((df1,df2,df3,df4),axis=1)\n return df\n\n# Split into train/test stratified by sequence length.\ndef sizebin(df):\n return pd.cut(df[\"seqlen\"],\n bins=[0,1000,2000,4000,8000,16000,np.inf],\n labels=[0,1,2,3,4,5])\ndef make_train_test(data):\n bin_labels= sizebin(data)\n from sklearn.model_selection import StratifiedShuffleSplit\n splitter = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=37863)\n # split(x,y) expects that y is the labels. \n # Trick: Instead of y, give it it the bin labels that we generated.\n for train_index,test_index in splitter.split(data,bin_labels):\n train_set = data.iloc[train_index]\n test_set = data.iloc[test_index]\n return (train_set,test_set)\n\ndef separate_X_and_y(data):\n y= data[['class']].copy()\n X= data.drop(columns=['class','seqnum','seqlen'])\n return (X,y)\n\ndef make_slice(data_set,min_len,max_len):\n print(\"original \"+str(data_set.shape))\n too_short = data_set[ data_set['seqlen'] < min_len ].index\n no_short=data_set.drop(too_short)\n print(\"no short \"+str(no_short.shape))\n too_long = no_short[ no_short['seqlen'] >= max_len ].index\n no_long_no_short=no_short.drop(too_long)\n print(\"no long, no short \"+str(no_long_no_short.shape))\n return no_long_no_short\n",
"_____no_output_____"
]
],
[
[
"## Make K-mers",
"_____no_output_____"
]
],
[
[
"def make_kmer_table(K):\n npad='N'*K\n shorter_kmers=['']\n for i in range(K):\n longer_kmers=[]\n for mer in shorter_kmers:\n longer_kmers.append(mer+'A')\n longer_kmers.append(mer+'C')\n longer_kmers.append(mer+'G')\n longer_kmers.append(mer+'T')\n shorter_kmers = longer_kmers\n all_kmers = shorter_kmers\n kmer_dict = {}\n kmer_dict[npad]=0\n value=1\n for mer in all_kmers:\n kmer_dict[mer]=value\n value += 1\n return kmer_dict\n\nKMER_TABLE=make_kmer_table(K)\n\ndef strings_to_vectors(data,uniform_len):\n all_seqs=[]\n for seq in data['sequence']:\n i=0\n seqlen=len(seq)\n kmers=[]\n while i < seqlen-K+1 -1: # stop at minus one for spaced seed\n kmer=seq[i:i+2]+seq[i+3:i+5] # SPACED SEED 2/1/2 for K=4\n #kmer=seq[i:i+K] \n i += 1\n value=KMER_TABLE[kmer]\n kmers.append(value)\n pad_val=0\n while i < uniform_len:\n kmers.append(pad_val)\n i += 1\n all_seqs.append(kmers)\n pd2d=pd.DataFrame(all_seqs)\n return pd2d # return 2D dataframe, uniform dimensions",
"_____no_output_____"
],
[
"def make_kmers(MAXLEN,train_set):\n (X_train_all,y_train_all)=separate_X_and_y(train_set)\n\n # The returned values are Pandas dataframes.\n # print(X_train_all.shape,y_train_all.shape)\n # (X_train_all,y_train_all)\n # y: Pandas dataframe to Python list.\n # y_train_all=y_train_all.values.tolist()\n # The sequences lengths are bounded but not uniform.\n X_train_all\n print(type(X_train_all))\n print(X_train_all.shape)\n print(X_train_all.iloc[0])\n print(len(X_train_all.iloc[0]['sequence']))\n\n # X: List of string to List of uniform-length ordered lists of K-mers.\n X_train_kmers=strings_to_vectors(X_train_all,MAXLEN)\n # X: true 2D array (no more lists)\n X_train_kmers.shape\n\n print(\"transform...\")\n # From pandas dataframe to numpy to list to numpy\n print(type(X_train_kmers))\n num_seqs=len(X_train_kmers)\n tmp_seqs=[]\n for i in range(num_seqs):\n kmer_sequence=X_train_kmers.iloc[i]\n tmp_seqs.append(kmer_sequence)\n X_train_kmers=np.array(tmp_seqs)\n tmp_seqs=None\n print(type(X_train_kmers))\n print(X_train_kmers)\n\n labels=y_train_all.to_numpy()\n return (X_train_kmers,labels)",
"_____no_output_____"
],
[
"def make_frequencies(Xin):\n # Input: numpy X(numseq,seqlen) list of vectors of kmerval where val0=NNN,val1=AAA,etc. \n # Output: numpy X(numseq,65) list of frequencies of 0,1,etc.\n Xout=[]\n VOCABULARY_SIZE= 4**K + 1 # plus one for 'NNN'\n for seq in Xin:\n freqs =[0] * VOCABULARY_SIZE\n total = 0\n for kmerval in seq:\n freqs[kmerval] += 1\n total += 1\n for c in range(VOCABULARY_SIZE):\n freqs[c] = freqs[c]/total\n Xout.append(freqs)\n Xnum = np.asarray(Xout)\n return (Xnum)",
"_____no_output_____"
]
],
[
[
"## Build model",
"_____no_output_____"
]
],
[
[
"def build_model(maxlen,dimen):\n act=\"sigmoid\"\n\n embed_layer = keras.layers.Embedding(\n VOCABULARY_SIZE,EMBED_DIMEN,input_length=maxlen);\n \n dense1_layer = keras.layers.Dense(64, activation=act,dtype=dt,input_dim=VOCABULARY_SIZE)\n dense2_layer = keras.layers.Dense(64, activation=act,dtype=dt)\n dense3_layer = keras.layers.Dense(64, activation=act,dtype=dt)\n output_layer = keras.layers.Dense(1, activation=act,dtype=dt)\n\n mlp = keras.models.Sequential()\n #mlp.add(embed_layer)\n mlp.add(dense1_layer)\n mlp.add(dense2_layer)\n mlp.add(dense3_layer)\n mlp.add(output_layer)\n \n bc=tf.keras.losses.BinaryCrossentropy(from_logits=False)\n print(\"COMPILE...\")\n mlp.compile(loss=bc, optimizer=\"Adam\",metrics=[\"accuracy\"])\n print(\"...COMPILED\")\n return mlp",
"_____no_output_____"
]
],
[
[
"## Cross validation",
"_____no_output_____"
]
],
[
[
"def do_cross_validation(X,y,eps,maxlen,dimen):\n model = None\n cv_scores = []\n fold=0\n splitter = ShuffleSplit(n_splits=SPLITS, test_size=0.2, random_state=37863)\n for train_index,valid_index in splitter.split(X):\n X_train=X[train_index] # use iloc[] for dataframe\n y_train=y[train_index]\n X_valid=X[valid_index]\n y_valid=y[valid_index]\n\n print(\"BUILD MODEL\")\n model=build_model(maxlen,dimen)\n\n print(\"FIT\")\n start_time=time.time()\n # this is complaining about string to float\n history=model.fit(X_train, y_train, # batch_size=10, default=32 works nicely\n epochs=eps, verbose=1, # verbose=1 for ascii art, verbose=0 for none\n validation_data=(X_valid,y_valid) )\n end_time=time.time()\n elapsed_time=(end_time-start_time)\n \n fold += 1\n print(\"Fold %d, %d epochs, %d sec\"%(fold,eps,elapsed_time))\n\n pd.DataFrame(history.history).plot(figsize=(8,5))\n plt.grid(True)\n plt.gca().set_ylim(0,1)\n plt.show()\n\n scores = model.evaluate(X_valid, y_valid, verbose=0)\n print(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n # What are the other metrics_names?\n # Try this from Geron page 505:\n # np.mean(keras.losses.mean_squared_error(y_valid,y_pred))\n cv_scores.append(scores[1] * 100)\n print()\n print(\"Validation core mean %.2f%% (+/- %.2f%%)\" % (np.mean(cv_scores), np.std(cv_scores)))\n return model",
"_____no_output_____"
]
],
[
[
"## Load",
"_____no_output_____"
]
],
[
[
"print(\"Load data from files.\")\nnc_seq=load_fasta(NC_FILENAME,0)\npc_seq=load_fasta(PC_FILENAME,1)\nall_seq=pd.concat((nc_seq,pc_seq),axis=0)\n\nprint(\"Put aside the test portion.\")\n(train_set,test_set)=make_train_test(all_seq)\n# Do this later when using the test data:\n# (X_test,y_test)=separate_X_and_y(test_set)\n\nnc_seq=None\npc_seq=None\nall_seq=None\n\nprint(\"Ready: train_set\")\ntrain_set",
"Load data from files.\nPut aside the test portion.\nReady: train_set\n"
]
],
[
[
"## Len 200-1Kb",
"_____no_output_____"
]
],
[
[
"MINLEN=200\nMAXLEN=1000\n\nprint (\"Compile the model\")\nmodel=build_model(MAXLEN,EMBED_DIMEN)\nprint (\"Summarize the model\")\nprint(model.summary()) # Print this only once\n\nprint(\"Working on full training set, slice by sequence length.\")\nprint(\"Slice size range [%d - %d)\"%(MINLEN,MAXLEN))\nsubset=make_slice(train_set,MINLEN,MAXLEN)# One array to two: X and y\n\nprint (\"Sequence to Kmer\")\n(X_train,y_train)=make_kmers(MAXLEN,subset)\nX_train\nX_train=make_frequencies(X_train)\nX_train\nprint (\"Cross valiation\")\nmodel1 = do_cross_validation(X_train,y_train,EPOCHS,MAXLEN,EMBED_DIMEN)\nmodel1.save(FILENAME+'.short.model')",
"Compile the model\nCOMPILE...\n...COMPILED\nSummarize the model\nModel: \"sequential_18\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_72 (Dense) (None, 64) 16512 \n_________________________________________________________________\ndense_73 (Dense) (None, 64) 4160 \n_________________________________________________________________\ndense_74 (Dense) (None, 64) 4160 \n_________________________________________________________________\ndense_75 (Dense) (None, 1) 65 \n=================================================================\nTotal params: 24,897\nTrainable params: 24,897\nNon-trainable params: 0\n_________________________________________________________________\nNone\nWorking on full training set, slice by sequence length.\nSlice size range [200 - 1000)\noriginal (30290, 4)\nno short (30290, 4)\nno long, no short (8879, 4)\nSequence to Kmer\n<class 'pandas.core.frame.DataFrame'>\n(8879, 1)\nsequence AGTCCCTCCCCAGCCCAGCAGTCCCTCCAGGCTACATCCAGGAGAC...\nName: 1280, dtype: object\n348\ntransform...\n<class 'pandas.core.frame.DataFrame'>\n<class 'numpy.ndarray'>\n[[ 38 182 216 ... 0 0 0]\n [ 46 136 61 ... 0 0 0]\n [140 30 104 ... 0 0 0]\n ...\n [153 68 48 ... 0 0 0]\n [239 137 49 ... 0 0 0]\n [140 15 41 ... 0 0 0]]\nCross valiation\nBUILD MODEL\nCOMPILE...\n...COMPILED\nFIT\nEpoch 1/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.6966 - accuracy: 0.5027 - val_loss: 0.6924 - val_accuracy: 0.4989\nEpoch 2/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.6922 - accuracy: 0.5212 - val_loss: 0.6867 - val_accuracy: 0.5270\nEpoch 3/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.6678 - accuracy: 0.6226 - val_loss: 0.6310 - val_accuracy: 0.6852\nEpoch 4/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5994 - accuracy: 0.6825 - val_loss: 0.5933 - val_accuracy: 0.6745\nEpoch 5/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5745 - accuracy: 0.6927 - val_loss: 0.5805 - val_accuracy: 0.6965\nEpoch 6/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5655 - accuracy: 0.7028 - val_loss: 0.5767 - val_accuracy: 0.6931\nEpoch 7/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.5596 - accuracy: 0.7066 - val_loss: 0.5681 - val_accuracy: 0.7027\nEpoch 8/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5544 - accuracy: 0.7162 - val_loss: 0.5666 - val_accuracy: 0.7044\nEpoch 9/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5469 - accuracy: 0.7225 - val_loss: 0.5671 - val_accuracy: 0.7027\nEpoch 10/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5423 - accuracy: 0.7236 - val_loss: 0.5556 - val_accuracy: 0.7106\nEpoch 11/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5384 - accuracy: 0.7225 - val_loss: 0.5522 - val_accuracy: 0.7111\nEpoch 12/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5345 - accuracy: 0.7269 - val_loss: 0.5477 - val_accuracy: 0.7190\nEpoch 13/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5284 - accuracy: 0.7298 - val_loss: 0.5432 - val_accuracy: 0.7258\nEpoch 14/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5238 - accuracy: 0.7370 - val_loss: 0.5463 - val_accuracy: 0.7202\nEpoch 15/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5183 - accuracy: 0.7386 - val_loss: 0.5440 - val_accuracy: 0.7241\nEpoch 16/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.5112 - accuracy: 0.7431 - val_loss: 0.5314 - val_accuracy: 0.7365\nEpoch 17/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.5073 - accuracy: 0.7470 - val_loss: 0.5255 - val_accuracy: 0.7438\nEpoch 18/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.5007 - accuracy: 0.7559 - val_loss: 0.5136 - val_accuracy: 0.7427\nEpoch 19/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.4927 - accuracy: 0.7566 - val_loss: 0.5162 - val_accuracy: 0.7517\nEpoch 20/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.4863 - accuracy: 0.7659 - val_loss: 0.4970 - val_accuracy: 0.7568\nEpoch 21/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4748 - accuracy: 0.7683 - val_loss: 0.4875 - val_accuracy: 0.7579\nEpoch 22/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4671 - accuracy: 0.7766 - val_loss: 0.4806 - val_accuracy: 0.7680\nEpoch 23/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.4541 - accuracy: 0.7842 - val_loss: 0.5166 - val_accuracy: 0.7506\nEpoch 24/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.4466 - accuracy: 0.7887 - val_loss: 0.4618 - val_accuracy: 0.7787\nEpoch 25/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4372 - accuracy: 0.7963 - val_loss: 0.4570 - val_accuracy: 0.7827\nEpoch 26/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4330 - accuracy: 0.8009 - val_loss: 0.4470 - val_accuracy: 0.7866\nEpoch 27/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4290 - accuracy: 0.7973 - val_loss: 0.4438 - val_accuracy: 0.7872\nEpoch 28/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4255 - accuracy: 0.8037 - val_loss: 0.4478 - val_accuracy: 0.7905\nEpoch 29/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.4154 - accuracy: 0.8111 - val_loss: 0.4387 - val_accuracy: 0.7900\nEpoch 30/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.4175 - accuracy: 0.8087 - val_loss: 0.4487 - val_accuracy: 0.7900\nEpoch 31/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4111 - accuracy: 0.8129 - val_loss: 0.4326 - val_accuracy: 0.7962\nEpoch 32/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4089 - accuracy: 0.8147 - val_loss: 0.4331 - val_accuracy: 0.7928\nEpoch 33/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.4122 - accuracy: 0.8101 - val_loss: 0.4359 - val_accuracy: 0.7934\nEpoch 34/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4104 - accuracy: 0.8102 - val_loss: 0.4374 - val_accuracy: 0.7962\nEpoch 35/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4047 - accuracy: 0.8153 - val_loss: 0.4320 - val_accuracy: 0.7967\nEpoch 36/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4058 - accuracy: 0.8154 - val_loss: 0.4478 - val_accuracy: 0.7956\nEpoch 37/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4024 - accuracy: 0.8202 - val_loss: 0.4258 - val_accuracy: 0.7928\nEpoch 38/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4034 - accuracy: 0.8149 - val_loss: 0.4254 - val_accuracy: 0.7939\nEpoch 39/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.4017 - accuracy: 0.8157 - val_loss: 0.4264 - val_accuracy: 0.7990\nEpoch 40/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.4044 - accuracy: 0.8149 - val_loss: 0.4240 - val_accuracy: 0.7934\nEpoch 41/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3990 - accuracy: 0.8171 - val_loss: 0.4241 - val_accuracy: 0.7962\nEpoch 42/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3975 - accuracy: 0.8204 - val_loss: 0.4314 - val_accuracy: 0.8035\nEpoch 43/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.4063 - accuracy: 0.8105 - val_loss: 0.4258 - val_accuracy: 0.7917\nEpoch 44/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3995 - accuracy: 0.8147 - val_loss: 0.4375 - val_accuracy: 0.7956\nEpoch 45/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3989 - accuracy: 0.8175 - val_loss: 0.4231 - val_accuracy: 0.7962\nEpoch 46/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3963 - accuracy: 0.8205 - val_loss: 0.4257 - val_accuracy: 0.7934\nEpoch 47/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3941 - accuracy: 0.8171 - val_loss: 0.4255 - val_accuracy: 0.8007\nEpoch 48/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3943 - accuracy: 0.8212 - val_loss: 0.4220 - val_accuracy: 0.7950\nEpoch 49/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.4024 - accuracy: 0.8140 - val_loss: 0.4626 - val_accuracy: 0.7759\nEpoch 50/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3970 - accuracy: 0.8212 - val_loss: 0.4343 - val_accuracy: 0.8012\nEpoch 51/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3941 - accuracy: 0.8253 - val_loss: 0.4201 - val_accuracy: 0.7979\nEpoch 52/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3948 - accuracy: 0.8174 - val_loss: 0.4443 - val_accuracy: 0.8001\nEpoch 53/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3970 - accuracy: 0.8181 - val_loss: 0.4218 - val_accuracy: 0.7956\nEpoch 54/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3943 - accuracy: 0.8195 - val_loss: 0.4296 - val_accuracy: 0.7956\nEpoch 55/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3904 - accuracy: 0.8218 - val_loss: 0.4528 - val_accuracy: 0.7973\nEpoch 56/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3973 - accuracy: 0.8189 - val_loss: 0.4196 - val_accuracy: 0.8007\nEpoch 57/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3908 - accuracy: 0.8239 - val_loss: 0.4220 - val_accuracy: 0.7973\nEpoch 58/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3897 - accuracy: 0.8239 - val_loss: 0.4699 - val_accuracy: 0.7838\nEpoch 59/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3932 - accuracy: 0.8157 - val_loss: 0.4233 - val_accuracy: 0.7973\nEpoch 60/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3890 - accuracy: 0.8209 - val_loss: 0.4445 - val_accuracy: 0.7995\nEpoch 61/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3913 - accuracy: 0.8219 - val_loss: 0.4304 - val_accuracy: 0.8041\nEpoch 62/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3923 - accuracy: 0.8219 - val_loss: 0.4191 - val_accuracy: 0.8018\nEpoch 63/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3917 - accuracy: 0.8247 - val_loss: 0.4204 - val_accuracy: 0.7990\nEpoch 64/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3940 - accuracy: 0.8197 - val_loss: 0.4284 - val_accuracy: 0.7962\nEpoch 65/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3882 - accuracy: 0.8230 - val_loss: 0.4447 - val_accuracy: 0.7979\nEpoch 66/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3922 - accuracy: 0.8175 - val_loss: 0.4399 - val_accuracy: 0.7883\nEpoch 67/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3967 - accuracy: 0.8167 - val_loss: 0.4184 - val_accuracy: 0.8024\nEpoch 68/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3889 - accuracy: 0.8235 - val_loss: 0.4323 - val_accuracy: 0.7956\nEpoch 69/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3868 - accuracy: 0.8237 - val_loss: 0.4221 - val_accuracy: 0.7995\nEpoch 70/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3896 - accuracy: 0.8211 - val_loss: 0.4322 - val_accuracy: 0.7990\nEpoch 71/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3882 - accuracy: 0.8240 - val_loss: 0.4259 - val_accuracy: 0.7979\nEpoch 72/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3864 - accuracy: 0.8233 - val_loss: 0.4242 - val_accuracy: 0.8024\nEpoch 73/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3900 - accuracy: 0.8206 - val_loss: 0.4181 - val_accuracy: 0.8012\nEpoch 74/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3882 - accuracy: 0.8225 - val_loss: 0.4189 - val_accuracy: 0.8007\nEpoch 75/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3870 - accuracy: 0.8251 - val_loss: 0.4279 - val_accuracy: 0.7984\nEpoch 76/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3845 - accuracy: 0.8243 - val_loss: 0.4184 - val_accuracy: 0.8007\nEpoch 77/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3910 - accuracy: 0.8220 - val_loss: 0.4186 - val_accuracy: 0.7973\nEpoch 78/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3903 - accuracy: 0.8223 - val_loss: 0.4213 - val_accuracy: 0.8007\nEpoch 79/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3858 - accuracy: 0.8236 - val_loss: 0.4185 - val_accuracy: 0.8018\nEpoch 80/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3857 - accuracy: 0.8225 - val_loss: 0.4204 - val_accuracy: 0.7990\nEpoch 81/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3864 - accuracy: 0.8225 - val_loss: 0.4426 - val_accuracy: 0.7883\nEpoch 82/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3857 - accuracy: 0.8218 - val_loss: 0.4184 - val_accuracy: 0.8007\nEpoch 83/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3863 - accuracy: 0.8237 - val_loss: 0.4301 - val_accuracy: 0.7990\nEpoch 84/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3861 - accuracy: 0.8257 - val_loss: 0.4239 - val_accuracy: 0.7956\nEpoch 85/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3870 - accuracy: 0.8254 - val_loss: 0.4594 - val_accuracy: 0.7905\nEpoch 86/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3871 - accuracy: 0.8233 - val_loss: 0.4186 - val_accuracy: 0.7995\nEpoch 87/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3831 - accuracy: 0.8228 - val_loss: 0.4191 - val_accuracy: 0.7990\nEpoch 88/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3874 - accuracy: 0.8270 - val_loss: 0.4199 - val_accuracy: 0.8007\nEpoch 89/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3840 - accuracy: 0.8250 - val_loss: 0.4184 - val_accuracy: 0.8001\nEpoch 90/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3840 - accuracy: 0.8229 - val_loss: 0.4201 - val_accuracy: 0.8018\nEpoch 91/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3823 - accuracy: 0.8250 - val_loss: 0.4480 - val_accuracy: 0.7973\nEpoch 92/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3841 - accuracy: 0.8242 - val_loss: 0.4257 - val_accuracy: 0.8007\nEpoch 93/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3842 - accuracy: 0.8232 - val_loss: 0.4658 - val_accuracy: 0.7815\nEpoch 94/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3882 - accuracy: 0.8198 - val_loss: 0.4204 - val_accuracy: 0.8029\nEpoch 95/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3833 - accuracy: 0.8226 - val_loss: 0.4294 - val_accuracy: 0.8041\nEpoch 96/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3859 - accuracy: 0.8228 - val_loss: 0.4204 - val_accuracy: 0.8029\nEpoch 97/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3827 - accuracy: 0.8253 - val_loss: 0.4349 - val_accuracy: 0.7995\nEpoch 98/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3843 - accuracy: 0.8258 - val_loss: 0.4208 - val_accuracy: 0.7995\nEpoch 99/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3847 - accuracy: 0.8199 - val_loss: 0.4243 - val_accuracy: 0.8024\nEpoch 100/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3819 - accuracy: 0.8253 - val_loss: 0.4216 - val_accuracy: 0.8024\nEpoch 101/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3843 - accuracy: 0.8239 - val_loss: 0.4340 - val_accuracy: 0.7995\nEpoch 102/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3816 - accuracy: 0.8277 - val_loss: 0.4327 - val_accuracy: 0.8012\nEpoch 103/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3813 - accuracy: 0.8296 - val_loss: 0.4403 - val_accuracy: 0.8074\nEpoch 104/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3885 - accuracy: 0.8230 - val_loss: 0.4275 - val_accuracy: 0.8029\nEpoch 105/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3871 - accuracy: 0.8225 - val_loss: 0.4188 - val_accuracy: 0.7990\nEpoch 106/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3843 - accuracy: 0.8275 - val_loss: 0.4206 - val_accuracy: 0.8018\nEpoch 107/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3804 - accuracy: 0.8288 - val_loss: 0.4308 - val_accuracy: 0.8029\nEpoch 108/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3834 - accuracy: 0.8233 - val_loss: 0.4203 - val_accuracy: 0.8024\nEpoch 109/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3860 - accuracy: 0.8223 - val_loss: 0.4192 - val_accuracy: 0.7979\nEpoch 110/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3824 - accuracy: 0.8277 - val_loss: 0.4212 - val_accuracy: 0.8024\nEpoch 111/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3816 - accuracy: 0.8268 - val_loss: 0.4194 - val_accuracy: 0.8012\nEpoch 112/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3821 - accuracy: 0.8260 - val_loss: 0.4196 - val_accuracy: 0.7990\nEpoch 113/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3845 - accuracy: 0.8264 - val_loss: 0.4329 - val_accuracy: 0.8012\nEpoch 114/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3830 - accuracy: 0.8256 - val_loss: 0.4252 - val_accuracy: 0.8035\nEpoch 115/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3841 - accuracy: 0.8239 - val_loss: 0.4242 - val_accuracy: 0.7962\nEpoch 116/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3834 - accuracy: 0.8229 - val_loss: 0.4254 - val_accuracy: 0.7984\nEpoch 117/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3794 - accuracy: 0.8281 - val_loss: 0.4214 - val_accuracy: 0.7990\nEpoch 118/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3825 - accuracy: 0.8247 - val_loss: 0.4212 - val_accuracy: 0.7990\nEpoch 119/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3806 - accuracy: 0.8275 - val_loss: 0.4232 - val_accuracy: 0.8012\nEpoch 120/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3836 - accuracy: 0.8229 - val_loss: 0.4311 - val_accuracy: 0.8018\nEpoch 121/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3802 - accuracy: 0.8264 - val_loss: 0.4207 - val_accuracy: 0.8024\nEpoch 122/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3809 - accuracy: 0.8270 - val_loss: 0.4264 - val_accuracy: 0.7984\nEpoch 123/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3819 - accuracy: 0.8267 - val_loss: 0.4201 - val_accuracy: 0.8018\nEpoch 124/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3806 - accuracy: 0.8274 - val_loss: 0.4454 - val_accuracy: 0.8052\nEpoch 125/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3836 - accuracy: 0.8230 - val_loss: 0.4313 - val_accuracy: 0.8012\nEpoch 126/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3830 - accuracy: 0.8218 - val_loss: 0.4205 - val_accuracy: 0.8007\nEpoch 127/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3837 - accuracy: 0.8249 - val_loss: 0.4401 - val_accuracy: 0.7945\nEpoch 128/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3806 - accuracy: 0.8263 - val_loss: 0.4225 - val_accuracy: 0.8024\nEpoch 129/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3789 - accuracy: 0.8274 - val_loss: 0.4256 - val_accuracy: 0.8035\nEpoch 130/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3818 - accuracy: 0.8244 - val_loss: 0.4225 - val_accuracy: 0.8024\nEpoch 131/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3810 - accuracy: 0.8274 - val_loss: 0.4214 - val_accuracy: 0.8018\nEpoch 132/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3822 - accuracy: 0.8253 - val_loss: 0.4287 - val_accuracy: 0.7990\nEpoch 133/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3807 - accuracy: 0.8271 - val_loss: 0.4239 - val_accuracy: 0.7990\nEpoch 134/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3825 - accuracy: 0.8261 - val_loss: 0.4210 - val_accuracy: 0.8018\nEpoch 135/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3845 - accuracy: 0.8266 - val_loss: 0.4207 - val_accuracy: 0.8024\nEpoch 136/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3829 - accuracy: 0.8257 - val_loss: 0.4230 - val_accuracy: 0.7990\nEpoch 137/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3812 - accuracy: 0.8273 - val_loss: 0.4208 - val_accuracy: 0.8012\nEpoch 138/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3784 - accuracy: 0.8284 - val_loss: 0.4226 - val_accuracy: 0.8007\nEpoch 139/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3822 - accuracy: 0.8242 - val_loss: 0.4214 - val_accuracy: 0.8012\nEpoch 140/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3803 - accuracy: 0.8274 - val_loss: 0.4231 - val_accuracy: 0.8012\nEpoch 141/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3853 - accuracy: 0.8270 - val_loss: 0.4219 - val_accuracy: 0.8012\nEpoch 142/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3821 - accuracy: 0.8189 - val_loss: 0.4211 - val_accuracy: 0.8001\nEpoch 143/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3832 - accuracy: 0.8228 - val_loss: 0.4206 - val_accuracy: 0.8007\nEpoch 144/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3816 - accuracy: 0.8260 - val_loss: 0.4301 - val_accuracy: 0.7990\nEpoch 145/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3799 - accuracy: 0.8240 - val_loss: 0.4221 - val_accuracy: 0.8012\nEpoch 146/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3791 - accuracy: 0.8251 - val_loss: 0.4461 - val_accuracy: 0.7894\nEpoch 147/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3850 - accuracy: 0.8277 - val_loss: 0.4296 - val_accuracy: 0.8041\nEpoch 148/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3799 - accuracy: 0.8254 - val_loss: 0.4271 - val_accuracy: 0.7979\nEpoch 149/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3837 - accuracy: 0.8235 - val_loss: 0.4229 - val_accuracy: 0.8007\nEpoch 150/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3802 - accuracy: 0.8249 - val_loss: 0.4215 - val_accuracy: 0.8001\nEpoch 151/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3790 - accuracy: 0.8271 - val_loss: 0.4213 - val_accuracy: 0.8012\nEpoch 152/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3798 - accuracy: 0.8256 - val_loss: 0.4707 - val_accuracy: 0.7827\nEpoch 153/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3817 - accuracy: 0.8239 - val_loss: 0.4435 - val_accuracy: 0.7945\nEpoch 154/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3824 - accuracy: 0.8208 - val_loss: 0.4213 - val_accuracy: 0.8001\nEpoch 155/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3816 - accuracy: 0.8271 - val_loss: 0.4274 - val_accuracy: 0.7990\nEpoch 156/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3798 - accuracy: 0.8270 - val_loss: 0.4216 - val_accuracy: 0.7995\nEpoch 157/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3829 - accuracy: 0.8288 - val_loss: 0.4654 - val_accuracy: 0.7956\nEpoch 158/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3857 - accuracy: 0.8223 - val_loss: 0.4290 - val_accuracy: 0.8052\nEpoch 159/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3766 - accuracy: 0.8268 - val_loss: 0.4226 - val_accuracy: 0.8001\nEpoch 160/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3804 - accuracy: 0.8253 - val_loss: 0.4219 - val_accuracy: 0.8007\nEpoch 161/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3856 - accuracy: 0.8237 - val_loss: 0.4311 - val_accuracy: 0.8046\nEpoch 162/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3812 - accuracy: 0.8258 - val_loss: 0.4243 - val_accuracy: 0.7990\nEpoch 163/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3799 - accuracy: 0.8285 - val_loss: 0.4235 - val_accuracy: 0.8024\nEpoch 164/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3786 - accuracy: 0.8267 - val_loss: 0.4224 - val_accuracy: 0.8012\nEpoch 165/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3811 - accuracy: 0.8267 - val_loss: 0.4225 - val_accuracy: 0.7990\nEpoch 166/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3800 - accuracy: 0.8260 - val_loss: 0.4249 - val_accuracy: 0.8001\nEpoch 167/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3797 - accuracy: 0.8253 - val_loss: 0.4253 - val_accuracy: 0.7973\nEpoch 168/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3832 - accuracy: 0.8258 - val_loss: 0.4221 - val_accuracy: 0.8018\nEpoch 169/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3804 - accuracy: 0.8242 - val_loss: 0.4316 - val_accuracy: 0.8035\nEpoch 170/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3819 - accuracy: 0.8237 - val_loss: 0.4450 - val_accuracy: 0.8035\nEpoch 171/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3812 - accuracy: 0.8274 - val_loss: 0.4259 - val_accuracy: 0.7973\nEpoch 172/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3812 - accuracy: 0.8275 - val_loss: 0.4230 - val_accuracy: 0.8001\nEpoch 173/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3770 - accuracy: 0.8266 - val_loss: 0.4308 - val_accuracy: 0.7984\nEpoch 174/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3791 - accuracy: 0.8236 - val_loss: 0.4453 - val_accuracy: 0.7922\nEpoch 175/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3800 - accuracy: 0.8271 - val_loss: 0.4238 - val_accuracy: 0.8024\nEpoch 176/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3787 - accuracy: 0.8274 - val_loss: 0.4228 - val_accuracy: 0.8007\nEpoch 177/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3809 - accuracy: 0.8270 - val_loss: 0.4445 - val_accuracy: 0.8029\nEpoch 178/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3793 - accuracy: 0.8266 - val_loss: 0.4267 - val_accuracy: 0.7984\nEpoch 179/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3806 - accuracy: 0.8251 - val_loss: 0.4233 - val_accuracy: 0.7984\nEpoch 180/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3796 - accuracy: 0.8282 - val_loss: 0.4228 - val_accuracy: 0.8007\nEpoch 181/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3844 - accuracy: 0.8244 - val_loss: 0.4618 - val_accuracy: 0.7979\nEpoch 182/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3839 - accuracy: 0.8253 - val_loss: 0.4352 - val_accuracy: 0.7995\nEpoch 183/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3803 - accuracy: 0.8258 - val_loss: 0.4255 - val_accuracy: 0.8012\nEpoch 184/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3818 - accuracy: 0.8273 - val_loss: 0.4276 - val_accuracy: 0.8001\nEpoch 185/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3774 - accuracy: 0.8294 - val_loss: 0.4293 - val_accuracy: 0.7995\nEpoch 186/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3778 - accuracy: 0.8274 - val_loss: 0.4253 - val_accuracy: 0.8012\nEpoch 187/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3794 - accuracy: 0.8257 - val_loss: 0.4316 - val_accuracy: 0.8029\nEpoch 188/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3775 - accuracy: 0.8298 - val_loss: 0.4230 - val_accuracy: 0.8012\nEpoch 189/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3810 - accuracy: 0.8240 - val_loss: 0.4228 - val_accuracy: 0.8012\nEpoch 190/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3852 - accuracy: 0.8247 - val_loss: 0.4373 - val_accuracy: 0.7967\nEpoch 191/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3768 - accuracy: 0.8274 - val_loss: 0.4232 - val_accuracy: 0.8001\nEpoch 192/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3783 - accuracy: 0.8250 - val_loss: 0.4366 - val_accuracy: 0.7984\nEpoch 193/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3788 - accuracy: 0.8289 - val_loss: 0.4278 - val_accuracy: 0.7995\nEpoch 194/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3817 - accuracy: 0.8257 - val_loss: 0.4466 - val_accuracy: 0.7905\nEpoch 195/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3779 - accuracy: 0.8301 - val_loss: 0.4234 - val_accuracy: 0.8001\nEpoch 196/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3780 - accuracy: 0.8251 - val_loss: 0.4232 - val_accuracy: 0.7990\nEpoch 197/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3817 - accuracy: 0.8267 - val_loss: 0.4245 - val_accuracy: 0.8024\nEpoch 198/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3768 - accuracy: 0.8264 - val_loss: 0.4236 - val_accuracy: 0.8012\nEpoch 199/200\n222/222 [==============================] - 0s 2ms/step - loss: 0.3801 - accuracy: 0.8250 - val_loss: 0.4307 - val_accuracy: 0.7990\nEpoch 200/200\n222/222 [==============================] - 0s 1ms/step - loss: 0.3798 - accuracy: 0.8277 - val_loss: 0.4237 - val_accuracy: 0.8012\nFold 1, 200 epochs, 68 sec\n"
]
],
[
[
"## Len 1Kb-2Kb",
"_____no_output_____"
]
],
[
[
"MINLEN=1000\nMAXLEN=2000\n\nprint (\"Compile the model\")\nmodel=build_model(MAXLEN,EMBED_DIMEN)\nprint (\"Summarize the model\")\nprint(model.summary()) # Print this only once\n\nprint(\"Working on full training set, slice by sequence length.\")\nprint(\"Slice size range [%d - %d)\"%(MINLEN,MAXLEN))\nsubset=make_slice(train_set,MINLEN,MAXLEN)# One array to two: X and y\n\nprint (\"Sequence to Kmer\")\n(X_train,y_train)=make_kmers(MAXLEN,subset)\nX_train\nX_train=make_frequencies(X_train)\nX_train\nprint (\"Cross valiation\")\nmodel2 = do_cross_validation(X_train,y_train,EPOCHS,MAXLEN,EMBED_DIMEN)\nmodel2.save(FILENAME+'.medium.model')",
"Compile the model\nCOMPILE...\n...COMPILED\nSummarize the model\nModel: \"sequential_20\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_80 (Dense) (None, 64) 16512 \n_________________________________________________________________\ndense_81 (Dense) (None, 64) 4160 \n_________________________________________________________________\ndense_82 (Dense) (None, 64) 4160 \n_________________________________________________________________\ndense_83 (Dense) (None, 1) 65 \n=================================================================\nTotal params: 24,897\nTrainable params: 24,897\nNon-trainable params: 0\n_________________________________________________________________\nNone\nWorking on full training set, slice by sequence length.\nSlice size range [1000 - 2000)\noriginal (30290, 4)\nno short (9273, 4)\nno long, no short (3368, 4)\nSequence to Kmer\n<class 'pandas.core.frame.DataFrame'>\n(3368, 1)\nsequence GGCGGGGTCGACTGACGGTAACGGGGCAGAGAGGCTGTTCGCAGAG...\nName: 12641, dtype: object\n1338\ntransform...\n<class 'pandas.core.frame.DataFrame'>\n<class 'numpy.ndarray'>\n[[171 155 107 ... 0 0 0]\n [229 132 31 ... 0 0 0]\n [111 170 182 ... 0 0 0]\n ...\n [169 177 226 ... 0 0 0]\n [ 36 158 69 ... 0 0 0]\n [192 240 192 ... 0 0 0]]\nCross valiation\nBUILD MODEL\nCOMPILE...\n...COMPILED\nFIT\nEpoch 1/200\n85/85 [==============================] - 0s 3ms/step - loss: 0.6678 - accuracy: 0.6221 - val_loss: 0.6714 - val_accuracy: 0.6039\nEpoch 2/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6654 - accuracy: 0.6221 - val_loss: 0.6730 - val_accuracy: 0.6039\nEpoch 3/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6645 - accuracy: 0.6221 - val_loss: 0.6759 - val_accuracy: 0.6039\nEpoch 4/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6628 - accuracy: 0.6221 - val_loss: 0.6724 - val_accuracy: 0.6039\nEpoch 5/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6639 - accuracy: 0.6221 - val_loss: 0.6749 - val_accuracy: 0.6039\nEpoch 6/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6631 - accuracy: 0.6221 - val_loss: 0.6697 - val_accuracy: 0.6039\nEpoch 7/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6637 - accuracy: 0.6221 - val_loss: 0.6729 - val_accuracy: 0.6039\nEpoch 8/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6616 - accuracy: 0.6221 - val_loss: 0.6678 - val_accuracy: 0.6039\nEpoch 9/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6610 - accuracy: 0.6221 - val_loss: 0.6678 - val_accuracy: 0.6039\nEpoch 10/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6590 - accuracy: 0.6221 - val_loss: 0.6696 - val_accuracy: 0.6039\nEpoch 11/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6580 - accuracy: 0.6221 - val_loss: 0.6612 - val_accuracy: 0.6039\nEpoch 12/200\n85/85 [==============================] - 0s 1ms/step - loss: 0.6534 - accuracy: 0.6221 - val_loss: 0.6536 - val_accuracy: 0.6039\nEpoch 13/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6434 - accuracy: 0.6221 - val_loss: 0.6414 - val_accuracy: 0.6172\nEpoch 14/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6341 - accuracy: 0.6281 - val_loss: 0.6284 - val_accuracy: 0.7003\nEpoch 15/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6185 - accuracy: 0.6414 - val_loss: 0.6073 - val_accuracy: 0.7033\nEpoch 16/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6073 - accuracy: 0.6537 - val_loss: 0.6104 - val_accuracy: 0.6187\nEpoch 17/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.6005 - accuracy: 0.6518 - val_loss: 0.5793 - val_accuracy: 0.6855\nEpoch 18/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5926 - accuracy: 0.6693 - val_loss: 0.5712 - val_accuracy: 0.7092\nEpoch 19/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5920 - accuracy: 0.6622 - val_loss: 0.5697 - val_accuracy: 0.6944\nEpoch 20/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5857 - accuracy: 0.6704 - val_loss: 0.6045 - val_accuracy: 0.6350\nEpoch 21/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5848 - accuracy: 0.6704 - val_loss: 0.5816 - val_accuracy: 0.6528\nEpoch 22/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5822 - accuracy: 0.6789 - val_loss: 0.5879 - val_accuracy: 0.6469\nEpoch 23/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5818 - accuracy: 0.6682 - val_loss: 0.5638 - val_accuracy: 0.6855\nEpoch 24/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5761 - accuracy: 0.6715 - val_loss: 0.5543 - val_accuracy: 0.7211\nEpoch 25/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5779 - accuracy: 0.6782 - val_loss: 0.5521 - val_accuracy: 0.7196\nEpoch 26/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5741 - accuracy: 0.6856 - val_loss: 0.5619 - val_accuracy: 0.6825\nEpoch 27/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5715 - accuracy: 0.6785 - val_loss: 0.5504 - val_accuracy: 0.7270\nEpoch 28/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5673 - accuracy: 0.6945 - val_loss: 0.5499 - val_accuracy: 0.7092\nEpoch 29/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5660 - accuracy: 0.6904 - val_loss: 0.5413 - val_accuracy: 0.7300\nEpoch 30/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5655 - accuracy: 0.6908 - val_loss: 0.5673 - val_accuracy: 0.6647\nEpoch 31/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5679 - accuracy: 0.6811 - val_loss: 0.5423 - val_accuracy: 0.7151\nEpoch 32/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5598 - accuracy: 0.7016 - val_loss: 0.5329 - val_accuracy: 0.7404\nEpoch 33/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5519 - accuracy: 0.7127 - val_loss: 0.5309 - val_accuracy: 0.7507\nEpoch 34/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5494 - accuracy: 0.7082 - val_loss: 0.5250 - val_accuracy: 0.7448\nEpoch 35/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5449 - accuracy: 0.7194 - val_loss: 0.5212 - val_accuracy: 0.7463\nEpoch 36/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5433 - accuracy: 0.7175 - val_loss: 0.5239 - val_accuracy: 0.7433\nEpoch 37/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5373 - accuracy: 0.7194 - val_loss: 0.5126 - val_accuracy: 0.7596\nEpoch 38/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5346 - accuracy: 0.7242 - val_loss: 0.5133 - val_accuracy: 0.7522\nEpoch 39/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5272 - accuracy: 0.7275 - val_loss: 0.5042 - val_accuracy: 0.7537\nEpoch 40/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5209 - accuracy: 0.7357 - val_loss: 0.5012 - val_accuracy: 0.7567\nEpoch 41/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5224 - accuracy: 0.7372 - val_loss: 0.4946 - val_accuracy: 0.7671\nEpoch 42/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5183 - accuracy: 0.7424 - val_loss: 0.4982 - val_accuracy: 0.7582\nEpoch 43/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5089 - accuracy: 0.7424 - val_loss: 0.4831 - val_accuracy: 0.7760\nEpoch 44/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.5001 - accuracy: 0.7580 - val_loss: 0.4763 - val_accuracy: 0.7864\nEpoch 45/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4928 - accuracy: 0.7591 - val_loss: 0.4873 - val_accuracy: 0.7433\nEpoch 46/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4889 - accuracy: 0.7613 - val_loss: 0.4673 - val_accuracy: 0.7819\nEpoch 47/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4769 - accuracy: 0.7817 - val_loss: 0.4607 - val_accuracy: 0.7938\nEpoch 48/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4866 - accuracy: 0.7587 - val_loss: 0.4544 - val_accuracy: 0.7982\nEpoch 49/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4775 - accuracy: 0.7706 - val_loss: 0.4477 - val_accuracy: 0.7997\nEpoch 50/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4633 - accuracy: 0.7817 - val_loss: 0.4652 - val_accuracy: 0.7522\nEpoch 51/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4554 - accuracy: 0.7958 - val_loss: 0.4478 - val_accuracy: 0.7730\nEpoch 52/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4622 - accuracy: 0.7903 - val_loss: 0.4351 - val_accuracy: 0.7923\nEpoch 53/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4418 - accuracy: 0.8018 - val_loss: 0.4273 - val_accuracy: 0.8086\nEpoch 54/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4393 - accuracy: 0.7947 - val_loss: 0.4355 - val_accuracy: 0.7774\nEpoch 55/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4350 - accuracy: 0.8059 - val_loss: 0.4189 - val_accuracy: 0.8175\nEpoch 56/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4314 - accuracy: 0.7973 - val_loss: 0.4158 - val_accuracy: 0.8190\nEpoch 57/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4324 - accuracy: 0.8051 - val_loss: 0.4143 - val_accuracy: 0.8042\nEpoch 58/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4223 - accuracy: 0.8088 - val_loss: 0.4133 - val_accuracy: 0.8071\nEpoch 59/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4224 - accuracy: 0.8040 - val_loss: 0.4166 - val_accuracy: 0.8264\nEpoch 60/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4200 - accuracy: 0.8099 - val_loss: 0.4219 - val_accuracy: 0.7878\nEpoch 61/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4096 - accuracy: 0.8218 - val_loss: 0.4154 - val_accuracy: 0.8012\nEpoch 62/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4104 - accuracy: 0.8192 - val_loss: 0.4030 - val_accuracy: 0.8264\nEpoch 63/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4125 - accuracy: 0.8137 - val_loss: 0.4031 - val_accuracy: 0.8249\nEpoch 64/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4035 - accuracy: 0.8174 - val_loss: 0.3993 - val_accuracy: 0.8175\nEpoch 65/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4021 - accuracy: 0.8192 - val_loss: 0.3996 - val_accuracy: 0.8131\nEpoch 66/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4086 - accuracy: 0.8096 - val_loss: 0.4032 - val_accuracy: 0.8086\nEpoch 67/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3959 - accuracy: 0.8241 - val_loss: 0.4029 - val_accuracy: 0.8056\nEpoch 68/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3958 - accuracy: 0.8237 - val_loss: 0.4432 - val_accuracy: 0.8042\nEpoch 69/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4049 - accuracy: 0.8129 - val_loss: 0.4001 - val_accuracy: 0.8071\nEpoch 70/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3981 - accuracy: 0.8255 - val_loss: 0.4130 - val_accuracy: 0.7953\nEpoch 71/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3935 - accuracy: 0.8267 - val_loss: 0.3950 - val_accuracy: 0.8145\nEpoch 72/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3911 - accuracy: 0.8267 - val_loss: 0.3907 - val_accuracy: 0.8131\nEpoch 73/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.4066 - accuracy: 0.8096 - val_loss: 0.4138 - val_accuracy: 0.7967\nEpoch 74/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3947 - accuracy: 0.8252 - val_loss: 0.4187 - val_accuracy: 0.7938\nEpoch 75/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3960 - accuracy: 0.8196 - val_loss: 0.3895 - val_accuracy: 0.8160\nEpoch 76/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3903 - accuracy: 0.8281 - val_loss: 0.3965 - val_accuracy: 0.8027\nEpoch 77/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3995 - accuracy: 0.8222 - val_loss: 0.4241 - val_accuracy: 0.7893\nEpoch 78/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3905 - accuracy: 0.8237 - val_loss: 0.3898 - val_accuracy: 0.8190\nEpoch 79/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3856 - accuracy: 0.8311 - val_loss: 0.4040 - val_accuracy: 0.8234\nEpoch 80/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3920 - accuracy: 0.8200 - val_loss: 0.3939 - val_accuracy: 0.8042\nEpoch 81/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3830 - accuracy: 0.8270 - val_loss: 0.3878 - val_accuracy: 0.8220\nEpoch 82/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3810 - accuracy: 0.8267 - val_loss: 0.3870 - val_accuracy: 0.8234\nEpoch 83/200\n85/85 [==============================] - 0s 1ms/step - loss: 0.3859 - accuracy: 0.8252 - val_loss: 0.3858 - val_accuracy: 0.8205\nEpoch 84/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3833 - accuracy: 0.8281 - val_loss: 0.3900 - val_accuracy: 0.8175\nEpoch 85/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3828 - accuracy: 0.8263 - val_loss: 0.3978 - val_accuracy: 0.7997\nEpoch 86/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3797 - accuracy: 0.8341 - val_loss: 0.3991 - val_accuracy: 0.7997\nEpoch 87/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3800 - accuracy: 0.8322 - val_loss: 0.4202 - val_accuracy: 0.7864\nEpoch 88/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3801 - accuracy: 0.8300 - val_loss: 0.3839 - val_accuracy: 0.8234\nEpoch 89/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3794 - accuracy: 0.8296 - val_loss: 0.3954 - val_accuracy: 0.7997\nEpoch 90/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3832 - accuracy: 0.8333 - val_loss: 0.3876 - val_accuracy: 0.8205\nEpoch 91/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3757 - accuracy: 0.8348 - val_loss: 0.3827 - val_accuracy: 0.8234\nEpoch 92/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3858 - accuracy: 0.8241 - val_loss: 0.3844 - val_accuracy: 0.8249\nEpoch 93/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3792 - accuracy: 0.8367 - val_loss: 0.4331 - val_accuracy: 0.7789\nEpoch 94/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3834 - accuracy: 0.8300 - val_loss: 0.3829 - val_accuracy: 0.8234\nEpoch 95/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3906 - accuracy: 0.8196 - val_loss: 0.3980 - val_accuracy: 0.8027\nEpoch 96/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3774 - accuracy: 0.8341 - val_loss: 0.3818 - val_accuracy: 0.8264\nEpoch 97/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3758 - accuracy: 0.8348 - val_loss: 0.4101 - val_accuracy: 0.7953\nEpoch 98/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3775 - accuracy: 0.8278 - val_loss: 0.3951 - val_accuracy: 0.8071\nEpoch 99/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3774 - accuracy: 0.8318 - val_loss: 0.3815 - val_accuracy: 0.8323\nEpoch 100/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3777 - accuracy: 0.8356 - val_loss: 0.3809 - val_accuracy: 0.8309\nEpoch 101/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3775 - accuracy: 0.8304 - val_loss: 0.3864 - val_accuracy: 0.8205\nEpoch 102/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3842 - accuracy: 0.8318 - val_loss: 0.3811 - val_accuracy: 0.8309\nEpoch 103/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3777 - accuracy: 0.8296 - val_loss: 0.3875 - val_accuracy: 0.8175\nEpoch 104/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3776 - accuracy: 0.8255 - val_loss: 0.3972 - val_accuracy: 0.8056\nEpoch 105/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3738 - accuracy: 0.8311 - val_loss: 0.3954 - val_accuracy: 0.8042\nEpoch 106/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3696 - accuracy: 0.8337 - val_loss: 0.3806 - val_accuracy: 0.8294\nEpoch 107/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3790 - accuracy: 0.8304 - val_loss: 0.3807 - val_accuracy: 0.8309\nEpoch 108/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3691 - accuracy: 0.8415 - val_loss: 0.3917 - val_accuracy: 0.8012\nEpoch 109/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3677 - accuracy: 0.8426 - val_loss: 0.4059 - val_accuracy: 0.8279\nEpoch 110/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3763 - accuracy: 0.8356 - val_loss: 0.4016 - val_accuracy: 0.8042\nEpoch 111/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3709 - accuracy: 0.8389 - val_loss: 0.3985 - val_accuracy: 0.8027\nEpoch 112/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3724 - accuracy: 0.8374 - val_loss: 0.3802 - val_accuracy: 0.8338\nEpoch 113/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3698 - accuracy: 0.8378 - val_loss: 0.3833 - val_accuracy: 0.8234\nEpoch 114/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3749 - accuracy: 0.8341 - val_loss: 0.3854 - val_accuracy: 0.8190\nEpoch 115/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3681 - accuracy: 0.8356 - val_loss: 0.4007 - val_accuracy: 0.8042\nEpoch 116/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3777 - accuracy: 0.8322 - val_loss: 0.3832 - val_accuracy: 0.8279\nEpoch 117/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3684 - accuracy: 0.8359 - val_loss: 0.3828 - val_accuracy: 0.8264\nEpoch 118/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3721 - accuracy: 0.8389 - val_loss: 0.3872 - val_accuracy: 0.8294\nEpoch 119/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3709 - accuracy: 0.8363 - val_loss: 0.3813 - val_accuracy: 0.8323\nEpoch 120/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3634 - accuracy: 0.8452 - val_loss: 0.4137 - val_accuracy: 0.7997\nEpoch 121/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3638 - accuracy: 0.8471 - val_loss: 0.4053 - val_accuracy: 0.8027\nEpoch 122/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3668 - accuracy: 0.8404 - val_loss: 0.4233 - val_accuracy: 0.7864\nEpoch 123/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3683 - accuracy: 0.8382 - val_loss: 0.3785 - val_accuracy: 0.8309\nEpoch 124/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3646 - accuracy: 0.8356 - val_loss: 0.3921 - val_accuracy: 0.8101\nEpoch 125/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3700 - accuracy: 0.8448 - val_loss: 0.4081 - val_accuracy: 0.8175\nEpoch 126/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3719 - accuracy: 0.8307 - val_loss: 0.3803 - val_accuracy: 0.8323\nEpoch 127/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3648 - accuracy: 0.8434 - val_loss: 0.3825 - val_accuracy: 0.8294\nEpoch 128/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3792 - accuracy: 0.8330 - val_loss: 0.4645 - val_accuracy: 0.7878\nEpoch 129/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3756 - accuracy: 0.8341 - val_loss: 0.4249 - val_accuracy: 0.8175\nEpoch 130/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3823 - accuracy: 0.8289 - val_loss: 0.3779 - val_accuracy: 0.8294\nEpoch 131/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3603 - accuracy: 0.8422 - val_loss: 0.3957 - val_accuracy: 0.8042\nEpoch 132/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3640 - accuracy: 0.8437 - val_loss: 0.3793 - val_accuracy: 0.8294\nEpoch 133/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3603 - accuracy: 0.8422 - val_loss: 0.3791 - val_accuracy: 0.8309\nEpoch 134/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3810 - accuracy: 0.8259 - val_loss: 0.3913 - val_accuracy: 0.8279\nEpoch 135/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3668 - accuracy: 0.8367 - val_loss: 0.4217 - val_accuracy: 0.7908\nEpoch 136/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3694 - accuracy: 0.8352 - val_loss: 0.3791 - val_accuracy: 0.8323\nEpoch 137/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3604 - accuracy: 0.8467 - val_loss: 0.3923 - val_accuracy: 0.8056\nEpoch 138/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3583 - accuracy: 0.8460 - val_loss: 0.3793 - val_accuracy: 0.8323\nEpoch 139/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3604 - accuracy: 0.8478 - val_loss: 0.3791 - val_accuracy: 0.8309\nEpoch 140/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3648 - accuracy: 0.8426 - val_loss: 0.3983 - val_accuracy: 0.8071\nEpoch 141/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3667 - accuracy: 0.8408 - val_loss: 0.3796 - val_accuracy: 0.8338\nEpoch 142/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3656 - accuracy: 0.8434 - val_loss: 0.3880 - val_accuracy: 0.8131\nEpoch 143/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3646 - accuracy: 0.8400 - val_loss: 0.3823 - val_accuracy: 0.8249\nEpoch 144/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3716 - accuracy: 0.8415 - val_loss: 0.3768 - val_accuracy: 0.8338\nEpoch 145/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3601 - accuracy: 0.8430 - val_loss: 0.3833 - val_accuracy: 0.8264\nEpoch 146/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3572 - accuracy: 0.8452 - val_loss: 0.3782 - val_accuracy: 0.8294\nEpoch 147/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3595 - accuracy: 0.8430 - val_loss: 0.3781 - val_accuracy: 0.8323\nEpoch 148/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3594 - accuracy: 0.8474 - val_loss: 0.3881 - val_accuracy: 0.8145\nEpoch 149/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3626 - accuracy: 0.8374 - val_loss: 0.3835 - val_accuracy: 0.8338\nEpoch 150/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3591 - accuracy: 0.8471 - val_loss: 0.3786 - val_accuracy: 0.8309\nEpoch 151/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3619 - accuracy: 0.8422 - val_loss: 0.3919 - val_accuracy: 0.8071\nEpoch 152/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3553 - accuracy: 0.8486 - val_loss: 0.3776 - val_accuracy: 0.8353\nEpoch 153/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3604 - accuracy: 0.8482 - val_loss: 0.3780 - val_accuracy: 0.8323\nEpoch 154/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3653 - accuracy: 0.8378 - val_loss: 0.3779 - val_accuracy: 0.8338\nEpoch 155/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3562 - accuracy: 0.8482 - val_loss: 0.4048 - val_accuracy: 0.8264\nEpoch 156/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3653 - accuracy: 0.8363 - val_loss: 0.3779 - val_accuracy: 0.8338\nEpoch 157/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3639 - accuracy: 0.8408 - val_loss: 0.3782 - val_accuracy: 0.8338\nEpoch 158/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3591 - accuracy: 0.8430 - val_loss: 0.3856 - val_accuracy: 0.8190\nEpoch 159/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3563 - accuracy: 0.8441 - val_loss: 0.4344 - val_accuracy: 0.8131\nEpoch 160/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3590 - accuracy: 0.8467 - val_loss: 0.3830 - val_accuracy: 0.8309\nEpoch 161/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3560 - accuracy: 0.8512 - val_loss: 0.3874 - val_accuracy: 0.8160\nEpoch 162/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3575 - accuracy: 0.8497 - val_loss: 0.3809 - val_accuracy: 0.8294\nEpoch 163/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3572 - accuracy: 0.8463 - val_loss: 0.3795 - val_accuracy: 0.8264\nEpoch 164/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3584 - accuracy: 0.8460 - val_loss: 0.3810 - val_accuracy: 0.8294\nEpoch 165/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3612 - accuracy: 0.8404 - val_loss: 0.3780 - val_accuracy: 0.8309\nEpoch 166/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3622 - accuracy: 0.8378 - val_loss: 0.3863 - val_accuracy: 0.8205\nEpoch 167/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3608 - accuracy: 0.8441 - val_loss: 0.4297 - val_accuracy: 0.7923\nEpoch 168/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3544 - accuracy: 0.8482 - val_loss: 0.3872 - val_accuracy: 0.8220\nEpoch 169/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3524 - accuracy: 0.8541 - val_loss: 0.3973 - val_accuracy: 0.8056\nEpoch 170/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3545 - accuracy: 0.8471 - val_loss: 0.3826 - val_accuracy: 0.8264\nEpoch 171/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3694 - accuracy: 0.8348 - val_loss: 0.3779 - val_accuracy: 0.8323\nEpoch 172/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3589 - accuracy: 0.8415 - val_loss: 0.3857 - val_accuracy: 0.8220\nEpoch 173/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3536 - accuracy: 0.8530 - val_loss: 0.3855 - val_accuracy: 0.8353\nEpoch 174/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3530 - accuracy: 0.8504 - val_loss: 0.4472 - val_accuracy: 0.7834\nEpoch 175/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3586 - accuracy: 0.8448 - val_loss: 0.3808 - val_accuracy: 0.8264\nEpoch 176/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3581 - accuracy: 0.8404 - val_loss: 0.3788 - val_accuracy: 0.8279\nEpoch 177/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3546 - accuracy: 0.8474 - val_loss: 0.3784 - val_accuracy: 0.8309\nEpoch 178/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3571 - accuracy: 0.8426 - val_loss: 0.4345 - val_accuracy: 0.7938\nEpoch 179/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3594 - accuracy: 0.8426 - val_loss: 0.3780 - val_accuracy: 0.8353\nEpoch 180/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3558 - accuracy: 0.8452 - val_loss: 0.4633 - val_accuracy: 0.7641\nEpoch 181/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3606 - accuracy: 0.8382 - val_loss: 0.3833 - val_accuracy: 0.8249\nEpoch 182/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3512 - accuracy: 0.8571 - val_loss: 0.4028 - val_accuracy: 0.8027\nEpoch 183/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3548 - accuracy: 0.8441 - val_loss: 0.3786 - val_accuracy: 0.8294\nEpoch 184/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3559 - accuracy: 0.8441 - val_loss: 0.3801 - val_accuracy: 0.8279\nEpoch 185/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3544 - accuracy: 0.8426 - val_loss: 0.3786 - val_accuracy: 0.8338\nEpoch 186/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3551 - accuracy: 0.8437 - val_loss: 0.3783 - val_accuracy: 0.8323\nEpoch 187/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3685 - accuracy: 0.8393 - val_loss: 0.3779 - val_accuracy: 0.8338\nEpoch 188/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3488 - accuracy: 0.8493 - val_loss: 0.3829 - val_accuracy: 0.8294\nEpoch 189/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3517 - accuracy: 0.8467 - val_loss: 0.3835 - val_accuracy: 0.8294\nEpoch 190/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3587 - accuracy: 0.8408 - val_loss: 0.4595 - val_accuracy: 0.7745\nEpoch 191/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3533 - accuracy: 0.8486 - val_loss: 0.3786 - val_accuracy: 0.8323\nEpoch 192/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3480 - accuracy: 0.8493 - val_loss: 0.3788 - val_accuracy: 0.8323\nEpoch 193/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3471 - accuracy: 0.8486 - val_loss: 0.4331 - val_accuracy: 0.7982\nEpoch 194/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3636 - accuracy: 0.8337 - val_loss: 0.4270 - val_accuracy: 0.7982\nEpoch 195/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3555 - accuracy: 0.8504 - val_loss: 0.3861 - val_accuracy: 0.8220\nEpoch 196/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3535 - accuracy: 0.8460 - val_loss: 0.3922 - val_accuracy: 0.8323\nEpoch 197/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3517 - accuracy: 0.8482 - val_loss: 0.3932 - val_accuracy: 0.8309\nEpoch 198/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3492 - accuracy: 0.8519 - val_loss: 0.3815 - val_accuracy: 0.8249\nEpoch 199/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3579 - accuracy: 0.8497 - val_loss: 0.3854 - val_accuracy: 0.8338\nEpoch 200/200\n85/85 [==============================] - 0s 2ms/step - loss: 0.3486 - accuracy: 0.8508 - val_loss: 0.3791 - val_accuracy: 0.8294\nFold 1, 200 epochs, 29 sec\n"
]
],
[
[
"## Len 2Kb-3Kb",
"_____no_output_____"
]
],
[
[
"MINLEN=2000\nMAXLEN=3000\n\nprint (\"Compile the model\")\nmodel=build_model(MAXLEN,EMBED_DIMEN)\nprint (\"Summarize the model\")\nprint(model.summary()) # Print this only once\n\nprint(\"Working on full training set, slice by sequence length.\")\nprint(\"Slice size range [%d - %d)\"%(MINLEN,MAXLEN))\nsubset=make_slice(train_set,MINLEN,MAXLEN)# One array to two: X and y\n\nprint (\"Sequence to Kmer\")\n(X_train,y_train)=make_kmers(MAXLEN,subset)\nX_train\nX_train=make_frequencies(X_train)\nX_train\nprint (\"Cross valiation\")\nmodel3 = do_cross_validation(X_train,y_train,EPOCHS,MAXLEN,EMBED_DIMEN)\nmodel3.save(FILENAME+'.long.model')",
"Compile the model\nCOMPILE...\n...COMPILED\nSummarize the model\nModel: \"sequential_22\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_88 (Dense) (None, 64) 16512 \n_________________________________________________________________\ndense_89 (Dense) (None, 64) 4160 \n_________________________________________________________________\ndense_90 (Dense) (None, 64) 4160 \n_________________________________________________________________\ndense_91 (Dense) (None, 1) 65 \n=================================================================\nTotal params: 24,897\nTrainable params: 24,897\nNon-trainable params: 0\n_________________________________________________________________\nNone\nWorking on full training set, slice by sequence length.\nSlice size range [2000 - 3000)\noriginal (30290, 4)\nno short (3221, 4)\nno long, no short (1351, 4)\nSequence to Kmer\n<class 'pandas.core.frame.DataFrame'>\n(1351, 1)\nsequence GTCATTCTAGCTGCCTGCTGCCTCCGCAGCGTCCCCCCAGCTCTCC...\nName: 19713, dtype: object\n2039\ntransform...\n<class 'pandas.core.frame.DataFrame'>\n<class 'numpy.ndarray'>\n[[180 224 78 ... 0 0 0]\n [ 5 36 159 ... 0 0 0]\n [ 46 181 243 ... 0 0 0]\n ...\n [ 51 202 5 ... 0 0 0]\n [145 99 138 ... 0 0 0]\n [ 47 138 56 ... 0 0 0]]\nCross valiation\nBUILD MODEL\nCOMPILE...\n...COMPILED\nFIT\nEpoch 1/200\n34/34 [==============================] - 0s 5ms/step - loss: 0.6102 - accuracy: 0.7083 - val_loss: 0.6295 - val_accuracy: 0.6790\nEpoch 2/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6053 - accuracy: 0.7083 - val_loss: 0.6295 - val_accuracy: 0.6790\nEpoch 3/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6071 - accuracy: 0.7083 - val_loss: 0.6276 - val_accuracy: 0.6790\nEpoch 4/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6054 - accuracy: 0.7083 - val_loss: 0.6281 - val_accuracy: 0.6790\nEpoch 5/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6061 - accuracy: 0.7083 - val_loss: 0.6275 - val_accuracy: 0.6790\nEpoch 6/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6104 - accuracy: 0.7083 - val_loss: 0.6402 - val_accuracy: 0.6790\nEpoch 7/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6055 - accuracy: 0.7083 - val_loss: 0.6305 - val_accuracy: 0.6790\nEpoch 8/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6051 - accuracy: 0.7083 - val_loss: 0.6394 - val_accuracy: 0.6790\nEpoch 9/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6059 - accuracy: 0.7083 - val_loss: 0.6297 - val_accuracy: 0.6790\nEpoch 10/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6041 - accuracy: 0.7083 - val_loss: 0.6295 - val_accuracy: 0.6790\nEpoch 11/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6066 - accuracy: 0.7083 - val_loss: 0.6340 - val_accuracy: 0.6790\nEpoch 12/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6112 - accuracy: 0.7083 - val_loss: 0.6276 - val_accuracy: 0.6790\nEpoch 13/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6038 - accuracy: 0.7083 - val_loss: 0.6317 - val_accuracy: 0.6790\nEpoch 14/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6037 - accuracy: 0.7083 - val_loss: 0.6268 - val_accuracy: 0.6790\nEpoch 15/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6040 - accuracy: 0.7083 - val_loss: 0.6266 - val_accuracy: 0.6790\nEpoch 16/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6060 - accuracy: 0.7083 - val_loss: 0.6265 - val_accuracy: 0.6790\nEpoch 17/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6032 - accuracy: 0.7083 - val_loss: 0.6326 - val_accuracy: 0.6790\nEpoch 18/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6042 - accuracy: 0.7083 - val_loss: 0.6322 - val_accuracy: 0.6790\nEpoch 19/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6028 - accuracy: 0.7083 - val_loss: 0.6261 - val_accuracy: 0.6790\nEpoch 20/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6033 - accuracy: 0.7083 - val_loss: 0.6268 - val_accuracy: 0.6790\nEpoch 21/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6037 - accuracy: 0.7083 - val_loss: 0.6322 - val_accuracy: 0.6790\nEpoch 22/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6020 - accuracy: 0.7083 - val_loss: 0.6276 - val_accuracy: 0.6790\nEpoch 23/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6055 - accuracy: 0.7083 - val_loss: 0.6501 - val_accuracy: 0.6790\nEpoch 24/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6014 - accuracy: 0.7083 - val_loss: 0.6243 - val_accuracy: 0.6790\nEpoch 25/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6001 - accuracy: 0.7083 - val_loss: 0.6329 - val_accuracy: 0.6790\nEpoch 26/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6014 - accuracy: 0.7083 - val_loss: 0.6251 - val_accuracy: 0.6790\nEpoch 27/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5993 - accuracy: 0.7083 - val_loss: 0.6215 - val_accuracy: 0.6790\nEpoch 28/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5990 - accuracy: 0.7083 - val_loss: 0.6200 - val_accuracy: 0.6790\nEpoch 29/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.6005 - accuracy: 0.7083 - val_loss: 0.6188 - val_accuracy: 0.6790\nEpoch 30/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5961 - accuracy: 0.7083 - val_loss: 0.6167 - val_accuracy: 0.6790\nEpoch 31/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5926 - accuracy: 0.7083 - val_loss: 0.6195 - val_accuracy: 0.6790\nEpoch 32/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5925 - accuracy: 0.7083 - val_loss: 0.6175 - val_accuracy: 0.6790\nEpoch 33/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5885 - accuracy: 0.7083 - val_loss: 0.6226 - val_accuracy: 0.6790\nEpoch 34/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5856 - accuracy: 0.7083 - val_loss: 0.6253 - val_accuracy: 0.6790\nEpoch 35/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5918 - accuracy: 0.7083 - val_loss: 0.6194 - val_accuracy: 0.6790\nEpoch 36/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5802 - accuracy: 0.7083 - val_loss: 0.6128 - val_accuracy: 0.6790\nEpoch 37/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5722 - accuracy: 0.7083 - val_loss: 0.5893 - val_accuracy: 0.6790\nEpoch 38/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5706 - accuracy: 0.7102 - val_loss: 0.5819 - val_accuracy: 0.6827\nEpoch 39/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5635 - accuracy: 0.7083 - val_loss: 0.5800 - val_accuracy: 0.6790\nEpoch 40/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5594 - accuracy: 0.7102 - val_loss: 0.5732 - val_accuracy: 0.6827\nEpoch 41/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5589 - accuracy: 0.7139 - val_loss: 0.5655 - val_accuracy: 0.6937\nEpoch 42/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5489 - accuracy: 0.7213 - val_loss: 0.5974 - val_accuracy: 0.6790\nEpoch 43/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5515 - accuracy: 0.7185 - val_loss: 0.5577 - val_accuracy: 0.7085\nEpoch 44/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5481 - accuracy: 0.7194 - val_loss: 0.5546 - val_accuracy: 0.7048\nEpoch 45/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5446 - accuracy: 0.7176 - val_loss: 0.5512 - val_accuracy: 0.7085\nEpoch 46/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5407 - accuracy: 0.7222 - val_loss: 0.5478 - val_accuracy: 0.7306\nEpoch 47/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5381 - accuracy: 0.7352 - val_loss: 0.5475 - val_accuracy: 0.7085\nEpoch 48/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5354 - accuracy: 0.7370 - val_loss: 0.5428 - val_accuracy: 0.7343\nEpoch 49/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5350 - accuracy: 0.7222 - val_loss: 0.5467 - val_accuracy: 0.7159\nEpoch 50/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5355 - accuracy: 0.7259 - val_loss: 0.5626 - val_accuracy: 0.6863\nEpoch 51/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5303 - accuracy: 0.7213 - val_loss: 0.5486 - val_accuracy: 0.7011\nEpoch 52/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5297 - accuracy: 0.7324 - val_loss: 0.5382 - val_accuracy: 0.7122\nEpoch 53/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5253 - accuracy: 0.7398 - val_loss: 0.5450 - val_accuracy: 0.7122\nEpoch 54/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5268 - accuracy: 0.7398 - val_loss: 0.5312 - val_accuracy: 0.7343\nEpoch 55/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5320 - accuracy: 0.7194 - val_loss: 0.5412 - val_accuracy: 0.7122\nEpoch 56/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5260 - accuracy: 0.7194 - val_loss: 0.5286 - val_accuracy: 0.7343\nEpoch 57/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5205 - accuracy: 0.7361 - val_loss: 0.5254 - val_accuracy: 0.7306\nEpoch 58/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5230 - accuracy: 0.7398 - val_loss: 0.5378 - val_accuracy: 0.7122\nEpoch 59/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5240 - accuracy: 0.7343 - val_loss: 0.5226 - val_accuracy: 0.7417\nEpoch 60/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5188 - accuracy: 0.7370 - val_loss: 0.5197 - val_accuracy: 0.7306\nEpoch 61/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5176 - accuracy: 0.7306 - val_loss: 0.5251 - val_accuracy: 0.7196\nEpoch 62/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5203 - accuracy: 0.7287 - val_loss: 0.5149 - val_accuracy: 0.7454\nEpoch 63/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5100 - accuracy: 0.7491 - val_loss: 0.5185 - val_accuracy: 0.7380\nEpoch 64/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5060 - accuracy: 0.7528 - val_loss: 0.5174 - val_accuracy: 0.7380\nEpoch 65/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5046 - accuracy: 0.7500 - val_loss: 0.5121 - val_accuracy: 0.7528\nEpoch 66/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.5014 - accuracy: 0.7500 - val_loss: 0.5047 - val_accuracy: 0.7454\nEpoch 67/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4991 - accuracy: 0.7593 - val_loss: 0.5024 - val_accuracy: 0.7380\nEpoch 68/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4976 - accuracy: 0.7657 - val_loss: 0.5018 - val_accuracy: 0.7601\nEpoch 69/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4954 - accuracy: 0.7546 - val_loss: 0.4974 - val_accuracy: 0.7565\nEpoch 70/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4918 - accuracy: 0.7667 - val_loss: 0.4948 - val_accuracy: 0.7528\nEpoch 71/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4874 - accuracy: 0.7593 - val_loss: 0.5166 - val_accuracy: 0.7085\nEpoch 72/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4904 - accuracy: 0.7667 - val_loss: 0.4883 - val_accuracy: 0.7528\nEpoch 73/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4825 - accuracy: 0.7648 - val_loss: 0.5071 - val_accuracy: 0.7232\nEpoch 74/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4891 - accuracy: 0.7676 - val_loss: 0.4914 - val_accuracy: 0.7712\nEpoch 75/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4840 - accuracy: 0.7657 - val_loss: 0.4845 - val_accuracy: 0.7601\nEpoch 76/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4785 - accuracy: 0.7648 - val_loss: 0.4833 - val_accuracy: 0.7675\nEpoch 77/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4791 - accuracy: 0.7648 - val_loss: 0.4727 - val_accuracy: 0.7712\nEpoch 78/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4704 - accuracy: 0.7824 - val_loss: 0.4704 - val_accuracy: 0.7675\nEpoch 79/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4658 - accuracy: 0.7796 - val_loss: 0.4760 - val_accuracy: 0.7749\nEpoch 80/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4654 - accuracy: 0.7870 - val_loss: 0.4624 - val_accuracy: 0.7749\nEpoch 81/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4656 - accuracy: 0.7787 - val_loss: 0.4951 - val_accuracy: 0.7380\nEpoch 82/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4540 - accuracy: 0.7806 - val_loss: 0.4666 - val_accuracy: 0.7749\nEpoch 83/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4592 - accuracy: 0.7880 - val_loss: 0.4577 - val_accuracy: 0.7897\nEpoch 84/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4475 - accuracy: 0.7944 - val_loss: 0.4490 - val_accuracy: 0.7786\nEpoch 85/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4421 - accuracy: 0.7944 - val_loss: 0.4503 - val_accuracy: 0.7860\nEpoch 86/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4399 - accuracy: 0.8028 - val_loss: 0.4506 - val_accuracy: 0.7897\nEpoch 87/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4385 - accuracy: 0.8019 - val_loss: 0.4584 - val_accuracy: 0.7638\nEpoch 88/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4340 - accuracy: 0.8074 - val_loss: 0.4415 - val_accuracy: 0.7897\nEpoch 89/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4344 - accuracy: 0.8019 - val_loss: 0.4291 - val_accuracy: 0.8081\nEpoch 90/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4258 - accuracy: 0.8037 - val_loss: 0.4254 - val_accuracy: 0.7970\nEpoch 91/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4218 - accuracy: 0.8139 - val_loss: 0.4431 - val_accuracy: 0.7786\nEpoch 92/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4183 - accuracy: 0.8167 - val_loss: 0.4197 - val_accuracy: 0.8081\nEpoch 93/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4210 - accuracy: 0.8056 - val_loss: 0.4446 - val_accuracy: 0.7675\nEpoch 94/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4202 - accuracy: 0.8148 - val_loss: 0.4477 - val_accuracy: 0.7601\nEpoch 95/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4275 - accuracy: 0.7907 - val_loss: 0.4365 - val_accuracy: 0.7675\nEpoch 96/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4065 - accuracy: 0.8296 - val_loss: 0.4183 - val_accuracy: 0.8229\nEpoch 97/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4055 - accuracy: 0.8213 - val_loss: 0.4031 - val_accuracy: 0.8081\nEpoch 98/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4006 - accuracy: 0.8231 - val_loss: 0.3995 - val_accuracy: 0.8044\nEpoch 99/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3893 - accuracy: 0.8324 - val_loss: 0.4009 - val_accuracy: 0.8229\nEpoch 100/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.4025 - accuracy: 0.8093 - val_loss: 0.4039 - val_accuracy: 0.8044\nEpoch 101/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3883 - accuracy: 0.8380 - val_loss: 0.4113 - val_accuracy: 0.7897\nEpoch 102/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3947 - accuracy: 0.8241 - val_loss: 0.4244 - val_accuracy: 0.7638\nEpoch 103/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3860 - accuracy: 0.8324 - val_loss: 0.3924 - val_accuracy: 0.8229\nEpoch 104/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3846 - accuracy: 0.8241 - val_loss: 0.3914 - val_accuracy: 0.8192\nEpoch 105/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3746 - accuracy: 0.8333 - val_loss: 0.4165 - val_accuracy: 0.7712\nEpoch 106/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3700 - accuracy: 0.8463 - val_loss: 0.4089 - val_accuracy: 0.7897\nEpoch 107/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3745 - accuracy: 0.8389 - val_loss: 0.3795 - val_accuracy: 0.8155\nEpoch 108/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3699 - accuracy: 0.8426 - val_loss: 0.3797 - val_accuracy: 0.8155\nEpoch 109/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3733 - accuracy: 0.8287 - val_loss: 0.4079 - val_accuracy: 0.7823\nEpoch 110/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3663 - accuracy: 0.8463 - val_loss: 0.3862 - val_accuracy: 0.8044\nEpoch 111/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3622 - accuracy: 0.8444 - val_loss: 0.3677 - val_accuracy: 0.8413\nEpoch 112/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3634 - accuracy: 0.8519 - val_loss: 0.3813 - val_accuracy: 0.8450\nEpoch 113/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3590 - accuracy: 0.8417 - val_loss: 0.3644 - val_accuracy: 0.8303\nEpoch 114/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3626 - accuracy: 0.8361 - val_loss: 0.3699 - val_accuracy: 0.8192\nEpoch 115/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3525 - accuracy: 0.8454 - val_loss: 0.3654 - val_accuracy: 0.8229\nEpoch 116/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3588 - accuracy: 0.8380 - val_loss: 0.3589 - val_accuracy: 0.8561\nEpoch 117/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3505 - accuracy: 0.8417 - val_loss: 0.3715 - val_accuracy: 0.8081\nEpoch 118/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3592 - accuracy: 0.8454 - val_loss: 0.3578 - val_accuracy: 0.8413\nEpoch 119/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3534 - accuracy: 0.8389 - val_loss: 0.3551 - val_accuracy: 0.8745\nEpoch 120/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3477 - accuracy: 0.8417 - val_loss: 0.3539 - val_accuracy: 0.8708\nEpoch 121/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3532 - accuracy: 0.8454 - val_loss: 0.3719 - val_accuracy: 0.8044\nEpoch 122/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3422 - accuracy: 0.8519 - val_loss: 0.3523 - val_accuracy: 0.8635\nEpoch 123/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3471 - accuracy: 0.8435 - val_loss: 0.3510 - val_accuracy: 0.8635\nEpoch 124/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3576 - accuracy: 0.8333 - val_loss: 0.3697 - val_accuracy: 0.8044\nEpoch 125/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3449 - accuracy: 0.8454 - val_loss: 0.3472 - val_accuracy: 0.8413\nEpoch 126/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3447 - accuracy: 0.8454 - val_loss: 0.3560 - val_accuracy: 0.8524\nEpoch 127/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3366 - accuracy: 0.8537 - val_loss: 0.3535 - val_accuracy: 0.8339\nEpoch 128/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3419 - accuracy: 0.8519 - val_loss: 0.3441 - val_accuracy: 0.8708\nEpoch 129/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3344 - accuracy: 0.8602 - val_loss: 0.3472 - val_accuracy: 0.8487\nEpoch 130/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3329 - accuracy: 0.8537 - val_loss: 0.3442 - val_accuracy: 0.8487\nEpoch 131/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3300 - accuracy: 0.8593 - val_loss: 0.3547 - val_accuracy: 0.8155\nEpoch 132/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3315 - accuracy: 0.8454 - val_loss: 0.3452 - val_accuracy: 0.8487\nEpoch 133/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3358 - accuracy: 0.8491 - val_loss: 0.3387 - val_accuracy: 0.8524\nEpoch 134/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3252 - accuracy: 0.8583 - val_loss: 0.3513 - val_accuracy: 0.8229\nEpoch 135/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3305 - accuracy: 0.8546 - val_loss: 0.3509 - val_accuracy: 0.8192\nEpoch 136/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3248 - accuracy: 0.8620 - val_loss: 0.3597 - val_accuracy: 0.8118\nEpoch 137/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3202 - accuracy: 0.8556 - val_loss: 0.3343 - val_accuracy: 0.8745\nEpoch 138/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3206 - accuracy: 0.8574 - val_loss: 0.3326 - val_accuracy: 0.8672\nEpoch 139/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3243 - accuracy: 0.8537 - val_loss: 0.3338 - val_accuracy: 0.8561\nEpoch 140/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3210 - accuracy: 0.8537 - val_loss: 0.3310 - val_accuracy: 0.8598\nEpoch 141/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3190 - accuracy: 0.8583 - val_loss: 0.3398 - val_accuracy: 0.8450\nEpoch 142/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3223 - accuracy: 0.8620 - val_loss: 0.3432 - val_accuracy: 0.8376\nEpoch 143/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3231 - accuracy: 0.8509 - val_loss: 0.3445 - val_accuracy: 0.8339\nEpoch 144/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3204 - accuracy: 0.8556 - val_loss: 0.3277 - val_accuracy: 0.8708\nEpoch 145/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3257 - accuracy: 0.8528 - val_loss: 0.4084 - val_accuracy: 0.7786\nEpoch 146/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3168 - accuracy: 0.8667 - val_loss: 0.4044 - val_accuracy: 0.7786\nEpoch 147/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3177 - accuracy: 0.8611 - val_loss: 0.3254 - val_accuracy: 0.8598\nEpoch 148/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3231 - accuracy: 0.8639 - val_loss: 0.3296 - val_accuracy: 0.8561\nEpoch 149/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3220 - accuracy: 0.8574 - val_loss: 0.3287 - val_accuracy: 0.8598\nEpoch 150/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3131 - accuracy: 0.8630 - val_loss: 0.3264 - val_accuracy: 0.8635\nEpoch 151/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3085 - accuracy: 0.8685 - val_loss: 0.3286 - val_accuracy: 0.8745\nEpoch 152/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3169 - accuracy: 0.8667 - val_loss: 0.3218 - val_accuracy: 0.8672\nEpoch 153/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3158 - accuracy: 0.8657 - val_loss: 0.4219 - val_accuracy: 0.7786\nEpoch 154/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3137 - accuracy: 0.8648 - val_loss: 0.3304 - val_accuracy: 0.8561\nEpoch 155/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3139 - accuracy: 0.8593 - val_loss: 0.3419 - val_accuracy: 0.8339\nEpoch 156/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3051 - accuracy: 0.8713 - val_loss: 0.3365 - val_accuracy: 0.8413\nEpoch 157/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3088 - accuracy: 0.8611 - val_loss: 0.3305 - val_accuracy: 0.8598\nEpoch 158/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3188 - accuracy: 0.8519 - val_loss: 0.3223 - val_accuracy: 0.8598\nEpoch 159/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3003 - accuracy: 0.8685 - val_loss: 0.3314 - val_accuracy: 0.8487\nEpoch 160/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2994 - accuracy: 0.8667 - val_loss: 0.3192 - val_accuracy: 0.8745\nEpoch 161/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3014 - accuracy: 0.8704 - val_loss: 0.3275 - val_accuracy: 0.8561\nEpoch 162/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3032 - accuracy: 0.8657 - val_loss: 0.3553 - val_accuracy: 0.8118\nEpoch 163/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3079 - accuracy: 0.8630 - val_loss: 0.3225 - val_accuracy: 0.8561\nEpoch 164/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3035 - accuracy: 0.8574 - val_loss: 0.3243 - val_accuracy: 0.8745\nEpoch 165/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2989 - accuracy: 0.8694 - val_loss: 0.3177 - val_accuracy: 0.8672\nEpoch 166/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2959 - accuracy: 0.8722 - val_loss: 0.3208 - val_accuracy: 0.8561\nEpoch 167/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3003 - accuracy: 0.8731 - val_loss: 0.3226 - val_accuracy: 0.8745\nEpoch 168/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3055 - accuracy: 0.8676 - val_loss: 0.3162 - val_accuracy: 0.8708\nEpoch 169/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2954 - accuracy: 0.8750 - val_loss: 0.3134 - val_accuracy: 0.8598\nEpoch 170/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2964 - accuracy: 0.8741 - val_loss: 0.3127 - val_accuracy: 0.8672\nEpoch 171/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3074 - accuracy: 0.8602 - val_loss: 0.3373 - val_accuracy: 0.8413\nEpoch 172/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3069 - accuracy: 0.8657 - val_loss: 0.3120 - val_accuracy: 0.8672\nEpoch 173/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3033 - accuracy: 0.8593 - val_loss: 0.3203 - val_accuracy: 0.8598\nEpoch 174/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2993 - accuracy: 0.8694 - val_loss: 0.3113 - val_accuracy: 0.8672\nEpoch 175/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2944 - accuracy: 0.8722 - val_loss: 0.3505 - val_accuracy: 0.8155\nEpoch 176/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2892 - accuracy: 0.8815 - val_loss: 0.3151 - val_accuracy: 0.8782\nEpoch 177/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2977 - accuracy: 0.8685 - val_loss: 0.3164 - val_accuracy: 0.8598\nEpoch 178/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2963 - accuracy: 0.8722 - val_loss: 0.3423 - val_accuracy: 0.8266\nEpoch 179/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3038 - accuracy: 0.8583 - val_loss: 0.3986 - val_accuracy: 0.7860\nEpoch 180/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2982 - accuracy: 0.8704 - val_loss: 0.3856 - val_accuracy: 0.7970\nEpoch 181/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2947 - accuracy: 0.8750 - val_loss: 0.3114 - val_accuracy: 0.8708\nEpoch 182/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2944 - accuracy: 0.8676 - val_loss: 0.3868 - val_accuracy: 0.7970\nEpoch 183/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2961 - accuracy: 0.8639 - val_loss: 0.3182 - val_accuracy: 0.8561\nEpoch 184/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2902 - accuracy: 0.8667 - val_loss: 0.3453 - val_accuracy: 0.8266\nEpoch 185/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2923 - accuracy: 0.8713 - val_loss: 0.3238 - val_accuracy: 0.8598\nEpoch 186/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2890 - accuracy: 0.8704 - val_loss: 0.3874 - val_accuracy: 0.7970\nEpoch 187/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2851 - accuracy: 0.8806 - val_loss: 0.3082 - val_accuracy: 0.8635\nEpoch 188/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2945 - accuracy: 0.8694 - val_loss: 0.3074 - val_accuracy: 0.8672\nEpoch 189/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2876 - accuracy: 0.8731 - val_loss: 0.3172 - val_accuracy: 0.8819\nEpoch 190/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.3043 - accuracy: 0.8583 - val_loss: 0.3070 - val_accuracy: 0.8635\nEpoch 191/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2847 - accuracy: 0.8824 - val_loss: 0.3070 - val_accuracy: 0.8635\nEpoch 192/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2937 - accuracy: 0.8694 - val_loss: 0.3594 - val_accuracy: 0.8118\nEpoch 193/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2815 - accuracy: 0.8833 - val_loss: 0.3133 - val_accuracy: 0.8561\nEpoch 194/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2880 - accuracy: 0.8750 - val_loss: 0.3164 - val_accuracy: 0.8561\nEpoch 195/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2837 - accuracy: 0.8750 - val_loss: 0.3220 - val_accuracy: 0.8598\nEpoch 196/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2801 - accuracy: 0.8815 - val_loss: 0.3287 - val_accuracy: 0.8450\nEpoch 197/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2855 - accuracy: 0.8759 - val_loss: 0.3625 - val_accuracy: 0.8155\nEpoch 198/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2837 - accuracy: 0.8778 - val_loss: 0.3085 - val_accuracy: 0.8635\nEpoch 199/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2776 - accuracy: 0.8852 - val_loss: 0.3155 - val_accuracy: 0.8598\nEpoch 200/200\n34/34 [==============================] - 0s 2ms/step - loss: 0.2809 - accuracy: 0.8843 - val_loss: 0.3178 - val_accuracy: 0.8598\nFold 1, 200 epochs, 14 sec\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a35d96a8d94e78fbacee280b6b4b25f2813feec
| 98,000 |
ipynb
|
Jupyter Notebook
|
CNN_FashionMNIST.ipynb
|
kcmath/Tf2-CNN
|
812b0667aca1797b02ed517731938e5b79f87e40
|
[
"MIT"
] | 1 |
2020-03-13T08:04:00.000Z
|
2020-03-13T08:04:00.000Z
|
CNN_FashionMNIST.ipynb
|
kcmath/Tf2-CNN
|
812b0667aca1797b02ed517731938e5b79f87e40
|
[
"MIT"
] | null | null | null |
CNN_FashionMNIST.ipynb
|
kcmath/Tf2-CNN
|
812b0667aca1797b02ed517731938e5b79f87e40
|
[
"MIT"
] | null | null | null | 179.487179 | 29,476 | 0.843327 |
[
[
[
"# Install TensorFlow\n!pip install tensorflow-gpu\n\ntry:\n %tensorflow_version 2.x # Colab only.\nexcept Exception:\n pass\n\nimport tensorflow as tf\nprint(tf.__version__)\nprint(tf.test.gpu_device_name())\nprint(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))",
"Requirement already satisfied: tensorflow-gpu in /usr/local/lib/python3.6/dist-packages (2.1.0)\nRequirement already satisfied: tensorboard<2.2.0,>=2.1.0 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (2.1.0)\nRequirement already satisfied: six>=1.12.0 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (1.13.0)\nRequirement already satisfied: keras-applications>=1.0.8 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (1.0.8)\nRequirement already satisfied: wrapt>=1.11.1 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (1.11.2)\nRequirement already satisfied: absl-py>=0.7.0 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (0.9.0)\nRequirement already satisfied: wheel>=0.26; python_version >= \"3\" in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (0.33.6)\nRequirement already satisfied: tensorflow-estimator<2.2.0,>=2.1.0rc0 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (2.1.0)\nRequirement already satisfied: grpcio>=1.8.6 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (1.26.0)\nRequirement already satisfied: astor>=0.6.0 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (0.8.1)\nRequirement already satisfied: keras-preprocessing>=1.1.0 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (1.1.0)\nRequirement already satisfied: scipy==1.4.1; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu) (1.4.1)\nRequirement already satisfied: numpy<2.0,>=1.16.0 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (1.18.1)\nRequirement already satisfied: termcolor>=1.1.0 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (1.1.0)\nRequirement already satisfied: opt-einsum>=2.3.2 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (3.1.0)\nRequirement already satisfied: google-pasta>=0.1.6 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (0.1.8)\nRequirement already satisfied: gast==0.2.2 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (0.2.2)\nRequirement already satisfied: protobuf>=3.8.0 in /tensorflow-2.1.0/python3.6 (from tensorflow-gpu) (3.11.2)\nRequirement already satisfied: setuptools>=41.0.0 in /tensorflow-2.1.0/python3.6 (from tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (45.0.0)\nRequirement already satisfied: requests<3,>=2.21.0 in /tensorflow-2.1.0/python3.6 (from tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (2.22.0)\nRequirement already satisfied: werkzeug>=0.11.15 in /tensorflow-2.1.0/python3.6 (from tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (0.16.0)\nRequirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /tensorflow-2.1.0/python3.6 (from tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (0.4.1)\nRequirement already satisfied: markdown>=2.6.8 in /tensorflow-2.1.0/python3.6 (from tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (3.1.1)\nRequirement already satisfied: google-auth<2,>=1.6.3 in /tensorflow-2.1.0/python3.6 (from tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (1.10.0)\nRequirement already satisfied: h5py in /tensorflow-2.1.0/python3.6 (from keras-applications>=1.0.8->tensorflow-gpu) (2.10.0)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /tensorflow-2.1.0/python3.6 (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (1.25.7)\nRequirement already satisfied: certifi>=2017.4.17 in /tensorflow-2.1.0/python3.6 (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (2019.11.28)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in /tensorflow-2.1.0/python3.6 (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (3.0.4)\nRequirement already satisfied: idna<2.9,>=2.5 in /tensorflow-2.1.0/python3.6 (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (2.8)\nRequirement already satisfied: requests-oauthlib>=0.7.0 in /tensorflow-2.1.0/python3.6 (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (1.3.0)\nRequirement already satisfied: pyasn1-modules>=0.2.1 in /tensorflow-2.1.0/python3.6 (from google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (0.2.8)\nRequirement already satisfied: rsa<4.1,>=3.1.4 in /tensorflow-2.1.0/python3.6 (from google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (4.0)\nRequirement already satisfied: cachetools<5.0,>=2.0.0 in /tensorflow-2.1.0/python3.6 (from google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (4.0.0)\nRequirement already satisfied: oauthlib>=3.0.0 in /tensorflow-2.1.0/python3.6 (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (3.1.0)\nRequirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /tensorflow-2.1.0/python3.6 (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow-gpu) (0.4.8)\n`%tensorflow_version` only switches the major version: `1.x` or `2.x`.\nYou set: `2.x # Colab only.`. This will be interpreted as: `2.x`.\n\n\nTensorFlow is already loaded. Please restart the runtime to change versions.\n2.1.0-rc1\n/device:GPU:0\nNum GPUs Available: 1\n"
],
[
"#imports some required libraries\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.layers import Input, Conv2D, Dense, Flatten, Dropout, MaxPooling2D\nfrom tensorflow.keras.models import Model",
"_____no_output_____"
],
[
"# Load in the data\nfashion_mnist = tf.keras.datasets.fashion_mnist\n\n(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\nprint(\"x_train.shape:\", x_train.shape)",
"x_train.shape: (60000, 28, 28)\n"
],
[
"# the data is only 2D!\n# convolution expects height x width x color\nx_train = np.expand_dims(x_train, -1)\nx_test = np.expand_dims(x_test, -1)\nprint(x_train.shape)",
"(60000, 28, 28, 1)\n"
],
[
"# number of classes\nK = len(set(y_train))\nprint(\"number of classes:\", K)",
"number of classes: 10\n"
],
[
"# Build the model using the functional API\ni = Input(shape=x_train[0].shape)\nx = Conv2D(128, (3, 3), strides=2, activation='relu', padding='same')(i)\nx = Conv2D(256, (3, 3), strides=2, activation='relu', padding='same')(x)\nx = MaxPooling2D((3, 3))(x)\nx = Conv2D(512, (3, 3), strides=2, activation='relu', padding='same')(x)\nx = Flatten()(x)\nx = Dropout(0.2)(x)\nx = Dense(1024, activation='relu')(x)\nx = Dropout(0.2)(x)\nx = Dense(512, activation='relu')(x)\nx = Dropout(0.2)(x)\nx = Dense(K, activation='softmax')(x)\n\nmodel = Model(i, x)",
"_____no_output_____"
],
[
"# Compile and fit\n# Note: make sure you are using the GPU for this!\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\nhistory = model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=25)",
"Train on 60000 samples, validate on 10000 samples\nEpoch 1/25\n60000/60000 [==============================] - 11s 186us/sample - loss: 0.5182 - accuracy: 0.8058 - val_loss: 0.3777 - val_accuracy: 0.8604\nEpoch 2/25\n60000/60000 [==============================] - 11s 180us/sample - loss: 0.3504 - accuracy: 0.8714 - val_loss: 0.3413 - val_accuracy: 0.8738\nEpoch 3/25\n60000/60000 [==============================] - 11s 178us/sample - loss: 0.3036 - accuracy: 0.8868 - val_loss: 0.3114 - val_accuracy: 0.8859\nEpoch 4/25\n60000/60000 [==============================] - 11s 176us/sample - loss: 0.2733 - accuracy: 0.8999 - val_loss: 0.3091 - val_accuracy: 0.8921\nEpoch 5/25\n60000/60000 [==============================] - 11s 177us/sample - loss: 0.2521 - accuracy: 0.9082 - val_loss: 0.3053 - val_accuracy: 0.8921\nEpoch 6/25\n60000/60000 [==============================] - 11s 178us/sample - loss: 0.2337 - accuracy: 0.9136 - val_loss: 0.3015 - val_accuracy: 0.8886\nEpoch 7/25\n60000/60000 [==============================] - 11s 178us/sample - loss: 0.2160 - accuracy: 0.9196 - val_loss: 0.3060 - val_accuracy: 0.8952\nEpoch 8/25\n60000/60000 [==============================] - 11s 180us/sample - loss: 0.2060 - accuracy: 0.9230 - val_loss: 0.3325 - val_accuracy: 0.8909\nEpoch 9/25\n60000/60000 [==============================] - 11s 181us/sample - loss: 0.1899 - accuracy: 0.9300 - val_loss: 0.3158 - val_accuracy: 0.9010\nEpoch 10/25\n60000/60000 [==============================] - 11s 180us/sample - loss: 0.1813 - accuracy: 0.9332 - val_loss: 0.2998 - val_accuracy: 0.9002\nEpoch 11/25\n60000/60000 [==============================] - 11s 178us/sample - loss: 0.1687 - accuracy: 0.9390 - val_loss: 0.3184 - val_accuracy: 0.9033\nEpoch 12/25\n60000/60000 [==============================] - 11s 178us/sample - loss: 0.1586 - accuracy: 0.9411 - val_loss: 0.3321 - val_accuracy: 0.9016\nEpoch 13/25\n60000/60000 [==============================] - 11s 177us/sample - loss: 0.1551 - accuracy: 0.9431 - val_loss: 0.3635 - val_accuracy: 0.9007\nEpoch 14/25\n60000/60000 [==============================] - 11s 180us/sample - loss: 0.1471 - accuracy: 0.9466 - val_loss: 0.3772 - val_accuracy: 0.9008\nEpoch 15/25\n60000/60000 [==============================] - 11s 181us/sample - loss: 0.1411 - accuracy: 0.9483 - val_loss: 0.3605 - val_accuracy: 0.9047\nEpoch 16/25\n60000/60000 [==============================] - 11s 177us/sample - loss: 0.1326 - accuracy: 0.9509 - val_loss: 0.3678 - val_accuracy: 0.8996\nEpoch 17/25\n60000/60000 [==============================] - 11s 178us/sample - loss: 0.1324 - accuracy: 0.9522 - val_loss: 0.3609 - val_accuracy: 0.9034\nEpoch 18/25\n60000/60000 [==============================] - 11s 177us/sample - loss: 0.1224 - accuracy: 0.9555 - val_loss: 0.3594 - val_accuracy: 0.9065\nEpoch 19/25\n60000/60000 [==============================] - 11s 179us/sample - loss: 0.1233 - accuracy: 0.9565 - val_loss: 0.3704 - val_accuracy: 0.9032\nEpoch 20/25\n60000/60000 [==============================] - 11s 179us/sample - loss: 0.1103 - accuracy: 0.9590 - val_loss: 0.4538 - val_accuracy: 0.9020\nEpoch 21/25\n60000/60000 [==============================] - 11s 181us/sample - loss: 0.1135 - accuracy: 0.9594 - val_loss: 0.4530 - val_accuracy: 0.8923\nEpoch 22/25\n60000/60000 [==============================] - 11s 177us/sample - loss: 0.1097 - accuracy: 0.9610 - val_loss: 0.4311 - val_accuracy: 0.9065\nEpoch 23/25\n60000/60000 [==============================] - 11s 179us/sample - loss: 0.1046 - accuracy: 0.9633 - val_loss: 0.4239 - val_accuracy: 0.9011\nEpoch 24/25\n60000/60000 [==============================] - 11s 178us/sample - loss: 0.1045 - accuracy: 0.9638 - val_loss: 0.4897 - val_accuracy: 0.9024\nEpoch 25/25\n60000/60000 [==============================] - 11s 179us/sample - loss: 0.1041 - accuracy: 0.9640 - val_loss: 0.5146 - val_accuracy: 0.9001\n"
],
[
"# Plot loss per iteration\nimport matplotlib.pyplot as plt\nplt.plot(history.history['loss'], label='loss')\nplt.plot(history.history['val_loss'], label='val_loss')\nplt.legend()",
"_____no_output_____"
],
[
"# Plot accuracy per iteration\nplt.plot(history.history['accuracy'], label='acc')\nplt.plot(history.history['val_accuracy'], label='val_acc')\nplt.legend()",
"_____no_output_____"
],
[
"# Plot confusion matrix\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.show()\n\n\np_test = model.predict(x_test).argmax(axis=1)\ncm = confusion_matrix(y_test, p_test)\nplot_confusion_matrix(cm, list(range(10)))\n\n",
"Confusion matrix, without normalization\n[[830 2 14 39 5 0 102 0 7 1]\n [ 3 982 0 10 1 0 3 0 1 0]\n [ 15 0 843 9 56 0 77 0 0 0]\n [ 12 6 12 915 39 0 16 0 0 0]\n [ 0 1 69 27 831 0 71 0 1 0]\n [ 0 0 0 0 0 973 0 17 3 7]\n [101 1 61 41 63 0 723 0 10 0]\n [ 0 0 0 0 0 10 0 979 0 11]\n [ 7 0 3 4 4 2 5 1 974 0]\n [ 0 1 0 0 0 5 0 43 0 951]]\n"
],
[
"# Label mapping\nlabels = '''T-shirt/top\nTrouser\nPullover\nDress\nCoat\nSandal\nShirt\nSneaker\nBag\nAnkle boot'''.split(\"\\n\")",
"_____no_output_____"
],
[
"# Show some misclassified examples\nmisclassified_idx = np.where(p_test != y_test)[0]\ni = np.random.choice(misclassified_idx)\nplt.imshow(x_test[i].reshape(28,28), cmap='gray')\nplt.title(\"True label: %s Predicted: %s\" % (labels[y_test[i]], labels[p_test[i]]));",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a35ef4683b15a82f5689d6125cda6f6b6f27da3
| 573 |
ipynb
|
Jupyter Notebook
|
docs/user-guide/hyperparameter-tuning.ipynb
|
Leo-VK/creme
|
0b02df4f4c826368747ee91946efca1a7e8653a6
|
[
"BSD-3-Clause"
] | 23 |
2020-11-21T22:09:24.000Z
|
2022-03-21T22:33:07.000Z
|
docs/user-guide/hyperparameter-tuning.ipynb
|
Leo-VK/creme
|
0b02df4f4c826368747ee91946efca1a7e8653a6
|
[
"BSD-3-Clause"
] | null | null | null |
docs/user-guide/hyperparameter-tuning.ipynb
|
Leo-VK/creme
|
0b02df4f4c826368747ee91946efca1a7e8653a6
|
[
"BSD-3-Clause"
] | 1 |
2021-04-25T16:24:43.000Z
|
2021-04-25T16:24:43.000Z
| 16.371429 | 34 | 0.516579 |
[
[
[
"# Hyperparameter tuning\n\nTo do.",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown"
]
] |
4a35f5fa90a85fa366edeec40ff2323d3d520d32
| 44,522 |
ipynb
|
Jupyter Notebook
|
python-part-1-workshop-notes-7-10-2020.ipynb
|
geoffswc/IntroToPythonPart1
|
972b012163d3f175e54d751812616ff8e08db42b
|
[
"MIT"
] | 5 |
2018-10-05T20:46:14.000Z
|
2021-09-25T07:21:28.000Z
|
python-part-1-workshop-notes-7-10-2020.ipynb
|
geoffswc/IntroToPythonPart1
|
972b012163d3f175e54d751812616ff8e08db42b
|
[
"MIT"
] | null | null | null |
python-part-1-workshop-notes-7-10-2020.ipynb
|
geoffswc/IntroToPythonPart1
|
972b012163d3f175e54d751812616ff8e08db42b
|
[
"MIT"
] | 1 |
2019-04-22T16:54:00.000Z
|
2019-04-22T16:54:00.000Z
| 21.37398 | 1,769 | 0.447711 |
[
[
[
"print(\"hello world\")",
"hello world\n"
],
[
"1 + (3 * 4) + 5",
"_____no_output_____"
],
[
"(1 + 3) * (4 + 5)",
"_____no_output_____"
],
[
"2**4",
"_____no_output_____"
],
[
"temperature = 72.5",
"_____no_output_____"
],
[
"print(\"temperature\")",
"temperature\n"
],
[
"print(temperature)",
"72.5\n"
],
[
"type(temperature)",
"_____no_output_____"
],
[
"day_of_week = 3",
"_____no_output_____"
],
[
"type(day_of_week)",
"_____no_output_____"
],
[
"day = \"tuesday\"",
"_____no_output_____"
],
[
"type(day)",
"_____no_output_____"
],
[
"print(day)",
"tuesday\n"
],
[
"whos",
"Variable Type Data/Info\n--------------------------------\nday str tuesday\nday_of_week int 3\ntemperature float 72.5\n"
],
[
"day_of_week + 1",
"_____no_output_____"
],
[
"print(day)\nprint(temperature)",
"tuesday\n72.5\n"
],
[
"day_of_week",
"_____no_output_____"
],
[
"day_of_week + 1",
"_____no_output_____"
],
[
"day_of_week = 4",
"_____no_output_____"
],
[
"day_of_week",
"_____no_output_____"
],
[
"day_of_week = day_of_week + 1",
"_____no_output_____"
],
[
"day_of_week",
"_____no_output_____"
],
[
"day_of_week = day_of_week + 10",
"_____no_output_____"
],
[
"day_of_week",
"_____no_output_____"
],
[
"day",
"_____no_output_____"
],
[
"day + 10",
"_____no_output_____"
],
[
"\"20\" + 30",
"_____no_output_____"
],
[
"\"20\" + str(30)",
"_____no_output_____"
],
[
"int(\"20\") + 30 + \" \" + 40",
"_____no_output_____"
],
[
"# exercise\n# create a humidity (humidity = 0.6)\n# create a temperature = 75\n# create a day \"saturday\"\n# try printing out humidity + temperature\n# try printing out day plus temperature\n# try printing day plus temperature plus humidity (with spaces between)\n# takes you through\n# creating variables\n# converting variables\n# adding them\n# printing\n# take 5 min (til 10:07 now)",
"_____no_output_____"
],
[
"humidity = 0.6\ntemperature = 75\nday = \"saturday\"",
"_____no_output_____"
],
[
"print(humidity + temperature)",
"75.6\n"
],
[
"print(day + \" \" + str(humidity) + \" \" + str(temperature))",
"saturday 0.6 75\n"
],
[
"print(day, humidity, temperature)",
"saturday 0.6 75\n"
],
[
"# built in functions and help",
"_____no_output_____"
],
[
"max(1, 5, 2, 6)",
"_____no_output_____"
],
[
"min(1, 5, 2, 6)",
"_____no_output_____"
],
[
"#cos(3.14)",
"_____no_output_____"
],
[
"import math",
"_____no_output_____"
],
[
"math.cos(3.14)",
"_____no_output_____"
],
[
"#alias",
"_____no_output_____"
],
[
"import math as m",
"_____no_output_____"
],
[
"m.cos(3.14)",
"_____no_output_____"
],
[
"from math import cos",
"_____no_output_____"
],
[
"cos(3.14)",
"_____no_output_____"
],
[
"m.pi",
"_____no_output_____"
],
[
"m.e",
"_____no_output_____"
],
[
"cos(m.pi)",
"_____no_output_____"
],
[
"help(math)",
"Help on module math:\n\nNAME\n math\n\nMODULE REFERENCE\n https://docs.python.org/3.6/library/math\n \n The following documentation is automatically generated from the Python\n source files. It may be incomplete, incorrect or include features that\n are considered implementation detail and may vary between Python\n implementations. When in doubt, consult the module reference at the\n location listed above.\n\nDESCRIPTION\n This module is always available. It provides access to the\n mathematical functions defined by the C standard.\n\nFUNCTIONS\n acos(...)\n acos(x)\n \n Return the arc cosine (measured in radians) of x.\n \n acosh(...)\n acosh(x)\n \n Return the inverse hyperbolic cosine of x.\n \n asin(...)\n asin(x)\n \n Return the arc sine (measured in radians) of x.\n \n asinh(...)\n asinh(x)\n \n Return the inverse hyperbolic sine of x.\n \n atan(...)\n atan(x)\n \n Return the arc tangent (measured in radians) of x.\n \n atan2(...)\n atan2(y, x)\n \n Return the arc tangent (measured in radians) of y/x.\n Unlike atan(y/x), the signs of both x and y are considered.\n \n atanh(...)\n atanh(x)\n \n Return the inverse hyperbolic tangent of x.\n \n ceil(...)\n ceil(x)\n \n Return the ceiling of x as an Integral.\n This is the smallest integer >= x.\n \n copysign(...)\n copysign(x, y)\n \n Return a float with the magnitude (absolute value) of x but the sign \n of y. On platforms that support signed zeros, copysign(1.0, -0.0) \n returns -1.0.\n \n cos(...)\n cos(x)\n \n Return the cosine of x (measured in radians).\n \n cosh(...)\n cosh(x)\n \n Return the hyperbolic cosine of x.\n \n degrees(...)\n degrees(x)\n \n Convert angle x from radians to degrees.\n \n erf(...)\n erf(x)\n \n Error function at x.\n \n erfc(...)\n erfc(x)\n \n Complementary error function at x.\n \n exp(...)\n exp(x)\n \n Return e raised to the power of x.\n \n expm1(...)\n expm1(x)\n \n Return exp(x)-1.\n This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.\n \n fabs(...)\n fabs(x)\n \n Return the absolute value of the float x.\n \n factorial(...)\n factorial(x) -> Integral\n \n Find x!. Raise a ValueError if x is negative or non-integral.\n \n floor(...)\n floor(x)\n \n Return the floor of x as an Integral.\n This is the largest integer <= x.\n \n fmod(...)\n fmod(x, y)\n \n Return fmod(x, y), according to platform C. x % y may differ.\n \n frexp(...)\n frexp(x)\n \n Return the mantissa and exponent of x, as pair (m, e).\n m is a float and e is an int, such that x = m * 2.**e.\n If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.\n \n fsum(...)\n fsum(iterable)\n \n Return an accurate floating point sum of values in the iterable.\n Assumes IEEE-754 floating point arithmetic.\n \n gamma(...)\n gamma(x)\n \n Gamma function at x.\n \n gcd(...)\n gcd(x, y) -> int\n greatest common divisor of x and y\n \n hypot(...)\n hypot(x, y)\n \n Return the Euclidean distance, sqrt(x*x + y*y).\n \n isclose(...)\n isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool\n \n Determine whether two floating point numbers are close in value.\n \n rel_tol\n maximum difference for being considered \"close\", relative to the\n magnitude of the input values\n abs_tol\n maximum difference for being considered \"close\", regardless of the\n magnitude of the input values\n \n Return True if a is close in value to b, and False otherwise.\n \n For the values to be considered close, the difference between them\n must be smaller than at least one of the tolerances.\n \n -inf, inf and NaN behave similarly to the IEEE 754 Standard. That\n is, NaN is not close to anything, even itself. inf and -inf are\n only close to themselves.\n \n isfinite(...)\n isfinite(x) -> bool\n \n Return True if x is neither an infinity nor a NaN, and False otherwise.\n \n isinf(...)\n isinf(x) -> bool\n \n Return True if x is a positive or negative infinity, and False otherwise.\n \n isnan(...)\n isnan(x) -> bool\n \n Return True if x is a NaN (not a number), and False otherwise.\n \n ldexp(...)\n ldexp(x, i)\n \n Return x * (2**i).\n \n lgamma(...)\n lgamma(x)\n \n Natural logarithm of absolute value of Gamma function at x.\n \n log(...)\n log(x[, base])\n \n Return the logarithm of x to the given base.\n If the base not specified, returns the natural logarithm (base e) of x.\n \n log10(...)\n log10(x)\n \n Return the base 10 logarithm of x.\n \n log1p(...)\n log1p(x)\n \n Return the natural logarithm of 1+x (base e).\n The result is computed in a way which is accurate for x near zero.\n \n log2(...)\n log2(x)\n \n Return the base 2 logarithm of x.\n \n modf(...)\n modf(x)\n \n Return the fractional and integer parts of x. Both results carry the sign\n of x and are floats.\n \n pow(...)\n pow(x, y)\n \n Return x**y (x to the power of y).\n \n radians(...)\n radians(x)\n \n Convert angle x from degrees to radians.\n \n sin(...)\n sin(x)\n \n Return the sine of x (measured in radians).\n \n sinh(...)\n sinh(x)\n \n Return the hyperbolic sine of x.\n \n sqrt(...)\n sqrt(x)\n \n Return the square root of x.\n \n tan(...)\n tan(x)\n \n Return the tangent of x (measured in radians).\n \n tanh(...)\n tanh(x)\n \n Return the hyperbolic tangent of x.\n \n trunc(...)\n trunc(x:Real) -> Integral\n \n Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.\n\nDATA\n e = 2.718281828459045\n inf = inf\n nan = nan\n pi = 3.141592653589793\n tau = 6.283185307179586\n\nFILE\n /anaconda3/lib/python3.6/lib-dynload/math.cpython-36m-darwin.so\n\n\n"
],
[
"# exercise\n# calculate the sin of two times pi\n# try another method or two from the math library\n# (maybe calculate the natural log of euler's constant)\n# take 5 min (til 10:28)",
"_____no_output_____"
],
[
"m.sin(round(2 * m.pi, 2))",
"_____no_output_____"
],
[
"m.log(m.e)",
"_____no_output_____"
],
[
"m.log10(10)",
"_____no_output_____"
],
[
"# reconvene at 10:42",
"_____no_output_____"
],
[
"# lists, loops, and conditionals",
"_____no_output_____"
],
[
"temperatures = [76, 73, 71, 68, 72, 65, 75]",
"_____no_output_____"
],
[
"temperatures[0]",
"_____no_output_____"
],
[
"temperatures[1]",
"_____no_output_____"
],
[
"temperatures[6]",
"_____no_output_____"
],
[
"temperatures[-1]",
"_____no_output_____"
],
[
"temperatures[-2]",
"_____no_output_____"
],
[
"temperatures[0:4]",
"_____no_output_____"
],
[
"temperatures[4:7]",
"_____no_output_____"
],
[
"len(temperatures)",
"_____no_output_____"
],
[
"temperatures[2:len(temperatures)]",
"_____no_output_____"
],
[
"temperatures[:4]",
"_____no_output_____"
],
[
"# exercise\n# create a new list called humidities\n# values [.6, .65, .7, .75, .65, .6, .55]\n# print the full list\n# print the length of the list\n# print from index 2 through 5\n# take til 11:00am",
"_____no_output_____"
],
[
"humidities = [.6, .65, .7, .75, .65, .6, .55]",
"_____no_output_____"
],
[
"print(humidities)",
"[0.6, 0.65, 0.7, 0.75, 0.65, 0.6, 0.55]\n"
],
[
"len(humidities)",
"_____no_output_____"
],
[
"humidities[2:6]",
"_____no_output_____"
],
[
"# enumerator\nprint(temperatures)\n\nfor t in temperatures:\n t = t + 10\n print(t)\n\nprint(\"all done!\")",
"[76, 73, 71, 68, 72, 65, 75]\n86\n83\n81\n78\n82\n75\n85\nall done!\n"
],
[
"# exercise - take the code in cell 110, and replace temperatures with humidities\n# move various print calls (either print(h) or print(\"all done\") in and out of the loop\n# take 5 min to do this, resume at 11:18\n# try out tuples vs lists if you have extra time",
"_____no_output_____"
],
[
"# tuples",
"_____no_output_____"
],
[
"humidities_tuple = (.5, .6, 7, .8)",
"_____no_output_____"
],
[
"for h in humidities_tuple:\n print(h)",
"0.5\n0.6\n7\n0.8\n"
],
[
"humidities_tuple[2]",
"_____no_output_____"
],
[
"my_list = [1, 2, 3, 4]",
"_____no_output_____"
],
[
"my_tuple = (1, 2, 3, 4)",
"_____no_output_____"
],
[
"my_list[2] = 10",
"_____no_output_____"
],
[
"my_list",
"_____no_output_____"
],
[
"temperatures",
"_____no_output_____"
],
[
"# enumerator\nfor t in temperatures:\n print(t)",
"76\n73\n71\n68\n72\n65\n75\n"
],
[
"# iterator\nfor i in range(len(temperatures)):\n print(i, temperatures[i])",
"0 76\n1 73\n2 71\n3 68\n4 72\n5 65\n6 75\n"
],
[
"# a couple of common errors in loop processing, using iterator syntax with enumerator values",
"_____no_output_____"
],
[
"#for t in temperatures:\n# print(t)\n# print(temperatures[t])",
"_____no_output_____"
],
[
"#for h in humidities:\n# print(h)\n# print(humidities[h])",
"_____no_output_____"
],
[
"for i in range(len(temperatures)):\n print(i, temperatures[i], humidities[i])",
"0 76 0.6\n1 73 0.65\n2 71 0.7\n3 68 0.75\n4 72 0.65\n5 65 0.6\n6 75 0.55\n"
],
[
"# exercise\n# days of the week\n# days = ['sunday', 'monday', ...]\n# add days[i] to the loop above\n# take 5 min, back at 11:38",
"_____no_output_____"
],
[
"days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']",
"_____no_output_____"
],
[
"for i in range(len(days)):\n print(i, days[i], temperatures[i], humidities[i])",
"0 sunday 76 0.6\n1 monday 73 0.65\n2 tuesday 71 0.7\n3 wednesday 68 0.75\n4 thursday 72 0.65\n5 friday 65 0.6\n6 saturday 75 0.55\n"
],
[
"for i in range(len(day)):\n if temperatures[i] > 72:\n print(\"it's hot\", temperatures[i])\n elif temperatures[i] > 70 or humidities[i] > .6:\n print(\"it's warm\", temperatures[i])\n else:\n print(\"it's cold\", temperatures[i])\n ",
"it's hot 76\nit's hot 73\nit's warm 71\nit's warm 68\nit's warm 72\nit's cold 65\nit's hot 75\n"
],
[
"# as an exercise on your own, I'd recommend doing this with humidities or a combination of temp and humidity",
"_____no_output_____"
],
[
"day",
"_____no_output_____"
],
[
"day[2]",
"_____no_output_____"
],
[
"temperature = 75",
"_____no_output_____"
],
[
"temperature[1]",
"_____no_output_____"
],
[
"for d in day:\n print(d)",
"s\na\nt\nu\nr\nd\na\ny\n"
],
[
"day[3]",
"_____no_output_____"
],
[
"day[3] = 'w'",
"_____no_output_____"
],
[
"day",
"_____no_output_____"
],
[
"days",
"_____no_output_____"
],
[
"len(day)",
"_____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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a35f96336372662b0ebb3462aae57be202805c3
| 39,850 |
ipynb
|
Jupyter Notebook
|
exercise_notebooks_my_solutions/2. Neural Networks/intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
|
Yixuan-Lee/udacity-deep-learning-nanodegree
|
bbdb8cff14bb5f6726ab36112b17e040bcc3baa9
|
[
"MIT"
] | null | null | null |
exercise_notebooks_my_solutions/2. Neural Networks/intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
|
Yixuan-Lee/udacity-deep-learning-nanodegree
|
bbdb8cff14bb5f6726ab36112b17e040bcc3baa9
|
[
"MIT"
] | null | null | null |
exercise_notebooks_my_solutions/2. Neural Networks/intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
|
Yixuan-Lee/udacity-deep-learning-nanodegree
|
bbdb8cff14bb5f6726ab36112b17e040bcc3baa9
|
[
"MIT"
] | 1 |
2022-02-10T03:23:47.000Z
|
2022-02-10T03:23:47.000Z
| 107.412399 | 24,056 | 0.846123 |
[
[
[
"# Classifying Fashion-MNIST\n\nNow it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% accuracy. Fashion-MNIST is a set of 28x28 greyscale images of clothes. It's more complex than MNIST, so it's a better representation of the actual performance of your network, and a better representation of datasets you'll use in the real world.\n\n<img src='assets/fashion-mnist-sprite.png' width=500px>\n\nIn this notebook, you'll build your own neural network. For the most part, you could just copy and paste the code from Part 3, but you wouldn't be learning. It's important for you to write the code yourself and get it to work. Feel free to consult the previous notebooks though as you work through this.\n\nFirst off, let's load the dataset through torchvision.",
"_____no_output_____"
]
],
[
[
"import torch\nfrom torchvision import datasets, transforms\nimport helper\n\n# Define a transform to normalize the data\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))])\n# Download and load the training data\ntrainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n\n# Download and load the test data\ntestset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)",
"Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to /Users/liyixuan/.pytorch/F_MNIST_data/FashionMNIST/raw/train-images-idx3-ubyte.gz\n"
]
],
[
[
"Here we can see one of the images.",
"_____no_output_____"
]
],
[
[
"image, label = next(iter(trainloader))\nhelper.imshow(image[0,:]);",
"_____no_output_____"
]
],
[
[
"## Building the network\n\nHere you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits or log-softmax from the forward pass. It's up to you how many layers you add and the size of those layers.",
"_____no_output_____"
]
],
[
[
"# TODO: Define your network architecture here\nfrom torch import nn\nimport torch.nn.functional as F\n\nclass Network(nn.Module):\n def __init__(self):\n super().__init__()\n \n # Here I choose to use the same network architecture as in MNIST\n self.fc1 = nn.Linear(784, 256)\n self.fc2 = nn.Linear(256, 128)\n self.fc3 = nn.Linear(128, 64)\n self.fc4 = nn.Linear(64, 32)\n self.fc5 = nn.Linear(32, 10)\n \n def forward(self, x):\n # make sure x is flattened\n x = x.view(x.shape[0], -1)\n \n x = self.fc1(x)\n x = F.relu(x)\n x = self.fc2(x)\n x = F.relu(x)\n x = self.fc3(x)\n x = F.relu(x)\n x = self.fc4(x)\n x = F.relu(x)\n x = self.fc5(x)\n x = F.softmax(x, dim=1)\n \n return x",
"_____no_output_____"
]
],
[
[
"# Train the network\n\nNow you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.html#loss-functions) ( something like `nn.CrossEntropyLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam`).\n\nThen write the training code. Remember the training pass is a fairly straightforward process:\n\n* Make a forward pass through the network to get the logits \n* Use the logits to calculate the loss\n* Perform a backward pass through the network with `loss.backward()` to calculate the gradients\n* Take a step with the optimizer to update the weights\n\nBy adjusting the hyperparameters (hidden units, learning rate, etc), you should be able to get the training loss below 0.4.",
"_____no_output_____"
]
],
[
[
"# TODO: Create the network\nmodel = Network()\nmodel",
"_____no_output_____"
],
[
"# TODO: Define the criterion and optimizer\ncriterion = nn.CrossEntropyLoss()\n\nfrom torch import optim\noptimizer = optim.SGD(model.parameters(), lr=0.03) # perform quite well\n# optimizer = optim.Adam(model.parameters(), lr=0.001) # perform not very well",
"_____no_output_____"
]
],
[
[
"**Lecture Note:**\n\nAdam optimizer uses momentum which speeds up the actual fitting process.\n\nAdam optimizer adjusts the learning rate for each of the individual parameter in the Network.",
"_____no_output_____"
]
],
[
[
"# TODO: Train the network here\nepochs = 5\n\nfor e in range(epochs):\n running_loss = 0\n \n for images, labels in trainloader:\n # flatten the images into a (n_samples, features) vector\n# images = images.view(images.shape[0], -1)\n \n # Training pass\n optimizer.zero_grad()\n output = model(images)\n loss = criterion(output, labels)\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item()\n else:\n print(f\"Training loss: {running_loss/len(trainloader)}\")",
"Training loss: 1.9475594691630365\nTraining loss: 1.8130571169893879\nTraining loss: 1.7529841395837666\nTraining loss: 1.7226296820874407\nTraining loss: 1.707173342770859\n"
],
[
"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport helper\n\n# Test out your network!\n\ndataiter = iter(testloader)\nimages, labels = dataiter.next()\nimg = images[0]\n# Convert 2D image to 1D vector\nimg = img.resize_(1, 784)\n\n# TODO: Calculate the class probabilities (softmax) for img\nps = model.forward(img)\n\n# Plot the image and probabilities\nhelper.view_classify(img.resize_(1, 28, 28), ps, version='Fashion')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a35fc1c0c04390046473dd59430a3eaf3dbab36
| 39,371 |
ipynb
|
Jupyter Notebook
|
reading/week3_intro_ode.ipynb
|
BioSysDesign/E164
|
69f6236de2d8172e541a5b56f7807d4767f20979
|
[
"BSD-3-Clause"
] | null | null | null |
reading/week3_intro_ode.ipynb
|
BioSysDesign/E164
|
69f6236de2d8172e541a5b56f7807d4767f20979
|
[
"BSD-3-Clause"
] | null | null | null |
reading/week3_intro_ode.ipynb
|
BioSysDesign/E164
|
69f6236de2d8172e541a5b56f7807d4767f20979
|
[
"BSD-3-Clause"
] | null | null | null | 179.776256 | 18,696 | 0.898275 |
[
[
[
"# Week 3 of Introduction to Biological System Design\n## Introduction to Modeling Biological Processes\n### Ayush Pandey\n\nPre-requisite: If you have installed numpy, scipy, matplotlib, and pandas already, then you are all set to run this notebook.\n\nThis notebook introduces modeling of biological processes using differential equations. Note that to model the growth of any variable $x$, we can write a differential equation:\n\n$\\frac{dx}{dt} = f(x,t)$\n\nwhere the function $f(x,t)$ models the rate of change of the variable $x$. In this notebook, we will use this formalism of modeling systems (deterministic ordinary differential equations) to study transcription and translation.",
"_____no_output_____"
],
[
"# ODE Modeling with Python\n## Introduction to `scipy.integrate`\n\nFor Homework 2, you implemented your own numerical integrator by using a form of backward difference method to compute the derivative. This method is often referred to as the Euler's method to integrate differential equations. The scientific computing workhorse of the Python language `Scipy` consists of various integration algorithms. One of the best method in the `scipy.integrate` module is called `odeint`. We will use `odeint` in this notebook and throughout the course quite often to integrate ODE models. \n\nYou can look at the `odeint` documentation here: https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html\n\n\nLet us learn how to use `odeint` by simulating a simple birth and death model:",
"_____no_output_____"
],
[
"### Growth and death model\n\nLet us assume that a species $x$ grows at the rate $k$ and dies at a rate of $d$. We can write a one-variable ODE model for this species:\n\n$\\frac{dx}{dt} = k - d\\cdot x$\n\nTo simulate this model, we can integrate this ODE over a set of time points and plot the result as $x(t)$ vs $t$ on a graph. \n\nDefine the ODE as a Python function. We can use the `*args` argument to pass multiple parameters to our ODE. Inside the function, we can unfold args to get out the parameter values from it. The function defines the ODE by defining the right hand side of the differential equation. Recall that we used similar function definitions to integrate using our crude numerical integrator. ",
"_____no_output_____"
]
],
[
[
"def growth_death_ode(x, t, *args):\n k, d = args\n return k - d*x\n\nfrom scipy.integrate import odeint\nimport numpy as np\n# It is often helpful to use Python functions with keyword arguments, so we know \n# the meanings of the arguments that are passed. This is helpful in easy debugging, as well as in documenting the \n# code better.\nk = 1.0\nd = 0.1\ninitial_values = np.array([5])\ntimepoints = np.linspace(0,50,100)\nsolution = odeint(func = growth_death_ode, y0 = initial_values, t = timepoints, \n args = (k, d))",
"_____no_output_____"
]
],
[
[
"### Take a look at what odeint returns by running the next cell \n(uncomment to run)",
"_____no_output_____"
]
],
[
[
"# solution",
"_____no_output_____"
]
],
[
[
"### Plot the simulated ODE with time:",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nfig, ax = plt.subplots()\nax.plot(timepoints, solution, lw = 3)\nax.set_xlabel('$t$', fontsize = 18)\nax.set_ylabel('$x(t)$', fontsize = 18)\nax.tick_params(labelsize = 14)",
"_____no_output_____"
]
],
[
[
"You can compare odeint performance with your numerical integrator by running both simultaneously.",
"_____no_output_____"
],
[
"## Validate `odeint` simulation with analytical solution\n\nSince the birth-death model that we considered is a simple equation that can be integrated analytically, we can validate the numerical ODE simulation by comparing it to our analytical solution. Note that analytically solving an ODE is not possible for all kinds of ODEs, especially, as write more complicated models it may not be possible to obtain a closed form solution.\n\nFor the model above, the analytical solution is given by:\n\n$ x(t) = \\frac{k}{d}(1 - e^{-d(t - t_0)}) + x(0)e^{-d(t - t_0)}$\n\nLet us plot this analytical solution alongside the numerical simulation:",
"_____no_output_____"
]
],
[
[
"def analytical_solution(t, k, d, t0, x0):\n return (k/d)*(1 - np.exp(-d*(t - t0))) + x0*np.exp(-d*(t - t0))\n\nx0 = initial_values\nt0 = timepoints[0]\nfig, ax = plt.subplots()\nax.plot(timepoints, solution, lw = 3, label = 'numerical', alpha = 0.9)\nax.scatter(timepoints, analytical_solution(timepoints, k, d, t0, x0), c = 'r', \n marker = 'x', label = 'analytical')\nax.set_xlabel('$t$', fontsize = 18)\nax.set_ylabel('$x(t)$', fontsize = 18)\nax.legend(fontsize = 14)\nax.tick_params(labelsize = 14)",
"_____no_output_____"
]
],
[
[
"`odeint` has various options that you can explore in the documentation. For example, you can use the `rtol` and the `atol` option to set the tolerance levels of the integration algorithm. The tolerance levels decide the accuracy of the solution => lower the tolerance for error, more accurate the simulation, but also it is slower. So you have a speed-accuracy tradeoff. You can also take a look at the `infodict` that is returned when you pass in `full_output = True`. The `infodict` dictionary consists of information about the solver and the steps it took. Finally, an advanced version of `odeint` is `solve_ivp` which has multiple algorithms to integrate ODEs. However, the disadvantage is that it has slightly higher overhead and needs to be setup correctly inorder to get reliable simulations for ill-conditioned differential equations.",
"_____no_output_____"
]
],
[
[
" ",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a3605bfd83f06c0b15945b7570a1c751dca6cfd
| 30,856 |
ipynb
|
Jupyter Notebook
|
W4/Cross_Validation (1).ipynb
|
mthd98/the-khana
|
09fa5e72e5879b40ddd7bca59dcc67a1611886fd
|
[
"MIT"
] | 4 |
2021-08-27T23:05:12.000Z
|
2021-09-17T19:22:02.000Z
|
W4/Cross_Validation (1).ipynb
|
mthd98/the-khana
|
09fa5e72e5879b40ddd7bca59dcc67a1611886fd
|
[
"MIT"
] | null | null | null |
W4/Cross_Validation (1).ipynb
|
mthd98/the-khana
|
09fa5e72e5879b40ddd7bca59dcc67a1611886fd
|
[
"MIT"
] | 5 |
2021-08-30T18:44:21.000Z
|
2022-01-01T21:50:34.000Z
| 33.285868 | 396 | 0.381709 |
[
[
[
"# Cross Validation\n\n\nSplitting our datasetes into train/test sets allows us to test our model on unseen examples. However, it might be the case that we got a lucky (or unlucky) split that doesn't represent the model's actual performance. To solve this problem, we'll use a technique called cross-validation, where we use the entire dataset for training and for testing and evaluate the model accordingly.\n\nThere are several ways of performing cross-validation, and there are several corresponding iterators defined in scikit-learn. Each defines a `split` method, which will generate arrays of indices from the data set, each array indicating the instances to go into the training or testing set. \n",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nfrom sklearn import datasets, svm, metrics, model_selection",
"_____no_output_____"
],
[
"x, y = datasets.load_breast_cancer(return_X_y=True)",
"_____no_output_____"
],
[
"# Define a function to split our dataset into train/test splits using indices\n\ndef kfold_train_test_split(x, y, train_indices, test_indices):\n return x[train_indices], x[test_indices], y[train_indices], y[test_indices]",
"_____no_output_____"
]
],
[
[
"### `KFold`\n\n`KFold` is arguably the simplest. It partitions the data into $k$ folds. It does not attempt to keep the proportions of classes. \n",
"_____no_output_____"
]
],
[
[
"k_fold = model_selection.KFold(n_splits=10) # splits the data into 10 splits, using 9 for training and 1 for testing in each iteration\n\n# Empty array to store the scores\nscores = [] \n\nfor train_indices, test_indices in k_fold.split(x):\n # Split data using our predefined function\n x_train, x_test, y_train, y_test = kfold_train_test_split(x, y, train_indices, test_indices)\n\n # Train model\n svc = svm.SVC()\n svc.fit(x_train, y_train)\n\n # Predict using test set\n y_pred = svc.predict(x_test)\n\n # Calculate scores\n accuracy = metrics.accuracy_score(y_test, y_pred)\n precision = metrics.precision_score(y_test, y_pred)\n recall = metrics.recall_score(y_test, y_pred)\n\n # Create scores dictionary\n scores_dict = {\"accuracy\": accuracy, \"precision\": precision, \"recall\": recall}\n\n # Append to scores array\n scores.append(scores_dict)",
"_____no_output_____"
],
[
"# Conver scores array to dataframe\nscores_df = pd.DataFrame(scores)\nscores_df",
"_____no_output_____"
],
[
"# Calculate the mean of the scores\nscores_df.mean()",
"_____no_output_____"
]
],
[
[
"### `StratifiedKFold`\n\n`StratifiedKFold` ensures that the proportion of classes are preserved in each training/testing set. ",
"_____no_output_____"
]
],
[
[
"stratified_k_fold = model_selection.StratifiedKFold(n_splits=10) # splits the data into 10 splits, using 9 for training and 1 for testing in each iteration\n\n# Empty array to store the scores\nscores = [] \n\nfor train_indices, test_indices in stratified_k_fold.split(x, y): # y is needed here for stratification, similar to stratify = y. \n # Split data using our predefined function\n x_train, x_test, y_train, y_test = kfold_train_test_split(x, y, train_indices, test_indices)\n\n # Train model\n svc = svm.SVC()\n svc.fit(x_train, y_train)\n\n # Predict using test set\n y_pred = svc.predict(x_test)\n\n # Calculate scores\n accuracy = metrics.accuracy_score(y_test, y_pred)\n precision = metrics.precision_score(y_test, y_pred)\n recall = metrics.recall_score(y_test, y_pred)\n\n # Create scores dictionary\n scores_dict = {\"accuracy\": accuracy, \"precision\": precision, \"recall\": recall}\n\n # Append to scores array\n scores.append(scores_dict)",
"_____no_output_____"
],
[
"# Conver scores array to dataframe\nscores_df = pd.DataFrame(scores)\nscores_df",
"_____no_output_____"
],
[
"# Calculate the mean of the scores\nscores_df.mean()",
"_____no_output_____"
]
],
[
[
"### `ShuffleSplit`\n\n`ShuffleSplit` will generate indepedent pairs of randomly shuffled training and testing sets. ",
"_____no_output_____"
]
],
[
[
"shuffle_k_fold = model_selection.ShuffleSplit(n_splits=10, random_state=42) # splits the data into 10 splits, using 9 for training and 1 for testing in each iteration\n\n# Empty array to store the scores\nscores = [] \n\nfor train_indices, test_indices in shuffle_k_fold.split(x): \n # Split data using our predefined function\n x_train, x_test, y_train, y_test = kfold_train_test_split(x, y, train_indices, test_indices)\n\n # Train model\n svc = svm.SVC()\n svc.fit(x_train, y_train)\n\n # Predict using test set\n y_pred = svc.predict(x_test)\n\n # Calculate scores\n accuracy = metrics.accuracy_score(y_test, y_pred)\n precision = metrics.precision_score(y_test, y_pred)\n recall = metrics.recall_score(y_test, y_pred)\n\n # Create scores dictionary\n scores_dict = {\"accuracy\": accuracy, \"precision\": precision, \"recall\": recall}\n\n # Append to scores array\n scores.append(scores_dict)",
"_____no_output_____"
],
[
"# Conver scores array to dataframe\nscores_df = pd.DataFrame(scores)\nscores_df",
"_____no_output_____"
],
[
"# Calculate the mean of the scores\nscores_df.mean()",
"_____no_output_____"
]
],
[
[
"### `StratifiedShuffleSplit`\n\n`StratifiedShuffleSplit` will generate indepedent pairs of shuffled training and testing sets. Here, however, it will ensure the training and test sets are stratified. ",
"_____no_output_____"
]
],
[
[
"stratified_shuffled_k_fold = model_selection.StratifiedShuffleSplit(n_splits=10) # splits the data into 10 splits, using 9 for training and 1 for testing in each iteration\n\n# Empty array to store the scores\nscores = [] \n\nfor train_indices, test_indices in stratified_shuffled_k_fold.split(x, y): # y is needed here for stratification, similar to stratify = y. \n # Split data using our predefined function\n x_train, x_test, y_train, y_test = kfold_train_test_split(x, y, train_indices, test_indices)\n\n # Train model\n svc = svm.SVC()\n svc.fit(x_train, y_train)\n\n # Predict using test set\n y_pred = svc.predict(x_test)\n\n # Calculate scores\n accuracy = metrics.accuracy_score(y_test, y_pred)\n precision = metrics.precision_score(y_test, y_pred)\n recall = metrics.recall_score(y_test, y_pred)\n\n # Create scores dictionary\n scores_dict = {\"accuracy\": accuracy, \"precision\": precision, \"recall\": recall}\n\n # Append to scores array\n scores.append(scores_dict)",
"_____no_output_____"
],
[
"# Conver scores array to dataframe\nscores_df = pd.DataFrame(scores)\nscores_df",
"_____no_output_____"
],
[
"# Calculate the mean of the scores\nscores_df.mean()",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4a36112a559227716375998a6feef47adf7994cc
| 18,268 |
ipynb
|
Jupyter Notebook
|
Car.ipynb
|
vectosaurus/car-files
|
935fd910704555c850f98bfdcc6836b5273803ed
|
[
"Apache-2.0"
] | null | null | null |
Car.ipynb
|
vectosaurus/car-files
|
935fd910704555c850f98bfdcc6836b5273803ed
|
[
"Apache-2.0"
] | null | null | null |
Car.ipynb
|
vectosaurus/car-files
|
935fd910704555c850f98bfdcc6836b5273803ed
|
[
"Apache-2.0"
] | null | null | null | 34.533081 | 1,603 | 0.574338 |
[
[
[
"<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Cars-File\" data-toc-modified-id=\"Cars-File-1\"><span class=\"toc-item-num\">1 </span>Cars File</a></span><ul class=\"toc-item\"><li><span><a href=\"#Data-Preparation\" data-toc-modified-id=\"Data-Preparation-1.1\"><span class=\"toc-item-num\">1.1 </span>Data Preparation</a></span></li><li><span><a href=\"#Model-Building\" data-toc-modified-id=\"Model-Building-1.2\"><span class=\"toc-item-num\">1.2 </span>Model Building</a></span><ul class=\"toc-item\"><li><span><a href=\"#Logistic-Regression\" data-toc-modified-id=\"Logistic-Regression-1.2.1\"><span class=\"toc-item-num\">1.2.1 </span>Logistic Regression</a></span></li><li><span><a href=\"#Decision-Trees\" data-toc-modified-id=\"Decision-Trees-1.2.2\"><span class=\"toc-item-num\">1.2.2 </span>Decision Trees</a></span></li><li><span><a href=\"#Random-Forest\" data-toc-modified-id=\"Random-Forest-1.2.3\"><span class=\"toc-item-num\">1.2.3 </span>Random Forest</a></span></li><li><span><a href=\"#Multilayer-Perceptron\" data-toc-modified-id=\"Multilayer-Perceptron-1.2.4\"><span class=\"toc-item-num\">1.2.4 </span>Multilayer Perceptron</a></span></li></ul></li><li><span><a href=\"#Accuracy-metrics\" data-toc-modified-id=\"Accuracy-metrics-1.3\"><span class=\"toc-item-num\">1.3 </span>Accuracy metrics</a></span></li><li><span><a href=\"#Results\" data-toc-modified-id=\"Results-1.4\"><span class=\"toc-item-num\">1.4 </span>Results</a></span></li></ul></li></ul></div>",
"_____no_output_____"
],
[
"## Cars File",
"_____no_output_____"
],
[
"### Data Preparation",
"_____no_output_____"
],
[
"**Get all the packages and data ready**",
"_____no_output_____"
]
],
[
[
"# read in all packages\nlibrary(data.table)\nlibrary(caret)\nlibrary(dummy)\nlibrary(nnet)\nlibrary(randomForest)\nlibrary(RWeka)\n# set options\noptions(warn=-1)\n# read data\ndata <- fread(\"train.arff.csv\")",
"Warning message:\n“package ‘caret’ was built under R version 3.4.1”Loading required package: lattice\nLoading required package: ggplot2\nWarning message in as.POSIXlt.POSIXct(Sys.time()):\n“unknown timezone 'zone/tz/2017c.1.0/zoneinfo/Asia/Kolkata'”dummy 0.1.3\ndummyNews()\nrandomForest 4.6-12\nType rfNews() to see new features/changes/bug fixes.\n\nAttaching package: ‘randomForest’\n\nThe following object is masked from ‘package:ggplot2’:\n\n margin\n\nWarning message:\n“package ‘RWeka’ was built under R version 3.4.3”"
]
],
[
[
"**Check the data types**",
"_____no_output_____"
]
],
[
[
"# check data types\ndtypes <- as.matrix(sapply(data, class))",
"_____no_output_____"
]
],
[
[
"**Change the data types of the columns from characters to factors**",
"_____no_output_____"
]
],
[
[
"num_levels <- as.matrix(sapply(data, function(x){length(unique(x))}))\ndata_class_changed <- as.data.frame(sapply(data,as.factor))\ntarget_levels <- as.matrix(sapply(data_class_changed, class))",
"_____no_output_____"
]
],
[
[
"**Impute Missing values**",
"_____no_output_____"
]
],
[
[
"num_nas <- apply(data_class_changed, 2, function(x) sum(x == \" \"))",
"_____no_output_____"
]
],
[
[
"<p style=\"color:green;\"><b>Has no missing values↑</b></p>",
"_____no_output_____"
],
[
"**Note**: in this exercise, we wont be splitting the dataset into test and train due to shortage of time.",
"_____no_output_____"
],
[
"**Check balance of data**",
"_____no_output_____"
]
],
[
[
"target_levels_dist <- 100*table(data_class_changed$class)/dim(data_class_changed)[1]",
"_____no_output_____"
]
],
[
[
"** Rename the `class` column. `class` is a function in R**",
"_____no_output_____"
]
],
[
[
"colnames(data_class_changed)[7] <- \"category_type\"",
"_____no_output_____"
]
],
[
[
"### Model Building",
"_____no_output_____"
],
[
"#### Logistic Regression",
"_____no_output_____"
]
],
[
[
"covariates <- names(data_class_changed)[!names(data_class_changed) == \"category_type\"]\nx = (dummy(data_class_changed[covariates]))\nx = sapply(x, function(xx){as.numeric(xx)-1})\nnew_names<- names(x)\ny = data_class_changed[\"category_type\"]\ny = y$category_type",
"_____no_output_____"
],
[
"data_class_changed$category_type <- relevel(data_class_changed$category_type, ref = \"unacc\")\nmodel_logreg <- multinom(category_type ~ ., data = data_class_changed)\npredictions_logreg <- predict(model_logreg,data_class_changed)",
"# weights: 68 (48 variable)\ninitial value 1677.416177 \niter 10 value 463.498200\niter 20 value 365.099598\niter 30 value 238.326744\niter 40 value 184.638230\niter 50 value 171.070923\niter 60 value 170.716280\niter 70 value 170.672318\niter 80 value 170.660067\niter 90 value 170.659530\nfinal value 170.659524 \nconverged\n"
]
],
[
[
"#### Decision Trees",
"_____no_output_____"
]
],
[
[
"model_dt <- J48(category_type~., data=data_class_changed)\npredictions_dt <- predict(model_dt, data_class_changed)",
"_____no_output_____"
]
],
[
[
"#### Random Forest",
"_____no_output_____"
]
],
[
[
"model_rf <- randomForest(category_type~., data=data_class_changed)\npredictions_rf <- predict(model_rf, data_class_changed)",
"_____no_output_____"
]
],
[
[
"#### Multilayer Perceptron",
"_____no_output_____"
]
],
[
[
"model_mlp <- caret::train(x, y, method=\"mlp\")\npredictions_mlp <- predict(model_mlp, x)",
"Loading required package: Rcpp\n\nAttaching package: ‘RSNNS’\n\nThe following objects are masked from ‘package:caret’:\n\n confusionMatrix, train\n\n"
]
],
[
[
"### Accuracy metrics",
"_____no_output_____"
]
],
[
[
"y_true <- as.factor(data_class_changed[,\"category_type\"])\n\n# build all the confusion matrices\ncm_logreg <- as.data.frame.matrix(table(predictions_logreg, y_true))\ncm_dt <- as.data.frame.matrix(table(predictions_dt, y_true))\ncm_rf <- as.data.frame.matrix(table(predictions_rf, y_true))\ncm_mlp <- as.data.frame.matrix(table(predictions_mlp, y_true))",
"_____no_output_____"
],
[
"# rearrange\ncm_logreg <- cm_logreg[order(rownames(cm_logreg)),order(colnames(cm_logreg))]\ncm_dt <- cm_dt[order(rownames(cm_dt)),order(colnames(cm_dt))]\ncm_rf <- cm_rf[order(rownames(cm_rf)),order(colnames(cm_rf))]\ncm_mlp <- cm_mlp[order(rownames(cm_mlp)),order(colnames(cm_mlp))]",
"_____no_output_____"
],
[
"# function to caclulate class wise precision, accuracy, recall\nclassification_metrics <- function(conf_mat,model_type){\n precision <- diag(as.matrix(conf_mat)) / rowSums(conf_mat)\n recall <- diag(as.matrix(conf_mat)) / colSums(conf_mat)\n accuracy <- diag(as.matrix(conf_mat)) / sum(conf_mat)\n df <- data.frame(accuracy,precision,recall)\n colnames(df) <- paste(model_type,c(\"accuracy\",\"precision\",\"recall\"),sep=\"_\")\n df\n}",
"_____no_output_____"
],
[
"# get all metrics\nmetrics_logreg <- classification_metrics(cm_logreg, \"logreg\")\nmetrics_dt <- classification_metrics(cm_dt, \"dt\")\nmetrics_rf <- classification_metrics(cm_rf, \"rf\")\nmetrics_mlp <- classification_metrics(cm_mlp, \"mlp\")",
"_____no_output_____"
],
[
"# combine all and rearrange\nmetric_comparison <- cbind(metrics_logreg, metrics_dt,metrics_rf,metrics_mlp)\nrownames(metric_comparison) <- c(\"unacc\", \"acc\", \"good\", \"vgood\")\nmodels <- c(\"logreg\", \"dt\", \"rf\", \"mlp\")\nmetrics <- c(\"accuracy\", \"recall\", \"precision\")\nmodel_metrics <- paste(rep(models,3),rep(metrics,4),sep=\"_\")\naccy <- model_metrics[grep(\"accuracy\", model_metrics)][order(model_metrics[grep(\"accuracy\", model_metrics)])]\nrecl <- model_metrics[grep(\"recall\", model_metrics)][order(model_metrics[grep(\"recall\", model_metrics)])]\nprec <- model_metrics[grep(\"precision\", model_metrics)][order(model_metrics[grep(\"precision\", model_metrics)])]",
"_____no_output_____"
]
],
[
[
"### Results",
"_____no_output_____"
],
[
"The below table compares the classification metrics for each level and model. We have calculated three metrics for each model and level(levels here refers to each of the unique levels of the variable we are predicting: \"unacc\", \"acc\", \"good\", \"vgood\"). The metrics that we are calculating are: \n<ul>\n<li><i><b>Accuracy: </b></i>measures the fraction of all instances that are correctly categorized</li>\n<li><i><b>Recall: </b></i>is the proportion of people that tested positive and are positive (True Positive, TP) of all the people that actually are positive </li>\n<li><i><b>Precision: </b></i>it is the proportion of true positives out of all positive results</li>\n</ul>",
"_____no_output_____"
],
[
"<img src=\"Precisionrecall.png\" width = 300px>",
"_____no_output_____"
]
],
[
[
"metric_comparison[c(accy,recl,prec)]",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
4a36166289897ed96b614efcfdde37f19736d070
| 14,223 |
ipynb
|
Jupyter Notebook
|
exercises/clutter/analytic_antipodal_grasps.ipynb
|
Magician6174/manipulation
|
5e386e3a5bb2414693a72f7a4a606a7fd4188045
|
[
"BSD-3-Clause"
] | null | null | null |
exercises/clutter/analytic_antipodal_grasps.ipynb
|
Magician6174/manipulation
|
5e386e3a5bb2414693a72f7a4a606a7fd4188045
|
[
"BSD-3-Clause"
] | null | null | null |
exercises/clutter/analytic_antipodal_grasps.ipynb
|
Magician6174/manipulation
|
5e386e3a5bb2414693a72f7a4a606a7fd4188045
|
[
"BSD-3-Clause"
] | null | null | null | 37.527704 | 343 | 0.594038 |
[
[
[
"## **Analytic Antipodal Grasps**",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nfrom manipulation import running_as_notebook\n\nfrom pydrake.all import(\n Variable, sin, cos, Evaluate, Jacobian, atan, MathematicalProgram, Solve, eq\n)\n\nimport matplotlib.pyplot as plt, mpld3\nif running_as_notebook:\n mpld3.enable_notebook()",
"_____no_output_____"
]
],
[
[
"## Introduction to Symbolic Differentiation \n\nFor this assignment, you will need [symbolic differentiation](https://en.wikipedia.org/wiki/Computer_algebra), supported by Drake's symbolic library. We will demonstrate how to use it with a simple function: \n$$T=\\cos^2(x) + y^5$$\n\nand it's Jacobian (first-order derivative), \n$$J = \\begin{pmatrix} \\frac{\\partial T}{\\partial x} & \\frac{\\partial T}{\\partial y} \\end{pmatrix}=\\begin{pmatrix} -2\\cos(x)\\sin(x) & 5y^4 \\end{pmatrix}$$\n\nas well as the Hessian (second-order derivative), \n$$H = \\begin{pmatrix} \\frac{\\partial^2 T}{\\partial x^2} & \\frac{\\partial^2 T}{\\partial x \\partial y} \\\\ \\frac{\\partial^2 T}{\\partial y \\partial x} & \\frac{\\partial^2 T}{\\partial y^2} \\end{pmatrix}=\\begin{pmatrix} 2 \\sin^2(x) - 2\\cos^2(x) & 0 \\\\ 0 & 20y^3 \\end{pmatrix}$$\n\nBelow are some snippets of how to define symbolic variables, differentiate expressions, and evaluate them using numerical values. ",
"_____no_output_____"
]
],
[
[
"# 1. Symbolic variables are defined\nx = Variable('x')\ny = Variable('y')\n\n# 2. Expressions can be written by composing operations on Variables. \nT = cos(x) ** 2.0 + y ** 5.0\nprint(T)\n\n# 3. Use Evaluate to query the numerical value of the expression given the variable values. \n# Use function for multi-dimensional quantities\nprint(Evaluate(np.array([T]), {x: 3.0, y:5.0}))\n# Use method for scalar quantities \nprint(T.Evaluate({x: 3.0, y:5.0}))\n\n# 4. Differentiate a quantity using Jacobian, or Differentiate. \nJ = np.array([T.Differentiate(x), T.Differentiate(y)])\nprint(J)\n# Use method for scalar quantities \nJ = T.Jacobian([x, y])\nprint(J)\nprint(Evaluate(J, {x: 3.0, y:5.0}))\n\n# Use function for taking Jacobian of multi-dimensional quantities.\nH = Jacobian(J, [x, y])\nprint(H)\nprint(Evaluate(H, {x: 3.0, y: 5.0}))",
"_____no_output_____"
]
],
[
[
"Are the symbolic values of the Jacobian and Hessian what you expect? ",
"_____no_output_____"
],
[
"## The Cycloidal Gear\n\nNow we enter the main part of the problem. \n\nAfter graduating from MIT, you decide to work at a company producing cutting-edge [hypercycloidal gears](https://youtu.be/MBWkibie_5I?t=74). You are in charge of designing a robotic pick-and-place system for these parts. In order to reliably grasp the gears, you decide to use your knowledge of antipodal points. \n\nThe mechanical design department gave you a pretty ugly parametric equation for what the shape looks like, which we won't even bother writing in latex! Instead, we provided it via the function `shape`. \n\nGiven a angle in polar coordinates (parameter $t$), it returns $p(t)=[x(t),y(t)]$, a position in 2D. \n\nThe below cell implements the function and shows you what the gear part looks like. ",
"_____no_output_____"
]
],
[
[
"def shape(t):\n x = (10*cos(t))-(1.5*cos(t+atan(sin(-9*t)/((4/3)-cos(-9*t)))))-(0.75*cos(10*t))\n y = (-10*sin(t))+(1.5*sin(t+atan(sin(-9*t)/((4/3)-cos(-9*t)))))+(0.75*sin(10*t))\n return np.array([x, y])\n\ndef plot_gear():\n theta = np.linspace(0, 2*np.pi, 500)\n gear_shape = []\n for i in range(500):\n gear_shape.append(Evaluate(shape(theta[i])).squeeze())\n gear_shape = np.array(gear_shape)\n plt.axis(\"equal\")\n plt.plot(gear_shape[:,0], gear_shape[:,1], 'k-')\n\nplot_gear()",
"_____no_output_____"
]
],
[
[
"## Grasp Energy Function\n\nHow can we analytically find a pair of antipodal points given the parametric equation of a shape? We make the following claim: \n\n**Claim**: Let $p(t_1)$ and $p(t_2)$ be a pair of antipodal points given in parametric space. Then $t_1$ and $t_2$ are critical points of the following energy function:\n$$E=\\frac{1}{2}\\kappa\\|p(t_1)-p(t_2)\\|^2$$\n\nthat is, they satisfy $\\frac{\\partial E}{\\partial \\mathbf{t}}=[0, 0]$ where $\\mathbf{t}=[t_1,t_2]$. \n\nFor the subsequent problems, you may assume $\\kappa=2$. \n\n**Problem 5.1.a** [2pts]: Prove the claim. \\\\\n**Problem 5.1.b** [2pts]: Prove that the converse may not necessarily hold. \n\nHINT: The derivative of $p(t)$ respect to $t$ gives the tangent 'velocity' vector: $v(t)=p'(t)$\n\nWrite down your answer in a paper / pdf file, and submit to the Gradescope written submission section! ",
"_____no_output_____"
],
[
"## Implementation\n\n**Problem 5.1.c** [4pts]\nUsing this knowledge, we will write a Mathematical Program to find the antipodal points. Since we are looking for $t_1$ and $t_2$ such that the Jacobians is a zero vector, we are solving a root finding problem. Problems of this nature can still be transcribed as an instance of a Mathematical program; it simply doesn't have a cost. \n\nWe will write down our problem as follows: \n\n$$\\begin{aligned} \\text{find} \\quad & \\mathbf{t} \\\\ \\text{s.t.} \\quad & \\frac{\\partial E}{\\partial \\mathbf{t}}(\\mathbf{t}) = \\mathbf{0} \\\\ \\quad & 0 \\leq \\mathbf{t} \\leq 2\\pi \\\\ \\quad & t_1 - t_2 \\geq \\varepsilon \\end{aligned}$$\n\nThe first constraint makes sure that they are critical points of the energy function, while the last two makes sure the points are not overlapping. You will write the following outer loop to check for the validity of solutions.\n\n1. Pick a random guess for $\\mathbf{t}$ using [SetInitialGuess](https://drake.mit.edu/pydrake/pydrake.solvers.mathematicalprogram.html?highlight=setinitialguess#pydrake.solvers.mathematicalprogram.MathematicalProgram.SetInitialGuess) by uniform sampling over $[0, 2\\pi]$ (use `np.random.rand(2)`). \n2. Using `MathematicalProgram`, solve the above problem. Remember there is no cost in this problem, so we simply only add the constraints. \n3. If the solution is not valid (i.e. problem doesn't return success), repeat 1-2 with random guesses until a valid solution is found. \n4. If a valid solution $\\mathbf{t}^*$ is found, return the Eigenvalues of the Hessian of $E$ at $\\mathbf{t}^*$. (Use `np.linalg.eigvals`)",
"_____no_output_____"
]
],
[
[
"def find_antipodal_pts(shape):\n \"\"\"\n Finds antipodal points given the parametric function that describes the shape of the object.\n Args:\n - shape: function from parametric space t to position R2. \n Returns:\n - result: 2-dim np array that contains antipodal grasp locations parametrized by [t1, t2] \n - H_eig: 2-dim np array that contains eigenvalues of the Hessian. \n \"\"\"\n\n eps = 1e-3 # do not modify, but use it for epsilon variable above. \n\n ## Fill your code here \n result = np.array([0., 0.]) # modify here\n H_eig = np.array([0., 0.]) # modify here \n\n return result, H_eig",
"_____no_output_____"
]
],
[
[
"You can run the cell below to check the correctnes of your implementation. As the constraint is nonlinear, it might take some time to compute. (Typically, the solve time will still be less than 2~3 seconds).",
"_____no_output_____"
]
],
[
[
"def plot_antipodal_pts(pts, shape):\n antipodal_pts = []\n for i in range(2):\n val = Evaluate(shape(pts[i])).squeeze()\n antipodal_pts.append(val)\n antipodal_pts = np.array(antipodal_pts)\n plt.scatter(antipodal_pts[:,0], antipodal_pts[:,1], color='red')\n\nplot_gear()\nresult, H_eig = find_antipodal_pts(shape)\nplot_antipodal_pts(result, shape)\nprint(H_eig)",
"_____no_output_____"
]
],
[
[
"## Hessian Analysis\n\nWhy did we implement the Hessian? You may remember that if the Hessian is used for the second-derivative test. For a function $f(x)$ with a critical point $x^*$, this critical point is:\n- A local minima if the Hessian is positive-definite (i.e. all positive eigenvalues)\n- A local maxima if the Hessian is negative-definite (i.e. all negative eigenvalues)\n- A saddle point if the Hessian has mixed positive / negative eigenvalues. \n\n**Problem 5.1.d** [2pts] Describe what grasps the local minima, maxima, and saddle points correspond to in terms of the geometry of the object. In a very simple sentence, explain why you might prefer one configuration over another. \n\nHINT: The cell below will visualize each of the cases. ",
"_____no_output_____"
]
],
[
[
"if (running_as_notebook):\n plt.subplot(1,3,1)\n plot_gear()\n plt.title(\"Local Minima\")\n np.random.seed(45)\n while True:\n result, H_eig = find_antipodal_pts(shape)\n if ((H_eig > 0).all()):\n break\n plot_antipodal_pts(result, shape)\n\n plt.subplot(1,3,2)\n plot_gear()\n plt.title(\"Local Maxima\")\n np.random.seed(4)\n while True:\n result, H_eig = find_antipodal_pts(shape)\n if ((H_eig < 0).all()):\n break\n plot_antipodal_pts(result, shape)\n\n plt.subplot(1,3,3)\n plot_gear()\n plt.title(\"Saddle Point\")\n np.random.seed(13)\n while True:\n result, H_eig = find_antipodal_pts(shape)\n if ((H_eig[0] > 0) and (H_eig[1] < 0)):\n break\n plot_antipodal_pts(result, shape)",
"_____no_output_____"
]
],
[
[
"## How will this notebook be Graded?\n\nIf you are enrolled in the class, this notebook will be graded using [Gradescope](www.gradescope.com). You should have gotten the enrollement code on our announcement in Piazza. \n\nFor submission of this assignment, you must do two things. \n- Download and submit the notebook `analytic_antipodal_grasps.ipynb` to Gradescope's notebook submission section, along with your notebook for the other problems.\n- Write down your answers to 5.1.a, 5.1.b, and 5.1.d to a separately pdf file and submit it to Gradescope's written submission section. \n\nWe will evaluate the local functions in the notebook to see if the function behaves as we have expected. For this exercise, the rubric is as follows:\n- [2 pts] 5.1.a is answered correctly.\n- [2 pts] 5.1.b is answered correctly. \n- [4 pts] `find_antipodal_points` must be implemented correctly.\n- [2 pts] 5.1.d is answered correctly.",
"_____no_output_____"
]
],
[
[
"from manipulation.exercises.clutter.test_analytic_grasp import TestAnalyticGrasp\nfrom manipulation.exercises.grader import Grader \n\nGrader.grade_output([TestAnalyticGrasp], [locals()], 'results.json')\nGrader.print_test_results('results.json')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a3620040725eb0069aa7a7bac6427d146f7c200
| 11,338 |
ipynb
|
Jupyter Notebook
|
examples/Notebooks/flopy3_array_outputformat_options.ipynb
|
Gael-de-Sailly/flopy
|
4104cf5e6a35e2a1fd6183442962ae5cb258fa7a
|
[
"CC0-1.0",
"BSD-3-Clause"
] | 1 |
2021-02-23T22:55:04.000Z
|
2021-02-23T22:55:04.000Z
|
examples/Notebooks/flopy3_array_outputformat_options.ipynb
|
Gael-de-Sailly/flopy
|
4104cf5e6a35e2a1fd6183442962ae5cb258fa7a
|
[
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null |
examples/Notebooks/flopy3_array_outputformat_options.ipynb
|
Gael-de-Sailly/flopy
|
4104cf5e6a35e2a1fd6183442962ae5cb258fa7a
|
[
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | 28.064356 | 238 | 0.519757 |
[
[
[
"# FloPy\n\n### A quick demo of how to control the ASCII format of numeric arrays written by FloPy",
"_____no_output_____"
],
[
"load and run the Freyberg model",
"_____no_output_____"
]
],
[
[
"import sys\nimport os\nimport platform\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n# run installed version of flopy or add local path\ntry:\n import flopy\nexcept:\n fpth = os.path.abspath(os.path.join('..', '..'))\n sys.path.append(fpth)\n import flopy\n\n#Set name of MODFLOW exe\n# assumes executable is in users path statement\nversion = 'mf2005'\nexe_name = 'mf2005'\nif platform.system() == 'Windows':\n exe_name = 'mf2005.exe'\nmfexe = exe_name\n\n#Set the paths\nloadpth = os.path.join('..', 'data', 'freyberg')\nmodelpth = os.path.join('data')\n\n#make sure modelpth directory exists\nif not os.path.exists(modelpth):\n os.makedirs(modelpth)\n \nprint(sys.version)\nprint('numpy version: {}'.format(np.__version__))\nprint('matplotlib version: {}'.format(mpl.__version__))\nprint('flopy version: {}'.format(flopy.__version__))",
"3.8.6 | packaged by conda-forge | (default, Oct 7 2020, 18:42:56) \n[Clang 10.0.1 ]\nnumpy version: 1.18.5\nmatplotlib version: 3.2.2\nflopy version: 3.3.3\n"
],
[
"ml = flopy.modflow.Modflow.load('freyberg.nam', model_ws=loadpth, \n exe_name=exe_name, version=version)\nml.model_ws = modelpth\nml.write_input()\nsuccess, buff = ml.run_model()\nif not success:\n print ('Something bad happened.')\nfiles = ['freyberg.hds', 'freyberg.cbc']\nfor f in files:\n if os.path.isfile(os.path.join(modelpth, f)):\n msg = 'Output file located: {}'.format(f)\n print (msg)\n else:\n errmsg = 'Error. Output file cannot be found: {}'.format(f)\n print (errmsg)",
"\nchanging model workspace...\n data\nFloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf2005\n\n MODFLOW-2005 \n U.S. GEOLOGICAL SURVEY MODULAR FINITE-DIFFERENCE GROUND-WATER FLOW MODEL\n Version 1.12.00 2/3/2017 \n\n Using NAME file: freyberg.nam \n Run start date and time (yyyy/mm/dd hh:mm:ss): 2021/02/18 11:30:46\n\n Solving: Stress period: 1 Time step: 1 Ground-Water Flow Eqn.\n Run end date and time (yyyy/mm/dd hh:mm:ss): 2021/02/18 11:30:46\n Elapsed run time: 0.018 Seconds\n\n Normal termination of simulation\nOutput file located: freyberg.hds\nOutput file located: freyberg.cbc\n"
]
],
[
[
"Each ``Util2d`` instance now has a ```.format``` attribute, which is an ```ArrayFormat``` instance:",
"_____no_output_____"
]
],
[
[
"print(ml.lpf.hk[0].format)",
"ArrayFormat: npl:20,format:E,width:15,decimal6,isfree:True,isbinary:False\n"
]
],
[
[
"The ```ArrayFormat``` class exposes each of the attributes seen in the ```ArrayFormat.___str___()``` call. ```ArrayFormat``` also exposes ``.fortran``, ``.py`` and ``.numpy`` atrributes, which are the respective format descriptors: ",
"_____no_output_____"
]
],
[
[
"print(ml.dis.botm[0].format.fortran)\nprint(ml.dis.botm[0].format.py)\nprint(ml.dis.botm[0].format.numpy)",
"(FREE)\n(20, '{0:15.6E}')\n%15E.6\n"
]
],
[
[
"#### (re)-setting ```.format```\n\nWe can reset the format using a standard fortran type format descriptor",
"_____no_output_____"
]
],
[
[
"ml.dis.botm[0].format.fortran = \"(6f10.4)\"\nprint(ml.dis.botm[0].format.fortran)\nprint(ml.dis.botm[0].format.py)\nprint(ml.dis.botm[0].format.numpy)",
"(FREE)\n(6, '{0:10.4F}')\n%10F.4\n"
],
[
"ml.write_input()\nsuccess, buff = ml.run_model()",
"FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf2005\n\n MODFLOW-2005 \n U.S. GEOLOGICAL SURVEY MODULAR FINITE-DIFFERENCE GROUND-WATER FLOW MODEL\n Version 1.12.00 2/3/2017 \n\n Using NAME file: freyberg.nam \n Run start date and time (yyyy/mm/dd hh:mm:ss): 2021/02/18 11:30:46\n\nforrtl: severe (59): list-directed I/O syntax error, unit 29, file /Users/jdhughes/Documents/Development/flopy_git/flopy_fork/examples/Notebooks/data/freyberg.dis\nImage PC Routine Line Source \nmf2005 000000010CE4DBFB Unknown Unknown Unknown\nmf2005 000000010CE89CE8 Unknown Unknown Unknown\nmf2005 000000010CE8871C Unknown Unknown Unknown\nmf2005 000000010C962E33 _u2drel_ 890 utl7.f\nmf2005 000000010C970BBA _sgwf2bas7ardis_ 759 gwf2bas7.f\nmf2005 000000010C9689F8 _gwf2bas7ar_ 217 gwf2bas7.f\nmf2005 000000010CB5A5A2 _MAIN__ 75 mf2005.f\nmf2005 000000010C92AB6E Unknown Unknown Unknown\n"
]
],
[
[
"Let's load the model we just wrote and check that the desired ```botm[0].format``` was used:",
"_____no_output_____"
]
],
[
[
"ml1 = flopy.modflow.Modflow.load(\"freyberg.nam\",model_ws=modelpth)\nprint(ml1.dis.botm[0].format)",
"ArrayFormat: npl:20,format:E,width:15,decimal6,isfree:True,isbinary:False\n"
]
],
[
[
"We can also reset individual format components (we can also generate some warnings):",
"_____no_output_____"
]
],
[
[
"ml.dis.botm[0].format.width = 9\nml.dis.botm[0].format.decimal = 1\nprint(ml1.dis.botm[0].format)",
"ArrayFormat warning:setting width less than default of 15\nArrayFormat warning: setting decimal less than default of 6\nArrayFormat warning: setting decimal less than current value of 6\nArrayFormat: npl:20,format:E,width:15,decimal6,isfree:True,isbinary:False\n"
]
],
[
[
"We can also select ``free`` format. Note that setting to free format resets the format attributes to the default, max precision:",
"_____no_output_____"
]
],
[
[
"ml.dis.botm[0].format.free = True\nprint(ml1.dis.botm[0].format)",
"ArrayFormat: npl:20,format:E,width:15,decimal6,isfree:True,isbinary:False\n"
],
[
"ml.write_input()\nsuccess, buff = ml.run_model()",
"FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf2005\n\n MODFLOW-2005 \n U.S. GEOLOGICAL SURVEY MODULAR FINITE-DIFFERENCE GROUND-WATER FLOW MODEL\n Version 1.12.00 2/3/2017 \n\n Using NAME file: freyberg.nam \n Run start date and time (yyyy/mm/dd hh:mm:ss): 2021/02/18 11:30:46\n\n Solving: Stress period: 1 Time step: 1 Ground-Water Flow Eqn.\n Run end date and time (yyyy/mm/dd hh:mm:ss): 2021/02/18 11:30:46\n Elapsed run time: 0.010 Seconds\n\n Normal termination of simulation\n"
],
[
"ml1 = flopy.modflow.Modflow.load(\"freyberg.nam\",model_ws=modelpth)\nprint(ml1.dis.botm[0].format)",
"ArrayFormat: npl:20,format:E,width:15,decimal6,isfree:True,isbinary:False\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4a36213fc2373058bc0cbb0cfb919d8445763fa9
| 9,845 |
ipynb
|
Jupyter Notebook
|
computer_vision/resnet_model/Keras_resnet.ipynb
|
nateandre/machine_learning
|
5c6535a18b46feaa5ffc38670e6404869836d2b1
|
[
"MIT"
] | 1 |
2018-12-31T17:38:02.000Z
|
2018-12-31T17:38:02.000Z
|
computer_vision/resnet_model/Keras_resnet.ipynb
|
nateandre/machine_learning
|
5c6535a18b46feaa5ffc38670e6404869836d2b1
|
[
"MIT"
] | null | null | null |
computer_vision/resnet_model/Keras_resnet.ipynb
|
nateandre/machine_learning
|
5c6535a18b46feaa5ffc38670e6404869836d2b1
|
[
"MIT"
] | 1 |
2020-05-05T10:05:57.000Z
|
2020-05-05T10:05:57.000Z
| 33.372881 | 152 | 0.519045 |
[
[
[
"### Simple Residual model in Keras\n\nThis notebook is simply for testing a resnet-50 inspired model built in Keras on a numerical signs dataset.",
"_____no_output_____"
]
],
[
[
"import keras\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras import layers\nfrom keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D,ZeroPadding1D, Conv1D, Add\nfrom keras.layers import MaxPooling2D, Dropout, AveragePooling2D\nfrom keras.models import Model\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\n\nimport warnings\nwarnings.filterwarnings('ignore')",
"Using TensorFlow backend.\n"
],
[
"# Using a signs dataset, with images of numerical signs from 0-9\nX = np.load(\"../data/sign-digits/X.npy\")\ny = np.load(\"../data/sign-digits/y.npy\")\nX.shape = (2062, 64, 64, 1)\nX = shuffle(X,random_state=0)\ny = shuffle(y,random_state=0)\nprint(X.shape)\nprint(y.shape)",
"(2062, 64, 64, 1)\n(2062, 10)\n"
],
[
"X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.1)\nprint(X_train.shape)\nprint(X_test.shape)",
"(1855, 64, 64, 1)\n(207, 64, 64, 1)\n"
],
[
"# Block corresponding with no change in size\ndef identity(X, f, filters):\n \"\"\"\n filters: filters for each of the conv2D\n f: size of filter to use in mid block\n \"\"\"\n F1,F2,F3 = filters\n \n X_earlier = X\n # Block 1\n X = Conv2D(F1, kernel_size=(1,1), strides=(1,1),padding=\"valid\",kernel_initializer=keras.initializers.glorot_normal())(X)\n X = BatchNormalization(axis=3)(X)\n X = Activation(\"relu\")(X)\n # Block 2\n X = Conv2D(F2, kernel_size=(f,f), strides=(1,1),padding=\"same\",kernel_initializer=keras.initializers.glorot_normal())(X)\n X = BatchNormalization(axis=3)(X)\n X = Activation(\"relu\")(X)\n # Block 3\n X = Conv2D(F3, kernel_size=(1,1), strides=(1,1),padding=\"valid\",kernel_initializer=keras.initializers.glorot_normal())(X)\n X = BatchNormalization(axis=3)(X)\n X = Add()([X,X_earlier]) # Add earlier activation\n X = Activation(\"relu\")(X)\n return X",
"_____no_output_____"
],
[
"# Block corresponding with a change in size\ndef conv_resid(X, f, filters,s):\n \"\"\"\n filters: filters for each of the conv2D\n s: stride size to resize the output\n \"\"\"\n F1,F2,F3 = filters\n X_earlier = X\n # Block 1\n X = Conv2D(F1, kernel_size=(1,1), strides=(s,s),padding=\"valid\",kernel_initializer=keras.initializers.glorot_normal())(X)\n X = BatchNormalization(axis=3)(X)\n X = Activation(\"relu\")(X)\n # Block 2\n X = Conv2D(F2, kernel_size=(f,f), strides=(1,1),padding=\"same\",kernel_initializer=keras.initializers.glorot_normal())(X)\n X = BatchNormalization(axis=3)(X)\n X = Activation(\"relu\")(X)\n # Block 3\n X = Conv2D(F3, kernel_size=(1,1), strides=(1,1),padding=\"valid\",kernel_initializer=keras.initializers.glorot_normal())(X)\n X = BatchNormalization(axis=3)(X)\n # Resize earlier activation (X_earlier)\n X_earlier = Conv2D(F3, kernel_size=(1,1), strides=(s,s),padding=\"valid\",kernel_initializer=keras.initializers.glorot_normal())(X_earlier)\n X_earlier = BatchNormalization(axis=3)(X_earlier)\n # Add earlier activation\n X = Add()([X,X_earlier])\n X = Activation(\"relu\")(X)\n return X",
"_____no_output_____"
],
[
"# The Input shape for this model will be 64x64x1\ndef model(input_shape):\n X_input = Input(input_shape)\n X = ZeroPadding2D(padding=(3,3))(X_input)\n X = Conv2D(64,kernel_size=(7,7),padding=\"valid\",kernel_initializer=keras.initializers.glorot_uniform())(X)\n X = BatchNormalization(axis=3)(X)\n X = Activation((\"relu\"))(X)\n X = MaxPooling2D((3,3),strides=(2,2))(X)\n \n # indentity block 1\n X = conv_resid(X, 3, [64,64,256], 1)\n X = identity(X, 3, [64,64,256])\n X = identity(X, 3, [64,64,256])\n \n # Identity block 2\n X = conv_resid(X, 3, [128,128,512], 2)\n X = identity(X, 3, [128,128,512])\n X = identity(X, 3, [128,128,512])\n X = identity(X, 3, [128,128,512])\n \n # Identity block 3\n X = conv_resid(X, 3, [256, 256, 1024], 2)\n X = identity(X, 3, [256, 256, 1024])\n X = identity(X, 3, [256, 256, 1024])\n X = identity(X, 3, [256, 256, 1024])\n X = identity(X, 3, [256, 256, 1024])\n X = identity(X, 3, [256, 256, 1024])\n \n # Identity block 4\n X = conv_resid(X, 3, [512, 512, 2048], 2)\n X = identity(X, 3, [512, 512, 2048])\n X = identity(X, 3, [512, 512, 2048])\n \n X = AveragePooling2D((2,2), name=\"avg_pool\")(X)\n # Flatten final layer\n X = Flatten()(X)\n X = Dense(10, activation=\"softmax\",name=\"dense02\",kernel_initializer = keras.initializers.glorot_normal())(X)\n \n model = Model(inputs=X_input, outputs=X, name=\"resnet\")\n return model",
"_____no_output_____"
],
[
"resid_classi = model(X_train[0].shape)",
"_____no_output_____"
],
[
"resid_classi.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\", metrics=['accuracy'])",
"_____no_output_____"
],
[
"resid_classi.fit(X_train, y_train,epochs=10,batch_size=10, validation_data=[X_test,y_test])",
"Train on 1855 samples, validate on 207 samples\nEpoch 1/10\n1855/1855 [==============================] - 756s 408ms/step - loss: 2.0275 - acc: 0.4965 - val_loss: 1.0932 - val_acc: 0.7874\nEpoch 2/10\n1855/1855 [==============================] - 697s 376ms/step - loss: 0.3569 - acc: 0.8852 - val_loss: 0.5941 - val_acc: 0.8261\nEpoch 3/10\n1855/1855 [==============================] - 701s 378ms/step - loss: 0.1776 - acc: 0.9488 - val_loss: 0.4580 - val_acc: 0.8792\nEpoch 4/10\n1855/1855 [==============================] - 690s 372ms/step - loss: 0.0929 - acc: 0.9725 - val_loss: 0.4911 - val_acc: 0.8647\nEpoch 5/10\n1855/1855 [==============================] - 688s 371ms/step - loss: 0.1306 - acc: 0.9601 - val_loss: 0.9518 - val_acc: 0.8019\nEpoch 6/10\n1855/1855 [==============================] - 691s 372ms/step - loss: 0.1014 - acc: 0.9698 - val_loss: 0.5530 - val_acc: 0.8261\nEpoch 7/10\n1855/1855 [==============================] - 688s 371ms/step - loss: 0.0902 - acc: 0.9725 - val_loss: 0.0832 - val_acc: 0.9710\nEpoch 8/10\n1855/1855 [==============================] - 689s 371ms/step - loss: 0.0667 - acc: 0.9779 - val_loss: 0.1891 - val_acc: 0.9517\nEpoch 9/10\n1855/1855 [==============================] - 787s 424ms/step - loss: 0.1690 - acc: 0.9477 - val_loss: 1.6629 - val_acc: 0.7150\nEpoch 10/10\n1855/1855 [==============================] - 684s 369ms/step - loss: 0.1144 - acc: 0.9644 - val_loss: 0.2849 - val_acc: 0.9517\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a3625d1addd06eaada0f0b6f7478db99af484cc
| 778 |
ipynb
|
Jupyter Notebook
|
DurableConsumptionModel/Untitled.ipynb
|
ChristofferJWeissert/ConsumptionSavingNotebooks
|
1c5cf6c1681d53fc2c0a67b4755a48ade40b31c7
|
[
"MIT"
] | 1 |
2021-11-07T23:37:25.000Z
|
2021-11-07T23:37:25.000Z
|
DurableConsumptionModel/Untitled.ipynb
|
ChristofferJWeissert/ConsumptionSavingNotebooks
|
1c5cf6c1681d53fc2c0a67b4755a48ade40b31c7
|
[
"MIT"
] | null | null | null |
DurableConsumptionModel/Untitled.ipynb
|
ChristofferJWeissert/ConsumptionSavingNotebooks
|
1c5cf6c1681d53fc2c0a67b4755a48ade40b31c7
|
[
"MIT"
] | null | null | null | 16.553191 | 36 | 0.494859 |
[
[
[
"import pandas as pd\npd.__version__",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
4a362ab4c0977f4f205d5fbe5b39ea89639ea42e
| 1,552 |
ipynb
|
Jupyter Notebook
|
Samples/.ipynb_checkpoints/BackgroundDifference-checkpoint.ipynb
|
zaml/ComputerVision
|
01afc8ee8c11c472a8251eabd3721d180223c2e8
|
[
"MIT"
] | null | null | null |
Samples/.ipynb_checkpoints/BackgroundDifference-checkpoint.ipynb
|
zaml/ComputerVision
|
01afc8ee8c11c472a8251eabd3721d180223c2e8
|
[
"MIT"
] | null | null | null |
Samples/.ipynb_checkpoints/BackgroundDifference-checkpoint.ipynb
|
zaml/ComputerVision
|
01afc8ee8c11c472a8251eabd3721d180223c2e8
|
[
"MIT"
] | null | null | null | 18.926829 | 52 | 0.48518 |
[
[
[
"# Required moduls\nimport cv2\nimport numpy as np",
"_____no_output_____"
],
[
"cap = cv2.VideoCapture(0)\nfgbg = cv2.createBackgroundSubtractorMOG2()\n\nret = cap.set(3,320) \nret = cap.set(4,240)\n\nwhile True:\n ret, frame = cap.read()\n fgmask = fgbg.apply(frame)\n \n cv2.imshow('original', frame)\n cv2.imshow('fg', fgmask)\n \n k = cv2.waitKey(30) & 0xff\n if k == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
4a362bc725e4d95a2188f3e6aebdc2f31810bc1d
| 4,492 |
ipynb
|
Jupyter Notebook
|
Training-a-RNN-using-TensorFlow-on-MNIST-dataset.ipynb
|
hualkassam/Training-a-RNN-using-TensorFlow-on-MNIST-dataset
|
7d8dac2dba2b35c579643aa86a404e8ce3c07dae
|
[
"Apache-2.0"
] | null | null | null |
Training-a-RNN-using-TensorFlow-on-MNIST-dataset.ipynb
|
hualkassam/Training-a-RNN-using-TensorFlow-on-MNIST-dataset
|
7d8dac2dba2b35c579643aa86a404e8ce3c07dae
|
[
"Apache-2.0"
] | null | null | null |
Training-a-RNN-using-TensorFlow-on-MNIST-dataset.ipynb
|
hualkassam/Training-a-RNN-using-TensorFlow-on-MNIST-dataset
|
7d8dac2dba2b35c579643aa86a404e8ce3c07dae
|
[
"Apache-2.0"
] | null | null | null | 32.550725 | 95 | 0.5748 |
[
[
[
"# Coder_Hussam Qassim\n\n# Import the necessary libraries \nimport tensorflow as tf \nfrom tensorflow.contrib.layers import fully_connected\nimport numpy as np \nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# Define the RNN parameters\nn_steps = 28\nn_inputs = 28\nn_neurons = 150\nn_outputs = 10\n\n# Create the inpute and lable data \nx = tf.placeholder(tf.float32, [None, n_steps, n_inputs])\ny = tf.placeholder(tf.int32, [None])\n\n# Create the graph on 1 input layer and 2 hidden layers and one output layer \nwith tf.name_scope(\"RNN\"):\n basic_cell = tf.contrib.rnn.BasicRNNCell(num_units=n_neurons)\n outputs, states = tf.nn.dynamic_rnn(basic_cell, x, dtype=tf.float32)\n logits = fully_connected(states, n_outputs, activation_fn=None)\n \n# Create the cost function \nwith tf.name_scope(\"loss\"):\n xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits)\n loss = tf.reduce_mean(xentropy, name=\"loss\")\n\n# Craete the optimizer \nlearning_rate = 0.001\nwith tf.name_scope(\"train\"):\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n training_op\t= optimizer.minimize(loss)\n \n# Evaluate the NN \nwith tf.name_scope(\"eval\"):\n correct = tf.nn.in_top_k(logits, y, 1)\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n \n# Initialize the variables \ninit = tf.global_variables_initializer()\n\n# Initialize the saver for save the model\nsaver = tf.train.Saver()\n\n# Fetch the data \nmnist = input_data.read_data_sets(\"data/\")\nx_test = mnist.test.images.reshape((-1, n_steps, n_inputs))\ny_test = mnist.test.labels\n\n# define the number of the epochs and the size of the batch\nn_epochs = 100\nbatch_size = 150\n\nwith tf.Session() as sess:\n init.run()\n for epoch in range(n_epochs):\n for iteration in range(mnist.train.num_examples // batch_size):\n x_batch, y_batch = mnist.train.next_batch(batch_size)\n x_batch = x_batch.reshape((-1, n_steps, n_inputs))\n sess.run(training_op, feed_dict={x: x_batch, y: y_batch})\n acc_train = accuracy.eval(feed_dict={x: x_batch, y: y_batch})\n acc_test = accuracy.eval(feed_dict={x: x_test, y: y_test })\n print(epoch, \"Train accuracy:\", acc_train, \"Test accuracy:\", acc_test)\n save_path = saver.save(sess, \"data/my_model_final.ckpt\")",
"Extracting data/train-images-idx3-ubyte.gz\nExtracting data/train-labels-idx1-ubyte.gz\nExtracting data/t10k-images-idx3-ubyte.gz\nExtracting data/t10k-labels-idx1-ubyte.gz\n0 Train accuracy: 0.946667 Test accuracy: 0.9161\n1 Train accuracy: 0.986667 Test accuracy: 0.9542\n"
],
[
"# Using the Neural Network\nwith tf.Session() as sess:\n saver.restore(sess,\t\"data/my_model_final.ckpt\")\n x_new_scaled = [...] # some new images (scaled from 0 to 1)\n z = logits.eval(feed_dict={x: x_new_scaled})\n y_pred = np.argmax(z, axis=1)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
4a363378d5212f0a022dfa80cf12e56223835985
| 457,379 |
ipynb
|
Jupyter Notebook
|
logistic_regression_from_scratch.ipynb
|
danhtaihoang/machine-learning
|
ee00b1a4b5cf2a51f4335578466b657cd07f1693
|
[
"MIT"
] | null | null | null |
logistic_regression_from_scratch.ipynb
|
danhtaihoang/machine-learning
|
ee00b1a4b5cf2a51f4335578466b657cd07f1693
|
[
"MIT"
] | null | null | null |
logistic_regression_from_scratch.ipynb
|
danhtaihoang/machine-learning
|
ee00b1a4b5cf2a51f4335578466b657cd07f1693
|
[
"MIT"
] | null | null | null | 1,104.780193 | 248,032 | 0.955934 |
[
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### Generate data",
"_____no_output_____"
]
],
[
[
"np.random.seed(12)\nnum_observations = 5000",
"_____no_output_____"
],
[
"x1 = np.random.multivariate_normal([0, 0], [[1, .75],[.75, 1]], num_observations)\nx1",
"_____no_output_____"
],
[
"x1.shape",
"_____no_output_____"
],
[
"x2 = np.random.multivariate_normal([1, 4], [[1, .75],[.75, 1]], num_observations)\nx2",
"_____no_output_____"
],
[
"x2.shape",
"_____no_output_____"
],
[
"simulated_separableish_features = np.vstack((x1, x2)).astype(np.float32)",
"_____no_output_____"
],
[
"simulated_separableish_features",
"_____no_output_____"
],
[
"simulated_separableish_features.shape",
"_____no_output_____"
],
[
"simulated_labels = np.hstack((np.zeros(num_observations),np.ones(num_observations)))\nsimulated_labels",
"_____no_output_____"
],
[
"simulated_labels.shape",
"_____no_output_____"
],
[
"plt.figure(figsize=(12,8))\nplt.scatter(simulated_separableish_features[:, 0], simulated_separableish_features[:, 1],\n c = simulated_labels, alpha = .4)",
"_____no_output_____"
],
[
"def sigmoid(scores):\n return 1/(1 + np.exp(-scores))",
"_____no_output_____"
],
[
"def log_likelihood(features, target, weights):\n scores = np.dot(features, weights)\n ll = np.sum(target*scores - np.log(1 + np.exp(scores)))\n return ll",
"_____no_output_____"
],
[
"def logistic_regression(features, target, num_steps, learning_rate, add_intercept = False):\n if add_intercept:\n intercept = np.ones((features.shape[0], 1))\n features = np.hstack((intercept, features))\n \n weights = np.zeros(features.shape[1])\n \n for step in range(num_steps):\n scores = np.dot(features, weights)\n predictions = sigmoid(scores)\n\n # Update weights with log likelihood gradient\n output_error_signal = target - predictions\n \n gradient = np.dot(features.T, output_error_signal)\n weights += learning_rate * gradient\n\n # Print log-likelihood every so often\n if step % 10000 == 0:\n print (log_likelihood(features, target, weights))\n \n return weights",
"_____no_output_____"
],
[
"weights = logistic_regression(simulated_separableish_features, simulated_labels,\n num_steps = 50000, learning_rate = 5e-5, add_intercept=True)\nprint (\"LOGISTIC REGRESSION FROM SRATCH WEIGHTS => \",weights)",
"-4346.264779152365\n-148.70672276805357\n-142.96493623107844\n-141.5453030715737\n-141.060319659308\nLOGISTIC REGRESSION FROM SRATCH WEIGHTS => [-13.58690551 -4.8809644 7.99812915]\n"
],
[
"final_scores = np.dot(np.hstack((np.ones((simulated_separableish_features.shape[0], 1)),\n simulated_separableish_features)), weights)\npreds = np.round(sigmoid(final_scores))",
"_____no_output_____"
],
[
"print ('Accuracy from scratch: {0}'.format((preds == simulated_labels).sum().astype(float) / len(preds)))",
"Accuracy from scratch: 0.9948\n"
],
[
"plt.figure(figsize = (12, 8))\nplt.scatter(simulated_separableish_features[:, 0], simulated_separableish_features[:, 1],\n c = preds == simulated_labels - 1, alpha = .8, s = 50)\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a36347a6bcc125dcaa5ac730269c14a5e20ad56
| 35,709 |
ipynb
|
Jupyter Notebook
|
ai-platform/notebooks/unofficial/AI_Platform_Custom_Container_Prediction_sklearn.ipynb
|
Google-Cloud-Tech-Career-Training/ai-platform-samples
|
b1702f237431d244935f626e9019324fc8ec1a35
|
[
"Apache-2.0"
] | null | null | null |
ai-platform/notebooks/unofficial/AI_Platform_Custom_Container_Prediction_sklearn.ipynb
|
Google-Cloud-Tech-Career-Training/ai-platform-samples
|
b1702f237431d244935f626e9019324fc8ec1a35
|
[
"Apache-2.0"
] | 13 |
2022-01-04T22:18:52.000Z
|
2022-03-15T01:36:15.000Z
|
ai-platform/notebooks/unofficial/AI_Platform_Custom_Container_Prediction_sklearn.ipynb
|
Google-Cloud-Tech-Career-Training/ai-platform-samples
|
b1702f237431d244935f626e9019324fc8ec1a35
|
[
"Apache-2.0"
] | null | null | null | 31.628875 | 286 | 0.516536 |
[
[
[
"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"<table align=\"left\">\n <td>\n <a href=\"https://github.com/GoogleCloudPlatform/ai-platform-samples/blob/main/ai-platform/notebooks/unofficial/AI_Platform_Custom_Container_Prediction_sklearn.ipynb\">\n <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n View on GitHub\n </a>\n </td>\n</table>",
"_____no_output_____"
],
[
"## Overview\n\nThis tutorial walks through building a custom container to serve a scikit-learn model on AI Platform Predictions. You will use the FastAPI Python web server framework to create a prediction and health endpoint.\nYou will also cover incorporating a pre-processor from training into your online serving.\n\n\n### Dataset\n\nThis tutorial uses R.A. Fisher's Iris dataset, a small dataset that is popular for trying out machine learning techniques. Each instance has four numerical features, which are different measurements of a flower, and a target label that\nmarks it as one of three types of iris: Iris setosa, Iris versicolour, or Iris virginica.\n\nThis tutorial uses [the copy of the Iris dataset included in the\nscikit-learn library](https://scikit-learn.org/stable/datasets/index.html#iris-dataset).\n\n### Objective\n\nThe goal is to:\n- Train a model that uses a flower's measurements as input to predict what type of iris it is.\n- Save the model and its serialized pre-processor\n- Build a FastAPI server to handle predictions and health checks\n- Build a custom container with model artifacts\n- Upload and deploy custom container to AI Platform Prediction\n\nThis tutorial focuses more on deploying this model with AI Platform than on\nthe design of the model itself.\n\n### Costs \n\nThis tutorial uses billable components of Google Cloud:\n\n* AI Platform \n\nLearn about [AI Platform (Classic)\npricing](https://cloud.google.com/ai-platform/pricing), and use the [Pricing\nCalculator](https://cloud.google.com/products/calculator/)\nto generate a cost estimate based on your projected usage.",
"_____no_output_____"
],
[
"### Set up your local development environment\n\n**If you are using Colab or AI Platform Notebooks**, your environment already meets\nall the requirements to run this notebook. You can skip this step.",
"_____no_output_____"
],
[
"**Otherwise**, make sure your environment meets this notebook's requirements.\nYou need the following:\n\n* Docker\n* Git\n* Google Cloud SDK (gcloud)\n* Python 3\n* virtualenv\n* Jupyter notebook running in a virtual environment with Python 3\n\nThe Google Cloud guide to [Setting up a Python development\nenvironment](https://cloud.google.com/python/setup) and the [Jupyter\ninstallation guide](https://jupyter.org/install) provide detailed instructions\nfor meeting these requirements. The following steps provide a condensed set of\ninstructions:\n\n1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n\n1. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n\n1. [Install\n virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n and create a virtual environment that uses Python 3. Activate the virtual environment.\n\n1. To install Jupyter, run `pip install jupyter` on the\ncommand-line in a terminal shell.\n\n1. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.\n\n1. Open this notebook in the Jupyter Notebook Dashboard.",
"_____no_output_____"
],
[
"### Install additional packages\n\nInstall additional package dependencies not installed in your notebook environment, such as NumPy, Scikit-learn, FastAPI, Uvicorn, and joblib. Use the latest major GA version of each package.",
"_____no_output_____"
]
],
[
[
"%%writefile requirements.txt\njoblib~=1.0\nnumpy~=1.20\nscikit-learn~=0.24\ngoogle-cloud-storage>=1.26.0,<2.0.0dev",
"_____no_output_____"
],
[
"# Required in Docker serving container\n%pip install -U -r requirements.txt\n\n# For local FastAPI development and running\n%pip install -U \"uvicorn[standard]>=0.12.0,<0.14.0\" fastapi~=0.63\n\n# AI Platform (Classic) client library\n%pip install -U google-api-python-client",
"_____no_output_____"
]
],
[
[
"### Restart the kernel\n\nAfter you install the additional packages, you need to restart the notebook kernel so it can find the packages.",
"_____no_output_____"
]
],
[
[
"# Automatically restart kernel after installs\nimport os\n\nif not os.getenv(\"IS_TESTING\"):\n # Automatically restart kernel after installs\n import IPython\n\n app = IPython.Application.instance()\n app.kernel.do_shutdown(True)",
"_____no_output_____"
]
],
[
[
"## Before you begin",
"_____no_output_____"
],
[
"### Set up your Google Cloud project\n\n**The following steps are required, regardless of your notebook environment.**\n\n1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n\n1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n\n1. [Enable the AI Platform (Classic) API and Compute Engine API](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component).\n\n1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n\n1. Enter your project ID in the cell below. Then run the cell to make sure the\nCloud SDK uses the right project for all the commands in this notebook.\n\n**Note**: Jupyter runs lines prefixed with `!` or `%` as shell commands, and it interpolates Python variables with `$` or `{}` into these commands.",
"_____no_output_____"
],
[
"#### Set your project ID\n\n**If you don't know your project ID**, you may be able to get your project ID using `gcloud`.",
"_____no_output_____"
]
],
[
[
"# Get your Google Cloud project ID from gcloud\nshell_output=!gcloud config list --format 'value(core.project)' 2>/dev/null\n\ntry:\n PROJECT_ID = shell_output[0]\nexcept IndexError:\n PROJECT_ID = None\n\nprint(\"Project ID:\", PROJECT_ID)",
"_____no_output_____"
]
],
[
[
"Otherwise, set your project ID here.",
"_____no_output_____"
]
],
[
[
"if PROJECT_ID == \"\" or PROJECT_ID is None:\n PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}",
"_____no_output_____"
]
],
[
[
"### Authenticate your Google Cloud account\n\n**If you are using AI Platform Notebooks**, your environment is already\nauthenticated. Skip this step.",
"_____no_output_____"
],
[
"**If you are using Colab**, run the cell below and follow the instructions\nwhen prompted to authenticate your account via oAuth.\n\n**Otherwise**, follow these steps:\n\n1. In the Cloud Console, go to the [**Create service account key**\n page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n\n2. Click **Create service account**.\n\n3. In the **Service account name** field, enter a name, and\n click **Create**.\n\n4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"AI Platform\"\ninto the filter box, and select\n **AI Platform Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n\n5. Click *Create*. A JSON file that contains your key downloads to your\nlocal environment.\n\n6. Enter the path to your service account key as the\n`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell.",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\n\n# If you are running this notebook in Colab, run this cell and follow the\n# instructions to authenticate your GCP account. This provides access to your\n# Cloud Storage bucket and lets you submit training jobs and prediction\n# requests.\n\n# If on AI Platform, then don't execute this code\nif not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n if \"google.colab\" in sys.modules:\n from google.colab import auth as google_auth\n\n google_auth.authenticate_user()\n\n # If you are running this notebook locally, replace the string below with the\n # path to your service account key and run this cell to authenticate your GCP\n # account.\n elif not os.getenv(\"IS_TESTING\") and not os.getenv(\n \"GOOGLE_APPLICATION_CREDENTIALS\"\n ):\n %env GOOGLE_APPLICATION_CREDENTIALS ''",
"_____no_output_____"
]
],
[
[
"### Configure project and resource names",
"_____no_output_____"
]
],
[
[
"REGION = \"us-central1\" # @param {type:\"string\"}\nMODEL_ARTIFACT_DIR = \"custom-container-prediction-model\" # @param {type:\"string\"}\nREPOSITORY = \"custom-container-prediction-sklearn\" # @param {type:\"string\"}\nIMAGE = \"sklearn-fastapi-server\" # @param {type:\"string\"}\nMODEL_NAME = \"sklearn_custom_container\" # @param {type:\"string\"}\nVERSION_NAME = \"v1\" # @param {type:\"string\"}",
"_____no_output_____"
]
],
[
[
"`REGION` - Used for operations\nthroughout the rest of this notebook. Make sure to [choose a region where Cloud\nAI Platform services are\navailable](https://cloud.google.com/ai-platform-unified/docs/general/locations#feature-availability). You may\nnot use a Multi-Regional Storage bucket for training with AI Platform.\n\n`MODEL_ARTIFACT_DIR` - Folder directory path to your model artifacts within a Cloud Storage bucket, for example: \"my-models/fraud-detection/trial-4\"\n\n`REPOSITORY` - Name of the Artifact Repository to create or use.\n\n`IMAGE` - Name of the container image that will be pushed.\n\n`MODEL_NAME` - Name of AI Platform Model.\n\n`VERSION_NAME` - Name of AI Platform Model version.",
"_____no_output_____"
],
[
"### Create a Cloud Storage bucket\n\n**The following steps are required, regardless of your notebook environment.**\n\nTo update your model artifacts without re-building the container, you must upload your model\nartifacts and any custom code to Cloud Storage.\n\nSet the name of your Cloud Storage bucket below. It must be unique across all\nCloud Storage buckets. ",
"_____no_output_____"
]
],
[
[
"BUCKET_NAME = \"gs://[your-bucket-name]\" # @param {type:\"string\"}",
"_____no_output_____"
]
],
[
[
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.",
"_____no_output_____"
]
],
[
[
"! gsutil mb -l $REGION $BUCKET_NAME",
"_____no_output_____"
]
],
[
[
"Finally, validate access to your Cloud Storage bucket by examining its contents:",
"_____no_output_____"
]
],
[
[
"! gsutil ls -al $BUCKET_NAME",
"_____no_output_____"
]
],
[
[
"## Write your pre-processor\nScaling training data so each numerical feature column has a mean of 0 and a standard deviation of 1 [can improve your model](https://developers.google.com/machine-learning/crash-course/representation/cleaning-data).\n\nCreate `preprocess.py`, which contains a class to do this scaling:",
"_____no_output_____"
]
],
[
[
"%mkdir app",
"_____no_output_____"
],
[
"%%writefile app/preprocess.py\nimport numpy as np\n\nclass MySimpleScaler(object):\n def __init__(self):\n self._means = None\n self._stds = None\n\n def preprocess(self, data):\n if self._means is None: # during training only\n self._means = np.mean(data, axis=0)\n\n if self._stds is None: # during training only\n self._stds = np.std(data, axis=0)\n if not self._stds.all():\n raise ValueError(\"At least one column has standard deviation of 0.\")\n\n return (data - self._means) / self._stds\n",
"_____no_output_____"
]
],
[
[
"## Train and store model with pre-processor\nNext, use `preprocess.MySimpleScaler` to preprocess the iris data, then train a model using scikit-learn.\n\nAt the end, export your trained model as a joblib (`.joblib`) file and export your `MySimpleScaler` instance as a pickle (`.pkl`) file:",
"_____no_output_____"
]
],
[
[
"%cd app/\n\nimport pickle\n\nimport joblib\nfrom preprocess import MySimpleScaler\nfrom sklearn.datasets import load_iris\nfrom sklearn.ensemble import RandomForestClassifier\n\niris = load_iris()\nscaler = MySimpleScaler()\n\nX = scaler.preprocess(iris.data)\ny = iris.target\n\nmodel = RandomForestClassifier()\nmodel.fit(X, y)\n\njoblib.dump(model, \"model.joblib\")\nwith open(\"preprocessor.pkl\", \"wb\") as f:\n pickle.dump(scaler, f)",
"_____no_output_____"
]
],
[
[
"### Upload model artifacts and custom code to Cloud Storage\n\nBefore you can deploy your model for serving, AI Platform needs access to the following files in Cloud Storage:\n\n* `model.joblib` (model artifact)\n* `preprocessor.pkl` (model artifact)\n\nRun the following commands to upload your files:",
"_____no_output_____"
]
],
[
[
"!gsutil cp model.joblib preprocessor.pkl {BUCKET_NAME}/{MODEL_ARTIFACT_DIR}/\n%cd ..",
"_____no_output_____"
]
],
[
[
"## Build a FastAPI server",
"_____no_output_____"
]
],
[
[
"%%writefile app/main.py\nfrom fastapi import FastAPI, Request\n\nimport joblib\nimport json\nimport numpy as np\nimport pickle\nimport os\n\nfrom google.cloud import storage\nfrom preprocess import MySimpleScaler\nfrom sklearn.datasets import load_iris\n\n\napp = FastAPI()\ngcs_client = storage.Client()\n\nwith open(\"preprocessor.pkl\", 'wb') as preprocessor_f, open(\"model.joblib\", 'wb') as model_f:\n gcs_client.download_blob_to_file(\n f\"{os.environ['AIP_STORAGE_URI']}/preprocessor.pkl\", preprocessor_f\n )\n gcs_client.download_blob_to_file(\n f\"{os.environ['AIP_STORAGE_URI']}/model.joblib\", model_f\n )\n\nwith open(\"preprocessor.pkl\", \"rb\") as f:\n preprocessor = pickle.load(f)\n\n_class_names = load_iris().target_names\n_model = joblib.load(\"model.joblib\")\n_preprocessor = preprocessor\n\n\[email protected](os.environ['AIP_HEALTH_ROUTE'], status_code=200)\ndef health():\n return {}\n\n\[email protected](os.environ['AIP_PREDICT_ROUTE'])\nasync def predict(request: Request):\n body = await request.json()\n\n instances = body[\"instances\"]\n inputs = np.asarray(instances)\n preprocessed_inputs = _preprocessor.preprocess(inputs)\n outputs = _model.predict(preprocessed_inputs)\n\n return {\"predictions\": [_class_names[class_num] for class_num in outputs]}\n",
"_____no_output_____"
]
],
[
[
"### Add pre-start script\nFastAPI will execute this script before starting up the server. The `PORT` environment variable is set to equal `AIP_HTTP_PORT` in order to run FastAPI on same the port expected by AI Platform Prediction.",
"_____no_output_____"
]
],
[
[
"%%writefile app/prestart.sh\n#!/bin/bash\nexport PORT=$AIP_HTTP_PORT",
"_____no_output_____"
]
],
[
[
"### Store test instances to use later\nTo learn more about formatting input instances in JSON, [read the documentation.](https://cloud.google.com/ai-platform-unified/docs/predictions/online-predictions-custom-models#request-body-details)",
"_____no_output_____"
]
],
[
[
"%%writefile instances.json\n{\n \"instances\": [\n [6.7, 3.1, 4.7, 1.5],\n [4.6, 3.1, 1.5, 0.2]\n ]\n}",
"_____no_output_____"
]
],
[
[
"## Build and push container to Artifact Registry",
"_____no_output_____"
],
[
"### Build your container\nOptionally copy in your credentials to run the container locally.",
"_____no_output_____"
]
],
[
[
"# NOTE: Copy in credentials to run locally, this step can be skipped for deployment\n%cp $GOOGLE_APPLICATION_CREDENTIALS app/credentials.json",
"_____no_output_____"
]
],
[
[
"Write the Dockerfile, using `tiangolo/uvicorn-gunicorn-fastapi` as a base image. This will automatically run FastAPI for you using Gunicorn and Uvicorn. Visit [the FastAPI docs to read more about deploying FastAPI with Docker](https://fastapi.tiangolo.com/deployment/docker/).",
"_____no_output_____"
]
],
[
[
"%%writefile Dockerfile\n\nFROM tiangolo/uvicorn-gunicorn-fastapi:python3.7\n\nCOPY ./app /app\nCOPY requirements.txt requirements.txt\n\nRUN pip install -r requirements.txt",
"_____no_output_____"
]
],
[
[
"Build the image and tag the Artifact Registry path that you will push to.",
"_____no_output_____"
]
],
[
[
"!docker build \\\n --tag={REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE} \\\n .",
"_____no_output_____"
]
],
[
[
"### Run and test the container locally (optional)\n\nRun the container locally in detached mode and provide the environment variables that the container requires. These env vars will be provided to the container by AI Platform Prediction once deployed. Test the `/health` and `/predict` routes, then stop the running image.",
"_____no_output_____"
]
],
[
[
"!docker rm local-iris\n!docker run -d -p 80:8080 \\\n --name=local-iris \\\n -e AIP_HTTP_PORT=8080 \\\n -e AIP_HEALTH_ROUTE=/health \\\n -e AIP_PREDICT_ROUTE=/predict \\\n -e AIP_STORAGE_URI={BUCKET_NAME}/{MODEL_ARTIFACT_DIR} \\\n -e GOOGLE_APPLICATION_CREDENTIALS=credentials.json \\\n {REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}",
"_____no_output_____"
],
[
"!curl localhost/health",
"_____no_output_____"
],
[
"!curl -X POST \\\n -d @instances.json \\\n -H \"Content-Type: application/json; charset=utf-8\" \\\n localhost/predict",
"_____no_output_____"
],
[
"!docker stop local-iris",
"_____no_output_____"
]
],
[
[
"### Push the container to artifact registry\n\nConfigure Docker to access Artifact Registry. Then push your container image to your Artifact Registry repository.",
"_____no_output_____"
]
],
[
[
"!gcloud beta artifacts repositories create {REPOSITORY} \\\n --repository-format=docker \\\n --location=$REGION",
"_____no_output_____"
],
[
"!gcloud auth configure-docker {REGION}-docker.pkg.dev",
"_____no_output_____"
],
[
"!docker push {REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}",
"_____no_output_____"
]
],
[
[
"## Deploy to AI Platform (Classic)\n\nUse gcloud CLI to create your model and model version.",
"_____no_output_____"
],
[
"### Create the model",
"_____no_output_____"
]
],
[
[
"!gcloud beta ai-platform models create $MODEL_NAME \\\n --region=$REGION \\\n --enable-logging \\\n --enable-console-logging",
"_____no_output_____"
]
],
[
[
"### Create the model version\nAfter this step completes, the model is deployed and ready for online prediction.",
"_____no_output_____"
]
],
[
[
"!echo \"deploymentUri: {BUCKET_NAME}/{MODEL_ARTIFACT_DIR}\" > config.yaml",
"_____no_output_____"
],
[
"!gcloud beta ai-platform versions create $VERSION_NAME \\\n --region=$REGION \\\n --model=$MODEL_NAME \\\n --machine-type=n1-standard-4 \\\n --config=config.yaml \\\n --image={REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}",
"_____no_output_____"
]
],
[
[
"## Send predictions\n\n### Using REST",
"_____no_output_____"
]
],
[
[
"!curl -X POST \\\n -H \"Authorization: Bearer $(gcloud auth print-access-token)\" \\\n -H \"Content-Type: application/json; charset=utf-8\" \\\n -d @instances.json \\\n https://{REGION}-ml.googleapis.com/v1/projects/{PROJECT_ID}/models/{MODEL_NAME}/versions/{VERSION_NAME}:predict",
"_____no_output_____"
]
],
[
[
"### Using Python SDK",
"_____no_output_____"
]
],
[
[
"from google.api_core.client_options import ClientOptions\nfrom googleapiclient import discovery\n\nclient_options = ClientOptions(api_endpoint=f\"https://{REGION}-ml.googleapis.com\")\n\nservice = discovery.build(\"ml\", \"v1\", client_options=client_options)\n\nresponse = (\n service.projects()\n .predict(\n name=f\"projects/{PROJECT_ID}/models/{MODEL_NAME}/versions/{VERSION_NAME}\",\n body={\"instances\": [[6.7, 3.1, 4.7, 1.5], [4.6, 3.1, 1.5, 0.2]]},\n )\n .execute()\n)\n\nif \"error\" in response:\n raise RuntimeError(response[\"error\"])\nelse:\n print(response)",
"_____no_output_____"
]
],
[
[
"### Using gcloud CLI",
"_____no_output_____"
]
],
[
[
"!gcloud beta ai-platform predict \\\n --region=$REGION \\\n --model=$MODEL_NAME \\\n --json-request=instances.json",
"_____no_output_____"
]
],
[
[
"## Cleaning up\n\nTo clean up all Google Cloud resources used in this project, you can [delete the Google Cloud\nproject](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n\nOtherwise, you can delete the individual resources you created in this tutorial:",
"_____no_output_____"
]
],
[
[
"# Delete the model version\n!gcloud ai-platform versions delete $VERSION_NAME \\\n --region=$REGION \\\n --model=$MODEL_NAME \\\n --quiet\n\n# Delete the model\n!gcloud ai-platform models delete $MODEL_NAME \\\n --region=$REGION \\\n --quiet\n\n# Delete the container image from Artifact Registry\n!gcloud artifacts docker images delete \\\n --quiet \\\n --delete-tags \\\n {REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a363ec29cad1e678dbe80bfbf0d81ea903268a2
| 780 |
ipynb
|
Jupyter Notebook
|
ml_fundamentals/.ipynb_checkpoints/ml_feature_engineering_normalization_standardization-checkpoint.ipynb
|
sjcorp/notebooks
|
ec3d9a09c3b20448087b0030bb3316be76e1b4b3
|
[
"MIT"
] | null | null | null |
ml_fundamentals/.ipynb_checkpoints/ml_feature_engineering_normalization_standardization-checkpoint.ipynb
|
sjcorp/notebooks
|
ec3d9a09c3b20448087b0030bb3316be76e1b4b3
|
[
"MIT"
] | null | null | null |
ml_fundamentals/.ipynb_checkpoints/ml_feature_engineering_normalization_standardization-checkpoint.ipynb
|
sjcorp/notebooks
|
ec3d9a09c3b20448087b0030bb3316be76e1b4b3
|
[
"MIT"
] | null | null | null | 16.595745 | 40 | 0.516667 |
[
[
[
"# Feature Transformation",
"_____no_output_____"
],
[
"## Standardisation & Normalisation",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown"
]
] |
4a364eb5dc82b86edf8dc72f1409aa4d3b30a503
| 359,621 |
ipynb
|
Jupyter Notebook
|
Cleaning_EDA.v.1.ipynb
|
HiIamJeff/Brown_Datathon
|
a1f5b93286df2c6f452e188aa74650d7615e9f5e
|
[
"MIT"
] | null | null | null |
Cleaning_EDA.v.1.ipynb
|
HiIamJeff/Brown_Datathon
|
a1f5b93286df2c6f452e188aa74650d7615e9f5e
|
[
"MIT"
] | null | null | null |
Cleaning_EDA.v.1.ipynb
|
HiIamJeff/Brown_Datathon
|
a1f5b93286df2c6f452e188aa74650d7615e9f5e
|
[
"MIT"
] | null | null | null | 76.450043 | 28,208 | 0.745963 |
[
[
[
"## Brown Datathon - Predicting house buying based on Credit Info\n\nData provided by Citizens Bank (Public use available)",
"_____no_output_____"
],
[
"### Setting Environment",
"_____no_output_____"
]
],
[
[
"## Load Basic Package \nprint('PYTHON & PACKAGE VERSION CONTROL')\nprint('----------')\nimport sys #access to system parameters https://docs.python.org/3/library/sys.html\nprint(\"Python version: {}\". format(sys.version))\nimport pandas as pd #collection of functions for data processing and analysis modeled after R dataframes with SQL like features\nprint(\"pandas version: {}\". format(pd.__version__))\nimport matplotlib #collection of functions for scientific and publication-ready visualization\nprint(\"matplotlib version: {}\". format(matplotlib.__version__))\nimport numpy as np #foundational package for scientific computing\nprint(\"NumPy version: {}\". format(np.__version__))\nimport scipy as sp #collection of functions for scientific computing and advance mathematics\nprint(\"SciPy version: {}\". format(sp.__version__)) \nimport IPython\nfrom IPython import display #pretty printing of dataframes in Jupyter notebook\nprint(\"IPython version: {}\". format(IPython.__version__)) \nimport sklearn #collection of machine learning algorithms\nprint(\"scikit-learn version: {}\". format(sklearn.__version__))\n\n#Visualization\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.pylab as pylab\nimport seaborn as sns\n# from pandas.tools.plotting import scatter_matrix\n\n#misc libraries\nimport random\nimport time\n#ignore warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\nprint('----------')",
"PYTHON & PACKAGE VERSION CONTROL\n----------\nPython version: 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)]\npandas version: 0.25.3\nmatplotlib version: 3.0.2\nNumPy version: 1.17.4\nSciPy version: 1.1.0\nIPython version: 7.2.0\nscikit-learn version: 0.20.1\n----------\n"
],
[
"## Path setting\n\npath = r'C:\\Users\\ADMIN\\Desktop\\Brown_Datathon\\citizens-home-financing-challenge' \nimport os\nprint('Path:', path)\nprint('----------')\nprint('\\n'.join(os.listdir(path)))",
"Path: C:\\Users\\ADMIN\\Desktop\\Brown_Datathon\\citizens-home-financing-challenge\n----------\nDatathonDictionaries.xlsx\ndictionaries\nzip9_coded_201904_pv.csv\nzip9_coded_201905_pv.csv\nzip9_coded_201906_pv.csv\nzip9_coded_201907_pv.csv\nzip9_coded_201908_pv.csv\nzip9_coded_201909_pv.csv\nzip9_demographics_coded_pv.csv\n"
]
],
[
[
"### First Loading Dataset\nBe careful for bigger dataset! (1.5GB couuld take about 30s through Modin)\n\nIf that is the case, use sample method in read_csv()!\n\n\n##### Modin can be faster. However, if doing functions below, use regular Pandas!\n- df.groupby(by='wp_type')\n- df.drop_duplicates()\n- df.describe()\n- df['seconds'].max()",
"_____no_output_____"
]
],
[
[
"# Pandas can have trouble dealing with moderately large data, here's a sampling example\ntotal_row_n = 6009259 # number of records in file\nsample_row_n = 60000 # sample size (can/should be changed to your preference)\nskip_row_list = sorted(random.sample(range(1,total_row_n+1), total_row_n-sample_row_n))\n\nsep_df = pd.read_csv(root_path + \"zip9_coded_201908_pv.csv\", skiprows=skip_row_list)\ndemo_df = pd.read_csv(root_path + \"zip9_demographics_coded_pv.csv\", skiprows=skip_row_list)\n\n\n",
"_____no_output_____"
],
[
"import os\nos.environ[\"MODIN_ENGINE\"] = \"dask\" # Modin will use Dask\nimport modin.pandas as pd\npd.__version__\n# import modin.pandas as pd\n# %%timeit -n1 -r1",
"_____no_output_____"
],
[
"t0 = time.time()\n\ndata_path = path\ndata_file = 'zip9_coded_201909_pv.csv'\ndata_set = pd.read_csv(data_path+'/'+data_file)\n\nprint('Complete loading df!')\n\nt1 = time.time()\nprint(\"Time to process {}s\".format(round(t1-t0,2)))",
"Complete loading df!\nTime to process 31.84s\n"
],
[
"df = data_set.copy()",
"_____no_output_____"
],
[
"#Basic Checking for dataset\nprint('Dataset Shape:\\n', df.shape)\ndf.head()",
"_____no_output_____"
]
],
[
[
"### New Inspection Tool: d-tale\nGithub: https://github.com/man-group/dtale",
"_____no_output_____"
]
],
[
[
"import dtale\nd = dtale.show(df)\nprint('Complete loading df!')\nd",
"_____no_output_____"
]
],
[
[
"## Data Wrangling\n### Basic Info about Dataset ",
"_____no_output_____"
]
],
[
[
"print(df.info())\nprint(\"-\"*10)\nprint('Dataset Shape:\\n', df.shape)\nprint(\"-\"*10)",
"_____no_output_____"
]
],
[
[
"### Data Cleaning: NA, Empty String, Meaningless Value\n#### Checking ",
"_____no_output_____"
]
],
[
[
"print('Dataset columns with null & None values:\\n', df.isnull().sum())\nprint('Note: Please Check for possible null-related values (empty string, meaningless value...)')\n# print(df2.describe())\nprint(\"-\"*10)\n\n## Check for 'empty string'\n## If this generate non-empty array, then dataset contains empty string in following position.\n# np.where(df.applymap(lambda x: x == ''))\nprint(df[df.applymap(lambda x: x == '').any(axis=1)])\nprint(\"p.s. If the dataframe above show no rows, then the dataframe doesn't have any empty string.\")",
"_____no_output_____"
]
],
[
[
"#### Data Cleaning: A variable & B variable",
"_____no_output_____"
]
],
[
[
"df.describe(include = 'all')",
"_____no_output_____"
],
[
"df.describe().apply(lambda s:s.apply(lambda x:format(x, 'f')))",
"_____no_output_____"
]
],
[
[
"### Data Cleaning: String Manipulation",
"_____no_output_____"
],
[
"## Explonatory Analysis",
"_____no_output_____"
],
[
"### Exploratory: Target Variable",
"_____no_output_____"
]
],
[
[
"## Target Variable\ntarget_variable_name = 'Survived'\nprint('target variable:', target_variable_name)\nprint('variable type:', type(df[target_variable_name][0]))\n\n# This is for changing the data type in some cases.\n# df_Regress[target_variable_name] = df_Regress[target_variable_name].replace('[^.0-9]', '', regex=True).astype(float)",
"_____no_output_____"
],
[
"## Classifier only\ndf_Class = df\ntarget_sum = pd.DataFrame([df_Class[target_variable_name].value_counts(),\n round(df_Class[target_variable_name].value_counts()/sum(df_Class[target_variable_name].value_counts()), 4)],\n index=['Count','Percentage']).T\nprint('Total Observations:', sum(df_Class[target_variable_name]))\nprint(target_sum.astype({\"Count\": int}))\n\nfig = plt.figure(figsize=[3,5])\nax = sns.barplot(y=\"Count\", x=['0','1'], data=target_sum)\nfor p, i in zip(ax.patches, [0,1]):\n percent = target_sum['Percentage'][i]\n ax.annotate('{:.2f}%'. format(percent*100), (p.get_x()+0.4, p.get_height()-50), ha='center', size=15, color='white')",
"_____no_output_____"
],
[
"## Regression only\ndf_Regress = df\nplt.figure(figsize=(10,5))\nsns.distplot(df_Regress[target_variable_name])\nplt.figure(figsize=(10,5))\nplt.hist(x=df_Regress[target_variable_name])",
"_____no_output_____"
],
[
"# data_path\ndata_path = r'C:\\Users\\ADMIN\\Desktop\\Brown_Datathon\\citizens-home-financing-challenge'",
"_____no_output_____"
],
[
"# data_path = r'C:\\Users\\ADMIN\\Desktop\\Brown_Datathon\\citizens-home-financing-challenge'\n# tar_data_file = 'ip9_demographics_coded_pv.csv'\n# tar_data_set = pd.read_csv(data_path+'/'+tar_data_file)\n\n \ndata_t1 = pd.read_csv(data_path+'/'+'zip9_demographics_coded_pv.csv')\n \nprint('Complete loading df!')",
"_____no_output_____"
],
[
"target_variable_name = 'homebuyers'\n\ndf_Regress = data_t1\nplt.figure(figsize=(10,5))\nsns.distplot(df_Regress[target_variable_name])\nplt.figure(figsize=(10,5))\nplt.hist(x=df_Regress[target_variable_name])",
"_____no_output_____"
],
[
"df_Regress[target_variable_name].value_counts()",
"_____no_output_____"
]
],
[
[
"### Exploratory: Target Variable vs Other Variable",
"_____no_output_____"
]
],
[
[
"path",
"_____no_output_____"
],
[
"path2 =r'C:\\Users\\ADMIN\\Desktop\\Brown_Datathon'",
"_____no_output_____"
]
],
[
[
"### Fast Auto Visuailization Package: AutoViz\n",
"_____no_output_____"
]
],
[
[
"n = 6009259 # number of records in file\ns = 60000 # sample size (can/should be changed to your preference)\n\nskip_list = sorted(random.sample(range(1,n+1),n-s))\nvis_df = pd.read_csv(path +'/'+ \"zip9_coded_201908_pv.csv\", skiprows=skip_list, dtype={'zip5': str})",
"_____no_output_____"
],
[
"# vis_df = pd.read_csv(path2+'/'+'merge_09_df.csv', )\n# vis_df\n\nsep_demo_merge11 = vis_df.merge(demo_df,\n how='inner',\n on='zip9_code',\n suffixes=('_sep','_demo'),\n validate='one_to_one')\n",
"_____no_output_____"
],
[
"### AutoViz\nfrom autoviz.AutoViz_Class import AutoViz_Class\nAV = AutoViz_Class()",
"_____no_output_____"
],
[
"sep_demo_merge11.head()",
"_____no_output_____"
],
[
"target_variable_name = 'homebuyers'\n\n##\nsep = '/'\ndft = AV.AutoViz('', ',', target_variable_name, sep_demo_merge11)\n\n",
"Shape of your Data Set: (60000, 59)\nClassifying variables in data set...\n 58 Predictors classified...\n This does not include the Target column(s)\n 16 variables removed since they were ID or low-information variables\n38 numeric variables in data exceeds limit, taking top 30 variables\nNumber of numeric variables = 38\n Number of variables removed due to high correlation = 7 \n Adding 4 categorical variables to reduced numeric variables of 31\nSelected No. of variables = 35 \nFinding Important Features...\nNot able to read or load file. Please check your inputs and try again...\n"
],
[
"# Generating a whole new html page of the dataframe. Should open it through outside the notebook!\nimport webbrowser\ndff.to_html(\"df_web.html\")\nurl = \"http://localhost:8888/files/notebook/df_web.html\"\n# webbrowser.open(url,new=2)",
"_____no_output_____"
]
],
[
[
"### Merging Data\n\n#### Fields",
"_____no_output_____"
]
],
[
[
"demo_df = pd.read_csv(data_path+'/'+'zip9_demographics_coded_pv.csv')\nsep_df = df",
"_____no_output_____"
],
[
"sep_demo_merge = sep_df.merge(demo_df,\n how='inner',\n on='zip9_code',\n suffixes=('_sep','_demo'),\n validate='one_to_one')\n\nsep_demo_merge = sep_demo_merge.drop(['Unnamed: 0', 'zip5_demo'], axis=1)",
"_____no_output_____"
],
[
"sep_demo_merge.head()",
"_____no_output_____"
],
[
"d = dtale.show(df)\nprint('Complete loading df!')",
"_____no_output_____"
],
[
"# sep_demo_merge.to_csv('merge_09_df.csv')\ndata_path = r'C:\\Users\\ADMIN\\Desktop\\Brown_Datathon'",
"_____no_output_____"
],
[
"# generate a smaller df to practice Tableau\n\nsep_demo_merge = pd.read_csv(data_path+'/'+'merge_09_df.csv')\nsmall_df = sep_demo_merge.sample(frac=0.05, random_state=1)\nprint('complete')",
"_____no_output_____"
],
[
"# small_df.to_csv('small_df.csv')\nmid_df = sep_demo_merge.sample(frac=0.2, random_state=1)\nmid_df.shape",
"_____no_output_____"
],
[
"mid_df.to_csv('mid_df.csv')\nprint('complete!')",
"_____no_output_____"
]
],
[
[
"#### Area assigned by ZIP Code ",
"_____no_output_____"
]
],
[
[
"from uszipcode import SearchEngine",
"_____no_output_____"
],
[
"small_df['district'] = [search.by_zipcode(i).values()[3] for i in small_df['zip5_sep']]\nsmall_df.head()\n\n# tt.head() \n# print(search.by_zipcode(tt['zip5_sep']).values()[3])",
"_____no_output_____"
],
[
"# small_df.head()['district'].str.split(', ', expand=True)\n# tt = small_df.head()\n# tt['district'].str.split(', ', expand=True)\ntt_1 = pd.concat([tt, tt['district'].str.split(', ', expand=True)], axis=1, join='inner')\ntt_1.rename(columns={0: 'small_district', 2:'state'}, inplace=True)\ntt_1\n# small_df.\n\n# result = pd.concat([df1, df4], axis=1, join='inner')\n",
"_____no_output_____"
]
],
[
[
"### New Sample: Claire\n",
"_____no_output_____"
]
],
[
[
"col_list = ['age',\n'autoloan_open',\n'bankcard_balance',\n'bankcard_limit',\n'bankcard_open',\n'bankcard_trades',\n'bankcard_util',\n'first_homebuyers',\n'homebuyers',\n'homeequity_open',\n'household_count',\n'mortgage_open',\n'mortgage1_loan_to_value',\n'person_count',\n'studentloan_open',\n'total_homeequity_balance',\n'total_homeequity_limit',\n'total_homeequity_trades',\n'total_mortgage_balance',\n'total_mortgage_limit',\n'total_mortgage_trades',\n'total_revolving_balance',\n'total_revolving_limit',\n'total_revolving_trades',\n'total_revolving_util',\n'zip5_sep',\n'zip9_code']\n\ncol_list1 = ['zip5','zip9_code',\n'autoloan_open',\n'bankcard_balance',\n'bankcard_limit',\n'bankcard_open',\n'bankcard_trades',\n'bankcard_util',\n'homeequity_open',\n'mortgage_open',\n'mortgage1_loan_to_value',\n'studentloan_open',\n'total_homeequity_balance',\n'total_homeequity_limit',\n'total_homeequity_trades',\n'total_mortgage_balance',\n'total_mortgage_limit',\n'total_mortgage_trades',\n'total_revolving_balance',\n'total_revolving_limit',\n'total_revolving_trades',\n'total_revolving_util']\n",
"_____no_output_____"
],
[
"data_set = pd.read_csv(path+'/'+'zip9_coded_201908_pv.csv', usecols=col_list1)\nprint('complete')",
"_____no_output_____"
],
[
"demo_df = pd.read_csv(path+'/'+'zip9_demographics_coded_pv.csv')\nprint('complete!')",
"_____no_output_____"
],
[
"sep_demo_merge = data_set.merge(demo_df,\n how='inner',\n on='zip9_code',\n suffixes=('_sep','_demo'),\n validate='one_to_one')\nsep_demo_merge = sep_demo_merge.drop(['zip5_demo'], axis=1)\n# check!",
"_____no_output_____"
],
[
"sep_demo_merge.to_csv('merge_08_df.csv',index=False)\nprint('complete')\n# check!",
"_____no_output_____"
],
[
"path = r'C:\\Users\\ADMIN\\Desktop\\Brown_Datathon\\citizens-home-financing-challenge'\npath2 = r'C:\\Users\\ADMIN\\Desktop\\Brown_Datathon'",
"_____no_output_____"
],
[
"## pipeline\nfor name in ['zip9_coded_201906_pv.csv', 'zip9_coded_201907_pv.csv']:\n data_set = pd.read_csv(path+'/'+name, usecols=col_list1)\n sep_demo_merge = data_set.merge(demo_df,\n how='inner',\n on='zip9_code',\n suffixes=('_sep','_demo'),\n validate='one_to_one')\n sep_demo_merge = sep_demo_merge.drop(['zip5_demo'], axis=1)\n sep_demo_merge.to_csv('new_'+name, index=False)\n print('complete '+ name)\n",
"_____no_output_____"
],
[
"data_set = pd.read_csv(path+'/'+'zip9_coded_201907_pv.csv', names=['zip5_sep','zip9_code'])\n",
"_____no_output_____"
]
],
[
[
"## Final works!!! New Feature: Jeff",
"_____no_output_____"
]
],
[
[
"# path\n# path2\npath2 =r'C:\\Users\\ADMIN\\Desktop\\Brown_Datathon'\necon_df = pd.read_csv(path2+'/'+'17zpallnoagi.csv')\nprint('complete')\n",
"complete\n"
],
[
"econ_df.head()\necon_df['STATEFIPS'].value_counts(dropna=False)\necon_df = econ_df.dropna()\necon_df.head()\n# test = econ_df[econ_df['STATEFIPS'] is not np.nan()]\n",
"_____no_output_____"
],
[
"econ = econ_df[['A18800']]\necon\n# econ_df['STATEFIPS'] == True\n\n\n",
"_____no_output_____"
],
[
"## new data stardization\nfrom sklearn import preprocessing\n",
"_____no_output_____"
],
[
"\n# Create the Scaler object\nscaler = preprocessing.StandardScaler()\nscaled_econ = scaler.fit_transform(np.array(econ))\nscaled_econ = np.reshape(scaled_econ, (scaled_econ.shape[0],))\nscaled_econ.tolist()",
"_____no_output_____"
],
[
"\n# econ_df['ZIPCODE'].astype('int64')\n# econ_df\n# econ_df['ZIPCODE']\nnew_econ_df = pd.DataFrame(scaled_econ.tolist(), index = econ_df['ZIPCODE'].astype('int64'))\nnew_econ_df = new_econ_df.reset_index()\nnew_econ_df.columns = ['zip5_sep', 'Personal_property_taxes_amount']\nnew_econ_df.head()\n",
"_____no_output_____"
]
],
[
[
"## Claire data + new econ metric\n\n",
"_____no_output_____"
]
],
[
[
"# from feature_selector import FeatureSelector\n# Features are in train and labels are in train_labels\n# fs = FeatureSelector(data = train, labels = train_labels)\npath2",
"_____no_output_____"
],
[
"data_file = 'Total_data.csv'\nfinal_df = pd.read_csv(path2+'/'+data_file)\nprint('complete')\n\n",
"complete\n"
],
[
"# final_df = final_df.drop('Unnamed: 0', axis = 1)\nfinal_df.head()\n\nfinal_df2 = final_df.merge(new_econ_df,\n how='inner',\n on='zip5_sep',\n suffixes=('_sep','_demo'),\n validate='many_to_many')",
"_____no_output_____"
],
[
"final_df3= final_df2[['person_count', 'age', \n 'mortgage_open', 'studentloan_open', 'bankcard_balance', \n 'total_revolving_util', 'total_revolving_trades', 'autoloan_open', \n 'total_homeequity_limit', 'total_homeequity_balance', 'total_mortgage_balance', \n 'zip5_sep', 'homeequity_open', 'Personal_property_taxes_amount','homebuyers']]",
"_____no_output_____"
],
[
"# final_df3.head()\n# final_df2.head()['total_homeequity_balance']\nfinal_df2.shape\nfinal_df3.shape",
"_____no_output_____"
],
[
"# no_nan_df = final_df2.dropna(how='any')\n",
"_____no_output_____"
],
[
"# no_nan_df.shape",
"_____no_output_____"
],
[
"\n# n = 6009259 # number of records in file\n# s = 60000 # sample size (can/should be changed to your preference)\n# \n# final_df2 \n\n# skip_list = sorted(random.sample(range(1,n+1),n-s))\n# sep_df = pd.read_csv(root_path + \"zip9_coded_201908_pv.csv\", skiprows=skip_list, dtype={'zip5': str})\n# demo_df = pd.read_csv(root_path + \"zip9_demographics_coded_pv.csv\", skiprows=skip_list, dtype={'zip5': str})\n\n# final_df2_sample = final_df2.sample(frac=0.05, random_state=1)\nfinal_df3_sample = final_df3.sample(frac=0.05, random_state=1)\nprint('complete')",
"complete\n"
]
],
[
[
"## Machine Learning",
"_____no_output_____"
]
],
[
[
"target_variable_name = 'homebuyers'\n\nfrom sklearn import model_selection\ntrain_X, test_X, train_y, test_y = model_selection.train_test_split(final_df3_sample.drop(target_variable_name, axis = 1), final_df3_sample[target_variable_name], test_size=0.3, random_state = 10)\n\n# generate the train and test data suitable for this package\ntrain = train_X.copy()\ntrain[target_variable_name] = train_y\ntest = test_X.copy()\ntest[target_variable_name] = test_y\n\n\n",
"_____no_output_____"
],
[
"# train_y",
"_____no_output_____"
],
[
"from autoviml.Auto_ViML import Auto_ViML",
"_____no_output_____"
],
[
"# final",
"_____no_output_____"
],
[
"import pickle",
"_____no_output_____"
],
[
"## Run the AutoML!\n#### If Boosting_Flag = True => XGBoost, Fase=>ExtraTrees, None=>Linear Model\nsample_submission=''\nscoring_parameter = 'balanced-accuracy'\n\nm, feats, trainm, testm = Auto_ViML(train, target_variable_name, test, sample_submission,\n scoring_parameter=scoring_parameter,\n hyper_param='GS',feature_reduction=True,\n Boosting_Flag=True,Binning_Flag=False,\n Add_Poly=0, Stacking_Flag=False, \n Imbalanced_Flag=False, \n verbose=1) \n\n# p.s. This could run much more than what the package estimated!\n\n# m, feats, trainm, testm = Auto_ViML(train, target_variable_name, test, sample_submission,\n# scoring_parameter=scoring_parameter,\n# hyper_param='GS',feature_reduction=True,\n# Boosting_Flag=True,Binning_Flag=False,\n# Add_Poly=0, Stacking_Flag=False, \n# Imbalanced_Flag=False, \n# verbose=1)\n",
"yes\nTrain (Size: 209753,28) has Single_Label with target: ['homebuyers']\n\"\n ################### Regression ######################\n Top columns in Train with missing values: ['total_homeequity_balance', 'total_homeequity_limit', 'total_mortgage_balance', 'total_mortgage_limit', 'bankcard_util']\n and their missing value totals: [110791, 110791, 38494, 38494, 1197]\nClassifying variables in data set...\n Number of Numeric Columns = 21\n Number of Integer-Categorical Columns = 4\n Number of String-Categorical Columns = 0\n Number of Factor-Categorical Columns = 0\n Number of String-Boolean Columns = 0\n Number of Numeric-Boolean Columns = 0\n Number of Discrete String Columns = 0\n Number of NLP String Columns = 0\n Number of Date Time Columns = 0\n Number of ID Columns = 2\n Number of Columns to Delete = 0\n 27 Predictors classified...\n This does not include the Target column(s)\n 2 variables removed since they were ID or low-information variables\nTest data has no missing values...\nNumber of numeric variables = 25\n Number of variables removed due to high correlation = 9 \n Feature Selection begins: currently 16 predictors\n\nData Ready for Modeling with homebuyers as Target...\nLinear feature selection: out of 0 categorical features...\nNumber of numeric variables = 16\n Number of variables removed due to high correlation = 1 \n Adding 0 categorical variables to reduced numeric variables of 15\nCurrent number of predictors = 15 \n Finding Important Features using Boosted Trees algorithm...\n using 15 variables...\n[03:15:11] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 12 variables...\n[03:15:22] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 9 variables...\n[03:15:31] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 6 variables...\n[03:15:38] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 3 variables...\n[03:15:46] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\nFound 15 important features\n Features list: ['first_homebuyers', 'person_count', 'age', 'mortgage_open', 'studentloan_open', 'bankcard_balance', 'total_revolving_util', 'total_revolving_trades', 'autoloan_open', 'total_homeequity_limit', 'total_homeequity_balance', 'total_mortgage_balance', 'zip5_sep', 'homeequity_open', 'Personal_property_taxes_amount']\nStarting Feature Engineering now...\n No Entropy Binning specified or there are no numeric vars in data set to Bin\n\nRows in Train data set = 178290\n Features in Train data set = 15\n Rows in held-out data set = 31463\nFinding Best Model and Hyper Parameters for Target: homebuyers...\n\nUsing XGBoost Model, Estimated Training time = 133.7 mins\n[05:42:09] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n Model training time (in seconds): 8786\n5-fold Cross Validation rmse Score = 0.1529\n Best Parameters for Model = {'gamma': 0, 'learning_rate': 0.2, 'max_depth': 2, 'n_estimators': 100}\nXGBoost Model Prediction Results on Held Out CV Data Set:\n"
],
[
"filename = 'finalized_model.sav'\npickle.dump(m, open(filename, 'wb'))",
"_____no_output_____"
],
[
"## second time without first homebuyer\n\nsample_submission=''\nscoring_parameter = 'balanced-accuracy'\n\nm1, feats1, trainm1, testm1 = Auto_ViML(train, target_variable_name, test, sample_submission,\n scoring_parameter=scoring_parameter,\n hyper_param='GS',feature_reduction=True,\n Boosting_Flag=True,Binning_Flag=False,\n Add_Poly=0, Stacking_Flag=False, \n Imbalanced_Flag=False, \n verbose=1)\n",
"yes\nTrain (Size: 209753,15) has Single_Label with target: ['homebuyers']\n\"\n ################### Regression ######################\n Top columns in Train with missing values: ['total_homeequity_balance', 'total_homeequity_limit', 'total_mortgage_balance', 'total_revolving_util']\n and their missing value totals: [110791, 110791, 38494, 382]\nClassifying variables in data set...\n Number of Numeric Columns = 12\n Number of Integer-Categorical Columns = 2\n Number of String-Categorical Columns = 0\n Number of Factor-Categorical Columns = 0\n Number of String-Boolean Columns = 0\n Number of Numeric-Boolean Columns = 0\n Number of Discrete String Columns = 0\n Number of NLP String Columns = 0\n Number of Date Time Columns = 0\n Number of ID Columns = 0\n Number of Columns to Delete = 0\n 14 Predictors classified...\n This does not include the Target column(s)\n No variables removed since no ID or low-information variables found in data set\nTest data has no missing values...\nNumber of numeric variables = 14\n No variables were removed since no highly correlated variables found in data\n Feature Selection begins: currently 14 predictors\n\nData Ready for Modeling with homebuyers as Target...\nLinear feature selection: out of 0 categorical features...\nNumber of numeric variables = 14\n No variables were removed since no highly correlated variables found in data\n Adding 0 categorical variables to reduced numeric variables of 14\nCurrent number of predictors = 14 \n Finding Important Features using Boosted Trees algorithm...\n using 14 variables...\n[07:41:02] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 11 variables...\n[07:41:11] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 8 variables...\n[07:41:18] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 5 variables...\n[07:41:24] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 2 variables...\n[07:41:29] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\nFound 14 important features\n Features list: ['person_count', 'total_revolving_trades', 'studentloan_open', 'bankcard_balance', 'autoloan_open', 'age', 'total_homeequity_balance', 'total_revolving_util', 'total_homeequity_limit', 'mortgage_open', 'Personal_property_taxes_amount', 'zip5_sep', 'total_mortgage_balance', 'homeequity_open']\nStarting Feature Engineering now...\n No Entropy Binning specified or there are no numeric vars in data set to Bin\n\nRows in Train data set = 178290\n Features in Train data set = 14\n Rows in held-out data set = 31463\nFinding Best Model and Hyper Parameters for Target: homebuyers...\n\nUsing XGBoost Model, Estimated Training time = 124.8 mins\nTraining regular model is Erroring: Check if your Input Data is in correct Format...\n"
],
[
"filename = 'finalized_model2.sav'\npickle.dump(m, open(filename, 'wb'))",
"_____no_output_____"
],
[
"#### Regression Only #####\n## Result of each model\n\ndef rmse(results, y_cv):\n return np.sqrt(np.mean((results - y_cv)**2, axis=0))\nfrom autoviml.Auto_ViML import print_regression_model_stats\n\n## Change the 'modelname' to generate different model result\nmodelname='LassoLarsCV Regression'\nprint('Model:', modelname)\n# print('RMSE:', rmse(test[target_variable_name].values,testm[target_variable_name+'_'+modelname+'_predictions'].values))\nprint_regression_model_stats(test[target_variable_name].values,testm[target_variable_name+'_'+modelname+'_predictions'].values)\n\n",
"_____no_output_____"
],
[
"\n\n## USE CLAIRE DATA",
"_____no_output_____"
],
[
"\n",
"_____no_output_____"
],
[
"# data_file = 'Total_data.csv'\n# df_new = pd.read_csv(path2+'/'+data_file)\n# print('complete')",
"complete\n"
],
[
"df_new = final_df3.fillna(0)\n\nprint('Dataset columns with null & None values:\\n', df_new.isnull().sum())\nprint('Note: Please Check for possible null-related values (empty string, meaningless value...)')\n# print(df2.describe())\nprint(\"-\"*10)\n\n## Check for 'empty string'\n## If this generate non-empty array, then dataset contains empty string in following position.\n# np.where(df.applymap(lambda x: x == ''))\n# print(df[df.applymap(lambda x: x == '').any(axis=1)])\n# print(\"p.s. If the dataframe above show no rows, then the dataframe doesn't have any empty string.\")",
"Dataset columns with null & None values:\n person_count 0\nage 0\nmortgage_open 0\nstudentloan_open 0\nbankcard_balance 0\ntotal_revolving_util 0\ntotal_revolving_trades 0\nautoloan_open 0\ntotal_homeequity_limit 0\ntotal_homeequity_balance 0\ntotal_mortgage_balance 0\nzip5_sep 0\nhomeequity_open 0\nPersonal_property_taxes_amount 0\nhomebuyers 0\ndtype: int64\nNote: Please Check for possible null-related values (empty string, meaningless value...)\n----------\n"
],
[
"df_new.shape",
"_____no_output_____"
],
[
"df_new_sample = df_new.sample(frac=0.01, random_state=1)\nprint('complete')\n\n",
"complete\n"
],
[
"df_new_sample.shape",
"_____no_output_____"
],
[
"from autoviml.Auto_ViML import Auto_ViML",
"_____no_output_____"
],
[
"target_variable_name = 'homebuyers'\n\nfrom sklearn import model_selection\ntrain_X1, test_X1, train_y1, test_y1 = model_selection.train_test_split(df_new_sample.drop(target_variable_name, axis = 1), df_new_sample[target_variable_name], test_size=0.3, random_state = 10)\n\n# generate the train and test data suitable for this package\ntrain1 = train_X1.copy()\ntrain1[target_variable_name] = train_y1\ntest1 = test_X1.copy()\ntest1[target_variable_name] = test_y1\n",
"_____no_output_____"
],
[
"\n## second time without first homebuyer\n\nsample_submission=''\nscoring_parameter = 'balanced-accuracy'\n\nm1, feats1, trainm1, testm1 = Auto_ViML(train1, target_variable_name, test1, sample_submission,\n scoring_parameter=scoring_parameter,\n hyper_param='GS',feature_reduction=True,\n Boosting_Flag=True,Binning_Flag=False,\n Add_Poly=0, Stacking_Flag=False, \n Imbalanced_Flag=False, \n verbose=1)\n",
"yes\nTrain (Size: 41951,15) has Single_Label with target: ['homebuyers']\n\"\n ################### Regression ######################\nClassifying variables in data set...\n Number of Numeric Columns = 12\n Number of Integer-Categorical Columns = 2\n Number of String-Categorical Columns = 0\n Number of Factor-Categorical Columns = 0\n Number of String-Boolean Columns = 0\n Number of Numeric-Boolean Columns = 0\n Number of Discrete String Columns = 0\n Number of NLP String Columns = 0\n Number of Date Time Columns = 0\n Number of ID Columns = 0\n Number of Columns to Delete = 0\n 14 Predictors classified...\n This does not include the Target column(s)\n No variables removed since no ID or low-information variables found in data set\nTest data has no missing values...\nNumber of numeric variables = 14\n Number of variables removed due to high correlation = 1 \n Feature Selection begins: currently 13 predictors\n\nData Ready for Modeling with homebuyers as Target...\nLinear feature selection: out of 0 categorical features...\nNumber of numeric variables = 13\n No variables were removed since no highly correlated variables found in data\n Adding 0 categorical variables to reduced numeric variables of 13\nCurrent number of predictors = 13 \n Finding Important Features using Boosted Trees algorithm...\n using 13 variables...\n[09:58:18] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 10 variables...\n[09:58:21] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 7 variables...\n[09:58:23] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 4 variables...\n[09:58:25] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n using 1 variables...\n[09:58:26] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\nFound 13 important features\n Features list: ['person_count', 'autoloan_open', 'total_homeequity_balance', 'total_revolving_util', 'mortgage_open', 'total_mortgage_balance', 'age', 'studentloan_open', 'bankcard_balance', 'homeequity_open', 'Personal_property_taxes_amount', 'zip5_sep', 'total_revolving_trades']\nStarting Feature Engineering now...\n No Entropy Binning specified or there are no numeric vars in data set to Bin\n\nRows in Train data set = 37755\n Features in Train data set = 13\n Rows in held-out data set = 4196\nFinding Best Model and Hyper Parameters for Target: homebuyers...\n\nUsing XGBoost Model, Estimated Training time = 24.5 mins\n[10:19:25] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n Model training time (in seconds): 1259\n5-fold Cross Validation rmse Score = 0.2348\n Best Parameters for Model = {'gamma': 0, 'learning_rate': 0.1, 'max_depth': 2, 'n_estimators': 100}\nXGBoost Model Prediction Results on Held Out CV Data Set:\n"
],
[
"\n\ntestm1",
"_____no_output_____"
],
[
"m1",
"_____no_output_____"
],
[
"path2",
"_____no_output_____"
],
[
"hold_out_set = pd.read_csv(path2+'/'+'zip9_coded_201909_wh.csv')\n# new_econ_df.column = ['zip5', 'Personal_property_taxes_amount']\n# new_econ_df.head()",
"_____no_output_____"
],
[
"demo_df2 = pd.read_csv(path2+'/'+'zip9_demographics_unlabeled_wh_test.csv')",
"_____no_output_____"
],
[
"hold_out_set.rename(columns={'zip5': 'zip5_sep'}, inplace=True)\nhold_out_set2 = hold_out_set.merge(demo_df2,\n how='inner',\n on='zip9_code',\n suffixes=('_sep','_demo'),\n validate='one_to_one')\nhold_out_set2.head()",
"_____no_output_____"
],
[
"# hold_out_set2\n\nhold_out_set2 = hold_out_set2.fillna(0)\n# hold_out_set.rename(columns={'zip5': 'zip5_sep'}, inplace=True)\n\n\nhold_out_set3 = hold_out_set2.merge(new_econ_df,\n how='inner',\n on='zip5_sep',\n suffixes=('_sep','_demo'),\n validate='many_to_many')\n\n",
"_____no_output_____"
],
[
"hold_out_set3.head()",
"_____no_output_____"
],
[
"hold_out_set4= hold_out_set3[['person_count', 'age', \n 'mortgage_open', 'studentloan_open', 'bankcard_balance', \n 'total_revolving_util', 'total_revolving_trades', 'autoloan_open', \n 'total_homeequity_balance', 'total_mortgage_balance', \n 'zip5_sep', 'homeequity_open', 'Personal_property_taxes_amount']]\n\n\n",
"_____no_output_____"
],
[
"hold_out_set5= hold_out_set4[['person_count', 'autoloan_open', 'total_homeequity_balance', 'total_revolving_util', 'mortgage_open', 'total_mortgage_balance', 'age', 'studentloan_open', 'bankcard_balance', 'homeequity_open', 'Personal_property_taxes_amount', 'zip5_sep', 'total_revolving_trades']]\n\n# output = m1.predict(data=hold_out_set3)\n# list(hold_out_set4.columns)\n\n\n",
"_____no_output_____"
],
[
"list(train_X1.columns)\n\n\n# output = m1.predict(data=hold_out_set)\n# final_df = pd.DataFrame()",
"_____no_output_____"
],
[
"output = m1.predict(data=hold_out_set5)",
"_____no_output_____"
],
[
"# output\naaa = pd.DataFrame(output)\naaa.head()",
"_____no_output_____"
],
[
"aaa.to_csv('result01.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",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a365282d8391a48cd9d203912f782fbe811f0f9
| 29,796 |
ipynb
|
Jupyter Notebook
|
numpy_exercises.ipynb
|
o0amandagomez0o/numpy-pandas-visualization-exercises
|
79feb98227aea16206e34e774dbc521ccd064766
|
[
"MIT"
] | null | null | null |
numpy_exercises.ipynb
|
o0amandagomez0o/numpy-pandas-visualization-exercises
|
79feb98227aea16206e34e774dbc521ccd064766
|
[
"MIT"
] | null | null | null |
numpy_exercises.ipynb
|
o0amandagomez0o/numpy-pandas-visualization-exercises
|
79feb98227aea16206e34e774dbc521ccd064766
|
[
"MIT"
] | null | null | null | 21.313305 | 987 | 0.464391 |
[
[
[
"import numpy as np",
"_____no_output_____"
],
[
"a = np.array([4, 10, 12, 23, -2, -1, 0, 0, 0, -6, 3, -7])",
"_____no_output_____"
]
],
[
[
"# 1.\nHow many negative numbers are there?",
"_____no_output_____"
]
],
[
[
"neg_a = a[a < 0]\n\n#neg_a\nlen(neg_a)",
"_____no_output_____"
]
],
[
[
"# 2.\nHow many positive numbers are there?",
"_____no_output_____"
]
],
[
[
"def pos_a(a):\n return a[a > 0]\n\n#pos_a(a)\nlen(pos_a(a))",
"_____no_output_____"
]
],
[
[
"# 3.\nHow many even positive numbers are there?",
"_____no_output_____"
]
],
[
[
"#even_a = a[a % 2 ==0]\n\npos_even_a = pos_a([pos_a % 2 == 0])\n\nlen(pos_even_a(a))",
"_____no_output_____"
],
[
"even_pos = a[(a > 0) & (a % 2 == 0)]\n\neven_pos",
"_____no_output_____"
]
],
[
[
"# 4. \nIf you were to add 3 to each data point, how many positive numbers would there be?",
"_____no_output_____"
]
],
[
[
"plus_3 = a + 3\n\n#plus_3\n\npos_a(plus_3)\n\nlen(pos_a(plus_3))",
"_____no_output_____"
]
],
[
[
"# 5. \nIf you squared each number, what would the new mean and standard deviation be?",
"_____no_output_____"
]
],
[
[
"a_sqrd = a * a\n\na_sqrd\n\na_sqrd.mean(), a_sqrd.std()",
"_____no_output_____"
]
],
[
[
"# 6.\nA common statistical operation on a dataset is **centering**. This means to adjust the data such that the mean of the data is 0. This is done by subtracting the mean from each data point. Center the data set. See this link for more on centering: https://www.theanalysisfactor.com/centering-and-standardizing-predictors/",
"_____no_output_____"
]
],
[
[
"centered_a = a - a.mean()\n\ncentered_a",
"_____no_output_____"
]
],
[
[
"# 7. \nCalculate the z-score for each data point. Recall that the z-score is given by:\n- z = (x - μ)/ σ\n",
"_____no_output_____"
]
],
[
[
"zscore_a = (a - a.mean()) / a.std()\n\nzscore_a",
"_____no_output_____"
]
],
[
[
"# 8.\nCopy the setup and exercise directions from More Numpy Practice (https://gist.github.com/ryanorsinger/c4cf5a64ec33c014ff2e56951bc8a42d) into your `numpy_exercises.py` and add your solutions.",
"_____no_output_____"
]
],
[
[
"import numpy as np\n# Life w/o numpy to life with numpy\n\n## Setup 1\na = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]",
"_____no_output_____"
],
[
"# Use python's built in functionality/operators to determine the following:\n# Exercise 1 - Make a variable called sum_of_a to hold the sum of all the numbers in above list\n#a = np.array(a)\n#sum_of_a = a.sum()\n\nsum_of_a = sum(a)\n\nsum_of_a",
"_____no_output_____"
],
[
"# Exercise 2 - Make a variable named min_of_a to hold the minimum of all the numbers in the above list\n#min_of_a = a.min()\nmin_of_a = min(a)\nmin_of_a",
"_____no_output_____"
],
[
"# Exercise 3 - Make a variable named max_of_a to hold the max number of all the numbers in the above list\n#max_of_a = a.max()\nmax_of_a = max(a)\nmax_of_a",
"_____no_output_____"
],
[
"# Exercise 4 - Make a variable named mean_of_a to hold the average of all the numbers in the above list\n#mean_of_a = a.mean()\nmean_of_a = sum(a) / len(a)\nmean_of_a",
"_____no_output_____"
],
[
"# Exercise 5 - Make a variable named product_of_a to hold the product of multiplying all the numbers in the above list together\n#product_of_a = a.prod()\ndef multiplication(num):\n product = 1\n for ele in num:\n product *= ele\n return product\n\nproduct_of_a = multiplication(a)\n\nproduct_of_a",
"_____no_output_____"
],
[
"# Exercise 6 - Make a variable named squares_of_a. It should hold each number in a squared like [1, 4, 9, 16, 25...]\n#squares_of_a = np.square(a)\ndef squared(numbers):\n sqs = []\n for n in numbers:\n sqs.append(n * n)\n return sqs\n\nsquares_of_a = squared(a)\n\nsquares_of_a",
"_____no_output_____"
],
[
"# Exercise 7 - Make a variable named odds_in_a. It should hold only the odd numbers\n#odds_in_a = a[a % 2 != 0]\ndef odd_numbers(digits):\n odd = []\n for d in digits:\n if d % 2 != 0:\n odd.append(d)\n else:\n continue\n return odd\n\nodds_in_a = odd_numbers(a)\n\nodds_in_a",
"_____no_output_____"
],
[
"# Exercise 8 - Make a variable named evens_in_a. It should hold only the evens.\n#evens_in_a = a[a % 2 == 0]\ndef even_numbers(numeros):\n even = []\n for n in numeros:\n if n % 2 == 0:\n even.append(n)\n else:\n continue\n return even\n\nevens_in_a = even_numbers(a)\n\nevens_in_a",
"_____no_output_____"
],
[
"## What about life in two dimensions? A list of lists is matrix, a table, \n# a spreadsheet, a chessboard...\n## Setup 2: Consider what it would take to find the sum, min, max, average, sum, \n# product, and list of squares for this list of two lists.\nb = [\n [3, 4, 5],\n [6, 7, 8]\n]",
"_____no_output_____"
],
[
"# Exercise 1 - refactor the following to use numpy. \n#Use sum_of_b as the variable. \n#**Hint, you'll first need to make sure that the \"b\" variable is a numpy array**\n#sum_of_b = 0\n#for row in b:\n# sum_of_b += sum(row)\n\nb = np.array(b)\n\nsum_of_b = b.sum()\n\nsum_of_b",
"_____no_output_____"
],
[
"# Exercise 2 - refactor the following to use numpy. \n#min_of_b = min(b[0]) if min(b[0]) <= min(b[1]) else min(b[1]) \n\nmin_of_b = b.min()\nmin_of_b",
"_____no_output_____"
],
[
"# Exercise 3 - refactor the following maximum calculation to find the answer with numpy.\n#max_of_b = max(b[0]) if max(b[0]) >= max(b[1]) else max(b[1])\n\nmax_of_b = b.max()\nmax_of_b",
"_____no_output_____"
],
[
"# Exercise 4 - refactor the following using numpy to find the mean of b\n#mean_of_b = (sum(b[0]) + sum(b[1])) / (len(b[0]) + len(b[1]))\n\nmean_of_b = b.mean()\nmean_of_b",
"_____no_output_____"
],
[
"# Exercise 5 - refactor the following to use numpy for calculating the product of all numbers multiplied together.\n#product_of_b = 1\n#for row in b:\n# for number in row:\n# product_of_b *= number\n\nproduct_of_b = b.prod()\nproduct_of_b",
"_____no_output_____"
]
],
[
[
"# the above functions are methods that live on the array\n\n## others like below live in the numpy library only",
"_____no_output_____"
]
],
[
[
"# Exercise 6 - refactor the following to use numpy to find the list of squares \n#squares_of_b = []\n#for row in b:\n# for number in row:\n# squares_of_b.append(number**2)\nb = np.array(b)\nsquares_of_b = np.square(b)\n#squares_of_b = b ** 2\nsquares_of_b",
"_____no_output_____"
],
[
"np.power(b, 2)",
"_____no_output_____"
],
[
"# Exercise 7 - refactor using numpy to determine the odds_in_b\n#odds_in_b = []\n#for row in b:\n# for number in row:\n# if(number % 2 != 0):\n# odds_in_b.append(number)\n\nodds_in_b = b[b % 2 != 0]\nodds_in_b",
"_____no_output_____"
],
[
"# Exercise 8 - refactor the following to use numpy to filter only the even numbers\n#evens_in_b = []\n#for row in b:\n# for number in row:\n# if(number % 2 == 0):\n# evens_in_b.append(number)\n\nevens_in_b = b[b % 2 == 0]\nevens_in_b",
"_____no_output_____"
],
[
"# Exercise 9 - print out the shape of the array b.\nnp.shape(b)",
"_____no_output_____"
],
[
"# Exercise 10 - transpose the array b.\nb.transpose()",
"_____no_output_____"
],
[
"b.T",
"_____no_output_____"
],
[
"# Exercise 11 - reshape the array b to be a single list of 6 numbers. (1 x 6)\nb.reshape(1, 6)",
"_____no_output_____"
],
[
"b.reshape(6)",
"_____no_output_____"
],
[
"# Exercise 12 - reshape the array b to be a list of 6 lists, each containing only 1 number (6 x 1)\nb.reshape(6, 1)",
"_____no_output_____"
],
[
"## Setup 3\nc = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]",
"_____no_output_____"
],
[
"# HINT, you'll first need to make sure that the \"c\" variable is a \n# numpy array prior to using numpy array methods.\n# Exercise 1 - Find the min, max, sum, and product of c.\n\nc = np.array(c)\nc.min(), c.max(), c.sum(), c.prod()",
"_____no_output_____"
],
[
"# Exercise 2 - Determine the standard deviation of c.\nc.std()",
"_____no_output_____"
],
[
"# Exercise 3 - Determine the variance of c.\nc.var()",
"_____no_output_____"
],
[
"# Exercise 4 - Print out the shape of the array c\nc.shape",
"_____no_output_____"
],
[
"# Exercise 5 - Transpose c and print out transposed result.\nprint(c.transpose())",
"[[1 4 7]\n [2 5 8]\n [3 6 9]]\n"
],
[
"# Exercise 6 - Get the dot product of the array c with c. \nnp.dot(c, c)",
"_____no_output_____"
],
[
"# Exercise 7 - Write the code necessary to sum up the result \n# of c times c transposed. Answer should be 261\nt_c = c.transpose()\nprod_tc = c * t_c\nprod_tc.sum()",
"_____no_output_____"
],
[
"t_c = c.transpose()\nprod_tc = np.dot(c, t_c)\nprod_tc.sum()",
"_____no_output_____"
],
[
"# Exercise 8 - Write the code necessary to determine the product of c times c transposed. Answer should be 131681894400.\nprod_tc.prod()",
"_____no_output_____"
],
[
"## Setup 4\nd = [\n [90, 30, 45, 0, 120, 180],\n [45, -90, -30, 270, 90, 0],\n [60, 45, -45, 90, -45, 180]\n]",
"_____no_output_____"
],
[
"# Exercise 1 - Find the sine of all the numbers in d\nnp.sin(d)",
"_____no_output_____"
],
[
"# Exercise 2 - Find the cosine of all the numbers in d\nnp.cos(d)",
"_____no_output_____"
],
[
"# Exercise 3 - Find the tangent of all the numbers in d\nnp.tan(d)",
"_____no_output_____"
],
[
"# Exercise 4 - Find all the negative numbers in d\nd = np.array(d)\n\nd[d < 0]",
"_____no_output_____"
],
[
"# Exercise 5 - Find all the positive numbers in d\nd[d > 0]",
"_____no_output_____"
],
[
"# Exercise 6 - Return an array of only the unique numbers in d.\nnp.unique(d)",
"_____no_output_____"
],
[
"# Exercise 7 - Determine how many unique numbers there are in d.\nlen(np.unique(d))",
"_____no_output_____"
],
[
"# Exercise 8 - Print out the shape of d.\nd.shape",
"_____no_output_____"
],
[
"# Exercise 9 - Transpose and then print out the shape of d.\nd.T.shape",
"_____no_output_____"
],
[
"# Exercise 10 - Reshape d into an array of 9 x 2\n\nd.reshape(9, 2)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a365c4f765d359aca6bf63ebe49759069f8f567
| 59,105 |
ipynb
|
Jupyter Notebook
|
notebooks/shallow_net_in_keras.ipynb
|
Spugnam/TensorFlow_Tests
|
8a4ebc738dd6b642a0cffe745d02b22017f2eecc
|
[
"MIT"
] | null | null | null |
notebooks/shallow_net_in_keras.ipynb
|
Spugnam/TensorFlow_Tests
|
8a4ebc738dd6b642a0cffe745d02b22017f2eecc
|
[
"MIT"
] | null | null | null |
notebooks/shallow_net_in_keras.ipynb
|
Spugnam/TensorFlow_Tests
|
8a4ebc738dd6b642a0cffe745d02b22017f2eecc
|
[
"MIT"
] | null | null | null | 50.517094 | 164 | 0.351358 |
[
[
[
"# Shallow Neural Network in Keras",
"_____no_output_____"
],
[
"Build a shallow neural network to classify MNIST digits",
"_____no_output_____"
],
[
"#### Set seed for reproducibility",
"_____no_output_____"
]
],
[
[
"import numpy as np\nnp.random.seed(42)",
"_____no_output_____"
]
],
[
[
"#### Load dependencies",
"_____no_output_____"
]
],
[
[
"import keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import SGD",
"_____no_output_____"
]
],
[
[
"#### Load data",
"_____no_output_____"
]
],
[
[
"(X_train, y_train), (X_test, y_test) = mnist.load_data()",
"Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz\n 8798208/11490434 [=====================>........] - ETA: 0s"
],
[
"X_train.shape",
"_____no_output_____"
],
[
"y_train.shape",
"_____no_output_____"
],
[
"y_train[0:99]",
"_____no_output_____"
],
[
"X_test.shape",
"_____no_output_____"
],
[
"X_test[0]",
"_____no_output_____"
],
[
"y_test.shape",
"_____no_output_____"
],
[
"y_test[0]",
"_____no_output_____"
]
],
[
[
"#### Preprocess data",
"_____no_output_____"
]
],
[
[
"X_train = X_train.reshape(60000, 784).astype('float32')\nX_test = X_test.reshape(10000, 784).astype('float32')",
"_____no_output_____"
],
[
"X_train /= 255\nX_test /= 255",
"_____no_output_____"
],
[
"X_test[0]",
"_____no_output_____"
],
[
"n_classes = 10\ny_train = keras.utils.to_categorical(y_train, n_classes)\ny_test = keras.utils.to_categorical(y_test, n_classes)",
"_____no_output_____"
],
[
"y_test[0]",
"_____no_output_____"
]
],
[
[
"#### Design neural network architecture",
"_____no_output_____"
]
],
[
[
"model = Sequential()\nmodel.add(Dense(64, activation='sigmoid', input_shape=(784,)))\nmodel.add(Dense(10, activation='softmax'))",
"_____no_output_____"
],
[
"model.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_1 (Dense) (None, 64) 50240 \n_________________________________________________________________\ndense_2 (Dense) (None, 10) 650 \n=================================================================\nTotal params: 50,890\nTrainable params: 50,890\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"(64*784)",
"_____no_output_____"
],
[
"(64*784)+64",
"_____no_output_____"
],
[
"(10*64)+10",
"_____no_output_____"
]
],
[
[
"#### Configure model",
"_____no_output_____"
]
],
[
[
"model.compile(loss='mean_squared_error', optimizer=SGD(lr=0.01), metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"#### Train!",
"_____no_output_____"
]
],
[
[
"model.fit(X_train, y_train, batch_size=128, epochs=200, verbose=1, validation_data=(X_test, y_test))",
"Train on 60000 samples, validate on 10000 samples\nEpoch 1/200\n60000/60000 [==============================] - 2s - loss: 0.0915 - acc: 0.0895 - val_loss: 0.0911 - val_acc: 0.0955\nEpoch 2/200\n60000/60000 [==============================] - 2s - loss: 0.0908 - acc: 0.1058 - val_loss: 0.0905 - val_acc: 0.1162\nEpoch 3/200\n60000/60000 [==============================] - 2s - loss: 0.0903 - acc: 0.1406 - val_loss: 0.0901 - val_acc: 0.1513\nEpoch 4/200\n60000/60000 [==============================] - 2s - loss: 0.0899 - acc: 0.1925 - val_loss: 0.0897 - val_acc: 0.2058\nEpoch 5/200\n60000/60000 [==============================] - 2s - loss: 0.0895 - acc: 0.2401 - val_loss: 0.0893 - val_acc: 0.2424\nEpoch 6/200\n60000/60000 [==============================] - 1s - loss: 0.0891 - acc: 0.2706 - val_loss: 0.0889 - val_acc: 0.2715\nEpoch 7/200\n60000/60000 [==============================] - 2s - loss: 0.0888 - acc: 0.2905 - val_loss: 0.0886 - val_acc: 0.2879\nEpoch 8/200\n60000/60000 [==============================] - 1s - loss: 0.0884 - acc: 0.3022 - val_loss: 0.0883 - val_acc: 0.3019\nEpoch 9/200\n60000/60000 [==============================] - 2s - loss: 0.0881 - acc: 0.3102 - val_loss: 0.0879 - val_acc: 0.3093\nEpoch 10/200\n60000/60000 [==============================] - 2s - loss: 0.0877 - acc: 0.3146 - val_loss: 0.0876 - val_acc: 0.3145\nEpoch 11/200\n60000/60000 [==============================] - 1s - loss: 0.0874 - acc: 0.3180 - val_loss: 0.0872 - val_acc: 0.3183\nEpoch 12/200\n60000/60000 [==============================] - 2s - loss: 0.0871 - acc: 0.3209 - val_loss: 0.0869 - val_acc: 0.3204\nEpoch 13/200\n60000/60000 [==============================] - 2s - loss: 0.0867 - acc: 0.3236 - val_loss: 0.0865 - val_acc: 0.3237\nEpoch 14/200\n60000/60000 [==============================] - 2s - loss: 0.0864 - acc: 0.3243 - val_loss: 0.0862 - val_acc: 0.3256\nEpoch 15/200\n60000/60000 [==============================] - 2s - loss: 0.0860 - acc: 0.3264 - val_loss: 0.0858 - val_acc: 0.3274\nEpoch 16/200\n60000/60000 [==============================] - 1s - loss: 0.0857 - acc: 0.3277 - val_loss: 0.0855 - val_acc: 0.3283\nEpoch 17/200\n60000/60000 [==============================] - 1s - loss: 0.0853 - acc: 0.3289 - val_loss: 0.0851 - val_acc: 0.3297\nEpoch 18/200\n60000/60000 [==============================] - 1s - loss: 0.0850 - acc: 0.3303 - val_loss: 0.0847 - val_acc: 0.3312\nEpoch 19/200\n60000/60000 [==============================] - 1s - loss: 0.0846 - acc: 0.3325 - val_loss: 0.0844 - val_acc: 0.3342\nEpoch 20/200\n60000/60000 [==============================] - 1s - loss: 0.0842 - acc: 0.3337 - val_loss: 0.0840 - val_acc: 0.3354\nEpoch 21/200\n60000/60000 [==============================] - 2s - loss: 0.0838 - acc: 0.3353 - val_loss: 0.0836 - val_acc: 0.3385\nEpoch 22/200\n60000/60000 [==============================] - 1s - loss: 0.0835 - acc: 0.3379 - val_loss: 0.0832 - val_acc: 0.3419\nEpoch 23/200\n60000/60000 [==============================] - 1s - loss: 0.0831 - acc: 0.3404 - val_loss: 0.0828 - val_acc: 0.3456\nEpoch 24/200\n60000/60000 [==============================] - 2s - loss: 0.0827 - acc: 0.3436 - val_loss: 0.0824 - val_acc: 0.3507\nEpoch 25/200\n60000/60000 [==============================] - 2s - loss: 0.0822 - acc: 0.3464 - val_loss: 0.0820 - val_acc: 0.3559\nEpoch 26/200\n60000/60000 [==============================] - 2s - loss: 0.0818 - acc: 0.3513 - val_loss: 0.0816 - val_acc: 0.3620\nEpoch 27/200\n60000/60000 [==============================] - 2s - loss: 0.0814 - acc: 0.3556 - val_loss: 0.0811 - val_acc: 0.3668\nEpoch 28/200\n60000/60000 [==============================] - 2s - loss: 0.0810 - acc: 0.3617 - val_loss: 0.0807 - val_acc: 0.3728\nEpoch 29/200\n60000/60000 [==============================] - 1s - loss: 0.0806 - acc: 0.3667 - val_loss: 0.0802 - val_acc: 0.3776\nEpoch 30/200\n60000/60000 [==============================] - 1s - loss: 0.0801 - acc: 0.3728 - val_loss: 0.0798 - val_acc: 0.3839\nEpoch 31/200\n60000/60000 [==============================] - 1s - loss: 0.0797 - acc: 0.3791 - val_loss: 0.0793 - val_acc: 0.3913\nEpoch 32/200\n60000/60000 [==============================] - 1s - loss: 0.0792 - acc: 0.3865 - val_loss: 0.0789 - val_acc: 0.3988\nEpoch 33/200\n60000/60000 [==============================] - 1s - loss: 0.0788 - acc: 0.3932 - val_loss: 0.0784 - val_acc: 0.4060\nEpoch 34/200\n60000/60000 [==============================] - 1s - loss: 0.0783 - acc: 0.3997 - val_loss: 0.0780 - val_acc: 0.4151\nEpoch 35/200\n60000/60000 [==============================] - 1s - loss: 0.0779 - acc: 0.4092 - val_loss: 0.0775 - val_acc: 0.4234\nEpoch 36/200\n60000/60000 [==============================] - 1s - loss: 0.0774 - acc: 0.4169 - val_loss: 0.0770 - val_acc: 0.4321\nEpoch 37/200\n60000/60000 [==============================] - 2s - loss: 0.0769 - acc: 0.4251 - val_loss: 0.0766 - val_acc: 0.4394\nEpoch 38/200\n60000/60000 [==============================] - 3s - loss: 0.0765 - acc: 0.4355 - val_loss: 0.0761 - val_acc: 0.4468\nEpoch 39/200\n60000/60000 [==============================] - 3s - loss: 0.0760 - acc: 0.4432 - val_loss: 0.0756 - val_acc: 0.4560\nEpoch 40/200\n60000/60000 [==============================] - 3s - loss: 0.0755 - acc: 0.4520 - val_loss: 0.0751 - val_acc: 0.4666\nEpoch 41/200\n60000/60000 [==============================] - 2s - loss: 0.0751 - acc: 0.4625 - val_loss: 0.0746 - val_acc: 0.4746\nEpoch 42/200\n60000/60000 [==============================] - 2s - loss: 0.0746 - acc: 0.4719 - val_loss: 0.0742 - val_acc: 0.4853\nEpoch 43/200\n60000/60000 [==============================] - 2s - loss: 0.0741 - acc: 0.4803 - val_loss: 0.0737 - val_acc: 0.4950\nEpoch 44/200\n60000/60000 [==============================] - 2s - loss: 0.0736 - acc: 0.4904 - val_loss: 0.0732 - val_acc: 0.5032\nEpoch 45/200\n60000/60000 [==============================] - 2s - loss: 0.0732 - acc: 0.4991 - val_loss: 0.0727 - val_acc: 0.5118\nEpoch 46/200\n60000/60000 [==============================] - 2s - loss: 0.0727 - acc: 0.5086 - val_loss: 0.0722 - val_acc: 0.5213\nEpoch 47/200\n60000/60000 [==============================] - 2s - loss: 0.0722 - acc: 0.5156 - val_loss: 0.0718 - val_acc: 0.5285\nEpoch 48/200\n60000/60000 [==============================] - 2s - loss: 0.0717 - acc: 0.5253 - val_loss: 0.0713 - val_acc: 0.5354\nEpoch 49/200\n60000/60000 [==============================] - 3s - loss: 0.0713 - acc: 0.5326 - val_loss: 0.0708 - val_acc: 0.5427\nEpoch 50/200\n60000/60000 [==============================] - 2s - loss: 0.0708 - acc: 0.5398 - val_loss: 0.0703 - val_acc: 0.5498\nEpoch 51/200\n60000/60000 [==============================] - 2s - loss: 0.0703 - acc: 0.5478 - val_loss: 0.0698 - val_acc: 0.5554\nEpoch 52/200\n60000/60000 [==============================] - 2s - loss: 0.0698 - acc: 0.5539 - val_loss: 0.0693 - val_acc: 0.5619\nEpoch 53/200\n60000/60000 [==============================] - 2s - loss: 0.0694 - acc: 0.5607 - val_loss: 0.0689 - val_acc: 0.5678\nEpoch 54/200\n60000/60000 [==============================] - 2s - loss: 0.0689 - acc: 0.5666 - val_loss: 0.0684 - val_acc: 0.5741\nEpoch 55/200\n60000/60000 [==============================] - 2s - loss: 0.0684 - acc: 0.5725 - val_loss: 0.0679 - val_acc: 0.5785\nEpoch 56/200\n60000/60000 [==============================] - 2s - loss: 0.0680 - acc: 0.5782 - val_loss: 0.0674 - val_acc: 0.5835\nEpoch 57/200\n60000/60000 [==============================] - 2s - loss: 0.0675 - acc: 0.5831 - val_loss: 0.0670 - val_acc: 0.5894\nEpoch 58/200\n60000/60000 [==============================] - 2s - loss: 0.0670 - acc: 0.5872 - val_loss: 0.0665 - val_acc: 0.5941\nEpoch 59/200\n60000/60000 [==============================] - 2s - loss: 0.0666 - acc: 0.5921 - val_loss: 0.0660 - val_acc: 0.5985\nEpoch 60/200\n60000/60000 [==============================] - 2s - loss: 0.0661 - acc: 0.5962 - val_loss: 0.0655 - val_acc: 0.6028\nEpoch 61/200\n60000/60000 [==============================] - 2s - loss: 0.0656 - acc: 0.6003 - val_loss: 0.0651 - val_acc: 0.6068\nEpoch 62/200\n60000/60000 [==============================] - 2s - loss: 0.0652 - acc: 0.6041 - val_loss: 0.0646 - val_acc: 0.6102\nEpoch 63/200\n60000/60000 [==============================] - 2s - loss: 0.0647 - acc: 0.6080 - val_loss: 0.0641 - val_acc: 0.6136\nEpoch 64/200\n"
],
[
"model.evaluate(X_test, y_test)",
" 9280/10000 [==========================>...] - ETA: 0s"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a3675bf15a33715e96b43a0682ea507669c6da7
| 6,115 |
ipynb
|
Jupyter Notebook
|
python/.ipynb_checkpoints/Python02_Into_Notebooks-checkpoint.ipynb
|
Ainiall/quantum
|
6e9be4654b0803cafdc1160c795fe20c568510cc
|
[
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null |
python/.ipynb_checkpoints/Python02_Into_Notebooks-checkpoint.ipynb
|
Ainiall/quantum
|
6e9be4654b0803cafdc1160c795fe20c568510cc
|
[
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null |
python/.ipynb_checkpoints/Python02_Into_Notebooks-checkpoint.ipynb
|
Ainiall/quantum
|
6e9be4654b0803cafdc1160c795fe20c568510cc
|
[
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | 28.179724 | 185 | 0.550777 |
[
[
[
"<a href=\"https://qworld.net\" target=\"_blank\" align=\"left\"><img src=\"../qworld/images/header.jpg\" align=\"left\"></a>\n_prepared by Abuzer Yakaryilmaz_",
"_____no_output_____"
]
],
[
[
"# A jupyter notebook is composed by one or more cells.\n# This notebook is prepared for jupyter notebooks, and the menu items and command buttons may differ in jupyter lab.\n# There are two main cells: Code and Markdown.\n# A code cell is used to write and execute your codes.\n# A markdown cell is used to write text descriptions, notes, formulas or include graphics and images.\n# On a markdown cell, you can format your content by using Markdown, HTML, or LaTeX code.\n# During our tutorial, you are expected to write only python codes.\n# Interested readers may also use markdown cells, but it is not necesary to complete our tutorial. \n\n#\n# We explain basic usage of cells in Jupyter notebooks here\n#\n\n# This is the first cell in this notebook.\n# You can write Python code here, \n# and then EXECUTE/RUN it by\n# 1) pressing CTRL+ENTER or SHIFT+ENTER\n# 2) clicking \"Run\" on the menu\n\n\n# here are few lines of python code\n\nprint(\"hello world\")\nstr=\"*\"\nfor i in range(10):\n print(str)\n str+=\"*\"\n\n# after executing this cell, the outcomes will immedeately appear after this cell\n# you can change the range above and re-run this cell",
"_____no_output_____"
],
[
"# This is the second cell in this notebook. \n#\n# By using menu item \"Insert\", you can add a new cell before or after the active cell.\n# When a cell is selected, you may delete it by using menu item \"Edit\".\n#\n# As you may notice, there are other editing options under \"Edit\",\n# for example, copy/cut-paste cells and split-merge cells.\n#",
"_____no_output_____"
]
],
[
[
"<b>This is the third cell.</b>\n\nThis is a markdown type cell.\n\nThe type of any cell is shown on the toolbar under the menu bar (right-side). You can change the type of a cell from this pulldown menu\n\nYou can write Markdown, HTML, and LaTex code on this cell.\n\n<i>By double clicking on this cell, you can see the code of this cell.</i> <br>\n<u>By execucting this cell, you see the result content.</u>",
"_____no_output_____"
],
[
"<b> This is the fourth cell.</b>\n\nThis is also a markdown cell.\n\nLaTex is used to show mathematical expressions, formulas, etc. \n\nFor example, $ x^2 + y ^ 2 = \\frac{4}{9} $, $ \\sum_{i=1}^n (i+2)^{3} $, or $ \\left( \\begin{array}{rr} 1 & 0 & -1 \\\\ 2 & -2 & 0 \\\\ 3 & -1 & -2 \\end{array} \\right) $.\n\n<i>By double clicking on this cell, you can see the code.</i> <br> \n<u>By executing/running this cell, you can see the result content.</u>",
"_____no_output_____"
],
[
"<h2> Tips </h2>",
"_____no_output_____"
],
[
"Showing line numbers: View $\\rightarrow$ Toggle Line Numbers\n\nCommand mode: CTRL+SHIFT+P",
"_____no_output_____"
],
[
"<h2>Magic Commands</h2>\n\nHere we list a few built-in magic commands for Jupyter notebooks that we will use during this tutorial. \n\nThese commands can be executed in code-type cells.",
"_____no_output_____"
],
[
"<b><u>Write the content of a code cell</u></b> into an external file:\n \n %%writefile FILENAME.py\nThis command should be placed in the first line of cell, and then the cell should be executed.\n\n<i> Example:</i>",
"_____no_output_____"
]
],
[
[
"%%writefile first.py \n\nprint(\"hello world\")\n\nstr=\"*\"\nfor i in range(5):\n print(str)\n str+=\"*\" ",
"_____no_output_____"
]
],
[
[
"<b><u>Execute an external script</u></b> without loading its content into the cell:\n \n %run FILENAME.py\n<i>Example:</i> ",
"_____no_output_____"
]
],
[
[
"%run first.py\n",
"_____no_output_____"
]
],
[
[
"<b><u>Load an external script</u></b> into a cell:\n\n %load FILENAME.py\nOnce this command is executed, the content of cell is replaced with the content of file. (The previous content is deleted.)\n\nBesides, this command is placed to the first line, and then commented out.\n\n<i>Example:</i>",
"_____no_output_____"
]
],
[
[
"%load first.py\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a367a19c2a223183ca62f84ebdd065bf2f215ef
| 446,824 |
ipynb
|
Jupyter Notebook
|
main/nbs/eda/manifoldAnalysis/output_space/visualization.ipynb
|
jason424217/Artificial-Code-Gen
|
a6e2c097c5ffe8cb0929e6703035b526f477e514
|
[
"MIT"
] | null | null | null |
main/nbs/eda/manifoldAnalysis/output_space/visualization.ipynb
|
jason424217/Artificial-Code-Gen
|
a6e2c097c5ffe8cb0929e6703035b526f477e514
|
[
"MIT"
] | null | null | null |
main/nbs/eda/manifoldAnalysis/output_space/visualization.ipynb
|
jason424217/Artificial-Code-Gen
|
a6e2c097c5ffe8cb0929e6703035b526f477e514
|
[
"MIT"
] | null | null | null | 620.588889 | 281,696 | 0.943092 |
[
[
[
"# Easily export jupyter cells to python module\nhttps://github.com/fastai/course-v3/blob/master/nbs/dl2/notebook2script.py",
"_____no_output_____"
]
],
[
[
"! python /tf/src/scripts/notebook2script.py visualization.ipynb",
"_____no_output_____"
],
[
"%matplotlib inline",
"_____no_output_____"
],
[
"! pip install -U scikit-learn",
"_____no_output_____"
],
[
"#export\nfrom exp.nb_clustering import *\nfrom exp.nb_evaluation import *\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport matplotlib.cm as cmx\nimport matplotlib.patches as patches\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.colors import LogNorm",
"_____no_output_____"
],
[
"cd /tf/src/data/features",
"/tf/src/data/features\n"
]
],
[
[
"# Generate all the feature vectors\n(Skip if already done)\n",
"_____no_output_____"
]
],
[
[
"embdr = D2VEmbedder(\"/tf/src/data/doc2vec/model\")",
"_____no_output_____"
],
[
"# Generate and Save Human Features\nhman_dict = embdr(\"/tf/src/data/methods/DATA00M_[god-r]/test\")\n\nwith open('hman_features.pickle', 'wb') as f:\n pickle.dump(hman_dict, f, protocol=pickle.HIGHEST_PROTOCOL)",
"_____no_output_____"
],
[
"# Generate and Save GPT-2 Pretrained Features\nm1_dict = embdr(\"/tf/src/data/samples/unconditional/m1_example\")\n\nwith open('m1_features.pickle', 'wb') as f:\n pickle.dump(m1_dict, f, protocol=pickle.HIGHEST_PROTOCOL)",
"_____no_output_____"
]
],
[
[
"# Read in Feature Vectors",
"_____no_output_____"
]
],
[
[
"models_path = \"/tf/src/data/features/output_space\"\nmodels_features = load_features(models_path)",
"_____no_output_____"
],
[
"len(models_features[0]), len(models_features[1])",
"_____no_output_____"
]
],
[
[
"# Visualize Features",
"_____no_output_____"
]
],
[
[
"dims = 2\nmodels_clusters = cluster(models_features, k_range = [2, 3, 4, 5], dims = 2)",
"[t-SNE] Computing 99 nearest neighbors...\n[t-SNE] Indexed 100 samples in 0.000s...\n[t-SNE] Computed neighbors for 100 samples in 0.001s...\n[t-SNE] Computed conditional probabilities for sample 100 / 100\n[t-SNE] Mean sigma: 3.040752\n[t-SNE] KL divergence after 250 iterations with early exaggeration: 69.940933\n[t-SNE] KL divergence after 300 iterations: 0.934385\nBest K was 3 with a silhouette score of 0.3131982\n[t-SNE] Computing 99 nearest neighbors...\n[t-SNE] Indexed 100 samples in 0.000s...\n[t-SNE] Computed neighbors for 100 samples in 0.001s...\n[t-SNE] Computed conditional probabilities for sample 100 / 100\n[t-SNE] Mean sigma: 5.540578\n[t-SNE] KL divergence after 250 iterations with early exaggeration: 73.307167\n[t-SNE] KL divergence after 300 iterations: 0.967118\nBest K was 3 with a silhouette score of 0.31246203\n"
],
[
"def setup_data(model):\n feature_vectors, _, _, centroids, kmeans = model\n # Step size of the mesh. Decrease to increase the quality of the VQ.\n h = .02 # point in the mesh [x_min, x_max]x[y_min, y_max].\n\n # Plot the decision boundary. For that, we will assign a color to each\n x_min, x_max = feature_vectors[:, 0].min() - 1, feature_vectors[:, 0].max() + 1\n y_min, y_max = feature_vectors[:, 1].min() - 1, feature_vectors[:, 1].max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n \n Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n \n return feature_vectors, centroids, xx, yy, Z",
"_____no_output_____"
],
[
"def plot_features(models_clusters, export = True):\n plt.figure(figsize=(12, 8))\n # Create 2x2 sub plots\n gs = gridspec.GridSpec(2, 2)\n plt.clf()\n for i, model in enumerate(models_clusters):\n # Setup data to be plotted\n feature_vectors, centroids, xx, yy, Z = setup_data(model)\n \n # Plot data\n plt.subplot(gs[0, i])\n plt.imshow(Z, interpolation='nearest',\n extent=(xx.min(), xx.max(), yy.min(), yy.max()),\n cmap=plt.cm.Paired,\n aspect='auto', origin='lower')\n\n plt.plot(feature_vectors[:, 0], feature_vectors[:, 1], 'k.', markersize=2)\n # Plot the centroids as a white X\n plt.scatter(centroids[:, 0], centroids[:, 1],\n marker='x', s=169, linewidths=3,\n color='w', zorder=10)\n plt.title('K-means clustering\\n'\n '(PCA & T-SNE - reduced data)\\n'\n 'Centroids are marked with white cross')\n plt.xlim(xx.min(), xx.max())\n plt.ylim(yy.min(), yy.max())\n \n plt.subplot(gs[1, :])\n colmap = {0: 'b.', 1: 'r.'}\n plt.title('Blue denotes Human Methods and Red denotes GPT-2 Unconditional Samples')\n for i, model in enumerate(models_clusters):\n feature_vectors, _, _, _ = model\n plt.plot(feature_vectors[:, 0], feature_vectors[:, 1], colmap[i], markersize=10)\n \n if export:\n if not os.path.exists('images/'): os.mkdir('images/')\n plt.savefig('images/feature_vectors_scatter_plot.png', dpi=100, format='png')\n plt.show()",
"_____no_output_____"
],
[
"plot_features(models_clusters)",
"_____no_output_____"
]
],
[
[
"# Gaussian Mixture Visualization",
"_____no_output_____"
],
[
"## Visualize 1D",
"_____no_output_____"
]
],
[
[
"dims = 1\nmodels_clusters = cluster(models_features, k_range = [2, 3, 4, 5], dims = dims)",
"[t-SNE] Computing 99 nearest neighbors...\n[t-SNE] Indexed 100 samples in 0.001s...\n[t-SNE] Computed neighbors for 100 samples in 0.001s...\n[t-SNE] Computed conditional probabilities for sample 100 / 100\n[t-SNE] Mean sigma: 3.040752\n[t-SNE] KL divergence after 250 iterations with early exaggeration: 73.936195\n[t-SNE] KL divergence after 300 iterations: 0.757610\nBest K was 3 with a silhouette score of 0.6141684\n[t-SNE] Computing 99 nearest neighbors...\n[t-SNE] Indexed 100 samples in 0.000s...\n[t-SNE] Computed neighbors for 100 samples in 0.001s...\n[t-SNE] Computed conditional probabilities for sample 100 / 100\n[t-SNE] Mean sigma: 5.540578\n[t-SNE] KL divergence after 250 iterations with early exaggeration: 77.741875\n[t-SNE] KL divergence after 300 iterations: 0.672689\nBest K was 2 with a silhouette score of 0.87282944\n"
],
[
"def plot_gmm_1d(models_clusters, export = True):\n plt.figure(figsize=(12, 8))\n # Create 2x2 sub plots\n gs = gridspec.GridSpec(1, 2)\n plt.clf()\n for i, model in enumerate(models_clusters):\n feature_vectors, _, _, kmeans = model\n gmm = generate_distributions(feature_vectors, kmeans.n_clusters - 1)\n x_min, x_max = feature_vectors[:, 0].min(), feature_vectors[:, 0].max()\n \n # Plot Data\n plt.subplot(gs[0, i])\n \n delta = 10\n x = np.linspace(x_min - delta, x_max + delta, 1000).reshape(1000,1)\n logprob = gmm.score_samples(x)\n pdf = np.exp(logprob)\n plt.plot(x, pdf, '-k')\n \n if export:\n if not os.path.exists('images/'): os.mkdir('images/')\n plt.savefig('images/1D_GMM_demonstration.png', dpi=100, format='png')\n \n plt.show()",
"_____no_output_____"
],
[
"plot_gmm_1d(models_clusters)",
"_____no_output_____"
]
],
[
[
"## Visualize 2D",
"_____no_output_____"
]
],
[
[
"dims = 2\nmodels_clusters = cluster(models_features, k_range = [2, 3, 4, 5], dims = dims)",
"[t-SNE] Computing 99 nearest neighbors...\n[t-SNE] Indexed 100 samples in 0.000s...\n[t-SNE] Computed neighbors for 100 samples in 0.001s...\n[t-SNE] Computed conditional probabilities for sample 100 / 100\n[t-SNE] Mean sigma: 3.040752\n[t-SNE] KL divergence after 250 iterations with early exaggeration: 80.587074\n[t-SNE] KL divergence after 300 iterations: 1.083076\nBest K was 3 with a silhouette score of 0.3245396\n[t-SNE] Computing 99 nearest neighbors...\n[t-SNE] Indexed 100 samples in 0.000s...\n[t-SNE] Computed neighbors for 100 samples in 0.001s...\n[t-SNE] Computed conditional probabilities for sample 100 / 100\n[t-SNE] Mean sigma: 5.540578\n[t-SNE] KL divergence after 250 iterations with early exaggeration: 69.750435\n[t-SNE] KL divergence after 300 iterations: 1.019413\nBest K was 5 with a silhouette score of 0.326521\n"
],
[
"# From http://www.itzikbs.com/gaussian-mixture-model-gmm-3d-point-cloud-classification-primer\ndef visualize_2D_gmm(points, w, mu, stdev, id, export=True):\n '''\n plots points and their corresponding gmm model in 2D\n Input: \n points: N X 2, sampled points\n w: n_gaussians, gmm weights\n mu: 2 X n_gaussians, gmm means\n stdev: 2 X n_gaussians, gmm standard deviation (assuming diagonal covariance matrix)\n Output:\n None\n '''\n n_gaussians = mu.shape[1]\n N = int(np.round(points.shape[0] / n_gaussians))\n # Visualize data\n# fig = plt.figure(figsize=(8, 8))\n axes = plt.gca()\n plt.set_cmap('Set1')\n colors = cmx.Set1(np.linspace(0, 1, n_gaussians))\n for i in range(n_gaussians):\n idx = range(i * N, (i + 1) * N)\n plt.scatter(points[idx, 0], points[idx, 1], alpha=0.3, c=colors[i])\n for j in range(8):\n axes.add_patch(\n patches.Ellipse(mu[:, i], width=(j+1) * stdev[0, i], height=(j+1) * stdev[1, i], fill=False, color=colors[i]))\n plt.title('GMM ' + str(id))\n plt.xlabel('X')\n plt.ylabel('Y')",
"_____no_output_____"
],
[
"def plot_gmm_2d(models_clusters, export = True):\n plt.figure(figsize=(12, 8))\n # Create 2x2 sub plots\n gs = gridspec.GridSpec(1, 2)\n plt.clf()\n for i, model in enumerate(models_clusters):\n feature_vectors, _, _, kmeans = model\n gmm = generate_distributions(feature_vectors, kmeans.n_clusters - 1)\n \n # Plot Data\n plt.subplot(gs[0, i])\n visualize_2D_gmm(feature_vectors, gmm.weights_, gmm.means_.T, np.sqrt(gmm.covariances_).T, i)\n \n if export:\n if not os.path.exists('images/'): os.mkdir('images/')\n plt.savefig('images/2D_GMM_demonstration.png', dpi=100, format='png')\n plt.show()",
"_____no_output_____"
],
[
"plot_gmm_2d(models_clusters)",
"'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.\n'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.\n'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.\n'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.\n'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.\n'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.\n"
]
],
[
[
"## Visualize 3D",
"_____no_output_____"
]
],
[
[
"dims = 3\nmodels_clusters = cluster(models_features, k_range = [2, 3, 4, 5], dims = dims)",
"[t-SNE] Computing 99 nearest neighbors...\n[t-SNE] Indexed 100 samples in 0.000s...\n[t-SNE] Computed neighbors for 100 samples in 0.002s...\n[t-SNE] Computed conditional probabilities for sample 100 / 100\n[t-SNE] Mean sigma: 3.040752\n[t-SNE] KL divergence after 250 iterations with early exaggeration: 160.454865\n[t-SNE] KL divergence after 300 iterations: 3.340936\nBest K was 2 with a silhouette score of 0.6622582\n[t-SNE] Computing 99 nearest neighbors...\n[t-SNE] Indexed 100 samples in 0.000s...\n[t-SNE] Computed neighbors for 100 samples in 0.001s...\n[t-SNE] Computed conditional probabilities for sample 100 / 100\n[t-SNE] Mean sigma: 5.540578\n[t-SNE] KL divergence after 250 iterations with early exaggeration: 137.538498\n[t-SNE] KL divergence after 300 iterations: 2.466228\nBest K was 2 with a silhouette score of 0.7663881\n"
],
[
"# From http://www.itzikbs.com/gaussian-mixture-model-gmm-3d-point-cloud-classification-primer\ndef plot_sphere(w=0, c=[0,0,0], r=[1, 1, 1], subdev=10, ax=None, sigma_multiplier=3):\n '''\n plot a sphere surface\n Input: \n c: 3 elements list, sphere center\n r: 3 element list, sphere original scale in each axis ( allowing to draw elipsoids)\n subdiv: scalar, number of subdivisions (subdivision^2 points sampled on the surface)\n ax: optional pyplot axis object to plot the sphere in.\n sigma_multiplier: sphere additional scale (choosing an std value when plotting gaussians)\n Output:\n ax: pyplot axis object\n '''\n\n if ax is None:\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n pi = np.pi\n cos = np.cos\n sin = np.sin\n phi, theta = np.mgrid[0.0:pi:complex(0,subdev), 0.0:2.0 * pi:complex(0,subdev)]\n x = sigma_multiplier*r[0] * sin(phi) * cos(theta) + c[0]\n y = sigma_multiplier*r[1] * sin(phi) * sin(theta) + c[1]\n z = sigma_multiplier*r[2] * cos(phi) + c[2]\n cmap = cmx.ScalarMappable()\n cmap.set_cmap('jet')\n c = cmap.to_rgba(w)\n\n ax.plot_surface(x, y, z, color=c, alpha=0.2, linewidth=1)\n\n return ax",
"_____no_output_____"
],
[
"# From http://www.itzikbs.com/gaussian-mixture-model-gmm-3d-point-cloud-classification-primer\ndef visualize_3d_gmm(points, w, mu, stdev, id, axes, export=True):\n '''\n plots points and their corresponding gmm model in 3D\n Input: \n points: N X 3, sampled points\n w: n_gaussians, gmm weights\n mu: 3 X n_gaussians, gmm means\n stdev: 3 X n_gaussians, gmm standard deviation (assuming diagonal covariance matrix)\n Output:\n None\n '''\n\n n_gaussians = mu.shape[1]\n N = int(np.round(points.shape[0] / n_gaussians))\n # Visualize data\n plt.set_cmap('Set1')\n colors = cmx.Set1(np.linspace(0, 1, n_gaussians))\n for i in range(n_gaussians):\n idx = range(i * N, (i + 1) * N)\n axes.scatter(points[idx, 0], points[idx, 1], points[idx, 2], alpha=0.3, c=colors[i])\n plot_sphere(w=w[i], c=mu[:, i], r=stdev[:, i], ax=axes)\n\n plt.title('3D GMM')\n axes.set_xlabel('X')\n axes.set_ylabel('Y')\n axes.set_zlabel('Z')\n axes.view_init(35.246, 45)",
"_____no_output_____"
],
[
"def plot_gmm_3d(models_clusters, export = True):\n # set up a figure twice as wide as it is tall\n fig = plt.figure(figsize=plt.figaspect(0.5))\n \n for i, model in enumerate(models_clusters):\n feature_vectors, _, _, kmeans = model\n gmm = generate_distributions(feature_vectors, kmeans.n_clusters - 1)\n \n # Plot Data\n axes = fig.add_subplot(121 + i, projection='3d')\n visualize_3d_gmm(feature_vectors, gmm.weights_, gmm.means_.T, np.sqrt(gmm.covariances_).T, i, axes)\n \n if export:\n if not os.path.exists('images/'): os.mkdir('images/')\n plt.savefig('images/3D_GMM_demonstration.png', dpi=100, format='png')\n plt.show()",
"_____no_output_____"
],
[
"plot_gmm_3d(models_clusters)",
"'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.\n'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.\n"
]
]
] |
[
"markdown",
"code",
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4a367bfc30b24d9543d316dad0494b2838695c20
| 88,627 |
ipynb
|
Jupyter Notebook
|
notebooks/NER- Annotation.ipynb
|
amrendra1002/ML-DL
|
66f0eb843ccfd4bca5fc4e4cd6ee95d1a078f708
|
[
"FTL"
] | 1 |
2021-01-31T08:41:58.000Z
|
2021-01-31T08:41:58.000Z
|
notebooks/NER- Annotation.ipynb
|
amrendra1002/ML-DL
|
66f0eb843ccfd4bca5fc4e4cd6ee95d1a078f708
|
[
"FTL"
] | null | null | null |
notebooks/NER- Annotation.ipynb
|
amrendra1002/ML-DL
|
66f0eb843ccfd4bca5fc4e4cd6ee95d1a078f708
|
[
"FTL"
] | null | null | null | 137.833593 | 41,097 | 0.73569 |
[
[
[
"import pandas as pd\nimport numpy as np\nimport re\nfrom itertools import accumulate",
"_____no_output_____"
],
[
"emails = pd.read_csv(r'C:\\Users\\amrenkumar\\Desktop\\TestData\\full-output.csv')",
"_____no_output_____"
],
[
"emails.shape",
"_____no_output_____"
],
[
"emails_clean = emails[~emails.interaction_content.isnull()]",
"_____no_output_____"
],
[
"emails_clean = emails_clean.interaction_content",
"_____no_output_____"
],
[
"emails_clean.drop_duplicates(keep='first', inplace=True)",
"C:\\Anaconda\\lib\\site-packages\\pandas\\core\\base.py:1241: 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 return self._update_inplace(result)\n"
],
[
"emails_clean.head()",
"_____no_output_____"
],
[
"email_clean= emails_clean.str.replace(\"[^a-zA-Z0-9. ]\", \"\")\n#email_clean= emails_clean.interaction_content.str",
"_____no_output_____"
],
[
"for i in email_clean[0:2]:\n print(i)",
"Trading ideas and investment strategies discussed herein may give rise to significant risk and are not suitable for all investors. Investors should have experience in FX markets and the financial resources to absorb any losses arising from applying these ideas or strategies. BofA Merrill Lynch does and seeks to do business with companies covered in its research reports. As a result investors should be aware that the firm may have a conflict of interest that could affect the objectivity of this report. Investors should consider this report as only a single factor in making their investment decision. Refer to important disclosures on page 8 to 10. Analyst Certification on Page 7. 11463056 Liquid Technical Edge Bearish despite basing Treasury yields amp ESZ4 Rates and FX Global 15 December 2014 MacNeil Curry CFA CMT 1 646 855 6781 Technical Strategist MLPFamp S macneil.currybaml.com strength should be faded as tries to base We are bearish . Elliott wave analysis says that nterm strength must be seen as corrective and temporary despite the potential for US equities and Treasury yields to resume their larger uptrends. Into 120.17119.65 we would look for a top and resumption lower for 115.63114.98 measured move and potentially below before greater signs of basing emerge. In contrast is trying to carve out a more sustainable base and turn higher from 1.56005 area support. A close above 1.57551.5791 confirms exposing the 200d at 1.6013 potentially 1.6172. US Treasury yields are set to turn higher as ESZ4 show signs of basing. We have been of the view that the recent weakness in both Treasury yields and ESZ4 has been corrective and temporary. With equity markets now showing signs of capitulation Friday saw the VXV VIX ratio close below 1 as both ESZ4 and 10s reaching proposed basing levels of 1190.501970.25 50d and 38.2 of Oct Dec rally and 2.0672.040 61.8 amp 23 rd of Oct Nov rise respectively we look expect a resumption of their larger uptrends. Through 2025.25 in ESZ4 says the uptrend has resumed for multiyear channel resistance at 2085.50 with a break of 2061 confirming a resumption of the bull trend. 10yr yields need a break of 2.150 to say the uptrend is resuming for the Nov highs at 2.404 and beyond with a break of 2.227 confirming a resumption of the bear trend. While we are bearish 10s 5yr yields should continue to lead the way. While they are caught in a near term consolidation Triangle between 1.7301.453 we look for a bearish breakout towards the 15m highs of 1.8651.879 Bearish Copper We are bearish and short Copper. The break of pivotal long term support at 66356602 says the long term downtrend has resumed for 59775893 Triangle objective and YTD channel support. The corrective bounce of the past several weeks is in the process of completing and should not exceed the 6565 area before the larger downtrend resumes. For the rest of 2015 Liquid Technical Edge will be on an ad hoc basis. Regular publication will resume Jan 05 2015 Outstanding Trades FX Short at 0.7935 risking 0.8050 target 0.7582 and potentially below FI No Trades CO Short LME Copper 90d Fwd at 6446 risk 6575 target 5969 potentially below Unauthorized redistribution of this report is prohibited. This report is intended for greg. kimbaml.com. Liquid Technical Edge 15 December 2014 2 Chart 1 USDJPY Chart 2 GBPUSD Liquid Technical Edge 15 December 2014 3 Chart 3 SampP500 E mini future Chart 4 SampP500 and VXV VIX ratio Liquid Technical Edge 15 December 2014 4 Chart 5 US 10yr Treasury yields Chart 6 US 5yr Treasury yields Liquid Technical Edge 15 December 2014 5 Chart 7 LME 90d Copper Table 1 Trade recommendation history rolling 12 month history Date trade entered Buy Sell Market Entry Level or premium bp Date trade closed Exit Level or premium Return TYPE 1162014 Buy US 5s30s 143.7000 11262014 138.8000 3.41 FI 10312014 Buy GBPZAR 17.6275 11172014 17.3065 1.82 FX 1132014 Sell CLF5 80.7000 11102014 79.4500 1.55 CO 10302014 Buy USDKRW 1054.0000 1152014 1089.4000 3.36 FX 10232014 Sell NZDUSD 0.7870 10282014 0.7944 0.94 FX 10212014 Sell AUDUSD 0.8818 10292014 0.8905 0.99 FX 7292014 Buy US 2s3s 44.30 1082014 45.85 3.50 FI 9232014 Buy USDMXN 13.2850 1082014 13.3550 0.53 FX 9232014 Sell GBPUSD 1.6376 1082014 1.6095 1.72 FX 9162014 Sell EURUSD 1.29500 9162014 1.299 0.31 FX 982014 Buy USDTRY 2.16720 9112014 2.191 1.10 FX 782014 Sell EURUSD 1.35950 942014 1.3104 3.61 FX 6202014 Buy NOKSEK 1.09060 932014 1.1275 3.38 FX 922014 Buy TYZ4 125.32813 932014 124.9375 0.31 FI 8142014 Buy AUDNZD 1.09450 8242014 1.1147 1.85 FX 8142014 Sell EURUSD 1.33950 8222014 1.3233 1.21 FX 862014 Sell WNU4 152.53125 872014 153.21875 0.45 FI 852014 Sell AUDUSD 0.9308 862014 0.935 0.45 FX 792014 Sell US 5s30s 166.3 7312014 158.3 4.81 FI 6302014 Buy USDCLP 552.1000 7302014 572.09 3.62 FX 722014 Sell USDJPY 101.9650 7302014 102.85 0.87 FX 7112014 Buy USDCNH 6.2041 7232014 6.1925 0.19 FX 6242014 Buy USDZAR 10.5797 7232014 10.5295 0.47 FX 6252014 Sell TYU4 124.984375 792014 124.984375 0.00 FI 6242014 Buy USDCNH 6.2275 712014 6.2045 0.37 FX Liquid Technical Edge 15 December 2014 6 Table 1 Trade recommendation history rolling 12 month history Date trade entered Buy Sell Market Entry Level or premium bp Date trade closed Exit Level or premium Return TYPE 6112014 Sell LME Copper 6675 6232014 6840 2.47 CO 6102014 Buy USDCHF 0.8992 6192014 0.8923 0.77 FX 5302014 Buy USDZAR 10.5635 6192014 10.6566 0.88 FX 5302014 Sell US 5s30s 183.0 6192014 174.6 4.59 FI 662014 Sell TYU4 124.78125 6192014 124.65625 0.10 FI 5302014 Buy CLZ4CLZ5 7.18 6182014 8.25 14.90 CO 5122014 Sell Spot Gold 1300 6122014 1270 2.31 CO 5162014 Sell IKM4 124.67 662014 125.84 0.94 FI 5192014 Sell EURUSD 1.3735 652014 1.3625 0.80 FX 4292014 Sell EURNOK 8.2956 652014 8.1675 1.54 FX 492014 Buy USDCHF 0.8796 652014 0.894 1.64 FX 472014 Buy USDCHF 0.8836 652014 0.894 1.18 FX 4252014 Sell EURAUD 1.4915 5192014 1.475 1.11 FX 512014 Sell Spot Silver 19.2000 5142014 19.95 3.91 CO 4222014 Buy GBPUSD 1.6844 592014 1.6909 0.39 FX 4252014 Buy AUDNZD 1.0805 522014 1.072 0.79 FX 4152014 Sell US 5s30s 185.3 4302014 178.8 3.51 FI 4152014 Sell Spot Gold 1300.8300 4242014 1295 0.45 CO 3242014 Sell GBPAUD 1.8075 4162014 1.7960 0.64 FX 3312014 Sell FVM4 118.7969 492014 119.3125 0.43 FI 422014 Sell COM4 104.4900 432014 106.15 1.59 CO 2192014 Buy USDCAD 1.1020 2262014 1.1115 0.86 FX 2262014 Buy USDMXN 13.2931 362014 13.175 0.89 FX 332014 Sell Spot Gold 1337.0000 332014 1346 0.67 CO 2242014 Buy AUDUSD 0.8990 2272014 0.893 0.67 FX 2132014 Buy AUDNZD 1.0750 2262014 1.078 0.28 FX 2252014 Sell USM4 131.8125 2252014 132.3125 0.38 FI 2122014 Buy TYH4 125.359375 2202014 125.671875 0.25 FI 2122014 Sell LME Copper 7098 2192014 7215 1.65 CO 1142014 Buy USDCAD 1.0930 2112014 1.101 0.73 FX 192014 Buy USDKRW 1059 242014 1081.0 2.08 FX 1152014 Buy COM4 105.00 1312014 105.00 0.00 CO 1172014 Sell EURUSD 1.3547 1232014 1.3650 0.76 FX 12192013 Buy USDTRY 2.0715 1172014 2.2161 6.98 FX 12102013 Buy USDMXN 12.86 12192013 12.86 0.00 FX 1252013 Sell TYH4 124.453125 12202013 123.75 0.56 FI 11122013 Buy USDJPY 99.53 12202013 104.6 5.09 FX 12162013 Sell EURUSD 1.3764 12272013 1.3834 0.51 FX 9202013 Sell LME Copper 7294 12132013 7207 1.19 CO Source BofA Merrill Lynch Global Research. Past performance is no guarantee of future results. Records for trades prior to May 2013 are available upon request Liquid Technical Edge 15 December 2014 7 Methodology Trades ideas are based primarily on tools such as pattern recognition and trend analysis but may also be based on market sentiment positioning and inter market relationships. This analysis provides directional views on global sovereign debt foreign exchange and commodity markets. Markets and instruments to be traded Foreign Exchange G20 currencies using cash forwards futures and options Fixed Income Global sovereign debt using cash swaps forwards futures and options Commodities Exchange traded energy base and precious metals and agricultural commodity markets Trade Specifics All trades will have a predetermined stop loss and profit objective and will ideally have a projected reward risk ratio of 3to1 or better i. e. we will enter trade recommendations where we expect that the potential return will be three times the possible loss. Entry and exit of trades will be done at market or limit using desk prices where we would buy on the offer and sell on the bid. All trade ideas will be published in either Liquid Technical Edge or Liquid Technical Alert report. We exit trades when our trades hit their respective targets or stops or when we change our views based on a change in market conditions. All trades will be closed out in a Liquid Technical Edge or a Liquid Technical Alert. Trade Performance We provide price return performance on a trade by trade basis using the previously published entry and exit levels for the previous last 12 months trades. We will publish price performance of all trades whenever a new trade is initiated or a previous trade is closed. Additionally performance of open trades can be seen daily in Liquid Technical Edge. The performance of trades entered into by investors will vary from our reported performance depending on entry and exit levels and any additional costs fees and expenses that that maybe associated with the trades. Past performance is not indicative of future performance of our trade recommendations. Analyst Certification I MacNeil Curry CFA CMT hereby certify that the views expressed in this research report accurately reflect my personal views about the subject securities and issuers. I also certify that no part of my compensation was is or will be directly or indirectly related to the specific recommendations or view expressed in this research report. Liquid Technical Edge 15 December 2014 8 Important Disclosures BofA Merrill Lynch Research personnel including the analyst s responsible for this report receive compensation based upon among other factors the overall profitability of Bank of America Corporation including profits derived from investment banking revenues. BofA Merrill Lynch Global Credit Research analysts regularly interact with sales and trading desk personnel in connection with their research including to ascertain pricing and liquidity in the fixed income markets. Other Important Disclosures This report may refer to fixed income securities that may not be offered or sold in one or more states or jurisdictions. Readers of this report are advised that any discussion recommendation or other mention of such securities is not a solicitation or offer to transact in such securities. Investors should contact their BofA Merrill Lynch representative or Merrill Lynch Financial Global Wealth Management financial advisor for information relating to fixed income securities Rule 144A securities may be offered or sold only to persons in the U. S. who are Qualified Institutional Buyers within the meaning of Rule 144A under the Securities Act of 1933 as amended. SECURITIES DISCUSSED HEREIN MAY BE RATED BELOW INVESTMENT GRADE AND SHOULD THEREFORE ONLY BE CONSIDERED FOR INCLUSION IN ACCOUNTS QUALIFIED FOR SPECULATIVE INVESTMENT. Recipients who are not institutional investors or market professionals should seek the advice of their independent financial advisor before considering information in this report in connection with any investment decision or for a necessary explanation of its contents. The securities discussed in this report may be traded overthecounter. Retail sales andor distribution of this report may be made only in states where these securities are exempt from registration or have been qualified for sale. Officers of MLPFamp S or one or more of its affiliates other than research analysts may have a financial interest in securities of the issuer s or in related investments. This report and the securities discussed herein may not be eligible for distribution or sale in all countries or to certain categories of investors. BofA Merrill Lynch Global Research policies relating to conflicts of interest are described at http www.ml.commedia43347.pdf. quot BofA Merrill Lynchquot includes Merrill Lynch Pierce Fenner amp Smith Incorporated quotMLPFamp Squot and its affiliates. Investors should contact their BofA Merrill Lynch representative or Merrill Lynch Global Wealth Management financial advisor if they have questions concerning this report. quot BofA Merrill Lynchquot and quot Merrill Lynchquot are each global brands for BofA Merrill Lynch Global Research. Information relating to NonUS affiliates of BofA Merrill Lynch and Distribution of Affiliate Research Reports MLPFamp S distributes or may in the future distribute research reports of the following nonUS affiliates in the US short name legal name Merrill Lynch France Merrill Lynch Capital Markets France SAS Merrill Lynch Frankfurt Merrill Lynch International Bank Ltd. Frankfurt Branch Merrill Lynch South Africa Merrill Lynch South Africa Pty Ltd. Merrill Lynch Milan Merrill Lynch International Bank Limited MLI UK Merrill Lynch International Merrill Lynch Australia Merrill Lynch Equities Australia Limited Merrill Lynch Hong Kong Merrill Lynch Asia Pacific Limited Merrill Lynch Singapore Merrill Lynch Singapore Pte Ltd. Merrill Lynch Canada Merrill Lynch Canada Inc Merrill Lynch Mexico Merrill Lynch Mexico SA de CV Casa de Bolsa Merrill Lynch Argentina Merrill Lynch Argentina SA Merrill Lynch Japan Merrill Lynch Japan Securities Co. Ltd. Merrill Lynch Seoul Merrill Lynch International Incorporated Seoul Branch Merrill Lynch Taiwan Merrill Lynch Securities Taiwan Ltd. DSP Merrill Lynch India DSP Merrill Lynch Limited PT Merrill Lynch Indonesia PT Merrill Lynch Indonesia Merrill Lynch Israel Merrill Lynch Israel Limited Merrill Lynch Russia OOO Merrill Lynch Securities Moscow Merrill Lynch Turkey I. B. Merrill Lynch Yatirim Bank A. S. Merrill Lynch Turkey Broker Merrill Lynch Menkul Deerler A.. Merrill Lynch Dubai Merrill Lynch International Dubai Branch MLPFamp S Zurich rep. office MLPFamp S Incorporated Zurich representative office Merrill Lynch Spain Merrill Lynch Capital Markets Espana S. A. S. V. Merrill Lynch Brazil Bank of America Merrill Lynch Banco Multiplo S. A. Merrill Lynch KSA Company Merrill Lynch Kingdom of Saudi Arabia Company. This research report has been approved for publication and is distributed in the United Kingdom to professional clients and eligible counterparties as each is defined in the rules of the Financial Conduct Authority and the Prudential Regulation Authority by Merrill Lynch International and Bank of America Merrill Lynch International Limited which are authorized by the Prudential Regulation Authority and regulated by the Financial Conduct Authority and the Prudential Regulation Authority and is distributed in the United Kingdom to retail clients as defined in the rules of the Financial Conduct Authority and the Prudential Regulation Authority by Merrill Lynch International Bank Limited London Branch which is authorised by the Central Bank of Ireland and subject to limited regulation by the Financial Conduct Authority and Prudential Regulation Authority details about the extent of our regulation by the Financial Conduct Authority and Prudential Regulation Authority are available from us on request has been considered and distributed in Japan by Merrill Lynch Japan Securities Co. Ltd. a registered securities dealer under the Financial Instruments and Exchange Act in Japan is distributed in Hong Kong by Merrill Lynch Asia Pacific Limited which is regulated by the Hong Kong SFC and the Hong Kong Monetary Authority is issued and distributed in Taiwan by Merrill Lynch Securities Taiwan Ltd. is issued and distributed in India by DSP Merrill Lynch Limited and is issued and distributed in Singapore to institutional investors andor accredited investors each as defined under the Financial Advisers Regulations by Merrill Lynch International Bank Limited Merchant Bank and Merrill Lynch Singapore Pte Ltd. Company Registration No. s F 06872E and 198602883D respectively. Merrill Lynch International Bank Limited Merchant Bank and Merrill Lynch Singapore Pte Ltd. are regulated by the Monetary Authority of Singapore. Bank of America N. A. Australian Branch ARBN 064 874 531 AFS License 412901 BANA Australia and Merrill Lynch Equities Australia Limited ABN 65 006 276 795 AFS License 235132 MLEA distributes this report in Australia only to Wholesale clients as defined by s.761G of the Corporations Act 2001. With the exception of BANA Australia neither MLEA nor any of its affiliates involved in preparing this research report is an Authorised DepositTaking Institution under the Banking Act 1959 nor regulated by the Australian Prudential Regulation Authority. No approval is required for publication or distribution of this report in Brazil and its local distribution is made by Bank of America Merrill Lynch Banco Mltiplo S. A. in accordance with applicable regulations. Merrill Lynch Dubai is authorized and regulated by the Dubai Financial Services Authority DFSA. Research reports prepared and issued by Merrill Lynch Dubai are prepared and issued in accordance with the requirements of the DFSA conduct of business rules. Merrill Lynch Frankfurt distributes this report in Germany. Merrill Lynch Frankfurt is regulated by BaFin. This research report has been prepared and issued by MLPFamp S andor one or more of its nonUS affiliates. MLPFamp S is the distributor of this research report in the US and accepts full responsibility for research reports of its nonUS affiliates distributed to MLPFamp S clients in the US. Any US person receiving this research report and wishing to effect any transaction in any security discussed in the report should do so through MLPFamp S and not such foreign affiliates. Hong Kong recipients of this research report should contact Merrill Lynch Asia Pacific Limited in respect of any matters relating to dealing in securities or provision of specific advice on securities. Singapore recipients of this research report should contact Merrill Lynch International Bank Limited Merchant Bank andor Merrill Lynch Singapore Pte Ltd in respect of any matters arising from or in connection with this research report. Liquid Technical Edge 15 December 2014 9 General Investment Related Disclosures Taiwan Readers Neither the information nor any opinion expressed herein constitutes an offer or a solicitation of an offer to transact in any securities or other financial instrument. No part of this report may be used or reproduced or quoted in any manner whatsoever in Taiwan by the press or any other person without the express written consent of BofA Merrill Lynch. This research report provides general information only. Neither the information nor any opinion expressed constitutes an offer or an invitation to make an offer to buy or sell any securities or other financial instrument or any derivative related to such securities or instruments e. g. options futures warrants and contracts for differences. This report is not intended to provide personal investment advice and it does not take into account the specific investment objectives financial situation and the particular needs of any specific person. Investors should seek financial advice regarding the appropriateness of investing in financial instruments and implementing investment strategies discussed or recommended in this report and should understand that statements regarding future prospects may not be realized. Any decision to purchase or subscribe for securities in any offering must be based solely on existing public information on such security or the information in the prospectus or other offering document issued in connection with such offering and not on this report. Securities and other financial instruments discussed in this report or recommended offered or sold by Merrill Lynch are not insured by the Federal Deposit Insurance Corporation and are not deposits or other obligations of any insured depository institution including Bank of America N. A.. Investments in general and derivatives in particular involve numerous risks including among others market risk counterparty default risk and liquidity risk. No security financial instrument or derivative is suitable for all investors. In some cases securities and other financial instruments may be difficult to value or sell and reliable information about the value or risks related to the security or financial instrument may be difficult to obtain. Investors should note that income from such securities and other financial instruments if any may fluctuate and that price or value of such securities and instruments may rise or fall and in some cases investors may lose their entire principal investment. Past performance is not necessarily a guide to future performance. Levels and basis for taxation may change. Futures and options are not appropriate for all investors. Such financial instruments may expire worthless. Before investing in futures or options clients must receive the appropriate risk disclosure documents. Investment strategies explained in this report may not be appropriate at all times. Costs of such strategies do not include commission or margin expenses. BofA Merrill Lynch is aware that the implementation of the ideas expressed in this report may depend upon an investor s ability to quotshortquot securities or other financial instruments and that such action may be limited by regulations prohibiting or restricting quotshortsellingquot in many jurisdictions. Investors are urged to seek advice regarding the applicability of such regulations prior to executing any short idea contained in this report. This report may contain a trading idea or recommendation which highlights a specific identified near term catalyst or event impacting a security issuer industry sector or the market generally that presents a transaction opportunity but does not have any impact on the analyst s particular Overweight or Underweight rating which is based on a three month trade horizon. Trading ideas and recommendations may differ directionally from the analyst s rating on a security or issuer because they reflect the impact of a near term catalyst or event. Foreign currency rates of exchange may adversely affect the value price or income of any security or financial instrument mentioned in this report. Investors in such securities and instruments effectively assume currency risk. UK Readers The protections provided by the U. K. regulatory regime including the Financial Services Scheme do not apply in general to business coordinated by BofA Merrill Lynch entities located outside of the United Kingdom. BofA Merrill Lynch Global Research policies relating to conflicts of interest are described at http www.ml.commedia43347.pdf. Officers of MLPFamp S or one or more of its affiliates other than research analysts may have a financial interest in securities of the issuer s or in related investments. MLPFamp S or one of its affiliates is a regular issuer of traded financial instruments linked to securities that may have been recommended in this report. MLPFamp S or one of its affiliates may at any time hold a trading position long or short in the securities and financial instruments discussed in this report. BofA Merrill Lynch through business units other than BofA Merrill Lynch Global Research may have issued and may in the future issue trading ideas or recommendations that are inconsistent with and reach different conclusions from the information presented in this report. Such ideas or recommendations reflect the different time frames assumptions views and analytical methods of the persons who prepared them and BofA Merrill Lynch is under no obligation to ensure that such other trading ideas or recommendations are brought to the attention of any recipient of this report. In the event that the recipient received this report pursuant to a contract between the recipient and MLPFamp S for the provision of research services for a separate fee and in connection therewith MLPFamp S may be deemed to be acting as an investment adviser such status relates if at all solely to the person with whom MLPFamp S has contracted directly and does not extend beyond the delivery of this report unless otherwise agreed specifically in writing by MLPFamp S. MLPFamp S is and continues to act solely as a brokerdealer in connection with the execution of any transactions including transactions in any securities mentioned in this report. Copyright and General Information regarding Research Reports Copyright 2014 Merrill Lynch Pierce Fenner amp Smith Incorporated. All rights reserved. This research report is prepared for the use of BofA Merrill Lynch clients and may not be redistributed retransmitted or disclosed in whole or in part or in any form or manner without the express written consent of BofA Merrill Lynch. BofA Merrill Lynch research reports are distributed simultaneously to internal and client websites and other portals by BofA Merrill Lynch and are not publiclyavailable materials. Any unauthorized use or disclosure is prohibited. Receipt and review of this research report constitutes your agreement not to redistribute retransmit or disclose to others the contents opinions conclusion or information contained in this report including any investment recommendations estimates or price targets without first obtaining expressed permission from an authorized officer of BofA Merrill Lynch. Materials prepared by BofA Merrill Lynch Global Research personnel are based on public information. Facts and views presented in this material have not been reviewed by and may not reflect information known to professionals in other business areas of BofA Merrill Lynch including investment banking personnel. BofA Merrill Lynch has established information barriers between BofA Merrill Lynch Global Research and certain business groups. As a result BofA Merrill Lynch does not disclose certain client relationships with or compensation received from such companies in research reports. To the extent this report discusses any legal proceeding or issues it has not been prepared as nor is it intended to express any legal conclusion opinion or advice. Investors should consult their own legal advisers as to issues of law relating to the subject matter of this report. BofA Merrill Lynch Global Research personnel s knowledge of legal proceedings in which any BofA Merrill Lynch entity andor its directors officers and employees may be plaintiffs defendants codefendants or coplaintiffs with or involving companies mentioned in this report is based on public information. Facts and views presented in this material that relate to any such proceedings have not been reviewed by discussed with and may not reflect information known to professionals in other business areas of BofA Merrill Lynch in connection with the legal proceedings or matters relevant to such proceedings. This report has been prepared independently of any issuer of securities mentioned herein and not in connection with any proposed offering of securities or as agent of any issuer of any securities. None of MLPFamp S any of its affiliates or their research analysts has any authority whatsoever to make any representation or warranty on behalf of the issuer s. BofA Merrill Lynch Global Research policy prohibits research personnel from disclosing a recommendation investment rating or investment thesis for review by an issuer prior to the publication of a research report containing such rating recommendation or investment thesis. Any information relating to the tax status of financial instruments discussed herein is not intended to provide tax advice or to be used by anyone to provide tax advice. Investors are urged to seek tax advice based on their particular circumstances from an independent tax professional. The information herein other than disclosure information relating to BofA Merrill Lynch and its affiliates was obtained from various sources and we do not guarantee its accuracy. This report may contain links to third party websites. BofA Merrill Lynch is not responsible for the content of any third party website or any linked content contained in a third party website. Content contained on such third party websites is not part of this report and is not incorporated by reference into this report. The inclusion of a link in this report does not imply any endorsement by or any affiliation with BofA Merrill Lynch. Access to any third party website is at Liquid Technical Edge 15 December 2014 10 your own risk and you should always review the terms and privacy policies at third party websites before submitting any personal information to them. BofA Merrill Lynch is not responsible for such terms and privacy policies and expressly disclaims any liability for them. All opinions projections and estimates constitute the judgment of the author as of the date of the report and are subject to change without notice. Prices also are subject to change without notice. BofA Merrill Lynch is under no obligation to update this report and BofA Merrill Lynch s ability to publish research on the subject companyies in the future is subject to applicable quiet periods. You should therefore assume that BofA Merrill Lynch will not update any fact circumstance or opinion contained in this report. Certain outstanding reports may contain discussions andor investment opinions relating to securities financial instruments andor issuers that are no longer current. Always refer to the most recent research report relating to a company or issuer prior to making an investment decision. In some cases a company or issuer may be classified as Restricted or may be Under Review or Extended Review. In each case investors should consider any investment opinion relating to such company or issuer or its security andor financial instruments to be suspended or withdrawn and should not rely on the analyses and investment opinion s pertaining to such issuer or its securities andor financial instruments nor should the analyses or opinion s be considered a solicitation of any kind. Sales persons and financial advisors affiliated with MLPFamp S or any of its affiliates may not solicit purchases of securities or financial instruments that are Restricted or Under Review and may only solicit securities under Extended Review in accordance with firm policies. Neither BofA Merrill Lynch nor any officer or employee of BofA Merrill Lynch accepts any liability whatsoever for any direct indirect or consequential damages or losses arising from any use of this report or its contents.\nTrading ideas and investment strategies discussed herein may give rise to significant risk and are not suitable for all investors. Investors should have experience in FX markets and the financial resources to absorb any losses arising from applying these ideas or strategies. BofA Merrill Lynch does and seeks to do business with companies covered in its research reports. As a result investors should be aware that the firm may have a conflict of interest that could affect the objectivity of this report. Investors should consider this report as only a single factor in making their investment decision. Refer to important disclosures on page 10 to 12. Analyst Certification on Page 9. 11466662 Liquid Insight BoE Nothing to see here Rates and Currencies Research Global 06 January 2015 Global Rates amp Currencies Research MLPFamp S Mark Capleton 44 20 7995 6118 Rates Strategist MLI UK mark.capletonbaml.com Kamal Sharma 44 20 7996 4855 FX Strategist MLI UK ksharma32baml.com Adarsh Sinha 852 2161 7155 FX Strategist Merrill Lynch Hong Kong adarsh.sinhabaml.com Yang Chen 852 3602 1695 Rates Strategist Merrill Lynch Hong Kong ychen8baml.com See Team Page for Full List of Contributors Recent Liquid Insight Publications 19 December 2014 Last call for GBP 19 December 2014 Pay 5y5y GBP valuation stretched and supports fading 18 December 2014 Fundamental shift or risk premium increase 17 December 2014 BoJ preview Oil price in focus 16 December 2014 It s not crazy to buy bonds 15 December 2014 Another December to remember 12 December 2014 TLTRO allotment unlikely to derail QE 11 December 2014 CNY Is the squeeze over 10 December 2014 The Fed s to do list 9 December 2014 Anchors away By Kamal Sharma and Mark Capleton Chart of the Day Wage developments will remain the key focus for MPC Source BoAML Global Research KPMG Comfortably on hold At its first scheduled meeting of the year we expect the Bank of England to leave interest rates on hold at 0.5 and the Asset Purchase Facility APF at 375bn. We do not expect it to release a statement following the announcement as is usual protocol. Nevertheless there should be a small nugget of information for the gilt market in the announcement. In order to maintain the stock of QE at 375bn the Bank will need to reinvest 4.3bn following a January 22 redemption. Since this precedes the February MPC meeting we would expect reinvestment confirmation this week. Unauthorized redistribution of this report is prohibited. This report is intended for benjamin.petobaml.com. Liquid Insight 06 January 2015 2 It has been an inauspicious start to the year for the GBP particularly versus the USD as UKUS rate differentials move against the sterling. The nearterm outlook thus appears to be challenging as inflation continues to disappoint and as investors look ahead to the UK general election. We think the decision to keep rates on hold for the majority of the Monetary Policy Committee should be a relatively easy one this time around and indeed over the coming months against the backdrop of a softening in nearterm inflationary pressures. The November CPI inflation reading fell from 1.3 to 1.0 significantly below consensus and to its lowest since Autumn 2002. In its November Inflation Report the BoE had looked for a 1.3 reading for November. In our view CPI inflation is set to fall further in the near term and will give the majority of the MPC greater control on the debate on the timing of the first rate hike. The December CPI due for release on 13 January is expected to show CPI inflation falling to around 0.7 yoy. This would trigger an open letter from BoE Governor Mark Carney to the Chancellor on the reasons why inflation is printed below 1 from the 2 target. Inflation is likely to trough around 0.5 early this year and this is notably below the BoE s expectations of a trough of around 1 in its November Inflation Report given the continued pressure on global energy prices. Clearly that gives the bulk of the MPC an easier backdrop to leave rates on hold. However the key debate for the MPC over the course of the year will be wage developments and it is this area where the two hawks Martin Weale and Ian McCafferty fundamentally disagree with the rest of the MPC. The Chart of the Day illustrates this point clearly. The hawks assert that the average earnings growth is on the cusp of a meaningful rise over the coming year as suggested by developments in the KPMG survey on permanent staff salaries. This would suggest the need for an immediate rise in rates to counteract future inflationary pressures. By contrast the mainstream have to date preferred to wait for actual signs of a strong pickup in average earnings before deciding to act on rates. UK rates markets have gradually priced out the chance of a UK rate hike in 2015 with expectations currently for a move in 1Q16 versus our own expectation for a move in August 2015. The Minutes of December meeting reveal that the MPC has been surprised and is perhaps slightly uncomfortable by the extent to which UK rates markets have pushed back ratehike expectations. Indeed Governor Carney recently stated that the Bank of England is prepared to look through the current supplydriven fall in oil prices. The key to this view is whether UK inflation expectations will remain resilient to recent declines in oil prices Chart 1 and whether there are any second round effects slowing average earnings for example. Since inflation expectations did not become dislodged to the upside despite UK CPI inflation averaging 3 over 200613 it would be asymmetric to expect it to become rapidly dislodged to the downside. Indeed while deflation is common within individual components of the UK CPI basket in the decade prior to the crisis around 30 of items were typically in deflation there is actually less downward pull on aggregate inflation than usual from such items at present. Liquid Insight 06 January 2015 3 Chart 1 UK GfK BoE 12month inflation expectations Source BoAML Global Research Bank of England RPI measure of inflation Rates Something does not seem right The pace of gilt issuance will be slower in value terms over the balance of the fiscal year although it will step up a gear once the new fiscal year begins in March and the market is well aware of the upcoming 4.3bn BoE reinvestment. We suspect these have helped gilts do so well both in outright terms and relative to other markets but are concerned the market may be overplaying the story. The overall risk to be delivered over the quarter after allowing for the BoE s risk extraction will still be fairly normal by recent standards because we will see a sizeable amount of linker risk coming via syndication later this month Chart 2 PVBP risk supply net of BoE buybacks to end March mn bp Source BoAML Global Research Debt Management Office Bank of England And of course the higher pace of issuance expected from April will not be tempered by BoE reinvestment at least until September since redemptions will be bunched later in the 201516 fiscal year 2.0 2.5 3.0 3.5 4.0 4.5 5.0 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 40 20 0 20 40 60 80 09 10 11 12 13 14 15 Nominal InflationLinked Liquid Insight 06 January 2015 4 Chart 3 BoE QE holdings bn showing late2015early2016 bunching Source BoAML Global Research Debt Management Office Bank of England By pushing the expected first hike into 1Q16 we believe the market has also moved to expect the 31.6bn total of potential BoE reinvestments between September 2015 and January 2016 to go ahead whereas we would argue at least half that amount is still in the balance. The latest Bankstats numbers just out confirmed that banks purchased another large block of gilts in November taking the total over two months to 11bn. Although it possible this marks a desire to accumulate high quality liquid assets we would question the likely persistence of such a large monthly bid. Meanwhile overseas investors continued to leave the gilt market alone and sterling weakness seems to corroborate the idea that gilts are not benefiting from rebalancing out of negativelyyielding core Euro as some are suggesting Chart 4 Monthly net gilt buying by UK banks and overseas investors bn Source BoAML Global Research Debt Management Office Bank of England We reaffirm our core bearish gilt view. The 5y5y Sonia at 1 is not our idea of a neutral policy rate. In trying to identify catalysts that might arrest the gilt rally perhaps we need look no further than this week s 10y nominal and 30y linker auctions. Though modest in size the yield levels are somewhat demanding. 0 2 4 6 8 10 12 14 16 18 Jan13 Jul13 Jan14 Jul14 Jan15 Jul15 Jan16 Jul16 All past reinvestments 2015 amp 16 prospective reinvestments 20 15 10 5 0 5 10 15 20 10 11 12 13 14 Oseas Banks Liquid Insight 06 January 2015 5 FX MPC losing the footrace versus the Fed It has been an inauspicious start to the year for GBP which has underperformed all of its G10 peers with the exception of the NOK. Sentiment has not been helped by further evidence of a loss of momentum in the UK economy with both the manufacturing and construction PMI numbers printing on the weaker side of expectations. Though the USD has made a strong start to 2015 GBP USD has been particularly hit hard driven primarily by a further shift in rate differentials in favor of the USD Chart 5. With the markets pushing back the chances of UK rate hikes into 1Q16 the Bank of England continues to lose the footrace to policy tightening versus the Fed. GBP USD is thus likely to remain under pressure in the nearterm as these forces continue to dominate sentiment. EUR GBP has once again failed to make a sustained break of the 0.7750 level despite significant pressure on the EUR at the start of the year. The conflicting forces of prospective QE weighing on EUR and softening nearterm UK inflationary pressures weighing on GBP suggest that EUR GBP will trade a range for the time being. But in our view with the UK general election on the horizon and continued uncertainty on the outcome there appears to be no respite for the GBP at present. Chart 5 GBPUSD versus UKUS 2yr rate differentials Source BoAML Global Research Bloomberg 0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 1.00 1.45 1.50 1.55 1.60 1.65 1.70 1.75 2010 2011 2012 2013 2014 2015 GBPUSD lhs UKUS rate spread rhs Liquid Insight 06 January 2015 6 Notable Rates and FX research Global Rates amp Currencies 2015 Year Ahead 23 November 2014 Sell GBP JPY FX Quant Trader 5 January 2015. Inching towards the inevitable Global Rates and FX Weekly 12 December 2014. Ringing in the year of the hike US Rates Weekly 19 December 2014. Riskoff as the year ends Liquid Cross Border Flows 15 December 2014. Key trade ideas Top Rates and FX trades for 2015 For rationale and details refer to Global Rates amp Currencies 2015 Year Ahead Liquidity Transfusion 23 November 2014 Rates Pay 5y US swap rates vs 5y offshore China swap rates entry 119bp target 60bp stop 145bp Receive Eonia 1y one year forward entry 4 bp target 15 bp stop 0bp Buy 1y6m onetouch put spread in EUR USD struck at 1.18 for 14.5 spot reference 1.2425 Buy 30y US inflation vs 30y Euro inflation in swaps entry cost 49bp target 80bp stop 35bp Buy 200mm T 0.625 111516 vs paying in matched maturity swaps entry 17.5bp target 28bp stop 12bp Buy 3y Portugal and 10y Bunds and sell 10y Spain 55 83 and 100 target 115bp stop 93bp FX Sell AUD USD spot entry 0.8710 target 0.78 stop 0.86 19 Dec 2014 Sell CHF NOK spot entry 7.00 target 6.25 stop loss 7.42 Sell 3m USD JPY 125 one touch option to finance buying a 6m 125 one touch option in U10mU13m ratio payout spot reference 117.80 1y USDCAD 1.27 digital call for 10.25 spot reference 1.13 New trade Rates Sell 10y US swap spreads by selling 100mm T 2.25 111524 vs receiving matched maturity swap Enter 10.3bp Target 7.5bp Stop loss 12bp To take advantage of a seasonal tightening pattern in January most of the tightening typically occurs around the first week of the month likely due to the corporate issuance calendar which typically picks up strongly at the start of January. Existing open trades Rates Sell US front end by shorting 4000 EDZ6 contracts Enter 98.14 target 97.75 stop 98.32. Nov 4 2014 Data confirms that the US recovery is intact and a data dependent Fed should increase risk premiums in the front end. Demand from foreign officials and banks appear to be slowing. Positioning is also cleaner. Buy 10y US swap spreads by buying 10y 200mm T2.375 8152024 Treasuries vs matched maturity swaps Enter 12.3bp Stop loss 5bp target 25bp. A costeffective way to position for either a surprising carrytrade unwind as Fed tightening approaches or a surprising riskoff development. Sell 100mm UST 2.5 51524 1st offtherun 10y vs receiving a durationmatched swap maturing on the same date Enter 12bp target 8bp stoploss 14.5bp Take advantage of a strong seasonal spread tightening in September due to heavy corporate issuance Buy 2m 2s5s curve cap spread buying 400mn 2m 2s5s ATMF cap vs 400mn 2m 2s5s ATMF15bp cap Entry cost 210K 5.25bp target Pamp L of 360K stoploss loss of 180K The RedsBlues curve looks rather flat to FOMC projections. In addition a too low neutral rate is priced in. Long 2035 inflationlinked bond entry BEI 2.52 target 2.80 stop 2.40 RBA inflation forecasts now see a rise towards the top of the band by the end of 2015. There is no term premium in long end linkers. As we expect significant depreciation of the AUD in 2015 imported inflation is expected to add to rising inflation pressures towards the end of next year. Liquid Insight 06 January 2015 7 Buy 1y1y payer ladders by buying 500mn 1y1y ATMF payers selling 500mn 1y1y ATMF27bp payers and selling 500mn 1y1y ATMF54bp payers entry cost 0 target 400K stoploss 200K The trade carries positively and offers an attractive valuation. It should deliver attractive terminal payoffs in any reasonable scenario of the Fed policy Buy 100mn ATM 1m10y payers Premium 680K target 1.4mn stoploss entire premium Economic data in coming weeks could further strengthen as we get payback from the extreme winter weather. Carry is less punitive in being short 10s Buy the ERU6 Sep16 99.12599.00 Jul put spread for 3.5 ticks target 5 ticks We favor downside positions in futures rather than OIS ahead of the ECB meeting and express this view via options as the probability of imminent ECB action is low but not zero Enter a 1y1y vs 3y1y Eonia steepener current 68.5bp target 84bp stop 63bp With the ECB expected to remain on hold we expect a bear steepening of the curve. Should the ECB surprise markets we see a simple refi rate cut as the most likely step which would also steepen the 1y1y3y1y curve Buy 125.87mn 1y2y ATM payers sell 125.87mn 1y2y ATM25bp payers vs sell 250mn 1y1y ATM68bp payers target Pamp L 125K stoploss loss of 60K Monetizes the richness of vols and payer skews and should benefit from a steeper RedsGreens curve Buy 200mm T0.625 93017 vs matched maturity swaps entry cost 13.5bp stoploss 5bp target 25bp 3y spreads offer more exposure to geopolitical risks and ongoing regulatory reform Buying EUR100mm 1m1y ATM vs selling 1m1y ATM10bp payers. Entry cost 3bp target maturity maximum 7bp gain. Market pricing in too aggressive ECB easing. This trade is a short term technical positioning for ECB disappointment. Buying 100mm 3m5y ATMF 1.77 receivers vs selling 26mm 3m30y ATMF 3.71 receivers. Entry cost 0 Stoploss 100K target 200K. To position for continuing data weakness while been protected against a market selloff FX Sell EUR JPY spot entry 147.52 target 142.00 stop 149.50 EURJPY has overshot relative to movements in 10year real rates and the market is underpricing the risk of Abe losing seats in the election. Strong demand for EUR puts against most currencies into the ECB suggests downside EUR risks Sell CAD MXN spot entry 12.1085 target 11.7972 stop 12.2000 To position for BoC on hold post the weak employment report vs. our bullish view on MXN as we expect growth to pick up in H2 2014 in Mexico. Flows and technical also support this trade. Liquid Insight 06 January 2015 8 Options Risk Statement Potential Risk at Expiry amp Options Limited Duration Risk Unlike owning or shorting a stock employing any listed options strategy is by definition governed by a finite duration. The most severe risks associated with general options trading are total loss of capital invested and delivery assignment risk all of which can occur in a short period. Investor suitability The use of standardized options and other related derivatives instruments are considered unsuitable for many investors. Investors considering such strategies are encouraged to become familiar with the quotCharacteristics and Risks of Standardized Optionsquot an OCC authored white paper on options risks. U. S. investors should consult with a FINRA Registered Options Principal. For detailed information regarding the risks involved with investing in listed options http www.theocc.comaboutpublicationscharacterrisks.jsp Liquid Insight 06 January 2015 9 Analyst Certification We David Woo Adarsh Sinha and Yang Chen hereby certify that the views expressed in this research report about securities and issuers accurately reflect our respective models applied in the analysis. We also certify that no part of our respective compensation was is or will be directly or indirectly related to the specific recommendations or view expressed in this research report. Liquid Insight 06 January 2015 10 Important Disclosures BofA Merrill Lynch Research personnel including the analyst s responsible for this report receive compensation based upon among other factors the overall profitability of Bank of America Corporation including profits derived from investment banking revenues. BofA Merrill Lynch Global Credit Research analysts regularly interact with sales and trading desk personnel in connection with their research including to ascertain pricing and liquidity in the fixed income markets. Other Important Disclosures This report may refer to fixed income securities that may not be offered or sold in one or more states or jurisdictions. Readers of this report are advised that any discussion recommendation or other mention of such securities is not a solicitation or offer to transact in such securities. Investors should contact their BofA Merrill Lynch representative or Merrill Lynch Financial Global Wealth Management financial advisor for information relating to fixed income securities Rule 144A securities may be offered or sold only to persons in the U. S. who are Qualified Institutional Buyers within the meaning of Rule 144A under the Securities Act of 1933 as amended. SECURITIES DISCUSSED HEREIN MAY BE RATED BELOW INVESTMENT GRADE AND SHOULD THEREFORE ONLY BE CONSIDERED FOR INCLUSION IN ACCOUNTS QUALIFIED FOR SPECULATIVE INVESTMENT. Recipients who are not institutional investors or market professionals should seek the advice of their independent financial advisor before considering information in this report in connection with any investment decision or for a necessary explanation of its contents. The securities discussed in this report may be traded overthecounter. Retail sales andor distribution of this report may be made only in states where these securities are exempt from registration or have been qualified for sale. Officers of MLPFamp S or one or more of its affiliates other than research analysts may have a financial interest in securities of the issuer s or in related investments. This report and the securities discussed herein may not be eligible for distribution or sale in all countries or to certain categories of investors. BofA Merrill Lynch Global Research policies relating to conflicts of interest are described at http www.ml.commedia43347.pdf. quot BofA Merrill Lynchquot includes Merrill Lynch Pierce Fenner amp Smith Incorporated quotMLPFamp Squot and its affiliates. Investors should contact their BofA Merrill Lynch representative or Merrill Lynch Global Wealth Management financial advisor if they have questions concerning this report. quot BofA Merrill Lynchquot and quot Merrill Lynchquot are each global brands for BofA Merrill Lynch Global Research. Information relating to NonUS affiliates of BofA Merrill Lynch and Distribution of Affiliate Research Reports MLPFamp S distributes or may in the future distribute research reports of the following nonUS affiliates in the US short name legal name Merrill Lynch France Merrill Lynch Capital Markets France SAS Merrill Lynch Frankfurt Merrill Lynch International Bank Ltd. Frankfurt Branch Merrill Lynch South Africa Merrill Lynch South Africa Pty Ltd. Merrill Lynch Milan Merrill Lynch International Bank Limited MLI UK Merrill Lynch International Merrill Lynch Australia Merrill Lynch Equities Australia Limited Merrill Lynch Hong Kong Merrill Lynch Asia Pacific Limited Merrill Lynch Singapore Merrill Lynch Singapore Pte Ltd. Merrill Lynch Canada Merrill Lynch Canada Inc Merrill Lynch Mexico Merrill Lynch Mexico SA de CV Casa de Bolsa Merrill Lynch Argentina Merrill Lynch Argentina SA Merrill Lynch Japan Merrill Lynch Japan Securities Co. Ltd. Merrill Lynch Seoul Merrill Lynch International Incorporated Seoul Branch Merrill Lynch Taiwan Merrill Lynch Securities Taiwan Ltd. DSP Merrill Lynch India DSP Merrill Lynch Limited PT Merrill Lynch Indonesia PT Merrill Lynch Indonesia Merrill Lynch Israel Merrill Lynch Israel Limited Merrill Lynch Russia OOO Merrill Lynch Securities Moscow Merrill Lynch Turkey I. B. Merrill Lynch Yatirim Bank A. S. Merrill Lynch Turkey Broker Merrill Lynch Menkul Deerler A.. Merrill Lynch Dubai Merrill Lynch International Dubai Branch MLPFamp S Zurich rep. office MLPFamp S Incorporated Zurich representative office Merrill Lynch Spain Merrill Lynch Capital Markets Espana S. A. S. V. Merrill Lynch Brazil Bank of America Merrill Lynch Banco Multiplo S. A. Merrill Lynch KSA Company Merrill Lynch Kingdom of Saudi Arabia Company. This research report has been approved for publication and is distributed in the United Kingdom to professional clients and eligible counterparties as each is defined in the rules of the Financial Conduct Authority and the Prudential Regulation Authority by Merrill Lynch International and Bank of America Merrill Lynch International Limited which are authorized by the Prudential Regulation Authority and regulated by the Financial Conduct Authority and the Prudential Regulation Authority and is distributed in the United Kingdom to retail clients as defined in the rules of the Financial Conduct Authority and the Prudential Regulation Authority by Merrill Lynch International Bank Limited London Branch which is authorised by the Central Bank of Ireland and subject to limited regulation by the Financial Conduct Authority and Prudential Regulation Authority details about the extent of our regulation by the Financial Conduct Authority and Prudential Regulation Authority are available from us on request has been considered and distributed in Japan by Merrill Lynch Japan Securities Co. Ltd. a registered securities dealer under the Financial Instruments and Exchange Act in Japan is distributed in Hong Kong by Merrill Lynch Asia Pacific Limited which is regulated by the Hong Kong SFC and the Hong Kong Monetary Authority is issued and distributed in Taiwan by Merrill Lynch Securities Taiwan Ltd. is issued and distributed in India by DSP Merrill Lynch Limited and is issued and distributed in Singapore to institutional investors andor accredited investors each as defined under the Financial Advisers Regulations by Merrill Lynch International Bank Limited Merchant Bank and Merrill Lynch Singapore Pte Ltd. Company Registration No. s F 06872E and 198602883D respectively. Merrill Lynch International Bank Limited Merchant Bank and Merrill Lynch Singapore Pte Ltd. are regulated by the Monetary Authority of Singapore. Bank of America N. A. Australian Branch ARBN 064 874 531 AFS License 412901 BANA Australia and Merrill Lynch Equities Australia Limited ABN 65 006 276 795 AFS License 235132 MLEA distributes this report in Australia only to Wholesale clients as defined by s.761G of the Corporations Act 2001. With the exception of BANA Australia neither MLEA nor any of its affiliates involved in preparing this research report is an Authorised DepositTaking Institution under the Banking Act 1959 nor regulated by the Australian Prudential Regulation Authority. No approval is required for publication or distribution of this report in Brazil and its local distribution is made by Bank of America Merrill Lynch Banco Mltiplo S. A. in accordance with applicable regulations. Merrill Lynch Dubai is authorized and regulated by the Dubai Financial Services Authority DFSA. Research reports prepared and issued by Merrill Lynch Dubai are prepared and issued in accordance with the requirements of the DFSA conduct of business rules. Merrill Lynch Frankfurt distributes this report in Germany. Merrill Lynch Frankfurt is regulated by BaFin. This research report has been prepared and issued by MLPFamp S andor one or more of its nonUS affiliates. MLPFamp S is the distributor of this research report in the US and accepts full responsibility for research reports of its nonUS affiliates distributed to MLPFamp S clients in the US. Any US person receiving this research report and wishing to effect any transaction in any security discussed in the report should do so through MLPFamp S and not such foreign affiliates. Hong Kong recipients of this research report should contact Merrill Lynch Asia Pacific Limited in respect of any matters relating to dealing in securities or provision of specific advice on securities. Singapore recipients of this research report should contact Merrill Lynch International Bank Limited Merchant Bank andor Merrill Lynch Singapore Pte Ltd in respect of any matters arising from or in connection with this research report. Liquid Insight 06 January 2015 11 General Investment Related Disclosures Taiwan Readers Neither the information nor any opinion expressed herein constitutes an offer or a solicitation of an offer to transact in any securities or other financial instrument. No part of this report may be used or reproduced or quoted in any manner whatsoever in Taiwan by the press or any other person without the express written consent of BofA Merrill Lynch. This research report provides general information only. Neither the information nor any opinion expressed constitutes an offer or an invitation to make an offer to buy or sell any securities or other financial instrument or any derivative related to such securities or instruments e. g. options futures warrants and contracts for differences. This report is not intended to provide personal investment advice and it does not take into account the specific investment objectives financial situation and the particular needs of any specific person. Investors should seek financial advice regarding the appropriateness of investing in financial instruments and implementing investment strategies discussed or recommended in this report and should understand that statements regarding future prospects may not be realized. Any decision to purchase or subscribe for securities in any offering must be based solely on existing public information on such security or the information in the prospectus or other offering document issued in connection with such offering and not on this report. Securities and other financial instruments discussed in this report or recommended offered or sold by Merrill Lynch are not insured by the Federal Deposit Insurance Corporation and are not deposits or other obligations of any insured depository institution including Bank of America N. A.. Investments in general and derivatives in particular involve numerous risks including among others market risk counterparty default risk and liquidity risk. No security financial instrument or derivative is suitable for all investors. In some cases securities and other financial instruments may be difficult to value or sell and reliable information about the value or risks related to the security or financial instrument may be difficult to obtain. Investors should note that income from such securities and other financial instruments if any may fluctuate and that price or value of such securities and instruments may rise or fall and in some cases investors may lose their entire principal investment. Past performance is not necessarily a guide to future performance. Levels and basis for taxation may change. Futures and options are not appropriate for all investors. Such financial instruments may expire worthless. Before investing in futures or options clients must receive the appropriate risk disclosure documents. Investment strategies explained in this report may not be appropriate at all times. Costs of such strategies do not include commission or margin expenses. BofA Merrill Lynch is aware that the implementation of the ideas expressed in this report may depend upon an investor s ability to quotshortquot securities or other financial instruments and that such action may be limited by regulations prohibiting or restricting quotshortsellingquot in many jurisdictions. Investors are urged to seek advice regarding the applicability of such regulations prior to executing any short idea contained in this report. This report may contain a trading idea or recommendation which highlights a specific identified near term catalyst or event impacting a security issuer industry sector or the market generally that presents a transaction opportunity but does not have any impact on the analyst s particular Overweight or Underweight rating which is based on a three month trade horizon. Trading ideas and recommendations may differ directionally from the analyst s rating on a security or issuer because they reflect the impact of a near term catalyst or event. Foreign currency rates of exchange may adversely affect the value price or income of any security or financial instrument mentioned in this report. Investors in such securities and instruments effectively assume currency risk. UK Readers The protections provided by the U. K. regulatory regime including the Financial Services Scheme do not apply in general to business coordinated by BofA Merrill Lynch entities located outside of the United Kingdom. BofA Merrill Lynch Global Research policies relating to conflicts of interest are described at http www.ml.commedia43347.pdf. Officers of MLPFamp S or one or more of its affiliates other than research analysts may have a financial interest in securities of the issuer s or in related investments. MLPFamp S or one of its affiliates is a regular issuer of traded financial instruments linked to securities that may have been recommended in this report. MLPFamp S or one of its affiliates may at any time hold a trading position long or short in the securities and financial instruments discussed in this report. BofA Merrill Lynch through business units other than BofA Merrill Lynch Global Research may have issued and may in the future issue trading ideas or recommendations that are inconsistent with and reach different conclusions from the information presented in this report. Such ideas or recommendations reflect the different time frames assumptions views and analytical methods of the persons who prepared them and BofA Merrill Lynch is under no obligation to ensure that such other trading ideas or recommendations are brought to the attention of any recipient of this report. In the event that the recipient received this report pursuant to a contract between the recipient and MLPFamp S for the provision of research services for a separate fee and in connection therewith MLPFamp S may be deemed to be acting as an investment adviser such status relates if at all solely to the person with whom MLPFamp S has contracted directly and does not extend beyond the delivery of this report unless otherwise agreed specifically in writing by MLPFamp S. MLPFamp S is and continues to act solely as a brokerdealer in connection with the execution of any transactions including transactions in any securities mentioned in this report. Copyright and General Information regarding Research Reports Copyright 2015 Merrill Lynch Pierce Fenner amp Smith Incorporated. All rights reserved. This research report is prepared for the use of BofA Merrill Lynch clients and may not be redistributed retransmitted or disclosed in whole or in part or in any form or manner without the express written consent of BofA Merrill Lynch. BofA Merrill Lynch research reports are distributed simultaneously to internal and client websites and other portals by BofA Merrill Lynch and are not publiclyavailable materials. Any unauthorized use or disclosure is prohibited. Receipt and review of this research report constitutes your agreement not to redistribute retransmit or disclose to others the contents opinions conclusion or information contained in this report including any investment recommendations estimates or price targets without first obtaining expressed permission from an authorized officer of BofA Merrill Lynch. Materials prepared by BofA Merrill Lynch Global Research personnel are based on public information. Facts and views presented in this material have not been reviewed by and may not reflect information known to professionals in other business areas of BofA Merrill Lynch including investment banking personnel. BofA Merrill Lynch has established information barriers between BofA Merrill Lynch Global Research and certain business groups. As a result BofA Merrill Lynch does not disclose certain client relationships with or compensation received from such companies in research reports. To the extent this report discusses any legal proceeding or issues it has not been prepared as nor is it intended to express any legal conclusion opinion or advice. Investors should consult their own legal advisers as to issues of law relating to the subject matter of this report. BofA Merrill Lynch Global Research personnel s knowledge of legal proceedings in which any BofA Merrill Lynch entity andor its directors officers and employees may be plaintiffs defendants codefendants or coplaintiffs with or involving companies mentioned in this report is based on public information. Facts and views presented in this material that relate to any such proceedings have not been reviewed by discussed with and may not reflect information known to professionals in other business areas of BofA Merrill Lynch in connection with the legal proceedings or matters relevant to such proceedings. This report has been prepared independently of any issuer of securities mentioned herein and not in connection with any proposed offering of securities or as agent of any issuer of any securities. None of MLPFamp S any of its affiliates or their research analysts has any authority whatsoever to make any representation or warranty on behalf of the issuer s. BofA Merrill Lynch Global Research policy prohibits research personnel from disclosing a recommendation investment rating or investment thesis for review by an issuer prior to the publication of a research report containing such rating recommendation or investment thesis. Any information relating to the tax status of financial instruments discussed herein is not intended to provide tax advice or to be used by anyone to provide tax advice. Investors are urged to seek tax advice based on their particular circumstances from an independent tax professional. The information herein other than disclosure information relating to BofA Merrill Lynch and its affiliates was obtained from various sources and we do not guarantee its accuracy. This report may contain links to third party websites. BofA Merrill Lynch is not responsible for the content of any third party website or any linked content contained in a third party website. Content contained on such third party websites is not part of this report and is not incorporated by reference into this report. The inclusion of a link in this report does not imply any endorsement by or any affiliation with BofA Merrill Lynch. Access to any third party website is at Liquid Insight 06 January 2015 12 your own risk and you should always review the terms and privacy policies at third party websites before submitting any personal information to them. BofA Merrill Lynch is not responsible for such terms and privacy policies and expressly disclaims any liability for them. All opinions projections and estimates constitute the judgment of the author as of the date of the report and are subject to change without notice. Prices also are subject to change without notice. BofA Merrill Lynch is under no obligation to update this report and BofA Merrill Lynch s ability to publish research on the subject companyies in the future is subject to applicable quiet periods. You should therefore assume that BofA Merrill Lynch will not update any fact circumstance or opinion contained in this report. Certain outstanding reports may contain discussions andor investment opinions relating to securities financial instruments andor issuers that are no longer current. Always refer to the most recent research report relating to a company or issuer prior to making an investment decision. In some cases a company or issuer may be classified as Restricted or may be Under Review or Extended Review. In each case investors should consider any investment opinion relating to such company or issuer or its security andor financial instruments to be suspended or withdrawn and should not rely on the analyses and investment opinion s pertaining to such issuer or its securities andor financial instruments nor should the analyses or opinion s be considered a solicitation of any kind. Sales persons and financial advisors affiliated with MLPFamp S or any of its affiliates may not solicit purchases of securities or financial instruments that are Restricted or Under Review and may only solicit securities under Extended Review in accordance with firm policies. Neither BofA Merrill Lynch nor any officer or employee of BofA Merrill Lynch accepts any liability whatsoever for any direct indirect or consequential damages or losses arising from any use of this report or its contents. Liquid Insight 06 January 2015 13 Team Page US David Woo 1 646 855 5442 FX and Rates Strategist MLPFamp S david.woobaml.com Priya Misra 1 646 855 6467 Rates Strategist MLPFamp S p.misrabaml.com Ralph Axel 1 646 855 6226 Rates Strategist MLPFamp S ralph.axelbaml.com Ruslan Bikbov 1 646 855 9770 Rates Strategist MLPFamp S ruslan.bikbovbaml.com Brian Smedley 1 646 855 9809 Rates Strategist MLPFamp S brian.smedleybaml.com Shyam S.Rajan 1 646 855 9808 Rates Strategist MLPFamp S shyam.rajanbaml.com John Shin 1 646 855 9342 FX Strategist MLPFamp S joong. s.shinbaml.com MacNeil Curry CFA CMT 1 646 855 6781 Technical Strategist MLPFamp S macneil.currybaml.com John Hopkinson 1 646 855 6246 FX Strategist MLPFamp S john.hopkinsonbaml.com Ankur Singh 1 646 855 9699 FX Strategist MLPFamp S ankur.singhbaml.com Ian Gordon 1 646 855 8749 FX Strategist MLPFamp S ian.gordonbaml.com Vadim Iaralov 1 646 855 8732 FX Strategist MLPFamp S vadim.iaralovbaml.com Europe Ralf Preusser CFA 44 20 7995 7331 Rates Strategist MLI UK ralf.preusserbaml.com Ruben SeguraCayuela 44 20 7995 2102 Europe Economist MLI UK ruben.seguracayuelabaml.com Mark Capleton 44 20 7995 6118 Rates Strategist MLI UK mark.capletonbaml.com Sphia Salim 44 20 7996 2227 Rates Strategist MLI UK sphia.salimbaml.com Athanasios Vamvakidis 44 20 7995 0790 FX Strategist MLI UK athanasios.vamvakidisbaml.com Kamal Sharma 44 20 7996 4855 FX Strategist MLI UK ksharma32baml.com Myria Kyriacou 44 20 7996 1728 FX Strategist MLI UK myria.kyriacoubaml.com Pac Rim Tony Morriss 61 2 9226 5023 Rates Strategist Merrill Lynch Australia tony.morrissbaml.com Shogo Fujita 81 3 6225 6684 Rates Strategist Merrill Lynch Japan shogo.fujitabaml.com Adarsh Sinha 852 2161 7155 FX Strategist Merrill Lynch Hong Kong adarsh.sinhabaml.com Shuichi Ohsaki 81 3 6225 7747 Rates Strategist Merrill Lynch Japan shuichi.ohsakibaml.com Yang Chen 852 3602 1695 Rates Strategist Merrill Lynch Hong Kong ychen8baml.com Shusuke Yamada CFA 81 3 6225 8515 FX Strategist Merrill Lynch Japan shusuke.yamadabaml.com Global Emerging Markets Alberto Ades 1 646 855 4044 GEM FI FX Strategy Economist MLPFamp S alberto. adesbaml.com Claudio Irigoyen 1 646 855 1734 LatAm FIFX Strategist MLPFamp S claudio.irigoyenbaml.com David Hauner CFA 44 20 7996 1241 EEMEA Strategist amp Economist MLI UK david.haunerbaml.com Claudio Piron 65 6591 0401 Emerging Asia FI FX Strategist Merrill Lynch Singapore claudio.pironbaml.com Isidore Smart 1 646 855 8083 GEM Economist MLPFamp S isidore.smartbaml.com .\n"
],
[
"import nltk\nfrom nltk.tag import pos_tag\nnltk.download('averaged_perceptron_tagger')",
"[nltk_data] Downloading package averaged_perceptron_tagger to\n[nltk_data] C:\\Users\\amrenkumar\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package averaged_perceptron_tagger is already up-to-\n[nltk_data] date!\n"
],
[
"sent_tokens=[]\nfor i in list(email_clean):\n sent_tokens.append(nltk.sent_tokenize(i))",
"_____no_output_____"
],
[
"sents = []\nfor sent in range(len(sent_tokens)):\n for i in range(len(sent_tokens[sent])):\n sents.append(sent_tokens[sent][i])\n ",
"_____no_output_____"
],
[
"def tokenizer(sent):\n tokens = nltk.word_tokenize(sent)\n tags = nltk.pos_tag(tokens)\n \n tag_p = []\n for i in range(len(tags)):\n tag_p.append(tags[i][1])\n \n token_len = []\n for i in tokens:\n token_len.append(len(i)+1)\n \n list2 = list(accumulate(token_len))\n list2 = [x -1 for x in list2 ]\n \n list0 = [0]\n for i in list2:\n list0.append(i+1)\n \n data = pd.DataFrame(list(zip(tokens,list0,list2, tag_p)))\n \n return data",
"_____no_output_____"
],
[
"df_final= pd.DataFrame()\nfor sent in sents[0:500]:\n df_final = df_final.append(tokenizer(sent))",
"_____no_output_____"
],
[
"df_final.to_csv('Annotation.csv')",
"_____no_output_____"
],
[
"df_final.head(40)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a3680ae9c7854fd97142d1b5aa856041ad49a65
| 95,533 |
ipynb
|
Jupyter Notebook
|
notebooks/data-prep/UCI-Metro.ipynb
|
HPI-Information-Systems/TimeEval
|
9b2717b89decd57dd09e04ad94c120f13132d7b8
|
[
"MIT"
] | 2 |
2022-01-29T03:46:31.000Z
|
2022-02-14T14:06:35.000Z
|
notebooks/data-prep/UCI-Metro.ipynb
|
HPI-Information-Systems/TimeEval
|
9b2717b89decd57dd09e04ad94c120f13132d7b8
|
[
"MIT"
] | null | null | null |
notebooks/data-prep/UCI-Metro.ipynb
|
HPI-Information-Systems/TimeEval
|
9b2717b89decd57dd09e04ad94c120f13132d7b8
|
[
"MIT"
] | null | null | null | 132.317175 | 71,832 | 0.82046 |
[
[
[
"# UCI Metro dataset",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport os\nfrom pathlib import Path\nfrom config import data_raw_folder, data_processed_folder\nfrom timeeval import Datasets\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"%matplotlib inline\nplt.rcParams['figure.figsize'] = (20, 10)",
"_____no_output_____"
],
[
"dataset_collection_name = \"Metro\"\nsource_folder = Path(data_raw_folder) / \"UCI ML Repository/Metro\"\ntarget_folder = Path(data_processed_folder)\n\nfrom pathlib import Path\nprint(f\"Looking for source datasets in {source_folder.absolute()} and\\nsaving processed datasets in {target_folder.absolute()}\")",
"Looking for source datasets in /home/projects/akita/data/benchmark-data/data-raw/UCI ML Repository/Metro and\nsaving processed datasets in /home/projects/akita/data/benchmark-data/data-processed\n"
]
],
[
[
"## Dataset transformation and pre-processing",
"_____no_output_____"
]
],
[
[
"train_type = \"unsupervised\"\ntrain_is_normal = False\ninput_type = \"multivariate\"\ndatetime_index = True\ndataset_type = \"real\"\n\n# create target directory\ndataset_subfolder = os.path.join(input_type, dataset_collection_name)\ntarget_subfolder = os.path.join(target_folder, dataset_subfolder)\ntry:\n os.makedirs(target_subfolder)\n print(f\"Created directories {target_subfolder}\")\nexcept FileExistsError:\n print(f\"Directories {target_subfolder} already exist\")\n pass\n\ndm = Datasets(target_folder)",
"Directories /home/projects/akita/data/benchmark-data/data-processed/multivariate/Metro already exist\n"
],
[
"# get target filenames\ndataset_name = \"metro-traffic-volume\"\nfilename = f\"{dataset_name}.test.csv\"\n\nsource_file = source_folder / \"Metro_Interstate_Traffic_Volume.csv\"\npath = os.path.join(dataset_subfolder, filename)\ntarget_filepath = os.path.join(target_subfolder, filename)\n\n# transform file\ndf = pd.read_csv(source_file)\ndf = df[[\"date_time\", \"traffic_volume\", \"temp\", \"rain_1h\", \"snow_1h\", \"clouds_all\", \"holiday\"]].copy()\ndf.insert(0, \"timestamp\", pd.to_datetime(df[\"date_time\"]))\ndf.loc[df[\"holiday\"] == \"None\", \"is_anomaly\"] = 0\ndf.loc[~(df[\"holiday\"] == \"None\"), \"is_anomaly\"] = 1\ndf[\"is_anomaly\"] = df[\"is_anomaly\"].astype(int)\ndf = df.drop(columns=[\"date_time\", \"holiday\"])\ndf.to_csv(target_filepath, index=False)\nprint(f\"Processed source dataset {source_file} -> {target_filepath}\")\n\ndataset_length = len(df)\n\n# save metadata\ndm.add_dataset((dataset_collection_name, dataset_name),\n train_path = None,\n test_path = path,\n dataset_type = dataset_type,\n datetime_index = datetime_index,\n split_at = None,\n train_type = train_type,\n train_is_normal = train_is_normal,\n input_type = input_type,\n dataset_length = dataset_length\n)\n\ndm.save()",
"Processed source dataset /home/projects/akita/data/benchmark-data/data-raw/UCI ML Repository/Metro/Metro_Interstate_Traffic_Volume.csv -> /home/projects/akita/data/benchmark-data/data-processed/multivariate/Metro/metro-traffic-volume.test.csv\n"
],
[
"dm.refresh()\ndm._df.loc[slice(dataset_collection_name, dataset_collection_name)]",
"_____no_output_____"
]
],
[
[
"## Experimentation",
"_____no_output_____"
]
],
[
[
"source_file = source_folder / \"Metro_Interstate_Traffic_Volume.csv\"\ndf = pd.read_csv(source_file)\ndf",
"_____no_output_____"
],
[
"df1 = df[[\"date_time\", \"traffic_volume\", \"temp\", \"rain_1h\", \"snow_1h\", \"clouds_all\", \"holiday\"]].copy()\ndf1.insert(0, \"timestamp\", pd.to_datetime(df1[\"date_time\"]))\ndf1.loc[df1[\"holiday\"] == \"None\", \"is_anomaly\"] = 0\ndf1.loc[~(df1[\"holiday\"] == \"None\"), \"is_anomaly\"] = 1\ndf1[\"is_anomaly\"] = df1[\"is_anomaly\"].astype(int)\ndf1 = df1.drop(columns=[\"date_time\", \"holiday\"])\ndf1",
"_____no_output_____"
],
[
"df1[[\"traffic_volume\", \"temp\", \"rain_1h\", \"snow_1h\", \"clouds_all\"]].plot()\ndf1[\"is_anomaly\"].plot(secondary_y=True)\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4a368eb819a6213be12dcd18b0f24dc1e7876b52
| 19,184 |
ipynb
|
Jupyter Notebook
|
day04/dealing_with_word_embeddings.ipynb
|
neychev/Sber2020_May
|
da5ff391c0fbb72e454e42e8ea1234429b0e83f2
|
[
"MIT"
] | 1 |
2021-11-21T11:20:47.000Z
|
2021-11-21T11:20:47.000Z
|
day04/dealing_with_word_embeddings.ipynb
|
neychev/Sber2020_May
|
da5ff391c0fbb72e454e42e8ea1234429b0e83f2
|
[
"MIT"
] | null | null | null |
day04/dealing_with_word_embeddings.ipynb
|
neychev/Sber2020_May
|
da5ff391c0fbb72e454e42e8ea1234429b0e83f2
|
[
"MIT"
] | 1 |
2020-06-15T21:54:43.000Z
|
2020-06-15T21:54:43.000Z
| 29.199391 | 307 | 0.578294 |
[
[
[
"## Practice: Dealing with Word Embeddings\n\nToday we gonna play with word embeddings: train our own little embedding, load one from gensim model zoo and use it to visualize text corpora.\n\nThis whole thing is gonna happen on top of embedding dataset.\n\n__Requirements:__ `pip install --upgrade nltk gensim bokeh umap-learn` , but only if you're running locally.",
"_____no_output_____"
]
],
[
[
"import itertools\nimport string\n\nimport numpy as np\nimport umap\nfrom nltk.tokenize import WordPunctTokenizer\n\nfrom matplotlib import pyplot as plt\n\nfrom IPython.display import clear_output",
"_____no_output_____"
],
[
"# download the data:\n!wget https://www.dropbox.com/s/obaitrix9jyu84r/quora.txt?dl=1 -O ./quora.txt -nc\n# alternative download link: https://yadi.sk/i/BPQrUu1NaTduEw",
"_____no_output_____"
],
[
"data = list(open(\"./quora.txt\", encoding=\"utf-8\"))\ndata[50]",
"_____no_output_____"
]
],
[
[
"__Tokenization:__ a typical first step for an nlp task is to split raw data into words.\nThe text we're working with is in raw format: with all the punctuation and smiles attached to some words, so a simple str.split won't do.\n\nLet's use __`nltk`__ - a library that handles many nlp tasks like tokenization, stemming or part-of-speech tagging.",
"_____no_output_____"
]
],
[
[
"tokenizer = WordPunctTokenizer()\n\nprint(tokenizer.tokenize(data[50]))",
"_____no_output_____"
],
[
"# TASK: lowercase everything and extract tokens with tokenizer. \n# data_tok should be a list of lists of tokens for each line in data.\n\ndata_tok = # YOUR CODE HEER",
"_____no_output_____"
]
],
[
[
"Let's peek at the result:",
"_____no_output_____"
]
],
[
[
"' '.join(data_tok[0])",
"_____no_output_____"
]
],
[
[
"Small check that everything is alright",
"_____no_output_____"
]
],
[
[
"assert all(isinstance(row, (list, tuple)) for row in data_tok), \"please convert each line into a list of tokens (strings)\"\nassert all(all(isinstance(tok, str) for tok in row) for row in data_tok), \"please convert each line into a list of tokens (strings)\"\nis_latin = lambda tok: all('a' <= x.lower() <= 'z' for x in tok)\nassert all(map(lambda l: not is_latin(l) or l.islower(), map(' '.join, data_tok))), \"please make sure to lowercase the data\"",
"_____no_output_____"
]
],
[
[
"__Word vectors:__ as the saying goes, there's more than one way to train word embeddings. There's Word2Vec and GloVe with different objective functions. Then there's fasttext that uses character-level models to train word embeddings. \n\nThe choice is huge, so let's start someplace small: __gensim__ is another NLP library that features many vector-based models incuding word2vec.",
"_____no_output_____"
]
],
[
[
"from gensim.models import Word2Vec\nmodel = Word2Vec(data_tok, \n size=32, # embedding vector size\n min_count=5, # consider words that occured at least 5 times\n window=5).wv # define context as a 5-word window around the target word",
"_____no_output_____"
],
[
"# now you can get word vectors !\nmodel.get_vector('anything')",
"_____no_output_____"
],
[
"# or query similar words directly. Go play with it!\nmodel.most_similar('bread')",
"_____no_output_____"
]
],
[
[
"### Using pre-trained model\n\nTook it a while, huh? Now imagine training life-sized (100~300D) word embeddings on gigabytes of text: wikipedia articles or twitter posts. \n\nThankfully, nowadays you can get a pre-trained word embedding model in 2 lines of code (no sms required, promise).",
"_____no_output_____"
]
],
[
[
"import gensim.downloader as api\nmodel = api.load('glove-twitter-25')",
"_____no_output_____"
],
[
"model.most_similar(positive=[\"coder\", \"money\"], negative=[\"brain\"])",
"_____no_output_____"
]
],
[
[
"### Visualizing word vectors\n\nOne way to see if our vectors are any good is to plot them. Thing is, those vectors are in 30D+ space and we humans are more used to 2-3D.\n\nLuckily, we machine learners know about __dimensionality reduction__ methods.\n\nLet's use that to plot 1000 most frequent words",
"_____no_output_____"
]
],
[
[
"words = sorted(model.vocab.keys(), \n key=lambda word: model.vocab[word].count,\n reverse=True)[:1000]\n\nprint(words[::100])",
"_____no_output_____"
],
[
"# for each word, compute it's vector with model\nword_vectors = # YOUR CODE",
"_____no_output_____"
],
[
"assert isinstance(word_vectors, np.ndarray)\nassert word_vectors.shape == (len(words), 25)\nassert np.isfinite(word_vectors).all()",
"_____no_output_____"
],
[
"word_vectors.shape",
"_____no_output_____"
]
],
[
[
"#### Linear projection: PCA\n\nThe simplest linear dimensionality reduction method is __P__rincipial __C__omponent __A__nalysis.\n\nIn geometric terms, PCA tries to find axes along which most of the variance occurs. The \"natural\" axes, if you wish.\n\n<img src=\"https://github.com/yandexdataschool/Practical_RL/raw/master/yet_another_week/_resource/pca_fish.png\" style=\"width:30%\">\n\n\nUnder the hood, it attempts to decompose object-feature matrix $X$ into two smaller matrices: $W$ and $\\hat W$ minimizing _mean squared error_:\n\n$$\\|(X W) \\hat{W} - X\\|^2_2 \\to_{W, \\hat{W}} \\min$$\n- $X \\in \\mathbb{R}^{n \\times m}$ - object matrix (**centered**);\n- $W \\in \\mathbb{R}^{m \\times d}$ - matrix of direct transformation;\n- $\\hat{W} \\in \\mathbb{R}^{d \\times m}$ - matrix of reverse transformation;\n- $n$ samples, $m$ original dimensions and $d$ target dimensions;\n\n",
"_____no_output_____"
]
],
[
[
"from sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\npca = PCA(2)\nscaler = StandardScaler()\n# map word vectors onto 2d plane with PCA. Use good old sklearn api (fit, transform)\n# after that, normalize vectors to make sure they have zero mean and unit variance\nword_vectors_pca = # YOUR CODE\n# and maybe MORE OF YOUR CODE here :)",
"_____no_output_____"
],
[
"assert word_vectors_pca.shape == (len(word_vectors), 2), \"there must be a 2d vector for each word\"\nassert max(abs(word_vectors_pca.mean(0))) < 1e-5, \"points must be zero-centered\"\nassert max(abs(1.0 - word_vectors_pca.std(0))) < 1e-2, \"points must have unit variance\"",
"_____no_output_____"
]
],
[
[
"#### Let's draw it!",
"_____no_output_____"
]
],
[
[
"import bokeh.models as bm, bokeh.plotting as pl\nfrom bokeh.io import output_notebook\noutput_notebook()\n\ndef draw_vectors(x, y, radius=10, alpha=0.25, color='blue',\n width=600, height=400, show=True, **kwargs):\n \"\"\" draws an interactive plot for data points with auxilirary info on hover \"\"\"\n if isinstance(color, str): color = [color] * len(x)\n data_source = bm.ColumnDataSource({ 'x' : x, 'y' : y, 'color': color, **kwargs })\n\n fig = pl.figure(active_scroll='wheel_zoom', width=width, height=height)\n fig.scatter('x', 'y', size=radius, color='color', alpha=alpha, source=data_source)\n\n fig.add_tools(bm.HoverTool(tooltips=[(key, \"@\" + key) for key in kwargs.keys()]))\n if show: pl.show(fig)\n return fig",
"_____no_output_____"
],
[
"draw_vectors(word_vectors_pca[:, 0], word_vectors_pca[:, 1], token=words)\n\n# hover a mouse over there and see if you can identify the clusters",
"_____no_output_____"
]
],
[
[
"### Visualizing neighbors with UMAP\nPCA is nice but it's strictly linear and thus only able to capture coarse high-level structure of the data.\n\nIf we instead want to focus on keeping neighboring points near, we could use UMAP, which is itself an embedding method. Here you can read __[more on UMAP (ru)](https://habr.com/ru/company/newprolab/blog/350584/)__ and on __[t-SNE](https://distill.pub/2016/misread-tsne/)__, which is also an embedding.",
"_____no_output_____"
]
],
[
[
"embedding = umap.UMAP(n_neighbors=5).fit_transform(word_vectors) # преобразовываем",
"_____no_output_____"
],
[
"draw_vectors(embedding[:, 0], embedding[:, 1], token=words)\n\n# hover a mouse over there and see if you can identify the clusters",
"_____no_output_____"
]
],
[
[
"### Visualizing phrases\n\nWord embeddings can also be used to represent short phrases. The simplest way is to take __an average__ of vectors for all tokens in the phrase with some weights.\n\nThis trick is useful to identify what data are you working with: find if there are any outliers, clusters or other artefacts.\n\nLet's try this new hammer on our data!\n",
"_____no_output_____"
]
],
[
[
"def get_phrase_embedding(phrase):\n \"\"\"\n Convert phrase to a vector by aggregating it's word embeddings. See description above.\n \"\"\"\n # 1. lowercase phrase\n # 2. tokenize phrase\n # 3. average word vectors for all words in tokenized phrase\n # skip words that are not in model's vocabulary\n # if all words are missing from vocabulary, return zeros\n \n vector = np.zeros([model.vector_size], dtype='float32')\n phrase_tokenized = # YOUR CODE HERE\n phrase_vectors = [model[x] for x in phrase_tokenized if x in model.vocab.keys()]\n\n if len(phrase_vectors) != 0:\n vector = np.mean(phrase_vectors, axis=0)\n\n # YOUR CODE\n \n return vector\n \n ",
"_____no_output_____"
],
[
"get_phrase_embedding(data[402687])",
"_____no_output_____"
],
[
"vector = get_phrase_embedding(\"I'm very sure. This never happened to me before...\")",
"_____no_output_____"
],
[
"# let's only consider ~5k phrases for a first run.\nchosen_phrases = data[::len(data) // 1000]\n\n# compute vectors for chosen phrases and turn them to numpy array\nphrase_vectors = np.asarray([get_phrase_embedding(x) for x in chosen_phrases]) # YOUR CODE",
"_____no_output_____"
],
[
"assert isinstance(phrase_vectors, np.ndarray) and np.isfinite(phrase_vectors).all()\nassert phrase_vectors.shape == (len(chosen_phrases), model.vector_size)",
"_____no_output_____"
],
[
"# map vectors into 2d space with pca, tsne or your other method of choice\n# don't forget to normalize\n\nphrase_vectors_2d = umap.UMAP(n_neighbors=3).fit_transform(phrase_vectors) # преобразовываем\n\n# phrase_vectors_2d = (phrase_vectors_2d - phrase_vectors_2d.mean(axis=0)) / phrase_vectors_2d.std(axis=0)",
"_____no_output_____"
],
[
"draw_vectors(phrase_vectors_2d[:, 0], phrase_vectors_2d[:, 1],\n phrase=[phrase[:50] for phrase in chosen_phrases],\n radius=20,)",
"_____no_output_____"
]
],
[
[
"Finally, let's build a simple \"similar question\" engine with phrase embeddings we've built.",
"_____no_output_____"
]
],
[
[
"# compute vector embedding for all lines in data\ndata_vectors = np.vstack([get_phrase_embedding(l) for l in data])",
"_____no_output_____"
],
[
"norms = np.linalg.norm(data_vectors, axis=1)",
"_____no_output_____"
],
[
"printable_set = set(string.printable)",
"_____no_output_____"
],
[
"data_subset = [x for x in data if set(x).issubset(printable_set)]",
"_____no_output_____"
],
[
"def find_nearest(query, k=10):\n \"\"\"\n given text line (query), return k most similar lines from data, sorted from most to least similar\n similarity should be measured as cosine between query and line embedding vectors\n hint: it's okay to use global variables: data and data_vectors. see also: np.argpartition, np.argsort\n \"\"\"\n # YOUR CODE\n query_vector = get_phrase_embedding(query)\n dists = data_vectors.dot(query_vector[:, None])[:, 0] / ((norms+1e-16)*np.linalg.norm(query_vector))\n nearest_elements = dists.argsort(axis=0)[-k:][::-1]\n out = [data[i] for i in nearest_elements]\n return out# <YOUR CODE: top-k lines starting from most similar>",
"_____no_output_____"
],
[
"results = find_nearest(query=\"How do i enter the matrix?\", k=10)\n\nprint(''.join(results))\n\nassert len(results) == 10 and isinstance(results[0], str)\nassert results[0] == 'How do I get to the dark web?\\n'\n# assert results[3] == 'What can I do to save the world?\\n'",
"_____no_output_____"
],
[
"find_nearest(query=\"How does Trump?\", k=10)",
"_____no_output_____"
],
[
"find_nearest(query=\"Why don't i ask a question myself?\", k=10)",
"_____no_output_____"
],
[
"from sklearn.cluster import DBSCAN, KMeans",
"_____no_output_____"
],
[
"kmeans = KMeans(3)",
"_____no_output_____"
],
[
"labels = kmeans.fit_predict(np.asarray(phrase_vectors))",
"_____no_output_____"
],
[
"plt.figure(figsize=(12, 10))\nplt.scatter(phrase_vectors_2d[:,0], phrase_vectors_2d[:, 1], c=labels.astype(float))",
"_____no_output_____"
]
],
[
[
"__Now what?__\n* Try running TSNE instead of UMAP (it takes a long time)\n* Try running UMAP or TSNEon all data, not just 1000 phrases\n* See what other embeddings are there in the model zoo: `gensim.downloader.info()`\n* Take a look at [FastText](https://github.com/facebookresearch/fastText) embeddings\n* Optimize find_nearest with locality-sensitive hashing: use [nearpy](https://github.com/pixelogik/NearPy) or `sklearn.neighbors`.\n\n\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"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",
"code"
],
[
"markdown"
]
] |
4a3694096aa0edab5eabbee9fca6a6a083f279f8
| 33,830 |
ipynb
|
Jupyter Notebook
|
blackbeard/gesture/gesture_demo.ipynb
|
DevGlitch/jaqen
|
40f5d57b7e9e73848e9af1e623358b20c6bf8fef
|
[
"MIT"
] | 1 |
2022-03-16T19:06:59.000Z
|
2022-03-16T19:06:59.000Z
|
blackbeard/gesture/gesture_demo.ipynb
|
DevGlitch/jaqen
|
40f5d57b7e9e73848e9af1e623358b20c6bf8fef
|
[
"MIT"
] | null | null | null |
blackbeard/gesture/gesture_demo.ipynb
|
DevGlitch/jaqen
|
40f5d57b7e9e73848e9af1e623358b20c6bf8fef
|
[
"MIT"
] | null | null | null | 25.963162 | 124 | 0.518238 |
[
[
[
"import numpy as np\nimport cv2\nimport mediapipe as mp\nimport tensorflow as tf\nimport time\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_hands = mp.solutions.hands",
"_____no_output_____"
],
[
"# load model\ntflite_save_path = 'model/model.tflite'\ninterpreter = tf.lite.Interpreter(model_path=tflite_save_path)\ninterpreter.allocate_tensors()\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n",
"_____no_output_____"
],
[
"def gesture_preprocess(landmark):\n \"\"\"\n convert landmarks for trainable data\n 66 features\n X (21): 0-20\n Y (21): 21-41\n Z (21): 42-62\n X,Y,Z range (3): 63-65\n \n params landmark: mediapipe landmark for 1 hand\n params label: str\n return: np.array (1,66)\n \"\"\" \n lm_x = np.array([])\n lm_y = np.array([])\n lm_z = np.array([])\n for hlm in landmark.landmark:\n lm_x = np.append(lm_x, hlm.x)\n lm_y = np.append(lm_y, hlm.y)\n lm_z = np.append(lm_z, hlm.z)\n data_gest = [lm_x, lm_y, lm_z]\n x_rng, y_rng, z_rng = lm_x.max()-lm_x.min(), lm_y.max()-lm_y.min(), lm_z.max()-lm_z.min()\n data_gest = np.ravel([(k-k.min())/(k.max()-k.min()) for i, k in enumerate(data_gest)])\n data_gest = np.append(data_gest, [x_rng, y_rng, z_rng])\n return data_gest.astype('float32')",
"_____no_output_____"
],
[
"def gesture_inference(data):\n \"\"\"\n inference\n \n param data: np.array\n return: int class\n \"\"\"\n interpreter.set_tensor(input_details[0]['index'], np.array([data]))\n interpreter.invoke()\n tflite_results = interpreter.get_tensor(output_details[0]['index'])\n inf_class_idx = np.argmax(np.squeeze(tflite_results))\n if np.squeeze(tflite_results)[inf_class_idx] < 0.95:\n return 4\n return inf_class_idx",
"_____no_output_____"
],
[
"# For webcam input:\ndetect_time = time.time()\ninf_class = {0: 'Hit', 1: 'Stand', 2: 'Split', 3: 'Reset', 4: 'None'}\ninf_class_idx = 4\n\ncap = cv2.VideoCapture(0)\nwith mp_hands.Hands(\n max_num_hands=1,\n model_complexity=1,\n min_detection_confidence=0.5,\n min_tracking_confidence=0.5) as hands:\n while cap.isOpened(): \n success, image = cap.read()\n if not success:\n print(\"Ignoring empty camera frame.\")\n continue\n # To improve performance, optionally mark the image as not writeable to\n # pass by reference.\n image.flags.writeable = False\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n results = hands.process(image)\n \n # Draw + infer: the hand annotations on the image.\n image.flags.writeable = True\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n if results.multi_hand_landmarks:\n if (time.time() - detect_time) > 0.5:\n print(\"detected hand\")\n for hand_landmarks in results.multi_hand_landmarks:\n # inference\n gest_data = gesture_preprocess(hand_landmarks)\n inf_class_idx = gesture_inference(gest_data)\n\n # draw\n mp_drawing.draw_landmarks(\n image,\n hand_landmarks,\n mp_hands.HAND_CONNECTIONS,\n mp_drawing_styles.get_default_hand_landmarks_style(),\n mp_drawing_styles.get_default_hand_connections_style())\n else:\n detect_time = time.time()\n image_height, image_width, _ = image.shape\n cv2.putText(image, f\"{inf_class[inf_class_idx]}\", (0, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)\n cv2.imshow('MediaPipe Hands', image)\n if cv2.waitKey(5) & 0xFF == 27:\n break\ncap.release()\ncv2.destroyAllWindows()",
"detected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\ndetected hand\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code"
]
] |
4a36a1c473204a0bf4a2789acf87cc527f7bdfec
| 53,947 |
ipynb
|
Jupyter Notebook
|
rome2Rio.ipynb
|
harishPyt/python_scripts_starter
|
92b7b0395ddca4732e88c39382c5fd09509dd4a2
|
[
"MIT"
] | null | null | null |
rome2Rio.ipynb
|
harishPyt/python_scripts_starter
|
92b7b0395ddca4732e88c39382c5fd09509dd4a2
|
[
"MIT"
] | null | null | null |
rome2Rio.ipynb
|
harishPyt/python_scripts_starter
|
92b7b0395ddca4732e88c39382c5fd09509dd4a2
|
[
"MIT"
] | null | null | null | 62.366474 | 2,135 | 0.582405 |
[
[
[
"### Rome2Rio ",
"_____no_output_____"
],
[
"#### Importing packages that are neccessary",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nfrom pymongo import MongoClient\nimport requests as req\nimport json\nfrom itertools import permutations\nimport random\nimport time\nimport json",
"_____no_output_____"
]
],
[
[
"#### All the utility functions are defined below.\n* They can connect to any DB , given that the URI string is given (Including authentication).\n* Return a MongoDB collection given a pymongo database object and a string mentioning the collection name.\n* Pluck - From an array of objects return a list containing the elements of a certain attribute present in the given array.",
"_____no_output_____"
]
],
[
[
"#Defining utility functions over here\n\n# Connect to a database.\ndef connectToDb(uri, dbName):\n client = MongoClient(uri)\n db = client[dbName]\n return db\n\n#Returns a specific collection.\ndef getACollection(db, collectionName):\n return db[collectionName]\n\n# Python Implementation of Underscore - Utiltiy Functions\ndef pluck(array, property):\n return [x[property] for x in array]",
"_____no_output_____"
]
],
[
[
"#### Rome2Rio Main API call.\nTo view the rome2rio search api documentation, [click here](https://www.rome2rio.com/documentation/1-4/search/). \nWhen the api was tested out, we were getting 401 authentication error for few api calls. Not sure as to why though. Sometimes responses comes at the first go, sometimes they don't. That is why we have a retry mechanism with a upper retry count of 50 (Too large a limit. Reduce to 10 or less, if you feel the api fetches responses within few tries.)\n",
"_____no_output_____"
]
],
[
[
"# Rome2Rio - api call and parsing functions\n\n#Get a rome2Rio route and return it as a json\ndef callRome2Rio(oName, dName, oPosLat, oPosLong, dPosLat, dPosLong):\n orgCo = str(oPosLat)+\",\"+str(oPosLong)\n destCo = str(dPosLat)+\",\"+str(dPosLong)\n url = 'http://free.rome2rio.com/api/1.4/json/Search?key=IRlABFW8&oName='+oName+'&dName='+dName+'&oPos='+orgCo+'&dPos='+destCo\n print(\"The url is \", url)\n retryCount = 0\n re = req.get(url)\n data = {}\n stopProcess = False\n if re.status_code==200:\n data = re.json()\n else:\n print(\"Something went wrong. The status we got is \", re.status_code)\n retryPass = False\n while retryPass==False and retryCount < 100:\n retryCount+=1\n print(\"Trying for the \",retryCount,\" time\")\n re = req.get(url)\n if(re.status_code==200):\n retryPass = True\n data = re.json()\n if(re.status_code==444):\n retryPass=True\n print(\"Wrong destination name\");\n data = {}\n if(re.status_code==429):\n retryPass=True\n print(\"Too-Many requests per hour\")\n stopProcess = True\n if(re.status_code==402):\n retryPass=True\n print(\"Payment Required\")\n stopProcess = True\n print(\"Got data in \",retryCount,\" retry/retries\") \n return data, stopProcess\n",
"_____no_output_____"
]
],
[
[
"#### Rome2Rio main parsing function and its corresponding helper functions.",
"_____no_output_____"
]
],
[
[
"#Main Parsing function call. \ndef parse_rome2rio(data, fromCity, toCity,stagingDb): \n \"\"\" This is the main rome2rio parsing functions.\n Inputs: data -> response from rome2rio which needs to be parsed\n fromCity -> City object from pyt database whose name is the fromCity to rome2rio api call.\n toCity -> City object from pyt database whose name is the toCity to rome2rio api call.\n Outputs: parsedJson -> This is the parsed data \n notParseblePreferredRouteCount -> This is the count of routes which cannot be parsed due to missing data etc.\n \"\"\"\n routes = data[\"routes\"]\n vehicles = data[\"vehicles\"]\n places = data[\"places\"]\n airlines = data[\"airlines\"]\n #Zeroth index is always the preferred route w.r.t combination of distance, time and price. Store the rest as alternative routes.\n routeFormed = False\n indexToLook = 0\n preferredRoute = {}\n notParseblePreferredRouteCount = 0\n totalDurationToNotExceed = int(routes[0][\"totalDuration\"]) * 1.5\n while routeFormed!=True:\n if routes[indexToLook][\"totalDuration\"] < totalDurationToNotExceed:\n preferredRoute, routeFormed = formRoute(routes[indexToLook], vehicles, places, airlines, fromCity, toCity)\n if routeFormed!=True:\n if indexToLook < len(routes):\n indexToLook+=1\n notParseblePreferredRouteCount+=1\n else:\n print(\"No route has an indicative price for \", fromCity[\"name\"], \" and \", toCity[\"name\"], \"route\")\n notParseblePreferredRouteCount+=1\n else:\n #Try to get the preferredRoute from city connection database.\n preferredRoute, routeFormed = getExistingCityConnection(fromCity, toCity, stagingDb)\n if routeFormed!=True:\n print(\"We can't form a viable route for\", fromCity[\"name\"], \" and \", toCity[\"name\"])\n routeFormed=True\n alternateRoutes = []\n for route in routes[1:]:\n routeJson, routeFormed = formRoute(route, vehicles, places, airlines, fromCity, toCity)\n alternateRoutes.append(routeJson)\n parsedJson = {\n \"fromCity\": fromCity[\"planningid\"],\n \"toCity\": toCity[\"planningid\"],\n \"preferredRoute\": preferredRoute,\n \"alternateRoutes\": alternateRoutes,\n \"timestamp\": time.time()\n }\n # Need to compute cost function for each preferred route\n return parsedJson, notParseblePreferredRouteCount\n#--------------------------------------------------------------------------------------------------------------------#\n## Forming route \ndef formRoute(route, vehicles, places, airlines, fromCity, toCity):\n \"\"\" This a part of parsing function where i take an individual route option and form my desired JSON structure.\n Inputs: route - Route for which i need to parse into my desired structure. (This can be a preferred route or an alternate route. Both have same structure)\n vehicles - Array that contains all vehicle types\n places - Array that contains all places within the fromCity and toCity that a route can traverse. This is for all routes\n airlines - Array that contains all airlines that ply within the 2 cities.\n Outputs: routeJson - My desired JSON Structure\n routeFormed - Boolean that returns True if desired structure is formed and False if not.\n \"\"\"\n routeFormed = False\n allSegments = route[\"segments\"]\n try:\n routePrice = getPrice(route[\"indicativePrices\"], route[\"name\"])\n except KeyError:\n routeFormed = False\n return {}, routeFormed\n preferredMode,flights, trains, bus, car, transfers = parseSegment(route[\"name\"], allSegments, vehicles, places, airlines)\n routeJson = {\n \"title\": route[\"name\"],\n \"fromCity\": fromCity[\"planningid\"],\n \"toCity\": toCity[\"planningid\"],\n \"totalDuration\": route[\"totalDuration\"],\n \"transitDuration\": route[\"totalTransitDuration\"],\n \"transferDuration\": route[\"totalTransferDuration\"],\n \"allPrice\": route[\"indicativePrices\"],\n \"price\": routePrice,\n \"currencyCode\": route[\"indicativePrices\"][0][\"currency\"],\n \"preferredMode\": list(set(preferredMode)),\n \"flights\": flights,\n \"trains\": trains,\n \"bus\": bus,\n \"car\": car,\n \"transfers\": transfers\n }\n routeFormed = True\n return routeJson, routeFormed\n#---------------------------------------------------------------------------------------------------------------------#\n#Parsing Segment.\ndef parseSegment(routeName, allSegments, vehicles, places, airlines):\n \"\"\" Given all segments within a route, parse it into my desired JSON Structure.\n Inputs: routeName -> String, that tells me as to the nature of mode of transport (Fly to some place, Train, rideshare etc..)\n allSegments -> Segment array that i need to parse\n vehicles - Array that contains all vehicle types\n places - Array that contains all places within the fromCity and toCity that a route can traverse. This is for all routes\n airlines - Array that contains all airlines that ply within the 2 cities.\n Outputs: preferredMode: contains an array of preferred mode of travel (that covers majority of the distance)\n flights: contains an array of flights in my desired format present within the route, empty if there isn't\n trains: contains an array of trains in my desired format present within the route, empty if there isn't.\n bus: contains an array of bus in my desired format present within the route, empty if there isn't.\n car: contains an array of flights in my desired format present within the route, empty if there isn't.\n transfers: contains an array of transfers in my desired format present within the route, empty if there isn't(Transfers cover for small distances and it can be in BUS, CAR or TRAIN)\n \"\"\"\n flights= []\n trains=[]\n bus=[]\n cars=[]\n transfers=[]\n preferredMode=[]\n isAirSegment=False\n car_types = [\"rideshare\", \"car\", \"shuttle\", \"taxi\", \"towncar\"]\n for segment in allSegments:\n depPlaceKeys = list(places[segment[\"depPlace\"]])\n arrPlaceKeys = list(places[segment[\"arrPlace\"]])\n segmentKeys = list(segment.keys())\n if segment[\"segmentKind\"] == \"air\":\n #This has flight data.\n preferredMode.append(\"flight\")\n for flightOption in segment[\"outbound\"]:\n assert places[segment[\"arrPlace\"]][\"kind\"]==\"airport\" \n flight = {\n \"vehicleType\": \"FLIGHT\",\n \"depCountryCode\": places[segment[\"depPlace\"]][\"countryCode\"],\n \"arrCountryCode\": places[segment[\"arrPlace\"]][\"countryCode\"],\n \"noOfStops\": len(flightOption[\"hops\"])-1,\n \"operatingDays\": flightOption[\"operatingDays\"],\n \"indicativePrice\": flightOption[\"indicativePrices\"][0][\"price\"],\n \"indicativeMaxPrice\": flightOption[\"indicativePrices\"][0][\"priceHigh\"],\n \"indicativeMinPrice\": flightOption[\"indicativePrices\"][0][\"priceLow\"],\n \"currencyCode\": flightOption[\"indicativePrices\"][0][\"currency\"],\n \"distance\": segment[\"distance\"],\n \"transitDuration\": segment[\"transitDuration\"],\n \"transferDuration\": segment[\"transferDuration\"],\n \"totalDuration\": segment[\"transitDuration\"] + segment[\"transferDuration\"]\n }\n if \"code\" in depPlaceKeys:\n flight[\"depAirportCode\"] = places[segment[\"depPlace\"]][\"code\"]\n if \"code\" in arrPlaceKeys:\n flight[\"arrAirportCode\"] = places[segment[\"arrPlace\"]][\"code\"]\n flights.append(flight)\n else:\n #This includes surface data (either train, bus, car. also check for comma as it indicates multiple modes of transport) \n if vehicles[segment[\"vehicle\"]][\"kind\"]==\"bus\":\n busSegment = {\n \"vehicleType\": \"BUS\", \n \"depPlaceCountryCode\": places[segment[\"depPlace\"]][\"countryCode\"],\n \"depPlaceTitle\": places[segment[\"depPlace\"]][\"shortName\"], \n \"arrPlaceCountryCode\": places[segment[\"arrPlace\"]][\"countryCode\"],\n \"arrPlaceTitle\": places[segment[\"arrPlace\"]][\"shortName\"],\n \"distance\": segment[\"distance\"], \n \"transitDuration\": segment[\"transitDuration\"],\n \"transferDuration\": segment[\"transferDuration\"],\n \"totalDuration\": segment[\"transitDuration\"] + segment[\"transferDuration\"]\n }\n if \"code\" in depPlaceKeys:\n busSegment[\"depPlaceCode\"] = places[segment[\"depPlace\"]][\"code\"]\n if \"code\" in arrPlaceKeys:\n busSegment[\"arrPlaceCode\"] = places[segment[\"arrPlace\"]][\"code\"]\n if \"indicativePrices\" in segmentKeys:\n busSegment[\"allPrices\"] = segment[\"indicativePrices\"]\n busSegment[\"indicativePrice\"] = segment[\"indicativePrices\"][0][\"price\"]\n busSegment[\"currencyCode\"] = segment[\"indicativePrices\"][0][\"currency\"]\n #It can be a primary mode of transport or transfer.\n if \"bus\" in routeName.lower():\n preferredMode.append(\"bus\")\n bus.append(busSegment)\n else:\n transfers.append(busSegment)\n \n if vehicles[segment[\"vehicle\"]][\"kind\"] == \"train\":\n trainSegment = {\n \"vehicleType\": \"TRAIN\",\n \"depPlaceCountryCode\": places[segment[\"depPlace\"]][\"countryCode\"],\n \"depPlaceTitle\": places[segment[\"depPlace\"]][\"shortName\"],\n \"arrPlaceCountryCode\": places[segment[\"arrPlace\"]][\"countryCode\"],\n \"arrPlaceTitle\": places[segment[\"arrPlace\"]][\"shortName\"],\n \"distance\": segment[\"distance\"],\n \"transitDuration\": segment[\"transitDuration\"],\n \"transferDuration\": segment[\"transferDuration\"],\n \"totalDuration\": segment[\"transitDuration\"] + segment[\"transferDuration\"]\n }\n if vehicles[segment[\"vehicle\"]][\"name\"]!=\"RER\" and \"indicativePrices\" in segmentKeys:\n if \"priceHigh\" in list(segment[\"indicativePrices\"][0].keys()):\n trainSegment[\"indicativeMaxPrice\"] = segment[\"indicativePrices\"][0][\"priceHigh\"]\n if \"priceLow\" in list(segment[\"indicativePrices\"][0].keys()):\n trainSegment[\"indicativeMinPrice\"] = segment[\"indicativePrices\"][0][\"priceLow\"]\n if \"code\" in depPlaceKeys:\n trainSegment[\"depPlaceCode\"] = places[segment[\"depPlace\"]][\"code\"]\n if \"code\" in arrPlaceKeys:\n trainSegment[\"arrPlaceCode\"] = places[segment[\"arrPlace\"]][\"code\"]\n if \"indicativePrices\" in segmentKeys:\n trainSegment[\"allPrices\"] = segment[\"indicativePrices\"]\n trainSegment[\"indicativePrice\"] = segment[\"indicativePrices\"][0][\"price\"]\n trainSegment[\"currencyCode\"] = segment[\"indicativePrices\"][0][\"currency\"]\n if \"train\" in routeName.lower():\n preferredMode.append(\"train\")\n trains.append(trainSegment)\n else:\n transfers.append(trainSegment)\n if vehicles[segment[\"vehicle\"]][\"kind\"] == \"car\":\n carSegment = {\n \"vehicleType\": \"CAR\",\n \"depPlaceTitle\": places[segment[\"depPlace\"]][\"shortName\"],\n \"arrPlaceTitle\": places[segment[\"arrPlace\"]][\"shortName\"],\n \"distance\": segment[\"distance\"],\n \"transitDuration\": segment[\"transitDuration\"],\n \"transferDuration\": segment[\"transferDuration\"],\n \"totalDuration\": segment[\"transitDuration\"] + segment[\"transferDuration\"]\n }\n if \"regionCode\" in depPlaceKeys:\n carSegment[\"depPlaceCode\"] = places[segment[\"depPlace\"]][\"regionCode\"]\n if \"regionCode\" in arrPlaceKeys:\n carSegment[\"arrPlaceCode\"] = places[segment[\"arrPlace\"]][\"regionCode\"]\n if \"indicativePrices\" in segmentKeys:\n carSegment[\"allPrices\"] = segment[\"indicativePrices\"]\n carSegment[\"currencyCode\"] = segment[\"indicativePrices\"][0][\"currency\"]\n if \"countryCode\" in depPlaceKeys:\n carSegment[\"depPlaceCountryCode\"] = places[segment[\"depPlace\"]][\"countryCode\"]\n if \"countryCode\" in arrPlaceKeys:\n carSegment[\"arrPlaceCountryCode\"] = places[segment[\"arrPlace\"]][\"countryCode\"]\n if \"drive\" in routeName.lower():\n preferredMode.append(\"car\")\n cars.append(carSegment)\n else:\n transfers.append(carSegment)\n return preferredMode, flights, trains, bus, cars, transfers\n#-------------------------------------------------------------------------------------------------------------------#\n#Parsing price\ndef getPrice(indicativePrice, routeName):\n \"\"\" Returns price object if there is a median, max and min price available , else returns indicativePrice as it is.\n There is no max or min price if the mode of transport is one of the car_types.\n Inputs: indicativePrice -> Array that contains an indicative price for the route.\n routeName -> Used to figure out the mode of transport. \n Output: A curated JSON containing the indicative price or the input indicativePrice array.\n \n \"\"\"\n car_types = [\"rideshare\", \"car\", \"shuttle\", \"taxi\", \"towncar\", \"drive\"]\n if routeName.lower() in car_types:\n return indicativePrice\n else:\n return {\n \"indicativeMedianPrice\": indicativePrice[0][\"price\"],\n \"indicativeMaxPrice\": indicativePrice[0][\"priceHigh\"],\n \"indicativeMinPrice\": indicativePrice[0][\"priceLow\"],\n \"currencyCode\": indicativePrice[0][\"currency\"]\n }",
"_____no_output_____"
],
[
"def getExistingCityConnection(fromCity, toCity, db):\n cityConn = getACollection(db, 'city_connection')\n connection = cityConn.find_one({\"fromCity\": fromCity[\"planningid\"], \"toCity\": toCity[\"planningid\"]})\n print(connection)\n if connection != None and \"_id\" in list(connection.keys()):\n return connection, True\n else:\n return {}, False\n ",
"_____no_output_____"
],
[
"def getAllEuropeanCities(db):\n \"\"\"Returns all European cities present in the database.\"\"\"\n region = getACollection(db, 'searchregion')\n europeanCountries = region.find_one({\"regionCode\": \"eur\"}, {\"countryIds\": 1})[\"countryIds\"]\n country = getACollection(db, 'country')\n europeanCountriesData = country.find({\"countryId\": {\"$in\": europeanCountries}})\n countryCodes = []\n for country in europeanCountriesData:\n countryCodes.append(country[\"countryCode\"])\n city = getACollection(db, 'city')\n europeanCities = city.find({\"countryCode\": {\"$in\": countryCodes}})\n return europeanCities\n",
"_____no_output_____"
],
[
"local = connectToDb(\"mongodb://oceanjar:wwmib3112@localhost:27017/localDb?authMechanism=SCRAM-SHA-1\", \"localDb\")",
"_____no_output_____"
]
],
[
[
"## Rome2Rio Execution Starts here",
"_____no_output_____"
]
],
[
[
"db=connectToDb(\"mongodb://oceanjardb:oceanjardbwwmib3112#@35.154.159.75:27017/oceanjar?authMechanism=MONGODB-CR\", \"oceanjar\")\neuropeanCities = getAllEuropeanCities(db)\neuropeanCitiesMap = {}\nrouteNotPresentCities = []\nfor city in europeanCities:\n europeanCitiesMap[city[\"planningid\"]] = city\n isRoutePresent = checkIfRoutePresent(city, db)\n if isRoutePresent!=True:\n routeNotPresentCities.append(city)\ndefaultResponseTemplates=[]\nfor city1 in routeNotPresentCities and len(routeNotPresentCities) > 0:\n for city2 in list(europeanCitiesMap.keys()):\n if city1!=city2:\n responseTemplate1 = {\n \"fromCity\": europeanCitiesMap[city1],\n \"toCity\": europeanCitiesMap[city2],\n \"response\": {}\n }\n responseTemplate2 = {\n \"fromCity\": europeanCitiesMap[city2],\n \"toCity\": europeanCitiesMap[city1],\n \"response\": {}\n }\n defaultResponseTemplates.append(responseTemplate1)\n defaultResponseTemplates.append(responseTemplate2)\nprint(\"length\", len(defaultResponseTemplates))\n#write_to_db(db, defaultResponseTemplates)\n\n",
"length 0\n"
],
[
"def checkIfRoutePresent(city, db):\n rome2rio = getACollection(db, 'rome2rioResponses')\n route = rome2rio.find_one({\"fromCity.planningid\": city[\"planningid\"]})\n if route!=None and \"routes\" in \"routes\" not in list(route[\"response\"].keys()):\n return True\n else:\n return False",
"_____no_output_____"
],
[
"#Testing out for 10 cities.\nsample_cities = []\nall_keys = list(europeanCitiesMap.keys())\nfor i in range(1,11):\n sample_cities.append(random.choice(all_keys))\n",
"_____no_output_____"
],
[
"def write_to_db(db, arr):\n r2r = getACollection(db, 'rome2rioResponses')\n result = r2r.insert_many(arr)\n try:\n assert len(result.inserted_ids) == len(arr)\n except AssertionError:\n print(\"There is a mis-match in the number of documents inserted\", len(result.inserted_ids), len(arr))\n return None",
"_____no_output_____"
],
[
"total_count = 0\nstart_time = time.time()\ntotal_api_call_time = 0\nparsedResponses = []\nfor city1 in list(europeanCitiesMap.keys())[0:5]:\n for city2 in list(europeanCitiesMap.keys())[0:5]:\n if city1!=city2:\n total_count+=1\n originCity = europeanCitiesMap[city1]\n destCity = europeanCitiesMap[city2]\n apiStTime = time.time()\n r2rResponse = callRome2Rio(originCity[\"name\"], destCity[\"name\"], originCity[\"latitude\"], originCity[\"longitude\"], destCity[\"latitude\"], destCity[\"longitude\"])\n r2rResponse[\"fromCityId\"] = originCity[\"planningid\"]\n r2rResponse[\"toCityId\"] = destCity[\"planningid\"]\n apiTime = time.time() - apiStTime\n total_api_call_time+=apiTime\n parsedResponses.append(r2rResponse)\n time.sleep(2)\nelapsed_time = time.time() - start_time\nprint(\"----Total Count is \", total_count, \"it is completed in \", elapsed_time ,\" seconds\")\nprint(\"-------Writing to database------------\")\nwrite_to_db(local, parsedResponses)\n",
"The url is http://free.rome2rio.com/api/1.4/json/Search?key=V67gPjlQ&oName=Padova&dName=Pisa&oPos=45.4064826965332,11.882489204406738&dPos=43.72283935546875,10.401689529418945\nSomething went wrong. The status we got is 401\nTrying for the 1 time\nTrying for the 2 time\nTrying for the 3 time\nTrying for the 4 time\nTrying for the 5 time\nTrying for the 6 time\nTrying for the 7 time\nTrying for the 8 time\nTrying for the 9 time\nTrying for the 10 time\nTrying for the 11 time\nTrying for the 12 time\nTrying for the 13 time\nTrying for the 14 time\nTrying for the 15 time\nTrying for the 16 time\nTrying for the 17 time\nTrying for the 18 time\nTrying for the 19 time\nTrying for the 20 time\nTrying for the 21 time\nTrying for the 22 time\nTrying for the 23 time\nTrying for the 24 time\nTrying for the 25 time\nTrying for the 26 time\nTrying for the 27 time\n"
],
[
"getExistingCityConnection({\"planningid\": 4}, {\"planningid\": 14}, db)",
"{'_id': ObjectId('58981ddecd9e4fa4a48b3bcf'), 'fromCity': 4.0, 'toCity': 14.0, 'directConnection': {'defaultConnection': {'mode': 'FLIGHT', 'travelTime': 85.0, 'transferType': 'SHARED', 'availability': 'MORNING', 'lcc': True, 'stops': 0.0, 'slot': 'MORNING_NOON'}, 'selfDrive': False, 'geographyFactor': 1.0}, 'geographyFactor': 1.0}\n"
],
[
"setResponse = []\nfor resp in parsedResponses:\n resp[\"preferredRoute\"][\"preferredMode\"] = list(set(resp[\"preferredRoute\"][\"preferredMode\"]))\n for alt in resp[\"alternateRoutes\"]:\n alt[\"preferredMode\"] = list(set(alt[\"preferredMode\"]))\n setResponse.append(resp)",
"_____no_output_____"
],
[
"print(\"API time\", total_api_call_time, \"Parsing time \", total_parsing_time)",
"API time 342.87971591949463 Parsing time 0.05852317810058594\n"
],
[
"print()",
"_____no_output_____"
],
[
"# Problems to be solved \n# 1. Identify whether a train/bus/car segment is a transfer if the preferred route is also the same.\n# 2. How to reduce API time. -> (parallelization is not supported by rome2rio. Do we need to explore more on this option ?)\n# 3. Sho\n",
"_____no_output_____"
],
[
"defaultResponseTemplates=[]\ncount=0\nfor city1 in list(europeanCitiesMap.keys()):\n for city2 in list(europeanCitiesMap.keys()):\n if city1!=city2:\n count+=1\n responseTemplate = {\n \"fromCity\": europeanCitiesMap[city1],\n \"toCity\": europeanCitiesMap[city2],\n \"response\": {}\n }\n defaultResponseTemplates.append(responseTemplate)",
"_____no_output_____"
],
[
"print(len(defaultResponseTemplates))",
"28730\n"
],
[
"write_to_db(local, defaultResponseTemplates)",
"_____no_output_____"
],
[
"print(len(list(europeanCitiesMap.keys())))",
"170\n"
],
[
"for i in range(1, 10):\n print(i)\n if i==4:\n break",
"1\n2\n3\n4\n"
],
[
"import logging",
"_____no_output_____"
],
[
"r2r = getACollection(local, 'rome2rioResponses')\nr2rAll = r2r.find()\ndata = []\nfor r in r2rAll:\n data.append(r)\nwrite_to_db(db, data)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a36e81ede551ea33108a129e3a63836ca392f2c
| 142,107 |
ipynb
|
Jupyter Notebook
|
course2/REG01-NB01.ipynb
|
Aafaaq77/machineLearningCoursera
|
7f00b8d8d29b59aa8ed9c365c86698acd48693ab
|
[
"MIT"
] | null | null | null |
course2/REG01-NB01.ipynb
|
Aafaaq77/machineLearningCoursera
|
7f00b8d8d29b59aa8ed9c365c86698acd48693ab
|
[
"MIT"
] | null | null | null |
course2/REG01-NB01.ipynb
|
Aafaaq77/machineLearningCoursera
|
7f00b8d8d29b59aa8ed9c365c86698acd48693ab
|
[
"MIT"
] | null | null | null | 85.196043 | 87,370 | 0.744172 |
[
[
[
"# Regression Week 1: Simple Linear Regression",
"_____no_output_____"
],
[
"In this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. You will:\n* Use Turi Create SArray and SFrame functions to compute important summary statistics (instead using Pandas and sklearn)\n* Write a function to compute the Simple Linear Regression weights using the closed form solution\n* Write a function to make predictions of the output given the input feature\n* Turn the regression around to predict the input given the output\n* Compare two different models for predicting house prices\n\n",
"_____no_output_____"
],
[
"### Importing the necessary libraries",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
]
],
[
[
"# Load house sales data\n\nDataset is from house sales in King County, the region where the city of Seattle, WA is located.",
"_____no_output_____"
]
],
[
[
"dtype_dict = {'bathrooms':float, 'waterfront':int, 'sqft_above':int, \n 'sqft_living15':float, 'grade':int, 'yr_renovated':int, \n 'price':float, 'bedrooms':float, 'zipcode':str, 'long':float, \n 'sqft_lot15':float, 'sqft_living':float, 'floors':str, \n 'condition':int, 'lat':float, 'date':str, 'sqft_basement':int, \n 'yr_built':int, 'id':str, 'sqft_lot':int, 'view':int}\nsales = pd.read_csv('kc_house_data.csv', dtype=dtype_dict, index_col=0)\nsales.head()",
"_____no_output_____"
],
[
"sales.dtypes",
"_____no_output_____"
]
],
[
[
"Relation between living area of house and it's price",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(figsize=(9, 7))\nsns.scatterplot(ax = ax, data=sales, x='sqft_living', y='price', hue='floors')",
"_____no_output_____"
]
],
[
[
"# Split data into training and testing",
"_____no_output_____"
],
[
"We use seed=0 so that everyone running this notebook gets the same results. In practice, you may set a random seed (or let Turi Create pick a random seed for you). ",
"_____no_output_____"
]
],
[
[
"# normally\n# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n# but for the quiz I will be using the training and testing data provided\ntrain_data = pd.read_csv('kc_house_train_data.csv', dtype=dtype_dict, index_col=0)\ntrain_data.head()",
"_____no_output_____"
],
[
"test_data = pd.read_csv('kc_house_test_data.csv', dtype=dtype_dict, index_col=0)\ntest_data.head()",
"_____no_output_____"
]
],
[
[
"# Useful SFrame summary functions",
"_____no_output_____"
],
[
"In order to make use of the closed form solution as well as take advantage of turi create's built in functions we will review some important ones. In particular:\n* Computing the sum of an SArray\n* Computing the arithmetic average (mean) of an SArray\n* multiplying SArrays by constants\n* multiplying SArrays by other SArrays\n\n(*) I will be using pandas instead and not turi create as mentioned in the course",
"_____no_output_____"
]
],
[
[
"# Let's compute the mean of the House Prices in King County in 2 different ways.\nprices = sales['price'] # extract the price column of the sales SFrame -- this is now a (pd.Series)\n\n# recall that the arithmetic average (the mean) is the sum of the prices divided by the total number of houses:\nsum_prices = prices.sum()\nnum_houses = len(prices)\navg_price_1 = sum_prices/num_houses\navg_price_2 = prices.mean() # if you just want the average, the .mean() function\nprint(\"average price via method 1: \" + str(avg_price_1))\nprint(\"average price via method 2: \" + str(avg_price_2))",
"average price via method 1: 540088.1417665294\naverage price via method 2: 540088.1417665294\n"
]
],
[
[
"As we see we get the same answer both ways",
"_____no_output_____"
]
],
[
[
"# or\nsales['price'].mean()",
"_____no_output_____"
],
[
"# Let's compute the sum of squares of price\nprices_squared = prices*prices\nsum_prices_squared = prices_squared.sum()\nprint(f\"the sum of price squared is: {sum_prices_squared}\")",
"the sum of price squared is: 9217325138472070.0\n"
]
],
[
[
"Aside: The python notation x.xxe+yy means x.xx \\* 10^(yy). e.g 100 = 10^2 = 1*10^2 = 1e2 ",
"_____no_output_____"
],
[
"# Build a generic simple linear regression function ",
"_____no_output_____"
],
[
"\nComplete the following function (or write your own) to compute the simple linear regression slope and intercept:",
"_____no_output_____"
],
[
"numerator = (mean of X * Y) - (mean of X)*(mean of Y)\n\ndenominator = (mean of X^2) - (mean of X)*(mean of X)\n\nintercept = (mean of Y) - slope * (mean of X)",
"_____no_output_____"
]
],
[
[
"def simple_linear_regression(input_feature, output):\n x_mean = input_feature.mean()\n y_mean = output.mean()\n x_y_mean = (input_feature * output).mean()\n x_square_mean = np.square(input_feature).mean()\n\n slope = (x_y_mean - (x_mean * y_mean)) / (x_square_mean - (x_mean * x_mean))\n\n\n intercept = y_mean - (slope*x_mean)\n return (intercept, slope)",
"_____no_output_____"
]
],
[
[
"We can test that our function works by passing it something where we know the answer. In particular we can generate a feature and then put the output exactly on a line: output = 1 + 1\\*input_feature then we know both our slope and intercept should be 1",
"_____no_output_____"
]
],
[
[
"test_feature = np.arange(5)\ntest_output = 1 + 1*test_feature\n(test_intercept, test_slope) = simple_linear_regression(test_feature, test_output)\nprint(f'Intercept: {test_intercept}')\nprint(f'Slope: {test_slope}')",
"Intercept: 1.0\nSlope: 1.0\n"
]
],
[
[
"Now that we know it works let's build a regression model for predicting price based on sqft_living. Rembember that we train on train_data!",
"_____no_output_____"
]
],
[
[
"sqft_intercept, sqft_slope = simple_linear_regression(train_data['sqft_living'], train_data['price'])\n\nprint(f\"Intercept: {sqft_intercept}\")\nprint(f\"Slope: {sqft_slope}\")",
"Intercept: -47116.07907289488\nSlope: 281.95883963034294\n"
]
],
[
[
"# Predicting Values",
"_____no_output_____"
],
[
"Now that we have the model parameters: intercept & slope we can make predictions. Using SArrays it's easy to multiply an SArray by a constant and add a constant value. Complete the following function to return the predicted output given the input_feature, slope and intercept:",
"_____no_output_____"
]
],
[
[
"def get_regression_predictions(input_feature, intercept, slope):\n # calculate the predicted values:\n predicted_values = slope*input_feature + intercept\n return predicted_values",
"_____no_output_____"
]
],
[
[
"Now that we can calculate a prediction given the slope and intercept let's make a prediction. Use (or alter) the following to find out the estimated price for a house with 2650 squarefeet according to the squarefeet model we estiamted above.\n\n**Quiz Question: Using your Slope and Intercept from (4), What is the predicted price for a house with 2650 sqft?**",
"_____no_output_____"
]
],
[
[
"my_house_sqft = 2650\nestimated_price = get_regression_predictions(my_house_sqft, sqft_intercept, sqft_slope)\nprint(f\"The estimated price for a house with {my_house_sqft} squarefeet is {estimated_price:.2f}\")",
"The estimated price for a house with 2650 squarefeet is 700074.85\n"
]
],
[
[
"# Residual Sum of Squares",
"_____no_output_____"
],
[
"Now that we have a model and can make predictions let's evaluate our model using Residual Sum of Squares (RSS). Recall that RSS is the sum of the squares of the residuals and the residuals is just a fancy word for the difference between the predicted output and the true output. \n\nComplete the following (or write your own) function to compute the RSS of a simple linear regression model given the input_feature, output, intercept and slope:",
"_____no_output_____"
]
],
[
[
"def get_residual_sum_of_squares(input_feature, output, intercept, slope):\n\n predictions = get_regression_predictions(input_feature, intercept, slope)\n diff = output - predictions\n squared = diff * diff\n RSS = squared.sum()\n\n return(RSS)",
"_____no_output_____"
]
],
[
[
"Let's test our get_residual_sum_of_squares function by applying it to the test model where the data lie exactly on a line. Since they lie exactly on a line the residual sum of squares should be zero!",
"_____no_output_____"
]
],
[
[
"print(get_residual_sum_of_squares(test_feature, test_output, test_intercept, test_slope))# should be 0.0",
"0.0\n"
]
],
[
[
"Now use your function to calculate the RSS on training data from the squarefeet model calculated above.\n\n**Quiz Question: According to this function and the slope and intercept from the squarefeet model What is the RSS for the simple linear regression using squarefeet to predict prices on TRAINING data?**",
"_____no_output_____"
]
],
[
[
"rss_prices_on_sqft = get_residual_sum_of_squares(train_data['sqft_living'], train_data['price'], sqft_intercept, sqft_slope)\nprint(f'The RSS of predicting Prices based on Square Feet is: {rss_prices_on_sqft}')",
"The RSS of predicting Prices based on Square Feet is: 1201918354177283.0\n"
]
],
[
[
"# Predict the squarefeet given price",
"_____no_output_____"
],
[
"What if we want to predict the squarefoot given the price? Since we have an equation y = a + b\\*x we can solve the function for x. So that if we have the intercept (a) and the slope (b) and the price (y) we can solve for the estimated squarefeet (x).\n\nComplete the following function to compute the inverse regression estimate, i.e. predict the input_feature given the output.",
"_____no_output_____"
]
],
[
[
"def inverse_regression_predictions(output, intercept, slope):\n \n estimated_feature = (output - intercept) / slope\n return estimated_feature",
"_____no_output_____"
]
],
[
[
"Now that we have a function to compute the squarefeet given the price from our simple regression model let's see how big we might expect a house that costs $800,000 to be.\n\n**Quiz Question: According to this function and the regression slope and intercept from (3) what is the estimated square-feet for a house costing $800,000?**",
"_____no_output_____"
]
],
[
[
"my_house_price = 800000\nestimated_squarefeet = inverse_regression_predictions(my_house_price, sqft_intercept, sqft_slope)\nprint(f\"The estimated squarefeet for a house worth {my_house_price:.2f} is {estimated_squarefeet}\")",
"The estimated squarefeet for a house worth 800000.00 is 3004.3962451522752\n"
]
],
[
[
"# New Model: estimate prices from bedrooms",
"_____no_output_____"
],
[
"We have made one model for predicting house prices using squarefeet, but there are many other features in the sales Data. \nUse your simple linear regression function to estimate the regression parameters from predicting Prices based on number of bedrooms. Use the training data!",
"_____no_output_____"
]
],
[
[
"# Estimate the slope and intercept for predicting 'price' based on 'bedrooms'\nbeds_intercept, beds_slope = simple_linear_regression(train_data['bedrooms'], train_data['price'])\nprint(f'Slope: {beds_slope}, intercept: {beds_intercept}')",
"Slope: 127588.95293398833, intercept: 109473.17762295791\n"
]
],
[
[
"# Test your Linear Regression Algorithm",
"_____no_output_____"
],
[
"Now we have two models for predicting the price of a house. How do we know which one is better? Calculate the RSS on the TEST data (remember this data wasn't involved in learning the model). Compute the RSS from predicting prices using bedrooms and from predicting prices using squarefeet.\n\n**Quiz Question: Which model (square feet or bedrooms) has lowest RSS on TEST data? Think about why this might be the case.**",
"_____no_output_____"
]
],
[
[
"# Compute RSS when using bedrooms on TEST data:\nrss_prices_on_beds = get_residual_sum_of_squares(test_data['bedrooms'], test_data['price'], beds_intercept, beds_slope)\nprint(f'The RSS of predicting Prices based on Square Feet is: {rss_prices_on_beds}')",
"The RSS of predicting Prices based on Square Feet is: 493364585960301.0\n"
],
[
"# Compute RSS when using squarefeet on TEST data:\nrss_prices_on_sqft = get_residual_sum_of_squares(test_data['sqft_living'], test_data['price'], sqft_intercept, sqft_slope)\nprint(f'The RSS of predicting Prices based on Square Feet is: {rss_prices_on_sqft}')",
"The RSS of predicting Prices based on Square Feet is: 275402933617812.16\n"
],
[
"rss_prices_on_beds > rss_prices_on_sqft",
"_____no_output_____"
],
[
"rss_prices_on_sqft / test_data.shape[0]",
"_____no_output_____"
],
[
"from sklearn.metrics import mean_squared_error",
"_____no_output_____"
],
[
"mean_squared_error(test_data['price'], get_regression_predictions(test_data['sqft_living'], sqft_intercept, sqft_slope))",
"_____no_output_____"
]
],
[
[
"## Comparing with sklearn",
"_____no_output_____"
]
],
[
[
"simple_model = LinearRegression()\nsimple_model.fit(train_data[['sqft_living']], train_data['price'])",
"_____no_output_____"
],
[
"preds = simple_model.predict(test_data[['sqft_living']])",
"_____no_output_____"
],
[
"mean_squared_error(test_data['price'], preds)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4a3703414408264c47f1395bea6dfea689b67412
| 134,062 |
ipynb
|
Jupyter Notebook
|
IA_NN_classificacaobinaria_keras.ipynb
|
TerradasExatas/Introdu-o-IA-e-Machine-Learning
|
243a599bde920768df995f9778c78b3ab1ae9e30
|
[
"MIT"
] | null | null | null |
IA_NN_classificacaobinaria_keras.ipynb
|
TerradasExatas/Introdu-o-IA-e-Machine-Learning
|
243a599bde920768df995f9778c78b3ab1ae9e30
|
[
"MIT"
] | null | null | null |
IA_NN_classificacaobinaria_keras.ipynb
|
TerradasExatas/Introdu-o-IA-e-Machine-Learning
|
243a599bde920768df995f9778c78b3ab1ae9e30
|
[
"MIT"
] | null | null | null | 326.184915 | 52,426 | 0.917986 |
[
[
[
"#rede neural para classificação Binária\n#cria o data set e salva em \"meu_data_set.h5\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\ns_p=30 #quantos pontos os dados de entrada tem\ns_d=80 #quantos exemplos de cada tipo tem meu Dtrain\ns_t=10 #quantos exemplos de cada tipo para teste\np_r = 0.7 #porcentagem de ruido nos cossenos\nt=np.linspace(0,8*np.pi,s_p)\n#dados de treinamento\nx=np.zeros([2*s_d,s_p])\nx[0:s_d,0:s_p]=(1-p_r)*np.ones([s_d,1])*np.cos(t)\nx[0:s_d,0:s_p]=x[0:s_d,0:s_p]+p_r*np.random.normal(0, 0.8, [s_d,s_p])\nx[s_d:2*s_d,0:s_p]=np.random.normal(0, 0.7, [s_d,s_p])\ny=np.zeros([2*s_d,1])\ny[0:s_d]=np.ones([s_d,1])\n#dados de teste\nx_t=np.zeros([2*s_t,s_p])\nx_t[0:s_t,0:s_p]=(1-p_r)*np.ones([s_t,1])*np.cos(t)\nx_t[0:s_t,0:s_p]=x_t[0:s_t,0:s_p]+p_r*np.random.normal(0, 0.8, [s_t,s_p])\nx_t[s_t:2*s_t,0:s_p]=np.random.normal(0, 0.7, [s_t,s_p])\ny_t=np.zeros([2*s_t,1]);y_t[0:s_t]=np.ones([s_t,1])\n#mostra alguns dados de treinamento\nplt.figure()\nfor nn in range(0,3):\n plt.subplot(1,3,nn+1)\n plt.plot(t,x[nn,:],'b.-',label='cos+rand')\n plt.plot(t,x[s_d+nn,:],'r.-',label='rand')\n plt.legend(loc='upper center')\nplt.tight_layout() \n# salva o dataset\nwith h5py.File('meu_data_set.h5', 'w') as hf:\n hf.create_dataset(\"tempo\", data=t)\n hf.create_dataset(\"xtreinamento\", data=x)\n hf.create_dataset(\"ytreinamento\", data=y)\n hf.create_dataset(\"xteste\", data=x_t)\n hf.create_dataset(\"yteste\", data=y_t)\n hf.create_dataset(\"data_info\",data=[s_p,s_d,s_t])\nprint('xtreinamento=',x.shape)",
"xtreinamento= (160, 30)\n"
],
[
"# carrega do dataset de \"meu_data_set.h5\" com opção de psd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport h5py\n\nwith h5py.File('meu_data_set.h5', 'r') as hf:\n print('dados do arquivo: ',list(hf.keys()))\n [s_p,s_d,s_t]=hf['data_info'][:] \n y_train = hf['ytreinamento'][:] \n y_test = hf['yteste'][:] \n x_train = hf['xtreinamento'][:]\n x_test = hf['xteste'][:]\nprint('numero de exemplos de treinamento:',2*s_d)\nprint('numero de exemplos de teste:',2*s_t)",
"dados do arquivo: ['data_info', 'tempo', 'xteste', 'xtreinamento', 'yteste', 'ytreinamento']\nnumero de exemplos de treinamento: 160\nnumero de exemplos de teste: 20\n"
],
[
"#https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/\n#cria e treina a rede neural\n# define a rede neural \"keras model\"\nmodel=tf.keras.Sequential(name='rede_IF_02')\nmodel.add(tf.keras.layers.Dense(12, input_dim=s_p, activation='relu'))\nmodel.add(tf.keras.layers.Dense(8, activation='relu'))\nmodel.add(tf.keras.layers.Dense(1, activation='sigmoid'))\n# compila a rede neural\nopt = tf.keras.optimizers.Adam(learning_rate=0.05);\nmodel.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])\nprint(model.summary())\n# treina a rede neural com o data set\nhistory =model.fit(x_train, y_train,batch_size=2*s_d, epochs=100,verbose=0)\n# mostra o loss e a acuracia durante o treinamento\nplt.figure()\nplt.subplot(2,1,1)\nplt.plot(history.history['loss'])\nplt.ylabel('loss');plt.xlabel('epoch')\nplt.legend(['Loss'], loc='upper right')\nplt.subplot(2,1,2)\nplt.plot(history.history['accuracy'])\nplt.ylabel('acurácia');plt.xlabel('epoch')\nplt.legend(['acurácia'], loc='lower right')\nplt.show()",
"Model: \"rede_IF_02\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) (None, 12) 372 \n_________________________________________________________________\ndense_1 (Dense) (None, 8) 104 \n_________________________________________________________________\ndense_2 (Dense) (None, 1) 9 \n=================================================================\nTotal params: 485\nTrainable params: 485\nNon-trainable params: 0\n_________________________________________________________________\nNone\n"
],
[
"#faz previsões com a rede treinada\ny_pred=model.predict(x_test)\n# calcula a accurácia do teste\n_, accuracy = model.evaluate(x_test, y_test)\nprint('Accuracy: %.2f' % (accuracy*100))\n#mostra os resultados esperados e os alcançados lado a lado\nprint('data pred =',np.concatenate((y_test, np.around(y_pred)),axis=1))\n# faz o gráfico do erro de previsão\nplt.figure()\nplt.plot(y_test-np.around(y_pred))\nplt.title('erro de previsão: $y-y_{previsto}$')\nplt.show()",
"1/1 [==============================] - 0s 163ms/step - loss: 3.2085 - accuracy: 0.7500\nAccuracy: 75.00\ndata pred = [[1. 0.]\n [1. 1.]\n [1. 0.]\n [1. 1.]\n [1. 1.]\n [1. 1.]\n [1. 1.]\n [1. 1.]\n [1. 1.]\n [1. 1.]\n [0. 0.]\n [0. 0.]\n [0. 1.]\n [0. 0.]\n [0. 0.]\n [0. 0.]\n [0. 1.]\n [0. 0.]\n [0. 0.]\n [0. 1.]]\n"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"var_acc=history.history['accuracy']\nfor n in range(0,100):\n if var_acc[n]>0.97:\n break\nprint('n= ',n)\nprint('acuracia(n)= ',var_acc[n])",
"n= 11\nacuracia(n)= 0.9750000238418579\n"
],
[
"#plota algumas curvas dos dados de treinamento\nplt.rcParams.update({'font.size': 12})\nplt.figure()\nplt.plot(t,x_train[nn,:],'b.-',label='cos+rand')\nplt.plot(t,x_train[s_d+nn,:],'r.-',label='rand')\nplt.legend(loc='upper left')\nplt.xlabel('tempo'),plt.ylabel('valor da função')",
"_____no_output_____"
],
[
"# carrega do dataset de \"meu_data_set.h5\" com opção de psd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport h5py\nfrom scipy import signal\n\n#q_dado='sinal'\nq_dado='psd'\n\n\nwith h5py.File('meu_data_set.h5', 'r') as hf:\n print('dados do arquivo: ',list(hf.keys()))\n y_train = hf['ytreinamento'][:] \n y_test = hf['yteste'][:] \n [s_p,s_d,s_t]=hf['data_info'][:] \n if (q_dado=='psd'):\n _,x_train=signal.welch(hf['xtreinamento'][:],fs=s_p/4,nperseg=s_p)\n _,x_test=signal.welch(hf['xteste'][:],fs=s_p/4,nperseg=s_p)\n s_p=16\n else:\n x_train = hf['xtreinamento'][:]\n x_test = hf['xteste'][:]\n\nprint('x_train=',x_train.shape)\nprint('numero de exemplos de treinamento:',2*s_d)\nprint('numero de exemplos de teste:',2*s_t)",
"dados do arquivo: ['data_info', 'tempo', 'xteste', 'xtreinamento', 'yteste', 'ytreinamento']\nx_train= (160, 16)\nnumero de exemplos de treinamento: 160\nnumero de exemplos de teste: 20\n"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4a3705886f2ca6d7dfcb10f3dd27d7f83fb82b7d
| 93,281 |
ipynb
|
Jupyter Notebook
|
iguanas/rule_scoring/examples/rule_scorer_example.ipynb
|
Aditya-Kapadiya/Iguanas
|
dcc2c1e71f00574c3427fa530191e7079834c11b
|
[
"Apache-2.0"
] | 20 |
2021-12-22T14:15:03.000Z
|
2022-03-31T22:46:42.000Z
|
iguanas/rule_scoring/examples/rule_scorer_example.ipynb
|
Aditya-Kapadiya/Iguanas
|
dcc2c1e71f00574c3427fa530191e7079834c11b
|
[
"Apache-2.0"
] | 12 |
2022-01-18T16:55:56.000Z
|
2022-03-10T11:39:39.000Z
|
iguanas/rule_scoring/examples/rule_scorer_example.ipynb
|
Aditya-Kapadiya/Iguanas
|
dcc2c1e71f00574c3427fa530191e7079834c11b
|
[
"Apache-2.0"
] | 5 |
2021-12-25T07:28:29.000Z
|
2022-02-23T09:40:03.000Z
| 82.990214 | 472 | 0.288312 |
[
[
[
"# Rule Scorer Example",
"_____no_output_____"
],
[
"The Rule Scorer is used to generate scores for a set of rules based on a labelled dataset.",
"_____no_output_____"
],
[
"## Requirements",
"_____no_output_____"
],
[
"To run, you'll need the following:\n\n* A rule set (specifically the binary columns of the rules as applied to a dataset).\n* The binary target column associated with the above dataset.",
"_____no_output_____"
],
[
"----",
"_____no_output_____"
],
[
"## Import packages",
"_____no_output_____"
]
],
[
[
"from iguanas.rule_scoring import RuleScorer, PerformanceScorer, ConstantScaler\nfrom iguanas.metrics.classification import Precision\n\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"## Read in data",
"_____no_output_____"
],
[
"Let's read in some dummy rules (stored as binary columns) and the target column.",
"_____no_output_____"
]
],
[
[
"X_rules_train = pd.read_csv(\n 'dummy_data/X_rules_train.csv', \n index_col='eid'\n)\ny_train = pd.read_csv(\n 'dummy_data/y_train.csv', \n index_col='eid'\n).squeeze()\nX_rules_test = pd.read_csv(\n 'dummy_data/X_rules_test.csv', \n index_col='eid'\n)\ny_test = pd.read_csv(\n 'dummy_data//y_test.csv', \n index_col='eid'\n).squeeze()",
"_____no_output_____"
]
],
[
[
"----",
"_____no_output_____"
],
[
"## Generate scores",
"_____no_output_____"
],
[
"### Set up class parameters",
"_____no_output_____"
],
[
"Now we can set our class parameters for the Rule Scorer. Here we pass an instantiated scoring class (which generates the raw scores) and an instantiated scaling class (which scales the scores to be more readable - **this is optional**). The scoring classes are located in the `rule_scoring_methods` module; the scaling classes are located in the `rule_score_scalers` module. **See the class docstrings for more information on each type of scoring/scaling class.**\n\nIn this example, we'll use the `PerformanceScorer` class for scoring the rules (based on the precision score) and the `ConstantScaler` class for scaling. **Note that we're using the *Precision* class from the *metrics.classification* module rather than Sklearn's *precision_score* function, as the former is ~100 times faster on larger datasets.**\n\n**Please see the class docstring for more information on each parameter.**",
"_____no_output_____"
]
],
[
[
"precision_score = Precision()",
"_____no_output_____"
],
[
"params = {\n 'scoring_class': PerformanceScorer(metric=precision_score.fit),\n 'scaling_class': ConstantScaler(limit=-100)\n}",
"_____no_output_____"
]
],
[
[
"### Instantiate class and run fit method",
"_____no_output_____"
],
[
"Once the parameters have been set, we can run the `fit` method to generate scores.",
"_____no_output_____"
]
],
[
[
"rs = RuleScorer(**params)\nrs.fit(\n X_rules=X_rules_train, \n y=y_train\n)",
"_____no_output_____"
]
],
[
[
"### Outputs",
"_____no_output_____"
],
[
"The `fit` method does not return anything. See the `Attributes` section in the class docstring for a description of each attribute generated:",
"_____no_output_____"
]
],
[
[
"rs.rule_scores.head()",
"_____no_output_____"
]
],
[
[
"----",
"_____no_output_____"
],
[
"## Apply rules to a separate dataset",
"_____no_output_____"
],
[
"Use the `transform` method to apply the generated rules to another dataset.",
"_____no_output_____"
]
],
[
[
"X_scores_test = rs.transform(X_rules=X_rules_test)",
"_____no_output_____"
]
],
[
[
"### Outputs",
"_____no_output_____"
],
[
"The `transform` method returns a dataframe giving the scores of the rules as applied to the dataset.",
"_____no_output_____"
]
],
[
[
"X_scores_test.head()",
"_____no_output_____"
]
],
[
[
"----",
"_____no_output_____"
],
[
"## Generate rule score and apply them to the training set (in one step)",
"_____no_output_____"
],
[
"You can also use the `fit_transform` method to generate scores and apply them to the training set.",
"_____no_output_____"
]
],
[
[
"X_scores_train = rs.fit_transform(\n X_rules=X_rules_train, \n y=y_train\n)",
"_____no_output_____"
]
],
[
[
"### Outputs",
"_____no_output_____"
],
[
"The `transform` method returns a dataframe giving the scores of the rules as applied to the dataset. See the `Attributes` section in the class docstring for a description of each attribute generated:",
"_____no_output_____"
]
],
[
[
"rs.rule_scores.head()",
"_____no_output_____"
],
[
"X_scores_train.head()",
"_____no_output_____"
]
],
[
[
"----",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4a370688c6cf2d6c597b877354a60f60f203c540
| 144,280 |
ipynb
|
Jupyter Notebook
|
sklearn splitted/main(unfinished).ipynb
|
YellingOilbird/SARIMAX-predictions-for-restaurants
|
8400f462a9c603485c33933549b56d9b29acc1a9
|
[
"MIT"
] | null | null | null |
sklearn splitted/main(unfinished).ipynb
|
YellingOilbird/SARIMAX-predictions-for-restaurants
|
8400f462a9c603485c33933549b56d9b29acc1a9
|
[
"MIT"
] | null | null | null |
sklearn splitted/main(unfinished).ipynb
|
YellingOilbird/SARIMAX-predictions-for-restaurants
|
8400f462a9c603485c33933549b56d9b29acc1a9
|
[
"MIT"
] | null | null | null | 266.199262 | 68,514 | 0.904755 |
[
[
[
"import warnings\nwarnings.simplefilter(action='ignore')\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib\n\nimport statsmodels.api as sm\nfrom matplotlib import pyplot as plt\nfrom datetime import datetime\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom statsmodels.tsa.stattools import adfuller, acf, pacf\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\n\ndf = pd.read_csv('/opt/anaconda3/futuraplan.csv',index_col=0)\ndf.set_index([pd.to_datetime(df.index)], inplace=True)\n\nguests = df['GUESTS']\nvol = df['VOL']\ncheck_av = df['AVCHECK']\n\n#Split dataset 80/20 as train and test sets\ntrain, test = train_test_split(df,shuffle=False, test_size=0.2)\n\n#seasonal trends in data metrics\nres1 = sm.tsa.seasonal_decompose(guests.interpolate(), model='additive', freq=12)\nres2 = sm.tsa.seasonal_decompose(vol.interpolate(), model='additive', freq=12)\nres3 = sm.tsa.seasonal_decompose(check_av.interpolate(), model='additive', freq=12)\n\ndef plotseasonal(res, axes ):\n res.observed.plot(ax=axes[0], legend=False)\n axes[0].set_ylabel('Observed')\n res.trend.plot(ax=axes[1], legend=False)\n axes[1].set_ylabel('Trend')\n res.seasonal.plot(ax=axes[2], legend=False)\n axes[2].set_ylabel('Seasonal')\n \nfig, axes = plt.subplots(ncols=3, nrows=3, sharex=True, figsize=(12,5))\naxes[0,0].set_title(\"Guests\")\naxes[0,1].set_title(\"Volume\")\naxes[0,2].set_title(\"Average check\")\n \nplotseasonal(res1, axes[:,0])\nplotseasonal(res2, axes[:,1])\nplotseasonal(res3, axes[:,2])\n\nfig.tight_layout()\nplt.show()\n\n#for checking results\n#print(test_V)\n#df.head()\n",
"_____no_output_____"
],
[
"#PACF-ACF for descision about model parameters for SARIMAX\ndef df_test(ts):\n result = adfuller(ts)\n print('ADF Statistic: %f' % result[0])\n print('p-value: %f' % result[1])\n print('Critical Values:')\n for key, value in result[4].items():\n print('\\t%s: %.3f' % (key, value))\n \ndf_test(vol)\nlag_pacf = pacf(vol, nlags=10)\n\n#Plot PACF: \nplt.plot(lag_pacf, 'ok-')\nplt.axhline(y=0,linestyle='--',color='gray')\nplt.axhline(y=-1.96/np.sqrt(len(vol)),linestyle='--',color='gray')\nplt.axhline(y=1.96/np.sqrt(len(vol)),linestyle='--',color='gray')\nplt.title('Partial Autocorrelation Function');\n",
"ADF Statistic: -0.179326\np-value: 0.940941\nCritical Values:\n\t1%: -4.012\n\t5%: -3.104\n\t10%: -2.691\n"
],
[
"lag_acf = acf(vol, nlags=40)\n\n#Plot ACF: \nplt.plot(lag_acf, 'ok-')\nplt.axhline(y=0,linestyle='--',color='gray')\nplt.axhline(y=-1.96/np.sqrt(len(vol)),linestyle='--',color='gray')\nplt.axhline(y=1.96/np.sqrt(len(vol)),linestyle='--',color='gray')\nplt.title('Autocorrelation Function');",
"_____no_output_____"
],
[
"model1 = SARIMAX(guests, order=(1,1,1), seasonal_order=(1,0,1,4))\nmodel2 = SARIMAX(vol, order=(1,1,1), seasonal_order=(1,0,1,4))\nmodel3 = SARIMAX(check_av, order=(1,1,1), seasonal_order=(1,0,0,12))\n\nsarima_res1 = model1.fit(disp=True)\nsarima_res2 = model2.fit(disp=True)\nsarima_res3 = model3.fit(disp=True)\n\ndf['FORECAST_GUESTS']= sarima_res1.predict(start=\"2021-07-31\", end=\"2022-11-30\", dynamic=True) \ndf['FORECAST_VOLUME']= sarima_res2.predict(start=\"2021-07-31\", end=\"2022-11-30\", dynamic=True) \ndf['FORECAST_AVCHECK']= sarima_res3.predict(start=\"2021-07-31\", end=\"2022-11-30\", dynamic=True) \n\ndf[['VOL','FORECAST_VOLUME']].plot()\n",
"RUNNING THE L-BFGS-B CODE\n\n * * *\n\nMachine precision = 2.220D-16\n N = 5 M = 10\n\nAt X0 0 variables are exactly at the bounds\n\nAt iterate 0 f= 8.93852D+00 |proj g|= 1.44821D-01\n\nAt iterate 1 f= 8.88209D+00 |proj g|= 6.26976D-02\n\nAt iterate 2 f= 8.87383D+00 |proj g|= 1.06300D-01\n\nAt iterate 3 f= 8.86008D+00 |proj g|= 3.58123D-02\n\nAt iterate 4 f= 8.85534D+00 |proj g|= 2.98865D-02\n\nAt iterate 5 f= 8.85373D+00 |proj g|= 1.90821D-02\n\nAt iterate 6 f= 8.85323D+00 |proj g|= 6.46832D-03\n\nAt iterate 7 f= 8.85319D+00 |proj g|= 5.09805D-04\n\nAt iterate 8 f= 8.85319D+00 |proj g|= 3.29641D-04\n\nAt iterate 9 f= 8.85319D+00 |proj g|= 5.85259D-04\n\nAt iterate 10 f= 8.85319D+00 |proj g|= 8.89957D-04\n\nAt iterate 11 f= 8.85319D+00 |proj g|= 1.59101D-03\n\nAt iterate 12 f= 8.85318D+00 |proj g|= 2.31854D-03\n\nAt iterate 13 f= 8.85316D+00 |proj g|= 2.49609D-03\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4a3706e223366709debc09daedf94455e386a62c
| 15,065 |
ipynb
|
Jupyter Notebook
|
wordrelatedness_model_testing.ipynb
|
americanthinker/cs224u
|
73191acc2eb985b00ced8a8697d7dd3eea115feb
|
[
"Apache-2.0"
] | null | null | null |
wordrelatedness_model_testing.ipynb
|
americanthinker/cs224u
|
73191acc2eb985b00ced8a8697d7dd3eea115feb
|
[
"Apache-2.0"
] | null | null | null |
wordrelatedness_model_testing.ipynb
|
americanthinker/cs224u
|
73191acc2eb985b00ced8a8697d7dd3eea115feb
|
[
"Apache-2.0"
] | null | null | null | 42.317416 | 402 | 0.656356 |
[
[
[
"from transformers import BertModel, BertTokenizer\nfrom utils import devdf_generator\nimport pandas as pd\nimport torch\nimport vsm\nimport os\n%load_ext autoreload\n%autoreload 2\n\nVSM_HOME = os.path.join('data', 'vsmdata')\n\nDATA_HOME = os.path.join('data', 'wordrelatedness')\n\ndef evaluate_pooled_bert(rel_df, layer, pool_func):\n \n if torch.cuda.is_available():\n device = torch.device('cuda')\n else:\n device = torch.device('cpu')\n \n bert_weights_name = 'bert-base-uncased'\n\n # Initialize a BERT tokenizer and BERT model based on\n # `bert_weights_name`:\n tokenizer = BertTokenizer.from_pretrained(bert_weights_name)\n model = BertModel.from_pretrained(bert_weights_name)\n model = model.to(device)\n print(f'Model is on {model.device}')\n\n # Get the vocabulary from `rel_df`:\n ##### YOUR CODE HERE\n vocab = set(rel_df.word1.values) | set(rel_df.word2.values)\n \n # Use `vsm.create_subword_pooling_vsm` with the user's arguments:\n pooled_df = vsm.create_subword_pooling_vsm(vocab, tokenizer, model, layer=layer, pool_func=pool_func)\n \n # Return the results of the relatedness evalution:\n return vsm.word_relatedness_evaluation(rel_df, pooled_df)",
"_____no_output_____"
],
[
"pooling_function = vsm.mean_pooling\ndev = pd.read_csv(os.path.join(DATA_HOME, \"cs224u-wordrelatedness-dev.csv\"))\nhighest = devdf_generator(dev, scoring='highest')\nlowest = devdf_generator(dev, scoring='lowest')\naverage = devdf_generator(dev, scoring='mean')",
"/anaconda/envs/haystack/lib/python3.8/site-packages/pandas/core/frame.py:4906: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n return super().drop(\n"
]
],
[
[
"### Series of Experiments using differnt \"hyperparameters\" for BERT pooling model",
"_____no_output_____"
]
],
[
[
"# 1. Same hypers, different dev datasets\nscores = {}\n\ndev_eval, dev_rho = evaluate_pooled_bert(dev, -1, pooling_function)\nscores['dev'] = dev_rho\n\nhighest, highest_rho = evaluate_pooled_bert(highest, -1, pooling_function)\nscores['highest'] = highest_rho\n\nlowest, lowest_rho = evaluate_pooled_bert(lowest, -1, pooling_function)\nscores['lowest'] = lowest_rho\n\nmean, mean_rho = evaluate_pooled_bert(average, -1, pooling_function)\nscores['mean'] = mean_rho",
"Some weights of the model checkpoint at bert-base-uncased were not used when initializing BertModel: ['cls.predictions.transform.dense.weight', 'cls.predictions.bias', 'cls.predictions.transform.LayerNorm.bias', 'cls.seq_relationship.bias', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.LayerNorm.weight', 'cls.seq_relationship.weight', 'cls.predictions.decoder.weight']\n- This IS expected if you are initializing BertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n- This IS NOT expected if you are initializing BertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n"
],
[
"scores",
"_____no_output_____"
],
[
"#2 same dev set (highest) different pooling functions\npooling_scores = {}\n\nmin_eval, min_rho = evaluate_pooled_bert(highest, -1, vsm.min_pooling)\npooling_scores['min'] = min_rho\n\nmax_eval, max_rho = evaluate_pooled_bert(highest, -1, vsm.max_pooling)\npooling_scores['max'] = max_rho\n\nmean_eval, mean_rho = evaluate_pooled_bert(highest, -1, vsm.mean_pooling)\npooling_scores['mean'] = mean_rho\n\nlast_eval, last_rho = evaluate_pooled_bert(average, -1, vsm.last_pooling)\npooling_scores['last'] = last_rho",
"Some weights of the model checkpoint at bert-base-uncased were not used when initializing BertModel: ['cls.predictions.transform.dense.weight', 'cls.predictions.bias', 'cls.predictions.transform.LayerNorm.bias', 'cls.seq_relationship.bias', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.LayerNorm.weight', 'cls.seq_relationship.weight', 'cls.predictions.decoder.weight']\n- This IS expected if you are initializing BertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n- This IS NOT expected if you are initializing BertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n"
],
[
"pooling_scores",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4a370e66b09360c8b2b4aa6bdffbff5ac2d3669f
| 7,158 |
ipynb
|
Jupyter Notebook
|
Gradient Boosting/CountFeatureGenerator.ipynb
|
srlakhe/Fake-News-Challenge
|
b0a79e63c3e277c9417141892820e65d885d6506
|
[
"MIT"
] | 7 |
2019-06-16T02:19:43.000Z
|
2020-10-30T19:51:34.000Z
|
Gradient Boosting/CountFeatureGenerator.ipynb
|
mrjnsudhan/Fake-News-Challenge-1
|
b0a79e63c3e277c9417141892820e65d885d6506
|
[
"MIT"
] | 2 |
2020-08-01T23:10:41.000Z
|
2021-01-16T10:21:27.000Z
|
Gradient Boosting/CountFeatureGenerator.ipynb
|
mrjnsudhan/Fake-News-Challenge-1
|
b0a79e63c3e277c9417141892820e65d885d6506
|
[
"MIT"
] | 6 |
2019-07-14T15:53:51.000Z
|
2021-01-01T07:38:23.000Z
| 45.884615 | 1,172 | 0.54708 |
[
[
[
"from FeatureGenerator import *\nimport ngram\nimport pickle\nimport pandas as pd\nfrom nltk.tokenize import sent_tokenize\nfrom helpers import *\nimport hashlib\n\nclass CountFeatureGenerator(FeatureGenerator):\n def __init__(self, name='countFeatureGenerator'):\n super(CountFeatureGenerator, self).__init__(name)\n \n def process(self, df):\n grams = [\"unigram\", \"bigram\", \"trigram\"]\n feat_names = [\"Headline\", \"articleBody\"]\n print(\"generate counting features\")\n \n for feat_name in feat_names:\n for gram in grams:\n df[\"count_of_%s_%s\" % (feat_name, gram)] = list(df.apply(lambda x: len(x[feat_name + \"_\" + gram]), axis=1))\n df[\"count_of_unique_%s_%s\" % (feat_name, gram)] = list(df.apply(lambda x: len(set(x[feat_name + \"_\" + gram])), axis=1))\n df[\"ratio_of_unique_%s_%s\" % (feat_name, gram)] = list(map(try_divide, df[\"count_of_unique_%s_%s\"%(feat_name,gram)], df[\"count_of_%s_%s\"%(feat_name,gram)]))\n\n # overlapping n-grams count\n for gram in grams:\n df[\"count_of_Headline_%s_in_articleBody\" % gram] = list(df.apply(lambda x: sum([1. for w in x[\"Headline_\" + gram] if w in set(x[\"articleBody_\" + gram])]), axis=1))\n df[\"ratio_of_Headline_%s_in_articleBody\" % gram] = list(map(try_divide, df[\"count_of_Headline_%s_in_articleBody\" % gram], df[\"count_of_Headline_%s\" % gram]))\n\n # number of sentences in headline and body\n for feat_name in feat_names:\n df['len_sent_%s' % feat_name] = df[feat_name].apply(lambda x: len(sent_tokenize(x)))\n \n \n # dump the basic counting features into a file\n feat_names = [ n for n in df.columns if \"count\" in n or \"ratio\" in n or \"len_sent\" in n]\n \n # binary refuting features\n _refuting_words = [\n 'fake',\n 'fraud',\n 'hoax',\n 'false',\n 'deny', 'denies',\n # 'refute',\n 'not',\n 'despite',\n 'nope',\n 'doubt', 'doubts',\n 'bogus',\n 'debunk',\n 'pranks',\n 'retract'\n ]\n\n \n check_words = _refuting_words\n for rf in check_words:\n fname = '%s_exist' % rf\n feat_names.append(fname)\n df[fname] = list(df['Headline'].map(lambda x: 1 if rf in x else 0))\n \n\n print('BasicCountFeatures:')\n print(df)\n \n train = df[~df['target'].isnull()]\n print('train:')\n print(train[['Headline_unigram','Body ID', 'count_of_Headline_unigram']])\n xBasicCountsTrain = train[feat_names].values\n outfilename_bcf_train = \"train.basic.pkl\"\n with open(outfilename_bcf_train, \"wb\") as outfile:\n pickle.dump(feat_names, outfile, -1)\n pickle.dump(xBasicCountsTrain, outfile, -1)\n print('basic counting features for training saved in %s' % outfilename_bcf_train)\n \n test = df[df['target'].isnull()]\n print('test:')\n print(test[['Headline_unigram','Body ID', 'count_of_Headline_unigram']])\n if test.shape[0] > 0:\n # test set exists\n print('saving test set')\n xBasicCountsTest = test[feat_names].values\n outfilename_bcf_test = \"test.basic.pkl\"\n with open(outfilename_bcf_test, 'wb') as outfile:\n pickle.dump(feat_names, outfile, -1)\n pickle.dump(xBasicCountsTest, outfile, -1)\n print('basic counting features for test saved in %s' % outfilename_bcf_test)\n \n def read(self, header='train'):\n filename_bcf = \"%s.basic.pkl\" % header\n with open(filename_bcf, \"rb\") as infile:\n feat_names = pickle.load(infile)\n xBasicCounts = pickle.load(infile)\n print('feature names: ')\n print(feat_names)\n print('xBasicCounts.shape:')\n print(xBasicCounts.shape)\n np.save('counts_test', [xBasicCounts])\n return [xBasicCounts]\nif __name__ == '__main__':\n\n cf = CountFeatureGenerator()\n cf.read('test')\n\n",
"feature names: \n['count_of_Headline_unigram', 'count_of_unique_Headline_unigram', 'ratio_of_unique_Headline_unigram', 'count_of_Headline_bigram', 'count_of_unique_Headline_bigram', 'ratio_of_unique_Headline_bigram', 'count_of_Headline_trigram', 'count_of_unique_Headline_trigram', 'ratio_of_unique_Headline_trigram', 'count_of_articleBody_unigram', 'count_of_unique_articleBody_unigram', 'ratio_of_unique_articleBody_unigram', 'count_of_articleBody_bigram', 'count_of_unique_articleBody_bigram', 'ratio_of_unique_articleBody_bigram', 'count_of_articleBody_trigram', 'count_of_unique_articleBody_trigram', 'ratio_of_unique_articleBody_trigram', 'count_of_Headline_unigram_in_articleBody', 'ratio_of_Headline_unigram_in_articleBody', 'count_of_Headline_bigram_in_articleBody', 'ratio_of_Headline_bigram_in_articleBody', 'count_of_Headline_trigram_in_articleBody', 'ratio_of_Headline_trigram_in_articleBody', 'len_sent_Headline', 'len_sent_articleBody', 'fake_exist', 'fraud_exist', 'hoax_exist', 'false_exist', 'deny_exist', 'denies_exist', 'not_exist', 'despite_exist', 'nope_exist', 'doubt_exist', 'doubts_exist', 'bogus_exist', 'debunk_exist', 'pranks_exist', 'retract_exist']\nxBasicCounts.shape:\n(25413, 41)\n"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
4a372e6fa8a7f3c4cc66a9d9898e0fffe55bc425
| 10,276 |
ipynb
|
Jupyter Notebook
|
course_2/course_material/Part_7_Deep_Learning/S51_L356/TensorFlow_Audiobooks_Preprocessing_Exercise_Solution.ipynb
|
Alexander-Meldrum/learning-data-science
|
a87cf6be80c67a8d1b57a96c042bdf423ba0a142
|
[
"MIT"
] | null | null | null |
course_2/course_material/Part_7_Deep_Learning/S51_L356/TensorFlow_Audiobooks_Preprocessing_Exercise_Solution.ipynb
|
Alexander-Meldrum/learning-data-science
|
a87cf6be80c67a8d1b57a96c042bdf423ba0a142
|
[
"MIT"
] | null | null | null |
course_2/course_material/Part_7_Deep_Learning/S51_L356/TensorFlow_Audiobooks_Preprocessing_Exercise_Solution.ipynb
|
Alexander-Meldrum/learning-data-science
|
a87cf6be80c67a8d1b57a96c042bdf423ba0a142
|
[
"MIT"
] | null | null | null | 36.7 | 175 | 0.643928 |
[
[
[
"# Audiobooks business case",
"_____no_output_____"
],
[
"## Preprocessing exercise\n\nIt makes sense to shuffle the indices prior to balancing the dataset. \n\nUsing the code from the lesson (below), shuffle the indices and then balance the dataset.\n\nAt the end of the course, you will have an exercise to create the same machine learning algorithm, with preprocessing done in this way.\n\nNote: This is more of a programming exercise rather than a machine learning one. Being able to complete it successfully will ensure you understand the preprocessing. \n\nGood luck!\n\n**Solution:**\n\nScroll down to the 'Exercise Solution' section",
"_____no_output_____"
],
[
"### Extract the data from the csv",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\n# We will use the sklearn preprocessing library, as it will be easier to standardize the data.\nfrom sklearn import preprocessing\n\n# Load the data\nraw_csv_data = np.loadtxt('Audiobooks_data.csv',delimiter=',')\n\n# The inputs are all columns in the csv, except for the first one [:,0]\n# (which is just the arbitrary customer IDs that bear no useful information),\n# and the last one [:,-1] (which is our targets)\n\nunscaled_inputs_all = raw_csv_data[:,1:-1]\n\n# The targets are in the last column. That's how datasets are conventionally organized.\ntargets_all = raw_csv_data[:,-1]",
"_____no_output_____"
]
],
[
[
"### EXERCISE SOLUTION\n\nWe shuffle the indices before balancing (to remove any day effects, etc.)\n\nHowever, we still have to shuffle them AFTER we balance the dataset as otherwise, all targets that are 1s will be contained in the train_targets.\n\nThis code is suboptimal, but is the easiest way to complete the exercise. Still, as we do the preprocessing only once, speed in not something we are aiming for.\n\nWe record the variables in themselves, so we don't amend the code that follows.",
"_____no_output_____"
]
],
[
[
"# When the data was collected it was actually arranged by date\n# Shuffle the indices of the data, so the data is not arranged in any way when we feed it.\n# Since we will be batching, we want the data to be as randomly spread out as possible\nshuffled_indices = np.arange(unscaled_inputs_all.shape[0])\nnp.random.shuffle(shuffled_indices)\n\n# Use the shuffled indices to shuffle the inputs and targets.\nunscaled_inputs_all = unscaled_inputs_all[shuffled_indices]\ntargets_all = targets_all[shuffled_indices]",
"_____no_output_____"
]
],
[
[
"### Balance the dataset",
"_____no_output_____"
]
],
[
[
"# Count how many targets are 1 (meaning that the customer did convert)\nnum_one_targets = int(np.sum(targets_all))\n\n# Set a counter for targets that are 0 (meaning that the customer did not convert)\nzero_targets_counter = 0\n\n# We want to create a \"balanced\" dataset, so we will have to remove some input/target pairs.\n# Declare a variable that will do that:\nindices_to_remove = []\n\n# Count the number of targets that are 0. \n# Once there are as many 0s as 1s, mark entries where the target is 0.\nfor i in range(targets_all.shape[0]):\n if targets_all[i] == 0:\n zero_targets_counter += 1\n if zero_targets_counter > num_one_targets:\n indices_to_remove.append(i)\n\n# Create two new variables, one that will contain the inputs, and one that will contain the targets.\n# We delete all indices that we marked \"to remove\" in the loop above.\nunscaled_inputs_equal_priors = np.delete(unscaled_inputs_all, indices_to_remove, axis=0)\ntargets_equal_priors = np.delete(targets_all, indices_to_remove, axis=0)",
"_____no_output_____"
]
],
[
[
"### Standardize the inputs",
"_____no_output_____"
]
],
[
[
"# That's the only place we use sklearn functionality. We will take advantage of its preprocessing capabilities\n# It's a simple line of code, which standardizes the inputs, as we explained in one of the lectures.\n# At the end of the business case, you can try to run the algorithm WITHOUT this line of code. \n# The result will be interesting.\nscaled_inputs = preprocessing.scale(unscaled_inputs_equal_priors)",
"_____no_output_____"
]
],
[
[
"### Shuffle the data",
"_____no_output_____"
]
],
[
[
"# When the data was collected it was actually arranged by date\n# Shuffle the indices of the data, so the data is not arranged in any way when we feed it.\n# Since we will be batching, we want the data to be as randomly spread out as possible\nshuffled_indices = np.arange(scaled_inputs.shape[0])\nnp.random.shuffle(shuffled_indices)\n\n# Use the shuffled indices to shuffle the inputs and targets.\nshuffled_inputs = scaled_inputs[shuffled_indices]\nshuffled_targets = targets_equal_priors[shuffled_indices]",
"_____no_output_____"
]
],
[
[
"### Split the dataset into train, validation, and test",
"_____no_output_____"
]
],
[
[
"# Count the total number of samples\nsamples_count = shuffled_inputs.shape[0]\n\n# Count the samples in each subset, assuming we want 80-10-10 distribution of training, validation, and test.\n# Naturally, the numbers are integers.\ntrain_samples_count = int(0.8 * samples_count)\nvalidation_samples_count = int(0.1 * samples_count)\n\n# The 'test' dataset contains all remaining data.\ntest_samples_count = samples_count - train_samples_count - validation_samples_count\n\n# Create variables that record the inputs and targets for training\n# In our shuffled dataset, they are the first \"train_samples_count\" observations\ntrain_inputs = shuffled_inputs[:train_samples_count]\ntrain_targets = shuffled_targets[:train_samples_count]\n\n# Create variables that record the inputs and targets for validation.\n# They are the next \"validation_samples_count\" observations, folllowing the \"train_samples_count\" we already assigned\nvalidation_inputs = shuffled_inputs[train_samples_count:train_samples_count+validation_samples_count]\nvalidation_targets = shuffled_targets[train_samples_count:train_samples_count+validation_samples_count]\n\n# Create variables that record the inputs and targets for test.\n# They are everything that is remaining.\ntest_inputs = shuffled_inputs[train_samples_count+validation_samples_count:]\ntest_targets = shuffled_targets[train_samples_count+validation_samples_count:]\n\n# We balanced our dataset to be 50-50 (for targets 0 and 1), but the training, validation, and test were \n# taken from a shuffled dataset. Check if they are balanced, too. Note that each time you rerun this code, \n# you will get different values, as each time they are shuffled randomly.\n# Normally you preprocess ONCE, so you need not rerun this code once it is done.\n# If you rerun this whole sheet, the npzs will be overwritten with your newly preprocessed data.\n\n# Print the number of targets that are 1s, the total number of samples, and the proportion for training, validation, and test.\nprint(np.sum(train_targets), train_samples_count, np.sum(train_targets) / train_samples_count)\nprint(np.sum(validation_targets), validation_samples_count, np.sum(validation_targets) / validation_samples_count)\nprint(np.sum(test_targets), test_samples_count, np.sum(test_targets) / test_samples_count)",
"1817.0 3579 0.5076837105336687\n200.0 447 0.44742729306487694\n220.0 448 0.49107142857142855\n"
]
],
[
[
"### Save the three datasets in *.npz",
"_____no_output_____"
]
],
[
[
"# Save the three datasets in *.npz.\n# In the next lesson, you will see that it is extremely valuable to name them in such a coherent way!\n\nnp.savez('Audiobooks_data_train', inputs=train_inputs, targets=train_targets)\nnp.savez('Audiobooks_data_validation', inputs=validation_inputs, targets=validation_targets)\nnp.savez('Audiobooks_data_test', inputs=test_inputs, targets=test_targets)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a372ef399470e03ce76c05dd165fd90d9ec0d2f
| 8,238 |
ipynb
|
Jupyter Notebook
|
Week_01_Unit_05.ipynb
|
DGCoach/jupyter
|
35bd2bd32f98e4583ba8a04d8385fcbc3e72fb69
|
[
"Apache-2.0"
] | null | null | null |
Week_01_Unit_05.ipynb
|
DGCoach/jupyter
|
35bd2bd32f98e4583ba8a04d8385fcbc3e72fb69
|
[
"Apache-2.0"
] | null | null | null |
Week_01_Unit_05.ipynb
|
DGCoach/jupyter
|
35bd2bd32f98e4583ba8a04d8385fcbc3e72fb69
|
[
"Apache-2.0"
] | null | null | null | 23.205634 | 138 | 0.519179 |
[
[
[
"# Enterprise Deep Learning with TensorFlow: openSAP \n\n## SAP Innovation Center Network\n```\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```",
"_____no_output_____"
],
[
"### Introduction to TensorFlow\nIn this notebook, we will learn \n- Some common TensorFlow operations \n- Run math operations using Session\n- Understand how TensorFlow can run computes on different devices",
"_____no_output_____"
]
],
[
[
"# Import tensorflow library\n# Reference it as tf for ease of calling\nimport tensorflow as tf",
"_____no_output_____"
],
[
"# Let's check our TensorFlow version\nprint(\"You are running TensorFlow %s\" % str(tf.__version__))",
"You are running TensorFlow 1.14.0\n"
],
[
"# List of math ops can be found here: https://www.tensorflow.org/api_guides/python/math_ops\n# Let us use an InteractiveSession \n# Provides an easy to use session for interactive environments like a Jupyter notebook\nsess = tf.InteractiveSession()",
"_____no_output_____"
],
[
"a = tf.constant(23, name='const_a')\nb = tf.constant(11, name='const_b')\n\n# Let's add the two prime numbers\nc = tf.add(a, b)\nprint(c.eval())",
"34\n"
],
[
"# Let's subtract two prime numbers\nc = tf.subtract(a, b)\nprint(c.eval())",
"12\n"
],
[
"# More ops for playing with TensorFlow \n# Let's multiply two prime numbers\nc = tf.multiply(a, b)\n# 253\n\n# Let's divide two prime numbers\nc = tf.divide(23, 13)\n# 2\n\na = tf.constant(23., name='const_a')\nb = tf.constant(11., name='const_b')\n\n# Now, let's divide two prime numbers to see the difference\nc = tf.divide(23, 13)\n# 2.090909\n\n# Let's get the modulus of two prime numbers\nc = tf.mod(a, b)\n# 1.0\n\na = tf.constant(2., name='const_a')\nb = tf.constant(10., name='const_b')\n\n# Let's calculate 2^10\nc = tf.pow(a, b)\n# 1024.0\n\n# List of control ops can be found here: https://www.tensorflow.org/api_guides/python/control_flow_ops\n# Check for a < b\nc = tf.less(a, b)\n# True \n\n# Check for a <= b\nc = tf.less_equal(a, b)\n# True\n\n# Check for a > b\nc = tf.greater(a, b)\n# False\n\n# Check for a >= b\nc = tf.greater_equal(a, b)\n# False\n\n# Some conditional check statements\nc = tf.logical_and(True, False)\n# False\n\ntf.logical_or(True, False)\n# True\n\ntf.logical_xor(True, False)\n# True",
"_____no_output_____"
],
[
"# Let's create two matrices, a 3x1 and another 1x3 matrix for multiplication\nmat_a = tf.constant([[1., 3., 5.]], name='mat_a')\nmat_b = tf.constant([[7.], [11.], [13.]], name='mat_b')",
"_____no_output_____"
],
[
"# Let's matrix multiply the two matrices\nprod_op = tf.matmul(mat_a, mat_b)\nprint(prod_op)",
"Tensor(\"MatMul:0\", shape=(1, 1), dtype=float32)\n"
],
[
"# Create a session object to run our matrix multiplication\nsess = tf.Session()",
"_____no_output_____"
],
[
"# Get the result by calling run on the session\n# Returns an numpy ndarray object\nmat_mul = sess.run(prod_op)",
"_____no_output_____"
],
[
"# Let's view the result \nprint(mat_mul)\n# [[ 105.]]",
"[[105.]]\n"
],
[
"# Remember to close the session when done, releases the resources\nsess.close()",
"_____no_output_____"
],
[
"# Easier way to handle session objects is \n# using the familiar 'with' block as follows\nwith tf.Session() as sess:\n mat_mul = sess.run(prod_op)\n print(mat_mul)\n# [[ 105.]]",
"[[105.]]\n"
],
[
"# If you have multiple devices capable of computes, use it as follows\n# /cpu:<device_id>\n# [Mac] Run the following command to know how many logical cores are present on your machine: sysctl -n hw.ncpu\n# [Win] Run the following command to know how many logical cores are present on your machine: systeminfo | find /i \"processors\"\nwith tf.Session() as sess:\n with tf.device(\"/cpu:0\"):\n mat_mul = sess.run(prod_op)\n print(mat_mul)\n# [[ 105.]]",
"[[105.]]\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a373208d80136d17c65a6931f52d0b5bf0f48e7
| 21,548 |
ipynb
|
Jupyter Notebook
|
Py2_Strings_and_Variables.ipynb
|
niklaust/self_study
|
ec8a8465b2d06d1fae856ede8510cf3c8fb3bde4
|
[
"Apache-2.0"
] | null | null | null |
Py2_Strings_and_Variables.ipynb
|
niklaust/self_study
|
ec8a8465b2d06d1fae856ede8510cf3c8fb3bde4
|
[
"Apache-2.0"
] | null | null | null |
Py2_Strings_and_Variables.ipynb
|
niklaust/self_study
|
ec8a8465b2d06d1fae856ede8510cf3c8fb3bde4
|
[
"Apache-2.0"
] | null | null | null | 24.73938 | 200 | 0.41331 |
[
[
[
"**Strings**\n\nIf you want to use text in Python, you have to use a **string.**\n\nA **string** is created by entering text between **two single or double quotation masks**\n\n> print(\"Python is fun!\")\n\n> print('Always look on the bright side of life')\n\nThe delimiter (\"or') used for a string doesn't affect how it behaves in anyway.",
"_____no_output_____"
]
],
[
[
"print(\"Hello world!\")",
"Hello world!\n"
]
],
[
[
"**Backslash**\n\nSome characters can't be directly included in a string. For instance, double quotes can't be directly included in a double quote string; this would cause it to end prematurely.\n\nCharacters like these must be escaped by placing a **backslash** before them. Double quotes only need to be escaped in double quote strings, and the same is true for singel quote strings.\n\n**For Example:**\n\n> print('Brian\\'s mother: He\\'s not an angel. He\\'s a very naughty boy!')\n\n**Backslashes** can also be used to escape tabs, arbitraty Unicode characters, and various other things that can't be reliably printed.",
"_____no_output_____"
]
],
[
[
"print('Brain\\'s mother: He\\'s not an angel. He\\'s a very naughty boy!') ",
"Brain's mother: He's not an angel. He's a very naughty boy!\n"
],
[
"print('I\\'m learning!')",
"I'm learning!\n"
]
],
[
[
"**Newlines**\n\n**\\n** represents a new line.\n\nIt can be used in strings to create multi-line output:\n\n> print('One \\nTwo \\nThree')\n\nSimilarly, **\\t** represents a tab.",
"_____no_output_____"
]
],
[
[
"print(\"Hello \\nWorld\")",
"Hello \nWorld\n"
]
],
[
[
"**Newlines**\n\nNewlines will be automatically added for strings that are created using **three quotes**.\n\n**For example**\n\n> print( \n \n \"\"\"\n\n this\n is a \n multiline \n text\n\n \"\"\"\n )\n\nThis makes it easier to format long, multi-line texts without the need to explicitly put **\\n** for line breaks.",
"_____no_output_____"
]
],
[
[
"print(\"Hi\")\nprint(\"\"\"This \nis \ngreat\"\"\")",
"Hi\nThis \nis \ngreat\n"
],
[
"print(\"Hi \\nThis \\nis \\ngreat\")",
"Hi \nThis \nis \ngreat\n"
]
],
[
[
"**Concatenation**\n\nAs with integers and floats, strings in Python can be added, using a process called **concatenation**, which can be done on any two strings.\n\n> print(\"Spam\" + 'eggs')\n\nEven if your strings contain numbers, they are still added as strings rather than integers.\n\n> print(\"2\" + \"2\")\n\n**Adding** a **string** to a **number** produces an **error**, as even though they might look similar, they are two different entities. ",
"_____no_output_____"
]
],
[
[
"print(\"Python \" + \"is \" + \"awesome. \")",
"Python is awesome. \n"
]
],
[
[
"**String Operations**\n\nStrings can also be **multipled by** **integers.** \n\nThis produces a **repeated version of the original string**. The order of the string and the integer doesn't matter, but the string usually coms first.\n\n> print(\"spam\" *3)\n\n> print(4 * '2')\n\nStrings can't be multiplied by other strings. Strings also can't be multiplied by floats, even if the floats are whole numbers.",
"_____no_output_____"
]
],
[
[
"print(3*'7')",
"777\n"
]
],
[
[
"**Variables**\n\nA **variable** allows you to store a value by assigning it to a name, which can be used to refer to the value alter in the program.\n\nFor example, in game development, you would use a variable to store the points of the player. \n\nTo assign a variable, use **one equals sign**\n\n> user = \"James\"\n\nIn given example we assigned string \"James\" to user variable.",
"_____no_output_____"
]
],
[
[
"age = 42\n\nprint(age)",
"42\n"
]
],
[
[
"**Variable names**\n\nCertain restrictions apply in regard to the characters that may be used in Python variable names. The only characters that are allowed are \n- **letters,** \n- **numbers,** and \n- **underscores.** \n\nAlso, they can't start with numbers. Not following these rules results in errors.\n\n> this_is_a_normal_name = 7\n\n> 123abc = 7 \nSyntaxError: invalid syntax\n\nPython is a case sensitive programming language. Thus, **Lastname** and **lastname** are two **different variable** names in Python.\n",
"_____no_output_____"
]
],
[
[
"A_VARIABLE_NAME = True\n\nif A_VARIABLE_NAME == True:\n print(\"yes\")\n\n",
"yes\n"
]
],
[
[
"**Working with Variables**\n\nYou can use variables to perform corresponding operations, just as you did with numbers and strings:\n\n> x = 7\n\n> print(x)\n\n> print( x + 3)\n\n> print(x)\n\nAs you can see, the variable stores its value throughout the program.",
"_____no_output_____"
]
],
[
[
"spam = \"eggs\"\n\nprint(spam*3)",
"eggseggseggs\n"
]
],
[
[
"**Working with Variables**\n\nVariables can be reassigned as many times as you want, in order to change their value.\n\n**In Python**, variables **don't have specific types**, so you can assign a string to a variable, and later assign an integer to the same variable.\n\n> x = 123.456\n\n> print(x)\n\n> x = \"This is a string\"\n\n> print(x + \"!\")\n\nHowever, it is not good practice. To avaid mistakes, try to avoid overwriting the same variable with different data types.",
"_____no_output_____"
]
],
[
[
"x = 5\ny = 7\n\nprint(x + y)",
"12\n"
]
],
[
[
"**Input**\n\nLet's assume we want to take the age of the user as input. We know that the **input()** function returns a string. To convert it to a number, we can use the **int()** function.\n\n> age = int(input())\n\n> print(age)\n\nSimilarly, inorder to convert a number to a string, the \"str()\" function is used. This can be useful if you need to use a number in string concatenation.\n\nFor example:\n\n> age = 42\n\n> print(\"His age is \" + str(age))",
"_____no_output_____"
]
],
[
[
"x = \"2\"\ny = \"4\"\nz = int(x) + int(y)\nprint(z)",
"6\n"
]
],
[
[
"**Input**\n\nYou can use input() multiple times to take multiple user inputs \n\n**For example:**\n\n> name = input()\n\n> age = input()\n\n> print(name + \" is \" + age)\n\nWhen input() function executes, program flow stops until a user enters some value.",
"_____no_output_____"
]
],
[
[
"x = int(input())\ny = int(input())\n\nprint(x + y)",
"7\n3\n10\n"
]
],
[
[
"**In-Place Operators**\n\n**In-place operators** allow you to write code like 'x = x + 3' more concisely, as ' x +=3'.\n\nThe same thing is possible with other operators such as -, * , /and % as well.\n\n> x = 2 \n\n> print(x)\n\n> x += 3\n\n> print(x)",
"_____no_output_____"
]
],
[
[
"x = 4\nx *=3\n\nprint(x)",
"12\n"
]
],
[
[
"**In-place Operators**\n\nThese operators can be used on types other than numbers, as well, such as **strings**\n\n> x = \"spam\"\n\n> print(x)\n\n> x += \"eggs\"\n\n> print(x)\n\nIn-place operators can be used for any numerical operation( + , - , * , / , %, **, //).",
"_____no_output_____"
]
],
[
[
"x = \"a\"\nx *= 3\n\nprint(x)",
"aaa\n"
],
[
"spam = \"7\"\nspam = spam + \"0\"\neggs = int(spam) + 3\n\nprint(float(eggs))",
"73.0\n"
],
[
"#enter '42' as input:\n\nage = int(input())\nprint(age + 8)",
"42\n50\n"
],
[
"x = 5\ny = x +3\ny = int(str(y) + \"2\")\n\nprint(y)",
"82\n"
],
[
"x = 4\nx += 5\n\nprint(x)",
"9\n"
],
[
"x = 3 \nnum = 17\n\nprint(num%x) # 3*5 =15",
"2\n"
],
[
"name = input()\n\nprint(\"Welcome,\"+ name)",
"john\nWelcome,john\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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a3739905c509c275e789c1ba85d72428569e9b6
| 28,039 |
ipynb
|
Jupyter Notebook
|
data/eHealth_kd.ipynb
|
eHealth-KD-PUCs-UFMG/vicomtech
|
411553d1347994f29f563cb421fa97d4d53e51b5
|
[
"MIT"
] | 4 |
2021-08-19T13:14:33.000Z
|
2022-03-08T01:44:50.000Z
|
data/eHealth_kd.ipynb
|
eHealth-KD-PUCs-UFMG/pucrj-pucpr-ufmg
|
411553d1347994f29f563cb421fa97d4d53e51b5
|
[
"MIT"
] | null | null | null |
data/eHealth_kd.ipynb
|
eHealth-KD-PUCs-UFMG/pucrj-pucpr-ufmg
|
411553d1347994f29f563cb421fa97d4d53e51b5
|
[
"MIT"
] | 1 |
2021-05-09T19:32:23.000Z
|
2021-05-09T19:32:23.000Z
| 51.542279 | 722 | 0.496202 |
[
[
[
"Importando as Dependências",
"_____no_output_____"
]
],
[
[
"import os\nimport copy\n# os.chdir('corpora')\n\nfrom scripts.anntools import Collection\nfrom pathlib import Path\n\nimport nltk\nnltk.download('punkt')",
"[nltk_data] Downloading package punkt to\n[nltk_data] /Users/thiagocastroferreira/nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n"
]
],
[
[
"Leitura de Arquivo",
"_____no_output_____"
]
],
[
[
"c = Collection()\n\nfor fname in Path(\"original/training/\").rglob(\"*.txt\"):\n c.load(fname)",
"_____no_output_____"
]
],
[
[
"Acesso a uma instância anotada",
"_____no_output_____"
]
],
[
[
"c.sentences[0]",
"_____no_output_____"
]
],
[
[
"Acesso ao texto de uma instância",
"_____no_output_____"
]
],
[
[
"c.sentences[0].text",
"_____no_output_____"
]
],
[
[
"Acesso às entidades nomeadas de uma instância",
"_____no_output_____"
]
],
[
[
"c.sentences[0].keyphrases",
"_____no_output_____"
]
],
[
[
"Acesso às relações anotadas de uma instância",
"_____no_output_____"
]
],
[
[
"c.sentences[0].relations",
"_____no_output_____"
]
],
[
[
"Pré-processando os Dados",
"_____no_output_____"
]
],
[
[
"def extract_keyphrases(keyphrases, text):\n tags = {}\n for keyphrase in sorted(keyphrases, key=lambda x: len(x.text)):\n ktext = keyphrase.text\n ktokens = [text[s[0]:s[1]] for s in keyphrase.spans]\n\n # casos contínuos\n idxs, ponteiro = [], 0\n for i, token in enumerate(tokens):\n if token == ktokens[ponteiro]:\n idxs.append(i)\n ponteiro += 1\n else:\n idxs, ponteiro = [], 0\n\n if ponteiro == len(ktokens):\n break\n \n if len(ktokens) != len(idxs):\n idxs, ponteiro = [], 0\n for i, token in enumerate(tokens):\n if token == ktokens[ponteiro]:\n idxs.append(i)\n ponteiro += 1\n\n if ponteiro == len(ktokens):\n break\n\n error = False\n if len(ktokens) != len(idxs):\n error = True\n\n tags[keyphrase.id] = {\n 'text': ktext,\n 'idxs': idxs,\n 'tokens': [text[s[0]:s[1]] for s in keyphrase.spans],\n 'attributes': [attr.__repr__() for attr in keyphrase.attributes],\n 'spans': keyphrase.spans,\n 'label': keyphrase.label,\n 'id': keyphrase.id,\n 'error': error\n }\n return tags\n\ndata = []\nfor instance in c.sentences:\n text = instance.text\n tokens = nltk.word_tokenize(text.replace('–', ' – '), language='spanish')\n\n keyphrases = extract_keyphrases(instance.keyphrases, text)\n\n relations = []\n for relation in instance.relations:\n relations.append({ \n 'arg1': relation.origin,\n 'arg2': relation.destination,\n 'label': relation.label \n })\n\n data.append({\n 'text': text,\n 'tokens': tokens,\n 'keyphrases': keyphrases,\n 'relations': relations\n })",
"_____no_output_____"
]
],
[
[
"Separando dados e salvando",
"_____no_output_____"
]
],
[
[
"from random import shuffle\n\nshuffle(data)",
"_____no_output_____"
],
[
"size = int(len(data)*0.2)\ntrainset, _set = data[size:], data[:size]\n\nsize = int(len(_set)*0.5)\ndevset, testset = _set[size:], _set[:size]",
"_____no_output_____"
],
[
"import json\n\nif not os.path.exists('preprocessed'):\n os.mkdir('preprocessed')\n\njson.dump(trainset, open('preprocessed/trainset.json', 'w'), sort_keys=True, indent=4, separators=(',', ':'))\njson.dump(devset, open('preprocessed/devset.json', 'w'), sort_keys=True, indent=4, separators=(',', ':'))\njson.dump(testset, open('preprocessed/testset.json', 'w'), sort_keys=True, indent=4, separators=(',', ':'))",
"_____no_output_____"
],
[
"for row in trainset:\n keyphrases = row['keyphrases']\n for kid in keyphrases:\n keyphrase = keyphrases[kid]\n for i, idx in enumerate(keyphrase['idxs']):\n if i > 0:\n if keyphrase['idxs'][i-1]+1 != idx:\n print(keyphrase)\n print(row['tokens'])\n print()\n break\n ",
"{'text': 'exámenes de laboratorio', 'idxs': [17, 21, 22], 'tokens': ['exámenes', 'de', 'laboratorio'], 'attributes': [], 'spans': [(106, 114), (129, 131), (132, 143)], 'label': 'Concept', 'id': 2155, 'error': False}\n['El', 'doctor', 'diagnosticará', 'la', 'endocarditis', 'basándose', 'en', 'sus', 'factores', 'de', 'riesgo', ',', 'historia', 'clínica', ',', 'síntomas', 'y', 'exámenes', 'del', 'corazón', 'y', 'de', 'laboratorio', '.']\n\n{'text': 'agencia de inteligencia', 'idxs': [24, 26, 27], 'tokens': ['agencia', 'de', 'inteligencia'], 'attributes': [], 'spans': [(168, 175), (183, 185), (186, 198)], 'label': 'Concept', 'id': 3135, 'error': False}\n['Los', 'talibanes', 'rápidamente', 'se', 'atribuyeron', 'responsabilidad', 'por', 'la', 'explosión', ',', 'afirmando', 'que', 'el', 'atacante', 'tenía', 'como', 'objetivo', 'dos', 'minibuses', 'que', 'transportaban', 'personal', 'de', 'la', 'agencia', 'afgana', 'de', 'inteligencia', 'y', 'que', '38', 'de', 'ellos', 'fueron', 'asesinados', '.']\n\n{'text': 'colitis ulcerosa', 'idxs': [28, 31], 'tokens': ['colitis', 'ulcerosa'], 'attributes': [], 'spans': [(192, 199), (213, 221)], 'label': 'Concept', 'id': 6741, 'error': False}\n['Existen', 'muchas', 'causas', 'posibles', 'de', 'hemorragia', 'gastrointestinal', ',', 'entre', 'ellas', 'se', 'encuentran', 'hemorroides', ',', 'úlceras', 'pépticas', ',', 'desgarres', 'o', 'inflamación', 'en', 'el', 'esófago', ',', 'diverticulosis', 'y', 'diverticulitis', ',', 'colitis', 'ulcerativa', 'o', 'ulcerosa', 'y', 'enfermedad', 'de', 'Crohn', ',', 'pólipos', 'del', 'colon', 'o', 'cáncer', 'de', 'colon', ',', 'estómago', 'o', 'esófago', '.']\n\n{'text': 'cáncer de esófago', 'idxs': [41, 42, 47], 'tokens': ['cáncer', 'de', 'esófago'], 'attributes': [], 'spans': [(265, 271), (272, 274), (293, 300)], 'label': 'Concept', 'id': 6746, 'error': False}\n['Existen', 'muchas', 'causas', 'posibles', 'de', 'hemorragia', 'gastrointestinal', ',', 'entre', 'ellas', 'se', 'encuentran', 'hemorroides', ',', 'úlceras', 'pépticas', ',', 'desgarres', 'o', 'inflamación', 'en', 'el', 'esófago', ',', 'diverticulosis', 'y', 'diverticulitis', ',', 'colitis', 'ulcerativa', 'o', 'ulcerosa', 'y', 'enfermedad', 'de', 'Crohn', ',', 'pólipos', 'del', 'colon', 'o', 'cáncer', 'de', 'colon', ',', 'estómago', 'o', 'esófago', '.']\n\n{'text': 'cáncer de estómago', 'idxs': [41, 42, 45], 'tokens': ['cáncer', 'de', 'estómago'], 'attributes': [], 'spans': [(265, 271), (272, 274), (282, 290)], 'label': 'Concept', 'id': 6745, 'error': False}\n['Existen', 'muchas', 'causas', 'posibles', 'de', 'hemorragia', 'gastrointestinal', ',', 'entre', 'ellas', 'se', 'encuentran', 'hemorroides', ',', 'úlceras', 'pépticas', ',', 'desgarres', 'o', 'inflamación', 'en', 'el', 'esófago', ',', 'diverticulosis', 'y', 'diverticulitis', ',', 'colitis', 'ulcerativa', 'o', 'ulcerosa', 'y', 'enfermedad', 'de', 'Crohn', ',', 'pólipos', 'del', 'colon', 'o', 'cáncer', 'de', 'colon', ',', 'estómago', 'o', 'esófago', '.']\n\n{'text': 'cuadros de tos', 'idxs': [1, 3, 4], 'tokens': ['cuadros', 'de', 'tos'], 'attributes': [], 'spans': [(4, 11), (19, 21), (22, 25)], 'label': 'Concept', 'id': 418, 'error': False}\n['Los', 'cuadros', 'agudos', 'de', 'tos', 'son', 'los', 'que', 'se', 'adquieren', 'frecuentemente', 'con', 'un', 'resfrío', 'o', 'una', 'gripe', '.']\n\n{'text': 'terapia del habla', 'idxs': [7, 12, 13], 'tokens': ['terapia', 'del', 'habla'], 'attributes': [], 'spans': [(45, 52), (75, 78), (79, 84)], 'label': 'Concept', 'id': 2055, 'error': False}\n['El', 'tratamiento', 'incluye', 'medicinas', ',', 'aparatos', 'y', 'terapia', 'física', ',', 'ocupacional', 'y', 'del', 'habla', '.']\n\n{'text': 'terapia ocupacional', 'idxs': [7, 10], 'tokens': ['terapia', 'ocupacional'], 'attributes': [], 'spans': [(45, 52), (61, 72)], 'label': 'Concept', 'id': 2054, 'error': False}\n['El', 'tratamiento', 'incluye', 'medicinas', ',', 'aparatos', 'y', 'terapia', 'física', ',', 'ocupacional', 'y', 'del', 'habla', '.']\n\n{'text': 'enfermedades cardiacas', 'idxs': [5, 8], 'tokens': ['enfermedades', 'cardiacas'], 'attributes': [], 'spans': [(28, 40), (53, 62)], 'label': 'Concept', 'id': 6890, 'error': False}\n['Entre', 'estos', 'se', 'incluyen', 'las', 'enfermedades', 'pulmonares', ',', 'cardiacas', ',', 'vasculares', ',', 'derrames', 'cerebrales', 'y', 'cataratas', '.']\n\n{'text': 'enfermedades vasculares', 'idxs': [5, 10], 'tokens': ['enfermedades', 'vasculares'], 'attributes': [], 'spans': [(28, 40), (64, 74)], 'label': 'Concept', 'id': 6891, 'error': False}\n['Entre', 'estos', 'se', 'incluyen', 'las', 'enfermedades', 'pulmonares', ',', 'cardiacas', ',', 'vasculares', ',', 'derrames', 'cerebrales', 'y', 'cataratas', '.']\n\n{'text': 'domingo 10', 'idxs': [4, 6], 'tokens': ['domingo', '10'], 'attributes': [], 'spans': [(16, 23), (25, 27)], 'label': 'Concept', 'id': 413, 'error': False}\n['En', 'la', 'noche', 'del', 'domingo', '(', '10', ')', 'el', 'coronel', 'retirado', 'Antonio', 'Rodríguez', 'Buratti', 'se', 'suicidó', 'disparándose', 'a', 'la', 'cabeza', 'en', 'el', 'garage', 'del', 'edificio', 'en', 'que', 'vivía', 'en', 'la', 'capital', 'uruguaya', '.']\n\n{'text': 'enfermedades del corazón', 'idxs': [17, 20, 21], 'tokens': ['enfermedades', 'del', 'corazón'], 'attributes': [], 'spans': [(113, 125), (137, 140), (141, 148)], 'label': 'Concept', 'id': 7037, 'error': False}\n['Los', 'problemas', 'valvulares', 'pueden', 'aparecer', 'al', 'momento', 'del', 'nacimiento', 'o', 'ser', 'consecuencia', 'de', 'infecciones', ',', 'infartos', 'o', 'enfermedades', 'o', 'lesiones', 'del', 'corazón', '.']\n\n{'text': 'cuatro semanas', 'idxs': [8, 11], 'tokens': ['cuatro', 'semanas'], 'attributes': [], 'spans': [(57, 63), (71, 78)], 'label': 'Concept', 'id': 3642, 'error': False}\n['Su', 'bebé', 'recibirá', 'medicamentos', 'contra', 'el', 'VIH/SIDA', 'durante', 'cuatro', 'a', 'seis', 'semanas', 'después', 'del', 'nacimiento', '.']\n\n{'text': 'cánceres de mama', 'idxs': [1, 9, 10], 'tokens': ['cánceres', 'de', 'mama'], 'attributes': [], 'spans': [(4, 12), (47, 49), (50, 54)], 'label': 'Concept', 'id': 5792, 'error': False}\n['Los', 'cánceres', 'más', 'comunes', 'en', 'el', 'embarazo', 'son', 'el', 'de', 'mama', ',', 'de', 'cuello', 'uterino', ',', 'linfoma', 'y', 'melanoma', '.']\n\n{'text': 'cánceres de cuello uterino', 'idxs': [1, 9, 13, 14], 'tokens': ['cánceres', 'de', 'cuello', 'uterino'], 'attributes': [], 'spans': [(4, 12), (56, 58), (59, 65), (66, 73)], 'label': 'Concept', 'id': 5793, 'error': False}\n['Los', 'cánceres', 'más', 'comunes', 'en', 'el', 'embarazo', 'son', 'el', 'de', 'mama', ',', 'de', 'cuello', 'uterino', ',', 'linfoma', 'y', 'melanoma', '.']\n\n{'text': 'defecto de nacimiento', 'idxs': [16, 19, 20], 'tokens': ['defecto', 'de', 'nacimiento'], 'attributes': [], 'spans': [(87, 94), (107, 109), (110, 120)], 'label': 'Concept', 'id': 5145, 'error': False}\n['Si', 'la', 'afecta', 'durante', 'los', 'primeros', 'tres', 'meses', 'del', 'embarazo', ',', 'este', 'riesgo', 'puede', 'causar', 'un', 'defecto', 'congénito', 'o', 'de', 'nacimiento', 'o', 'un', 'aborto', 'espontáneo', '.']\n\n{'text': 'pruebas de médula ósea', 'idxs': [7, 8, 12, 13], 'tokens': ['pruebas', 'de', 'médula', 'ósea'], 'attributes': [], 'spans': [(49, 56), (69, 71), (72, 78), (79, 83)], 'label': 'Concept', 'id': 4977, 'error': False}\n['La', 'leucemia', 'linfocítica', 'aguda', 'se', 'diagnostica', 'con', 'pruebas', 'de', 'sangre', 'y', 'de', 'médula', 'ósea', '.']\n\n{'text': 'sistemas muscular', 'idxs': [9, 12], 'tokens': ['sistemas', 'muscular'], 'attributes': [], 'spans': [(47, 55), (66, 74)], 'label': 'Concept', 'id': 5090, 'error': False}\n['La', 'vitamina', 'D', 'juega', 'un', 'papel', 'importante', 'en', 'los', 'sistemas', 'nervioso', ',', 'muscular', 'e', 'inmunitario', '.']\n\n{'text': 'sistemas inmunitario', 'idxs': [9, 14], 'tokens': ['sistemas', 'inmunitario'], 'attributes': [], 'spans': [(47, 55), (77, 88)], 'label': 'Concept', 'id': 5091, 'error': False}\n['La', 'vitamina', 'D', 'juega', 'un', 'papel', 'importante', 'en', 'los', 'sistemas', 'nervioso', ',', 'muscular', 'e', 'inmunitario', '.']\n\n{'text': '20 años', 'idxs': [11, 14], 'tokens': ['20', 'años'], 'attributes': [], 'spans': [(74, 76), (82, 86)], 'label': 'Concept', 'id': 3733, 'error': False}\n['El', 'cáncer', 'de', 'testículos', 'afecta', 'principalmente', 'a', 'hombres', 'jóvenes', 'entre', 'los', '20', 'y', '39', 'años', '.']\n\n{'text': 'uno días', 'idxs': [12, 15], 'tokens': ['uno', 'días'], 'attributes': [], 'spans': [(81, 84), (91, 95)], 'label': 'Concept', 'id': 6857, 'error': False}\n['La', 'polimialgia', 'reumática', 'responde', 'muy', 'bien', 'al', 'tratamiento', 'y', 'puede', 'desaparecer', 'en', 'uno', 'o', 'dos', 'días', '.']\n\n{'text': 'árbol del caucho', 'idxs': [9, 11, 12], 'tokens': ['árbol', 'del', 'caucho'], 'attributes': [], 'spans': [(48, 53), (63, 66), (67, 73)], 'label': 'Concept', 'id': 1378, 'error': False}\n['El', 'látex', 'es', 'un', 'líquido', 'lechoso', 'que', 'proviene', 'del', 'árbol', 'tropical', 'del', 'caucho', '.']\n\n{'text': 'una de cuatro', 'idxs': [2, 3, 5], 'tokens': ['una', 'de', 'cuatro'], 'attributes': [], 'spans': [(9, 12), (13, 15), (21, 27)], 'label': 'Predicate', 'id': 3262, 'error': False}\n['Cerca', 'de', 'una', 'de', 'cada', 'cuatro', 'personas', 'con', 'VIH', 'en', 'los', 'Estados', 'Unidos', 'es', 'mujer', '.']\n\n{'text': 'final de vida', 'idxs': [15, 16, 18], 'tokens': ['final', 'de', 'vida'], 'attributes': [], 'spans': [(87, 92), (93, 95), (99, 103)], 'label': 'Concept', 'id': 7113, 'error': False}\n['Éstas', 'pueden', 'ayudar', 'a', 'los', 'proveedores', 'de', 'salud', 'y', 'familiares', 'a', 'tomar', 'decisiones', 'para', 'el', 'final', 'de', 'la', 'vida', 'si', 'usted', 'no', 'puede', 'tomarlas', '.']\n\n{'text': 'medios de comunicación', 'idxs': [5, 7, 8], 'tokens': ['medios', 'de', 'comunicación'], 'attributes': [], 'spans': [(27, 33), (50, 52), (53, 65)], 'label': 'Concept', 'id': 1268, 'error': False}\n['El', 'hecho', 'fue', 'condenado', 'por', 'medios', 'internacionales', 'de', 'comunicación', '.']\n\n{'text': 'sentidos del olfato', 'idxs': [1, 2, 6], 'tokens': ['sentidos', 'del', 'olfato'], 'attributes': [], 'spans': [(4, 12), (13, 16), (28, 34)], 'label': 'Concept', 'id': 6156, 'error': False}\n['Los', 'sentidos', 'del', 'gusto', 'y', 'el', 'olfato', 'nos', 'brindan', 'gran', 'placer', '.']\n\n{'text': '1 de 2.500', 'idxs': [10, 11, 13], 'tokens': ['1', 'de', '2.500'], 'attributes': [], 'spans': [(55, 56), (57, 59), (65, 70)], 'label': 'Predicate', 'id': 5328, 'error': False}\n['En', 'los', 'Estados', 'Unidos', ',', 'la', 'CMT', 'afecta', 'aproximadamente', 'a', '1', 'de', 'cada', '2.500', 'personas', '.']\n\n{'text': 'sistema muscular', 'idxs': [9, 12], 'tokens': ['sistema', 'muscular'], 'attributes': [], 'spans': [(41, 48), (59, 67)], 'label': 'Concept', 'id': 3176, 'error': False}\n['La', 'vitamina', 'D', 'también', 'juega', 'un', 'rol', 'en', 'su', 'sistema', 'nervioso', ',', 'muscular', 'e', 'inmunitario', '.']\n\n{'text': 'sistema inmunitario', 'idxs': [9, 14], 'tokens': ['sistema', 'inmunitario'], 'attributes': [], 'spans': [(41, 48), (70, 81)], 'label': 'Concept', 'id': 3177, 'error': False}\n['La', 'vitamina', 'D', 'también', 'juega', 'un', 'rol', 'en', 'su', 'sistema', 'nervioso', ',', 'muscular', 'e', 'inmunitario', '.']\n\n{'text': 'Instituto Nacional del Corazón los Pulmones y la Sangre', 'idxs': [16, 17, 18, 19, 21, 22, 23, 24, 25], 'tokens': ['Instituto', 'Nacional', 'del', 'Corazón', 'los', 'Pulmones', 'y', 'la', 'Sangre'], 'attributes': [], 'spans': [(101, 110), (111, 119), (120, 123), (124, 131), (133, 136), (137, 145), (146, 147), (148, 150), (151, 157)], 'label': 'Concept', 'id': 53, 'error': False}\n['La', 'dieta', 'consiste', 'en', 'un', 'plan', 'de', 'alimentación', 'basado', 'en', 'estudios', 'de', 'investigación', 'patrocinados', 'por', 'el', 'Instituto', 'Nacional', 'del', 'Corazón', ',', 'los', 'Pulmones', 'y', 'la', 'Sangre', '(', 'NHLBI', ')', '.']\n\n{'text': 'ozono bueno', 'idxs': [1, 3], 'tokens': ['ozono', 'bueno'], 'attributes': [], 'spans': [(3, 8), (10, 15)], 'label': 'Concept', 'id': 4578, 'error': False}\n['El', 'ozono', '``', 'bueno', \"''\", 'se', 'encuentra', 'en', 'la', 'naturaleza', 'a', 'aproximadamente', '10', 'a', '30', 'millas', 'sobre', 'la', 'superficie', 'terrestre', '.']\n\n{'text': 'cadena de televisión', 'idxs': [1, 3, 4], 'tokens': ['cadena', 'de', 'televisión'], 'attributes': [], 'spans': [(3, 9), (19, 21), (22, 32)], 'label': 'Concept', 'id': 2047, 'error': False}\n['En', 'cadena', 'nacional', 'de', 'televisión', ',', 'Chinchilla', 'afirmó', 'que', 'la', 'concesión', 'se', 'suspendió', 'por', '``', 'mutuo', 'acuerdo', \"''\", ',', 'sin', 'embargo', 'sus', 'detractores', 'no', 'ven', 'con', 'buenos', 'ojos', 'que', 'el', 'Gobierno', 'pague', 'a', 'la', 'empresa', 'tal', 'cantidad', 'de', 'dinero', ',', 'puesto', 'que', '``', 'no', 'movieron', 'ni', 'una', 'piedra', \"''\", '.']\n\n{'text': 'gotas para ojos', 'idxs': [4, 5, 7], 'tokens': ['gotas', 'para', 'ojos'], 'attributes': [], 'spans': [(32, 37), (38, 42), (47, 51)], 'label': 'Concept', 'id': 3821, 'error': False}\n['Los', 'tratamientos', 'suelen', 'incluir', 'gotas', 'para', 'los', 'ojos', 'y/o', 'cirugía', '.']\n\n{'text': 'gammagrafía de tiroides', 'idxs': [9, 10, 12], 'tokens': ['gammagrafía', 'de', 'tiroides'], 'attributes': [], 'spans': [(44, 55), (56, 58), (62, 70)], 'label': 'Concept', 'id': 147, 'error': False}\n['Un', 'tipo', 'de', 'examen', 'de', 'medicina', 'nuclear', 'es', 'la', 'gammagrafía', 'de', 'la', 'tiroides', '.']\n\n{'text': '65 años', 'idxs': [8, 11], 'tokens': ['65', 'años'], 'attributes': [], 'spans': [(47, 49), (55, 59)], 'label': 'Concept', 'id': 188, 'error': False}\n['Las', 'pruebas', 'se', 'recomiendan', 'a', 'personas', 'de', 'entre', '65', 'y', '75', 'años', 'si', 'tienen', 'antecedentes', 'familiares', 'o', 'si', 'son', 'hombres', 'fumadores', '.']\n\n{'text': 'domingo 10', 'idxs': [4, 6], 'tokens': ['domingo', '10'], 'attributes': [], 'spans': [(16, 23), (25, 27)], 'label': 'Concept', 'id': 2828, 'error': False}\n['En', 'la', 'noche', 'del', 'domingo', '(', '10', ')', 'el', 'coronel', 'retirado', 'Antonio', 'Rodríguez', 'Buratti', 'se', 'suicidó', 'disparándose', 'a', 'la', 'cabeza', 'en', 'el', 'garage', 'del', 'edificio', 'en', 'que', 'vivía', 'en', 'la', 'capital', 'uruguaya', '.']\n\n{'text': 'medios de comunicación', 'idxs': [5, 7, 8], 'tokens': ['medios', 'de', 'comunicación'], 'attributes': [], 'spans': [(27, 33), (50, 52), (53, 65)], 'label': 'Concept', 'id': 3103, 'error': False}\n['El', 'hecho', 'fue', 'condenado', 'por', 'medios', 'internacionales', 'de', 'comunicación', '.']\n\n{'text': 'sinusitis crónica', 'idxs': [10, 13], 'tokens': ['sinusitis', 'crónica'], 'attributes': [], 'spans': [(73, 82), (91, 98)], 'label': 'Concept', 'id': 3981, 'error': False}\n['Alergias', ',', 'problemas', 'nasales', 'y', 'ciertas', 'enfermedades', 'también', 'pueden', 'causar', 'sinusitis', 'aguda', 'y', 'crónica', '.']\n\n{'text': 'enfermedades cardíacas', 'idxs': [1, 5], 'tokens': ['enfermedades', 'cardíacas'], 'attributes': [], 'spans': [(4, 16), (30, 39)], 'label': 'Concept', 'id': 5373, 'error': False}\n['Las', 'enfermedades', 'del', 'corazón', '(', 'cardíacas', ')', 'son', 'la', 'principal', 'causa', 'de', 'muerte', 'en', 'los', 'Estados', 'Unidos', 'y', 'también', 'una', 'causa', 'importante', 'de', 'discapacidad', '.']\n\n{'text': 'análisis de orina', 'idxs': [1, 2, 5], 'tokens': ['análisis', 'de', 'orina'], 'attributes': [], 'spans': [(4, 12), (13, 15), (25, 30)], 'label': 'Concept', 'id': 2964, 'error': False}\n['Los', 'análisis', 'de', 'sangre', 'y', 'orina', 'son', 'la', 'única', 'manera', 'de', 'saber', 'si', 'usted', 'tiene', 'enfermedad', 'renal', '.']\n\n{'text': 'uno días', 'idxs': [4, 7], 'tokens': ['uno', 'días'], 'attributes': [], 'spans': [(24, 27), (34, 38)], 'label': 'Concept', 'id': 2477, 'error': False}\n['El', 'dolor', 'puede', 'comenzar', 'uno', 'o', 'dos', 'días', 'antes', 'de', 'su', 'período', '.']\n\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",
"code",
"code",
"code"
]
] |
4a3740407459e016b6be7ce7e21d0520b7ba727e
| 40,317 |
ipynb
|
Jupyter Notebook
|
labs/lab1/python_numpy_tutorial.ipynb
|
deep-learning-su/deep-learning-su
|
43f37d289c1a610426fbfcb005bff00f55041252
|
[
"MIT"
] | 15 |
2018-02-25T20:55:17.000Z
|
2021-11-08T13:41:56.000Z
|
labs/lab1/python_numpy_tutorial.ipynb
|
deep-learning-su/deep-learning-su
|
43f37d289c1a610426fbfcb005bff00f55041252
|
[
"MIT"
] | 16 |
2020-01-28T22:39:06.000Z
|
2022-03-11T23:42:33.000Z
|
labs/lab1/python_numpy_tutorial.ipynb
|
deep-learning-su/deep-learning-su
|
43f37d289c1a610426fbfcb005bff00f55041252
|
[
"MIT"
] | 2 |
2018-05-21T21:34:55.000Z
|
2019-02-26T15:50:31.000Z
| 26.895931 | 580 | 0.491629 |
[
[
[
"# SU Deep Learning with Tensorflow: Python & NumPy Tutorial",
"_____no_output_____"
],
[
"Python 3 and NumPy will be used extensively throughout this course, so it's important to be familiar with them. \n\nOne can also check the website's tutorial for further preparation:\nhttps://deep-learning-su.github.io/python-numpy-tutorial/",
"_____no_output_____"
],
[
"## Python 3",
"_____no_output_____"
],
[
"If you're unfamiliar with Python 3, here are some of the most common changes from Python 2 to look out for.",
"_____no_output_____"
],
[
"### Print is a function",
"_____no_output_____"
]
],
[
[
"print(\"Hello!\")",
"Hello!\n"
]
],
[
[
"Without parentheses, printing will not work.",
"_____no_output_____"
]
],
[
[
"print \"Hello!\"",
"_____no_output_____"
]
],
[
[
"### Floating point division by default",
"_____no_output_____"
]
],
[
[
"5 / 2",
"_____no_output_____"
]
],
[
[
"To do integer division, we use two backslashes:",
"_____no_output_____"
]
],
[
[
"5 // 2",
"_____no_output_____"
]
],
[
[
"### No xrange",
"_____no_output_____"
],
[
"The xrange from Python 2 is now merged into \"range\" for Python 3 and there is no xrange in Python 3. In Python 3, range(3) does not create a list of 3 elements as it would in Python 2, rather just creates a more memory efficient iterator.\n\nHence, \nxrange in Python 3: Does not exist \nrange in Python 3: Has very similar behavior to Python 2's xrange",
"_____no_output_____"
]
],
[
[
"for i in range(3):\n print(i)",
"0\n1\n2\n"
],
[
"range(3)",
"_____no_output_____"
],
[
"# If need be, can use the following to get a similar behavior to Python 2's range:\nprint(list(range(3)))",
"[0, 1, 2]\n"
]
],
[
[
"# NumPy",
"_____no_output_____"
],
[
"\"NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more\" \n-https://docs.scipy.org/doc/numpy-1.10.1/user/whatisnumpy.html.",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
]
],
[
[
"Let's run through an example showing how powerful NumPy is. Suppose we have two lists a and b, consisting of the first 100,000 non-negative numbers, and we want to create a new list c whose *i*th element is a[i] + 2 * b[i]. \n\nWithout NumPy:",
"_____no_output_____"
]
],
[
[
"%%time\na = [i for i in range(100000)]\nb = [i for i in range(100000)]",
"CPU times: user 13.6 ms, sys: 10.4 ms, total: 24 ms\nWall time: 23.4 ms\n"
],
[
"%%time\nc = []\nfor i in range(len(a)):\n c.append(a[i] + 2 * b[i])",
"CPU times: user 52 ms, sys: 7.44 ms, total: 59.4 ms\nWall time: 60.5 ms\n"
]
],
[
[
"With NumPy:",
"_____no_output_____"
]
],
[
[
"%%time\na = np.arange(100000)\nb = np.arange(100000)",
"CPU times: user 3.62 ms, sys: 3.42 ms, total: 7.04 ms\nWall time: 4.85 ms\n"
],
[
"%%time\nc = a + 2 * b",
"CPU times: user 6.53 ms, sys: 6.13 ms, total: 12.7 ms\nWall time: 9.37 ms\n"
]
],
[
[
"The result is 10 to 15 times faster, and we could do it in fewer lines of code (and the code itself is more intuitive)!",
"_____no_output_____"
],
[
"Regular Python is much slower due to type checking and other overhead of needing to interpret code and support Python's abstractions.\n\nFor example, if we are doing some addition in a loop, constantly type checking in a loop will lead to many more instructions than just performing a regular addition operation. NumPy, using optimized pre-compiled C code, is able to avoid a lot of the overhead introduced.\n\nThe process we used above is **vectorization**. Vectorization refers to applying operations to arrays instead of just individual elements (i.e. no loops).",
"_____no_output_____"
],
[
"Why vectorize?\n1. Much faster\n2. Easier to read and fewer lines of code\n3. More closely assembles mathematical notation\n\nVectorization is one of the main reasons why NumPy is so powerful.",
"_____no_output_____"
],
[
"## ndarray",
"_____no_output_____"
],
[
"ndarrays, n-dimensional arrays of homogenous data type, are the fundamental datatype used in NumPy. As these arrays are of the same type and are fixed size at creation, they offer less flexibility than Python lists, but can be substantially more efficient runtime and memory-wise. (Python lists are arrays of pointers to objects, adding a layer of indirection.)\n\nThe number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.",
"_____no_output_____"
]
],
[
[
"# Can initialize ndarrays with Python lists, for example:\na = np.array([1, 2, 3]) # Create a rank 1 array\nprint(type(a)) # Prints \"<class 'numpy.ndarray'>\"\nprint(a.shape) # Prints \"(3,)\"\nprint(a[0], a[1], a[2]) # Prints \"1 2 3\"\na[0] = 5 # Change an element of the array\nprint(a) # Prints \"[5, 2, 3]\"\n\nb = np.array([[1, 2, 3],\n [4, 5, 6]]) # Create a rank 2 array\nprint(b.shape) # Prints \"(2, 3)\"\nprint(b[0, 0], b[0, 1], b[1, 0]) # Prints \"1 2 4\"",
"<class 'numpy.ndarray'>\n(3,)\n1 2 3\n[5 2 3]\n(2, 3)\n1 2 4\n"
]
],
[
[
"There are many other initializations that NumPy provides:",
"_____no_output_____"
]
],
[
[
"a = np.zeros((2, 2)) # Create an array of all zeros\nprint(a) # Prints \"[[ 0. 0.]\n # [ 0. 0.]]\"\n\nb = np.full((2, 2), 7) # Create a constant array\nprint(b) # Prints \"[[ 7. 7.]\n # [ 7. 7.]]\"\n\nc = np.eye(2) # Create a 2 x 2 identity matrix\nprint(c) # Prints \"[[ 1. 0.]\n # [ 0. 1.]]\"\n\nd = np.random.random((2, 2)) # Create an array filled with random values\nprint(d) # Might print \"[[ 0.91940167 0.08143941]\n # [ 0.68744134 0.87236687]]\"",
"[[0. 0.]\n [0. 0.]]\n[[7 7]\n [7 7]]\n[[1. 0.]\n [0. 1.]]\n[[0.17511952 0.67921684]\n [0.04555329 0.08641358]]\n"
]
],
[
[
"How do we create a 2 by 2 matrix of ones?",
"_____no_output_____"
]
],
[
[
"a = np.ones((2, 2)) # Create an array of all ones\nprint(a) # Prints \"[[ 1. 1.]\n # [ 1. 1.]]\"",
"[[1. 1.]\n [1. 1.]]\n"
]
],
[
[
"Useful to keep track of shape; helpful for debugging and knowing dimensions will be very useful when computing gradients, among other reasons.",
"_____no_output_____"
]
],
[
[
"nums = np.arange(8)\nprint(nums)\nprint(nums.shape)\n\nnums = nums.reshape((2, 4))\nprint('Reshaped:\\n', nums)\nprint(nums.shape)\n\n# The -1 in reshape corresponds to an unknown dimension that numpy will figure out,\n# based on all other dimensions and the array size.\n# Can only specify one unknown dimension.\n# For example, sometimes we might have an unknown number of data points, and\n# so we can use -1 instead without worrying about the true number.\nnums = nums.reshape((4, -1))\nprint('Reshaped with -1:\\n', nums)\nprint(nums.shape)",
"[0 1 2 3 4 5 6 7]\n(8,)\nReshaped:\n [[0 1 2 3]\n [4 5 6 7]]\n(2, 4)\nReshaped with -1:\n [[0 1]\n [2 3]\n [4 5]\n [6 7]]\n(4, 2)\n"
]
],
[
[
"NumPy supports an object-oriented paradigm, such that ndarray has a number of methods and attributes, with functions similar to ones in the outermost NumPy namespace. For example, we can do both:",
"_____no_output_____"
]
],
[
[
"nums = np.arange(8)\nprint(nums.min()) # Prints 0\nprint(np.min(nums)) # Prints 0",
"0\n0\n"
]
],
[
[
"## Array Operations/Math",
"_____no_output_____"
],
[
"NumPy supports many elementwise operations:",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2],\n [3, 4]], dtype=np.float64)\ny = np.array([[5, 6],\n [7, 8]], dtype=np.float64)\n\n# Elementwise sum; both produce the array\n# [[ 6.0 8.0]\n# [10.0 12.0]]\nprint(x + y)\nprint(np.add(x, y))\n\n# Elementwise difference; both produce the array\n# [[-4.0 -4.0]\n# [-4.0 -4.0]]\nprint(x - y)\nprint(np.subtract(x, y))\n\n# Elementwise product; both produce the array\n# [[ 5.0 12.0]\n# [21.0 32.0]]\nprint(x * y)\nprint(np.multiply(x, y))\n\n# Elementwise square root; produces the array\n# [[ 1. 1.41421356]\n# [ 1.73205081 2. ]]\nprint(np.sqrt(x))",
"[[ 6. 8.]\n [10. 12.]]\n[[ 6. 8.]\n [10. 12.]]\n[[-4. -4.]\n [-4. -4.]]\n[[-4. -4.]\n [-4. -4.]]\n[[ 5. 12.]\n [21. 32.]]\n[[ 5. 12.]\n [21. 32.]]\n[[1. 1.41421356]\n [1.73205081 2. ]]\n"
]
],
[
[
"How do we elementwise divide between two arrays?",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2], [3, 4]], dtype=np.float64)\ny = np.array([[5, 6], [7, 8]], dtype=np.float64)\n\n# Elementwise division; both produce the array\n# [[ 0.2 0.33333333]\n# [ 0.42857143 0.5 ]]\nprint(x / y)\nprint(np.divide(x, y))",
"[[0.2 0.33333333]\n [0.42857143 0.5 ]]\n[[0.2 0.33333333]\n [0.42857143 0.5 ]]\n"
]
],
[
[
"Note * is elementwise multiplication, not matrix multiplication. We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot is available both as a function in the numpy module and as an instance method of array objects:\n\n",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2], [3, 4]])\ny = np.array([[5, 6], [7, 8]])\n\nv = np.array([9, 10])\nw = np.array([11, 12])\n\n# Inner product of vectors; both produce 219\nprint(v.dot(w))\nprint(np.dot(v, w))\n\n# Matrix / vector product; both produce the rank 1 array [29 67]\nprint(x.dot(v))\nprint(np.dot(x, v))\n\n# Matrix / matrix product; both produce the rank 2 array\n# [[19 22]\n# [43 50]]\nprint(x.dot(y))\nprint(np.dot(x, y))",
"219\n219\n[29 67]\n[29 67]\n[[19 22]\n [43 50]]\n[[19 22]\n [43 50]]\n"
]
],
[
[
"There are many useful functions built into NumPy, and often we're able to express them across specific axes of the ndarray:",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2, 3], \n [4, 5, 6]])\n\nprint(np.sum(x)) # Compute sum of all elements; prints \"21\"\nprint(np.sum(x, axis=0)) # Compute sum of each column; prints \"[5 7 9]\"\nprint(np.sum(x, axis=1)) # Compute sum of each row; prints \"[6 15]\"\n\nprint(np.max(x, axis=1)) # Compute max of each row; prints \"[3 6]\" ",
"21\n[5 7 9]\n[ 6 15]\n[3 6]\n"
]
],
[
[
"How can we compute the index of the max value of each row? Useful, to say, find the class that corresponds to the maximum score for an input image.",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2, 3], \n [4, 5, 6]])\n\nprint(np.argmax(x, axis=1)) # Compute index of max of each row; prints \"[2 2]\"",
"[2 2]\n"
]
],
[
[
"Note the axis you apply the operation will have its dimension removed from the shape.\nThis is useful to keep in mind when you're trying to figure out what axis corresponds\nto what.\n\nFor example:",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2, 3], \n [4, 5, 6]])\n\nprint(x.shape) # Has shape (2, 3)\nprint((x.max(axis=0)).shape) # Taking the max over axis 0 has shape (3,)\n # corresponding to the 3 columns.\n\n# An array with rank 3\nx = np.array([[[1, 2, 3], \n [4, 5, 6]],\n [[10, 23, 33], \n [43, 52, 16]]\n ])\n\nprint(x)\nprint(x.shape) # Has shape (2, 2, 3)\nprint((x.max(axis=1)).shape) # Taking the max over axis 1 has shape (2, 3)\n\nprint((x.max(axis=(1, 2)))) # Can take max over multiple axes; prints [6 52]\nprint((x.max(axis=(1, 2))).shape) # Taking the max over axes 1, 2 has shape (2,)",
"(2, 3)\n(3,)\n[[[ 1 2 3]\n [ 4 5 6]]\n\n [[10 23 33]\n [43 52 16]]]\n(2, 2, 3)\n(2, 3)\n[ 6 52]\n(2,)\n"
]
],
[
[
"## Indexing",
"_____no_output_____"
],
[
"NumPy also provides powerful indexing schemes.",
"_____no_output_____"
]
],
[
[
"# Create the following rank 2 array with shape (3, 4)\n# [[ 1 2 3 4]\n# [ 5 6 7 8]\n# [ 9 10 11 12]]\na = np.array([[1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12]])\nprint('Original:\\n', a)\n\n# Can select an element as you would in a 2 dimensional Python list\nprint('Element (0, 0) (a[0][0]):\\n', a[0][0]) # Prints 1\n# or as follows\nprint('Element (0, 0) (a[0, 0]) :\\n', a[0, 0]) # Prints 1\n\n# Use slicing to pull out the subarray consisting of the first 2 rows\n# and columns 1 and 2; b is the following array of shape (2, 2):\n# [[2 3]\n# [6 7]]\nb = a[:2, 1:3]\nprint('Sliced (a[:2, 1:3]):\\n', b)\n\n# Steps are also supported in indexing. The following reverses the first row:\nprint('Reversing the first row (a[0, ::-1]) :\\n', a[0, ::-1]) # Prints [4 3 2 1]",
"Original:\n [[ 1 2 3 4]\n [ 5 6 7 8]\n [ 9 10 11 12]]\nElement (0, 0) (a[0][0]):\n 1\nElement (0, 0) (a[0, 0]) :\n 1\nSliced (a[:2, 1:3]):\n [[2 3]\n [6 7]]\nReversing the first row (a[0, ::-1]) :\n [4 3 2 1]\n"
]
],
[
[
"Often, it's useful to select or modify one element from each row of a matrix. The following example employs **fancy indexing**, where we index into our array using an array of indices (say an array of integers or booleans):",
"_____no_output_____"
]
],
[
[
"# Create a new array from which we will select elements\na = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n [10, 11, 12]])\n\nprint(a) # prints \"array([[ 1, 2, 3],\n # [ 4, 5, 6],\n # [ 7, 8, 9],\n # [10, 11, 12]])\"\n\n# Create an array of indices\nb = np.array([0, 2, 0, 1])\n\n# Select one element from each row of a using the indices in b\nprint(a[np.arange(4), b]) # Prints \"[ 1 6 7 11]\"\n\n# Mutate one element from each row of a using the indices in b\na[np.arange(4), b] += 10\n\nprint(a) # prints \"array([[11, 2, 3],\n # [ 4, 5, 16],\n # [17, 8, 9],\n # [10, 21, 12]])\n",
"[[ 1 2 3]\n [ 4 5 6]\n [ 7 8 9]\n [10 11 12]]\n[ 1 6 7 11]\n[[11 2 3]\n [ 4 5 16]\n [17 8 9]\n [10 21 12]]\n"
]
],
[
[
"We can also use boolean indexing/masks. Suppose we want to set all elements greater than MAX to MAX:",
"_____no_output_____"
]
],
[
[
"MAX = 5\nnums = np.array([1, 4, 10, -1, 15, 0, 5])\nprint(nums > MAX) # Prints [False, False, True, False, True, False, False]\n\nnums[nums > MAX] = MAX\nprint(nums) # Prints [1, 4, 5, -1, 5, 0, 5]",
"[False False True False True False False]\n[ 1 4 5 -1 5 0 5]\n"
]
],
[
[
"Finally, note that the indices in fancy indexing can appear in any order and even multiple times:",
"_____no_output_____"
]
],
[
[
"nums = np.array([1, 4, 10, -1, 15, 0, 5])\nprint(nums[[1, 2, 3, 1, 0]]) # Prints [4 10 -1 4 1]",
"[ 4 10 -1 4 1]\n"
]
],
[
[
"## Broadcasting",
"_____no_output_____"
],
[
"Many of the operations we've looked at above involved arrays of the same rank. \nHowever, many times we might have a smaller array and use that multiple times to update an array of a larger rank. \nFor example, consider the below example of shifting the mean of each column from the elements of the corresponding column:",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2, 3],\n [3, 5, 7]])\nprint(x.shape) # Prints (2, 3)\n\ncol_means = x.mean(axis=0)\nprint(col_means) # Prints [2. 3.5 5.]\nprint(col_means.shape) # Prints (3,)\n # Has a smaller rank than x!\n\nmean_shifted = x - col_means\nprint('\\n', mean_shifted)\nprint(mean_shifted.shape) # Prints (2, 3)",
"(2, 3)\n[2. 3.5 5. ]\n(3,)\n\n [[-1. -1.5 -2. ]\n [ 1. 1.5 2. ]]\n(2, 3)\n"
]
],
[
[
"Or even just multiplying a matrix by 2:",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2, 3],\n [3, 5, 7]])\nprint(x * 2) # Prints [[ 2 4 6]\n # [ 6 10 14]]\n",
"[[ 2 4 6]\n [ 6 10 14]]\n"
]
],
[
[
"Broadcasting two arrays together follows these rules:\n\n1. If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.\n2. The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.\n3. The arrays can be broadcast together if they are compatible in all dimensions.\n4. After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.\n5. In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension.",
"_____no_output_____"
],
[
"For example, when subtracting the columns above, we had arrays of shape (2, 3) and (3,).\n\n1. These arrays do not have same rank, so we prepend the shape of the lower rank one to make it (1, 3).\n2. (2, 3) and (1, 3) are compatible (have the same size in the dimension, or if one of the arrays has size 1 in that dimension).\n3. Can be broadcast together!\n4. After broadcasting, each array behaves as if it had shape equal to (2, 3).\n5. The smaller array will behave as if it were copied along dimension 0.",
"_____no_output_____"
],
[
"Let's try to subtract the mean of each row!",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2, 3],\n [3, 5, 7]])\n\nrow_means = x.mean(axis=1)\nprint(row_means) # Prints [2. 5.]\n\nmean_shifted = x - row_means",
"[2. 5.]\n"
]
],
[
[
"To figure out what's wrong, we print some shapes:",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2, 3],\n [3, 5, 7]])\nprint(x.shape) # Prints (2, 3)\n\nrow_means = x.mean(axis=1)\nprint(row_means) # Prints [2. 5.]\nprint(row_means.shape) # Prints (2,)\n\n# Results in the following error: ValueError: operands could not be broadcast together with shapes (2,3) (2,) \nmean_shifted = x - row_means",
"(2, 3)\n[2. 5.]\n(2,)\n"
]
],
[
[
"What happened?",
"_____no_output_____"
],
[
"Answer: If we following broadcasting rule 1, then we'd prepend a 1 to the smaller rank array ot get (1, 2). However, the last dimensions don't match now between (2, 3) and (1, 2), and so we can't broadcast.",
"_____no_output_____"
],
[
"Take 2, reshaping the row means to get the desired behavior:",
"_____no_output_____"
]
],
[
[
"x = np.array([[1, 2, 3],\n [3, 5, 7]])\nprint(x.shape) # Prints (2, 3)\n\nrow_means = x.mean(axis=1).reshape((-1, 1))\nprint(row_means) # Prints [[2.], [5.]]\nprint(row_means.shape) # Prints (2, 1)\n\nmean_shifted = x - row_means\nprint(mean_shifted)\nprint(mean_shifted.shape) # Prints (2, 3)",
"(2, 3)\n[[2.]\n [5.]]\n(2, 1)\n[[-1. 0. 1.]\n [-2. 0. 2.]]\n(2, 3)\n"
]
],
[
[
"More broadcasting examples!",
"_____no_output_____"
]
],
[
[
"# Compute outer product of vectors\nv = np.array([1, 2, 3]) # v has shape (3,)\nw = np.array([4, 5]) # w has shape (2,)\n# To compute an outer product, we first reshape v to be a column\n# vector of shape (3, 1); we can then broadcast it against w to yield\n# an output of shape (3, 2), which is the outer product of v and w:\n# [[ 4 5]\n# [ 8 10]\n# [12 15]]\nprint(np.reshape(v, (3, 1)) * w)\n\n# Add a vector to each row of a matrix\nx = np.array([[1, 2, 3], [4, 5, 6]])\n# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),\n# giving the following matrix:\n# [[2 4 6]\n# [5 7 9]]\nprint(x + v)\n\n# Add a vector to each column of a matrix\n# x has shape (2, 3) and w has shape (2,).\n# If we transpose x then it has shape (3, 2) and can be broadcast\n# against w to yield a result of shape (3, 2); transposing this result\n# yields the final result of shape (2, 3) which is the matrix x with\n# the vector w added to each column. Gives the following matrix:\n# [[ 5 6 7]\n# [ 9 10 11]]\nprint((x.T + w).T)\n# Another solution is to reshape w to be a column vector of shape (2, 1);\n# we can then broadcast it directly against x to produce the same\n# output.\nprint(x + np.reshape(w, (2, 1)))",
"[[ 4 5]\n [ 8 10]\n [12 15]]\n[[2 4 6]\n [5 7 9]]\n[[ 5 6 7]\n [ 9 10 11]]\n[[ 5 6 7]\n [ 9 10 11]]\n"
]
],
[
[
"## Views vs. Copies",
"_____no_output_____"
],
[
"Unlike a copy, in a **view** of an array, the data is shared between the view and the array. Sometimes, our results are copies of arrays, but other times they can be views. Understanding when each is generated is important to avoid any unforeseen issues.\n\nViews can be created from a slice of an array, changing the dtype of the same data area (using arr.view(dtype), not the result of arr.astype(dtype)), or even both.",
"_____no_output_____"
]
],
[
[
"x = np.arange(5)\nprint('Original:\\n', x) # Prints [0 1 2 3 4]\n\n# Modifying the view will modify the array\nview = x[1:3]\nview[1] = -1\nprint('Array After Modified View:\\n', x) # Prints [0 1 -1 3 4]",
"Original:\n [0 1 2 3 4]\nArray After Modified View:\n [ 0 1 -1 3 4]\n"
],
[
"x = np.arange(5)\nview = x[1:3]\nview[1] = -1\n\n# Modifying the array will modify the view\nprint('View Before Array Modification:\\n', view) # Prints [1 -1]\nx[2] = 10\nprint('Array After Modifications:\\n', x) # Prints [0 1 10 3 4]\nprint('View After Array Modification:\\n', view) # Prints [1 10]",
"View Before Array Modification:\n [ 1 -1]\nArray After Modifications:\n [ 0 1 10 3 4]\nView After Array Modification:\n [ 1 10]\n"
]
],
[
[
"However, if we use fancy indexing, the result will actually be a copy and not a view:",
"_____no_output_____"
]
],
[
[
"x = np.arange(5)\nprint('Original:\\n', x) # Prints [0 1 2 3 4]\n\n# Modifying the result of the selection due to fancy indexing\n# will not modify the original array.\ncopy = x[[1, 2]]\ncopy[1] = -1\nprint('Copy:\\n', copy) # Prints [1 -1]\nprint('Array After Modified Copy:\\n', x) # Prints [0 1 2 3 4]",
"Original:\n [0 1 2 3 4]\nCopy:\n [ 1 -1]\nArray After Modified Copy:\n [0 1 2 3 4]\n"
],
[
"# Another example involving fancy indexing\nx = np.arange(5)\nprint('Original:\\n', x) # Prints [0 1 2 3 4]\n\ncopy = x[x >= 2]\nprint('Copy:\\n', copy) # Prints [2 3 4]\nx[3] = 10\nprint('Modified Array:\\n', x) # Prints [0 1 2 10 4]\nprint('Copy After Modified Array:\\n', copy) # Prints [2 3 4]",
"Original:\n [0 1 2 3 4]\nCopy:\n [2 3 4]\nModified Array:\n [ 0 1 2 10 4]\nCopy After Modified Array:\n [2 3 4]\n"
]
],
[
[
"## Summary\n\n1. NumPy is an incredibly powerful library for computation providing both massive efficiency gains and convenience.\n2. Vectorize! Orders of magnitude faster.\n3. Keeping track of the shape of your arrays is often useful.\n4. Many useful math functions and operations built into NumPy.\n5. Select and manipulate arbitrary pieces of data with powerful indexing schemes.\n6. Broadcasting allows for computation across arrays of different shapes.\n7. Watch out for views vs. copies.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4a374130ae62f3f1487e4bfe3d2260d915d196ec
| 333,351 |
ipynb
|
Jupyter Notebook
|
notebooks/3.0-modeling-regression.ipynb
|
jads-nl/nhs-proms
|
ee90359256c7726ddf75e342c2154ee7db6dbbbe
|
[
"MIT"
] | null | null | null |
notebooks/3.0-modeling-regression.ipynb
|
jads-nl/nhs-proms
|
ee90359256c7726ddf75e342c2154ee7db6dbbbe
|
[
"MIT"
] | null | null | null |
notebooks/3.0-modeling-regression.ipynb
|
jads-nl/nhs-proms
|
ee90359256c7726ddf75e342c2154ee7db6dbbbe
|
[
"MIT"
] | 2 |
2020-11-01T11:14:20.000Z
|
2021-08-31T12:19:25.000Z
| 182.858475 | 192,632 | 0.874769 |
[
[
[
"<a href=\"https://colab.research.google.com/github/jads-nl/execute-nhs-proms/blob/master/notebooks/3.0-modeling-regression.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Background to osteoarthritis case study\n\nThis is day 3 from the [5-day JADS NHS PROMs data science case study](https://github.com/jads-nl/execute-nhs-proms/blob/master/README.md). To recap from the previous lectures, we have looked at defining the outcome of knee replacement.\n\n- Lecture 1:\n - Good outcome for knee replacement Y is measured using difference in Oxford Knee Score (OKS)\n - Research has shown that an improvement in OKS score of approx. 30% is relevant ([van der Wees 2017](https://github.com/jads-nl/execute-nhs-proms/blob/master/references/vanderwees2017patient-reported.pdf)). Hence an increase of +14 points is considered a 'good' outcome.\n - To account for the ceiling effect, a high final `t1_oks_score` is also considered as a good outcome (even if `delta_oks_score` is smaller than 14)\n \n- Lecture 2:\n - We have constructed a combined outcome parameter using cut-off points for pain and physical functioning.\n",
"_____no_output_____"
],
[
"# Modeling: regression and linear modeling\n\n",
"_____no_output_____"
],
[
"## Learning objectives\n### Modeling: regression and linear modeling\nFor this lecture we are going to build various predictors for `t1_eq_vas`, i.e. the reported quality of life after operation. `t1_eq_vas` is measured on a scale from 0 to 100.\n\nWe are going to use stratefied sampling to ensure we don't introduce sampling bias, using `StratefiedShuffleSplit`. This is different from the simplest function `train_test_split` which is a random sampling method. This is generally fine if your dataset is large enough (especially relative to the number of attributes). But if it is not, you run the risk of introducing significant sampling bias.\n\nBy the end of this lecture you should know:\n- Know how to perform different regressions models in Python using scikit-learn\n- Know how to interpret and assess regression models, including the bias-variance trade-of\n\n",
"_____no_output_____"
],
[
"### Python: Hands-on Machine Learning (2nd edition)\n\n- [End-to-end Machine Learning project (chapter 2)](https://github.com/ageron/handson-ml2/blob/master/02_end_to_end_machine_learning_project.ipynb)\n- [Training linear models (chapter 4)](https://github.com/ageron/handson-ml2/blob/master/04_training_linear_models.ipynb)\n\n\n### scikit-learn\n- [Tutorial cross validation score](https://scikit-learn.org/stable/auto_examples/exercises/plot_cv_diabetes.html?highlight=cross%20validation%20score)",
"_____no_output_____"
]
],
[
[
"import warnings\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom sklearn.feature_selection import chi2, VarianceThreshold\nimport sklearn.linear_model\n\n#supressing warnings for readability\nwarnings.filterwarnings(\"ignore\")\n\n# To plot pretty figures directly within Jupyter\n%matplotlib inline\n\n# choose your own style: https://matplotlib.org/3.1.0/gallery/style_sheets/style_sheets_reference.html\nplt.style.use('seaborn-whitegrid')\n\n# Go to town with https://matplotlib.org/tutorials/introductory/customizing.html\n# plt.rcParams.keys()\nmpl.rc('axes', labelsize=14, titlesize=14)\nmpl.rc('figure', titlesize=20)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\n\n# contants for figsize\nS = (8,8)\nM = (12,12)\nL = (14,14)\n\n# pandas options\npd.set_option(\"display.max.columns\", None)\npd.set_option(\"display.max.rows\", None)\npd.set_option(\"display.precision\", 2)\n\n# import data\ndf = pd.read_parquet('https://github.com/jads-nl/execute-nhs-proms/blob/master/data/interim/knee-provider.parquet?raw=true')",
"_____no_output_____"
],
[
"from sklearn.model_selection import StratifiedShuffleSplit\n\n\n# 999 is used as a sentinel value, replacing those with median\ndf[\"t1_eq_vas_impute\"] = df.t1_eq_vas.replace(\n to_replace=999, value=np.median(df.t1_eq_vas)\n)\n\n# add t1_eq_vas categories\ndf['t1_eq_vas_cat'] = pd.cut(df.t1_eq_vas_impute, 10)\n\n# Only using 1 split for stratefied sampling, more folds are used later on in cross-validation\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.3, random_state=42)\nfor train_index, test_index in split.split(df, df['t1_eq_vas_cat']):\n df_train = df.loc[train_index]\n df_test = df.loc[test_index]\n\n# remove columns so we continue working with original dataset\nfor set_ in (df_train, df_test):\n set_.drop([\"t1_eq_vas_impute\", \"t1_eq_vas_cat\"], axis=1, inplace=True)",
"_____no_output_____"
]
],
[
[
"# Data preparation in a scikit-learn Pipeline\nPreviously we have already discussed the various steps in data preparation using [pandas](https://pandas.pydata.org/). As explained in the [documentation of scikit-learn](https://scikit-learn.org/stable/modules/compose.html#column-transformer), this may be problematic for one of the following reasons:\n\n* Incorporating statistics from test data into the preprocessors makes cross-validation scores unreliable (known as data leakage), for example in the case of scalers or imputing missing values.\n\n* You may want to include the parameters of the preprocessors in a [parameter search](https://scikit-learn.org/stable/modules/grid_search.html#grid-search).\n\nTo this purpose, the [`ColumnTransformer` class](https://scikit-learn.org/stable/modules/generated/sklearn.compose.ColumnTransformer.html?highlight=columntransformer#sklearn.compose.ColumnTransformer) has been recently added to scikit-learn. The documentation gives an example how to use this for [pre-processing mixed types](https://scikit-learn.org/stable/auto_examples/compose/plot_column_transformer_mixed_types.html#sphx-glr-auto-examples-compose-plot-column-transformer-mixed-types-py). Historically, `sklearn` transformers are designed to work with numpy arrays, not with pandas dataframes. You can use [`sklearn-pandas`](https://github.com/scikit-learn-contrib/sklearn-pandas) to bridge this gap or use `ColumnTransformer` directly on pandas DataFrames. We will use the latter.\n\n",
"_____no_output_____"
],
[
"## Using ColumnsTransformers and Pipelines\n\nRecalling from the second lecture, we want to perform the following preprocessing per (group of) columns. In case feature requires more than one preprocessing step, the use of `Pipeline` is recommended.\n\n### Passing 1D or 2D arrays in your `Pipeline`\nIt is important to remember that `scikit-learn` can be quite fussy about the difference between passing 1D arrays/series and 2D arrays/dataframes.\n\nFor example, the following code will result in an error because `categories` needs to be a list of lists:\n```\nenc = OrdinalEncoder(categories=age_band_categories)\nenc.fit(df[age_band])\n```\n\nThe correct code is (brackets!):\n```\nenc = OrdinalEncoder(categories=[age_band_categories])\nenc.fit(df[age_band])\n```\n\n\n### Beware: difference between `OrdinalEncoder` and `OneHotEncoding`\nUsing `OrdinalEncoder` to generate an integer representation of a categorical variable can not be used directly with all scikit-learn estimators, as these expect continuous input, and would interpret the categories as being ordered, which is often not desired.\n\nAnother possibility to convert categorical features to features that can be used with scikit-learn estimators is to use a one-of-K, also known as one-hot or dummy encoding. This type of encoding can be obtained with the OneHotEncoder, which transforms each categorical feature with n_categories possible values into n_categories binary features, with one of them 1, and all others 0.",
"_____no_output_____"
]
],
[
[
"from sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.preprocessing import OrdinalEncoder, OneHotEncoder, LabelEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.impute import SimpleImputer\n\n\n# group columns\nage_band = [\"age_band\"]\ngender = [\"gender\"]\nage_band_categories = sorted([x for x in df.age_band.unique() if isinstance(x, str)])\ncomorb = [\n \"heart_disease\",\n \"high_bp\",\n \"stroke\",\n \"circulation\",\n \"lung_disease\",\n \"diabetes\",\n \"kidney_disease\",\n \"nervous_system\",\n \"liver_disease\",\n \"cancer\",\n \"depression\",\n \"arthritis\",\n]\nboolean = [\"t0_assisted\", \"t0_previous_surgery\", \"t0_disability\"]\neq5d = [\"t0_mobility\", \"t0_self_care\", \"t0_activity\", \"t0_discomfort\", \"t0_anxiety\"]\neq_vas = [\"t0_eq_vas\"]\ncategorical = [\"t0_symptom_period\", \"t0_previous_surgery\", \"t0_living_arrangements\"]\noks_questions = [\n col for col in df.columns if col.startswith(\"oks_t0\") and not col.endswith(\"_score\")\n]\noks_score = [\"oks_t0_score\"]\n\n# preprocessing pipelines for specific columns\nage_band_pipe = Pipeline(\n steps=[\n (\"impute\", SimpleImputer(missing_values=None, strategy=\"most_frequent\")),\n (\"ordinal\", OrdinalEncoder(categories=[age_band_categories])),\n ]\n)\n\ngender_pipe = Pipeline(\n steps=[\n (\"impute\", SimpleImputer(missing_values=np.nan, strategy=\"most_frequent\")),\n ('onehot', OneHotEncoder()),\n ]\n)\n\n\n# ColumnTransformer on all included columns.\n# Note columns that are not specified are dropped by default\ntransformers = {\n \"age\": (\"age\", age_band_pipe, age_band),\n \"gender\": (\"gender\", gender_pipe, gender),\n \"comorb\": (\n \"comorb\",\n SimpleImputer(missing_values=9, strategy=\"constant\", fill_value=0),\n comorb,\n ),\n \"categorical\": (\n \"categorical\",\n SimpleImputer(missing_values=9, strategy=\"most_frequent\"),\n boolean + eq5d + categorical,\n ),\n \"oks\": (\n \"oks\",\n SimpleImputer(missing_values=9, strategy=\"most_frequent\"),\n oks_questions,\n ),\n \"oks_score\": (\n \"oks_score\",\n SimpleImputer(missing_values=np.nan, strategy=\"most_frequent\"),\n oks_score,\n ),\n \"eq_vas\": (\"eqvas\", SimpleImputer(missing_values=999, strategy=\"median\"), eq_vas),\n}\nprep = ColumnTransformer(transformers=[v for _, v in transformers.items()])\n\nX_train = prep.fit_transform(df_train)\nX_test = prep.fit_transform(df_test)",
"_____no_output_____"
],
[
"# list of columns for convenience\n# https://stackoverflow.com/questions/54646709/sklearn-pipeline-get-feature-name-after-onehotencode-in-columntransformer\nX_columns = pd.Series(\n age_band\n + prep.named_transformers_[\"gender\"][\"onehot\"].get_feature_names().tolist()\n + comorb\n + boolean\n + eq5d\n + categorical\n + oks_questions\n + oks_score\n + eq_vas\n)",
"_____no_output_____"
]
],
[
[
"### Writing custom transformers (advanced, see Géron chapter 2)\nAlthough Scikit-Learn provides many useful transformers, you will need to write your own for tasks such as custom cleanup operations or combining specific attributes. You will want your transformer to work seamlessly with Scikit-Learn functionalities (such as pipelines), and since Scikit-Learn relies on duck typing (not inheritance), all you need to do is create a class and implement three methods: fit() (returning self), transform(), and fit_transform().\n\nWhen writing transformers for data preparation, you only need to define `transform()`. Basically, `ColumnTransformer` passes only the subset of columns from the original dataframe to the transformer. So when writing your own transformer you don't need to do any subsetting, but you can assume that the `transform()` method should be applied to the whole dataframe.\n\n",
"_____no_output_____"
]
],
[
[
"# just as an example, not used in Pipeline\nclass ReplaceSentinels(BaseEstimator, TransformerMixin):\n \"\"\"Replace sentinel values in dataframe.\n \n Attributes:\n sentinel: sentinel value, default 9\n replace_with: value to replace sentinel with, default np.nan\n \"\"\"\n def __init__(self, sentinel = 9, replace_with=np.nan):\n self.sentinel = sentinel\n self.replace_with = replace_with\n def fit(self, X, y=None):\n return self\n def transform(self, X, ):\n return X.replace(9, self.replace_with)\n",
"_____no_output_____"
]
],
[
[
"## Training and assessing linear models",
"_____no_output_____"
],
[
"### Simple regression\nRegression of `t1_eq_vas` ~ `t0_eq_vas`. We don't get our hopes up, since the scatterplot is all over the place:",
"_____no_output_____"
]
],
[
[
"df_train.plot(kind='scatter', x='t0_eq_vas', y='t1_eq_vas', xlim=(0,100), ylim=(0,100), alpha=0.1, figsize=M);",
"_____no_output_____"
],
[
"from sklearn.linear_model import LinearRegression\n\n\ndef fill_median(s):\n return s.fillna(value=s.median()).to_frame() \n\neq = ['t0_eq_vas', 't1_eq_vas']\neq_prep = ColumnTransformer(transformers=\n [('eq',\n SimpleImputer(missing_values=999,\n strategy='median'),\n eq),\n ])\neq_prep.fit(df_train)\n\n# note y = t1_eq\nt0_eq, t1_eq = eq_prep.transform(df_train)[:,0].reshape(-1,1), eq_prep.transform(df_train)[:,1]\n\n# prepare t1_eq_test for use in model assessment\nt1_eq_test = eq_prep.transform(df_test)[:,1]\n\n# simple linear regression\nlin_reg = LinearRegression()\nlin_reg.fit(t0_eq, t1_eq)\nlin_reg.intercept_, lin_reg.coef_, lin_reg.score(t0_eq, t1_eq)",
"_____no_output_____"
]
],
[
[
"So this very first, basic model yields an $R^2$ of 0.12 which is not very exciting. Let's do a more robust cross validation using the Mean Square Error (MSE) as our metric",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import cross_val_score\n\n\ndef display_scores(scores):\n print(f\"Scores: {scores}\")\n print(f\"Mean: {scores.mean():.4f}\")\n print(f\"Standard deviation: {scores.std():.4f}\")\n\nscores = cross_val_score(lin_reg, t0_eq, t1_eq, scoring='neg_mean_squared_error', cv=5)\nlin_rmse_scores = np.sqrt(-scores)\ndisplay_scores(lin_rmse_scores)",
"Scores: [16.66593682 16.82464722 16.87729003 16.88592997 16.93669798]\nMean: 16.8381\nStandard deviation: 0.0931\n"
]
],
[
[
"This confirms a simple linear model has little flexibility (and high bias): the scores for the five CV-folds are very similar. Now that we have seen the simplest setup for a univariate lineair regression, let's try to find out which features are the best predictors.",
"_____no_output_____"
],
[
"### SelectKBest\n\nFor regression tasks, you often want to get a first idea which features contain the most information i.e. are the best predictors. There are various techniques to answer this question, such as stepwise selection. Scikit-learn has various [univariate feature selection](https://scikit-learn.org/stable/modules/feature_selection.html) methods for this purpose. We will use [SelectKBest](https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectKBest.html#sklearn.feature_selection.SelectKBest).\n",
"_____no_output_____"
]
],
[
[
"from sklearn.feature_selection import SelectKBest, f_regression\n\nk10best = Pipeline(\n steps=[\n (\"prep\", ColumnTransformer(transformers=transformers.values())),\n (\"kbest\", SelectKBest(f_regression, k=10)),\n# (\"lin_reg\", LinearRegression())\n ]\n)\n\nX_10best = k10best.fit(df_train, t1_eq).transform(df_train)\nlin_10best = LinearRegression()\nscores_10best = cross_val_score(lin_10best, X_10best, t1_eq, scoring='neg_mean_squared_error', cv=5)\nlin_10best_rmse_scores = np.sqrt(-scores_10best)\ndisplay_scores(lin_10best_rmse_scores)",
"Scores: [15.99162775 16.14324365 16.17794808 16.22819153 16.19174312]\nMean: 16.1466\nStandard deviation: 0.0821\n"
]
],
[
[
"Using 10 KBest features, the model performs slightly better with RMSE of 16.1 +/- 0.08",
"_____no_output_____"
]
],
[
[
"# show features in descending order of importance\npd.concat(\n {\"score\": pd.Series(k10best[\"kbest\"].scores_), \"feature\": X_columns}, axis=1\n ).sort_values(\"score\", ascending=False)\n",
"_____no_output_____"
]
],
[
[
"### Regularized linear models: Lasso regression\n\nConstruct a Lasso regression with cross-validation, following the example from [scikit-learn documentation](https://scikit-learn.org/stable/auto_examples/linear_model/plot_lasso_model_selection.html#sphx-glr-auto-examples-linear-model-plot-lasso-model-selection-py). Recall that for regularized linear regression a cost function is added. In case of Lasso this is\n\n$$ J(\\Theta) = MSE (\\Theta) + \\alpha\\sum\\limits_{i=1}^n \\mid{\\Theta_{i}}\\mid$$\n\nThe larger $\\alpha$, the larger the penalty and hence more coefficients will be set to zero. By default `LassoCV` tries 100 different values for $\\alpha$ so let's plot MSE against $\\alpha$:",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LassoCV\n\n# This is to avoid division by zero while doing np.log10\nEPSILON = 1e-4\n\nlasso = LassoCV(cv=5, random_state=42, n_jobs=-1).fit(X_train, t1_eq)",
"_____no_output_____"
],
[
"plt.figure(figsize=S)\nplt.semilogx(lasso.alphas_ + EPSILON, np.sqrt(lasso.mse_path_), \":\")\nplt.plot(\n lasso.alphas_ + EPSILON,\n np.sqrt(lasso.mse_path_.mean(axis=-1)),\n \"k\",\n label=\"Average across the folds\",\n linewidth=2,\n)\nplt.axvline(\n lasso.alpha_ + EPSILON, linestyle=\"--\", color=\"k\", label=\"alpha: CV estimate\"\n)\nplt.legend()\nplt.xlabel(r\"$\\alpha$\")\nplt.ylabel(\"Root mean square error\")\nplt.title(\"Root mean square error on each fold: coordinate descent\")\nplt.axis(\"tight\");",
"_____no_output_____"
]
],
[
[
"The Lasso model performs best for lowest $\\alpha$",
"_____no_output_____"
]
],
[
[
"print(\"Best Lasso model:\\n\"\n f\" RMSE: {np.sqrt(mean_squared_error(lasso.predict(X_train), t1_eq)):.2f}\\n\"\n f\" intercept: {lasso.intercept_:.2f}\")",
"Best Lasso model:\n RMSE: 15.97\n intercept: 55.62\n"
]
],
[
[
"Inspect the relative feature importance by looking at the (absolute) coefficients:",
"_____no_output_____"
]
],
[
[
"pd.concat({'coef_abs': pd.Series(abs(lasso.coef_)), 'coef': pd.Series(lasso.coef_), 'feature': X_columns}, axis=1).sort_values('coef_abs', ascending=False)",
"_____no_output_____"
],
[
"# final test\nprint(f\"MSE from training with CV: {np.sqrt(mean_squared_error(lasso.predict(X_train), t1_eq)):.2f}\\n\"\n f\"MSE test: {np.sqrt(mean_squared_error(lasso.predict(X_test), t1_eq_test)):.2f}\")",
"MSE from training with CV: 15.97\nMSE test: 15.98\n"
]
],
[
[
"### KNN",
"_____no_output_____"
]
],
[
[
"from sklearn.neighbors import KNeighborsRegressor\nfrom collections import defaultdict\n\nn_neighbors = [1, 2, 3, 5, 10, 20, 30, 50, 100, 200, 300]\nknn = defaultdict(dict) # use defaultdict for nested dicts\nfor n in n_neighbors:\n knn[n][\"model\"] = KNeighborsRegressor(n_neighbors=n, n_jobs=-1).fit(X_train, t1_eq)\n knn[n][\"cross validation scores\"] = cross_val_score(\n knn[n][\"model\"], X_train, t1_eq, scoring=\"neg_mean_squared_error\", cv=5\n )",
"_____no_output_____"
],
[
"# plot 1/K vs. error rate just like in ISLR figure 3.19 (p. 108)\nknn_mse = [np.sqrt(np.mean(-knn[n]['cross validation scores'])) for n in n_neighbors]\nplt.figure(figsize=S)\nplt.semilogx([1/n for n in n_neighbors], knn_mse, 'o-', markeredgecolor='w', markeredgewidth='2');",
"_____no_output_____"
],
[
"# minimum RMSE is 16.2 at 1/K = 10-2, i.e. n=100\nknn_mse",
"_____no_output_____"
],
[
"# final test\nprint(f\"{np.sqrt(mean_squared_error(knn[100]['model'].predict(X_test), t1_eq_test)):.4f}\") ",
"16.2473\n"
]
],
[
[
"### RandomForest regression\n_consider this as a sneak preview for the next lecture, where we will use RandomForest for classification_",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestRegressor\n\nrf_reg = RandomForestRegressor(random_state=42)\nrf_reg.fit(X_train, t1_eq)\nrf_crosscv = cross_val_score(rf_reg, X_train, t1_eq, scoring=\"neg_mean_squared_error\", cv=5)",
"_____no_output_____"
],
[
"print(f\"{np.sqrt(np.mean(-rf_crosscv)):.4f}\")",
"16.1322\n"
],
[
"# final test\nprint(f\"{np.sqrt(mean_squared_error(rf_reg.predict(X_test), t1_eq_test)):.4f}\") ",
"16.1506\n"
]
],
[
[
"That looks promising: out-of-the-box RandomForest performs better than KNN (but slightly worse than Lasso). Like Lasso, we can inspect feature importance:",
"_____no_output_____"
]
],
[
[
"pd.concat(\n {\"feature\": X_columns, \"importance\": pd.Series(rf_reg.feature_importances_)}, axis=1\n).sort_values(\"importance\", ascending=False)",
"_____no_output_____"
]
],
[
[
"## Discussion & summary",
"_____no_output_____"
],
[
"### For discussion\n- Which model would you choose to predict `t1_eq_vas_` and why?\n- Reflect on the differences in feature importance between SelectKBest, Lasso coefficients and RandomForest\n - See, for example, [this discussion](https://datascience.stackexchange.com/questions/12148/feature-importance-via-random-forest-and-linear-regression-are-different)\n\n",
"_____no_output_____"
],
[
"### Summary\nWe have considered three basic machine learning algorithms:\n- (Simple) linear regression\n- LASSO\n- KNN\n\nA regression is often used as a baseline model, whereas LASSO and KNN are expected to have better performance. An obvious starting strategy, would be to: \n- Run a regression to get a baseline performance\n- Run LASSO and compare performance\n- With the selected variables in your LASSO, run KNN and compare performance\n\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
4a375e66f4acf6de088f90d5b37d75aa70cb2299
| 38,448 |
ipynb
|
Jupyter Notebook
|
caffe2/python/tutorials/create_your_own_dataset.ipynb
|
ZiboMeng/caffe2
|
e8eb1d0bd173a31eda9a5412df1a7200d78aaf83
|
[
"Apache-2.0"
] | 58 |
2019-01-03T02:20:41.000Z
|
2022-02-25T14:24:13.000Z
|
caffe2/python/tutorials/create_your_own_dataset.ipynb
|
ZiboMeng/caffe2
|
e8eb1d0bd173a31eda9a5412df1a7200d78aaf83
|
[
"Apache-2.0"
] | 27 |
2018-04-14T06:44:22.000Z
|
2018-08-01T18:02:39.000Z
|
caffe2/python/tutorials/create_your_own_dataset.ipynb
|
ZiboMeng/caffe2
|
e8eb1d0bd173a31eda9a5412df1a7200d78aaf83
|
[
"Apache-2.0"
] | 23 |
2018-04-13T10:47:31.000Z
|
2021-05-06T08:38:06.000Z
| 90.893617 | 12,716 | 0.806024 |
[
[
[
"# How do I create my own dataset?\n\nSo Caffe2 uses a binary DB format to store the data that we would like to train models on. A Caffe2 DB is a glorified name of a key-value storage where the keys are usually randomized so that the batches are approximately i.i.d. The values are the real stuff here: they contain the serialized strings of the specific data formats that you would like your training algorithm to ingest. So, the stored DB would look (semantically) like this:\n\nkey1 value1\nkey2 value2\nkey3 value3\n...\n\nTo a DB, it treats the keys and values as strings, but you probably want structured contents. One way to do this is to use a TensorProtos protocol buffer: it essentially wraps Tensors, aka multi-dimensional arrays, together with the tensor data type and shape information. Then, one can use the TensorProtosDBInput operator to load the data into an SGD training fashion.\n\nHere, we will show you one example of how to create your own dataset. To this end, we will use the UCI Iris dataset - which was a very popular classical dataset for classifying Iris flowers. It contains 4 real-valued features representing the dimensions of the flower, and classifies things into 3 types of Iris flowers. The dataset can be downloaded [here](https://archive.ics.uci.edu/ml/datasets/Iris).",
"_____no_output_____"
]
],
[
[
"# First let's import a few things needed.\n%matplotlib inline\nimport urllib2 # for downloading the dataset from the web.\nimport numpy as np\nfrom matplotlib import pyplot\nfrom StringIO import StringIO\nfrom caffe2.python import core, utils, workspace\nfrom caffe2.proto import caffe2_pb2",
"WARNING:root:This caffe2 python run does not have GPU support. Will run in CPU only mode.\nWARNING:root:Debug message: No module named caffe2_pybind11_state_gpu\n"
],
[
"f = urllib2.urlopen('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data')\nraw_data = f.read()\nprint('Raw data looks like this:')\nprint(raw_data[:100] + '...')",
"Raw data looks like this:\n5.1,3.5,1.4,0.2,Iris-setosa\n4.9,3.0,1.4,0.2,Iris-setosa\n4.7,3.2,1.3,0.2,Iris-setosa\n4.6,3.1,1.5,0.2,...\n"
],
[
"# load the features to a feature matrix.\nfeatures = np.loadtxt(StringIO(raw_data), dtype=np.float32, delimiter=',', usecols=(0, 1, 2, 3))\n# load the labels to a feature matrix\nlabel_converter = lambda s : {'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2}[s]\nlabels = np.loadtxt(StringIO(raw_data), dtype=np.int, delimiter=',', usecols=(4,), converters={4: label_converter})",
"_____no_output_____"
]
],
[
[
"Before we do training, one thing that is often beneficial is to separate the dataset into training and testing. In this case, let's randomly shuffle the data, use the first 100 data points to do training, and the remaining 50 to do testing. For more sophisticated approaches, you can use e.g. cross validation to separate your dataset into multiple training and testing splits. Read more about cross validation [here](http://scikit-learn.org/stable/modules/cross_validation.html).",
"_____no_output_____"
]
],
[
[
"random_index = np.random.permutation(150)\nfeatures = features[random_index]\nlabels = labels[random_index]\n\ntrain_features = features[:100]\ntrain_labels = labels[:100]\ntest_features = features[100:]\ntest_labels = labels[100:]",
"_____no_output_____"
],
[
"# Let's plot the first two features together with the label.\n# Remember, while we are plotting the testing feature distribution\n# here too, you might not be supposed to do so in real research,\n# because one should not peek into the testing data.\nlegend = ['rx', 'b+', 'go']\npyplot.title(\"Training data distribution, feature 0 and 1\")\nfor i in range(3):\n pyplot.plot(train_features[train_labels==i, 0], train_features[train_labels==i, 1], legend[i])\npyplot.figure()\npyplot.title(\"Testing data distribution, feature 0 and 1\")\nfor i in range(3):\n pyplot.plot(test_features[test_labels==i, 0], test_features[test_labels==i, 1], legend[i])",
"_____no_output_____"
]
],
[
[
"Now, as promised, let's put things into a Caffe2 DB. In this DB, what would happen is that we will use \"train_xxx\" as the key, and use a TensorProtos object to store two tensors for each data point: one as the feature and one as the label. We will use Caffe2 python's DB interface to do so.",
"_____no_output_____"
]
],
[
[
"# First, let's see how one can construct a TensorProtos protocol buffer from numpy arrays.\nfeature_and_label = caffe2_pb2.TensorProtos()\nfeature_and_label.protos.extend([\n utils.NumpyArrayToCaffe2Tensor(features[0]),\n utils.NumpyArrayToCaffe2Tensor(labels[0])])\nprint('This is what the tensor proto looks like for a feature and its label:')\nprint(str(feature_and_label))\nprint('This is the compact string that gets written into the db:')\nprint(feature_and_label.SerializeToString())",
"This is what the tensor proto looks like for a feature and its label:\nprotos {\n dims: 4\n data_type: FLOAT\n float_data: 5.40000009537\n float_data: 3.0\n float_data: 4.5\n float_data: 1.5\n}\nprotos {\n data_type: INT32\n int32_data: 1\n}\n\nThis is the compact string that gets written into the db:\n\n\u0016\b\u0004\u0010\u0001\u001a\u0010�̬@\u0000\u0000@@\u0000\u0000�@\u0000\u0000�?\n\u0005\u0010\u0002\"\u0001\u0001\n"
],
[
"# Now, actually write the db.\n\ndef write_db(db_type, db_name, features, labels):\n db = core.C.create_db(db_type, db_name, core.C.Mode.write)\n transaction = db.new_transaction()\n for i in range(features.shape[0]):\n feature_and_label = caffe2_pb2.TensorProtos()\n feature_and_label.protos.extend([\n utils.NumpyArrayToCaffe2Tensor(features[i]),\n utils.NumpyArrayToCaffe2Tensor(labels[i])])\n transaction.put(\n 'train_%03d'.format(i),\n feature_and_label.SerializeToString())\n # Close the transaction, and then close the db.\n del transaction\n del db\n\nwrite_db(\"minidb\", \"iris_train.minidb\", train_features, train_labels)\nwrite_db(\"minidb\", \"iris_test.minidb\", test_features, test_labels)",
"_____no_output_____"
]
],
[
[
"Now, let's create a very simple network that only consists of one single TensorProtosDBInput operator, to showcase how we load data from the DB that we created. For training, you might want to do something more complex: creating a network, train it, get the model, and run the prediction service. To this end you can look at the MNIST tutorial for details.",
"_____no_output_____"
]
],
[
[
"net_proto = core.Net(\"example_reader\")\ndbreader = net_proto.CreateDB([], \"dbreader\", db=\"iris_train.minidb\", db_type=\"minidb\")\nnet_proto.TensorProtosDBInput([dbreader], [\"X\", \"Y\"], batch_size=16)\n\nprint(\"The net looks like this:\")\nprint(str(net_proto.Proto()))",
"The net looks like this:\nname: \"example_reader\"\nop {\n output: \"dbreader\"\n name: \"\"\n type: \"CreateDB\"\n arg {\n name: \"db_type\"\n s: \"minidb\"\n }\n arg {\n name: \"db\"\n s: \"iris_train.minidb\"\n }\n}\nop {\n input: \"dbreader\"\n output: \"X\"\n output: \"Y\"\n name: \"\"\n type: \"TensorProtosDBInput\"\n arg {\n name: \"batch_size\"\n i: 16\n }\n}\n\n"
],
[
"workspace.CreateNet(net_proto)",
"_____no_output_____"
],
[
"# Let's run it to get batches of features.\nworkspace.RunNet(net_proto.Proto().name)\nprint(\"The first batch of feature is:\")\nprint(workspace.FetchBlob(\"X\"))\nprint(\"The first batch of label is:\")\nprint(workspace.FetchBlob(\"Y\"))\n\n# Let's run again.\nworkspace.RunNet(net_proto.Proto().name)\nprint(\"The second batch of feature is:\")\nprint(workspace.FetchBlob(\"X\"))\nprint(\"The second batch of label is:\")\nprint(workspace.FetchBlob(\"Y\"))",
"The first batch of feature is:\n[[ 5.19999981 4.0999999 1.5 0.1 ]\n [ 5.0999999 3.79999995 1.5 0.30000001]\n [ 6.9000001 3.0999999 4.9000001 1.5 ]\n [ 7.69999981 2.79999995 6.69999981 2. ]\n [ 6.5999999 2.9000001 4.5999999 1.29999995]\n [ 6.30000019 2.79999995 5.0999999 1.5 ]\n [ 7.30000019 2.9000001 6.30000019 1.79999995]\n [ 5.5999999 2.9000001 3.5999999 1.29999995]\n [ 6.5 3. 5.19999981 2. ]\n [ 5. 3.4000001 1.5 0.2 ]\n [ 6.9000001 3.0999999 5.4000001 2.0999999 ]\n [ 6. 3.4000001 4.5 1.60000002]\n [ 5.4000001 3.4000001 1.70000005 0.2 ]\n [ 6.30000019 2.70000005 4.9000001 1.79999995]\n [ 5.19999981 2.70000005 3.9000001 1.39999998]\n [ 6.19999981 2.9000001 4.30000019 1.29999995]]\nThe first batch of label is:\n[0 0 1 2 1 2 2 1 2 0 2 1 0 2 1 1]\nThe second batch of feature is:\n[[ 5.69999981 2.79999995 4.0999999 1.29999995]\n [ 5.0999999 2.5 3. 1.10000002]\n [ 4.4000001 2.9000001 1.39999998 0.2 ]\n [ 7. 3.20000005 4.69999981 1.39999998]\n [ 5.69999981 2.9000001 4.19999981 1.29999995]\n [ 5. 3.5999999 1.39999998 0.2 ]\n [ 5.19999981 3.5 1.5 0.2 ]\n [ 6.69999981 3. 5.19999981 2.29999995]\n [ 6.19999981 3.4000001 5.4000001 2.29999995]\n [ 6.4000001 2.70000005 5.30000019 1.89999998]\n [ 6.5 3.20000005 5.0999999 2. ]\n [ 6.0999999 3. 4.9000001 1.79999995]\n [ 5.4000001 3.4000001 1.5 0.40000001]\n [ 4.9000001 3.0999999 1.5 0.1 ]\n [ 5.5 3.5 1.29999995 0.2 ]\n [ 6.69999981 3. 5. 1.70000005]]\nThe second batch of label is:\n[1 1 0 1 1 0 0 2 2 2 2 2 0 0 0 1]\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4a376387edf9adc53c1a8dffd9f91e9555f10902
| 179,920 |
ipynb
|
Jupyter Notebook
|
Machine Learning/Decision Tree.ipynb
|
jgj9883/Unsupervised-learning
|
6578a61bb4a542917ea7035e38c928ae138edc6f
|
[
"MIT"
] | null | null | null |
Machine Learning/Decision Tree.ipynb
|
jgj9883/Unsupervised-learning
|
6578a61bb4a542917ea7035e38c928ae138edc6f
|
[
"MIT"
] | null | null | null |
Machine Learning/Decision Tree.ipynb
|
jgj9883/Unsupervised-learning
|
6578a61bb4a542917ea7035e38c928ae138edc6f
|
[
"MIT"
] | null | null | null | 121.814489 | 42,048 | 0.814612 |
[
[
[
"## Decision Tree",
"_____no_output_____"
]
],
[
[
"from sklearn.tree import DecisionTreeClassifier\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# DecisionTree Classifier 생성\ndt_clf = DecisionTreeClassifier(random_state=156)\n\n\n# 불꽃 데이터를 로딩하고, 학습과 테스트 데이터 세트로 분리\niris_data = load_iris()\nX_train, X_test, y_train, y_test = train_test_split(iris_data.data, iris_data.target, test_size=0.2, random_state=11)\n\n# DecisionTreeClassifer 학습.\ndt_clf.fit(X_train, y_train)",
"_____no_output_____"
],
[
"from sklearn.tree import export_graphviz\n\n# export_graphviz()의 호출 결과로 out_file로 지정된 tree.dot 파일을 생성함.\nexport_graphviz(dt_clf, out_file=\"tree.dot\", class_names=iris_data.target_names, \\\n feature_names = iris_data.feature_names, impurity=True, filled=True)",
"_____no_output_____"
],
[
"import graphviz\n# 위에서 생성된 tree.dot 파일을 Graphviz가 읽어서 주피터 노트북상에서 시각화\nwith open(\"tree.dot\") as f:\n dot_graph = f.read()\ngraphviz.Source(dot_graph)",
"_____no_output_____"
],
[
"import seaborn as sns\nimport numpy as np\n%matplotlib inline\n\n# feature importance 추출\nprint(\"Feature importances:\\n{0}\".format(np.round(dt_clf.feature_importances_,3)))\n\n# feature importance 매핑\nfor name, value in zip(iris_data.feature_names, dt_clf.feature_importances_):\n print('{0} : {1:.3f}'.format(name, value))\n \n# feature importance를 column 별로 시각화하기\nsns.barplot(x=dt_clf.feature_importances_, y=iris_data.feature_names)",
"Feature importances:\n[0.025 0. 0.555 0.42 ]\nsepal length (cm) : 0.025\nsepal width (cm) : 0.000\npetal length (cm) : 0.555\npetal width (cm) : 0.420\n"
],
[
"from sklearn.datasets import make_classification\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.title(\"3 Class values with 2 Features Sample data creation\")\n\n# 2차원 시각화를 위해서 피처는 2개, 클래스는 3가지 유형의 분류 샘플 데이터 생성.\nX_features, y_labels = make_classification(n_features=2, n_redundant=0, n_informative=2, \n n_classes=3, n_clusters_per_class=1, random_state=0)\n\n# 그래프 형태로 2개의 피처로 2차원 좌표 시각화, 각 클래스 값은 다른 색깔로 표시\nplt.scatter(X_features[:,0], X_features[:, 1], marker='o', c=y_labels, s=25, edgecolor='k')",
"_____no_output_____"
],
[
"from sklearn.tree import DecisionTreeClassifier\n\n# 특정한 트리 생성 제약 없는 결정 트리의 학습과 결정 경계 시각화.\ndt_clf = DecisionTreeClassifier().fit(X_features, y_labels)\nvisualize_boundary(dt_clf, X_features, y_labels)",
"_____no_output_____"
]
],
[
[
"### 결정 트리 실습 - 사용자 행동 인식 데이터 세트",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# feature.txt 파일에는 피처 이름 index와 피처명이 공백으로 분리되어 있음. 이를 DataFrame으로 롣,.\nfeature_name_df = pd.read_csv('./data/human_activity/features.txt', sep='\\s+',\n header=None, names=['column_index','column_name'])\n\n# 피처명 index를 제거하고, 피처명만 리스트 객체로 생성한 뒤 샘플로 10개만 추출\nfeature_name = feature_name_df.iloc[:,1].values.tolist()\nprint('전체 피처명에서 10개만 추출:', feature_name[:10])",
"전체 피처명에서 10개만 추출: ['tBodyAcc-mean()-X', 'tBodyAcc-mean()-Y', 'tBodyAcc-mean()-Z', 'tBodyAcc-std()-X', 'tBodyAcc-std()-Y', 'tBodyAcc-std()-Z', 'tBodyAcc-mad()-X', 'tBodyAcc-mad()-Y', 'tBodyAcc-mad()-Z', 'tBodyAcc-max()-X']\n"
],
[
"feature_dup_df = feature_name_df.groupby('column_name').count()\nprint(feature_dup_df[feature_dup_df['column_index'] > 1].count())\nfeature_dup_df[feature_dup_df['column_index'] > 1].head()",
"column_index 42\ndtype: int64\n"
],
[
"def get_new_feature_name_df(old_feature_name_df):\n feature_dup_df = pd.DataFrame(data=old_feature_name_df.groupby('column_name').cumcount(), columns=['dup_cnt'])\n feature_dup_df = feature_dup_df.reset_index()\n new_feature_name_df = pd.merge(old_feature_name_df.reset_index(), feature_dup_df, how='outer')\n new_feature_name_df['column_name'] = new_feature_name_df[['column_name','dup_cnt']].apply(lambda x : x[0]+'_'+str(x[1]) \n if x[1] > 0 else x[0], axis=1)\n new_feature_name_df = new_feature_name_df.drop(['index'], axis=1)\n return new_feature_name_df\n ",
"_____no_output_____"
],
[
"def get_human_dataset():\n \n # 각 데이터 파일은 공백으로 분리되어 있으므로 read_csv에서 공백 문자를 sep으로 할당.\n feature_name_df = pd.read_csv('./data/human_activity/features.txt', sep='\\s+',\n header=None, names=['column_index', 'column_name'])\n \n # 중복된 피처명을 수정하는 get_new_feature_name_df()를 이용, 신규 피처명 DataFrame 생성.\n new_feature_name_df = get_new_feature_name_df(feature_name_df)\n \n # DataFrame에 피처명을 칼럼으로 부여하기 위해 리스트 객체로 다시 반환\n feature_name = new_feature_name_df.iloc[:, 1].values.tolist()\n \n # 학습 피처 데이터세트와 테스트 피처 데이터를 DataFrame으로 로딩, 칼럼명은 feature_name 적용\n X_train = pd.read_csv('./data/human_activity/train/X_train.txt', sep='\\s+', names=feature_name)\n X_test = pd.read_csv('./data/human_activity/test/X_test.txt', sep='\\s+', names=feature_name)\n \n # 학습 레이블과 테스트 레이블 데이터를 DataFrame으로 로딩하고 칼럼명은 action으로 부여\n y_train = pd.read_csv('./data/human_activity/train/y_train.txt', sep='\\s+', header=None, names=['action'])\n y_test = pd.read_csv('./data/human_activity/test/y_test.txt', sep='\\s+', header=None, names=['action'])\n \n # 로드된 학습/테스트용 DataFrame을 모두 반환\n \n return X_train, X_test, y_train, y_test\n\nX_train, X_test, y_train, y_test = get_human_dataset()",
"_____no_output_____"
],
[
"print('## 학습 피처 데이터셋 info()')\nprint(X_train.info())",
"## 학습 피처 데이터셋 info()\n<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 7352 entries, 0 to 7351\nColumns: 561 entries, tBodyAcc-mean()-X to angle(Z,gravityMean)\ndtypes: float64(561)\nmemory usage: 31.5 MB\nNone\n"
],
[
"print(y_train['action'].value_counts())",
"6 1407\n5 1374\n4 1286\n1 1226\n2 1073\n3 986\nName: action, dtype: int64\n"
],
[
"from sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\n\n# 예제 반복 시마다 동일한 예측 결과 도출을 위해 random_state 설정\ndt_clf = DecisionTreeClassifier(random_state = 156)\ndt_clf.fit(X_train, y_train)\npred = dt_clf.predict(X_test)\naccuracy = accuracy_score(y_test, pred)\nprint('결정 트리 예측 정확도: {0:.4f}'.format(accuracy))\n\n# DecisionTreeClassifier의 하이퍼 파라미터 추출\nprint('DecisionTreeClassifier 기본 하이퍼 파라미터:\\n', dt_clf.get_params())",
"결정 트리 예측 정확도: 0.8548\nDecisionTreeClassifier 기본 하이퍼 파라미터:\n {'ccp_alpha': 0.0, 'class_weight': None, 'criterion': 'gini', 'max_depth': None, 'max_features': None, 'max_leaf_nodes': None, 'min_impurity_decrease': 0.0, 'min_impurity_split': None, 'min_samples_leaf': 1, 'min_samples_split': 2, 'min_weight_fraction_leaf': 0.0, 'random_state': 156, 'splitter': 'best'}\n"
],
[
"from sklearn.model_selection import GridSearchCV\n\nparams = {\n 'max_depth' : [6, 8, 10, 12, 16, 20, 24]\n}\n\ngrid_cv = GridSearchCV(dt_clf, param_grid = params, scoring='accuracy', cv=5, verbose=1)\ngrid_cv.fit(X_train, y_train)\nprint('GridSearchCV 최고 평균 정확도 수치 : {0:.4f}'.format(grid_cv.best_score_))\nprint('GridSearchCV 최적 하이퍼 파라미터:', grid_cv.best_params_)\n",
"Fitting 5 folds for each of 7 candidates, totalling 35 fits\nGridSearchCV 최고 평균 정확도 수치 : 0.8513\nGridSearchCV 최적 하이퍼 파라미터: {'max_depth': 16}\n"
],
[
"# GridSearchCV 객체의 cv_results_ 속성을 DataFrame으로 생성.\ncv_results_df = pd.DataFrame(grid_cv.cv_results_)\n\n\n# max_depth 파라미터 값과 그때의 테스트 세트, 학습 데이터 세트의 정확도 수치 추출\ncv_results_df[['param_max_depth', 'mean_test_score']]",
"_____no_output_____"
],
[
"max_depths=[6, 8, 10, 12, 16, 20, 24]\n# max_depth 값을 변화시키면서 그때마다 학습과 테스트 세트에서의 예측 성능 측정\nfor depth in max_depths:\n dt_clf = DecisionTreeClassifier(max_depth=depth, random_state=156)\n dt_clf.fit(X_train, y_train)\n pred = dt_clf.predict(X_test)\n accuracy = accuracy_score(y_test, pred)\n print('max_depth={0} 정확도:{1:.4f}'.format(depth,accuracy))",
"max_depth=6 정확도:0.8558\nmax_depth=8 정확도:0.8707\nmax_depth=10 정확도:0.8673\nmax_depth=12 정확도:0.8646\nmax_depth=16 정확도:0.8575\nmax_depth=20 정확도:0.8548\nmax_depth=24 정확도:0.8548\n"
],
[
"params = {\n 'max_depth' : [8, 12, 16, 20],\n 'min_samples_split' : [16, 24],\n}\n\ngrid_cv = GridSearchCV(dt_clf, param_grid=params, scoring='accuracy', cv=5, verbose=1)\ngrid_cv.fit(X_train, y_train)\nprint('GridSearchCV 최고 평균 정확도 수치:{0:.4f}'.format(grid_cv.best_score_))\nprint('GridSearchCV 최적 하이퍼 파라미터:', grid_cv.best_parmas_)",
"Fitting 5 folds for each of 8 candidates, totalling 40 fits\nGridSearchCV 최고 평균 정확도 수치:0.8549\n"
],
[
"best_df_clf = grid_cv.best_estimator_\npred1 = best_df_clf.predict(X_test)\naccuracy = accuracy_score(y_test, pred1)\nprint('결정 트리 예측 정확도 : {0:.4f}'.format(accuracy))",
"결정 트리 예측 정확도 : 0.8717\n"
],
[
"import seaborn as sns\n\nftr_importances_values = best_df_clf.feature_importances_\n# Top 중요도로 정렬을 쉽게, 사본(Seaborn)의 막대그래프로 쉽게 표현하기 위해 Series 변환\nftr_importances = pd.Series(ftr_importances_values, index=X_train.columns)\n# 중요도값 순으로 Series를 정렬\nftr_top20 = ftr_importances.sort_values(ascending=False)[:20]\nplt.figure(figsize=(8, 6))\nplt.title('Feature importances Top 20')\nsns.barplot(x=ftr_top20, y=ftr_top20.index)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Ensemble Learning",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\ncancer = load_breast_cancer()\n\ndata_df = pd.DataFrame(cancer.data, columns=cancer.feature_names)\ndata_df.head(3)",
"_____no_output_____"
],
[
"# 개별 모델은 로지스틱 회귀와 KNN임.\nlr_clf = LogisticRegression()\nknn_clf = KNeighborsClassifier(n_neighbors=8)\n\n# 개별 모델을 소프트 보팅 기반의 앙상블 모델로 구현한 분류기\nvo_clf = VotingClassifier(estimators=[('LR', lr_clf),('KNN', knn_clf)], voting='soft')\n\nX_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, test_size=0.2, random_state= 156)\n\n# VotingClassifier 학습/예측/평가.\nvo_clf.fit(X_train, y_train)\npred = vo_clf.predict(X_test)\nprint('Voting 분류기 정확도:{0:.4f}'.format(accuracy_score(y_test, pred)))\n\n# 개별 모델의 학습/예측/평가\nclassifiers= [lr_clf, knn_clf]\nfor classifier in classifiers:\n classifier.fit(X_train, y_train)\n pred = classifier.predict(X_test)\n class_name = classifier.__class__.__name__\n print('{0} 정확도 : {1:.4f}'.format(class_name, accuracy_score(y_test, pred)))",
"Voting 분류기 정확도:0.9474\nLogisticRegression 정확도 : 0.9386\nKNeighborsClassifier 정확도 : 0.9386\n"
]
],
[
[
"## Random Forest",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\nimport pandas as pd\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# 결정 트리에서 사용한 get_human_dataset()를 이용해 학습/테스트용 DataFrame 반환\nX_train, X_test, y_train, y_test = get_human_dataset()\n\n# 랜덤 포레스트 학습 및 별도의 테스트 세트로 예측 성능 평가\nrf_clf = RandomForestClassifier(random_state=0)\nrf_clf.fit(X_train, y_train)\npred = rf_clf.predict(X_test)\naccuracy = accuracy_score(y_test, pred)\nprint('랜덤 포레스트 정확도: {0:.4f}'.format(accuracy))",
"랜덤 포레스트 정확도: 0.9253\n"
],
[
"from sklearn.model_selection import GridSearchCV\n\nparams = {\n 'n_estimators':[100],\n 'max_depth' : [6, 8, 10, 12],\n 'min_samples_leaf' : [8, 12, 18],\n 'min_samples_split' : [8, 16, 20]\n}\n\n# RandomForestClassifier 객체 생성 후 GridSearchCV 수행\nrf_clf = RandomForestClassifier(random_state=0, n_jobs=-1)\ngrid_cv = GridSearchCV(rf_clf, param_grid = params, cv=2, n_jobs=-1)\ngrid_cv.fit(X_train, y_train)\n\nprint('최적 하이퍼 파라미터:\\n', grid_cv.best_params_)",
"최적 하이퍼 파라미터:\n {'max_depth': 10, 'min_samples_leaf': 8, 'min_samples_split': 8, 'n_estimators': 100}\n"
],
[
"rf_clf1 = RandomForestClassifier(n_estimators=300, max_depth=10, min_samples_leaf=8, \\\n min_samples_split=8, random_state=0)\n\nrf_clf1.fit(X_train, y_train)\npred = rf_clf1.predict(X_test)\nprint('예측 정확도 : {0:.4f}'.format(accuracy_score(y_test,pred)))",
"예측 정확도 : 0.9165\n"
]
],
[
[
"### 피처 중요도",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\nftr_importances_values = rf_clf1.feature_importances_\nftr_importances = pd.Series(ftr_importances_values, index=X_train.columns)\nftr_top20 = ftr_importances.sort_values(ascending=False)[:20]\n\nplt.figure(figsize=(8,6))\nplt.title('Feature importances Top 20')\nsns.barplot(x=ftr_top20, y = ftr_top20.index)",
"_____no_output_____"
]
],
[
[
"## Gradient Boosting Machine",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import GradientBoostingClassifier\nimport time\nimport warnings\nwarnings.filterwarnings('ignore')\n\nX_train, X_test, y_train, y_test = get_human_dataset()\n\n# GBM 수행 시간 측정을 위함. 시작 시간 설정.\nstart_time = time.time()\n\ngb_clf = GradientBoostingClassifier(random_state=0)\ngb_clf.fit(X_train, y_train)\ngb_pred = gb_clf.predict(X_test)\ngb_accuracy = accuracy_score(y_test, gb_pred)\n\nprint('GBM 정확도 : {0:.4f}'.format(gb_accuracy))\nprint('GBM 수행 시간 : {0:.1f} 초'.format(time.time() - start_time))\nprint('GBM 수행 시간 : {0:.1f} 분'.format(time.time() - start_time)/60)",
"GBM 정확도 : 0.9389\nGBM 수행 시간 : 459.9 초\n"
]
],
[
[
"#### GridSearchCV 사용한 하이퍼 파라미터 최적화",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import GridSearchCV\n\nparmas = {\n 'n_estimators' : [100, 500],\n 'learing+rate' : [0.05, 0.01]\n}\n\ngrid_cv = GridSearchCV(gb_clf, param_grid=params, cv=2, verbose=1)\ngrid_cv.fit(X_train, y_train)\nprint('최적 하이퍼 파라미터:\\n', grid_cv.best_params_)\nprint('최고 예측 정확도:{0:.4f}'.format(grid_cv.best_score_))",
"Fitting 2 folds for each of 36 candidates, totalling 72 fits\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a37648994d9c1fb7ea4c77431f65933485a623a
| 215,465 |
ipynb
|
Jupyter Notebook
|
src/jupyter/significance-tests.ipynb
|
webis-de/ecir22-anchor-text
|
254ab53fe4a5fca809af0f846f82b3fb6abd2a82
|
[
"MIT"
] | 3 |
2021-11-16T19:52:54.000Z
|
2022-01-20T22:55:01.000Z
|
src/jupyter/significance-tests.ipynb
|
webis-de/ecir22-anchor-text
|
254ab53fe4a5fca809af0f846f82b3fb6abd2a82
|
[
"MIT"
] | null | null | null |
src/jupyter/significance-tests.ipynb
|
webis-de/ecir22-anchor-text
|
254ab53fe4a5fca809af0f846f82b3fb6abd2a82
|
[
"MIT"
] | null | null | null | 37.589846 | 230 | 0.342571 |
[
[
[
"# Significance Tests with PyTerrier",
"_____no_output_____"
]
],
[
[
"import pyterrier as pt\nimport pandas as pd\n\nRUN_DIR='/mnt/ceph/storage/data-in-progress/data-teaching/theses/wstud-thesis-probst/retrievalExperiments/runs-ecir22/'\nRUN_DIR_MARCO_V2='/mnt/ceph/storage/data-in-progress/data-teaching/theses/wstud-thesis-probst/retrievalExperiments/runs-marco-v2-ecir22/'\nQREL_DIR = '/mnt/ceph/storage/data-tmp/2021/kibi9872/thesis-probst/Data/navigational-topics-and-qrels-ms-marco-'\n\nif not pt.started():\n pt.init()\n\ndef pt_qrels(ret):\n from trectools import TrecQrel\n ret = TrecQrel(QREL_DIR + ret).qrels_data\n ret = ret.copy()\n del ret['q0']\n ret = ret.rename(columns={'query': 'qid','docid': 'docno', 'rel': 'label'})\n ret['qid'] = ret['qid'].astype(str)\n ret['label'] = ret['label'].astype(int)\n return ret\n\ndef pt_topics(ret):\n from trectools import TrecQrel\n qids = TrecQrel(QREL_DIR + ret).qrels_data['query'].unique()\n \n ret = []\n for qid in qids:\n ret += [{'qid': str(qid), 'query': 'Unused, only for significance tests for qid: ' + str(qid)}]\n \n return pd.DataFrame(ret)\n\ndef trec_run(run_name):\n from pyterrier.transformer import get_transformer\n return get_transformer(pt.io.read_results(run_name))\n\n\nQRELS = {\n 'v1-popular': pt_qrels('v1/qrels.msmarco-entrypage-popular.txt'),\n 'v1-random': pt_qrels('v1/qrels.msmarco-entrypage-random.txt'),\n 'v2-popular': pt_qrels('v2/qrels.msmarco-v2-entrypage-popular.txt'),\n 'v2-random': pt_qrels('v2/qrels.msmarco-v2-entrypage-random.txt'),\n}\n\nTOPICS = {\n 'v1-popular': pt_topics('v1/qrels.msmarco-entrypage-popular.txt'),\n 'v1-random': pt_topics('v1/qrels.msmarco-entrypage-random.txt'),\n 'v2-popular': pt_topics('v2/qrels.msmarco-v2-entrypage-popular.txt'),\n 'v2-random': pt_topics('v2/qrels.msmarco-v2-entrypage-random.txt'),\n}",
"_____no_output_____"
],
[
"APPROACH_TO_MARCO_V1_RUN_FILE={\n 'BM25@2016-07': 'run.cc-16-07-anchortext.bm25-default.txt',\n 'BM25@2017-04': 'run.cc-17-04-anchortext.bm25-default.txt',\n 'BM25@2018-13': 'run.cc-18-13-anchortext.bm25-default.txt',\n 'BM25@2019-47': 'run.cc-19-47-anchortext.bm25-default.txt',\n 'BM25@2020-05': 'run.cc-20-05-anchortext.bm25-default.txt',\n 'BM25@2021-04': 'run.cc-21-04-anchortext.bm25-default.txt',\n 'BM25@16--21': 'run.cc-combined-anchortext.bm25-default.txt',\n 'BM25@Content': 'run.ms-marco-content.bm25-default.txt',\n 'BM25@Title': 'run.msmarco-document-v1-title-only.pos+docvectors+raw.bm25-default.txt',\n 'BM25@Orcas': 'run.orcas.bm25-default.txt',\n 'DeepCT@Anchor': 'run.ms-marco-deepct-v1-anserini-docs-cc-2019-47-sampled-test-overlap-removed-389979.bm25-default.txt',\n 'DeepCT@Orcas': 'run.ms-marco-deepct-v1-anserini-docs-orcas-sampled-test-overlap-removed-390009.bm25-default.txt',\n 'DeepCT@Train':'run.ms-marco-deepct-v1-anserini-docs-ms-marco-training-set-test-overlap-removed-389973.bm25-default.txt',\n 'MonoT5': 'run.ms-marco-content.bm25-mono-t5-maxp.txt',\n 'MonoBERT': 'run.ms-marco-content.bm25-mono-bert-maxp.txt',\n 'LambdaMART@CTA':'run.ms-marco.lambda-mart-cta-trees-1000.txt',\n 'LambdaMART@CTOA':'run.ms-marco.lambda-mart-ctoa-trees-1000.txt',\n 'LambdaMART@CTO':'run.ms-marco.lambda-mart-cto-trees-1000.txt',\n 'LambdaMART@CT':'run.ms-marco.lambda-mart-ct-trees-1000.txt',\n}\n\nAPPROACH_TO_MARCO_V2_RUN_FILE={\n 'BM25@Content': 'run.msmarco-doc-v2.bm25-default.txt',\n 'BM25@Orcas': 'run.orcas-ms-marco-v2.bm25-default.txt',\n 'BM25@2016-07': 'run.cc-16-07-anchortext.bm25-default.txt',\n 'BM25@2017-04': 'run.cc-17-04-anchortext.bm25-default.txt',\n 'BM25@2018-13': 'run.cc-18-13-anchortext.bm25-default.txt',\n 'BM25@2019-47': 'run.cc-19-47-anchortext-v2.bm25-default.txt',\n 'BM25@2020-05': 'run.cc-20-05-anchortext.bm25-default.txt',\n 'BM25@2021-04': 'run.cc-21-04-anchortext.bm25-default.txt',\n 'BM25@16--21': 'run.cc-union-16-to-21-anchortext-1000.bm25-default.txt',\n 'DeepCT@Anchor': 'run.ms-marco-deepct-v2-anserini-docs-cc-2019-47-sampled-test-overlap-removed-389979.bm25-default.txt',\n 'DeepCT@Orcas': 'run.ms-marco-deepct-v2-anserini-docs-orcas-sampled-test-overlap-removed-390009.bm25-default.txt',\n 'DeepCT@Train':'run.ms-marco-deepct-v2-anserini-docs-ms-marco-training-set-test-overlap-removed-389973.bm25-default.txt',\n 'MonoT5': 'run.ms-marco-content.bm25-mono-t5-maxp.txt',\n 'MonoBERT': 'run.ms-marco-content.bm25-mono-bert-maxp.txt',\n 'LambdaMART@CTA':'run.ms-marco.lambda-mart-cta-trees-1000.txt',\n 'LambdaMART@CTOA':'run.ms-marco.lambda-mart-ctoa-trees-1000.txt',\n 'LambdaMART@CTO':'run.ms-marco.lambda-mart-cto-trees-1000.txt',\n 'LambdaMART@CT':'run.ms-marco.lambda-mart-ct-trees-1000.txt',\n}",
"_____no_output_____"
]
],
[
[
"### Comparison of MRR for Anchor Text approaches to DeepCT",
"_____no_output_____"
]
],
[
[
"runs = ['DeepCT@Anchor', 'BM25@2016-07', 'BM25@2017-04', 'BM25@2018-13', 'BM25@2019-47', 'BM25@2020-05', 'BM25@2021-04', 'BM25@16--21']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-random/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-random'],\n QRELS['v1-random'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
]
],
[
[
"Result: From xy above we see....",
"_____no_output_____"
],
[
"### Comparison of MRR for BM25 on Content with DeepCT trained on anchor text, DeepCT, MonoT5, MonoBERT, and LambdaMART",
"_____no_output_____"
]
],
[
[
"runs = ['BM25@Content', 'DeepCT@Orcas', 'DeepCT@Anchor', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'LambdaMART@CTA', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-random/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-random'],\n QRELS['v1-random'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
]
],
[
[
"Result:\n \nDeepCT trained on anchor text, DeepCT trained on the ORCAS query log, MonoT5, MonoBERT, and three of the LambdaMART models improve statistically significant upon the MRR of 0.21 achieved by the BM25 retrieval on the content.",
"_____no_output_____"
],
[
"### Comparison of BM25 on Orcas with other Content-Only Models",
"_____no_output_____"
]
],
[
[
"runs = ['BM25@Orcas', 'BM25@Content', 'DeepCT@Orcas', 'DeepCT@Anchor', 'DeepCT@Train', 'MonoT5', 'MonoBERT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-random/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-random'],\n QRELS['v1-random'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
]
],
[
[
"Result:\n \nBM25 on ORCAS improves statistically significantly upon all content-only models.",
"_____no_output_____"
],
[
"### Comparison of all Anchor-Text Models with all other approaches",
"_____no_output_____"
]
],
[
[
"runs = ['BM25@2016-07', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@2017-04', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@2018-13', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@2019-47', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@2020-05', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@2021-04', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@16--21', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
]
],
[
[
"Result:\n\nFor queries pointing to popular entry pages, all BM25 models retrieving on anchor text outperform all other retrieval models statistically significant",
"_____no_output_____"
],
[
"### Compare BM25 on ORCAS for popular topics with all other non-anchor-approaches",
"_____no_output_____"
]
],
[
[
"runs = ['BM25@Orcas', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recip_rank'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
]
],
[
[
"# Evaluations Recall@3 and Recall@10",
"_____no_output_____"
],
[
"### Comparison of Recall for Anchor Text approaches to DeepCT",
"_____no_output_____"
]
],
[
[
"runs = ['DeepCT@Anchor', 'BM25@2016-07', 'BM25@2017-04', 'BM25@2018-13', 'BM25@2019-47', 'BM25@2020-05', 'BM25@2021-04', 'BM25@16--21']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-random/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-random'],\n QRELS['v1-random'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
]
],
[
[
"### Comparison of Recall for BM25 on Content with DeepCT trained on anchor text, DeepCT, MonoT5, MonoBERT, and LambdaMART",
"_____no_output_____"
]
],
[
[
"runs = ['BM25@Content', 'DeepCT@Orcas', 'DeepCT@Anchor', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'LambdaMART@CTA', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-random/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-random'],\n QRELS['v1-random'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
]
],
[
[
"### Comparison of BM25 on Orcas with other Content-Only Models",
"_____no_output_____"
]
],
[
[
"runs = ['BM25@Orcas', 'BM25@Content', 'DeepCT@Orcas', 'DeepCT@Anchor', 'DeepCT@Train', 'MonoT5', 'MonoBERT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-random/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-random'],\n QRELS['v1-random'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
]
],
[
[
"Result:\n \nBM25 on ORCAS does not statisticall improve upon DeepCT@Anchor (for Recall@3) and DeepCT@Anchor, DeepCT@Orcas, and MonoT5 (Recall@10)",
"_____no_output_____"
],
[
"### Comparison of all Anchor-Text Models with all other approaches",
"_____no_output_____"
]
],
[
[
"runs = ['BM25@2016-07', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@2017-04', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@2018-13', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@2019-47', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@2020-05', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@2021-04', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
],
[
"runs = ['BM25@16--21', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'BM25@Orcas', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\n)",
"_____no_output_____"
]
],
[
[
"Result: We see exactly the same relevance results as for MRR.",
"_____no_output_____"
],
[
"### Compare BM25 on ORCAS for popular topics with all other non-anchor-approaches",
"_____no_output_____"
]
],
[
[
"runs = ['BM25@Orcas', 'BM25@Content', 'DeepCT@Anchor', 'DeepCT@Orcas', 'DeepCT@Train', 'MonoT5', 'MonoBERT', 'LambdaMART@CTOA', 'LambdaMART@CTO', 'LambdaMART@CTA', 'LambdaMART@CT']\nruns = [(i, trec_run(RUN_DIR + '/entrypage-popular/' + APPROACH_TO_MARCO_V1_RUN_FILE[i])) for i in runs]\n\npt.Experiment(\n [i for _, i in runs],\n TOPICS['v1-popular'],\n QRELS['v1-popular'],\n ['recall.3', 'recall.10'],\n [i for i, _ in runs],\n baseline = 0,\n test='t',\n correction='b'\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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
4a377cf4f67531094b3cff7c9ab5aad51dd84103
| 14,118 |
ipynb
|
Jupyter Notebook
|
custom_tensorflow_keras_nlp/Headline Classifier Local.ipynb
|
acere/sagemaker-101-workshop
|
ad05ea05167ff494e542954083577ee37bd35203
|
[
"MIT-0"
] | null | null | null |
custom_tensorflow_keras_nlp/Headline Classifier Local.ipynb
|
acere/sagemaker-101-workshop
|
ad05ea05167ff494e542954083577ee37bd35203
|
[
"MIT-0"
] | null | null | null |
custom_tensorflow_keras_nlp/Headline Classifier Local.ipynb
|
acere/sagemaker-101-workshop
|
ad05ea05167ff494e542954083577ee37bd35203
|
[
"MIT-0"
] | null | null | null | 29.78481 | 414 | 0.593144 |
[
[
[
"# End-to-End NLP: News Headline Classifier (Local Version)\n\n_**Train a Keras-based model to classify news headlines between four domains**_\n\nThis notebook works well with the `Python 3 (TensorFlow 1.15 Python 3.7 CPU Optimized)` kernel on SageMaker Studio, or `conda_tensorflow_p36` on classic SageMaker Notebook Instances.\n\n---\n\nIn this version, the model is trained and evaluated here on the notebook instance itself. We'll show in the follow-on notebook how to take advantage of Amazon SageMaker to separate these infrastructure needs.\n\nNote that you can safely ignore the WARNING about the pip version.\n",
"_____no_output_____"
]
],
[
[
"# First install some libraries which might not be available across all kernels (e.g. in Studio):\n!pip install ipywidgets",
"_____no_output_____"
]
],
[
[
"### Set Up Execution Role and Session\n\nLet's start by specifying:\n\n- The S3 bucket and prefix that you want to use for training and model data. This should be within the same region as the Notebook Instance, training, and hosting. If you don't specify a bucket, SageMaker SDK will create a default bucket following a pre-defined naming convention in the same region. \n- The IAM role ARN used to give SageMaker access to your data. It can be fetched using the **get_execution_role** method from sagemaker python SDK.\n",
"_____no_output_____"
]
],
[
[
"%%time\n%load_ext autoreload\n%autoreload 2\n\nimport sagemaker\nfrom sagemaker import get_execution_role\n\nrole = get_execution_role()\nprint(role)\nsess = sagemaker.Session()\n",
"_____no_output_____"
]
],
[
[
"### Download News Aggregator Dataset\n\nWe will download **FastAi AG News** dataset from the https://registry.opendata.aws/fast-ai-nlp/ public repository. This dataset contains a table of news headlines and their corresponding classes.\n",
"_____no_output_____"
]
],
[
[
"%%time\nimport util.preprocessing\n\nutil.preprocessing.download_dataset()\n",
"_____no_output_____"
]
],
[
[
"### Let's visualize the dataset\n\nWe will load the ag_news_csv/train.csv file to a Pandas dataframe for our data processing work.",
"_____no_output_____"
]
],
[
[
"import os\nimport re\nimport numpy as np\nimport pandas as pd\n",
"_____no_output_____"
],
[
"column_names = [\"CATEGORY\", \"TITLE\", \"CONTENT\"]\n# we use the train.csv only\ndf = pd.read_csv(\"data/ag_news_csv/train.csv\", names=column_names, header=None, delimiter=\",\")\n# shuffle the DataFrame rows\ndf = df.sample(frac = 1)\n# make the category classes more readable\nmapping = {1: 'World', 2: 'Sports', 3: 'Business', 4: 'Sci/Tech'}\ndf = df.replace({'CATEGORY': mapping})\ndf.head()\n",
"_____no_output_____"
]
],
[
[
"For this exercise we'll **only use**:\n\n- The **title** (Headline) of the news story, as our input\n- The **category**, as our target variable\n",
"_____no_output_____"
]
],
[
[
"df[\"CATEGORY\"].value_counts()\n",
"_____no_output_____"
]
],
[
[
"The dataset has **four article categories** with equal weighting:\n\n- Business\n- Sci/Tech\n- Sports\n- World\n",
"_____no_output_____"
],
[
"## Natural Language Pre-Processing\n\nWe'll do some basic processing of the text data to convert it into numerical form that the algorithm will be able to consume to create a model.\n\nWe will do typical pre processing for NLP workloads such as: dummy encoding the labels, tokenizing the documents and set fixed sequence lengths for input feature dimension, padding documents to have fixed length input vectors.\n",
"_____no_output_____"
],
[
"### Dummy Encode the Labels\n",
"_____no_output_____"
]
],
[
[
"encoded_y, labels = util.preprocessing.dummy_encode_labels(df, \"CATEGORY\")\nprint(labels)\n",
"_____no_output_____"
],
[
"df[\"CATEGORY\"][1]",
"_____no_output_____"
],
[
"encoded_y[0]",
"_____no_output_____"
]
],
[
[
"### Tokenize and Set Fixed Sequence Lengths\n\nWe want to describe our inputs at the more meaningful word level (rather than individual characters), and ensure a fixed length of the input feature dimension.\n",
"_____no_output_____"
]
],
[
[
"padded_docs, tokenizer = util.preprocessing.tokenize_pad_docs(df, \"TITLE\")\n",
"_____no_output_____"
],
[
"df[\"TITLE\"][1]",
"_____no_output_____"
],
[
"padded_docs[0]",
"_____no_output_____"
]
],
[
[
"### Import Word Embeddings\n\nTo represent our words in numeric form, we'll use pre-trained vector representations for each word in the vocabulary: In this case we'll be using pre-built GloVe word embeddings.\n\nYou could also explore training custom, domain-specific word embeddings using SageMaker's built-in [BlazingText algorithm](https://docs.aws.amazon.com/sagemaker/latest/dg/blazingtext.html). See the official [blazingtext_word2vec_text8 sample](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/introduction_to_amazon_algorithms/blazingtext_word2vec_text8) for an example notebook showing how.\n",
"_____no_output_____"
]
],
[
[
"%%time\nembedding_matrix = util.preprocessing.get_word_embeddings(tokenizer, \"data/embeddings\")\n",
"_____no_output_____"
],
[
"np.save(\n file=\"./data/embeddings/docs-embedding-matrix\",\n arr=embedding_matrix,\n allow_pickle=False,\n)\nvocab_size=embedding_matrix.shape[0]\nprint(embedding_matrix.shape)\n",
"_____no_output_____"
]
],
[
[
"### Split Train and Test Sets\n\nFinally we need to divide our data into model training and evaluation sets:\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(\n padded_docs,\n encoded_y,\n test_size=0.2,\n random_state=42\n)\n",
"_____no_output_____"
],
[
"# Do you always remember to save your datasets for traceability when experimenting locally? ;-)\nos.makedirs(\"./data/train\", exist_ok=True)\nnp.save(\"./data/train/train_X.npy\", X_train)\nnp.save(\"./data/train/train_Y.npy\", y_train)\nos.makedirs(\"./data/test\", exist_ok=True)\nnp.save(\"./data/test/test_X.npy\", X_test)\nnp.save(\"./data/test/test_Y.npy\", y_test)\n",
"_____no_output_____"
]
],
[
[
"## Define the Model\n",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nfrom tensorflow.keras.layers import Conv1D, Dense, Dropout, Embedding, Flatten, MaxPooling1D\nfrom tensorflow.keras.models import Sequential\n\nseed = 42\nnp.random.seed(seed)\nnum_classes=len(labels)\n",
"_____no_output_____"
],
[
"model = Sequential()\nmodel.add(Embedding(\n vocab_size,\n 100,\n weights=[embedding_matrix],\n input_length=40,\n trainable=False,\n name=\"embed\"\n))\nmodel.add(Conv1D(filters=128, kernel_size=3, activation=\"relu\", name=\"conv_1\"))\nmodel.add(MaxPooling1D(pool_size=5, name=\"maxpool_1\"))\nmodel.add(Flatten(name=\"flat_1\"))\nmodel.add(Dropout(0.3, name=\"dropout_1\"))\nmodel.add(Dense(128, activation=\"relu\", name=\"dense_1\"))\nmodel.add(Dense(num_classes, activation=\"softmax\", name=\"out_1\"))\n\n# Compile the model\noptimizer = tf.keras.optimizers.RMSprop(learning_rate=0.001)\nmodel.compile(optimizer=optimizer, loss=\"binary_crossentropy\", metrics=[\"acc\"])\n\nmodel.summary()\n",
"_____no_output_____"
]
],
[
[
"## Fit (Train) and Evaluate the Model\n",
"_____no_output_____"
]
],
[
[
"%%time\n# fit the model here in the notebook:\nprint(\"Training model\")\nmodel.fit(X_train, y_train, batch_size=16, epochs=5, verbose=1)\nprint(\"Evaluating model\")\n# TODO: Better differentiate train vs val loss in logs\nscores = model.evaluate(X_test, y_test, verbose=2)\nprint(\n \"Validation results: \"\n + \"; \".join(map(\n lambda i: f\"{model.metrics_names[i]}={scores[i]:.5f}\", range(len(model.metrics_names))\n ))\n)\n ",
"_____no_output_____"
]
],
[
[
"## Use the Model (Locally)\n\nLet's evaluate our model with some example headlines...\n\nIf you struggle with the widget, you can always simply call the `classify()` function from Python. You can be creative with your headlines!\n",
"_____no_output_____"
]
],
[
[
"from IPython import display\nimport ipywidgets as widgets\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\ndef classify(text):\n \"\"\"Classify a headline and print the results\"\"\"\n encoded_example = tokenizer.texts_to_sequences([text])\n # Pad documents to a max length of 40 words\n max_length = 40\n padded_example = pad_sequences(encoded_example, maxlen=max_length, padding=\"post\")\n result = model.predict(padded_example)\n print(result)\n ix = np.argmax(result)\n print(f\"Predicted class: '{labels[ix]}' with confidence {result[0][ix]:.2%}\")\n\ninteraction = widgets.interact_manual(\n classify,\n text=widgets.Text(\n value=\"The markets were bullish after news of the merger\",\n placeholder=\"Type a news headline...\",\n description=\"Headline:\",\n layout=widgets.Layout(width=\"99%\"),\n )\n)\ninteraction.widget.children[1].description = \"Classify!\"",
"_____no_output_____"
]
],
[
[
"## Review\n\nIn this notebook we pre-processed publicly downloadable data and trained a neural news headline classifier model: As a data scientist might normally do when working on a local machine.\n\n...But can we use the cloud more effectively to allocate high-performance resources; and easily deploy our trained models for use by other applications?\n\nHead on over to the next notebook, [Headline Classifier SageMaker.ipynb](Headline%20Classifier%20SageMaker.ipynb), where we'll show how the same model can be trained and then deployed on specific target infrastructure with Amazon SageMaker.\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"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a37a1f5bb7bc0a1e699136e97b1286e6c33e813
| 102,561 |
ipynb
|
Jupyter Notebook
|
howto/00-intro-ROOT.ipynb
|
HolyBayes/rep
|
8a8d70f87e148e6fd73ff0c3a8606e6074a5c47b
|
[
"Apache-2.0"
] | 726 |
2015-04-16T08:16:30.000Z
|
2022-03-25T19:19:42.000Z
|
howto/00-intro-ROOT.ipynb
|
HolyBayes/rep
|
8a8d70f87e148e6fd73ff0c3a8606e6074a5c47b
|
[
"Apache-2.0"
] | 86 |
2015-04-16T23:57:01.000Z
|
2021-09-26T01:03:47.000Z
|
howto/00-intro-ROOT.ipynb
|
HolyBayes/rep
|
8a8d70f87e148e6fd73ff0c3a8606e6074a5c47b
|
[
"Apache-2.0"
] | 167 |
2015-04-16T11:42:18.000Z
|
2022-01-11T15:10:19.000Z
| 159.503888 | 24,022 | 0.868566 |
[
[
[
"# 5 minutes intro to IPython for ROOT users\n\nIn this notebook we show how to use inside IPython __ROOT__ (C++ library, de-facto standard in High Energy Physics).\n\nThis notebook is aimed to help __ROOT__ users.\n\nWorking using ROOT-way loops is very slow in python and in most cases useless.\n\nYou're proposed to use `root_numpy` — a very convenient python library to operate with ROOT (`root_numpy` is included in REP docker image, but it is installed quite easily).",
"_____no_output_____"
],
[
"### Allowing inline plots",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## Creating ROOT file using root_numpy\n\nThere are two libraries to work with ROOT files\n\n* rootpy http://www.rootpy.org - direct wrapper to ROOT methods.\n* root_numpy http://rootpy.github.io/root_numpy/ - new-style, efficient and simple library to deal with ROOT files from python\n\nLet's show how to use the second library.",
"_____no_output_____"
]
],
[
[
"import numpy\nimport root_numpy\n# generating random data\ndata = numpy.random.normal(size=[10000, 2])\n# adding names of columns\ndata = data.view([('first', float), ('second', float)])\n# saving to file\nroot_numpy.array2root(data, filename='./toy_datasets/random.root', treename='tree', mode='recreate')",
"_____no_output_____"
],
[
"!ls ./toy_datasets",
"MiniBooNE_PID.txt README.md magic04.data random.root wget-log\r\n"
]
],
[
[
"## Add column to the ROOT file using root_numpy",
"_____no_output_____"
]
],
[
[
"from rootpy.io import root_open\nwith root_open('./toy_datasets/random.root', mode='a') as myfile:\n new_column = numpy.array(numpy.ones([10000, 1]) , dtype=[('new', 'f8')])\n root_numpy.array2tree(new_column, tree=myfile.tree)\n myfile.write()",
"_____no_output_____"
],
[
"root_numpy.root2array('./toy_datasets/random.root', treename='tree')",
"_____no_output_____"
]
],
[
[
"# Plot function using ROOT\n\npay attention that `canvas` is on the last line. This is an output value of cell.\n\nWhen IPython cell return canvas, it is automatically drawn",
"_____no_output_____"
]
],
[
[
"import ROOT\nfrom rep.plotting import canvas\ncanvas = canvas('my_canvas')\nfunction1 = ROOT.TF1( 'fun1', 'abs(sin(x)/x)', 0, 10)\ncanvas.SetGridx()\ncanvas.SetGridy()\nfunction1.Draw()\n# Drawing output (last line is considered as output of cell)\ncanvas",
"_____no_output_____"
]
],
[
[
"# Plot histogram using ROOT for branch in root file",
"_____no_output_____"
]
],
[
[
"File = ROOT.TFile(\"toy_datasets/random.root\")\nTree = File.Get(\"tree\")\nTree.Draw(\"first\")\ncanvas",
"_____no_output_____"
]
],
[
[
"## use histogram settings",
"_____no_output_____"
]
],
[
[
"# we need to keep histogram in any variable, otherwise it will be deleted automatically\nh1 = ROOT.TH1F(\"h1\",\"hist from tree\",50, -0.25, 0.25)\nTree.Draw(\"first>>h1\")\ncanvas",
"_____no_output_____"
]
],
[
[
"# root_numpy + ipython way\n\nBut IPython provides it's own plotting / data manipulation techniques. Brief demostration below.\n\nPay attention that there is column-expression which is evaluated on-the-fly.",
"_____no_output_____"
]
],
[
[
"data = root_numpy.root2array(\"toy_datasets/random.root\", \n treename='tree', \n branches=['first', 'second', 'sin(first) * exp(second)'], \n selection='first > 0')",
"_____no_output_____"
]
],
[
[
"__in the example above__ we selected three branches (one of which is an expression and was computed on-the-fly) and selections",
"_____no_output_____"
]
],
[
[
"# taking, i.e. first 10 elements using python slicing:\ndata2 = data[:10]",
"_____no_output_____"
]
],
[
[
"### Convert to pandas\n\npandas allows easy manipulations with data.",
"_____no_output_____"
]
],
[
[
"import pandas\ndataframe = pandas.DataFrame(data)\n# looking at first elements\ndataframe.head()",
"_____no_output_____"
],
[
"# taking elements, that satisfy some condition, again showing only first\ndataframe[dataframe['second'] > 0].head()",
"_____no_output_____"
],
[
"# adding new column as result of some operation\ndataframe['third'] = dataframe['first'] + dataframe['second'] \ndataframe.head()",
"_____no_output_____"
]
],
[
[
"## Histograms in python\n\nDefault library for plotting in python is matplotlib.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nplt.figure(figsize=(9, 7))\nplt.hist(data['first'], bins=50)\nplt.xlabel('first')",
"_____no_output_____"
],
[
"plt.figure(figsize=(9, 7))\nplt.hist(data['second'], bins=50)\nplt.xlabel('second')",
"_____no_output_____"
]
],
[
[
"## Summary\n\n- you can work in standard way with ROOT (by using rootpy), but it is slow\n- you can benefit serously from python tools (those are fast and very flexible):\n - matplotlib for plotting\n - numpy / pandas for manipating arrays/dataframes\n- to deal with ROOT files, you can use `root_numpy` as a very nice bridge between two worlds.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4a37ce01eeeafa9c14789637803758691d09b1ad
| 131,739 |
ipynb
|
Jupyter Notebook
|
Electricity.ipynb
|
Open-Source-Spatial-Clean-Cooking-Tool/OnSSTOVE
|
4c02ab15319cb3b464d7b93b0754c239dfaef987
|
[
"MIT"
] | null | null | null |
Electricity.ipynb
|
Open-Source-Spatial-Clean-Cooking-Tool/OnSSTOVE
|
4c02ab15319cb3b464d7b93b0754c239dfaef987
|
[
"MIT"
] | 124 |
2021-06-18T07:18:56.000Z
|
2022-01-18T08:38:23.000Z
|
Electricity.ipynb
|
Open-Source-Spatial-Clean-Cooking-Tool/OnSSTOVE
|
4c02ab15319cb3b464d7b93b0754c239dfaef987
|
[
"MIT"
] | null | null | null | 234.828877 | 34,180 | 0.918604 |
[
[
[
"from onstove.raster import *\nimport rasterio\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nimport matplotlib\nimport numpy as np\nimport psycopg2\nfrom decouple import config\nimport plotly.express as px\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.cluster import DBSCAN, OPTICS\nfrom rasterstats import zonal_stats",
"_____no_output_____"
],
[
"POSTGRES_USER = config('POSTGRES_USER')\nPOSTGRES_KEY = config('POSTGRES_KEY')\n\nconn = psycopg2.connect(\n database=\"nepal\", user=POSTGRES_USER, password=POSTGRES_KEY\n)",
"_____no_output_____"
],
[
"pop_path = 'data/population_npl_2018-10-01_3857_100x100.tif'\nwith rasterio.open(pop_path) as src:\n population = src.read(1)\n population_meta = src.meta",
"_____no_output_____"
]
],
[
[
"## Clusering and urban/rural split",
"_____no_output_____"
]
],
[
[
"rows, cols = np.where(population>0)",
"_____no_output_____"
],
[
"x, y = rasterio.transform.xy(population_meta['transform'], \n rows, cols, \n offset='center')\ncoords = np.column_stack((x, y))",
"_____no_output_____"
],
[
"labels = DBSCAN(eps=500, min_samples=50).fit_predict(coords)\n# labels = OPTICS(max_eps=300, min_samples=7, xi=.05, min_cluster_size=.05).fit_predict(coords)",
"_____no_output_____"
],
[
"clusters = population.copy()\nclusters[rows, cols] = labels\nclusters[np.isnan(clusters)] = -9999",
"_____no_output_____"
],
[
"out_meta = population_meta.copy()\nout_meta.update(compression='DEFLATE',\n dtype=rasterio.int32,\n nodata=-9999)\n\nwith rasterio.open('data/clusters.tif', 'w', **out_meta) as dst:\n dst.write(clusters.astype(int), 1)",
"_____no_output_____"
],
[
"df = gpd.GeoDataFrame({'Population': population[rows, cols], 'Cluster': clusters[rows, cols], \n 'geometry': gpd.points_from_xy(x, y)})",
"_____no_output_____"
],
[
"max_cluster = df['Cluster'].max()\ncluster_number = df.loc[df['Cluster']==-1, 'Cluster'].count()",
"_____no_output_____"
],
[
"df.loc[df['Cluster']==-1, 'Cluster'] = [max_cluster + i for i in range(1, cluster_number + 1)]\ndf['Area'] = population_meta['transform'][0] * abs(population_meta['transform'][4]) / (1000 ** 2)\ndf_clusters = df.groupby('Cluster')[['Population', 'Area']].sum().reset_index()",
"_____no_output_____"
],
[
"calibrate_urban(df_clusters, 0.197, '')",
"Modelled urban ratio is 0.188% in comparision to the actual ratio of 0.197% after 1 iterations.\n"
],
[
"dff = df.merge(df_clusters[['Cluster', 'IsUrban']], on='Cluster', how='left')",
"_____no_output_____"
],
[
"isurban = population.copy()\nisurban[rows, cols] = dff['IsUrban']\nisurban[np.isnan(isurban)] = -9999",
"_____no_output_____"
],
[
"out_meta = population_meta.copy()\nout_meta.update(compression='DEFLATE',\n dtype=rasterio.int32,\n nodata=-9999)\n\nwith rasterio.open('data/isurban.tif', 'w', **out_meta) as dst:\n dst.write(isurban.astype(int), 1)",
"_____no_output_____"
]
],
[
[
"## Tiers analysis",
"_____no_output_____"
]
],
[
[
"ntl, ntl_meta = align_raster(pop_path, \n 'data/npp_2020_average_masked.tif',\n method='average')",
"_____no_output_____"
],
[
"land_cover, land_cover_meta = align_raster(pop_path, \n 'data/MCD12Q1_type1.tif',\n method='nearest')",
"_____no_output_____"
],
[
"# npp_pop = (population>0) * (land_cover==13) * (npp>0.35) * npp\nntl_pop = (population>0) * (ntl>0) * ntl\n# npp_pop[population>0] /= population[population>0]",
"_____no_output_____"
],
[
"sql = 'SELECT * FROM admin.npl_admbnda_adm0_nd_20201117'\nadm0 = gpd.read_postgis(sql, conn)\nshapes = ((g, 1) for g in adm0.to_crs(3857)['geom'].values)\n\nwith rasterio.open(pop_path) as src:\n mask = features.rasterize(\n shapes,\n out_shape=src.shape,\n transform=src.transform,\n all_touched=False,\n fill=0)\nmask[population>0] = 1\nntl_pop[mask==0] = np.nan\nntl_pop[ntl_pop==0] = np.nan\n\nntl_urban = ntl_pop.copy()\nntl_urban[isurban!=2] = np.nan\n\nntl_periurban = ntl_pop.copy()\nntl_periurban[isurban!=1] = np.nan\n\nntl_rural = ntl_pop.copy()\nntl_rural[isurban!=0] = np.nan\n# npp_pop_copy = npp_pop.copy()\n# npp_pop_copy[npp_pop_copy==0] = -9999",
"_____no_output_____"
],
[
"out_meta = population_meta.copy()\nout_meta.update(compression='DEFLATE',\n dtype=rasterio.float64,\n nodata=np.nan)\n\nwith rasterio.open('data/ntl_urban.tif', 'w', **out_meta) as dst:\n dst.write(ntl_urban, 1)",
"_____no_output_____"
],
[
"out_meta = population_meta.copy()\nout_meta.update(compression='DEFLATE',\n dtype=rasterio.float64,\n nodata=np.nan)\n\nwith rasterio.open('data/ntl_periurban.tif', 'w', **out_meta) as dst:\n dst.write(ntl_periurban, 1)",
"_____no_output_____"
],
[
"out_meta = population_meta.copy()\nout_meta.update(compression='DEFLATE',\n dtype=rasterio.float64,\n nodata=np.nan)\n\nwith rasterio.open('data/ntl_rural.tif', 'w', **out_meta) as dst:\n dst.write(ntl_rural, 1)",
"_____no_output_____"
],
[
"sql = 'SELECT * FROM admin.npl_admbnda_districts_nd_20201117'\ndf_district = gpd.read_postgis(sql, conn)\ndf_district.to_crs(3857, inplace=True)\n# shapes = ((g, d) for g, d in zip(df_district['geom'].values, df_district['id'].values))",
"_____no_output_____"
],
[
"def get_tiers(raster_path, ntl, gdf):\n stats = ['percentile_20', 'percentile_40', 'percentile_60', 'percentile_80']\n result = zonal_stats(gdf, raster_path, \n stats=stats,\n geojson_out=True)\n \n percentiles = gpd.GeoDataFrame.from_features(result)\n \n df = percentiles[stats].melt()\n medians = percentiles[stats].median()\n \n ax = sns.displot(df, x='value', hue='variable', kind=\"kde\")\n# ax.set(xlim=(0, 2))\n \n tiers = ntl.copy()\n tiers[(ntl>0) & (ntl<medians['percentile_30'])] = 1\n tiers[(ntl>=medians['percentile_20']) & (ntl<medians['percentile_40'])] = 2\n tiers[(ntl>=medians['percentile_40']) & (ntl<medians['percentile_60'])] = 3\n tiers[(ntl>=medians['percentile_60']) & (ntl<medians['percentile_80'])] = 4\n tiers[(ntl>=medians['percentile_80'])] = 5\n tiers[np.isnan(tiers)] = 0\n \n return tiers",
"_____no_output_____"
],
[
"tiers_urban = get_tiers('data/ntl_urban.tif', ntl_urban, df_district)\ntiers_periurban = get_tiers('data/ntl_periurban.tif', ntl_periurban, df_district)\ntiers_rural = get_tiers('data/ntl_rural.tif', ntl_rural, df_district)",
"_____no_output_____"
],
[
"tiers = tiers_urban + tiers_periurban + tiers_rural",
"_____no_output_____"
],
[
"cmap = matplotlib.cm.get_cmap(\"Spectral_r\", 6)\nfig, ax = plt.subplots(1, 1, figsize=(16,9))\ncax = ax.imshow(tiers, extent=extent, cmap=cmap)\ncbar = fig.colorbar(cax, shrink=0.8, ticks=[0, 1, 2, 3, 4, 5])\n# fig.savefig(f\"data/tiers.png\", dpi=300, bbox_inches='tight')",
"_____no_output_____"
],
[
"np.nansum(population[tiers==5]) / np.nansum(population) * 100",
"_____no_output_____"
],
[
"np.nansum(population[tiers_urban==5]) / np.nansum(population) * 100",
"_____no_output_____"
],
[
"tiers[np.isnan(population)] = -9999\nout_meta = population_meta.copy()\nout_meta.update(compression='DEFLATE',\n dtype=rasterio.int32,\n nodata=-9999)\n\nwith rasterio.open('data/tiers3.tif', 'w', **out_meta) as dst:\n dst.write(tiers.astype(int), 1)",
"_____no_output_____"
]
],
[
[
"### This approach is not giving good results, so maybe we can calibrate the Tiers with a similar approach as the Urban / Rural split, but using NTL, population density and wealth index.",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
4a37d2996efd5705b0bd63791d8a2c06fad9b3dd
| 14,145 |
ipynb
|
Jupyter Notebook
|
custom_tensorflow_keras_nlp/Headline Classifier Local.ipynb
|
tagekezo/sagemaker-101-workshop
|
1fecdc727fc69b7d82f21c9763fc0fe1783f6f84
|
[
"MIT-0"
] | null | null | null |
custom_tensorflow_keras_nlp/Headline Classifier Local.ipynb
|
tagekezo/sagemaker-101-workshop
|
1fecdc727fc69b7d82f21c9763fc0fe1783f6f84
|
[
"MIT-0"
] | null | null | null |
custom_tensorflow_keras_nlp/Headline Classifier Local.ipynb
|
tagekezo/sagemaker-101-workshop
|
1fecdc727fc69b7d82f21c9763fc0fe1783f6f84
|
[
"MIT-0"
] | null | null | null | 29.841772 | 414 | 0.593708 |
[
[
[
"# End-to-End NLP: News Headline Classifier (Local Version)\n\n_**Train a Keras-based model to classify news headlines between four domains**_\n\nThis notebook works well with the `Python 3 (TensorFlow 1.15 Python 3.7 CPU Optimized)` kernel on SageMaker Studio, or `conda_tensorflow_p36` on classic SageMaker Notebook Instances.\n\n---\n\nIn this version, the model is trained and evaluated here on the notebook instance itself. We'll show in the follow-on notebook how to take advantage of Amazon SageMaker to separate these infrastructure needs.\n\nNote that you can safely ignore the WARNING about the pip version.\n",
"_____no_output_____"
]
],
[
[
"# First install some libraries which might not be available across all kernels (e.g. in Studio):\n!pip install ipywidgets",
"_____no_output_____"
]
],
[
[
"### Set Up Execution Role and Session\n\nLet's start by specifying:\n\n- The S3 bucket and prefix that you want to use for training and model data. This should be within the same region as the Notebook Instance, training, and hosting. If you don't specify a bucket, SageMaker SDK will create a default bucket following a pre-defined naming convention in the same region. \n- The IAM role ARN used to give SageMaker access to your data. It can be fetched using the **get_execution_role** method from sagemaker python SDK.\n",
"_____no_output_____"
]
],
[
[
"%%time\n%load_ext autoreload\n%autoreload 2\n\nimport sagemaker\nfrom sagemaker import get_execution_role\n\nrole = get_execution_role()\nprint(role)\nsess = sagemaker.Session()\n",
"_____no_output_____"
]
],
[
[
"### Download News Aggregator Dataset\n\nWe will download **FastAi AG News** dataset from the https://registry.opendata.aws/fast-ai-nlp/ public repository. This dataset contains a table of news headlines and their corresponding classes.\n",
"_____no_output_____"
]
],
[
[
"%%time\nimport util.preprocessing\n\nutil.preprocessing.download_dataset()\n",
"_____no_output_____"
]
],
[
[
"### Let's visualize the dataset\n\nWe will load the ag_news_csv/train.csv file to a Pandas dataframe for our data processing work.",
"_____no_output_____"
]
],
[
[
"import os\nimport re\nimport numpy as np\nimport pandas as pd\n",
"_____no_output_____"
],
[
"column_names = [\"CATEGORY\", \"TITLE\", \"CONTENT\"]\n# we use the train.csv only\ndf = pd.read_csv(\"data/ag_news_csv/train.csv\", names=column_names, header=None, delimiter=\",\")\n# shuffle the DataFrame rows\ndf = df.sample(frac=1, random_state=1337)\n# make the category classes more readable\nmapping = {1: 'World', 2: 'Sports', 3: 'Business', 4: 'Sci/Tech'}\ndf = df.replace({'CATEGORY': mapping})\ndf.head()\n",
"_____no_output_____"
]
],
[
[
"For this exercise we'll **only use**:\n\n- The **title** (Headline) of the news story, as our input\n- The **category**, as our target variable\n",
"_____no_output_____"
]
],
[
[
"df[\"CATEGORY\"].value_counts()\n",
"_____no_output_____"
]
],
[
[
"The dataset has **four article categories** with equal weighting:\n\n- Business\n- Sci/Tech\n- Sports\n- World\n",
"_____no_output_____"
],
[
"## Natural Language Pre-Processing\n\nWe'll do some basic processing of the text data to convert it into numerical form that the algorithm will be able to consume to create a model.\n\nWe will do typical pre processing for NLP workloads such as: dummy encoding the labels, tokenizing the documents and set fixed sequence lengths for input feature dimension, padding documents to have fixed length input vectors.\n",
"_____no_output_____"
],
[
"### Dummy Encode the Labels\n",
"_____no_output_____"
]
],
[
[
"encoded_y, labels = util.preprocessing.dummy_encode_labels(df, \"CATEGORY\")\nprint(labels)\n",
"_____no_output_____"
],
[
"df[\"CATEGORY\"].iloc[0]",
"_____no_output_____"
],
[
"encoded_y[0]",
"_____no_output_____"
]
],
[
[
"### Tokenize and Set Fixed Sequence Lengths\n\nWe want to describe our inputs at the more meaningful word level (rather than individual characters), and ensure a fixed length of the input feature dimension.\n",
"_____no_output_____"
]
],
[
[
"padded_docs, tokenizer = util.preprocessing.tokenize_pad_docs(df, \"TITLE\")\n",
"_____no_output_____"
],
[
"df[\"TITLE\"].iloc[0]",
"_____no_output_____"
],
[
"padded_docs[0]",
"_____no_output_____"
]
],
[
[
"### Import Word Embeddings\n\nTo represent our words in numeric form, we'll use pre-trained vector representations for each word in the vocabulary: In this case we'll be using pre-built GloVe word embeddings.\n\nYou could also explore training custom, domain-specific word embeddings using SageMaker's built-in [BlazingText algorithm](https://docs.aws.amazon.com/sagemaker/latest/dg/blazingtext.html). See the official [blazingtext_word2vec_text8 sample](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/introduction_to_amazon_algorithms/blazingtext_word2vec_text8) for an example notebook showing how.\n",
"_____no_output_____"
]
],
[
[
"%%time\nembedding_matrix = util.preprocessing.get_word_embeddings(tokenizer, \"data/embeddings\")\n",
"_____no_output_____"
],
[
"np.save(\n file=\"./data/embeddings/docs-embedding-matrix\",\n arr=embedding_matrix,\n allow_pickle=False,\n)\nvocab_size=embedding_matrix.shape[0]\nprint(embedding_matrix.shape)\n",
"_____no_output_____"
]
],
[
[
"### Split Train and Test Sets\n\nFinally we need to divide our data into model training and evaluation sets:\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(\n padded_docs,\n encoded_y,\n test_size=0.2,\n random_state=42\n)\n",
"_____no_output_____"
],
[
"# Do you always remember to save your datasets for traceability when experimenting locally? ;-)\nos.makedirs(\"./data/train\", exist_ok=True)\nnp.save(\"./data/train/train_X.npy\", X_train)\nnp.save(\"./data/train/train_Y.npy\", y_train)\nos.makedirs(\"./data/test\", exist_ok=True)\nnp.save(\"./data/test/test_X.npy\", X_test)\nnp.save(\"./data/test/test_Y.npy\", y_test)\n",
"_____no_output_____"
]
],
[
[
"## Define the Model\n",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nfrom tensorflow.keras.layers import Conv1D, Dense, Dropout, Embedding, Flatten, MaxPooling1D\nfrom tensorflow.keras.models import Sequential\n\nseed = 42\nnp.random.seed(seed)\nnum_classes=len(labels)\n",
"_____no_output_____"
],
[
"model = Sequential()\nmodel.add(Embedding(\n vocab_size,\n 100,\n weights=[embedding_matrix],\n input_length=40,\n trainable=False,\n name=\"embed\"\n))\nmodel.add(Conv1D(filters=128, kernel_size=3, activation=\"relu\", name=\"conv_1\"))\nmodel.add(MaxPooling1D(pool_size=5, name=\"maxpool_1\"))\nmodel.add(Flatten(name=\"flat_1\"))\nmodel.add(Dropout(0.3, name=\"dropout_1\"))\nmodel.add(Dense(128, activation=\"relu\", name=\"dense_1\"))\nmodel.add(Dense(num_classes, activation=\"softmax\", name=\"out_1\"))\n\n# Compile the model\noptimizer = tf.keras.optimizers.RMSprop(learning_rate=0.001)\nmodel.compile(optimizer=optimizer, loss=\"binary_crossentropy\", metrics=[\"acc\"])\n\nmodel.summary()\n",
"_____no_output_____"
]
],
[
[
"## Fit (Train) and Evaluate the Model\n",
"_____no_output_____"
]
],
[
[
"%%time\n# fit the model here in the notebook:\nprint(\"Training model\")\nmodel.fit(X_train, y_train, batch_size=16, epochs=5, verbose=1)\nprint(\"Evaluating model\")\n# TODO: Better differentiate train vs val loss in logs\nscores = model.evaluate(X_test, y_test, verbose=2)\nprint(\n \"Validation results: \"\n + \"; \".join(map(\n lambda i: f\"{model.metrics_names[i]}={scores[i]:.5f}\", range(len(model.metrics_names))\n ))\n)\n ",
"_____no_output_____"
]
],
[
[
"## Use the Model (Locally)\n\nLet's evaluate our model with some example headlines...\n\nIf you struggle with the widget, you can always simply call the `classify()` function from Python. You can be creative with your headlines!\n",
"_____no_output_____"
]
],
[
[
"from IPython import display\nimport ipywidgets as widgets\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\ndef classify(text):\n \"\"\"Classify a headline and print the results\"\"\"\n encoded_example = tokenizer.texts_to_sequences([text])\n # Pad documents to a max length of 40 words\n max_length = 40\n padded_example = pad_sequences(encoded_example, maxlen=max_length, padding=\"post\")\n result = model.predict(padded_example)\n print(result)\n ix = np.argmax(result)\n print(f\"Predicted class: '{labels[ix]}' with confidence {result[0][ix]:.2%}\")\n\ninteraction = widgets.interact_manual(\n classify,\n text=widgets.Text(\n value=\"The markets were bullish after news of the merger\",\n placeholder=\"Type a news headline...\",\n description=\"Headline:\",\n layout=widgets.Layout(width=\"99%\"),\n )\n)\ninteraction.widget.children[1].description = \"Classify!\"",
"_____no_output_____"
]
],
[
[
"## Review\n\nIn this notebook we pre-processed publicly downloadable data and trained a neural news headline classifier model: As a data scientist might normally do when working on a local machine.\n\n...But can we use the cloud more effectively to allocate high-performance resources; and easily deploy our trained models for use by other applications?\n\nHead on over to the next notebook, [Headline Classifier SageMaker.ipynb](Headline%20Classifier%20SageMaker.ipynb), where we'll show how the same model can be trained and then deployed on specific target infrastructure with Amazon SageMaker.\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"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a37d74bb654e74b69d7f3c0606077ee44660a47
| 3,004 |
ipynb
|
Jupyter Notebook
|
2021/day06/day06.ipynb
|
acz13/advent-of-code-2019
|
7b94d1ed3d775946f0445c1f97863f74120ed372
|
[
"MIT"
] | null | null | null |
2021/day06/day06.ipynb
|
acz13/advent-of-code-2019
|
7b94d1ed3d775946f0445c1f97863f74120ed372
|
[
"MIT"
] | null | null | null |
2021/day06/day06.ipynb
|
acz13/advent-of-code-2019
|
7b94d1ed3d775946f0445c1f97863f74120ed372
|
[
"MIT"
] | null | null | null | 23.653543 | 82 | 0.477031 |
[
[
[
"import ipywidgets as widgets\nfrom aocd import submit\n\nta = widgets.Textarea(\n placeholder='Input data',\n description='Input:',\n disabled=False\n)\nta",
"_____no_output_____"
],
[
"import collections\n\ndef disp(i):\n s = str(i)\n return f\"{s[0]}.{s[1:5]}e{len(s)-1}\"\n\ndef lanternfish_count(ages, t):\n day_counter = collections.Counter(t - age - 1 for age in ages)\n\n # Start computing our table from here\n combs = collections.deque([1, 0, 0, 0, 0, 0, 0, 1, 0])\n # and our sums from here\n population = 3\n\n def _iterate():\n s = combs.popleft() + combs[1]\n combs.append(s)\n return s\n \n k = 8\n for i in range(9, t-6):\n population += _iterate()\n k += 1\n if k == 10000:\n print(f\"\\rDay {i}: Table at {disp(population)}\", end=\"\")\n k = 0\n \n count = 0\n\n for day in range(t-6, t):\n population += _iterate()\n count += day_counter[day] * population\n\n return count",
"_____no_output_____"
],
[
"ages = [int(i) for i in ta.value.split(\",\")]\nprint(\"Part 1:\", lanternfish_count(ages, 80))\nprint(\"Part 2:\", lanternfish_count(ages, 256))",
"Part 1: 386640\nPart 2: 1733403626279\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
4a37ec5fe12b641b7d9804d79a5a32e3bec6d00d
| 2,250 |
ipynb
|
Jupyter Notebook
|
01_getting_started/10_role_of_spark_or_hive_metastore.ipynb
|
itversity/spark-sql
|
017181d9976e39848c5e46fc628a7ba9cbc38ec0
|
[
"MIT"
] | 9 |
2020-12-26T11:03:45.000Z
|
2022-03-03T14:12:30.000Z
|
01_getting_started/10_role_of_spark_or_hive_metastore.ipynb
|
itversity/spark-sql
|
017181d9976e39848c5e46fc628a7ba9cbc38ec0
|
[
"MIT"
] | null | null | null |
01_getting_started/10_role_of_spark_or_hive_metastore.ipynb
|
itversity/spark-sql
|
017181d9976e39848c5e46fc628a7ba9cbc38ec0
|
[
"MIT"
] | 17 |
2020-12-26T20:23:45.000Z
|
2022-03-10T06:10:55.000Z
| 29.605263 | 175 | 0.606222 |
[
[
[
"## Role of Spark or Hive Metastore\n\nLet us understand the role of Spark Metastore or Hive Metasore. We need to first understand details related to Metadata generated for Spark Metastore tables.",
"_____no_output_____"
]
],
[
[
"%%HTML\n<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/MKzHiKgKHIY?rel=0&controls=1&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>",
"_____no_output_____"
]
],
[
[
"* When we create a Spark Metastore table, there is metadata associated with it.\n * Table Name\n * Column Names and Data Types\n * Location\n * File Format\n * and more\n* This metadata has to be stored some where so that Query Engines such as Spark SQL can access the information to serve our queries.\n\nLet us understand where the metadata is stored.\n\n* Information is typically stored in relational database and it is called as metastore.\n* It is extensively used by Hive or Spark SQL engine for syntax and semantics check as well as execution of queries.\n* In our case it is stored in MySQL Database. Let us review the details by going through relevant properties.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a38013533039abe04cbd1ef56603989bc273550
| 193,374 |
ipynb
|
Jupyter Notebook
|
exercises/minimal_clustering&classification/.ipynb_checkpoints/clustering-blobs-kmeans-within-sum-of-squares-checkpoint.ipynb
|
kolibril13/data-science-and-big-data-analytics
|
68abb8c8aed3ecd73ad3de62d6f41894893f37a6
|
[
"Apache-2.0"
] | 1 |
2019-12-15T19:42:06.000Z
|
2019-12-15T19:42:06.000Z
|
exercises/minimal_clustering&classification/.ipynb_checkpoints/clustering-blobs-kmeans-within-sum-of-squares-checkpoint.ipynb
|
kolibril13/data-science-and-big-data-analytics
|
68abb8c8aed3ecd73ad3de62d6f41894893f37a6
|
[
"Apache-2.0"
] | null | null | null |
exercises/minimal_clustering&classification/.ipynb_checkpoints/clustering-blobs-kmeans-within-sum-of-squares-checkpoint.ipynb
|
kolibril13/data-science-and-big-data-analytics
|
68abb8c8aed3ecd73ad3de62d6f41894893f37a6
|
[
"Apache-2.0"
] | null | null | null | 971.728643 | 95,992 | 0.953179 |
[
[
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nplt.rcParams['figure.dpi'] = 150 \n",
"_____no_output_____"
],
[
"from sklearn.datasets import make_blobs\nplt.rcParams['figure.dpi'] = 150 \n# create dataset\nX, y = make_blobs(\n n_samples=150, n_features=2,\n centers=3, cluster_std=0.5,\n shuffle=True, random_state=0\n)\n\n\n# plot\nplt.scatter(\n X[:, 0], X[:, 1],\n edgecolor='black', s=50\n)\nplt.show()",
"_____no_output_____"
],
[
"from sklearn.cluster import KMeans\nwss= []\nindex = []\nfor i in range(1,10):\n km = KMeans(\n n_clusters=i, init='random',\n n_init=10, max_iter=10000, \n tol=1e-04, random_state=0\n )\n y_km = km.fit_predict(X)\n wss.append(km.inertia_)\n index.append(i)\nindex, wss",
"_____no_output_____"
],
[
"plt.plot(index,wss, marker= \"+\" )",
"_____no_output_____"
],
[
"km = KMeans(\n n_clusters=3, init='random',\n n_init=10, max_iter=10000, \n tol=1e-04, random_state=0\n )\ny_km = km.fit_predict(X)\nplt.scatter(X[:,0], X[:,1], c=y_km, s=50, cmap=plt.cm.Paired, alpha=0.4)\nplt.scatter(km.cluster_centers_[:, 0],km.cluster_centers_[:, 1], \n s=250, marker='*', label='centroids',\n edgecolor='black',\n c=np.arange(0,3),cmap=plt.cm.Paired,)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code"
]
] |
4a380efbd5ec5c5851db701fe7cc4efd669601f1
| 7,426 |
ipynb
|
Jupyter Notebook
|
DeepLearningFrameworks/Chainer_CNN.ipynb
|
gopala-kr/ds-notebooks
|
bc35430ecdd851f2ceab8f2437eec4d77cb59423
|
[
"MIT"
] | 1 |
2019-05-10T09:16:23.000Z
|
2019-05-10T09:16:23.000Z
|
DeepLearningFrameworks/Chainer_CNN.ipynb
|
gopala-kr/ds-notebooks
|
bc35430ecdd851f2ceab8f2437eec4d77cb59423
|
[
"MIT"
] | null | null | null |
DeepLearningFrameworks/Chainer_CNN.ipynb
|
gopala-kr/ds-notebooks
|
bc35430ecdd851f2ceab8f2437eec4d77cb59423
|
[
"MIT"
] | 1 |
2019-05-10T09:17:28.000Z
|
2019-05-10T09:17:28.000Z
| 25.258503 | 99 | 0.49798 |
[
[
[
"# High-level Chainer Example",
"_____no_output_____"
]
],
[
[
"import os\nos.environ['CHAINER_TYPE_CHECK'] = '0'\nimport sys\nimport numpy as np\nimport math\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer import optimizers\nfrom chainer import cuda\nfrom common.params import *\nfrom common.utils import *",
"_____no_output_____"
],
[
"cuda.set_max_workspace_size(512 * 1024 * 1024)\nchainer.global_config.autotune = True",
"_____no_output_____"
],
[
"print(\"OS: \", sys.platform)\nprint(\"Python: \", sys.version)\nprint(\"Chainer: \", chainer.__version__)\nprint(\"CuPy: \", chainer.cuda.cupy.__version__)\nprint(\"Numpy: \", np.__version__)\nprint(\"GPU: \", get_gpu_name())",
"OS: linux\nPython: 3.5.2 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:53:06) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]\nChainer: 3.1.0\nCuPy: 2.1.0\nNumpy: 1.13.3\nGPU: ['Tesla K80']\n"
],
[
"class SymbolModule(chainer.Chain):\n def __init__(self):\n super(SymbolModule, self).__init__()\n with self.init_scope():\n self.conv1 = L.Convolution2D(3, 50, ksize=3, pad=1)\n self.conv2 = L.Convolution2D(50, 50, ksize=3, pad=1)\n self.conv3 = L.Convolution2D(50, 100, ksize=3, pad=1)\n self.conv4 = L.Convolution2D(100, 100, ksize=3, pad=1)\n # feature map size is 8*8 by pooling\n self.fc1 = L.Linear(100*8*8, 512)\n self.fc2 = L.Linear(512, N_CLASSES)\n \n def __call__(self, x):\n h = F.relu(self.conv2(F.relu(self.conv1(x))))\n h = F.max_pooling_2d(h, ksize=2, stride=2)\n h = F.dropout(h, 0.25)\n \n h = F.relu(self.conv4(F.relu(self.conv3(h))))\n h = F.max_pooling_2d(h, ksize=2, stride=2)\n h = F.dropout(h, 0.25) \n \n h = F.dropout(F.relu(self.fc1(h)), 0.5)\n return self.fc2(h)",
"_____no_output_____"
],
[
"def init_model(m):\n optimizer = optimizers.MomentumSGD(lr=LR, momentum=MOMENTUM)\n optimizer.setup(m)\n return optimizer",
"_____no_output_____"
],
[
"%%time\n# Data into format for library\n#x_train, x_test, y_train, y_test = mnist_for_library(channel_first=True)\nx_train, x_test, y_train, y_test = cifar_for_library(channel_first=True)\nprint(x_train.shape, x_test.shape, y_train.shape, y_test.shape)\nprint(x_train.dtype, x_test.dtype, y_train.dtype, y_test.dtype)",
"Preparing train set...\nPreparing test set...\n(50000, 3, 32, 32) (10000, 3, 32, 32) (50000,) (10000,)\nfloat32 float32 int32 int32\nCPU times: user 885 ms, sys: 560 ms, total: 1.44 s\nWall time: 1.44 s\n"
],
[
"%%time\n# Create symbol\nsym = SymbolModule()\nif GPU:\n chainer.cuda.get_device(0).use() # Make a specified GPU current\n sym.to_gpu() # Copy the model to the GPU",
"CPU times: user 257 ms, sys: 232 ms, total: 488 ms\nWall time: 513 ms\n"
],
[
"%%time\noptimizer = init_model(sym)",
"CPU times: user 100 µs, sys: 0 ns, total: 100 µs\nWall time: 103 µs\n"
],
[
"%%time\n# 162s\nfor j in range(EPOCHS):\n for data, target in yield_mb(x_train, y_train, BATCHSIZE, shuffle=True):\n # Get samples\n data = cuda.to_gpu(data)\n target = cuda.to_gpu(target)\n output = sym(data)\n loss = F.softmax_cross_entropy(output, target)\n sym.cleargrads()\n loss.backward()\n optimizer.update()\n # Log\n print(j)",
"0\n1\n2\n3\n4\n5\n6\n7\n8\n9\nCPU times: user 2min 40s, sys: 1.68 s, total: 2min 42s\nWall time: 2min 42s\n"
],
[
"%%time\nn_samples = (y_test.shape[0]//BATCHSIZE)*BATCHSIZE\ny_guess = np.zeros(n_samples, dtype=np.int)\ny_truth = y_test[:n_samples]\nc = 0\n\nwith chainer.using_config('train', False), chainer.using_config('enable_backprop', False):\n for data, target in yield_mb(x_test, y_test, BATCHSIZE):\n # Forwards\n pred = cuda.to_cpu(sym(cuda.to_gpu(data)).data.argmax(-1))\n # Collect results\n y_guess[c*BATCHSIZE:(c+1)*BATCHSIZE] = pred\n c += 1",
"CPU times: user 1.74 s, sys: 32.1 ms, total: 1.77 s\nWall time: 1.77 s\n"
],
[
"print(\"Accuracy: \", sum(y_guess == y_truth)/len(y_guess))",
"Accuracy: 0.794070512821\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a38140dc9aa69067bcd9337732911bf082f6fe5
| 37,460 |
ipynb
|
Jupyter Notebook
|
notebooks/Perfect and Semiperfect gas models.ipynb
|
MRod5/pyturb
|
08b4016528fc50733fff58d967d1000bf1e634c9
|
[
"MIT"
] | 32 |
2017-04-13T12:25:23.000Z
|
2022-01-23T01:23:19.000Z
|
notebooks/Perfect and Semiperfect gas models.ipynb
|
sergiodobler/pyturb
|
248ea0ddc939c6d6f2c8d6b3f9a3d13976c22910
|
[
"MIT"
] | 12 |
2017-11-13T23:19:15.000Z
|
2021-11-28T20:18:28.000Z
|
notebooks/Perfect and Semiperfect gas models.ipynb
|
sergiodobler/pyturb
|
248ea0ddc939c6d6f2c8d6b3f9a3d13976c22910
|
[
"MIT"
] | 10 |
2017-05-06T20:05:46.000Z
|
2022-03-19T13:31:52.000Z
| 87.116279 | 24,492 | 0.823145 |
[
[
[
"# Gases: Perfect and Semiperfect Models\n\nIn this Notebook we will use `PerfectIdealGas` and `SemiperfectIdealGas` classes from **pyTurb**, to access the thermodynamic properties with a Perfect Ideal Gas or a Semiperfect Ideal Gas approach. Both classes acquire the thermodynamic properties of different species from the *NASA Glenn coefficients* in `thermo_properties.py`.\n\nNote that `PerfectIdealGas` and `SemiperfectIdealGas` classes are two different approaches for an *Ideal Gas*. \n\nThe `gas_models` functions and classes can be found in the following folders:\n\n- pyturb\n - gas_models\n - thermo_prop\n - PerfectIdealGas\n - SemiperfectIdealGas\n - GasMixture\n \n```python\n from pyturb.gas_models import ThermoProperties\n from pyturb.gas_models import PerfectIdealGas\n from pyturb.gas_models import SemiperfectIdealGas\n from pyturb.gas_models import GasMixture\n```\n\nFor an example about how to declae and use a Gas Mixture in **pyTurb**, go the \"Gas Mixtures.ipynb\" Notebook.\n\n### Ideal Gas\n\nWhile an Ideal Gas is characterized by a compressibility factor of 1:\n\n$$Z=1=\\frac{pv}{R_gT}$$\n\nWhich means that the *Ideal Gas Equation of State* is available: ($pv=R_gT$). It also means that the Mayer Equation is applicable: $R_g=c_p-c_v$.\n\n\n### Perfect and Semiperfect approaches\n\nA Perfect Gas or a Semiperfect Ideal Gas approach means:\n- If the gas is perfect: $c_v, c_p, \\gamma_g \\equiv constant$\n- If the gas is Semiperfect: $c_v(T), c_p(T), \\gamma_g(T) \\equiv f(T)$\n\nBy definition, the model used in `ThermoProperties` provide a 7 coefficients polynomial for the heat capacity at constant pressure ($c_p$):\n\n$$ \\frac{c_p}{R_g} = a_1T^{-2}+a_2T^{-1} + a_3 + a_4T + a_5T^2 a_6T^3 + a_7T^4$$\n\nWith the $c_p$, the Mayer Equation (valid for $Z=1$) and the heat capacity ratio we can obtain $c_v \\left(T\\right)$ and $\\gamma \\left(T\\right)$:\n\n$$ R_g =c_p\\left(T\\right)-c_v \\left(T\\right) $$\n\n$$\\gamma_g\\left(T\\right) = \\frac{c_p\\left(T\\right)}{c_v\\left(T\\right)}$$\n\n\n> In practice, the `PerfectIdealGas` object is a `SemiperfectIdealGas` where the temperature is set to $25ºC$.\n\n\n\n### Perfect and Semiperfect content\n\nBoth `PerfectIdealGas` and `SemiPerfectIdealGas` classes have the following content:\n\n- **Gas properties:** Ru, Rg, Mg, cp, cp_molar, cv, cv_molar, gamma\n- **Gas enthalpies, moles and mass:** h0, h0_molar, mg, Ng\n- **Chemical properties:** gas_species, thermo_prop\n\n### Other dependencies:\nWe will import `numpy` and `pyplot` as well, to make some graphical examples. \n\n---",
"_____no_output_____"
],
[
"### Check Gas Species availability:",
"_____no_output_____"
]
],
[
[
"from pyturb.gas_models import ThermoProperties",
"_____no_output_____"
],
[
"tp = ThermoProperties()\nprint(tp.species_list[850:875])",
"['Ni-', 'NiCL', 'NiCL2', 'NiO', 'NiS', 'O', 'O+', 'O-', 'OD', 'OD-', 'OH', 'OH+', 'OH-', 'O2', 'O2+', 'O2-', 'O3', 'P', 'P+', 'P-', 'PCL', 'PCL2', 'PCL2-', 'PCL3', 'PCL5']\n"
],
[
"tp.is_available('Air')",
"_____no_output_____"
]
],
[
[
"---\n\n### Import Perfect and Semiperfect Ideal Gas classes:\n\nExamples with Air:",
"_____no_output_____"
]
],
[
[
"from pyturb.gas_models import PerfectIdealGas\nfrom pyturb.gas_models import SemiperfectIdealGas",
"_____no_output_____"
],
[
"# Air as perfect gas:\nperfect_air = PerfectIdealGas('Air')\n\n# Air as semiperfect gas:\nsemiperfect_air = SemiperfectIdealGas('Air')",
"_____no_output_____"
]
],
[
[
"---\n##### To retrieve the thermodynamic properties you can `print` the `thermo_prop` from the gas:\n\nIncluding:\n- Chemical formula\n- Heat of formation\n- Molecular mass\n- cp coefficients",
"_____no_output_____"
]
],
[
[
"print(perfect_air.thermo_prop)",
"Species: Air\tMg=28.9651784 g/mol\tdeltaHf_ref=-125.53 J/mol\tdeltaHf_0K=8649.26 J/mol\n-->Chemical formula: {'N': 1.56, 'O': 0.42, 'AR': 0.01, 'C': 0.0}\n-->Tinterval: [200.0:1000.0] K\n Coefficients: order -2 | order -1 | order 0 | order 1 | order 2 | order 3 | order 4\n 1.010e+04 -1.968e+02 5.009e+00 -5.761e-03 1.067e-05 -7.940e-09 2.185e-12\n\n-->Tinterval: [1000.0:6000.0] K\n Coefficients: order -2 | order -1 | order 0 | order 1 | order 2 | order 3 | order 4\n 2.415e+05 -1.258e+03 5.145e+00 -2.139e-04 7.065e-08 -1.071e-11 6.578e-16\n\n\n"
]
],
[
[
"---\nYou can get the thermodynamic properties directly from the gas object. Note that all units are International System of Units (SI):",
"_____no_output_____"
]
],
[
[
"print(perfect_air.Rg)\nprint(perfect_air.Mg)\nprint(perfect_air.cp())\nprint(perfect_air.cp_molar())\nprint(perfect_air.cv())\nprint(perfect_air.cv_molar())\nprint(perfect_air.gamma())",
"287.0502816634901\n28.9651784\n1004.7188747023865\n29.10186144760187\n717.6685930388965\n20.78739882944863\n1.3999760954398244\n"
]
],
[
[
"---\n##### Use the docstrings for more info about the content of a PerfectIdealGas or a SemiperfectIdealGas:\n\n",
"_____no_output_____"
]
],
[
[
"perfect_air?",
"_____no_output_____"
]
],
[
[
"---\n##### Compare both models:\n\nNote that *Perfect Ideal Air*, with constant $c_p$, $c_v$ and $\\gamma$, yields the same properties than a semiperfect gas model at 25ºC (reference temperature):",
"_____no_output_____"
]
],
[
[
"T = 288.15 #K\ncp_perf = perfect_air.cp()\ncp_sp = semiperfect_air.cp(T)\n\nprint('At T={0:8.2f}K, cp_perfect={1:8.2f}J/kg/K'.format(T, cp_perf))\nprint('At T={0:8.2f}K, cp_semipft={1:8.2f}J/kg/K'.format(T, cp_sp))\n\nT = 1500 #K\ncp_perf = perfect_air.cp()\ncp_sp = semiperfect_air.cp(T)\n\nprint('At T={0:8.2f}K, cp_perfect={1:8.2f}J/kg/K'.format(T, cp_perf))\nprint('At T={0:8.2f}K, cp_semipft={1:8.2f}J/kg/K'.format(T, cp_sp))",
"At T= 288.15K, cp_perfect= 1004.72J/kg/K\nAt T= 288.15K, cp_semipft= 1004.27J/kg/K\nAt T= 1500.00K, cp_perfect= 1004.72J/kg/K\nAt T= 1500.00K, cp_semipft= 1210.97J/kg/K\n"
]
],
[
[
"---\n##### $c_p$, $c_v$ and $\\gamma$ versus temperature:",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom matplotlib import pyplot as plt",
"_____no_output_____"
],
[
"T = np.linspace(200, 2000, 50)\ncp = np.zeros_like(T)\ncv = np.zeros_like(T)\ngamma = np.zeros_like(T)\n\nfor ii, temperature in enumerate(T):\n cp[ii] = semiperfect_air.cp(temperature)\n cv[ii] = semiperfect_air.cv(temperature)\n gamma[ii] = semiperfect_air.gamma(temperature)\n \nfig, (ax1, ax2) = plt.subplots(2)\nfig.suptitle('Air properties')\nax1.plot(T, cp)\nax1.plot(T, cv)\nax2.plot(T, gamma)\n\nax1.set(xlabel=\"Temperature [K]\", ylabel=\"cp, cv [J/kg/K]\")\nax2.set(xlabel=\"Temperature [K]\", ylabel=\"gamma [-]\")\nax1.grid()\nax2.grid()\nplt.show()\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a381d8f06bdecc2e1328126a4559360f081b7d9
| 224,636 |
ipynb
|
Jupyter Notebook
|
part2/lab7/QandA_SQuAD.ipynb
|
yasheshshroff/ODSC2021_NLP_PyTorch
|
359a9df1a97dff00eaeaa354f07df82e70ac23a2
|
[
"MIT"
] | 4 |
2020-10-28T22:54:10.000Z
|
2020-11-06T21:17:18.000Z
|
part2/lab7/QandA_SQuAD.ipynb
|
yasheshshroff/ODSC2021_NLP_PyTorch
|
359a9df1a97dff00eaeaa354f07df82e70ac23a2
|
[
"MIT"
] | null | null | null |
part2/lab7/QandA_SQuAD.ipynb
|
yasheshshroff/ODSC2021_NLP_PyTorch
|
359a9df1a97dff00eaeaa354f07df82e70ac23a2
|
[
"MIT"
] | 15 |
2021-03-12T19:57:47.000Z
|
2021-11-18T19:45:29.000Z
| 111.648111 | 163,784 | 0.863192 |
[
[
[
"### Required dependencies\n\n***Datasets***: Lightweight and extensible library to easily share and access datasets and evaluation metrics for Natural Language Processing (NLP) and more.\n\n**Transformers**: provides thousands of pretrained models to perform tasks on texts such as classification, information extraction, question answering, summarization, translation, text generation, etc in 100+ languages. Its aim is to make cutting-edge NLP easier to use for everyone.\n\nSource:\n\nhttps://pypi.org/project/transformers/\n\nhttps://github.com/huggingface/datasets\n",
"_____no_output_____"
]
],
[
[
"!wget https://github.com/ravi-ilango/aicamp-mar-2021/blob/main/lab7/Archive.zip?raw=true -O Archive.zip\n\n!unzip Archive.zip",
"_____no_output_____"
],
[
"!pip install datasets\n!pip install transformers\n!pip install wikipedia\n",
"_____no_output_____"
],
[
"from transformers import AutoTokenizer, AutoModelForQuestionAnswering, BertForQuestionAnswering, BertTokenizer, pipeline\nimport torch",
"_____no_output_____"
]
],
[
[
"# **Overview of bert-base-uncased**\n\nPretrained model on English language using a masked language modeling (MLM) objective. This model is uncased: it does not make a difference between english and English.\n\nThe BERT model was pretrained on BookCorpus, a dataset consisting of 11,038 unpublished books and English Wikipedia (excluding lists, tables and headers).\n(https://huggingface.co/bert-base-uncased)\n\n\n---\n\n\n**The masked language model (MLM) objective:**\n\n“The masked language model randomly masks some of the tokens from the input, and the objective is to predict the original vocabulary id of the masked word based only on its context. Unlike left-to-right language model pre-training, the MLM objective allows the representation to fuse the left and the right context, which allows us to pre-train a deep bidirectional Transformer.”\n\nQuote from the paper (https://arxiv.org/abs/1810.04805)\n",
"_____no_output_____"
],
[
"\n\n (https://arxiv.org/abs/1810.04805)",
"_____no_output_____"
],
[
"# **SQuAD**\n\n**Stanford Question Answering Dataset** (SQuAD) is a reading comprehension dataset, consisting of questions posed by crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span, from the corresponding reading passage, or the question might be unanswerable.\n\nEach Question and answer is accompanied by the context. The context is used to determine an answer to the question.\n\n**SQuAD2.0** combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions written adversarially by crowdworkers to look similar to answerable ones\n\n\n\n\nsource: https://rajpurkar.github.io/SQuAD-explorer/\n",
"_____no_output_____"
],
[
"## **Training bert-base-uncased with SQuAD.**\n\nThe bert-base-uncased model was trained with an MLM objective. We will be using this pre-trained model to handle questions answering. We will be using the Stanford Question Answering Dataset (SQuAD) for training our model.\n\nSource: https://github.com/huggingface/transformers/tree/master/examples/question-answering",
"_____no_output_____"
]
],
[
[
"# Training took ~6 hours. Latest checkpoint is ~1.5gb.\n\n\"\"\"\nOUTPUT_DIR = \"./checkpoint\"\n\n!python ./run_qa.py \\\n --model_name_or_path bert-base-uncased \\\n --dataset_name squad \\\n --do_train \\\n --do_eval \\\n --per_device_train_batch_size 12 \\\n --learning_rate 3e-5 \\\n --num_train_epochs 2 \\\n --max_seq_length 384 \\\n --doc_stride 128 \\\n --output_dir OUTPUT_DIR\n\n\"\"\"\n\n#Note: you may run out of disk space, so delete the old checkpoint files regularly.",
"_____no_output_____"
]
],
[
[
"## Training Results\n\nTraining took roughly 5-6 hours to complete. Below you can access the checkpoint from which you can test the model yourself.\n\n\nExercise: Change the context and come up with your own questions. ",
"_____no_output_____"
]
],
[
[
"# # Load the model\n# model = BertForQuestionAnswering.from_pretrained('./checkpoint-14500/')\n# tokenizer = BertTokenizer.from_pretrained(\"./checkpoint-14500/\", return_token_type_ids = True)\n\n# #Setup nlp pipeline to use the model\n# nlp = pipeline('question-answering', model=model, tokenizer=tokenizer)\n",
"_____no_output_____"
],
[
"# Let us load the pretrained model\n\nmodel = BertForQuestionAnswering.from_pretrained(\"bert-large-uncased-whole-word-masking-finetuned-squad\")\n\ntokenizer = BertTokenizer.from_pretrained(\"bert-large-uncased-whole-word-masking-finetuned-squad\", return_token_type_ids = True)\n\n#Setup nlp pipeline to use the model\nnlp = pipeline(\"question-answering\", model=model, tokenizer=tokenizer)\n",
"_____no_output_____"
],
[
"questions = [\n \"Who is the president of USA?\",\n \"What is the temperature today?\",\n \"What is the temperature of airpod today?\",\n \"What is Airpod Max?\",\n \"What are Airpods?\",\n \"Who developed airpods?\",\n \"What chip does the airpod use?\",\n \"When was the airpods first released?\",\n \"When was the 2nd generation airpods released?\",\n \"What are the features of the 2nd generation airpods?\",\n \"How many airpods were sold in 2017?\",\n \"How many airpods were sold in 2018?\",\n \"How many airpods were sold in 2019?\",\n \"Which year did Apple sell 60 million airpods?\",\n \"How big is airpod's marketshare?\",\n \"How much of Airpod's revenues comes from replacements?\"\n]",
"_____no_output_____"
],
[
"context=\"\"\"AirPods are wireless Bluetooth earbuds created by Apple. They were first released on December 13, 2016, with a \n 2nd generation released in March 2019. They are Apple's entry-level wireless headphones, sold alongside AirPods \n Pro, higher-end wireless earbuds, and AirPods Max, wireless over-ear headphones. Within two years, they became \n Apple's most popular accessory, turning into a critical success and viral sensation.\n \n In addition to playing audio, AirPods feature a built-in microphone that filters out background noise, which \n allows phone calls and talking to Apple's digital assistant, Siri. Additionally, built-in accelerometers and \n optical sensors can detect taps (e.g. double-tap to pause audio) and in-ear placement, which enables automatic \n pausing when they are taken out of the ears.\n\n On March 20, 2019, Apple released the 2nd generation AirPods, which feature the H1 chip, longer talk time, and \n hands-free \"Hey Siri\" support. An optional wireless charging case was added in the offerings.\n\n Analysts estimate Apple sold between 14 million and 16 million AirPods in 2017. In 2018, AirPods were \n Apple's most popular accessory product, with 35 million units sold. 60 million units were sold in \n 2019.[39] Analysts estimate AirPods make up 60% of the global wireless headphone market and that Apple’s \n entire Wearables products (Apple Watch, AirPods, and AirPods Pro) “is now bigger than 60% of the companies \n in the Fortune 500”. An estimated 5-7% of Apple's revenue from AirPods comes from replacement \n earbuds and cases.\n \"\"\"",
"_____no_output_____"
],
[
"# results = wiki.search(question)\n# page = wiki.page(results[0])\n# context = ' '.join(page.content.split())\n\n# print(f\"Context: {context}\")",
"_____no_output_____"
],
[
"for question in questions:\n print(f\"Question: {question}\")\n print(f\"Answer (Bert): {nlp(question=question, context=context)}\\n\")\n print()",
"_____no_output_____"
]
],
[
[
"### Exercise: \nSet a threshold for filtering out anwers for irrelevant questions (and ofcourse incorrect answers)",
"_____no_output_____"
],
[
"### Exercise: \nCheckout the squad dataset",
"_____no_output_____"
]
],
[
[
"from datasets import load_dataset\n\ndataset = load_dataset(\"squad\")\n",
"_____no_output_____"
],
[
"dataset['validation'][105]",
"_____no_output_____"
],
[
"# Load the model from https://huggingface.co/models\nPRETRAINED_MODEL = 'deepset/roberta-base-squad2'\n\nmodel = AutoModelForQuestionAnswering.from_pretrained(PRETRAINED_MODEL)\ntokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL, return_token_type_ids = True)\n\n#Setup nlp pipeline to use the model\nnlp = pipeline('question-answering', model=model, tokenizer=tokenizer)\n",
"_____no_output_____"
]
],
[
[
"### Exercise: \n\nUse the above 'question-answering' pipeline (which uses Roberta model), set the threshold for the same questions and compare with the BERT model.",
"_____no_output_____"
],
[
"### Exercise: \nUse a different pretrained model from https://huggingface.co/models\n\nhint: distilbert-base-uncased-distilled-squad",
"_____no_output_____"
],
[
"### Exercise (future experiment): \n\nFinetune BertForQuestionAnswering model with data specific to your domain. You have to create the training dataset in SQuAD format.\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
4a3822d462c54722ef9f026c8669a955faa12a0f
| 3,043 |
ipynb
|
Jupyter Notebook
|
test_coord_transform.ipynb
|
csherwood-usgs/DUNEX
|
995ae6336adadffb3cb6bd7a66b95ae8cd4ffd16
|
[
"CC0-1.0"
] | null | null | null |
test_coord_transform.ipynb
|
csherwood-usgs/DUNEX
|
995ae6336adadffb3cb6bd7a66b95ae8cd4ffd16
|
[
"CC0-1.0"
] | null | null | null |
test_coord_transform.ipynb
|
csherwood-usgs/DUNEX
|
995ae6336adadffb3cb6bd7a66b95ae8cd4ffd16
|
[
"CC0-1.0"
] | 1 |
2021-09-02T00:30:14.000Z
|
2021-09-02T00:30:14.000Z
| 31.371134 | 232 | 0.583635 |
[
[
[
"from pyproj import Proj, transform, Transformer, CRS\n\nutmx = 456534.\nutmy = 3948028.\n\n# old way - generates deprecation warnings\nwgs84 = Proj('epsg:4326')\nutm18 = Proj('epsg:26918')\nncsp = CRS.from_proj4('+proj=lcc +lat_1=34.33333333333334 +lat_2=36.16666666666666 +lat_0=33.75 +lon_0=-79 +x_0=609601.22 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs') \n\nlat,lon=transform(utm18, wgs84, utmx, utmy)\nncx,ncy=transform(utm18, ncsp, utmx, utmy)\n\nprint(\"Lon / Lat : \",lon,lat)\nprint(\"NC x / NC y: \",ncx,ncy)",
"Lon / Lat : -75.48030601667956 35.67517248557048\nNC x / NC y: 928147.244959051 219209.98329007678\n"
],
[
"# new way (seems clunkier)\nncsp = CRS.from_proj4('+proj=lcc +lat_1=34.33333333333334 +lat_2=36.16666666666666 +lat_0=33.75 +lon_0=-79 +x_0=609601.22 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs') \n\nutm18_to_wgs84 = Transformer.from_crs('epsg:26918','epsg:4326')\nutm18_to_ncsp = Transformer.from_crs('epsg:26918', ncsp)\nlat,lon=utm18_to_wgs84.transform(utmx,utmy)\nncx,ncy=utm18_to_ncsp.transform(utmx, utmy)\n\nprint(\"Lon / Lat : \",lon,lat)\nprint(\"NC x / NC y: \",ncx,ncy)",
"Lon / Lat : -75.48030601667956 35.67517248557048\nNC x / NC y: 928147.244959051 219209.98329007678\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
4a38234cebbe0cc42f0c0ba5f37879f84624a7e6
| 23,330 |
ipynb
|
Jupyter Notebook
|
docs/examples/animation_options.ipynb
|
csaladenes/ipyvizzu
|
80a33d9ea4415cd378cc7b9004d840d335ed620a
|
[
"Apache-2.0"
] | null | null | null |
docs/examples/animation_options.ipynb
|
csaladenes/ipyvizzu
|
80a33d9ea4415cd378cc7b9004d840d335ed620a
|
[
"Apache-2.0"
] | null | null | null |
docs/examples/animation_options.ipynb
|
csaladenes/ipyvizzu
|
80a33d9ea4415cd378cc7b9004d840d335ed620a
|
[
"Apache-2.0"
] | null | null | null | 37.387821 | 344 | 0.517017 |
[
[
[
"## Animation options\n\nIn Vizzu you can set the timing and duration of the animation. You can do this either for the whole animation, or for animation groups such as the elements moving along the x-axis or the y-axis, appearing or disappearing or when the coordinate system is changed.\n\nLet’s see first a simple example when a stacked column chart is grouped using the default animation options.",
"_____no_output_____"
]
],
[
[
"from ipyvizzu import Chart, Data, Config\n\nchart = Chart()\n\ndata = Data.from_json(\"../data/music_example_data.json\")\n\nchart.animate(data)\n\nchart.animate(Config({\n \"channels\": {\n \"y\": {\n \"set\": [\"Popularity\", \"Types\"]\n }, \n \"x\": {\n \"set\": \"Genres\"\n }\n }, \n \"label\": {\n \"attach\": \"Popularity\"\n },\n \"color\": {\n \"set\": \"Types\"\n },\n \"title\": \"Default options - step 1\"\n}))\n\nchart.animate(Config({\n \"channels\": {\n \"y\": {\n \"detach\": \"Types\"\n }, \n \"x\": {\n \"attach\": \"Types\"\n }\n }\n}))\n\nsnapshot1 = chart.store()",
"_____no_output_____"
]
],
[
[
"We stack the columns, still with the default options.",
"_____no_output_____"
]
],
[
[
"chart.animate(snapshot1)\n\nchart.animate(Config({\"title\": \"Default options - step 2\"}))\n\nchart.animate(Config({\n \"channels\": {\n \"x\": {\n \"detach\": \"Types\"\n }, \n \"y\": {\n \"attach\": \"Types\"\n }\n }\n}))\n\nsnapshot2 = chart.store()",
"_____no_output_____"
]
],
[
[
"Now we change the animation settings for the elements moving along the y-axis and also the change in styles, more specifically when the labels on the markers move from the center of the chart elements to the top of them.",
"_____no_output_____"
]
],
[
[
"chart.animate(snapshot2)\n\nchart.animate(Config({\"title\": \"Custom animation settings for specific groups\"}))\n\nchart.animate(\n Config({\n \"channels\": {\n \"y\": {\n \"detach\": \"Types\"\n }, \n \"x\": {\n \"attach\": \"Types\"\n }\n }\n }),\n y={\n \"duration\": 2,\n \"delay\": 2\n },\n style={\n \"duration\": 2,\n \"delay\": 4\n }\n)\n\nsnapshot3 = chart.store()",
"_____no_output_____"
]
],
[
[
"This is an example of changing the settings for the whole animation at once.",
"_____no_output_____"
]
],
[
[
"chart.animate(snapshot3)\n\nchart.animate(Config({\"title\": \"Custom options for the whole animation\"}))\n\nchart.animate(\n Config({\n \"channels\": {\n \"x\": {\n \"detach\": \"Types\"\n }, \n \"y\": {\n \"attach\": \"Types\"\n }\n }\n }),\n duration=1,\n easing=\"linear\"\n)\n\nsnapshot4 = chart.store()",
"_____no_output_____"
]
],
[
[
"When the two settings are combined, Vizzu will use the general animation options and spread the unique settings for specific groups proportionally. This is why you can see the same animation as two steps before but happening much quicker since the duration of the whole animation is set to 1 second.",
"_____no_output_____"
]
],
[
[
"chart.animate(snapshot4)\n\nchart.animate(Config({\"title\": \"Custom settings for both\"}))\n\nchart.animate(\n Config({\n \"channels\": {\n \"y\": {\n \"detach\": \"Types\"\n }, \n \"x\": {\n \"attach\": \"Types\"\n }\n }\n }),\n duration=1,\n easing=\"linear\",\n y={\n \"duration\": 2,\n \"delay\": 2\n },\n style={\n \"duration\": 2,\n \"delay\": 4\n }\n)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a382dcbe25b97b9f6f502cab6a1564d91b5e8e0
| 255,853 |
ipynb
|
Jupyter Notebook
|
Application_Spot_France.ipynb
|
mzaffran/AdaptiveConformalPredictionsTimeSeries
|
131656fe4c25251bad745f52db3c2d7cb1c24bbb
|
[
"MIT"
] | 1 |
2022-02-20T19:28:18.000Z
|
2022-02-20T19:28:18.000Z
|
Application_Spot_France.ipynb
|
mzaffran/AdaptiveConformalPredictionsTimeSeries
|
131656fe4c25251bad745f52db3c2d7cb1c24bbb
|
[
"MIT"
] | null | null | null |
Application_Spot_France.ipynb
|
mzaffran/AdaptiveConformalPredictionsTimeSeries
|
131656fe4c25251bad745f52db3c2d7cb1c24bbb
|
[
"MIT"
] | 2 |
2022-03-01T23:13:47.000Z
|
2022-03-07T08:17:25.000Z
| 297.157956 | 59,764 | 0.91263 |
[
[
[
"# General parameters",
"_____no_output_____"
]
],
[
[
"import files\nimport utils\nimport os\nimport models\nimport numpy as np\nfrom tqdm.autonotebook import tqdm\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\nimport datetime\nimport seaborn as sns",
"/Users/mzaffran/Documents/Code/CP/cp-epf-clean/models.py:5: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n from tqdm.autonotebook import tqdm\n"
],
[
"import matplotlib as mpl\nfrom matplotlib.backends.backend_pgf import FigureCanvasPgf\nmpl.backend_bases.register_backend('pdf', FigureCanvasPgf)\nfrom mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset,inset_axes\n\nsize=19\nmpl.rcParams.update({\n \"pgf.texsystem\": \"pdflatex\",\n 'font.family': 'serif',\n 'font.serif': 'Times',\n 'text.usetex': True,\n 'pgf.rcfonts': False,\n 'font.size': size,\n 'axes.labelsize':size,\n 'axes.titlesize':size,\n 'figure.titlesize':size,\n 'xtick.labelsize':size,\n 'ytick.labelsize':size,\n 'legend.fontsize':size,\n})\n\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as mlines",
"_____no_output_____"
],
[
"#########################################################\n# Global random forests parameters\n#########################################################\n\n# the number of trees in the forest\nn_estimators = 1000\n\n# the minimum number of samples required to be at a leaf node\n# (default skgarden's parameter)\nmin_samples_leaf = 1\n\n# the number of features to consider when looking for the best split\n# (default skgarden's parameter)\nmax_features = 6\n\nparams_basemodel = {'n_estimators':n_estimators, 'min_samples_leaf':min_samples_leaf, 'max_features':max_features,\n 'cores':1}",
"_____no_output_____"
]
],
[
[
"# Data import",
"_____no_output_____"
]
],
[
[
"# load the dataset\n\ndata = pd.read_csv(\"data_prices/Prices_2016_2019_extract.csv\")",
"_____no_output_____"
],
[
"data.shape\n# the first week (24*7 rows) has been removed because of the lagged variables.",
"_____no_output_____"
],
[
"date_plot = pd.to_datetime(data.Date)\n\nplt_1 = plt.figure(figsize=(10, 5))\nplt.plot(date_plot, data.Spot, color='black', linewidth=0.6)\nlocs, labels = plt.xticks()\nplt.xticks(locs[0:len(locs):2], labels=['2016','2017','2018','2019','2020'])\nplt.xlabel('Date')\nplt.ylabel('Spot price (\\u20AC/MWh)')\nplt.show()",
"_____no_output_____"
],
[
"limit = datetime.datetime(2019, 1, 1, tzinfo=datetime.timezone.utc)\nid_train = data.index[pd.to_datetime(data['Date'], utc=True) < limit].tolist()\ndata_train = data.iloc[id_train,:]\nsub_data_train = data_train.loc[:,['hour','dow_0','dow_1','dow_2','dow_3','dow_4','dow_5','dow_6'] + \n ['lag_24_%d'%i for i in range(24)] +\n ['lag_168_%d'%i for i in range(24)] + ['conso']]\nall_x_train = [np.array(sub_data_train.loc[sub_data_train.hour == h]) for h in range(24)]\n\ntrain_size = all_x_train[0].shape[0]",
"_____no_output_____"
],
[
"sub_data = data.loc[:,['hour','dow_0','dow_1','dow_2','dow_3','dow_4','dow_5','dow_6'] + \n ['lag_24_%d'%i for i in range(24)] +\n ['lag_168_%d'%i for i in range(24)] + ['conso']]\nall_x = [np.array(sub_data.loc[sub_data.hour == h]) for h in range(24)]\n\nall_y = [np.array(data.loc[data.hour == h, 'Spot']) for h in range(24)]",
"_____no_output_____"
],
[
"all_x_train[0].shape",
"_____no_output_____"
]
],
[
[
"# CP methods",
"_____no_output_____"
]
],
[
[
"alpha = 0.1",
"_____no_output_____"
],
[
"for h in tqdm(range(24)):\n \n X = all_x[h]\n Y = all_y[h]\n\n data_dict = {'X': np.transpose(X), 'Y': Y}\n\n dataset = 'Spot_France_Hour_'+str(h)+'_train_'+str(limit)[:10]\n\n methods = ['CP', 'EnbPI']\n \n params_methods = {'B': 30}\n\n results, methods_ran = models.run_experiments_real_data(data_dict, alpha, methods, params_methods, 'RF', params_basemodel,\n train_size, dataset, erase=False)\n\n for method in methods_ran:\n name_dir, name_method = files.get_name_results(method, dataset=dataset)\n results_method = results[method]\n files.write_file('results/'+name_dir, name_method, 'pkl', results_method)\n \n # Mean EnbPI\n \n params_methods = {'B': 30, 'mean': True}\n\n results, methods_ran = models.run_experiments_real_data(data_dict, alpha, methods, params_methods, 'RF', params_basemodel,\n train_size, dataset, erase=False)\n\n for method in methods_ran:\n name_dir, name_method = files.get_name_results(method, dataset=dataset)\n results_method = results[method]\n files.write_file('results/'+name_dir, name_method, 'pkl', results_method)\n \n # Offline\n \n methods = ['CP']\n params_methods = {'online': False}\n\n results, methods_ran = models.run_experiments_real_data(data_dict, alpha, methods, params_methods, 'RF', params_basemodel,\n train_size, dataset, erase=False)\n\n for method in methods_ran:\n name_dir, name_method = files.get_name_results(method, online=False, dataset=dataset)\n results_method = results[method]\n files.write_file('results/'+name_dir, name_method, 'pkl', results_method)",
"_____no_output_____"
],
[
"tab_gamma = [0,\n 0.000005,\n 0.00005,\n 0.0001,0.0002,0.0003,0.0004,0.0005,0.0006,0.0007,0.0008,0.0009,\n 0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,\n 0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09]\n\nfor h in tqdm(range(24)):\n \n X = all_x[h]\n Y = all_y[h]\n\n data_dict = {'X': np.transpose(X), 'Y': Y}\n\n dataset = 'Spot_France_Hour_'+str(h)+'_train_'+str(limit)[:10]\n\n \n results, methods_ran = models.run_multiple_gamma_ACP_real_data(data_dict, alpha, tab_gamma, 'RF', \n params_basemodel, train_size, dataset,\n erase=False)\n \n online = True\n for method in methods_ran:\n name_dir, name_method = files.get_name_results(method, dataset=dataset)\n results_method = results[method]\n files.write_file('results/'+name_dir, name_method, 'pkl', results_method)",
"_____no_output_____"
]
],
[
[
"## Results concatenated",
"_____no_output_____"
],
[
"Be careful that the aggregation algorithm (AgACI) must be run in R separately from this notebook before running the following cells (if you use a new data set or if you erased the supplied results).",
"_____no_output_____"
]
],
[
[
"id_test = data.index[pd.to_datetime(data['Date'], utc=True) >= limit].tolist()\n\ndata_test = data.iloc[id_test,:]",
"_____no_output_____"
],
[
"methods = ['CP','EnbPI','EnbPI_Mean']+['ACP_'+str(gamma) for gamma in tab_gamma]+['Aggregation_EWA_Gradient','Aggregation_EWA',\n 'Aggregation_MLpol_Gradient','Aggregation_MLpol',\n 'Aggregation_BOA_Gradient','Aggregation_BOA']",
"_____no_output_____"
],
[
"for method in methods:\n \n y_upper = [None]*data_test.shape[0]\n y_lower = [None]*data_test.shape[0]\n\n for i in range(24):\n dataset = 'Spot_France_Hour_'+str(i)+'_train_'+str(limit)[:10]\n\n name_dir, name_method = files.get_name_results(method, dataset=dataset)\n results = files.load_file('results/'+name_dir, name_method, 'pkl')\n\n y_upper[i::24] = list(results['Y_sup'].reshape(1,-1)[0])\n y_lower[i::24] = list(results['Y_inf'].reshape(1,-1)[0])\n\n y_upper = np.array(y_upper)\n y_lower = np.array(y_lower)\n\n results_method = {'Y_inf': y_lower, 'Y_sup':y_upper}\n dataset = 'Spot_France_ByHour_train_'+str(limit)[:10]\n name_dir, name_method = files.get_name_results(method, dataset=dataset)\n if not os.path.isdir('results/'+name_dir):\n os.mkdir('results/'+name_dir)\n files.write_file('results/'+name_dir, name_method, 'pkl', results_method)\n \n if method == 'CP':\n y_upper = [None]*data_test.shape[0]\n y_lower = [None]*data_test.shape[0]\n\n for i in range(24):\n dataset = 'Spot_France_Hour_'+str(i)+'_train_'+str(limit)[:10]\n\n name_dir, name_method = files.get_name_results(method, online=False, dataset=dataset)\n results = files.load_file('results/'+name_dir, name_method, 'pkl')\n\n y_upper[i::24] = list(results['Y_sup'].reshape(1,-1)[0])\n y_lower[i::24] = list(results['Y_inf'].reshape(1,-1)[0])\n\n y_upper = np.array(y_upper)\n y_lower = np.array(y_lower)\n\n results_method = {'Y_inf': y_lower, 'Y_sup':y_upper}\n dataset = 'Spot_France_ByHour_train_'+str(limit)[:10]\n name_dir, name_method = files.get_name_results(method, online=False, dataset=dataset)\n if not os.path.isdir('results/'+name_dir):\n os.mkdir('results/'+name_dir)\n files.write_file('results/'+name_dir, name_method, 'pkl', results_method)",
"_____no_output_____"
],
[
"dataset = 'Spot_France_ByHour_train_'+str(limit)[:10]\n\nY = data_test['Spot'].values",
"_____no_output_____"
]
],
[
[
"### Visualisation",
"_____no_output_____"
]
],
[
[
"colors_blindness = sns.color_palette(\"colorblind\")",
"_____no_output_____"
],
[
"method = 'Aggregation_BOA_Gradient'\nname_dir, name_method = files.get_name_results(method, dataset=dataset)\nresults = files.load_file('results/'+name_dir, name_method, 'pkl')\ncontains = (Y <= results['Y_sup']) & (Y >= results['Y_inf'])\nlengths = results['Y_sup'] - results['Y_inf']\ny_pred = (results['Y_sup'] + results['Y_inf'])/2",
"_____no_output_____"
],
[
"d = 20",
"_____no_output_____"
],
[
"plt.plot(pd.to_datetime(data_test['Date'])[24*d:(24*(d+4)+1)],data_test['Spot'][24*d:(24*(d+4)+1)], color='black', \n label='Observed price')\nplt.plot(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],data_test['Spot'][24*(d+4):24*(d+5)],\n color='black',alpha=.5)\nplt.plot(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],y_pred[24*(d+4):24*(d+5)],'--',\n color=(230/255,120/255,20/255), label='Predicted price')\nplt.ylabel(\"Spot price (€/MWh)\")\nplt.xticks(rotation=45)\nplt.legend()\n#plt.savefig('plots/prices/spot_last.png', bbox_inches='tight',dpi=300)\nplt.show()",
"_____no_output_____"
],
[
"plt.plot(pd.to_datetime(data_test['Date'])[24*d:(24*(d+4)+1)],data_test['Spot'][24*d:(24*(d+4)+1)], color='black',\n label='Observed price')\nplt.plot(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],data_test['Spot'][24*(d+4):24*(d+5)],\n color='black', alpha=.5)\nplt.plot(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],results['Y_sup'][24*(d+4):24*(d+5)],\n color=colors_blindness[9])\nplt.plot(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],results['Y_inf'][24*(d+4):24*(d+5)],\n color=colors_blindness[9])\nplt.fill_between(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],results['Y_sup'][24*(d+4):24*(d+5)], \n results['Y_inf'][24*(d+4):24*(d+5)], \n alpha=.3, fc=colors_blindness[9], ec='None', label='Predicted interval')\nplt.plot(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],y_pred[24*(d+4):24*(d+5)],'--',\n color=colors_blindness[1], label='Predicted price')\nplt.ylabel(\"Spot price (€/MWh)\")\nplt.xticks(rotation=45)\nplt.legend()\n#plt.savefig('plots/prices/ex_int_'+method+'.pdf', bbox_inches='tight',dpi=300)\nplt.show()",
"_____no_output_____"
],
[
"date_plot = pd.to_datetime(data.Date)\n\n\nfig,ax = plt.subplots(1,1,figsize=(10, 5))\n\naxins = inset_axes(ax,4.3,2.1,loc='upper right')\n\n\nax.plot(date_plot, data.Spot, color='black', linewidth=0.6)\nlocs = ax.get_xticks()\nax.set_xticks(locs[0:len(locs):2])\nax.set_xticklabels(['2016','2017','2018','2019','2020'])\nax.set_xlabel('Date')\nax.set_ylabel('Spot price (\\u20AC/MWh)')\n\naxins.plot(pd.to_datetime(data_test['Date'])[24*d:(24*(d+4)+1)],data_test['Spot'][24*d:(24*(d+4)+1)], color='black',\n label='Observed price')\naxins.plot(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],data_test['Spot'][24*(d+4):24*(d+5)],\n color='black', alpha=.5)\naxins.plot(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],results['Y_sup'][24*(d+4):24*(d+5)],\n color=colors_blindness[9])\naxins.plot(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],results['Y_inf'][24*(d+4):24*(d+5)],\n color=colors_blindness[9])\naxins.fill_between(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],results['Y_sup'][24*(d+4):24*(d+5)], \n results['Y_inf'][24*(d+4):24*(d+5)], \n alpha=.3, fc=colors_blindness[9], ec='None', label='Predicted interval')\naxins.plot(pd.to_datetime(data_test['Date'])[24*(d+4):24*(d+5)],y_pred[24*(d+4):24*(d+5)],'--',\n color=colors_blindness[1], label='Predicted price')\naxins.legend(prop={'size': 14})\n\naxins.set_yticks([50,75,100,125])\naxins.set_yticklabels([50,75,100,125])\nlocs = axins.get_xticks()\naxins.set_xticks(locs[:len(locs)-1])\naxins.set_xticklabels(['21/01','22/01','23/01','24/01','25/01'])\naxins.tick_params(axis='x', rotation=20)\nmark_inset(ax, axins, loc1=3, loc2=4, fc=\"none\", ec=\"0.7\")\n\n#plt.savefig('plots/prices/spot_and_ex_int_'+method+'.pdf', bbox_inches='tight',dpi=300)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Marginal validity and efficiency comparison",
"_____no_output_____"
]
],
[
[
"lines = False\nadd_offline = True\n\nmethods = ['CP', 'EnbPI_Mean', 'ACP_0','ACP_0.01', 'ACP_0.05', 'Aggregation_BOA_Gradient']\nmarker_size = 80\nfig, (ax1) = plt.subplots(1, 1, figsize=(10,5), sharex=True, sharey=True)\nmarkers = {'Gaussian': \"o\", 'CP': \"s\", 'ACP':'D','ACP_0.05':'D', 'ACP_0.01': \"d\", 'ACP_0': \"^\", 'Aggregation_BOA_Gradient':'*',\n 'QR': \"v\", 'CQR': \"D\", 'CQR_CV': \"d\", 'EnbPI': 'x','EnbPI_Mean': '+'}\nmethods_display = {'Gaussian': 'Gaussian', 'CP': 'OSSCP', # (adapted from Lei et al., 2018)\n 'EnbPI': 'EnbPI (Xu \\& Xie, 2021)','EnbPI_Mean': 'EnbPI V2',\n 'ACP': 'ACI '+r'$\\gamma = 0.05$',#(Gibbs \\& Candès, 2021)\n 'ACP_0.05': 'ACI '+r'$\\gamma = 0.05$',#(Gibbs \\& Candès, 2021)\n 'ACP_0.01': 'ACI '+r'$\\gamma = 0.01$',# (Gibbs \\& Candès, 2021), \n 'ACP_0': 'ACI '+r'$\\gamma = 0$',# (Gibbs \\& Candès, 2021), \n 'Aggregation_BOA_Gradient':'AgACI'}\n\nfor method in methods:\n name_dir, name_method = files.get_name_results(method, dataset=dataset)\n results = files.load_file('results/'+name_dir, name_method, 'pkl')\n contains = (Y <= results['Y_sup']) & (Y >= results['Y_inf'])\n lengths = results['Y_sup'] - results['Y_inf']\n if method not in [\"ACP\",\"ACP_0.01\",\"ACP_QCP_0.05\",'EnbPI_Mean', 'Aggregation_BOA_Gradient']:\n ax1.scatter(np.mean(contains),np.median(lengths), \n marker=markers[method], color='black',s=marker_size)\n elif method in [\"ACP\",\"ACP_0.01\",\"ACP_QCP_0.05\"]:\n ax1.scatter(np.mean(contains),np.median(lengths), \n marker=markers[method], color='black',s=marker_size)\n elif method in ['EnbPI_Mean','Aggregation_BOA_Gradient']:\n ax1.scatter(np.mean(contains),np.median(lengths), \n marker=markers[method], color='black',s=marker_size+30)\n if add_offline and method in ['Gaussian','CP','CQR','CQR_CV']:\n name_dir, name_method = files.get_name_results(method, online=False, dataset=dataset)\n results = files.load_file('results/'+name_dir, name_method, 'pkl')\n contains = (Y <= results['Y_sup']) & (Y >= results['Y_inf'])\n lengths = results['Y_sup'] - results['Y_inf']\n ax1.scatter(np.mean(contains),np.median(lengths), \n marker=markers[method], color='black', facecolors='none',s=marker_size)\nax1.axvline(x=1-alpha, color='black', ls=':')\nax1.set_xlabel(\"Coverage\")\nax1.set_ylabel(\"Median length\")\n\n# Methods legend\n\nhandles = []\nnames = []\nnames_wo_offline = list( map(methods_display.get, methods) )\nif add_offline:\n names = np.append(names,names_wo_offline[0])\n names = np.append(names,names_wo_offline)\n names[1] = 'Offline SSCP'# (adapted from Lei et al., 2018)\nelse:\n names = names_wo_offlines\nfor marker in list( map(markers.get, methods) ):\n handles.append(mlines.Line2D([], [], color='black', marker=marker, linestyle='None'))\n if add_offline and marker == 's':\n handles.append(mlines.Line2D([], [], color='black', marker=marker, linestyle='None', markerfacecolor='none'))\n\nfig.legend(handles, names, bbox_to_anchor=(0,0.95,1,0.2), loc='upper center', ncol=3)\n\nif lines:\n name_plot = 'plots/prices/'+dataset+'_lines'\nelse:\n name_plot = 'plots/prices/'+dataset+'_median'\nif add_offline :\n name_plot = name_plot + '_offline'\n#plt.savefig(name_plot+'.pdf', bbox_inches='tight',dpi=300)\nplt.show()",
"_____no_output_____"
],
[
"lines = False\nadd_offline = True\n\nmethods = ['CP', 'EnbPI_Mean', 'ACP_0','ACP_0.01', 'ACP_0.05', 'Aggregation_BOA_Gradient']\nmarker_size = 80\nfig, (ax1) = plt.subplots(1, 1, figsize=(10,5), sharex=True, sharey=True)\nmarkers = {'Gaussian': \"o\", 'CP': \"s\", 'ACP':'D','ACP_0.05':'D', 'ACP_0.01': \"d\", 'ACP_0': \"^\", 'Aggregation_BOA_Gradient':'*',\n 'QR': \"v\", 'CQR': \"D\", 'CQR_CV': \"d\", 'EnbPI': 'x','EnbPI_Mean': '+'}\nmethods_display = {'Gaussian': 'Gaussian', 'CP': 'OSSCP', # (adapted from Lei et al., 2018)\n 'EnbPI': 'EnbPI (Xu \\& Xie, 2021)','EnbPI_Mean': 'EnbPI V2',\n 'ACP': 'ACI '+r'$\\gamma = 0.05$',#(Gibbs \\& Candès, 2021)\n 'ACP_0.05': 'ACI '+r'$\\gamma = 0.05$',#(Gibbs \\& Candès, 2021)\n 'ACP_0.01': 'ACI '+r'$\\gamma = 0.01$',# (Gibbs \\& Candès, 2021), \n 'ACP_0': 'ACI '+r'$\\gamma = 0$',# (Gibbs \\& Candès, 2021), \n 'Aggregation_BOA_Gradient':'AgACI',\n 'ACP_QCP_0.05': 'ACI (Gibbs \\& Candès, 2021) with corrected quantile',\n 'QR': 'QR (Koenker \\& Bassett)', 'CQR': 'CQR (Romano et al., 2019)', \n 'CQR_CV': 'CQR with CV (Romano et al., 2019)'}\n\n# Get values for imputation\nname_dir, name_method = files.get_name_results('ACP_0', dataset=dataset)\nresults = files.load_file('results/'+name_dir, name_method, 'pkl')\nborne_sup = results['Y_sup']\nborne_inf = results['Y_inf']\ny_chap = (borne_sup+borne_inf)/2\nabs_res = np.abs(Y - y_chap)\nmax_eps = np.max(abs_res)\nval_max = y_chap+max_eps\nval_min = y_chap-max_eps\n\nfor method in methods:\n name_dir, name_method = files.get_name_results(method, dataset=dataset)\n results = files.load_file('results/'+name_dir, name_method, 'pkl')\n contains = (Y <= results['Y_sup']) & (Y >= results['Y_inf'])\n lengths = results['Y_sup']-results['Y_inf']\n if method[:3] in ['ACP','Agg']:\n borne_sup = results['Y_sup']\n borne_inf = results['Y_inf']\n borne_sup[np.isinf(borne_sup)] = val_max[np.isinf(borne_sup)]\n borne_inf[np.isinf(borne_inf)] = val_min[np.isinf(borne_inf)]\n borne_sup[borne_sup > val_max] = val_max[borne_sup > val_max]\n borne_inf[borne_inf < val_min] = val_min[borne_inf < val_min]\n lengths = borne_sup-borne_inf\n if method not in [\"ACP\",\"ACP_0.01\",\"ACP_QCP_0.05\",'EnbPI_Mean', 'Aggregation_BOA_Gradient']:\n ax1.scatter(np.mean(contains),np.mean(lengths), \n marker=markers[method], color='black',s=marker_size)\n elif method in [\"ACP\",\"ACP_0.01\",\"ACP_QCP_0.05\"]:\n ax1.scatter(np.mean(contains),np.mean(lengths), \n marker=markers[method], color='black',s=marker_size)\n elif method in ['EnbPI_Mean','Aggregation_BOA_Gradient']:\n ax1.scatter(np.mean(contains),np.mean(lengths), \n marker=markers[method], color='black',s=marker_size+30)\n if add_offline and method in ['Gaussian','CP','CQR','CQR_CV']:\n name_dir, name_method = files.get_name_results(method, online=False, dataset=dataset)\n results = files.load_file('results/'+name_dir, name_method, 'pkl')\n contains = (Y <= results['Y_sup']) & (Y >= results['Y_inf'])\n lengths = results['Y_sup'] - results['Y_inf']\n ax1.scatter(np.mean(contains),np.mean(lengths), \n marker=markers[method], color='black', facecolors='none',s=marker_size)\nax1.axvline(x=1-alpha, color='black', ls=':')\nax1.set_xlabel(\"Coverage\")\nax1.set_ylabel(\"Average length\")\n\n# Methods legend\n\nhandles = []\nnames = []\nnames_wo_offline = list( map(methods_display.get, methods) )\nif add_offline:\n names = np.append(names,names_wo_offline[0])\n names = np.append(names,names_wo_offline)\n names[1] = 'Offline SSCP'# (adapted from Lei et al., 2018)\nelse:\n names = names_wo_offlines\nfor marker in list( map(markers.get, methods) ):\n handles.append(mlines.Line2D([], [], color='black', marker=marker, linestyle='None'))\n if add_offline and marker == 's':\n handles.append(mlines.Line2D([], [], color='black', marker=marker, linestyle='None', markerfacecolor='none'))\n\nfig.legend(handles, names, bbox_to_anchor=(0,0.95,1,0.2), loc='upper center', ncol=3)\n \nif lines:\n name_plot = 'plots/prices/'+dataset+'imputed_lines'\nelse:\n name_plot = 'plots/prices/'+dataset+'imputed_mean'\nif add_offline :\n name_plot = name_plot + '_offline'\n#plt.savefig(name_plot+'.pdf', bbox_inches='tight',dpi=300)\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a38365006adddedcdab5bf3d49604cdc7b072fa
| 19,645 |
ipynb
|
Jupyter Notebook
|
LGBM Model with SMOTEENN.ipynb
|
raiswetaj21/JOB-A-THON---March-2022
|
f9f0ef21771739bd8d25ae4acfb9919b42b06ccf
|
[
"MIT"
] | null | null | null |
LGBM Model with SMOTEENN.ipynb
|
raiswetaj21/JOB-A-THON---March-2022
|
f9f0ef21771739bd8d25ae4acfb9919b42b06ccf
|
[
"MIT"
] | null | null | null |
LGBM Model with SMOTEENN.ipynb
|
raiswetaj21/JOB-A-THON---March-2022
|
f9f0ef21771739bd8d25ae4acfb9919b42b06ccf
|
[
"MIT"
] | null | null | null | 31.891234 | 99 | 0.327106 |
[
[
[
"import pandas as pd\nimport numpy as np\nfrom sklearn import metrics\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nimport xgboost as xgb\nimport lightgbm as lgb\nfrom imblearn.combine import SMOTEENN",
"_____no_output_____"
],
[
"train = pd.read_csv(\"train.csv\")\ntest = pd.read_csv(\"test.csv\")",
"_____no_output_____"
],
[
"df = train.drop('ID', axis=1)\ndf = pd.get_dummies(df, drop_first=True)\ndf",
"_____no_output_____"
],
[
"X = df.drop('Is_Churn', axis=1)\nY = df['Is_Churn']\n\n# Feature Scaling\nscaler = StandardScaler()\nX = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)\n\nx_train,x_test,y_train,y_test = train_test_split(X, Y, test_size=0.2, random_state=604)",
"_____no_output_____"
],
[
"# LGBM\n\nmodel_lgbm=lgb.LGBMClassifier()\nmodel_lgbm.fit(x_train,y_train)\ny_pred=model_lgbm.predict(x_test)\nscore = model_lgbm.score(x_test,y_test)\nprint(\"DT test data score\", score)",
"DT test data score 0.7699248120300752\n"
],
[
"print(classification_report(y_test, y_pred, labels=[0,1]))",
" precision recall f1-score support\n\n 0 0.78 0.98 0.87 1028\n 1 0.46 0.07 0.12 302\n\n accuracy 0.77 1330\n macro avg 0.62 0.52 0.49 1330\nweighted avg 0.71 0.77 0.70 1330\n\n"
],
[
"# Using SMOTEENN (UpSampling+ENN) to handle class imbalance\nsm = SMOTEENN()\nX_resampled, y_resampled = sm.fit_resample(X,Y)\nxr_train,xr_test,yr_train,yr_test=train_test_split(X_resampled, y_resampled,test_size=0.2)\nmodel_lgbm_smote=lgb.LGBMClassifier()\nmodel_lgbm_smote.fit(xr_train,yr_train)\nyr_predict = model_lgbm_smote.predict(xr_test)\nmodel_score_smote = model_lgbm_smote.score(xr_test, yr_test)\nprint(\"Balanced Class test data score is:\", model_score_smote)\nf_one_score = (f1_score(yr_test, yr_predict, average='macro'))*100\nprint(\"F1 Score:\", f_one_score)\nprint(metrics.classification_report(yr_test, yr_predict))",
"Balanced Class test data score is: 0.8726554787759131\nF1 Score: 86.93973129289434\n precision recall f1-score support\n\n 0 0.85 0.85 0.85 426\n 1 0.89 0.89 0.89 587\n\n accuracy 0.87 1013\n macro avg 0.87 0.87 0.87 1013\nweighted avg 0.87 0.87 0.87 1013\n\n"
],
[
"# Data Preprocessing and Feature Engineering on Testing data\n\nX = test.drop(\"ID\", axis=1)\nX = pd.get_dummies(X, drop_first=True)\n\n# Feature Scaling\n\nscaler = StandardScaler()\nX = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)\n\nPredicted_Churn = model_lgbm_smote.predict(X)\n\n# Checking the predicted churn details and storing in dataframe format\npredicted_output = pd.DataFrame()\npredicted_output['ID'] = test[\"ID\"]\npredicted_output['Is_Churn'] = Predicted_Churn\npredicted_output",
"_____no_output_____"
],
[
"predicted_output.to_csv(\"sample_submission_solution.csv\", index=False)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a38467c87133a52825f6d0b02b60a86a2b67099
| 5,825 |
ipynb
|
Jupyter Notebook
|
0.intro-to-unix-commands/2.text-analysis.ipynb
|
Alex-bzh/python-M2TTD
|
c6debc2084121f99387b8bd2cc07f277a7a0a5f3
|
[
"MIT"
] | null | null | null |
0.intro-to-unix-commands/2.text-analysis.ipynb
|
Alex-bzh/python-M2TTD
|
c6debc2084121f99387b8bd2cc07f277a7a0a5f3
|
[
"MIT"
] | null | null | null |
0.intro-to-unix-commands/2.text-analysis.ipynb
|
Alex-bzh/python-M2TTD
|
c6debc2084121f99387b8bd2cc07f277a7a0a5f3
|
[
"MIT"
] | null | null | null | 27.347418 | 226 | 0.524635 |
[
[
[
"# Analyse de texte avec Unix",
"_____no_output_____"
],
[
"## Filtrage\n\nL’utilitaire `grep` (*file pattern searcher*) associé à l’option `-a` considère les fichiers en paramètres comme de l’ASCII. Il est utile pour rechercher un motif (*pattern*) en utilisant les expressions rationnelles.\n\n```bash\n# find, in all the TXT files, the lines that contain the word 'upon'\ncat ./files/*.txt | grep -a upon\n```\n\n```bash\n# words that end with suffix -ly\ncat ./files/*.txt | grep -a \"[a-zA-Z]*ly\"\n```",
"_____no_output_____"
],
[
"## Remplacement",
"_____no_output_____"
],
[
"### *SED*\n\n`sed` (*stream editor*) est un utilitaire très puissant qui permet d’éditer les lignes d’un flux en effectuant des remplacements.\n\n```bash\n# substitutes first occurrence of 'id' by 'it'\necho \"Le petit chat boid du laid.\" | sed 's/id/it/'\n```\n\n```bash\n# substitutes all occurrences of 'id' by 'it'\necho \"Le petit chat boid du laid.\" | sed 's/id/it/g'\n```\n\nIl est possible d’utiliser des expressions rationnelles :\n\n```bash\necho \"Le petit chat boid du laid.\" | sed 's/\\w*d/t/g'\n```\n\nSi l’utilitaire renvoie ordinairement le flux dans la sortie standard, l’option `-i` effectue le remplacement en place dans les fichiers en paramètres :\n\n```bash\nsed -i '' 's/subscribe/unsubscribe/g' ./files/*.txt\n```\n\nLa configuration `d` dans le paramétrage de l’outil permet de supprimer les lignes qui répondent au motif renseigné :\n\n```bash\n# remove lines starting with a whitespace character\nsed '/^[[:space:]]/d' ./files/*.txt\n```\n\n```bash\n# remove empty lines\nsed '/^$/d' ./files/*.txt\n```",
"_____no_output_____"
],
[
"### *TR*\n\nUn autre utilitaire pour manipuler le flux d’un texte est `tr` (*translate characters*). Il offre la capacité d’effectuer une concordance entre plusieurs caractères à remplacer.\n\n```bash\n# 'a' => 'e' ; 'e' => 'a'\necho \"Le petit chat boit du lait.\" | tr ae ea\n```\n\nLes remplacements peuvent s’opérer depuis un fichier :\n\n```bash\ntr ae ea < ./files/*.txt\n```\n\nL’option `-d` s’utilise pour supprimer des caractères :\n\n```bash\n# removes all occurrences of character 'e'\ntr -d e < ./files/*.txt\n```\n\nAvec l’option `-s`, les caractères répétés fusionnent :\n```bash\n# the three whitespace characters become one, while single ones still\necho \"Le petit chat boit du lait.\" | tr -s '[:blank:]' ' '\n```\n\nUne autre option intéressante consiste à effectuer un remplacement sur tous les autres caractères sauf ceux indiqués :\n\n```bash\n# keep all digits\necho \"La révolution française a eu lieu en 1789.\" | tr -cd '[:digit:]'\n```\n\n```bash\n# every character but digits become an 'x'\necho \"La révolution française a eu lieu en 1789.\" | tr -c '[:digit:]' 'x'\n```",
"_____no_output_____"
],
[
"## Tri\n\nL’utilitaire `sort` permet de trier des lignes de textes. Avec l’option `-r`, le tri s’effectue de manière inversée et, avec `-f`, il ignore la casse des caractères :\n\n```bash\necho \"Le\npetit\nchat\nboit\ndu\nlait\n.\" | sort -rf\n```\n\nEt pour effectuer un tri sur des valeurs numériques plutôt qu’alphabétiques, il faut recourir à l’option `-n`.",
"_____no_output_____"
],
[
"## Comptage\n\nIl existe un utilitaire pour compter les lignes, mots et caractères dans un texte : `wc` (*word count*).\n\n```bash\n# 1 line, 6 words, 28 characters\necho \"Le petit chat boit du lait.\" | wc\n```\n\nPour limiter le comptage à l’une ou l’autre des unités, il faut utiliser les options `-l` (lignes), `-w` (mots) et `-m` (caractères).",
"_____no_output_____"
],
[
"## Fréquence\n\nGrâce à `uniq` et son option `-c`, il est possible d’obtenir un décompte des occurrences d’un mot dans un texte :\n\n```bash\necho \"Le\npetit\nchat\nboit\ndu\nlait\n.\nLe\npetit\nchien\nboit\nde\nl’\neau\n.\" | sort | uniq -c | sort -rn\n```\n\nÀ noter que l’option `-i` permet d’effectuer ce calcul en ignorant la casse.",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4a38479671ccbb0d877863ae77ccca04cf400e85
| 2,537 |
ipynb
|
Jupyter Notebook
|
python/python_glob.ipynb
|
icescut/my.summary
|
718ccadd987378361bf77183065a01a81d9a2719
|
[
"MIT"
] | null | null | null |
python/python_glob.ipynb
|
icescut/my.summary
|
718ccadd987378361bf77183065a01a81d9a2719
|
[
"MIT"
] | null | null | null |
python/python_glob.ipynb
|
icescut/my.summary
|
718ccadd987378361bf77183065a01a81d9a2719
|
[
"MIT"
] | null | null | null | 17.741259 | 150 | 0.49192 |
[
[
[
"# Python glob",
"_____no_output_____"
],
[
"glob是python自己带的一个文件操作相关模块,内容也不多,用它可以查找符合自己目的的文件,就类似于Windows下的文件搜索,而且也支持通配符`*`,`?`,`[]`这三个通配符,`*`代表0个或多个字符,`?`代表一个字符,`[]`匹配指定范围内的字符,如`[0-9]`匹配数字。",
"_____no_output_____"
],
[
"## glob函数\n它的主要方法就是glob,该方法返回所有匹配的文件路径列表,该方法需要一个参数用来指定匹配的路径字符串(本字符串可以为绝对路径也可以为相对路径),比如:",
"_____no_output_____"
]
],
[
[
"import glob\nglob.glob(r'c:/*.txt')",
"_____no_output_____"
]
],
[
[
"也可以使用相对路径:",
"_____no_output_____"
]
],
[
[
"glob.glob(r'*.py')",
"_____no_output_____"
]
],
[
[
"## iglob函数\n与glob方法类似,但是iglob返回的是一个生成器。",
"_____no_output_____"
]
],
[
[
"f = glob.iglob(r'c:/*.txt')\nprint(f)\nfor txt in f:\n print(txt)",
"<generator object _iglob at 0x00000278A5DD6D00>\nc:/Recovery.txt\n"
]
],
[
[
"注意`*`并不会匹配路径分隔符`/`。",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a386b17098b73c22f08d0f98095e38b1b01a27f
| 2,701 |
ipynb
|
Jupyter Notebook
|
examples/jupyter/demo224_dirichlet_bddc.ipynb
|
MalachiTimothyPhillips/LFAToolkit.jl
|
ff1cddefa56c7153ff8307c57fac7dbe1011ba6b
|
[
"BSD-2-Clause"
] | 7 |
2020-12-04T22:12:53.000Z
|
2022-01-05T18:42:42.000Z
|
examples/jupyter/demo224_dirichlet_bddc.ipynb
|
MalachiTimothyPhillips/LFAToolkit.jl
|
ff1cddefa56c7153ff8307c57fac7dbe1011ba6b
|
[
"BSD-2-Clause"
] | 23 |
2020-09-15T23:25:01.000Z
|
2022-02-20T01:06:55.000Z
|
examples/jupyter/demo224_dirichlet_bddc.ipynb
|
MalachiTimothyPhillips/LFAToolkit.jl
|
ff1cddefa56c7153ff8307c57fac7dbe1011ba6b
|
[
"BSD-2-Clause"
] | 3 |
2020-09-12T02:37:19.000Z
|
2022-02-05T14:49:30.000Z
| 22.889831 | 102 | 0.498334 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4a387024a745a4e3b6274cae9f397b95473a16e4
| 34,840 |
ipynb
|
Jupyter Notebook
|
database/notebooks/01-set-up-database.ipynb
|
thangdc1982/serverless-full-stack-apps-azure-sql
|
24d211450dca2d0dab30d9bb847e3dfb3b9c1421
|
[
"MIT"
] | null | null | null |
database/notebooks/01-set-up-database.ipynb
|
thangdc1982/serverless-full-stack-apps-azure-sql
|
24d211450dca2d0dab30d9bb847e3dfb3b9c1421
|
[
"MIT"
] | null | null | null |
database/notebooks/01-set-up-database.ipynb
|
thangdc1982/serverless-full-stack-apps-azure-sql
|
24d211450dca2d0dab30d9bb847e3dfb3b9c1421
|
[
"MIT"
] | null | null | null | 38.883929 | 547 | 0.345809 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4a38a6166aa9cf4562adb6922969afc76126cebc
| 301,250 |
ipynb
|
Jupyter Notebook
|
src/simulations_algorithm.ipynb
|
Sega314/cojo-robustness
|
55663fe2ca6add5b82ea7b1b6ba028e1d4cdfc5c
|
[
"MIT"
] | null | null | null |
src/simulations_algorithm.ipynb
|
Sega314/cojo-robustness
|
55663fe2ca6add5b82ea7b1b6ba028e1d4cdfc5c
|
[
"MIT"
] | null | null | null |
src/simulations_algorithm.ipynb
|
Sega314/cojo-robustness
|
55663fe2ca6add5b82ea7b1b6ba028e1d4cdfc5c
|
[
"MIT"
] | null | null | null | 471.43975 | 253,498 | 0.921388 |
[
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import axes3d\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\nimport seaborn as sns\n\n%matplotlib inline\nsns.set(style=\"white\", color_codes=True)",
"/usr/local/lib/python3.5/dist-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"
]
],
[
[
"# Genotypes simulation algorithm",
"_____no_output_____"
],
[
"Рассмотрим следующую простую модель. Пусть есть два биаллельных ОНП $A$ и $B$ с аллелями $a_1$, $a_2$, и $b_1$, $b_2$ соответственно. \nПараметры модели: $P(a_1)$ -- частота аллеля $a_1$ в ОНП $A$, $P(b_1)$ -- частота аллеля $b_1$ в ОНП $B$, $N$ -- число индивидов в популяции, $r$ -- коэффициент корреляции между снипами.\nЗапишем выражение для коэффициента неравновесия по сцеплению через частоты всех возможных пар аллелей:\n\n$$ D = P(a_1 b_1) - P(a_1) P(b_1) $$ \n$$ -D = P(a_1 b_2) - P(a_1) P(b_2) $$ \n$$ -D = P(a_2 b_1) - P(a_2) P(b_1) $$ \n$$ D = P(a_2 b_2) - P(a_2) P(b_2) $$\n\nИз этой системы уравнений можно выразить вероятности гаплотипов:\n\n| | $b_1$ | $b_2$ |\n|:-----:|:--------------------------------:|:--------------------------------:|\n| $a_1$ | $P(a_1 b_1) = P(a_1) P(b_1) + D$ | $P(a_1 b_2) = P(a_1) P(b_2) - D$ |\n| $a_2$ | $P(a_2 b_1) = P(a_2) P(b_1) - D$ | $P(a_2 b_2) = P(a_2) P(b_2) + D$ |\n\nТеперь, когда известно распределение вероятностей гаплотипов, сгенерируем $2N$ гаплотипов и случайным образом объединив их пары, получим $N$ генотипов.",
"_____no_output_____"
],
[
"# Genotypes simulation algorithm implementation",
"_____no_output_____"
],
[
"### Setting parameters",
"_____no_output_____"
]
],
[
[
"population_size = 100000 # number of individuals in population\n\nfreq_a1 = 0.7 # allele frequency of the first allele in first site\nfreq_a2 = 1 - freq_a1 # allele frequency of the second allele in first site \n\nfreq_b1 = 0.6 # allele frequency of the first allele in second site\nfreq_b2 = 1 - freq_b1 # allele frequency of the second allele in second site\n\nr = 0.7 # absolute value should not be more than 0.2 (??)\nd = r * np.sqrt(freq_a1 * freq_a2 * freq_b1 * freq_b2)\nprint(\"d =\", d)",
"d = 0.157149610245\n"
]
],
[
[
"### Calculating probabilities of haplotypes",
"_____no_output_____"
]
],
[
[
"p_a1_b1 = d + freq_a1 * freq_b1\np_a1_b2 = -d + freq_a1 * freq_b2\np_a2_b1 = -d + freq_a2 * freq_b1\np_a2_b2 = d + freq_a2 * freq_b2 # 1 - p_a1_b1 - p_a1_b2 - p_a2_b1\n\nif 0.0 <= p_a1_b1 <= 1.0 and \\\n 0.0 <= p_a1_b2 <= 1.0 and \\\n 0.0 <= p_a2_b1 <= 1.0 and \\\n 0.0 <= p_a2_b2 <= 1.0:\n \n print(\"p_a1_b1 =\", p_a1_b1)\n print(\"p_a1_b2 =\", p_a1_b2)\n print(\"p_a2_b1 =\", p_a2_b1)\n print(\"p_a2_b2 =\", p_a2_b2)\n \nelse:\n \n print(\"incorrect input\")\n \n# plot d from r and p_ai_bj, найти множество допустимых значений",
"p_a1_b1 = 0.577149610245\np_a1_b2 = 0.122850389755\np_a2_b1 = 0.0228503897555\np_a2_b2 = 0.277149610245\n"
]
],
[
[
"### Generating haplotypes",
"_____no_output_____"
]
],
[
[
"haplotypes = []\n\nfor counter in range(2 * population_size):\n \n x = float(np.random.uniform(0, 1, 1))\n if x < p_a1_b1:\n haplotypes.append(11)\n elif x < p_a1_b1 + p_a1_b2:\n haplotypes.append(12)\n elif x < p_a1_b1 + p_a1_b2 + p_a2_b1:\n haplotypes.append(21)\n else:\n haplotypes.append(22)",
"_____no_output_____"
]
],
[
[
"### Generating genotypes",
"_____no_output_____"
]
],
[
[
"genotypes = []\n\nfor i in range(population_size):\n genotype = str(haplotypes[i] // 10 + haplotypes[i + population_size] // 10 - 2)\n genotype += str(haplotypes[i] % 10 + haplotypes[i + population_size] % 10 - 2)\n genotypes.append(genotype)\n\ngenotypes = np.array([list(i) for i in genotypes], dtype='int') \n\nmse_genotypes_a = np.mean((genotypes[:, 0] - np.mean(genotypes[:, 0])) ** 2)\nmse_genotypes_b = np.mean((genotypes[:, 1] - np.mean(genotypes[:, 1])) ** 2)\n\nprint(mse_genotypes_a, 2 * freq_a1 * freq_a2)\nprint(mse_genotypes_b, 2 * freq_b1 * freq_b2)",
"0.4210839936 0.42000000000000004\n0.4811979951 0.48\n"
],
[
"fig = plt.figure()\nax = fig.add_subplot(111)\nn, bins, rectangles = ax.hist(genotypes[:, 1], 100, normed=True)\nfig.canvas.draw()\nplt.show()",
"_____no_output_____"
],
[
"count_a, count_b = 0, 0\n\nfor i in range(population_size):\n count_a += genotypes[i][0]\n count_b += genotypes[i][1]\n\nprint(\" Calc allele freq \\t Exp allele freq\")\nprint(\"A: \", 1 - count_a / (2 * population_size), \"\\t\\t\", freq_a1)\nprint(\"B: \", 1 - count_b / (2 * population_size), \"\\t\\t\", freq_b1)",
" Calc allele freq \t Exp allele freq\nA: 0.69996 \t\t 0.7\nB: 0.599965 \t\t 0.6\n"
]
],
[
[
"# Phenotypes simulation algorithm",
"_____no_output_____"
],
[
"Рассмотрим аддитивную модель с параметрами $\\beta_A$ и $\\beta_B$:\n\n$a_1 a_1$ 0 \n$a_1 a_2$ $\\beta_A$ \n$a_2 a_2$ $2 \\beta_A$ \n\n$b_1 b_1$ 0 \n$b_1 b_2$ $\\beta_B$ \n$b_2 b_2$ $2 \\beta_B$ \n\n$\\mathbf{y} = \\mathbf{G} \\mathbf{w} + \\mathbf{\\varepsilon}$\n\n$\\mathbf{y}$ -- вектор фенотипов, \n$\\mathbf{G}$ -- матрица генотипов, \n$\\mathbf{w}$ -- вектор весов, \n$\\mathbf{\\varepsilon}$ -- вектор ошибок, полученный из стандартного распределения\n\nПусть $\\sigma_y = 1$, тогда, поскольку $\\sigma_y = \\sigma_{Gw} + \\sigma_{\\varepsilon}$,\n\n$\\sigma_{\\varepsilon} = 1 - \\sigma_{Gw}$\n\n$ \\sigma_{Gw} = \\beta_1^2 mse_a + \\beta_2^2 mse_b - 2 cov(\\beta_1^2 mse_a, \\beta_2^2 mse_b)$\n",
"_____no_output_____"
],
[
"# Phenotypes simulation algorithm implementation",
"_____no_output_____"
],
[
"### Setting parameters",
"_____no_output_____"
]
],
[
[
"beta_a = 0.15 # effect of heterozygote in the first snp on phenotype\nbeta_b = 0.13 # effect of heterozygote in the second snp on phenotype",
"_____no_output_____"
],
[
"phenotypes = []\n\nsigma_err = 1 - mse_genotypes_a * beta_a ** 2 - mse_genotypes_b * beta_b ** 2\n\nfor i in range(population_size):\n phenotype = genotypes[i][0] * beta_a + genotypes[i][1] * beta_b + np.random.normal(0, np.sqrt(sigma_err))\n phenotypes.append(phenotype)\n\n# test phenotypes mean and d \n# test against normal distr.",
"_____no_output_____"
],
[
"np.std(phenotypes)",
"_____no_output_____"
],
[
"simulated_data = pd.DataFrame({\"phenotype\": phenotypes, \n \"snp_a_gen\": genotypes[:, 0], \n \"snp_b_gen\": genotypes[:, 1]})\nsimulated_data.head()",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(20, 15))\nax = fig.gca(projection=\"3d\")\n\nax.plot(simulated_data.snp_a_gen, \n simulated_data.snp_b_gen, \n simulated_data.phenotype, 'co', zorder=0)\n\nax.plot(simulated_data.snp_a_gen, \n simulated_data.phenotype, \n 'ko', zdir='y', alpha=0.25, zs=3.0, mec=None, zorder=0)\n\nax.plot(simulated_data.snp_b_gen, \n simulated_data.phenotype, \n 'ko', zdir='x', alpha=0.25, zs=3.06, mec=None, zorder=0)\n\nax.plot(simulated_data.snp_a_gen,\n simulated_data.snp_b_gen,\n 'ko', zdir='z', alpha=0.25, zs=-3.1, mec=None, zorder=0)\n\n# adding plane\nmodel = smf.ols('phenotype ~ snp_a_gen + snp_b_gen', data=simulated_data).fit()\n# print(model.summary())\nxx, yy = np.meshgrid(np.linspace(0, 3.0, 20), np.linspace(0, 3.0, 20))\nzz = model.params[1] * xx + model.params[2] * yy + model.params[0]\nplane = ax.plot_surface(xx, yy, zz, color='blue', alpha=0.5, cmap=cm.coolwarm, zorder=1)\n\n\nfit_a = np.polyfit(simulated_data.snp_a_gen, \n simulated_data.phenotype, \n deg=1)\nax.plot(np.array(simulated_data.snp_a_gen), \n fit_a[0] * np.array(simulated_data.snp_a_gen) + fit_a[1], \n color='k', zdir='y', zs=3.0, zorder=1)\n\nfit_b = np.polyfit(simulated_data.snp_b_gen, \n simulated_data.phenotype, \n deg=1)\nax.plot(np.array(simulated_data.snp_b_gen), \n fit_b[0] * np.array(simulated_data.snp_b_gen) + fit_b[1], \n color='k', zdir='x', zs=3.06, zorder=1)\n\nfor gen_a in range(3):\n for gen_b in range(3):\n print(\"gen_a =\", gen_a, \n \", gen_b =\", gen_b, \n \", mean =\", simulated_data[(simulated_data.snp_a_gen == gen_a) & \n (simulated_data.snp_b_gen == gen_b)].phenotype.mean())\n ax.scatter(xs=[gen_a], \n ys=[gen_b], \n zs=[simulated_data[(simulated_data.snp_a_gen == gen_a) & \n (simulated_data.snp_b_gen == gen_b)].phenotype.mean()],\n color='r',\n zorder=10)\n\nprint(simulated_data[(simulated_data.snp_a_gen == 2) & \n (simulated_data.snp_b_gen == 2)].phenotype.mean())\n \nfor gen in range(3):\n \n ax.plot([gen], \n [simulated_data[simulated_data.snp_a_gen == gen].phenotype.mean()], \n color='k', \n zdir='y', \n zs=3.0,\n zorder=10)\n \n ax.plot([gen], \n [simulated_data[simulated_data.snp_b_gen == gen].phenotype.mean()], \n color='k', \n zdir='x', \n zs=3.0,\n zorder=10)\n\nax.set_xlabel(\"A SNP Genotypes\")\nax.set_xlim(3.0, 0.0)\n\nax.set_ylabel('B SNP Genotypes')\nax.set_ylim(0.0, 3.0)\n\nax.set_zlabel(\"Phenotype\")\nax.set_zlim(-3.0, 3.0)\n\nax.set_yticks(range(3))\nax.set_xticks(range(3))\n\nfig.colorbar(plane, shrink=0.5, aspect=20, ticks=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])\n\n# fig.savefig(\"./multivariate_regression_on_simulated_data.pdf\", dpi=300)\n# fig.savefig(\"./multivariate_regression_on_simulated_data.png\", dpi=300)\n\nplt.show()\nplt.close(fig)",
"gen_a = 0 , gen_b = 0 , mean = -0.004617011175153093\ngen_a = 0 , gen_b = 1 , mean = 0.13084558883030362\ngen_a = 0 , gen_b = 2 , mean = 0.2971367899934479\ngen_a = 1 , gen_b = 0 , mean = 0.1513158824202622\ngen_a = 1 , gen_b = 1 , mean = 0.28365252295784515\ngen_a = 1 , gen_b = 2 , mean = 0.4038542094539864\ngen_a = 2 , gen_b = 0 , mean = 0.2268785044655681\ngen_a = 2 , gen_b = 1 , mean = 0.4227611735248942\ngen_a = 2 , gen_b = 2 , mean = 0.5623698024850529\n0.5623698024850529\n"
],
[
"joint_z1_z2 = pd.read_csv(\"../out/1000_iter_z1_z2.csv\", names=\"z1 z2\".split())\n\nprint(joint_z1_z2.head())\n\ng = sns.jointplot(\"z1\", \"z2\", data=joint_z1_z2, kind=\"kde\", space=0, color=\"g\")\ng.savefig(\"../out/joint_distr_z1_z2_1000_iter.png\", dpi=300)\nplt.show()",
" z1 z2\n0 8.049642 4.756826\n1 8.157889 6.887383\n2 7.552011 6.820614\n3 5.460234 7.479007\n4 8.014952 5.661308\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a38bf4fc76aedcdb6815be72993b4073c9dad3f
| 13,068 |
ipynb
|
Jupyter Notebook
|
Deep Learning/Convolutional Neural Networks (CNN)/convolutional_neural_network_samrat_with_10_epochs.ipynb
|
World-of-ML-AI/Machine-learning-a-to-z
|
07c1dbb0b5f7d356c7674c3989103041b5f51f9d
|
[
"MIT"
] | 1 |
2021-12-13T21:12:30.000Z
|
2021-12-13T21:12:30.000Z
|
Deep Learning/Convolutional Neural Networks (CNN)/convolutional_neural_network_samrat_with_10_epochs.ipynb
|
World-of-ML-AI/Machine-learning-a-to-z
|
07c1dbb0b5f7d356c7674c3989103041b5f51f9d
|
[
"MIT"
] | null | null | null |
Deep Learning/Convolutional Neural Networks (CNN)/convolutional_neural_network_samrat_with_10_epochs.ipynb
|
World-of-ML-AI/Machine-learning-a-to-z
|
07c1dbb0b5f7d356c7674c3989103041b5f51f9d
|
[
"MIT"
] | null | null | null | 27.804255 | 343 | 0.451561 |
[
[
[
"<a href=\"https://colab.research.google.com/github/lionelsamrat10/machine-learning-a-to-z/blob/main/Deep%20Learning/Convolutional%20Neural%20Networks%20(CNN)/convolutional_neural_network_samrat_with_10_epochs.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Convolutional Neural Network",
"_____no_output_____"
],
[
"### Importing the libraries",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator\nimport numpy as np",
"_____no_output_____"
],
[
"tf.__version__",
"_____no_output_____"
]
],
[
[
"## Part 1 - Data Preprocessing",
"_____no_output_____"
],
[
"### Preprocessing the Training set",
"_____no_output_____"
]
],
[
[
"# Transforming the Image\n# Rescale applies Feature Scaling to each pixels in our images\n# We are doing this to avoid Overfitting\ntrain_datagen = ImageDataGenerator(rescale = 1./255,\n shear_range = 0.2,\n zoom_range = 0.2,\n horizontal_flip = True)\n# Only 32 images will run in one batch\ntraining_set = train_datagen.flow_from_directory('dataset/training_set',\n target_size = (64, 64),\n batch_size = 32,\n class_mode = 'binary')",
"Found 8000 images belonging to 2 classes.\n"
]
],
[
[
"### Preprocessing the Test set",
"_____no_output_____"
]
],
[
[
"test_datagen = ImageDataGenerator(rescale = 1./255)\ntest_set = test_datagen.flow_from_directory('dataset/test_set',\n target_size = (64, 64),\n batch_size = 32,\n class_mode = 'binary')",
"Found 2000 images belonging to 2 classes.\n"
]
],
[
[
"## Part 2 - Building the CNN",
"_____no_output_____"
],
[
"### Initialising the CNN",
"_____no_output_____"
]
],
[
[
"cnn = tf.keras.models.Sequential();",
"_____no_output_____"
]
],
[
[
"### Step 1 - Convolution",
"_____no_output_____"
]
],
[
[
"cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu', input_shape=[64, 64, 3]))\n# Kernel Size is same as the number of rows in the Feature Detector\n# The images are resized as 64px X 64px and 3 denotes 3D R, G, B ",
"_____no_output_____"
]
],
[
[
"### Step 2 - Pooling",
"_____no_output_____"
]
],
[
[
"cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))",
"_____no_output_____"
]
],
[
[
"### Adding a second convolutional layer",
"_____no_output_____"
]
],
[
[
"cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu'))\ncnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))",
"_____no_output_____"
]
],
[
[
"### Step 3 - Flattening",
"_____no_output_____"
]
],
[
[
"cnn.add(tf.keras.layers.Flatten()) #Flattens the 2D array into an 1D array",
"_____no_output_____"
]
],
[
[
"### Step 4 - Full Connection",
"_____no_output_____"
]
],
[
[
"cnn.add(tf.keras.layers.Dense(units=128, activation='relu')) # Units mean the number of neurons in the hidden layer",
"_____no_output_____"
]
],
[
[
"### Step 5 - Output Layer",
"_____no_output_____"
]
],
[
[
"cnn.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))",
"_____no_output_____"
]
],
[
[
"## Part 3 - Training the CNN",
"_____no_output_____"
],
[
"### Compiling the CNN",
"_____no_output_____"
]
],
[
[
"cnn.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])",
"_____no_output_____"
]
],
[
[
"### Training the CNN on the Training set and evaluating it on the Test set",
"_____no_output_____"
]
],
[
[
"cnn.fit(x = training_set, validation_data = test_set, epochs = 10)",
"Epoch 1/10\n250/250 [==============================] - 166s 661ms/step - loss: 0.6130 - accuracy: 0.6650 - val_loss: 0.7774 - val_accuracy: 0.5945\nEpoch 2/10\n250/250 [==============================] - 99s 395ms/step - loss: 0.5584 - accuracy: 0.7097 - val_loss: 0.5321 - val_accuracy: 0.7280\nEpoch 3/10\n250/250 [==============================] - 98s 390ms/step - loss: 0.5273 - accuracy: 0.7419 - val_loss: 0.6004 - val_accuracy: 0.6915\nEpoch 4/10\n250/250 [==============================] - 103s 413ms/step - loss: 0.5002 - accuracy: 0.7551 - val_loss: 0.4929 - val_accuracy: 0.7640\nEpoch 5/10\n250/250 [==============================] - 99s 397ms/step - loss: 0.4772 - accuracy: 0.7674 - val_loss: 0.4710 - val_accuracy: 0.7740\nEpoch 6/10\n250/250 [==============================] - 100s 399ms/step - loss: 0.4656 - accuracy: 0.7768 - val_loss: 0.4704 - val_accuracy: 0.7775\nEpoch 7/10\n250/250 [==============================] - 102s 409ms/step - loss: 0.4499 - accuracy: 0.7876 - val_loss: 0.4600 - val_accuracy: 0.7875\nEpoch 8/10\n250/250 [==============================] - 112s 448ms/step - loss: 0.4342 - accuracy: 0.7945 - val_loss: 0.4567 - val_accuracy: 0.7875\nEpoch 9/10\n250/250 [==============================] - 103s 411ms/step - loss: 0.4277 - accuracy: 0.7994 - val_loss: 0.4424 - val_accuracy: 0.7920\nEpoch 10/10\n250/250 [==============================] - 102s 406ms/step - loss: 0.4156 - accuracy: 0.8090 - val_loss: 0.4633 - val_accuracy: 0.7865\n"
]
],
[
[
"## Part 4 - Making a single prediction",
"_____no_output_____"
]
],
[
[
"from keras.preprocessing import image\ntest_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64, 64)) # Creates a PIL image\ntest_image = image.img_to_array(test_image) # Converts the PIL image to a NumPy Array\ntest_image = np.expand_dims(test_image, axis = 0) # Cobtain the image into a Batch\nresult = cnn.predict(test_image)\ntraining_set.class_indices\nif result[0][0] == 1:\n prediction = 'dog'\nelse:\n prediction = 'cat'",
"_____no_output_____"
],
[
"print(prediction) # cat_or_dog_1.jpg originally is an image of a dog",
"dog\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",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a38daf6937d20a57aec384ad0d39d64b363f884
| 317,164 |
ipynb
|
Jupyter Notebook
|
recitations/Rec5/Rec5_WFP.ipynb
|
1ozturkbe/15094code
|
323ba5d8e1f462a3e298d101e740abd8f02a42c0
|
[
"MIT"
] | 1 |
2021-12-28T18:51:55.000Z
|
2021-12-28T18:51:55.000Z
|
recitations/Rec5/Rec5_WFP.ipynb
|
1ozturkbe/15094code
|
323ba5d8e1f462a3e298d101e740abd8f02a42c0
|
[
"MIT"
] | 1 |
2021-04-26T00:20:19.000Z
|
2021-04-26T00:20:19.000Z
|
recitations/Rec5/Rec5_WFP.ipynb
|
1ozturkbe/15094code
|
323ba5d8e1f462a3e298d101e740abd8f02a42c0
|
[
"MIT"
] | 1 |
2022-01-21T00:22:45.000Z
|
2022-01-21T00:22:45.000Z
| 1,078.789116 | 305,036 | 0.952939 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4a38e993fcd1c3a1e80cbb19bfb107defa8cd1f3
| 264,084 |
ipynb
|
Jupyter Notebook
|
bak/problems/problem_0001/baseline-Copy1.ipynb
|
IGARDS/RPLib
|
a23a2a9b0622fc4fc46ad175ff3a9c94cd345fa4
|
[
"MIT"
] | null | null | null |
bak/problems/problem_0001/baseline-Copy1.ipynb
|
IGARDS/RPLib
|
a23a2a9b0622fc4fc46ad175ff3a9c94cd345fa4
|
[
"MIT"
] | 27 |
2021-02-05T20:56:05.000Z
|
2022-03-07T04:11:57.000Z
|
bak/problems/problem_0001/baseline-Copy1.ipynb
|
IGARDS/RPLib
|
a23a2a9b0622fc4fc46ad175ff3a9c94cd345fa4
|
[
"MIT"
] | null | null | null | 31.952087 | 516 | 0.349847 |
[
[
[
"# RPLib Problem 0001 - Baseline\n\nProvides the baseline version to rankability problem 0001. Focuses on Massey and Colley out of the box without ties or indirect game information.",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2\n%matplotlib inline",
"The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n"
],
[
"import copy\nimport os\n\nimport pandas as pd\nimport numpy as np\n\nfrom scipy.stats import pearsonr\n\nfrom tqdm import tqdm\n#import matplotlib.pyplot as plt\nfrom joblib import Parallel, delayed\nimport joblib\nimport itertools\nfrom pathlib import Path\n\nfrom IPython.display import display, Markdown, Latex",
"_____no_output_____"
]
],
[
[
"**All packages are relative to the home directory of the user**",
"_____no_output_____"
]
],
[
[
"home = str(Path.home())",
"_____no_output_____"
]
],
[
[
"**Import the main rankability package**",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.insert(0,\"%s/rankability_toolbox_dev\"%home)\nimport pyrankability",
"_____no_output_____"
]
],
[
[
"**Load the problem information**",
"_____no_output_____"
]
],
[
[
"problem = joblib.load(\"/disk/RPLib/problem_0001.joblib.z\")",
"_____no_output_____"
]
],
[
[
"## Explore and setup the problem",
"_____no_output_____"
]
],
[
[
"problem.keys()",
"_____no_output_____"
],
[
"print(problem[\"description\"])",
"\nA practitioner wants to predict the degree to which a the rankings during season \nof the NCAA Men’s Basketball are likely to change as more games are played (i.e., sensitivity to more games). \nThey want to start the analysis after a minimum of 50% of the games are played. \nThey want to run Massey and Colley.\n\nSensitivity of new games will be measured as the intersection of between two \nrankings derived from before and after the new games are included.\n\n"
],
[
"problem['target']",
"_____no_output_____"
],
[
"problem['data'].keys()",
"_____no_output_____"
],
[
"problem['data']['2002'].keys()",
"_____no_output_____"
]
],
[
[
"**Create easier to reference variables**",
"_____no_output_____"
]
],
[
[
"years = list(problem['data'].keys())\nfrac_keys = list(problem['data'][years[0]].keys())\nremaining_games = problem['other']['remaining_games']\nmadness_teams = problem['other']['madness_teams']\nbest_df = problem['other']['best_df']\ntop_k = problem['other']['top_k']\ntarget_column = f\"top{top_k}_intersection\"\nbest_pred_df = problem['other']['best_pred_df']",
"_____no_output_____"
]
],
[
[
"## Define helper functions",
"_____no_output_____"
],
[
"**Function to compute a D matrix from games using hyperparameters**",
"_____no_output_____"
]
],
[
[
"def compute_D(game_df,team_range,direct_thres,spread_thres):\n map_func = lambda linked: pyrankability.construct.support_map_vectorized_direct_indirect(linked,direct_thres=direct_thres,spread_thres=spread_thres)\n Ds = pyrankability.construct.V_count_vectorized(game_df,map_func)\n for i in range(len(Ds)):\n Ds[i] = Ds[i].reindex(index=team_range,columns=team_range)\n return Ds",
"_____no_output_____"
],
[
"def process(data,target,best_df_all):\n index_cols = [\"Year\",\"frac_key\",\"direct_thres\",\"spread_thres\",\"weight_indirect\",\"range\"]\n Ds = pd.DataFrame(columns=[\"D\"]+index_cols)\n Ds.set_index(index_cols,inplace=True)\n for frac_key,year in tqdm(itertools.product(frac_keys,years)):\n frac = float(frac_key.split(\"=\")[1])\n best_df = best_df_all.set_index('frac').loc[frac]\n for index,row in best_df.iterrows():\n dom,ran,dt,st,iw = row.loc['domain'],row.loc['range'],row.loc['direct_thres'],row.loc['spread_thres'],row.loc['weight_indirect']\n # set the team_range\n team_range = None\n if ran == 'madness':\n team_range = madness_teams[year]\n elif ran == 'all':\n team_range = all_teams[year]\n else:\n raise Exception(f\"range={ran} not supported\")\n name = (year,frac_key,dt,st,iw,ran)\n if iw == 0:\n st = np.Inf\n D = compute_D(data[year][frac_key],team_range,dt,st)\n Ds = Ds.append(pd.Series([D],index=[\"D\"],name=name)) \n return Ds",
"_____no_output_____"
]
],
[
[
"## Create D matrices\nWe will ignore indirect games and ties (direct threshold modification).",
"_____no_output_____"
]
],
[
[
"param_df = best_df.copy()\nparam_df.spread_thres = 0\nparam_df.weight_indirect = 0\nparam_df.direct_thres = 0\nparam_df",
"_____no_output_____"
],
[
"Ds = process(problem['data'],problem['target'],param_df)",
"102it [01:33, 1.62s/it]\n"
],
[
"Ds",
"_____no_output_____"
],
[
"Ds.iloc[[0,-1]]",
"_____no_output_____"
],
[
"Ds.loc['2002',\"D\"][0][0]",
"/opt/tljh/user/lib/python3.7/site-packages/ipykernel_launcher.py:1: PerformanceWarning: indexing past lexsort depth may impact performance.\n \"\"\"Entry point for launching an IPython kernel.\n"
],
[
"Ds.loc['2002',\"D\"][0][1]",
"/opt/tljh/user/lib/python3.7/site-packages/ipykernel_launcher.py:1: PerformanceWarning: indexing past lexsort depth may impact performance.\n \"\"\"Entry point for launching an IPython kernel.\n"
],
[
"Ds.index.names",
"_____no_output_____"
]
],
[
[
"### Compute the features",
"_____no_output_____"
]
],
[
[
"feature_columns = [\"delta_lop\",\"delta_hillside\",\"nfrac_xstar_lop\",\"nfrac_xstar_hillside\",\"diameter_lop\",\"diameter_hillside\"]\n\ndef compute_features(D,rankings,top_k):\n top_teams = list(rankings.sort_values().index[:top_k])\n D = D.loc[top_teams,top_teams]\n \n delta_lop,details_lop = pyrankability.rank.solve(D.fillna(0),method='lop',cont=True)\n\n x = pd.DataFrame(details_lop['x'],index=D.index,columns=D.columns)\n r = x.sum(axis=0)\n order = np.argsort(r)\n xstar = x.iloc[order,:].iloc[:,order]\n xstar.loc[:,:] = pyrankability.common.threshold_x(xstar.values)\n inxs = np.triu_indices(len(xstar),k=1)\n xstar_upper = xstar.values[inxs[0],inxs[1]]\n nfrac_upper_lop = sum((xstar_upper > 0) & (xstar_upper < 1))\n \n top_teams = xstar.columns[:top_k]\n \n k_two_distant,details_two_distant = pyrankability.search.solve_pair_max_tau(D.fillna(0),method='lop',cont=False,verbose=False)\n d_lop = details_two_distant['tau']\n \n delta_hillside,details_hillside = pyrankability.rank.solve(D,method='hillside',cont=True)\n \n x = pd.DataFrame(details_hillside['x'],index=D.index,columns=D.columns)\n r = x.sum(axis=0)\n order = np.argsort(r)\n xstar = x.iloc[order,:].iloc[:,order]\n xstar.loc[:,:] = pyrankability.common.threshold_x(xstar.values)\n inxs = np.triu_indices(len(xstar),k=1)\n xstar_upper = xstar.values[inxs[0],inxs[1]]\n nfrac_upper_hillside = sum((xstar_upper > 0) & (xstar_upper < 1))\n \n top_teams = xstar.columns[:top_k]\n \n k_two_distant,details_two_distant = pyrankability.search.solve_pair_max_tau(D,method='hillside',verbose=False,cont=False)\n d_hillside = details_two_distant['tau']\n \n features = pd.Series([delta_lop,delta_hillside,2*nfrac_upper_lop,2*nfrac_upper_hillside,d_lop,d_hillside],index=feature_columns)\n\n return features",
"_____no_output_____"
],
[
"best_pred_df = best_pred_df.reset_index()\nbest_pred_df['frac_key'] = \"frac=\"+best_pred_df['frac'].astype(str)\nbest_pred_df",
"_____no_output_____"
],
[
"def create_features(Ds,best_pred_df,top_k):\n index_cols = list(Ds.index.names)+[\"Method\",\"Construction\"]\n X = pd.DataFrame(columns=index_cols + feature_columns)\n X.set_index(index_cols,inplace=True)\n for index,row in tqdm(Ds.iterrows()):\n year,frac_key,dt,st,iw,ran = index\n frac = float(frac_key.split(\"=\")[1])\n spec_best_pred_df = best_pred_df.set_index(list(Ds.index.names)).loc[[(year,frac_key,dt,st,iw,ran)]]\n sum_D = None\n for i,D in enumerate(Ds.loc[(year,frac_key,dt,st,iw,ran),\"D\"]):\n if sum_D is None:\n sum_D = D\n else:\n sum_D = sum_D.add(iw*D,fill_value=0)\n if i == 0:\n construction = \"Direct\"\n elif i == 1:\n construction = \"Indirect\"\n else:\n raise Exception(\"Error\")\n methods = spec_best_pred_df[\"Method\"].unique()\n for method in methods:\n rankings = spec_best_pred_df.set_index('Method').loc[method,'rankings']\n features = compute_features(D,rankings,top_k)\n features.name = tuple(list(index)+[method,construction])\n X = X.append(features)\n construction = \"Both\"\n methods = spec_best_pred_df[\"Method\"].unique()\n for method in methods:\n rankings = spec_best_pred_df.set_index('Method').loc[method,'rankings']\n features = compute_features(sum_D,rankings,top_k)\n features.name = tuple(list(index)+[method,construction])\n X = X.append(features)\n return X",
"_____no_output_____"
],
[
"X = create_features(Ds,best_pred_df.reset_index(),top_k)",
"\n\n\n\n\n\n\n\n\n\n\n\n\n0it [00:00, ?it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n1it [00:00, 1.06it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n2it [00:01, 1.26it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n3it [00:02, 1.23it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n4it [00:02, 1.34it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n5it [00:03, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n6it [00:04, 1.53it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n7it [00:04, 1.40it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n8it [00:05, 1.57it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n9it [00:06, 1.47it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n10it [00:06, 1.63it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n11it [00:07, 1.53it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n12it [00:07, 1.63it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n13it [00:08, 1.56it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n14it [00:09, 1.54it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n15it [00:10, 1.44it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n16it [00:10, 1.64it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n17it [00:11, 1.52it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n18it [00:11, 1.68it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n19it [00:12, 1.57it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n20it [00:12, 1.74it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n21it [00:13, 1.52it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n22it [00:14, 1.36it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n23it [00:15, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n24it [00:15, 1.52it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n25it [00:16, 1.38it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n26it [00:17, 1.56it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n27it [00:17, 1.52it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n28it [00:18, 1.68it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n29it [00:19, 1.53it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n30it [00:19, 1.68it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n31it [00:20, 1.51it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n32it [00:20, 1.64it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n33it [00:21, 1.54it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n34it [00:21, 1.70it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n35it [00:22, 1.44it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n36it [00:23, 1.62it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n37it [00:24, 1.44it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n38it [00:24, 1.53it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n39it [00:25, 1.49it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n40it [00:25, 1.64it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n41it [00:26, 1.40it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n42it [00:27, 1.55it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n43it [00:28, 1.49it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n44it [00:28, 1.66it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n45it [00:29, 1.59it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n46it [00:29, 1.75it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n47it [00:30, 1.64it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n48it [00:30, 1.80it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n49it [00:31, 1.68it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n50it [00:31, 1.84it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n51it [00:32, 1.57it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n52it [00:33, 1.71it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n53it [00:33, 1.65it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n54it [00:34, 1.80it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n55it [00:35, 1.56it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n56it [00:36, 1.40it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n57it [00:37, 1.20it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n58it [00:37, 1.39it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n59it [00:38, 1.27it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n60it [00:39, 1.46it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n61it [00:40, 1.30it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n62it [00:40, 1.49it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n63it [00:41, 1.34it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n64it [00:41, 1.45it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n65it [00:42, 1.42it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n66it [00:43, 1.42it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n67it [00:44, 1.37it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n68it [00:44, 1.38it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n69it [00:45, 1.29it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n70it [00:46, 1.36it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n71it [00:47, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n72it [00:47, 1.53it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n73it [00:48, 1.42it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n74it [00:48, 1.56it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n75it [00:49, 1.49it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n76it [00:50, 1.39it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n77it [00:51, 1.11it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n78it [00:52, 1.26it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n79it [00:53, 1.25it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n80it [00:53, 1.36it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n81it [00:54, 1.26it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n82it [00:55, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n83it [00:56, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n84it [00:56, 1.54it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n85it [00:57, 1.38it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n86it [00:58, 1.45it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n87it [00:58, 1.37it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n88it [00:59, 1.53it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n89it [01:00, 1.31it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n90it [01:00, 1.41it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n91it [01:02, 1.19it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n92it [01:02, 1.38it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n93it [01:03, 1.34it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n94it [01:03, 1.46it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n95it [01:04, 1.32it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n96it [01:05, 1.38it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n97it [01:06, 1.21it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n98it [01:07, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n99it [01:07, 1.31it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n100it [01:08, 1.42it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n101it [01:09, 1.32it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n102it [01:09, 1.40it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n103it [01:10, 1.28it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n104it [01:11, 1.47it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n105it [01:12, 1.29it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n106it [01:12, 1.34it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n107it [01:13, 1.36it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n108it [01:14, 1.51it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n109it [01:14, 1.40it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n110it [01:15, 1.42it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n111it [01:16, 1.37it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n112it [01:17, 1.39it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n113it [01:18, 1.21it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n114it [01:18, 1.37it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n115it [01:19, 1.27it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n116it [01:20, 1.39it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n117it [01:20, 1.41it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n118it [01:21, 1.58it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n119it [01:22, 1.51it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n120it [01:22, 1.57it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n121it [01:23, 1.43it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n122it [01:24, 1.55it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n123it [01:24, 1.41it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n124it [01:25, 1.32it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n125it [01:26, 1.22it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n126it [01:27, 1.33it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n127it [01:28, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n128it [01:28, 1.48it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n129it [01:29, 1.39it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n130it [01:30, 1.40it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n131it [01:31, 1.11it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n132it [01:31, 1.30it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n133it [01:32, 1.34it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n134it [01:33, 1.41it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n135it [01:33, 1.41it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n136it [01:34, 1.37it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n137it [01:35, 1.28it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n138it [01:36, 1.46it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n139it [01:37, 1.19it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n140it [01:37, 1.34it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n141it [01:38, 1.24it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n142it [01:39, 1.44it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n143it [01:39, 1.41it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n144it [01:40, 1.52it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n145it [01:41, 1.38it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n146it [01:41, 1.50it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n147it [01:43, 1.24it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n148it [01:43, 1.39it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n149it [01:44, 1.19it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n150it [01:45, 1.28it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n151it [01:46, 1.28it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n152it [01:46, 1.43it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n153it [01:47, 1.40it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n154it [01:47, 1.46it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n155it [01:48, 1.30it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n156it [01:49, 1.42it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n157it [01:50, 1.37it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n158it [01:50, 1.56it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n159it [01:51, 1.27it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n160it [01:52, 1.46it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n161it [01:53, 1.29it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n162it [01:53, 1.49it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n163it [01:54, 1.32it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n164it [01:55, 1.37it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n165it [01:56, 1.24it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n166it [01:56, 1.32it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n167it [01:57, 1.21it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n168it [01:58, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n169it [01:59, 1.21it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n170it [02:00, 1.34it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n171it [02:00, 1.23it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n172it [02:01, 1.38it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n173it [02:02, 1.27it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n174it [02:03, 1.37it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n175it [02:03, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n176it [02:04, 1.52it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n177it [02:05, 1.34it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n178it [02:05, 1.50it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n179it [02:06, 1.32it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n180it [02:07, 1.37it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n181it [02:08, 1.24it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n182it [02:08, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n183it [02:09, 1.30it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n184it [02:10, 1.25it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n185it [02:11, 1.19it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n186it [02:12, 1.38it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n187it [02:12, 1.43it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n188it [02:13, 1.56it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n189it [02:14, 1.37it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n190it [02:14, 1.43it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n191it [02:15, 1.38it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n192it [02:16, 1.14it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n193it [02:17, 1.07it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n194it [02:18, 1.20it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n195it [02:19, 1.13it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n196it [02:20, 1.23it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n197it [02:20, 1.23it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n198it [02:21, 1.42it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n199it [02:22, 1.33it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n200it [02:22, 1.35it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n201it [02:23, 1.31it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n202it [02:24, 1.43it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n203it [02:25, 1.22it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n\n\n\n\n\n\n\n\n\n\n\n204it [02:26, 1.26it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A"
],
[
"X",
"_____no_output_____"
]
],
[
[
"## Refine the target dataset",
"_____no_output_____"
]
],
[
[
"target = problem['target'].groupby(['frac1','frac2','Method','Year','direct_thres','spread_thres','weight_indirect'])[target_column].mean().to_frame()\ntarget",
"_____no_output_____"
],
[
"X_for_join = X.copy().reset_index()\nX_for_join['frac1']= X_for_join['frac_key'].str.replace(\"frac=\",\"\").astype(float)\nX_for_join",
"_____no_output_____"
],
[
"target",
"_____no_output_____"
],
[
"Xy = target.reset_index().set_index(['Method','frac1','Year','direct_thres','spread_thres','weight_indirect']).join(X_for_join.set_index(['Method','frac1','Year','direct_thres','spread_thres','weight_indirect'])).dropna()\nXy = Xy.reset_index()\nXy",
"_____no_output_____"
]
],
[
[
"## Process results",
"_____no_output_____"
]
],
[
[
"frac_pairs = [(0.5,0.6),(0.6,0.7),(0.7,0.8),(0.8,0.9),(0.9,1.)]\nsummary = None\nfor pair in frac_pairs:\n data = Xy.set_index(['frac1','frac2']).loc[pair].reset_index()\n for_corr = data.set_index(['Method','Construction',\"frac1\",\"frac2\"])\n if summary is None:\n summary = pd.DataFrame(columns=[\"frac1\",\"frac2\",\"Method\",\"Construction\"]+feature_columns).set_index(list(for_corr.index.names))\n for ix in for_corr.index.unique():\n corr_results = for_corr.loc[ix][[target_column]+feature_columns].corr()\n target_corr_results = corr_results.loc[target_column].drop(target_column)\n target_corr_results.name = ix\n summary = summary.append(target_corr_results)",
"/opt/tljh/user/lib/python3.7/site-packages/ipykernel_launcher.py:4: PerformanceWarning: indexing past lexsort depth may impact performance.\n after removing the cwd from sys.path.\n/opt/tljh/user/lib/python3.7/site-packages/ipykernel_launcher.py:9: PerformanceWarning: indexing past lexsort depth may impact performance.\n if __name__ == '__main__':\n"
],
[
"display(summary)",
"_____no_output_____"
],
[
"summary",
"_____no_output_____"
]
],
[
[
"## 0.6 to 0.7",
"_____no_output_____"
]
],
[
[
"data = Xy.set_index(['frac1','frac2']).loc[(0.6,0.7)].reset_index()\nfor_corr = data.set_index(['Method','Construction'])\nfor ix in for_corr.index.unique():\n display(pd.Series(ix,index=for_corr.index.names))\n display(for_corr.loc[ix][[target_column]+feature_columns].corr())",
"/opt/tljh/user/lib/python3.7/site-packages/ipykernel_launcher.py:1: PerformanceWarning: indexing past lexsort depth may impact performance.\n \"\"\"Entry point for launching an IPython kernel.\n"
]
],
[
[
"### 0.7 to 0.8",
"_____no_output_____"
]
],
[
[
"data = Xy.set_index(['frac1','frac2']).loc[(0.7,0.8)].reset_index()\nfor_corr = data.set_index(['Method'])\nfor ix in for_corr.index.unique():\n display(pd.Series(ix,index=for_corr.index.names))\n display(for_corr.loc[ix][[target_column]+feature_columns].corr())",
"/opt/tljh/user/lib/python3.7/site-packages/ipykernel_launcher.py:1: PerformanceWarning: indexing past lexsort depth may impact performance.\n \"\"\"Entry point for launching an IPython kernel.\n"
]
],
[
[
"### 0.8 to 0.9",
"_____no_output_____"
]
],
[
[
"data = Xy.set_index(['frac1','frac2']).loc[(0.8,0.9)].reset_index()\nfor_corr = data.set_index(['Method'])\nfor ix in for_corr.index.unique():\n display(pd.Series(ix,index=for_corr.index.names))\n display(for_corr.loc[ix][[target_column]+feature_columns].corr())",
"/opt/tljh/user/lib/python3.7/site-packages/ipykernel_launcher.py:1: PerformanceWarning: indexing past lexsort depth may impact performance.\n \"\"\"Entry point for launching an IPython kernel.\n"
]
],
[
[
"### 0.9 to 1.",
"_____no_output_____"
]
],
[
[
"data = Xy.set_index(['frac1','frac2']).loc[(0.9,1.)].reset_index()\nfor_corr = data.set_index(['Method'])\nfor ix in for_corr.index.unique():\n display(pd.Series(ix,index=for_corr.index.names))\n display(for_corr.loc[ix][[target_column]+feature_columns].corr())",
"/opt/tljh/user/lib/python3.7/site-packages/ipykernel_launcher.py:1: PerformanceWarning: indexing past lexsort depth may impact performance.\n \"\"\"Entry point for launching an IPython kernel.\n"
],
[
"for_corr = data.set_index(['Method','direct_thres','spread_thres','weight_indirect'])\nfor_display = pd.DataFrame(columns=feature_columns+list(for_corr.index.names))\nfor_display.set_index(list(for_corr.index.names),inplace=True)\nfor ix in for_corr.index.unique():\n dt = for_corr.loc[ix][[target_column]+feature_columns].corr().loc[target_column,feature_columns]\n dt.name = ix\n for_display = for_display.append(dt)",
"/opt/tljh/user/lib/python3.7/site-packages/ipykernel_launcher.py:5: PerformanceWarning: indexing past lexsort depth may impact performance.\n \"\"\"\n"
],
[
"for_display.T",
"_____no_output_____"
],
[
"print(for_display.T.to_latex())",
"\\begin{tabular}{lrr}\n\\toprule\nMethod & Massey & Colley \\\\\ndirect\\_thres & 0.0 & 3.0 \\\\\nspread\\_thres & 3.0 & 3.0 \\\\\nweight\\_indirect & 0.25 & 0.00 \\\\\n\\midrule\ndelta\\_lop & -0.181122 & -0.045966 \\\\\ndelta\\_hillside & -0.118407 & 0.284547 \\\\\nnfrac\\_xstar\\_lop & 0.067466 & -0.065937 \\\\\nnfrac\\_xstar\\_hillside & -0.087980 & 0.058396 \\\\\ndiameter\\_lop & -0.079867 & 0.376589 \\\\\ndiameter\\_hillside & 0.421510 & 0.102595 \\\\\n\\bottomrule\n\\end{tabular}\n\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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4a38fe45e60d4668f5f091c9d7ba5207a2ce9b53
| 74,826 |
ipynb
|
Jupyter Notebook
|
notebooks/jupyter_themes_tester.ipynb
|
mrola/jupyter_themes_testone
|
ee20d9b130a8601ea45e7ecd63d7479aa3462d26
|
[
"MIT"
] | 1 |
2018-05-30T13:14:02.000Z
|
2018-05-30T13:14:02.000Z
|
notebooks/jupyter_themes_tester.ipynb
|
mrola/jupyter_themes_testone
|
ee20d9b130a8601ea45e7ecd63d7479aa3462d26
|
[
"MIT"
] | null | null | null |
notebooks/jupyter_themes_tester.ipynb
|
mrola/jupyter_themes_testone
|
ee20d9b130a8601ea45e7ecd63d7479aa3462d26
|
[
"MIT"
] | null | null | null | 122.866995 | 58,152 | 0.860115 |
[
[
[
"<div align=\"Right\"><font size=\"1\">https://github.com/mrola/jupyter_themes_preview<br>Ola Söderström - 2018</font></div>",
"_____no_output_____"
],
[
"-----\n\n<p align=\"center\"><font size=\"6\">Jupyter notebook for testing out different themes</font></p>\n\n-----",
"_____no_output_____"
],
[
"# import libs",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"import os\nimport sys\nimport numpy as np\nimport pandas as pd\n\nimport seaborn as sns\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom IPython.core.display import display, HTML\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"",
"_____no_output_____"
]
],
[
[
"## Display version info",
"_____no_output_____"
]
],
[
[
"try:\n %load_ext version_information\n %version_information wget, pandas, numpy\nexcept ModuleNotFoundError:\n print(\"Module \\\"version_information\\\" not found, install using \\\"pip install version_information\\\"\")\n pass",
"_____no_output_____"
]
],
[
[
"## Check requirements",
"_____no_output_____"
]
],
[
[
"if not (sys.version_info.major > 2 and sys.version_info.minor > 2):\n print(\"Notebook requires Python 3.2 or higher\")",
"_____no_output_____"
]
],
[
[
"# Try new style css",
"_____no_output_____"
],
[
"## Fetch css and store as new profile",
"_____no_output_____"
]
],
[
[
"def mynewstyle(new_style_url, profilename=\"newcoolprofile\"):\n '''Creates directory and custom.css for new notebook style.\n \n Run HTML command displayed at the end of execution to apply new style.\n <style> tags will be inserted if missing.\n To revert to default style, comment out HTML command using \"#\".\n \n Parameters:\n new_style_url : URL to css file to download\n profilename : Name of new profile (arbitrary)\n '''\n \n use_new_style = True\n\n print(\"Will use {}\".format(os.path.basename(new_style_url)))\n m = !ipython locate profile\n print(\"{:35} {}\".format(\"Default profile location:\", m[0])) \n\n !ipython profile create $profilename\n m1 = !ipython locate profile $profilename\n print(\"{:35} {}\".format(\"New profile directory created\", m1[0]))\n\n p=!ipython locate profile $profilename\n p = p[0] + '/static/custom/'\n\n if os.path.exists(p) is True:\n print(\"{:35} {}\".format(\"Directory already exists:\", p))\n else:\n print(\"Creating {}\".format(p))\n os.makedirs(p, exist_ok=True)\n\n ccss = p + 'custom.css'\n \n print()\n !wget $new_style_url -nv -O $ccss\n \n styletag = False\n with open(ccss, 'r+') as f:\n for line in f.readlines():\n if 'DOCTYPE' in line:\n print(\"This appears to be a html document, need standalone css.\")\n return\n elif '<style>' in line:\n styletag = True \n break\n \n if styletag is False:\n# print(\"\\nHTML <style> tags appears to be missing in custom.css, will add...\")\n !sed -i '1s/^/\\<style\\>/' $ccss\n !echo \"<\\style>\" >> $ccss\n\n html_line = 'HTML(open(\\'{}\\', \\'r\\').read())'.format(ccss)\n print(\"\\nNow you need to execute the follwing line in single cell: \\n {}\".format(html_line))",
"_____no_output_____"
]
],
[
[
"### Set URL",
"_____no_output_____"
],
[
"Just some random themes I picked up for testing.",
"_____no_output_____"
]
],
[
[
"#new_style_url='https://raw.githubusercontent.com/dunovank/jupyter-themes/master/jupyterthemes/styles/compiled/monokai.css'\nnew_style_url='https://raw.githubusercontent.com/neilpanchal/spinzero-jupyter-theme/master/custom.css'\nprint(\"Will be using css from {}\".format(new_style_url))",
"Will be using css from https://raw.githubusercontent.com/neilpanchal/spinzero-jupyter-theme/master/custom.css\n"
]
],
[
[
"### Run script",
"_____no_output_____"
]
],
[
[
"mynewstyle(new_style_url, profilename=\"newprofile_34\")",
"Will use custom.css\nDefault profile location: /home/ola/.ipython/profile_default\nNew profile directory created /home/ola/.ipython/profile_newprofile_34\nDirectory already exists: /home/ola/.ipython/profile_newprofile_34/static/custom/\n\n2018-05-23 13:18:04 URL:https://raw.githubusercontent.com/neilpanchal/spinzero-jupyter-theme/master/custom.css [13315/13315] -> \"/home/ola/.ipython/profile_newprofile_34/static/custom/custom.css\" [1]\n\nNow you need to execute the follwing line in single cell: \n HTML(open('/home/ola/.ipython/profile_newprofile_34/static/custom/custom.css', 'r').read())\n"
]
],
[
[
"## Activate new style",
"_____no_output_____"
]
],
[
[
"HTML(open('/home/ola/.ipython/profile_newprofile_34/static/custom/custom.css', 'r').read())",
"_____no_output_____"
]
],
[
[
"# Check style on some random stuff",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),columns=['a', 'b', 'c', 'd', 'e'])\ndf.loc[0, 'a'] = \"This is some text\"\ndf",
"_____no_output_____"
]
],
[
[
"## This is heading 2",
"_____no_output_____"
],
[
"### This is heading 3",
"_____no_output_____"
],
[
"This is markdown text.",
"_____no_output_____"
],
[
"# Viz",
"_____no_output_____"
]
],
[
[
"def sinplot(flip=1):\n x = np.linspace(0, 14, 100)\n for i in range(1, 7):\n plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)",
"_____no_output_____"
],
[
"sinplot()\nsns.set_style(\"ticks\")\nsns.despine(offset=10, trim=True)",
"_____no_output_____"
]
],
[
[
"# Setting individual styles using display(HTML)",
"_____no_output_____"
]
],
[
[
"display(HTML(\"<style>.cell { font-size: 12px; width:900px }</style>\"))\ndisplay(HTML(\"<style>.input { margin-top:2em, margin-bottom:2em }</style>\"))\n#display(HTML(\"<style>.div.output_wrapper { margin-top:2em, margin-bottom:2em }</style>\"))\n#display(HTML(\"<style>.rendered_html { background-color: white; }</style>\"))\n#display(HTML(\"<style>.text_cell_render { font-size: 15px; }</style>\"))\n#display(HTML(\"<style>.text_cell { font-size: 15px; }</style>\"))\n#display(HTML(\"<style>.cell { font-size: 12px; max-width:000px }</style>\"))\n#display(HTML(\"<style>.CodeMirror { background-color: #2b303b; }</style>\"))\n#display(HTML(\"<style>.cell { background-color: #2b303b; }</style>\"))",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a390a1e388c0a129982a06a156210adeda91e4a
| 51,386 |
ipynb
|
Jupyter Notebook
|
nbs/course/lesson7-human-numbers.ipynb
|
rbracco/fastai2
|
2f72da76d37ad4fd831ba48ea9fb2b3be4ec1723
|
[
"Apache-2.0"
] | null | null | null |
nbs/course/lesson7-human-numbers.ipynb
|
rbracco/fastai2
|
2f72da76d37ad4fd831ba48ea9fb2b3be4ec1723
|
[
"Apache-2.0"
] | null | null | null |
nbs/course/lesson7-human-numbers.ipynb
|
rbracco/fastai2
|
2f72da76d37ad4fd831ba48ea9fb2b3be4ec1723
|
[
"Apache-2.0"
] | null | null | null | 30.696535 | 470 | 0.460028 |
[
[
[
"# Human numbers",
"_____no_output_____"
]
],
[
[
"from fastai2.basics import *\nfrom fastai2.text.all import *\nfrom fastai2.callback.all import *",
"_____no_output_____"
],
[
"bs=64",
"_____no_output_____"
]
],
[
[
"## Data",
"_____no_output_____"
]
],
[
[
"path = untar_data(URLs.HUMAN_NUMBERS)\npath.ls()",
"_____no_output_____"
],
[
"def readnums(d): return ', '.join(o.strip() for o in open(path/d).readlines())",
"_____no_output_____"
],
[
"train_txt = readnums('train.txt'); train_txt[:80]",
"_____no_output_____"
],
[
"valid_txt = readnums('valid.txt'); valid_txt[-80:]",
"_____no_output_____"
],
[
"train_tok = tokenize1(train_txt)\nvalid_tok = tokenize1(valid_txt)",
"_____no_output_____"
],
[
"dsrc = DataSource([train_tok, valid_tok], tfms=Numericalize, dl_type=LMDataLoader, splits=[[0], [1]])",
"_____no_output_____"
],
[
"dbunch = dsrc.databunch(bs=bs, val_bs=bs, after_batch=Cuda())",
"_____no_output_____"
],
[
"dsrc.show((dsrc.train[0][0][:80],))",
"xxbos one , two , three , four , five , six , seven , eight , nine , ten , eleven , twelve , thirteen , fourteen , fifteen , sixteen , seventeen , eighteen , nineteen , twenty , twenty one , twenty two , twenty three , twenty four , twenty five , twenty six , twenty seven , twenty eight , twenty nine , thirty , thirty one , thirty two , thirty three , thirty\n"
],
[
"len(dsrc.valid[0][0])",
"_____no_output_____"
],
[
"len(dbunch.valid_dl)",
"_____no_output_____"
],
[
"dbunch.seq_len, len(dbunch.valid_dl)",
"_____no_output_____"
],
[
"13017/72/bs",
"_____no_output_____"
],
[
"it = iter(dbunch.valid_dl)\nx1,y1 = next(it)\nx2,y2 = next(it)\nx3,y3 = next(it)\nit.close()",
"_____no_output_____"
],
[
"x1.numel()+x2.numel()+x3.numel()",
"_____no_output_____"
]
],
[
[
"This is the closes multiple of 64 below 13017",
"_____no_output_____"
]
],
[
[
"x1.shape,y1.shape",
"_____no_output_____"
],
[
"x2.shape,y2.shape",
"_____no_output_____"
],
[
"x1[0]",
"_____no_output_____"
],
[
"y1[0]",
"_____no_output_____"
],
[
"v = dbunch.vocab",
"_____no_output_____"
],
[
"' '.join([v[x] for x in x1[0]])",
"_____no_output_____"
],
[
"' '.join([v[x] for x in y1[0]])",
"_____no_output_____"
],
[
"' '.join([v[x] for x in x2[0]])",
"_____no_output_____"
],
[
"' '.join([v[x] for x in x3[0]])",
"_____no_output_____"
],
[
"' '.join([v[x] for x in x1[1]])",
"_____no_output_____"
],
[
"' '.join([v[x] for x in x2[1]])",
"_____no_output_____"
],
[
"' '.join([v[x] for x in x3[1]])",
"_____no_output_____"
],
[
"' '.join([v[x] for x in x3[-1]])",
"_____no_output_____"
],
[
"dbunch.valid_dl.show_batch()",
"_____no_output_____"
]
],
[
[
"## Single fully connected model",
"_____no_output_____"
]
],
[
[
"dbunch = dsrc.databunch(bs=bs, seq_len=3, after_batch=Cuda)",
"_____no_output_____"
],
[
"x,y = dbunch.one_batch()\nx.shape,y.shape",
"_____no_output_____"
],
[
"nv = len(v); nv",
"_____no_output_____"
],
[
"nh=64",
"_____no_output_____"
],
[
"def loss4(input,target): return F.cross_entropy(input, target[:,-1])\ndef acc4 (input,target): return accuracy(input, target[:,-1])",
"_____no_output_____"
],
[
"class Model0(Module):\n def __init__(self):\n self.i_h = nn.Embedding(nv,nh) # green arrow\n self.h_h = nn.Linear(nh,nh) # brown arrow\n self.h_o = nn.Linear(nh,nv) # blue arrow\n self.bn = nn.BatchNorm1d(nh)\n \n def forward(self, x):\n h = self.bn(F.relu(self.h_h(self.i_h(x[:,0]))))\n if x.shape[1]>1:\n h = h + self.i_h(x[:,1])\n h = self.bn(F.relu(self.h_h(h)))\n if x.shape[1]>2:\n h = h + self.i_h(x[:,2])\n h = self.bn(F.relu(self.h_h(h)))\n return self.h_o(h)",
"_____no_output_____"
],
[
"learn = Learner(dbunch, Model0(), loss_func=loss4, metrics=acc4)",
"_____no_output_____"
],
[
"learn.fit_one_cycle(6, 1e-4)",
"_____no_output_____"
]
],
[
[
"## Same thing with a loop",
"_____no_output_____"
]
],
[
[
"class Model1(Module):\n def __init__(self):\n self.i_h = nn.Embedding(nv,nh) # green arrow\n self.h_h = nn.Linear(nh,nh) # brown arrow\n self.h_o = nn.Linear(nh,nv) # blue arrow\n self.bn = nn.BatchNorm1d(nh)\n \n def forward(self, x):\n h = torch.zeros(x.shape[0], nh).to(device=x.device)\n for i in range(x.shape[1]):\n h = h + self.i_h(x[:,i])\n h = self.bn(F.relu(self.h_h(h)))\n return self.h_o(h)",
"_____no_output_____"
],
[
"learn = Learner(dbunch, Model1(), loss_func=loss4, metrics=acc4)",
"_____no_output_____"
],
[
"learn.fit_one_cycle(6, 1e-4)",
"_____no_output_____"
]
],
[
[
"## Multi fully connected model",
"_____no_output_____"
]
],
[
[
"dbunch = dsrc.databunch(bs=bs, seq_len=20, after_batch=Cuda)",
"_____no_output_____"
],
[
"x,y = dbunch.one_batch()\nx.shape,y.shape",
"_____no_output_____"
],
[
"class Model2(Module):\n def __init__(self):\n self.i_h = nn.Embedding(nv,nh)\n self.h_h = nn.Linear(nh,nh)\n self.h_o = nn.Linear(nh,nv)\n self.bn = nn.BatchNorm1d(nh)\n \n def forward(self, x):\n h = torch.zeros(x.shape[0], nh).to(device=x.device)\n res = []\n for i in range(x.shape[1]):\n h = h + self.i_h(x[:,i])\n h = F.relu(self.h_h(h))\n res.append(self.h_o(self.bn(h)))\n return torch.stack(res, dim=1)",
"_____no_output_____"
],
[
"learn = Learner(dbunch, Model2(), loss_func=CrossEntropyLossFlat(), metrics=accuracy)",
"_____no_output_____"
],
[
"learn.fit_one_cycle(10, 1e-4, pct_start=0.1)",
"_____no_output_____"
]
],
[
[
"## Maintain state",
"_____no_output_____"
]
],
[
[
"class Model3(Module):\n def __init__(self):\n self.i_h = nn.Embedding(nv,nh)\n self.h_h = nn.Linear(nh,nh)\n self.h_o = nn.Linear(nh,nv)\n self.bn = nn.BatchNorm1d(nh)\n self.h = torch.zeros(bs, nh).cuda()\n \n def forward(self, x):\n res = []\n if x.shape[0]!=self.h.shape[0]: self.h = torch.zeros(x.shape[0], nh).cuda()\n h = self.h\n for i in range(x.shape[1]):\n h = h + self.i_h(x[:,i])\n h = F.relu(self.h_h(h))\n res.append(self.bn(h))\n self.h = h.detach()\n res = torch.stack(res, dim=1)\n res = self.h_o(res)\n return res\n \n def reset(self): self.f.h = torch.zeros(bs, nh).cuda()",
"_____no_output_____"
],
[
"learn = Learner(dbunch, Model3(), metrics=accuracy, loss_func=CrossEntropyLossFlat())",
"_____no_output_____"
],
[
"learn.fit_one_cycle(20, 3e-3)",
"_____no_output_____"
]
],
[
[
"## nn.RNN",
"_____no_output_____"
]
],
[
[
"class Model4(Module):\n def __init__(self):\n self.i_h = nn.Embedding(nv,nh)\n self.rnn = nn.RNN(nh,nh, batch_first=True)\n self.h_o = nn.Linear(nh,nv)\n self.bn = BatchNorm1dFlat(nh)\n self.h = torch.zeros(1, bs, nh).cuda()\n \n def forward(self, x):\n if x.shape[0]!=self.h.shape[1]: self.h = torch.zeros(1, x.shape[0], nh).cuda()\n res,h = self.rnn(self.i_h(x), self.h)\n self.h = h.detach()\n return self.h_o(self.bn(res))",
"_____no_output_____"
],
[
"learn = Learner(dbunch, Model4(), loss_func=CrossEntropyLossFlat(), metrics=accuracy)",
"_____no_output_____"
],
[
"learn.fit_one_cycle(20, 3e-3)",
"_____no_output_____"
]
],
[
[
"## 2-layer GRU",
"_____no_output_____"
]
],
[
[
"class Model5(Module):\n def __init__(self):\n self.i_h = nn.Embedding(nv,nh)\n self.rnn = nn.GRU(nh, nh, 2, batch_first=True)\n self.h_o = nn.Linear(nh,nv)\n self.bn = BatchNorm1dFlat(nh)\n self.h = torch.zeros(2, bs, nh).cuda()\n \n def forward(self, x):\n if x.shape[0]!=self.h.shape[1]: self.h = torch.zeros(2, x.shape[0], nh).cuda()\n res,h = self.rnn(self.i_h(x), self.h)\n self.h = h.detach()\n return self.h_o(self.bn(res))",
"_____no_output_____"
],
[
"learn = Learner(dbunch, Model5(), loss_func=CrossEntropyLossFlat(), metrics=accuracy)",
"_____no_output_____"
],
[
"learn.fit_one_cycle(10, 1e-2)",
"_____no_output_____"
]
],
[
[
"## fin",
"_____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",
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
4a3927b24946bde7e01e0b363c25963c716ae9e9
| 81,211 |
ipynb
|
Jupyter Notebook
|
notebooks/image_search1.ipynb
|
aksroa/Visual-portfolio
|
b9cb5ce68682923ed4cad8ee7ba0cf62b95febee
|
[
"MIT"
] | null | null | null |
notebooks/image_search1.ipynb
|
aksroa/Visual-portfolio
|
b9cb5ce68682923ed4cad8ee7ba0cf62b95febee
|
[
"MIT"
] | null | null | null |
notebooks/image_search1.ipynb
|
aksroa/Visual-portfolio
|
b9cb5ce68682923ed4cad8ee7ba0cf62b95febee
|
[
"MIT"
] | null | null | null | 65.282154 | 116 | 0.608982 |
[
[
[
"# I start by importing the packages\nimport os\nimport sys\nsys.path.append(os.path.join(\"..\"))\nimport cv2\nimport numpy as np\nsys.path.append(os.path.join(\"..\"))\nfrom utils.imutils import jimshow\nfrom utils.imutils import jimshow_channel\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nimport pandas as pd",
"_____no_output_____"
],
[
"def jimshow_channel(image, title=False):\n \"\"\"\n Modified jimshow() to plot individual channels\n \"\"\"\n # Acquire default dots per inch value of matplotlib\n dpi = mpl.rcParams['figure.dpi']\n height, width = image.shape\n figsize = width / float(dpi), height / float(dpi)\n plt.figure(figsize=figsize)\n plt.imshow(image, cmap='gray')\n if title:\n plt.title(title)\n plt.axis('off')\n plt.show()",
"_____no_output_____"
],
[
"os.getcwd()",
"_____no_output_____"
],
[
"# Loading the target image\ntarget_image = cv2.imread(os.path.join(\"..\", \"data\", \"jpg\",\"image_0001.jpg\"))",
"_____no_output_____"
],
[
"# Making the path to the images\nfilepath = os.path.join(\"..\", \"data\", \"jpg\")",
"_____no_output_____"
],
[
"# I create the histogram for the target image\nhist1 = cv2.calcHist([target_image], [0,1,2], None, [8,8,8], [0,256, 0,256, 0,256])",
"_____no_output_____"
],
[
"# I create an empty list\nlist_of_comparisons = []",
"_____no_output_____"
],
[
"# Creates a loop that reads all the images in the folder, creates a histogram for these and calculates the \n# differnces between these images and the target image\nfor filename in Path(filepath).glob(\"*.jpg\"):\n comparison_image = cv2.imread(str(filename))\n hist2 = cv2.calcHist([comparison_image], [0,1,2], None, [8,8,8], [0,256, 0,256, 0,256])\n distance = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CHISQR)\n list_of_comparisons.append((filename, distance))\n",
"_____no_output_____"
],
[
"#Showing the list with filenames and distances\nlist_of_comparisons",
"_____no_output_____"
],
[
"# Making a list of filenames\nfilenames = [os.path.basename(image_name) for image_name in Path(filepath).glob(\"*.jpg\")]\n# Creating csv file with filenames and distance\ndf = pd.DataFrame(data={\"filename\": filenames, \"distance\": distance})\n\n# Creating new df without main image and its distance value, since I don't want to compare it to itself\ndf = df[df.filename != 'image_0310.jpg']\n# Saving df as .csv file\noutpath = os.path.join(\"..\", \"data\", \"image_distance.csv\")\ndf.to_csv(outpath, sep=',', index= False)",
"_____no_output_____"
],
[
"distance",
"_____no_output_____"
],
[
"# Looking for lowest distance (most similar image)\ndf.min()[\"distance\"]",
"_____no_output_____"
],
[
"#finding the image name\nprint (df.loc[df[\"distance\"] == 347200.09])",
"_____no_output_____"
],
[
"#showing the closest image\nclosest_image = cv2.imread(os.path.join(\"..\", \"data\", \"jpg\", \"image_0090.jpg\"))\njimshow(closest_image, \"Closest image\")",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a3932300bb768c6af94a9df64a9416f98b3ff87
| 81,806 |
ipynb
|
Jupyter Notebook
|
chapter02_supervised-learning/linear-regression-scratch.ipynb
|
vishaalkapoor/mxnet-the-straight-dope
|
8b69042bae8bb9ab2fa73a357ab4cc0111a9b92e
|
[
"Apache-2.0"
] | 3 |
2018-09-03T14:34:56.000Z
|
2018-12-18T10:08:29.000Z
|
chapter02_supervised-learning/linear-regression-scratch.ipynb
|
vishaalkapoor/mxnet-the-straight-dope
|
8b69042bae8bb9ab2fa73a357ab4cc0111a9b92e
|
[
"Apache-2.0"
] | null | null | null |
chapter02_supervised-learning/linear-regression-scratch.ipynb
|
vishaalkapoor/mxnet-the-straight-dope
|
8b69042bae8bb9ab2fa73a357ab4cc0111a9b92e
|
[
"Apache-2.0"
] | 2 |
2018-09-03T09:11:01.000Z
|
2018-09-03T14:45:22.000Z
| 117.200573 | 22,028 | 0.84253 |
[
[
[
"# Linear regression from scratch\n\nPowerful ML libraries can eliminate repetitive work, but if you rely too much on abstractions, you might never learn how neural networks really work under the hood. So for this first example, let's get our hands dirty and build everything from scratch, relying only on autograd and NDArray. First, we'll import the same dependencies as in the [autograd chapter](../chapter01_crashcourse/autograd.ipynb). We'll also import the powerful `gluon` package but in this chapter, we'll only be using it for data loading.",
"_____no_output_____"
]
],
[
[
"from __future__ import print_function\nimport mxnet as mx\nfrom mxnet import nd, autograd, gluon\nmx.random.seed(1)",
"_____no_output_____"
]
],
[
[
"## Set the context\n\nWe'll also want to specify the contexts where computation should happen. This tutorial is so simple that you could probably run it on a calculator watch. But, to develop good habits we're going to specify two contexts: one for data and one for our models. ",
"_____no_output_____"
]
],
[
[
"data_ctx = mx.cpu()\nmodel_ctx = mx.cpu()",
"_____no_output_____"
]
],
[
[
"## Linear regression\n\n\nTo get our feet wet, we'll start off by looking at the problem of regression.\nThis is the task of predicting a *real valued target* $y$ given a data point $x$.\nIn linear regression, the simplest and still perhaps the most useful approach,\nwe assume that prediction can be expressed as a *linear* combination of the input features \n(thus giving the name *linear* regression):\n\n$$\\hat{y} = w_1 \\cdot x_1 + ... + w_d \\cdot x_d + b$$\n\n\nGiven a collection of data points $X$, and corresponding target values $\\boldsymbol{y}$, \nwe'll try to find the *weight* vector $\\boldsymbol{w}$ and bias term $b$ \n(also called an *offset* or *intercept*)\nthat approximately associate data points $\\boldsymbol{x}_i$ with their corresponding labels ``y_i``. \nUsing slightly more advanced math notation, we can express the predictions $\\boldsymbol{\\hat{y}}$\ncorresponding to a collection of datapoints $X$ via the matrix-vector product:\n\n$$\\boldsymbol{\\hat{y}} = X \\boldsymbol{w} + b$$\n\n\nBefore we can get going, we will need two more things \n\n* Some way to measure the quality of the current model \n* Some way to manipulate the model to improve its quality\n\n\n### Square loss\nIn order to say whether we've done a good job, \nwe need some way to measure the quality of a model. \nGenerally, we will define a *loss function*\nthat says *how far* are our predictions from the correct answers.\nFor the classical case of linear regression, \nwe usually focus on the squared error.\nSpecifically, our loss will be the sum, over all examples, of the squared error $(y_i-\\hat{y})^2)$ on each:\n\n$$\\ell(y, \\hat{y}) = \\sum_{i=1}^n (\\hat{y}_i-y_i)^2.$$\n\n\nFor one-dimensional data, we can easily visualize the relationship between our single feature and the target variable. It's also easy to visualize a linear predictor and it's error on each example. \nNote that squared loss *heavily penalizes outliers*. For the visualized predictor below, the lone outlier would contribute most of the loss.\n\n\n\n\n### Manipulating the model\n\nFor us to minimize the error,\nwe need some mechanism to alter the model.\nWe do this by choosing values of the *parameters*\n$\\boldsymbol{w}$ and $b$.\nThis is the only job of the learning algorithm.\nTake training data ($X$, $y$) and the functional form of the model $\\hat{y} = X\\boldsymbol{w} + b$.\nLearning then consists of choosing the best possible $\\boldsymbol{w}$ and $b$ based on the available evidence.\n\n\n\n\n\n### Historical note\n\nYou might reasonably point out that linear regression is a classical statistical model.\n[According to Wikipedia](https://en.wikipedia.org/wiki/Regression_analysis#History), \nLegendre first developed the method of least squares regression in 1805,\nwhich was shortly thereafter rediscovered by Gauss in 1809. \nPresumably, Legendre, who had Tweeted about the paper several times,\nwas peeved that Gauss failed to cite his arXiv preprint. \n\n\n\n\nMatters of provenance aside, you might wonder - if Legendre and Gauss \nworked on linear regression, does that mean there were the original deep learning researchers?\nAnd if linear regression doesn't wholly belong to deep learning, \nthen why are we presenting a linear model \nas the first example in a tutorial series on neural networks? \nWell it turns out that we can express linear regression \nas the simplest possible (useful) neural network. \nA neural network is just a collection of nodes (aka neurons) connected by directed edges. \nIn most networks, we arrange the nodes into layers with each feeding its output into the layer above. \nTo calculate the value of any node, we first perform a weighted sum of the inputs (according to weights ``w``) \nand then apply an *activation function*. \nFor linear regression, we only have two layers, one corresponding to the input (depicted in orange) \nand a one-node layer (depicted in green) correspnding to the ouput.\nFor the output node the activation function is just the identity function.\n\n\n\nWhile you certainly don't have to view linear regression through the lens of deep learning, \nyou can (and we will!).\nTo ground the concepts that we just discussed in code, \nlet's actually code up a neural network for linear regression from scratch.\n\n\nTo get going, we will generate a simple synthetic dataset by sampling random data points ``X[i]`` and corresponding labels ``y[i]`` in the following manner. Out inputs will each be sampled from a random normal distribution with mean $0$ and variance $1$. Our features will be independent. Another way of saying this is that they will have diagonal covariance. The labels will be generated accoding to the *true* labeling function `y[i] = 2 * X[i][0]- 3.4 * X[i][1] + 4.2 + noise` where the noise is drawn from a random gaussian with mean ``0`` and variance ``.01``. We could express the labeling function in mathematical notation as:\n$$y = X \\cdot w + b + \\eta, \\quad \\text{for } \\eta \\sim \\mathcal{N}(0,\\sigma^2)$$ \n",
"_____no_output_____"
]
],
[
[
"num_inputs = 2\nnum_outputs = 1\nnum_examples = 10000\n\ndef real_fn(X):\n return 2 * X[:, 0] - 3.4 * X[:, 1] + 4.2\n \nX = nd.random_normal(shape=(num_examples, num_inputs), ctx=data_ctx)\nnoise = .1 * nd.random_normal(shape=(num_examples,), ctx=data_ctx)\ny = real_fn(X) + noise",
"_____no_output_____"
]
],
[
[
"Notice that each row in ``X`` consists of a 2-dimensional data point and that each row in ``Y`` consists of a 1-dimensional target value. ",
"_____no_output_____"
]
],
[
[
"print(X[0])\nprint(y[0])",
"\n[-1.22338355 2.39233518]\n<NDArray 2 @cpu(0)>\n\n[-6.09602737]\n<NDArray 1 @cpu(0)>\n"
]
],
[
[
"Note that because our synthetic features `X` live on `data_ctx` and because our noise also lives on `data_ctx`, the labels `y`, produced by combining `X` and `noise` in `real_fn` also live on `data_ctx`. \nWe can confirm that for any randomly chosen point, \na linear combination with the (known) optimal parameters \nproduces a prediction that is indeed close to the target value",
"_____no_output_____"
]
],
[
[
"print(2 * X[0, 0] - 3.4 * X[0, 1] + 4.2)",
"\n[-6.38070679]\n<NDArray 1 @cpu(0)>\n"
]
],
[
[
"We can visualize the correspondence between our second feature (``X[:, 1]``) and the target values ``Y`` by generating a scatter plot with the Python plotting package ``matplotlib``. Make sure that ``matplotlib`` is installed. Otherwise, you may install it by running ``pip2 install matplotlib`` (for Python 2) or ``pip3 install matplotlib`` (for Python 3) on your command line. \n\nIn order to plot with ``matplotlib`` we'll just need to convert ``X`` and ``y`` into NumPy arrays by using the `.asnumpy()` function. ",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nplt.scatter(X[:, 1].asnumpy(),y.asnumpy())\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Data iterators\n\nOnce we start working with neural networks, we're going to need to iterate through our data points quickly. We'll also want to be able to grab batches of ``k`` data points at a time, to shuffle our data. In MXNet, data iterators give us a nice set of utilities for fetching and manipulating data. In particular, we'll work with the simple ``DataLoader`` class, that provides an intuitive way to use an ``ArrayDataset`` for training models.\n\n\nWe can load `X` and `y` into an ArrayDataset, by calling `gluon.data.ArrayDataset(X, y)`. It's ok for `X` to be a multi-dimensional input array (say, of images) and `y` to be just a one-dimensional array of labels. The one requirement is that they have equal lengths along the first axis, i.e., `len(X) == len(y)`. \n\nGiven an `ArrayDataset`, we can create a DataLoader which will grab random batches of data from an `ArrayDataset`. We'll want to specify two arguments. First, we'll need to say the `batch_size`, i.e., how many examples we want to grab at a time. Second, we'll want to specify whether or not to shuffle the data between iterations through the dataset. ",
"_____no_output_____"
]
],
[
[
"batch_size = 4\ntrain_data = gluon.data.DataLoader(gluon.data.ArrayDataset(X, y),\n batch_size=batch_size, shuffle=True)",
"_____no_output_____"
]
],
[
[
"Once we've initialized our DataLoader (``train_data``), we can easily fetch batches by iterating over `train_data` just as if it were a Python list. You can use your favorite iterating techniques like foreach loops: `for data, label in train_data` or enumerations: `for i, (data, label) in enumerate(train_data)`. \nFirst, let's just grab one batch and break out of the loop.",
"_____no_output_____"
]
],
[
[
"for i, (data, label) in enumerate(train_data):\n print(data, label)\n break",
"\n[[-0.14732301 -1.32803488]\n [-0.56128627 0.48301753]\n [ 0.75564283 -0.12659997]\n [-0.96057719 -0.96254188]]\n<NDArray 4x2 @cpu(0)> \n[ 8.25711536 1.30587864 6.15542459 5.48825312]\n<NDArray 4 @cpu(0)>\n"
]
],
[
[
"If we run that same code again you'll notice that we get a different batch. That's because we instructed the `DataLoader` that `shuffle=True`. ",
"_____no_output_____"
]
],
[
[
"for i, (data, label) in enumerate(train_data):\n print(data, label)\n break",
"\n[[-0.59027743 -1.52694809]\n [-0.00750104 2.68466949]\n [ 1.50308061 0.54902577]\n [ 1.69129586 0.32308948]]\n<NDArray 4x2 @cpu(0)> \n[ 8.28844357 -5.07566643 5.3666563 6.52408457]\n<NDArray 4 @cpu(0)>\n"
]
],
[
[
"Finally, if we actually pass over the entire dataset, and count the number of batches, we'll find that there are 2500 batches. We expect this because our dataset has 10,000 examples and we configured the `DataLoader` with a batch size of 4.",
"_____no_output_____"
]
],
[
[
"counter = 0\nfor i, (data, label) in enumerate(train_data):\n pass\nprint(i+1)",
"2500\n"
]
],
[
[
"## Model parameters\n\nNow let's allocate some memory for our parameters and set their initial values. We'll want to initialize these parameters on the `model_ctx`. ",
"_____no_output_____"
]
],
[
[
"w = nd.random_normal(shape=(num_inputs, num_outputs), ctx=model_ctx)\nb = nd.random_normal(shape=num_outputs, ctx=model_ctx)\nparams = [w, b]",
"_____no_output_____"
]
],
[
[
"In the succeeding cells, we're going to update these parameters to better fit our data. This will involve taking the gradient (a multi-dimensional derivative) of some *loss function* with respect to the parameters. We'll update each parameter in the direction that reduces the loss. But first, let's just allocate some memory for each gradient.",
"_____no_output_____"
]
],
[
[
"for param in params:\n param.attach_grad()",
"_____no_output_____"
]
],
[
[
"## Neural networks\n\nNext we'll want to define our model. In this case, we'll be working with linear models, the simplest possible *useful* neural network. To calculate the output of the linear model, we simply multiply a given input with the model's weights (``w``), and add the offset ``b``.",
"_____no_output_____"
]
],
[
[
"def net(X):\n return mx.nd.dot(X, w) + b",
"_____no_output_____"
]
],
[
[
"Ok, that was easy.",
"_____no_output_____"
],
[
"## Loss function\n\nTrain a model means making it better and better over the course of a period of training. But in order for this goal to make any sense at all, we first need to define what *better* means in the first place. In this case, we'll use the squared distance between our prediction and the true value. ",
"_____no_output_____"
]
],
[
[
"def square_loss(yhat, y): \n return nd.mean((yhat - y) ** 2)",
"_____no_output_____"
]
],
[
[
"## Optimizer\n\nIt turns out that linear regression actually has a closed-form solution. However, most interesting models that we'll care about cannot be solved analytically. So we'll solve this problem by stochastic gradient descent. At each step, we'll estimate the gradient of the loss with respect to our weights, using one batch randomly drawn from our dataset. Then, we'll update our parameters a small amount in the direction that reduces the loss. The size of the step is determined by the *learning rate* ``lr``. ",
"_____no_output_____"
]
],
[
[
"def SGD(params, lr): \n for param in params:\n param[:] = param - lr * param.grad",
"_____no_output_____"
]
],
[
[
"## Execute training loop\n\nNow that we have all the pieces, we just need to wire them together by writing a training loop. \nFirst we'll define ``epochs``, the number of passes to make over the dataset. Then for each pass, we'll iterate through ``train_data``, grabbing batches of examples and their corresponding labels. \n\nFor each batch, we'll go through the following ritual:\n \n* Generate predictions (``yhat``) and the loss (``loss``) by executing a forward pass through the network.\n* Calculate gradients by making a backwards pass through the network (``loss.backward()``). \n* Update the model parameters by invoking our SGD optimizer. \n",
"_____no_output_____"
]
],
[
[
"epochs = 10\nlearning_rate = .0001\nnum_batches = num_examples/batch_size\n\nfor e in range(epochs):\n cumulative_loss = 0\n # inner loop\n for i, (data, label) in enumerate(train_data):\n data = data.as_in_context(model_ctx)\n label = label.as_in_context(model_ctx).reshape((-1, 1))\n with autograd.record():\n output = net(data)\n loss = square_loss(output, label)\n loss.backward()\n SGD(params, learning_rate)\n cumulative_loss += loss.asscalar()\n print(cumulative_loss / num_batches)",
"24.6606138554\n9.09776815639\n3.36058844271\n1.24549788469\n0.465710770596\n0.178157229481\n0.0721970594548\n0.0331197250206\n0.0186954441286\n0.0133724625537\n"
]
],
[
[
"## Visualizing our training progess\n\nIn the succeeding chapters, we'll introduce more realistic data, fancier models, more complicated loss functions, and more. But the core ideas are the same and the training loop will look remarkably familiar. Because these tutorials are self-contained, you'll get to know this ritual quite well. In addition to updating out model, we'll often want to do some bookkeeping. Among other things, we might want to keep track of training progress and visualize it graphically. We demonstrate one slighly more sophisticated training loop below.",
"_____no_output_____"
]
],
[
[
"############################################\n# Re-initialize parameters because they \n# were already trained in the first loop\n############################################\nw[:] = nd.random_normal(shape=(num_inputs, num_outputs), ctx=model_ctx)\nb[:] = nd.random_normal(shape=num_outputs, ctx=model_ctx)\n\n############################################\n# Script to plot the losses over time\n############################################\ndef plot(losses, X, sample_size=100):\n xs = list(range(len(losses)))\n f, (fg1, fg2) = plt.subplots(1, 2)\n fg1.set_title('Loss during training')\n fg1.plot(xs, losses, '-r')\n fg2.set_title('Estimated vs real function')\n fg2.plot(X[:sample_size, 1].asnumpy(),\n net(X[:sample_size, :]).asnumpy(), 'or', label='Estimated')\n fg2.plot(X[:sample_size, 1].asnumpy(),\n real_fn(X[:sample_size, :]).asnumpy(), '*g', label='Real')\n fg2.legend()\n\n plt.show()\n\nlearning_rate = .0001\nlosses = []\nplot(losses, X)\n\nfor e in range(epochs):\n cumulative_loss = 0\n for i, (data, label) in enumerate(train_data):\n data = data.as_in_context(model_ctx)\n label = label.as_in_context(model_ctx).reshape((-1, 1))\n with autograd.record():\n output = net(data)\n loss = square_loss(output, label)\n loss.backward()\n SGD(params, learning_rate)\n cumulative_loss += loss.asscalar()\n\n print(\"Epoch %s, batch %s. Mean loss: %s\" % (e, i, cumulative_loss/num_batches))\n losses.append(cumulative_loss/num_batches)\n \nplot(losses, X)",
"_____no_output_____"
]
],
[
[
"## Conclusion \n\nYou've seen that using just mxnet.ndarray and mxnet.autograd, we can build statistical models from scratch. In the following tutorials, we'll build on this foundation, introducing the basic ideas behind modern neural networks and demonstrating the powerful abstractions in MXNet's `gluon` package for building complex models with little code. ",
"_____no_output_____"
],
[
"## Next\n[Linear regression with gluon](../chapter02_supervised-learning/linear-regression-gluon.ipynb)",
"_____no_output_____"
],
[
"For whinges or inquiries, [open an issue on GitHub.](https://github.com/zackchase/mxnet-the-straight-dope)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
4a39500ecf51a45269de1cf50fa1bb6549e67ca4
| 27,653 |
ipynb
|
Jupyter Notebook
|
Final Project (1).ipynb
|
ThrottIe/hcde-410-final
|
b89099b662a85abc6e0349a68c9e9a705414c98d
|
[
"MIT"
] | null | null | null |
Final Project (1).ipynb
|
ThrottIe/hcde-410-final
|
b89099b662a85abc6e0349a68c9e9a705414c98d
|
[
"MIT"
] | null | null | null |
Final Project (1).ipynb
|
ThrottIe/hcde-410-final
|
b89099b662a85abc6e0349a68c9e9a705414c98d
|
[
"MIT"
] | null | null | null | 50.369763 | 1,285 | 0.701949 |
[
[
[
"# Introduction",
"_____no_output_____"
],
[
"Crypocurrency is a topic that is important to discuss. With the increase in companies accepting cryptocurrency as payment, it is becoming more integral to people's lives. Due to its decentralized and anonymous nature, it eliminates the need for a governing body to dictate its value and relies purely on supply and demand (Farrel, 2015). When Bitcoin was introduced in 2009, one of its greatest benefits was that it employed a peer-to-peer transaction system that relied on cryptographic proof instead of \"trust\" (Farrel, 2015). By doing this, Bitcoin replaced human actions with mathematical algorithms. However, this system gave to rise to new problems associated with double spending and coinage protection, topics that are addressed in the background information section. Since the cryptocurrency industry is relatively new and interest has recently increased, there is little research into how groups are able to take advantage of it compared to establishing how the coin works. Furthermore, there exists many different coin varieties that employ different algorithms which significantly increases the scope of what is possible to research. In this project, I will focus on systems (BitCoin and DogeCoin) that have existed for many years and have a large cultural impact. ",
"_____no_output_____"
],
[
"### Personal Motivation",
"_____no_output_____"
],
[
"The initial motivation for proposing this project comes from my lack of previous knowledge on this issue. I decided on cryptocurrency because I wished to learn more about digital transactions, hashing algorithms and cryptography systems. In quarantine, I was heavily invested in mathematical theory but did not focus on applying a human centered perspective to what I was learning. This class has allowed me to see that data ethics is heavily important and that replacing human actions with algorithms isn't enough to remove prejudices and biases that were present before. Hence, in addition to investigating how cryptosystems work, I intend to address the question of whether having a privalged position in society allows you to take advantage of the system\n\nDue to its anonimity, there is little known about how these systems are implemented and how it impacts certain groups of individuals. In this project, I hope to uncover more about that impact and hope to uncover possible market manipulation and advantages that are given to certain Miners over others. Futhermore, the cryptocurrency industry is somewhat unregulated and crypto transactions have been used for malicious actions as a result of its anonimity. \n***",
"_____no_output_____"
],
[
"# Background Information",
"_____no_output_____"
],
[
"### What is Bitcoin?",
"_____no_output_____"
],
[
"In 2009, Satoshi Nakamoto developed the first ever decentralized cryptocurrency, a virtual method of currency exchange that functions similarly to standard currency but eliminates the need for a trusted central authority (Farrel, 2015). By getting rid of this Hierarchy, individuals and business perform transactions on a peer-to-peer network that works through digital signatures (Farrel, 2015). ",
"_____no_output_____"
],
[
"### How is it secure?",
"_____no_output_____"
],
[
"Bitcoin was developed with the intention of replacing physical objects with a \"computer file\" (Velde, 2013). It functions on the same principles as currency- exchange something of value for goods and services. However, for a physical transaction, there is a guarantee that you are giving the money to another paty and that you are receiving something in return (ignoring the issue of counterfeiting). How can we guarentee that if we exchange Bitcoin, one party is guarenteed to receive it? Futhermore, digital signatures can easily be duplicated on a computer so how are we able to guarentee that double-spending does not occur? To prevent this, Bitcoin can only be spent and received after they have been publicly recorded in a ledge, known as the \"block chain\". To transfer a coin, the transcation is first recorded in a public ledger, where a new signature is made by combining the time stamp with the digital signatures of each party (Farrel, 2015). This new signature represents the path that a coin has taken in the network and is then broadcasted to all nodes in the blockchain. \n\nTo be more precise, let Alice be the owner of a Bitcoin which is essentially a string of 1s and 0s that is stored in a physical hard drive (called the \"wallet\") (Velde, 2013). She wishes to send this coin to Bob who also has a wallet on his device (Note that these \"wallets\" are managed by an application the computer) (Velde, 2013). Then Alice's application broadcastes to a network of nodes indicating that there is a proposed transaction between Alice and Bob. Then the \"Miners\" gather the proposed transaction and attempt to add it to the block chain, which makes the transfer valid. The key for preventing fraud is to ensure that adding to the block chain is \"difficult\". As an analogy to the physical medium, think of this as saying when a merchant transfers a precious metal, it is clear that the merchant didn't \"fake\" it because of the amount of costly resources it takes to acquire it. However, it is very easy to check that it is indeed a precious metal. For Bitcoin, the process is similar but utilizes a **hash function**, a function that takes in text and numbers and maps it to a fixed integer. A **Miner** solves the problem (Velde, 2013):\n\n**Given the current blockchain $x$, a new (proposed) block $y$, a hashing function $f$ a fixed value $\\alpha$, find an $n$ s.t $f(x,y,n) <= \\alpha$**\n\n\nThe security of this process hinges on the fact that it is very difficult to find $n$ given only $x,y,f, \\alpha$ but it is very easy to check that for a given $n$, $f(x,y,n) <= \\alpha$ holds. To address the issue of double spending, finding $n$ for a given new addition $y$ verifies whether no previous bitcoin transaction involving $y$ existed. When $y$ is added to the block chain $x$, the transaction becomes official and the bitcoin has been transferred to Bob. ",
"_____no_output_____"
],
[
"### Rewards",
"_____no_output_____"
],
[
"When the first miner succesfully makes an addition to the block chain, the message is broadcasted to the Blockchain and the miner receives $N$ new bitcoin attributed to it, a reward for the resources used. The Bitcoin protocol keeps the hashing function constant but changes $\\alpha$ and $N$ over time, depending on how many new nodes (or miners) are added to the blockchain. In the case of Bitcoin, the Blockchain is public so any individual with the proper hardware can send transactions or become a miner (Wikipedia). The reason for providing these rewards is because mining requires high energy consumption and has been critized for being very \"inefficient\". ",
"_____no_output_____"
],
[
"### Arms race",
"_____no_output_____"
],
[
"As stated before, the process of finding $n$ is challenging and can only be done through exhaustive checking. Specifically, solving the mathematical equations comes from constantly running operations on a device until a solution is found. In the beginning, users utilized the CPU but as time went on, the same functions could be run more efficiently on GPUs (Farrel, 2015). Think of mining as a single device that runs constantly and keeps running a hash every second, similar to filling out a lottery ticket until you get a winning ticket. Due to this incentive, GPUs have been very hard to acquire (Uzman, 2021). ",
"_____no_output_____"
],
[
"### What is DogeCoin?",
"_____no_output_____"
],
[
"With the advent of BitCoin, numerous different cryptocurrencies have been introduced, utilizing the same model of peer-to-peer transactions without the need of a central authority. An unusual example of this is DogeCoin, a cryptocurrency that has recently been in the news due its large monetary growth. As a start, Doge is an internet meme that was created around 2010 and the coin was designed to initially be a joke (Young, 2018). Though it still has the peer-to-peer model, it has fundamental differences from BitCoin. For once, the circulation of coins is significantly larger than Bitcoin- around 300 billion. Its monetary value per unit is also significantly less and implements a different algorithm for deriving its keys (Young, 2018). DogeCoin is an interesting case of demand heavily increasing its value, with numerous individuals and companies profiting heavily off it. ",
"_____no_output_____"
],
[
"***",
"_____no_output_____"
],
[
"# Research Questions and Hypothesis",
"_____no_output_____"
],
[
"Now that the proper background knowledge has been presented, we wish to formulate a hypothesis that relates to how certain groups of people are impacted by cryptocurrency over others. Because BitCoin uses a public Blockchain, there is no restriction on who is able to perform a transaction or become a miner. This accessibility is an area that is important to look at given the large monetary value that these currencies have now attained. Though the claim is that anyone can be apart of the group, acquiring the necessary hardware can be a challenge. Furthermore, digital coins are not immune to fraud and there is the potential for large amounts of money to be lost (Mt. Gox as an example).\n\nIt is also important to note that there are many different cryptocurrencies that exist so it is best to focus on the most well-known blockchain (Bitcoin) and see if the findings can be extrapolated to other systems. The preliminary research questions from the plan were:",
"_____no_output_____"
],
[
"- What impact does the cryptocurrency system have on minority groups in the United States?\n- Does the algorithm behind specific cryptocurrencies target more privaleged groups? Are people in a position of power able to take advantage of such a design?\n- What mathematical models are companies using to create cryptosystems?\n- How does encryption and the anonimity of cryptocurrency impact the tech industry?",
"_____no_output_____"
],
[
"In the background research, the 2nd and 3rd questions have been addressed and there are numerous studies regarding the mathematical models and encryption systems that companies use. Thus, we can focus less on the theory and more on the availability of cryptocurrency to the user. In regard to the second question, this would be difficult to address because it involves identifying what we mean by \"privaleged groups\" and also what it means to design biased cryptocurrency. Thus, we can reformulate the first question in a way that allows us to create a reasonable hypothesis.",
"_____no_output_____"
],
[
"#### Research Question",
"_____no_output_____"
],
[
"**How does the socio-economic status of an individual in the United States impact their ability to receive economic benefits from BitCoin?**",
"_____no_output_____"
],
[
"#### Hypothesis",
"_____no_output_____"
],
[
"**A person with higher socio-economic status will be able to receive more benefits from transactions of Bitcoins as well as ready access to become a miner.**",
"_____no_output_____"
],
[
"***",
"_____no_output_____"
],
[
"# Methadology",
"_____no_output_____"
],
[
"At the start of the project, much of the research came from reading academic articles about the cryptocurrency industry and understanding how BitCoin worked. I was heavily invested in learning about mathematical models to the point where I realized that I was not properly incorporating the techniques I learned in HCDE 410 to conduct human-centered research. Nevetheless, I was able to restructure the project and come up with a plan:",
"_____no_output_____"
],
[
"### Part 1: Find articles that address the growth of cryptocurrency industry",
"_____no_output_____"
],
[
"### Part 2: Find data about price of GPUs, cryptocurrency over time",
"_____no_output_____"
],
[
"### Part 3: Find articles about the acessibility of BitCoin",
"_____no_output_____"
],
[
"### Part 4: Data analysis techniques",
"_____no_output_____"
],
[
"***",
"_____no_output_____"
],
[
"# Findings",
"_____no_output_____"
],
[
"### Easy access to transactions and mining",
"_____no_output_____"
],
[
"This finding is primarily in relation to BitCoin. In my research, I wanted to understand whether someone who has little background knowledge in cryptocurrency is able to easily become apart of the mining process. My initial perception was that Bitcoin mining required immense mathematical background and that only those with a upper-level education background were able to find success with it. However, this turned out to be a false assumption. \n\nFor one, a miner is not directly interacting with the code and mathematics behind mining. Rather, they are installing an application on their device to run constantly and mine the bitcoin (Bitcoinmining, 2017). Furthermore, there exists numerous cloud computing services that run the algorithm in the background and are easy to install on your device (Bitcoinmining, 2017). Once you have installed the software, you are then able to join a \"pool\" which is a group of miners that work together to solve a particular block (Wikipedia). Once you are part of that group, you are able to set up a wallet on your computer and you are good to go. Purchasing cryptocurrency is also readily available on most platforms and typically involves less privacy concerns because your personal information does not get sent to a third party merchant. Thus, there is a higher likelyhood that your personal financial information is safe",
"_____no_output_____"
],
[
"### GPU demand has increased in recent years",
"_____no_output_____"
],
[
"Cryptomining has had a direct impact on the surge of prices of graphics cards. It has been reported that many miners have been buying mid-range graphics cards in bulk to build machines that mine bitcoin and other cryptocurrencies (Warren, 2018). Hence, we conclude that for individuals with lower socio-economic standing, it is more difficult to participate in the mining process. ",
"_____no_output_____"
],
[
"- https://www.techspot.com/article/2257-cpu-gpu-pricing-2021-update/\n- https://www.theverge.com/2018/1/30/16949550/bitcoin-graphics-cards-pc-prices-surge",
"_____no_output_____"
],
[
"### Profitability of cryptomining",
"_____no_output_____"
],
[
"For most cryptosystems, the profitability of mining comes from succesfully adding a new block to the block chain. Due to the immense resources required to do this, the algorithm rewards the miner with \"coins\" that are worth a monitary value. While many different algorithms exist depending on the coin, they always involve some kind of hash functions that is easy to verify but difficult to check. Since the prices of GPUs have gone up in recent years, it can be challenging to turn a profit from rewards. It is also unclear whether a user should peform mining individually or whether they should join a pool. On one hand, a pool could potentially allow you to guarentee that you are succesfully validating new blocks but individual mining allows you to maximize profits. Furthermore, profitability is also governed by the monitary value of the currency which is heavily volatile. ",
"_____no_output_____"
],
[
"***",
"_____no_output_____"
],
[
"# Implications",
"_____no_output_____"
],
[
"One of the problems with this project was that I did not allocate enough time into the data analysis and so I relied on previously existing studies that helped support my claims. Hence, I was not able to make any \"new\" findings and the project became more of a survey of a multitude of academic articles. In my plan, I wanted to display visuals of my findings but I was unable to because of time constraints. \n\nThe research showed that the cryptoindustry is more accessible than I had initially assumed. The mathematical theory behind how cryptosystems work is interesting for me but not necessary to perform transactions or become a miner. My hypothesis was partially supported because it is harder for individuals to acquire the hardware to become successful miners. However, for people who only wish to buy and trade crypto, services exist which allow you to buy a fraction of coins for any value. Because transactions are fairly quick and your privacy isn't compromised, it is beneficial to use cryptocurrency is a way to purchase goods and services. However, due to the volatile nature of the prices, for individuals with a lower socio-economic background, it is important to not place all liquid assets in this system since it is governed by demand alone. While it is profitable now, it is unclear whether it will stay that way. \n\nI was more ambitious in my project plan when I formulated my previous research question. However, I found it hard to find datat to support my claims and I instead had to narrow the scope to a topic that has more numerical data (socio-economic standing). ",
"_____no_output_____"
],
[
"***",
"_____no_output_____"
],
[
"# Conclusion",
"_____no_output_____"
],
[
"In this project, I explored the theory behind decentralized cryptocurrencies and how they utilize complex mathematical functions to secure their coinage. With the advent of mining becoming more popular, we found that being from a higher socio-economic standing is more beneficial to become part of the mining process but performing transactions remains unchanged. ",
"_____no_output_____"
],
[
"***",
"_____no_output_____"
],
[
"# Possible futher analysis",
"_____no_output_____"
],
[
"Due to personal reasons and time constraints, I was unable to perform a lot of what was listed in my initial plan. Regadless, I do wish to continue with this project for later as I have been experimenting with statistical analysis. In the future, I wish to utilize theoretical dynamic system analysis, which comes from being able to communicate information about the equations and mathematical systems that companies use in their cryptosystem construction. In regards to the analytic methods, I have background in probability theory that I wish to use to simulate possible price trajectories for the future. The Martingale and Monte-carlo simulations are bit of a stretch-goal which I hope to elaborate on when I finish the other parts of the project.",
"_____no_output_____"
],
[
"**Analytic Methods**",
"_____no_output_____"
],
[
"- Statistical analysis through least-squares-regression (via R-Studio on .csv data sets)\n- Implementing NumPy modules (in Python) to find trends in data sets.\n- Martingale and Monte-carlo simulations run via PyCharm.\n- Theoretical dynamic system analysis.\n- Reading over academic articles relating to research questions",
"_____no_output_____"
],
[
"**Presenting findings**",
"_____no_output_____"
],
[
"- Academic style report (using overleaf.com LaTeX renderer)\n- Line graphs showing price trends, with contexualization\n- Time series graphs",
"_____no_output_____"
],
[
"***",
"_____no_output_____"
],
[
"# References",
"_____no_output_____"
],
[
"- Bitcoin arms race\n https://ieeexplore.ieee.org/abstract/document/6521016\n- Introduction to bitcoin and crytocurrency systems\n https://repository.upenn.edu/cgi/viewcontent.cgi?article=1133&context=wharton_research_scholars\n- Survey on GPU stock and prices in 2021\n https://wccftech.com/nvidia-and-amd-gpu-supply-will-remain-grim-in-q1-2021/#:~:text=It%20seems%20that%20now%20is%20a%20good%20time,very%20large%20number%20of%20variables%20at%20play%20here.\nhttps://poseidon01.ssrn.com/delivery.php\n- Introduction to DogeCoin\n https://poseidon01.ssrn.com/delivery.php?ID=773124118097097113031023086096078065057081049043000029071006125069009064110096091085056017039010001111005112082093089097000006043087058092007069069087089015094089022071021048009066120095090110120113076065113122114110107111096001024091099107110111095125&EXT=pdf&INDEX=TRUE\n- Survey on GPU prices\n https://www.theverge.com/2018/1/30/16949550/bitcoin-graphics-cards-pc-prices-surge\n- Survey on GPU pricing \n https://www.techspot.com/article/2257-cpu-gpu-pricing-2021-update/\n- Introduction to Cryptocurrency\n https://www.coinbase.com/learn/crypto-basics/what-is-cryptocurrency\n- Introduction to Bitcoin mining\n https://www.bitcoinmining.com/getting-started/#:~:text=Bitcoin%20Mining%20Guide%20-%20Getting%20started%20with%20Bitcoin,is%20important%20for%20your%20bitcoin%20mining%20profits.%20\n- Bitcoin Wikipedia\n https://en.wikipedia.org/wiki/Bitcoin",
"_____no_output_____"
],
[
"#### Data sets",
"_____no_output_____"
],
[
"- Bitcoin historic data \n https://www.nasdaq.com/market-activity/cryptocurrency/btc/historical\n- CPU parts data\n https://www.kaggle.com/raczeq/ethereum-effect-pc-parts",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4a395575e61a9fd8c1c5e7f873e9862cbb68d2a6
| 879,419 |
ipynb
|
Jupyter Notebook
|
notebooks/GUAM/GUAM/01_Offshore/03_TIDES_MMSL_Regression.ipynb
|
teslakit/teslak
|
3f3dda08c5c5998cb2a7debbf22f2be675a4ff8b
|
[
"MIT"
] | 12 |
2019-11-14T22:19:12.000Z
|
2022-03-04T01:25:33.000Z
|
notebooks/GUAM/GUAM/01_Offshore/03_TIDES_MMSL_Regression.ipynb
|
anderdyl/teslaCoSMoS
|
1495bfa2364ddbacb802d145b456a35213abfb7c
|
[
"MIT"
] | 5 |
2020-03-24T18:21:41.000Z
|
2021-08-23T20:39:43.000Z
|
notebooks/GUAM/GUAM/01_Offshore/03_TIDES_MMSL_Regression.ipynb
|
anderdyl/teslaCoSMoS
|
1495bfa2364ddbacb802d145b456a35213abfb7c
|
[
"MIT"
] | 2 |
2021-03-06T07:54:41.000Z
|
2021-06-30T14:33:22.000Z
| 1,298.994092 | 142,164 | 0.958722 |
[
[
[
"\n... ***CURRENTLY UNDER DEVELOPMENT*** ...\n",
"_____no_output_____"
],
[
"## Simulate Monthly Mean Sea Level using a multivariate-linear regression model based on the annual SST PCs\n\ninputs required: \n * WaterLevel historical data from a tide gauge at the study site \n * Historical and simulated Annual PCs (*from Notebook 01*)\n\nin this notebook:\n * Obtain monthly mean sea level anomalies (MMSLA) from the tidal gauge record\n * Perform linear regression between MMSLA and annual PCs\n * Obtain predicted timeseries of MMSLA based on simulated timeseries of annual PCs ",
"_____no_output_____"
],
[
"### Workflow:\n\n<div>\n<img src=\"resources/nb01_02.png\" width=\"300px\">\n</div>\n\n",
"_____no_output_____"
],
[
"Monthly sea level variability is typically due to processes occurring at longer timescales than the daily weather. Slowly varying seasonality and anomalies due to ENSO are retained in the climate emulator via the principle components (APC) used to develop the AWT. A multivariate regression model containing a mean plus annual and seasonal cycles at 12-month and 6-month periods for each APC covariate was fit to the MMSLA. This simple model explains ~75% of the variance without any specific information regarding local conditions (i.e., local anomalies due to coastal shelf dynamics, or local SSTAs) and slightly underpredicts extreme monthly sea level anomalies by ~10 cm. While this component of the approach is a subject of ongoing research, the regression model produces an additional ~0.35 m of regional SWL variability about mean sea level, which was deemed sufficient for the purposes of demonstrating the development of the stochastic climate emulator.",
"_____no_output_____"
]
],
[
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# basic import\nimport os\nimport os.path as op\nfrom collections import OrderedDict\n\n# python libs\nimport numpy as np\nfrom numpy.random import multivariate_normal\nimport xarray as xr\nfrom scipy.stats import linregress\nfrom scipy.optimize import least_squares, curve_fit\nfrom datetime import datetime, timedelta\n\n# DEV: override installed teslakit\nimport sys\nsys.path.insert(0, op.join(os.path.abspath(''), '..', '..', '..'))\n\n# teslakit\nfrom teslakit.database import Database\nfrom teslakit.tides import Calculate_MMSL\nfrom teslakit.statistical import runmean\nfrom teslakit.util.time_operations import date2yearfrac as d2yf\n\nfrom teslakit.plotting.tides import Plot_Tide_SLR, Plot_Tide_RUNM, Plot_Tide_MMSL, \\\nPlot_Validate_MMSL_tseries, Plot_Validate_MMSL_scatter, Plot_MMSL_Prediction, \\\nPlot_MMSL_Histogram\n",
"_____no_output_____"
]
],
[
[
"\n## Database and Site parameters",
"_____no_output_____"
]
],
[
[
"# --------------------------------------\n# Teslakit database\n\np_data = r'/media/administrador/HD/Dropbox/Guam/teslakit/data'\ndb = Database(p_data)\n\n# set site\ndb.SetSite('GUAM')",
"_____no_output_____"
],
[
"# --------------------------------------\n# load data and set parameters\n\nWL_split = db.Load_TIDE_hist_astro() # water level historical data (tide gauge)\nWL = WL_split.WaterLevels\n\nSST_KMA = db.Load_SST_KMA() # SST Anual Weather Types PCs\nSST_PCs_sim_m = db.Load_SST_PCs_sim_m() # simulated SST PCs (monthly)\n\n# parameters for mmsl calculation\nmmsl_year_ini = 1947\nmmsl_year_end = 2018\n",
"_____no_output_____"
]
],
[
[
"\n## Monthly Mean Sea Level",
"_____no_output_____"
]
],
[
[
"# --------------------------------------\n# Calculate SLR using linear regression\n\ntime = WL.time.values[:]\nwl = WL.values[:] * 1000 # (m to mm)\n\nlr_time = np.array(range(len(time))) # for linregress\nmask = ~np.isnan(wl) # remove nans with mask\n\nslope, intercept, r_value, p_value, std_err = linregress(lr_time[mask], wl[mask])\nslr = intercept + slope * lr_time\n\n# Plot tide with SLR\nPlot_Tide_SLR(time, wl, slr);\n",
"_____no_output_____"
],
[
"# --------------------------------------\n# remove SLR and runmean from tide \n\ntide_noslr = wl - slr\n\n# calculate tide running mean\ntime_window = 365*24*3\nrunm = runmean(tide_noslr, time_window, 'mean')\n\n# remove running mean\ntide_noslr_norunm = tide_noslr - runm\n\n# store data \nTNSR = xr.DataArray(tide_noslr_norunm, dims=('time'), coords={'time':time})\n\n\n# Plot tide without SLR and runm\nPlot_Tide_RUNM(time, tide_noslr, runm);\n",
"_____no_output_____"
],
[
"# --------------------------------------\n# calculate Monthly Mean Sea Level (mmsl)\n\nMMSL = Calculate_MMSL(TNSR, mmsl_year_ini, mmsl_year_end)\n\n# fill nans with interpolated values\np_nan = np.isnan(MMSL.mmsl)\nMMSL.mmsl[p_nan]= np.interp(MMSL.time[p_nan], MMSL.time[~p_nan], MMSL.mmsl[~p_nan])\n\nmmsl_time = MMSL.time.values[:]\nmmsl_vals = MMSL.mmsl.values[:]\n\n# Plot tide and mmsl \nPlot_Tide_MMSL(TNSR.time, TNSR.values, mmsl_time, mmsl_vals);\n\n# store historical mmsl\ndb.Save_TIDE_hist_mmsl(MMSL)\n",
"_____no_output_____"
]
],
[
[
"\n## Monthly Mean Sea Level - Principal Components\nThe annual PCs are passed to a monthly resolution",
"_____no_output_____"
]
],
[
[
"# --------------------------------------\n# SST Anual Weather Types PCs\n\nPCs = np.array(SST_KMA.PCs.values)\nPC1, PC2, PC3 = PCs[:,0], PCs[:,1], PCs[:,2]\nPCs_years = [int(str(t).split('-')[0]) for t in SST_KMA.time.values[:]]\n\n# MMSL PCs calculations: cut and pad it to monthly resolution\nntrs_m_mean = np.array([])\nntrs_time = []\n\nMMSL_PC1 = np.array([])\nMMSL_PC2 = np.array([])\nMMSL_PC3 = np.array([])\n\nfor c, y in enumerate(PCs_years):\n pos = np.where(\n (mmsl_time >= np.datetime64('{0}-06-01'.format(y))) &\n (mmsl_time <= np.datetime64('{0}-05-29'.format(y+1)))\n )\n\n if pos[0].size:\n ntrs_m_mean = np.concatenate((ntrs_m_mean, mmsl_vals[pos]),axis=0)\n # TODO check for 0s and nans in ntrs_m_mean?\n ntrs_time.append(mmsl_time[pos])\n\n MMSL_PC1 = np.concatenate((MMSL_PC1, np.ones(pos[0].size)*PC1[c]),axis=0)\n MMSL_PC2 = np.concatenate((MMSL_PC2, np.ones(pos[0].size)*PC2[c]),axis=0)\n MMSL_PC3 = np.concatenate((MMSL_PC3, np.ones(pos[0].size)*PC3[c]),axis=0)\n\nntrs_time = np.concatenate(ntrs_time)\n\n# Parse time to year fraction for linear-regression seasonality \nfrac_year = np.array([d2yf(x) for x in ntrs_time])\n",
"_____no_output_____"
]
],
[
[
"\n## Monthly Mean Sea Level - Multivariate-linear Regression Model",
"_____no_output_____"
]
],
[
[
"# --------------------------------------\n# Fit linear regression model \n\ndef modelfun(data, *x):\n pc1, pc2, pc3, t = data\n \n return x[0] + x[1]*pc1 + x[2]*pc2 + x[3]*pc3 + \\\n np.array([x[4] + x[5]*pc1 + x[6]*pc2 + x[7]*pc3]).flatten() * np.cos(2*np.pi*t) + \\\n np.array([x[8] + x[9]*pc1 + x[10]*pc2 + x[11]*pc3]).flatten() * np.sin(2*np.pi*t) + \\\n np.array([x[12] + x[13]*pc1 + x[14]*pc2 + x[15]*pc3]).flatten() * np.cos(4*np.pi*t) + \\\n np.array([x[16] + x[17]*pc1 + x[18]*pc2 + x[19]*pc3]).flatten() * np.sin(4*np.pi*t) \n\n# use non-linear least squares to fit our model\nsplit = 160 # train / validation split index\nx0 = np.ones(20)\nsigma = np.ones(split)\n\n# select data for scipy.optimize.curve_fit\nx_train = ([MMSL_PC1[:split], MMSL_PC2[:split], MMSL_PC3[:split], frac_year[:split]])\ny_train = ntrs_m_mean[:split]\n\nres_lsq, res_cov = curve_fit(modelfun, x_train, y_train, x0, sigma)\n\n# print optimal parameters and covariance\n#print('optimal parameters (minimized sum of squares residual)\\n{0}\\n'.format(res_lsq))\n#print('optimal parameters covariance\\n{0}\\n'.format(res_cov))\n",
"_____no_output_____"
]
],
[
[
"## Train and test model",
"_____no_output_____"
]
],
[
[
"# Check model at fitting period\n\nyp_train = modelfun(x_train, *res_lsq)\n\nPlot_Validate_MMSL_tseries(ntrs_time[:split], ntrs_m_mean[:split], yp_train);\nPlot_Validate_MMSL_scatter(ntrs_m_mean[:split], yp_train);\n",
"_____no_output_____"
],
[
"# Check model at validation period\n\nx_val = ([MMSL_PC1[split:], MMSL_PC2[split:], MMSL_PC3[split:], frac_year[split:]])\nyp_val = modelfun(x_val, *res_lsq)\n\nPlot_Validate_MMSL_tseries(ntrs_time[split:], ntrs_m_mean[split:], yp_val);\nPlot_Validate_MMSL_scatter(ntrs_m_mean[split:], yp_val);\n",
"_____no_output_____"
],
[
"# Parameter sampling (generate sample of params based on covariance matrix)\n\nn_sims = 10\ntheta_gen = res_lsq\ntheta_sim = multivariate_normal(theta_gen, res_cov, n_sims)\n\n\n# Check model at validation period\nyp_valp = np.ndarray((n_sims, len(ntrs_time[split:]))) * np.nan\nfor i in range(n_sims):\n yp_valp[i, :] = modelfun(x_val, *theta_sim[i,:])\n\n# 95% percentile\nyp_val_quant = np.percentile(yp_valp, [2.275, 97.275], axis=0)\n\nPlot_Validate_MMSL_tseries(ntrs_time[split:], ntrs_m_mean[split:], yp_val, mmsl_pred_quantiles=yp_val_quant);\n",
"_____no_output_____"
],
[
"# Fit model using entire dataset\n\nsigma = np.ones(len(frac_year))\nx_fit = ([MMSL_PC1, MMSL_PC2, MMSL_PC3, frac_year])\ny_fit = ntrs_m_mean\n\nres_lsq, res_cov = curve_fit(modelfun, x_fit, y_fit, x0, sigma)\n\n# obtain model output\nyp = modelfun(x_fit, *res_lsq)\n\n\n# Generate 1000 simulations of the parameters \nn_sims = 1000\ntheta_gen = res_lsq\nparam_sim = multivariate_normal(theta_gen, res_cov, n_sims)\n\n\n# Check model\nyp_p = np.ndarray((n_sims, len(ntrs_time))) * np.nan\nfor i in range(n_sims):\n yp_p[i, :] = modelfun(x_fit, *param_sim[i,:])\n\n# 95% percentile\nyp_quant = np.percentile(yp_p, [2.275, 97.275], axis=0)\n\nPlot_Validate_MMSL_tseries(ntrs_time, ntrs_m_mean, yp, mmsl_pred_quantiles=yp_quant);\n\n# Save model parameters to use in climate change \nmodel_coefs = xr.Dataset({'sim_params' : (('n_sims','n_params'), param_sim)})\ndb.Save_TIDE_mmsl_params(model_coefs)",
"_____no_output_____"
]
],
[
[
"\n## Monthly Mean Sea Level - Prediction",
"_____no_output_____"
]
],
[
[
"# --------------------------------------\n# Predict 1000 years using simulated PCs (monthly time resolution)\n\n# get simulation time as year fractions\nPCs_sim_time = SST_PCs_sim_m.time.values[:]\nfrac_year_sim = np.array([d2yf(x) for x in PCs_sim_time])\n\n# solve each PCs simulation\ny_sim_n = np.ndarray((len(SST_PCs_sim_m.n_sim), len(frac_year_sim))) * np.nan\nfor s in SST_PCs_sim_m.n_sim:\n \n PCs_s_m = SST_PCs_sim_m.sel(n_sim=s)\n MMSL_PC1_sim = PCs_s_m.PC1.values[:]\n MMSL_PC2_sim = PCs_s_m.PC2.values[:]\n MMSL_PC3_sim = PCs_s_m.PC3.values[:]\n \n # use linear-regression model\n x_sim = ([MMSL_PC1_sim, MMSL_PC2_sim, MMSL_PC3_sim, frac_year_sim])\n y_sim_n[s, :] = modelfun(x_sim, *param_sim[s,:])\n\n\n# join output and store it\nMMSL_sim = xr.Dataset(\n {\n 'mmsl' : (('n_sim','time'), y_sim_n / 1000), # mm to m\n },\n {'time' : PCs_sim_time}\n)\nprint(MMSL_sim)\n\ndb.Save_TIDE_sim_mmsl(MMSL_sim)\n",
"<xarray.Dataset>\nDimensions: (n_sim: 100, time: 12012)\nCoordinates:\n * time (time) object 1999-06-01 00:00:00 ... 3000-05-01 00:00:00\nDimensions without coordinates: n_sim\nData variables:\n mmsl (n_sim, time) float64 0.06209 0.1021 0.1271 ... -0.01842 0.01059\n"
],
[
"# Plot mmsl simulation \n\nplot_sim = 0\n\ny_sim = MMSL_sim.sel(n_sim=plot_sim).mmsl.values[:] * 1000 # m to mm\nt_sim = MMSL_sim.sel(n_sim=plot_sim).time.values[:]\n\n# Plot mmsl prediction\nPlot_MMSL_Prediction(t_sim, y_sim);\n\n# compare model histograms\nPlot_MMSL_Histogram(ntrs_m_mean, y_sim);\n",
"_____no_output_____"
],
[
"# compare model histograms for all simulations\n\ny_sim = MMSL_sim.mmsl.values[:].flatten() * 1000 # m to mm\n\nPlot_MMSL_Histogram(ntrs_m_mean, y_sim);\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4a3959bfbabeca677bd7ef27e4b3840899b92b52
| 15,369 |
ipynb
|
Jupyter Notebook
|
examples/01_Simple_GP_Regression/Simple_MultiGPU_GP_Regression.ipynb
|
beyucel/gpytorch
|
a5394937495756945b831d83035349579d8fac31
|
[
"MIT"
] | 2 |
2019-04-19T00:35:49.000Z
|
2019-04-19T02:51:49.000Z
|
examples/01_Simple_GP_Regression/Simple_MultiGPU_GP_Regression.ipynb
|
beyucel/gpytorch
|
a5394937495756945b831d83035349579d8fac31
|
[
"MIT"
] | null | null | null |
examples/01_Simple_GP_Regression/Simple_MultiGPU_GP_Regression.ipynb
|
beyucel/gpytorch
|
a5394937495756945b831d83035349579d8fac31
|
[
"MIT"
] | 1 |
2019-05-10T17:52:39.000Z
|
2019-05-10T17:52:39.000Z
| 35.908879 | 401 | 0.557681 |
[
[
[
"# Exact GP Regression with Multiple GPUs and Kernel Partitioning\n\nIn this notebook, we'll demonstrate training exact GPs on large datasets using two key features from the paper https://arxiv.org/abs/1903.08114: \n\n1. The ability to distribute the kernel matrix across multiple GPUs, for additional parallelism.\n2. Partitioning the kernel into chunks computed on-the-fly when performing each MVM to reduce memory usage.\n\nWe'll be using the `protein` dataset, which has about 37000 training examples. The techniques in this notebook can be applied to much larger datasets, but the training time required will depend on the computational resources you have available: both the number of GPUs available and the amount of memory they have (which determines the partition size) have a significant effect on training time.",
"_____no_output_____"
]
],
[
[
"import math\nimport torch\nimport gpytorch\nimport sys\nfrom matplotlib import pyplot as plt\nsys.path.append('../')\nfrom LBFGS import FullBatchLBFGS\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
]
],
[
[
"## Downloading Data\nWe will be using the Protein UCI dataset which contains a total of 40000+ data points. The next cell will download this dataset from a Google drive and load it.",
"_____no_output_____"
]
],
[
[
"import os\nimport urllib.request\nfrom scipy.io import loadmat\ndataset = 'protein'\nif not os.path.isfile(f'{dataset}.mat'):\n print(f'Downloading \\'{dataset}\\' UCI dataset...')\n urllib.request.urlretrieve('https://drive.google.com/uc?export=download&id=1nRb8e7qooozXkNghC5eQS0JeywSXGX2S',\n f'{dataset}.mat')\n \ndata = torch.Tensor(loadmat(f'{dataset}.mat')['data'])",
"_____no_output_____"
]
],
[
[
"## Normalization and train/test Splits\n\nIn the next cell, we split the data 80/20 as train and test, and do some basic z-score feature normalization.",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nN = data.shape[0]\n# make train/val/test\nn_train = int(0.8 * N)\ntrain_x, train_y = data[:n_train, :-1], data[:n_train, -1]\ntest_x, test_y = data[n_train:, :-1], data[n_train:, -1]\n\n# normalize features\nmean = train_x.mean(dim=-2, keepdim=True)\nstd = train_x.std(dim=-2, keepdim=True) + 1e-6 # prevent dividing by 0\ntrain_x = (train_x - mean) / std\ntest_x = (test_x - mean) / std\n\n# normalize labels\nmean, std = train_y.mean(),train_y.std()\ntrain_y = (train_y - mean) / std\ntest_y = (test_y - mean) / std\n\n# make continguous\ntrain_x, train_y = train_x.contiguous(), train_y.contiguous()\ntest_x, test_y = test_x.contiguous(), test_y.contiguous()\n\noutput_device = torch.device('cuda:0')\n\ntrain_x, train_y = train_x.to(output_device), train_y.to(output_device)\ntest_x, test_y = test_x.to(output_device), test_y.to(output_device)",
"_____no_output_____"
]
],
[
[
"## How many GPUs do you want to use?\n\nIn the next cell, specify the `n_devices` variable to be the number of GPUs you'd like to use. By default, we will use all devices available to us.",
"_____no_output_____"
]
],
[
[
"n_devices = torch.cuda.device_count()\nprint('Planning to run on {} GPUs.'.format(n_devices))",
"Planning to run on 2 GPUs.\n"
]
],
[
[
"## GP Model + Training Code\n\nIn the next cell we define our GP model and training code. For this notebook, the only thing different from the Simple GP tutorials is the use of the `MultiDeviceKernel` to wrap the base covariance module. This allows for the use of multiple GPUs behind the scenes.",
"_____no_output_____"
]
],
[
[
"class ExactGPModel(gpytorch.models.ExactGP):\n def __init__(self, train_x, train_y, likelihood, n_devices):\n super(ExactGPModel, self).__init__(train_x, train_y, likelihood)\n self.mean_module = gpytorch.means.ConstantMean()\n base_covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel())\n \n self.covar_module = gpytorch.kernels.MultiDeviceKernel(\n base_covar_module, device_ids=range(n_devices),\n output_device=output_device\n )\n \n def forward(self, x):\n mean_x = self.mean_module(x)\n covar_x = self.covar_module(x)\n return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)\n\ndef train(train_x,\n train_y,\n n_devices,\n output_device,\n checkpoint_size,\n preconditioner_size,\n n_training_iter,\n):\n likelihood = gpytorch.likelihoods.GaussianLikelihood().to(output_device)\n model = ExactGPModel(train_x, train_y, likelihood, n_devices).to(output_device)\n model.train()\n likelihood.train()\n \n optimizer = FullBatchLBFGS(model.parameters(), lr=0.1)\n # \"Loss\" for GPs - the marginal log likelihood\n mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)\n\n \n with gpytorch.beta_features.checkpoint_kernel(checkpoint_size), \\\n gpytorch.settings.max_preconditioner_size(preconditioner_size):\n\n def closure():\n optimizer.zero_grad()\n output = model(train_x)\n loss = -mll(output, train_y)\n return loss\n\n loss = closure()\n loss.backward()\n\n for i in range(n_training_iter):\n options = {'closure': closure, 'current_loss': loss, 'max_ls': 10}\n loss, _, _, _, _, _, _, fail = optimizer.step(options)\n \n print('Iter %d/%d - Loss: %.3f lengthscale: %.3f noise: %.3f' % (\n i + 1, n_training_iter, loss.item(),\n model.covar_module.module.base_kernel.lengthscale.item(),\n model.likelihood.noise.item()\n ))\n \n if fail:\n print('Convergence reached!')\n break\n \n print(f\"Finished training on {train_x.size(0)} data points using {n_devices} GPUs.\")\n return model, likelihood",
"_____no_output_____"
]
],
[
[
"## Automatically determining GPU Settings\n\nIn the next cell, we automatically determine a roughly reasonable partition or *checkpoint* size that will allow us to train without using more memory than the GPUs available have. Not that this is a coarse estimate of the largest possible checkpoint size, and may be off by as much as a factor of 2. A smarter search here could make up to a 2x performance improvement.",
"_____no_output_____"
]
],
[
[
"import gc\n\ndef find_best_gpu_setting(train_x,\n train_y,\n n_devices,\n output_device,\n preconditioner_size\n):\n N = train_x.size(0)\n \n # Find the optimum partition/checkpoint size by decreasing in powers of 2\n # Start with no partitioning (size = 0)\n settings = [0] + [int(n) for n in np.ceil(N / 2**np.arange(1, np.floor(np.log2(N))))]\n\n for checkpoint_size in settings:\n print('Number of devices: {} -- Kernel partition size: {}'.format(n_devices, checkpoint_size))\n try:\n # Try a full forward and backward pass with this setting to check memory usage\n _, _ = train(train_x, train_y,\n n_devices=n_devices, output_device=output_device,\n checkpoint_size=checkpoint_size,\n preconditioner_size=preconditioner_size, n_training_iter=1)\n \n # when successful, break out of for-loop and jump to finally block\n break\n except RuntimeError as e:\n print('RuntimeError: {}'.format(e))\n except AttributeError as e:\n print('AttributeError: {}'.format(e))\n finally:\n # handle CUDA OOM error\n gc.collect()\n torch.cuda.empty_cache()\n return checkpoint_size\n\n# Set a large enough preconditioner size to reduce the number of CG iterations run\npreconditioner_size = 100\ncheckpoint_size = find_best_gpu_setting(train_x, train_y,\n n_devices=n_devices, \n output_device=output_device,\n preconditioner_size=preconditioner_size)",
"Number of devices: 2 -- Kernel partition size: 0\n"
]
],
[
[
"# Training",
"_____no_output_____"
]
],
[
[
"model, likelihood = train(train_x, train_y,\n n_devices=n_devices, output_device=output_device,\n checkpoint_size=checkpoint_size,\n preconditioner_size=preconditioner_size,\n n_training_iter=20)",
"Iter 1/20 - Loss: 1.030 lengthscale: 0.671 noise: 0.570\nIter 2/20 - Loss: 0.995 lengthscale: 0.606 noise: 0.476\nIter 3/20 - Loss: 0.969 lengthscale: 0.534 noise: 0.410\nIter 4/20 - Loss: 0.949 lengthscale: 0.473 noise: 0.360\nIter 5/20 - Loss: 0.935 lengthscale: 0.442 noise: 0.325\nIter 6/20 - Loss: 0.927 lengthscale: 0.418 noise: 0.302\nIter 7/20 - Loss: 0.912 lengthscale: 0.383 noise: 0.267\nIter 8/20 - Loss: 0.907 lengthscale: 0.358 noise: 0.243\nIter 9/20 - Loss: 0.904 lengthscale: 0.342 noise: 0.225\nIter 10/20 - Loss: 0.898 lengthscale: 0.326 noise: 0.212\nIter 11/20 - Loss: 0.897 lengthscale: 0.320 noise: 0.205\nIter 12/20 - Loss: 0.895 lengthscale: 0.318 noise: 0.200\nIter 13/20 - Loss: 0.895 lengthscale: 0.313 noise: 0.193\nIter 14/20 - Loss: 0.896 lengthscale: 0.313 noise: 0.193\nFinished training on 36584 data points using 2 GPUs.\n"
]
],
[
[
"# Testing: Computing test time caches",
"_____no_output_____"
]
],
[
[
"# Get into evaluation (predictive posterior) mode\nmodel.eval()\nlikelihood.eval()\n\nwith torch.no_grad(), gpytorch.settings.fast_pred_var():\n latent_pred = model(test_x)",
"_____no_output_____"
]
],
[
[
"# Testing: Computing predictions",
"_____no_output_____"
]
],
[
[
"with torch.no_grad(), gpytorch.settings.fast_pred_var():\n %time latent_pred = model(test_x)\n \ntest_rmse = torch.sqrt(torch.mean(torch.pow(latent_pred.mean - test_y, 2)))\nprint(f\"Test RMSE: {test_rmse.item()}\")",
"CPU times: user 53 ms, sys: 12.3 ms, total: 65.3 ms\nWall time: 63 ms\nTest RMSE: 0.5422027707099915\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"
]
] |
4a395c4058a18fbbc6abeb35488f2bb6549628f7
| 18,173 |
ipynb
|
Jupyter Notebook
|
nbs/06_data.block.ipynb
|
manycoding/fastai2
|
18986a55b20c0e5d2c262e14043346fcfae22a76
|
[
"Apache-2.0"
] | null | null | null |
nbs/06_data.block.ipynb
|
manycoding/fastai2
|
18986a55b20c0e5d2c262e14043346fcfae22a76
|
[
"Apache-2.0"
] | null | null | null |
nbs/06_data.block.ipynb
|
manycoding/fastai2
|
18986a55b20c0e5d2c262e14043346fcfae22a76
|
[
"Apache-2.0"
] | null | null | null | 39.679039 | 2,168 | 0.627689 |
[
[
[
"#default_exp data.block",
"_____no_output_____"
],
[
"#export\nfrom fastai2.torch_basics import *\nfrom fastai2.data.core import *\nfrom fastai2.data.load import *\nfrom fastai2.data.external import *\nfrom fastai2.data.transforms import *",
"_____no_output_____"
],
[
"from nbdev.showdoc import *",
"_____no_output_____"
]
],
[
[
"# Data block\n\n> High level API to quickly get your data in a `DataBunch`",
"_____no_output_____"
],
[
"## TransformBlock -",
"_____no_output_____"
]
],
[
[
"#export\nclass TransformBlock():\n \"A basic wrapper that links defaults transforms for the data block API\"\n def __init__(self, type_tfms=None, item_tfms=None, batch_tfms=None, dl_type=None, dbunch_kwargs=None):\n self.type_tfms = L(type_tfms)\n self.item_tfms = ToTensor + L(item_tfms)\n self.batch_tfms = L(batch_tfms)\n self.dl_type,self.dbunch_kwargs = dl_type,({} if dbunch_kwargs is None else dbunch_kwargs)",
"_____no_output_____"
],
[
"#export\ndef CategoryBlock(vocab=None, add_na=False):\n \"`TransformBlock` for single-label categorical targets\"\n return TransformBlock(type_tfms=Categorize(vocab=vocab, add_na=add_na))",
"_____no_output_____"
],
[
"#export\ndef MultiCategoryBlock(encoded=False, vocab=None, add_na=False):\n \"`TransformBlock` for multi-label categorical targets\"\n tfm = EncodedMultiCategorize(vocab=vocab) if encoded else [MultiCategorize(vocab=vocab, add_na=add_na), OneHotEncode]\n return TransformBlock(type_tfms=tfm)",
"_____no_output_____"
]
],
[
[
"## General API",
"_____no_output_____"
]
],
[
[
"#export\nfrom inspect import isfunction,ismethod",
"_____no_output_____"
],
[
"#export\ndef _merge_tfms(*tfms):\n \"Group the `tfms` in a single list, removing duplicates (from the same class) and instantiating\"\n g = groupby(concat(*tfms), lambda o:\n o if isinstance(o, type) else o.__qualname__ if (isfunction(o) or ismethod(o)) else o.__class__)\n return L(v[-1] for k,v in g.items()).map(instantiate)",
"_____no_output_____"
],
[
"#For example, so not exported\nfrom fastai2.vision.core import *\nfrom fastai2.vision.data import *",
"_____no_output_____"
],
[
"#hide\ntfms = _merge_tfms([Categorize, MultiCategorize, Categorize(['dog', 'cat'])], Categorize(['a', 'b']))\n#If there are several instantiated versions, the last one is kept.\ntest_eq(len(tfms), 2)\ntest_eq(tfms[1].__class__, MultiCategorize)\ntest_eq(tfms[0].__class__, Categorize)\ntest_eq(tfms[0].vocab, ['a', 'b'])\n\ntfms = _merge_tfms([PILImage.create, PILImage.show])\n#Check methods are properly separated\ntest_eq(len(tfms), 2)\ntfms = _merge_tfms([show_image, set_trace])\n#Check functions are properly separated\ntest_eq(len(tfms), 2)",
"_____no_output_____"
],
[
"#export\n@docs\n@funcs_kwargs\nclass DataBlock():\n \"Generic container to quickly build `DataSource` and `DataBunch`\"\n get_x=get_items=splitter=get_y = None\n dl_type = TfmdDL\n _methods = 'get_items splitter get_y get_x'.split()\n def __init__(self, blocks=None, dl_type=None, getters=None, n_inp=None, **kwargs):\n blocks = L(getattr(self,'blocks',(TransformBlock,TransformBlock)) if blocks is None else blocks)\n blocks = L(b() if callable(b) else b for b in blocks)\n self.default_type_tfms = blocks.attrgot('type_tfms', L())\n self.default_item_tfms = _merge_tfms(*blocks.attrgot('item_tfms', L()))\n self.default_batch_tfms = _merge_tfms(*blocks.attrgot('batch_tfms', L()))\n for t in blocks: \n if getattr(t, 'dl_type', None) is not None: self.dl_type = t.dl_type\n if dl_type is not None: self.dl_type = dl_type\n self.databunch = delegates(self.dl_type.__init__)(self.databunch)\n self.dbunch_kwargs = merge(*blocks.attrgot('dbunch_kwargs', {}))\n self.n_inp,self.getters = n_inp,L(getters)\n if getters is not None: assert self.get_x is None and self.get_y is None\n assert not kwargs\n\n def datasource(self, source, type_tfms=None):\n self.source = source\n items = (self.get_items or noop)(source)\n if isinstance(items,tuple):\n items = L(items).zip()\n labellers = [itemgetter(i) for i in range_of(self.default_type_tfms)]\n else: labellers = [noop] * len(self.default_type_tfms)\n splits = (self.splitter or noop)(items)\n if self.get_x: labellers[0] = self.get_x\n if self.get_y: labellers[1] = self.get_y\n if self.getters: labellers = self.getters\n if type_tfms is None: type_tfms = [L() for t in self.default_type_tfms]\n type_tfms = L([self.default_type_tfms, type_tfms, labellers]).map_zip(\n lambda tt,tfm,l: L(l) + _merge_tfms(tt, tfm))\n return DataSource(items, tfms=type_tfms, splits=splits, dl_type=self.dl_type, n_inp=self.n_inp)\n\n def databunch(self, source, path='.', type_tfms=None, item_tfms=None, batch_tfms=None, **kwargs):\n dsrc = self.datasource(source, type_tfms=type_tfms)\n item_tfms = _merge_tfms(self.default_item_tfms, item_tfms)\n batch_tfms = _merge_tfms(self.default_batch_tfms, batch_tfms)\n kwargs = {**self.dbunch_kwargs, **kwargs}\n return dsrc.databunch(path=path, after_item=item_tfms, after_batch=batch_tfms, **kwargs)\n\n _docs = dict(datasource=\"Create a `Datasource` from `source` with `type_tfms`\",\n databunch=\"Create a `DataBunch` from `source` with `item_tfms` and `batch_tfms`\")",
"_____no_output_____"
]
],
[
[
"To build a `DataBlock` you need to give the library four things: the types of your input/labels then at least two functions: `get_items` and `splitter`. You may also need to include `get_x` and `get_y` or a more generic list of `getters` that are applied to the results of `get_items`.\n\nOnce those are provided, you automatically get a `DataSource` or a `DataBunch`:",
"_____no_output_____"
]
],
[
[
"show_doc(DataBlock.datasource)",
"_____no_output_____"
],
[
"#hide_input\ndblock = DataBlock()\nshow_doc(dblock.databunch, name=\"DataBlock.databunch\")",
"_____no_output_____"
]
],
[
[
"You can create a `DataBlock` by passing functions or subclassing. The two following data blocks are the same for instance:",
"_____no_output_____"
]
],
[
[
"class MNIST(DataBlock):\n blocks = ImageBlock(cls=PILImageBW),CategoryBlock\n def get_items(self, source): return get_image_files(Path(source))\n def splitter (self, items ): return GrandparentSplitter()(items)\n def get_y (self, item ): return parent_label(item)\n \nmnist = MNIST()",
"_____no_output_____"
],
[
"mnist = DataBlock(blocks = (ImageBlock(cls=PILImageBW),CategoryBlock),\n get_items = get_image_files,\n splitter = GrandparentSplitter(),\n get_y = parent_label)",
"_____no_output_____"
]
],
[
[
"Each type comes with default transforms that will be applied\n- at the base level to create items in a tuple (usually input,target) from the base elements (like filenames)\n- at the item level of the datasource\n- at the batch level\n\nThey are called respectively type transforms, item transforms, batch transforms. In the case of MNIST, the type transforms are the method to create a `PILImageBW` (for the input) and the `Categorize` transform (for the target), the item transform is `ToTensor` and the batch transforms are `Cuda` and `IntToFloatTensor`. You can add any other transforms by passing them in `DataBlock.datasource` or `DataBlock.databunch`.",
"_____no_output_____"
]
],
[
[
"test_eq(mnist.default_type_tfms[0], [PILImageBW.create])\ntest_eq(mnist.default_type_tfms[1].map(type), [Categorize])\ntest_eq(mnist.default_item_tfms.map(type), [ToTensor])\ntest_eq(mnist.default_batch_tfms.map(type), [IntToFloatTensor])",
"_____no_output_____"
],
[
"dsrc = MNIST().datasource(untar_data(URLs.MNIST_TINY))\ntest_eq(dsrc.vocab, ['3', '7'])\nx,y = dsrc.train[0]\ntest_eq(x.size,(28,28))\nshow_at(dsrc.train, 0, cmap='Greys', figsize=(2,2));",
"_____no_output_____"
]
],
[
[
"## Export -",
"_____no_output_____"
]
],
[
[
"#hide\nfrom nbdev.export import notebook2script\nnotebook2script()",
"Converted 00_torch_core.ipynb.\nConverted 01_layers.ipynb.\nConverted 02_data.load.ipynb.\nConverted 03_data.core.ipynb.\nConverted 04_data.external.ipynb.\nConverted 05_data.transforms.ipynb.\nConverted 06_data.block.ipynb.\nConverted 07_vision.core.ipynb.\nConverted 08_vision.data.ipynb.\nConverted 09_vision.augment.ipynb.\nConverted 09b_vision.utils.ipynb.\nConverted 09c_vision.widgets.ipynb.\nConverted 10_tutorial.pets.ipynb.\nConverted 11_vision.models.xresnet.ipynb.\nConverted 12_optimizer.ipynb.\nConverted 13_learner.ipynb.\nConverted 13a_metrics.ipynb.\nConverted 14_callback.schedule.ipynb.\nConverted 14a_callback.data.ipynb.\nConverted 15_callback.hook.ipynb.\nConverted 15a_vision.models.unet.ipynb.\nConverted 16_callback.progress.ipynb.\nConverted 17_callback.tracker.ipynb.\nConverted 18_callback.fp16.ipynb.\nConverted 19_callback.mixup.ipynb.\nConverted 20_interpret.ipynb.\nConverted 20a_distributed.ipynb.\nConverted 21_vision.learner.ipynb.\nConverted 22_tutorial.imagenette.ipynb.\nConverted 23_tutorial.transfer_learning.ipynb.\nConverted 24_vision.gan.ipynb.\nConverted 30_text.core.ipynb.\nConverted 31_text.data.ipynb.\nConverted 32_text.models.awdlstm.ipynb.\nConverted 33_text.models.core.ipynb.\nConverted 34_callback.rnn.ipynb.\nConverted 35_tutorial.wikitext.ipynb.\nConverted 36_text.models.qrnn.ipynb.\nConverted 37_text.learner.ipynb.\nConverted 38_tutorial.ulmfit.ipynb.\nConverted 40_tabular.core.ipynb.\nConverted 41_tabular.data.ipynb.\nConverted 42_tabular.learner.ipynb.\nConverted 43_tabular.model.ipynb.\nConverted 45_collab.ipynb.\nConverted 50_datablock_examples.ipynb.\nConverted 60_medical.imaging.ipynb.\nConverted 65_medical.text.ipynb.\nConverted 70_callback.wandb.ipynb.\nConverted 71_callback.tensorboard.ipynb.\nConverted 97_test_utils.ipynb.\nConverted index.ipynb.\nConverted migrating.ipynb.\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a39642e1464f79ccee71f558fca29eed2f50b10
| 10,197 |
ipynb
|
Jupyter Notebook
|
Notebook/Word concreteness.ipynb
|
HerbertVidela/Tesis
|
d511f167a42ee4f77db3cf76ec1156e4618a4a71
|
[
"MIT"
] | null | null | null |
Notebook/Word concreteness.ipynb
|
HerbertVidela/Tesis
|
d511f167a42ee4f77db3cf76ec1156e4618a4a71
|
[
"MIT"
] | null | null | null |
Notebook/Word concreteness.ipynb
|
HerbertVidela/Tesis
|
d511f167a42ee4f77db3cf76ec1156e4618a4a71
|
[
"MIT"
] | null | null | null | 29.386167 | 376 | 0.547612 |
[
[
[
"### Import custom modules from current folder",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\n\nmodule_path = os.path.abspath(os.path.join('..'))\n\nif module_path not in sys.path:\n sys.path.append(module_path)",
"_____no_output_____"
],
[
"import nltk\nfrom text_easability_metrics import TextEasabilityMetrics, StanfordNLP\nfrom simple_text_representation.classes import Text\nfrom simple_text_representation.models import Database\nfrom nltk.tree import Tree\nimport pandas as pd\n# from nltk.draw.tree import draw_trees",
"_____no_output_____"
],
[
"database = Database('educationalTexts', 'postgres', '', '0.0.0.0', 5432)\npath = r'/Users/herbert/Projects/Tesis/stanford-corenlp-full-2017-06-09'\npath = r'http://corenlp.run'\npath = r'http://localhost/'",
"_____no_output_____"
]
],
[
[
"### Word Concreteness",
"_____no_output_____"
]
],
[
[
"def removeSpecialCharacters(strWord):\n return ''.join(character for character in strWord if character.isalnum())",
"_____no_output_____"
],
[
"def getWordNetTag(tag):\n if tag.startswith('J'):\n return wordnet.ADJ\n elif tag.startswith('S'):\n return wordnet.ADJ_SAT\n elif tag.startswith('R'):\n return wordnet.ADV\n elif tag.startswith('N'):\n return wordnet.NOUN\n elif tag.startswith('V'):\n return wordnet.VERB\n else:\n return ''",
"_____no_output_____"
],
[
"import nltk\nfrom nltk.corpus import wordnet\n\ndef getWordConcreteness(currentText):\n textTotal = 0\n for paragraph in currentText:\n sentenceCount = 0\n for sentence in paragraph:\n sentenceToken = nltk.word_tokenize(sentence)\n posTags = nltk.pos_tag(sentenceToken)\n for taggedWord in posTags:\n word = taggedWord[0]\n tag = taggedWord[1]pos_tag\n if (getWordNetTag(tag)):\n for ss in wordnet.synsets(word, getWordNetTag(tag), lang='spa'):\n hyperyms = ss.hypernym_paths()[0]\n if (len(hyperyms)) > 1:\n# print(ss.hypernym_paths()[0])\n category = ss.hypernym_paths()[0][1]\n sentenceCount += 1 if \"physical\" in category.name() else 0\n # print(ss, \"physical\" in category.name())\n textTotal += sentenceCount\n\n return textTotal",
"_____no_output_____"
],
[
"testTest = [['Si bien los trasplantes se han convertido en una práctica habitual, aún persisten fuertes temores en la población para donar órganos, lograr su superación es la clave para aumentar el número de los donadores solidarios que hacen falta para salvar miles de vidas.'],\n ['Es preciso, entonces, que se aclaren algunas dudas para que las personas pierdan el miedo a donar.',\n ' Primero, que lo complicado de los procedimientos de extirpación y trasplantación, en el que intervienen varios equipos médicos altamente especializados, vuelve muy difícil la existencia de mafias.',\n ' Segundo, que la necesaria compatibilidad (afinidad de grupo sanguíneo) entre donante y receptor dificulta la posibilidad de muertes “a pedido”.'],\n ['La última cuestión es la más compleja; en la actualidad, aunque alguien haya manifestado expresamente su voluntad de donar, es a la familia a la que se consulta en el momento en que la donación puede efectuarse.',\n ' Como se entiende, tal consulta llega en un momento difícil y poco propicio para las reflexiones profundas, más aún si se tiene que tomar una decisión rápida.'],\n ['Por lo tanto, las campañas públicas deben esclarecer la naturaleza de los procedimientos técnicos y legales, para disipar miedos; pero, esencialmente, deben apuntar a que se tome conciencia de lo que significa salvar otra vida, porque para decidirlo en un momento crucial es necesario que la idea se haya considerado y discutido previamente, con reflexión y calma.']]",
"_____no_output_____"
],
[
"getWordConcreteness(testTest)",
"_____no_output_____"
],
[
"textOfSeventhGrade = Text.getTexts(database, grade=7)\ntextOfEightGrade = Text.getTexts(database, grade=8)\ntextOfNineGrade = Text.getTexts(database, grade=9)\ntextOfTenthGrade = Text.getTexts(database, grade=10)\ntextOfEleventhGrade = Text.getTexts(database, grade=11)",
"_____no_output_____"
],
[
"def getResultsOfTexts(currentTexts):\n results = list()\n for text in currentTexts:\n results.append(getWordConcreteness(text))\n return results",
"_____no_output_____"
],
[
"resultsSeventh = getResultsOfTexts(textOfSeventhGrade)\nresultsMeanSeventh = sum(resultsSeventh)/len(resultsSeventh)",
"_____no_output_____"
],
[
"resultsEighth = getResultsOfTexts(textOfEightGrade)\nresultsMeanEighth = sum(resultsEighth)/len(resultsEighth)",
"_____no_output_____"
],
[
"resultsNinth = getResultsOfTexts(textOfNineGrade)\nresultsMeanNinth = sum(resultsNinth)/len(resultsNinth)",
"_____no_output_____"
],
[
"resultsTenh = getResultsOfTexts(textOfTenthGrade)\nresultsMeanTenth = sum(resultsTenh)/len(resultsTenh)",
"_____no_output_____"
],
[
"resultsEleventh = getResultsOfTexts(textOfEleventhGrade)\nresultsMeanEleventh = sum(resultsEleventh)/len(resultsEleventh)",
"_____no_output_____"
],
[
"import seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nsns.set_style(\"whitegrid\")\n\nresultsMean = [resultsMeanSeventh, resultsMeanEighth, resultsMeanNinth, resultsMeanTenth, resultsMeanEleventh]\n\ndata = np.array(resultsMean).reshape((1, len(resultsMean)))\nlabels = ['Primero', 'Segundo', 'Tercero', 'Cuarto', 'Quinto']\ndf = pd.DataFrame(data, columns=labels)\ndf\nax = sns.barplot(data=df)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a3968866905529c9dd543ecbe42be8c8fccd69b
| 2,154 |
ipynb
|
Jupyter Notebook
|
src/vad/VOX_2_display.ipynb
|
pawel-rozwoda/lstm-diarization
|
c900b08996bdd38b2d92182e8a428caa9de62445
|
[
"MIT"
] | null | null | null |
src/vad/VOX_2_display.ipynb
|
pawel-rozwoda/lstm-diarization
|
c900b08996bdd38b2d92182e8a428caa9de62445
|
[
"MIT"
] | null | null | null |
src/vad/VOX_2_display.ipynb
|
pawel-rozwoda/lstm-diarization
|
c900b08996bdd38b2d92182e8a428caa9de62445
|
[
"MIT"
] | null | null | null | 23.413043 | 92 | 0.530176 |
[
[
[
"# Vad on 2'nd vox dataset",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.append('../')\nfrom config import GMM_FILE, VOX_2_PATH\nfrom aux import Cluster, load_audio, int16_to_float\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom tqdm import tqdm\nimport pickle5\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\nSRC = VOX_2_PATH + 'aac/id00056/EEjaqWQ99uI/'\n\n\nvad_cluster=None\n\n\"\"\"reading ultimate gmm pkl\"\"\"\nwith open(GMM_FILE, 'rb') as fid:\n vad_cluster =pickle5.load(fid)\n \nfor filename in os.listdir(SRC):\n plt.figure(figsize=(14, 5))\n print(filename)\n\n sample_rate, audio = load_audio(SRC + filename, 16000, mono=True) \n speech = vad_cluster.detect_speech(signal=audio, fit_to_audio=True)\n\n plt.subplot(1, 1, 1)\n plt.ylim(-1., 1.)\n plt.plot(int16_to_float(audio))\n plt.title('single channel audio', x=.5, y=.6)\n plt.fill_between(range(speech.shape[0]), speech * .8,color='orange', alpha=0.3)\n\n plt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
]
] |
4a396eb325c33f03f9877db35bc79f55c385ea4c
| 6,577 |
ipynb
|
Jupyter Notebook
|
Assignment_TaskC_Producer3.ipynb
|
tonbao30/Parallel-dataprocessing-simulation
|
2674ad83009be73af719e0a837970e45857b7517
|
[
"MIT"
] | null | null | null |
Assignment_TaskC_Producer3.ipynb
|
tonbao30/Parallel-dataprocessing-simulation
|
2674ad83009be73af719e0a837970e45857b7517
|
[
"MIT"
] | null | null | null |
Assignment_TaskC_Producer3.ipynb
|
tonbao30/Parallel-dataprocessing-simulation
|
2674ad83009be73af719e0a837970e45857b7517
|
[
"MIT"
] | null | null | null | 43.846667 | 190 | 0.555877 |
[
[
[
"# import statements\nfrom time import sleep\nfrom json import dumps\nfrom kafka import KafkaProducer\nimport random\nimport datetime as dt\n",
"_____no_output_____"
],
[
"import csv\nimport json\n\ncsvfile = open('./assignment_data/hotspot_TERRA_streaming.csv', 'r')\n\n\nfieldnames = (\"lat\",\"lon\",\"confidence\",\"surface_temp\")\nreader = csv.DictReader( csvfile, fieldnames)\nrows = list(reader)\ndata = rows[1:]",
"_____no_output_____"
],
[
"# import statements\n\nfrom time import sleep\nfrom json import dumps\nfrom kafka import KafkaProducer\nimport random\nimport datetime as dt\n\nrandom.seed(123)\ndef publish_message(producer_instance, topic_name, key, data):\n try:\n key_bytes = bytes(key, encoding='utf-8')\n producer_instance.send(topic_name, key=key_bytes, value=data)\n producer_instance.flush()\n print('Message published successfully : ' + str(data))\n except Exception as ex:\n print('Exception in publishing message.')\n print(str(ex))\n \ndef connect_kafka_producer():\n _producer = None\n try:\n _producer = KafkaProducer(bootstrap_servers=['localhost:9092'],\n value_serializer=lambda x:dumps(x).encode('ascii'),\n api_version=(0, 10))\n except Exception as ex:\n print('Exception while connecting Kafka.')\n print(str(ex))\n finally:\n return _producer\n \n\n \nif __name__ == '__main__':\n \n topic = 'TaskC'\n \n print('Publishing records..')\n producer03 = connect_kafka_producer()\n \n #for selecting random data without replacement\n rd = random.sample(range(len(data)), len(data))\n \n for e in range(len(data)):\n #use datetime as ISO format for readable in mongoDB\n datetime = dt.datetime.now().replace(microsecond=0).isoformat()\n stream_data = {'created_time': datetime, 'sender_id': 3,'data' : data[rd[e]]}\n publish_message(producer03, topic,'sender_3', stream_data)\n interval = random.randrange(10,31)\n# uncomment to see the interval \n# print(interval)\n sleep(interval) #stream every 10-30 seconds",
"Publishing records..\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:01:59', 'data': {'confidence': '90', 'surface_temp': '67', 'lat': '-36.4325', 'lon': '144.3142'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:02:15', 'data': {'confidence': '90', 'surface_temp': '66', 'lat': '-35.1949', 'lon': '141.0622'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:02:40', 'data': {'confidence': '84', 'surface_temp': '58', 'lat': '-36.8871', 'lon': '145.1536'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:02:51', 'data': {'confidence': '93', 'surface_temp': '73', 'lat': '-37.4984', 'lon': '142.9739'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:03:19', 'data': {'confidence': '96', 'surface_temp': '77', 'lat': '-38.127', 'lon': '143.82'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:03:37', 'data': {'confidence': '55', 'surface_temp': '39', 'lat': '-36.7001', 'lon': '141.7567'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:04:06', 'data': {'confidence': '85', 'surface_temp': '59', 'lat': '-36.3739', 'lon': '141.3614'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:04:20', 'data': {'confidence': '59', 'surface_temp': '40', 'lat': '-38.0383', 'lon': '144.4307'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:04:34', 'data': {'confidence': '66', 'surface_temp': '45', 'lat': '-37.7331', 'lon': '142.923'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:04:52', 'data': {'confidence': '68', 'surface_temp': '44', 'lat': '-36.9986', 'lon': '143.8953'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:05:05', 'data': {'confidence': '73', 'surface_temp': '34', 'lat': '-37.561', 'lon': '148.032'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:05:18', 'data': {'confidence': '62', 'surface_temp': '43', 'lat': '-36.2455', 'lon': '141.3205'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:05:41', 'data': {'confidence': '66', 'surface_temp': '43', 'lat': '-36.5513', 'lon': '144.1473'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:06:06', 'data': {'confidence': '100', 'surface_temp': '96', 'lat': '-37.4352', 'lon': '143.1444'}}\nMessage published successfully : {'sender_id': 3, 'created_time': '2019-05-24T15:06:32', 'data': {'confidence': '81', 'surface_temp': '54', 'lat': '-37.7916', 'lon': '148.4098'}}\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
4a3973a20797412514bf1af921905480ded0cf7c
| 1,790 |
ipynb
|
Jupyter Notebook
|
numpy-obrazki.ipynb
|
MrUPGrade/hack4change-workshop
|
a8efb05abeb7df35e45e2f5cf0e3f1a5fba5e02f
|
[
"MIT"
] | 5 |
2020-06-20T10:34:03.000Z
|
2020-06-21T10:35:42.000Z
|
numpy-obrazki.ipynb
|
MrUPGrade/hack4change-workshop
|
a8efb05abeb7df35e45e2f5cf0e3f1a5fba5e02f
|
[
"MIT"
] | null | null | null |
numpy-obrazki.ipynb
|
MrUPGrade/hack4change-workshop
|
a8efb05abeb7df35e45e2f5cf0e3f1a5fba5e02f
|
[
"MIT"
] | null | null | null | 18.453608 | 83 | 0.508939 |
[
[
[
"# Numpy - obrazki\n\nTest tego, jak numpy współpracuje z bibliotekami do operacji na obrazkach.\n\nhttps://pillow.readthedocs.io/en/stable/",
"_____no_output_____"
]
],
[
[
"from PIL import Image\nimport numpy as np",
"_____no_output_____"
],
[
"arr = np.linspace(1, 100, num=100)\narr",
"_____no_output_____"
],
[
"box = arr.reshape(10, 10).repeat(20, axis=0).repeat(20, axis=1)\nbox",
"_____no_output_____"
],
[
"img1 = Image.fromarray(box.astype(dtype=np.uint8), \"P\")\nimg1",
"_____no_output_____"
],
[
"box2 = box * 2.5\nbox2",
"_____no_output_____"
],
[
"img2 = Image.fromarray(box2.astype(dtype=np.uint8), \"P\")\nimg2",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.