markdown
stringlengths 0
1.02M
| code
stringlengths 0
832k
| output
stringlengths 0
1.02M
| license
stringlengths 3
36
| path
stringlengths 6
265
| repo_name
stringlengths 6
127
|
---|---|---|---|---|---|
Write output | human_outdir = 'Eukaryota/human-visual-transduction-fastas/'
! mkdir $human_outdir
with open(f'{human_outdir}/human_visual_transduction_proteins.fasta', 'w') as f:
for record in tf_records:
f.write(">{name}\n{sequence}\n".format(**record)) | mkdir: cannot create directory ‘Eukaryota/human-visual-transduction-fastas/’: File exists
| MIT | notebooks/521_subset_human_retina_genes.ipynb | czbiohub/kh-analysis |
Building your Recurrent Neural Network - Step by StepWelcome to Course 5's first assignment! In this assignment, you will implement your first Recurrent Neural Network in numpy.Recurrent Neural Networks (RNN) are very effective for Natural Language Processing and other sequence tasks because they have "memory". They can read inputs $x^{\langle t \rangle}$ (such as words) one at a time, and remember some information/context through the hidden layer activations that get passed from one time-step to the next. This allows a uni-directional RNN to take information from the past to process later inputs. A bidirection RNN can take context from both the past and the future. **Notation**:- Superscript $[l]$ denotes an object associated with the $l^{th}$ layer. - Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters.- Superscript $(i)$ denotes an object associated with the $i^{th}$ example. - Example: $x^{(i)}$ is the $i^{th}$ training example input.- Superscript $\langle t \rangle$ denotes an object at the $t^{th}$ time-step. - Example: $x^{\langle t \rangle}$ is the input x at the $t^{th}$ time-step. $x^{(i)\langle t \rangle}$ is the input at the $t^{th}$ timestep of example $i$. - Lowerscript $i$ denotes the $i^{th}$ entry of a vector. - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$.We assume that you are already familiar with `numpy` and/or have completed the previous courses of the specialization. Let's get started! Let's first import all the packages that you will need during this assignment. | import numpy as np
from rnn_utils import * | _____no_output_____ | MIT | Course5 - Sequence Models/week1 Recurrent Neural Networks/Building a recurrent neural network/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb | bheil123/DeepLearning |
1 - Forward propagation for the basic Recurrent Neural NetworkLater this week, you will generate music using an RNN. The basic RNN that you will implement has the structure below. In this example, $T_x = T_y$. **Figure 1**: Basic RNN model Here's how you can implement an RNN: **Steps**:1. Implement the calculations needed for one time-step of the RNN.2. Implement a loop over $T_x$ time-steps in order to process all the inputs, one at a time. Let's go! 1.1 - RNN cellA Recurrent neural network can be seen as the repetition of a single cell. You are first going to implement the computations for a single time-step. The following figure describes the operations for a single time-step of an RNN cell. **Figure 2**: Basic RNN cell. Takes as input $x^{\langle t \rangle}$ (current input) and $a^{\langle t - 1\rangle}$ (previous hidden state containing information from the past), and outputs $a^{\langle t \rangle}$ which is given to the next RNN cell and also used to predict $y^{\langle t \rangle}$ **Exercise**: Implement the RNN-cell described in Figure (2).**Instructions**:1. Compute the hidden state with tanh activation: $a^{\langle t \rangle} = \tanh(W_{aa} a^{\langle t-1 \rangle} + W_{ax} x^{\langle t \rangle} + b_a)$.2. Using your new hidden state $a^{\langle t \rangle}$, compute the prediction $\hat{y}^{\langle t \rangle} = softmax(W_{ya} a^{\langle t \rangle} + b_y)$. We provided you a function: `softmax`.3. Store $(a^{\langle t \rangle}, a^{\langle t-1 \rangle}, x^{\langle t \rangle}, parameters)$ in cache4. Return $a^{\langle t \rangle}$ , $y^{\langle t \rangle}$ and cacheWe will vectorize over $m$ examples. Thus, $x^{\langle t \rangle}$ will have dimension $(n_x,m)$, and $a^{\langle t \rangle}$ will have dimension $(n_a,m)$. | # GRADED FUNCTION: rnn_cell_forward
def rnn_cell_forward(xt, a_prev, parameters):
"""
Implements a single forward step of the RNN-cell as described in Figure (2)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias, numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a_next -- next hidden state, of shape (n_a, m)
yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
cache -- tuple of values needed for the backward pass, contains (a_next, a_prev, xt, parameters)
"""
# Retrieve parameters from "parameters"
Wax = parameters["Wax"]
Waa = parameters["Waa"]
Wya = parameters["Wya"]
ba = parameters["ba"]
by = parameters["by"]
### START CODE HERE ### (≈2 lines)
# compute next activation state using the formula given above
a_next = np.tanh(np.dot(Wax,xt) + np.dot(Waa, a_prev) + ba)
# compute output of the current cell using the formula given above
yt_pred = softmax(np.dot(Wya, a_next) + by)
### END CODE HERE ###
# store values you need for backward propagation in cache
cache = (a_next, a_prev, xt, parameters)
return a_next, yt_pred, cache
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
Waa = np.random.randn(5,5)
Wax = np.random.randn(5,3)
Wya = np.random.randn(2,5)
ba = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Waa": Waa, "Wax": Wax, "Wya": Wya, "ba": ba, "by": by}
a_next, yt_pred, cache = rnn_cell_forward(xt, a_prev, parameters)
print("a_next[4] = ", a_next[4])
print("a_next.shape = ", a_next.shape)
print("yt_pred[1] =", yt_pred[1])
print("yt_pred.shape = ", yt_pred.shape) | a_next[4] = [ 0.59584544 0.18141802 0.61311866 0.99808218 0.85016201 0.99980978
-0.18887155 0.99815551 0.6531151 0.82872037]
a_next.shape = (5, 10)
yt_pred[1] = [ 0.9888161 0.01682021 0.21140899 0.36817467 0.98988387 0.88945212
0.36920224 0.9966312 0.9982559 0.17746526]
yt_pred.shape = (2, 10)
| MIT | Course5 - Sequence Models/week1 Recurrent Neural Networks/Building a recurrent neural network/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb | bheil123/DeepLearning |
**Expected Output**: **a_next[4]**: [ 0.59584544 0.18141802 0.61311866 0.99808218 0.85016201 0.99980978 -0.18887155 0.99815551 0.6531151 0.82872037] **a_next.shape**: (5, 10) **yt[1]**: [ 0.9888161 0.01682021 0.21140899 0.36817467 0.98988387 0.88945212 0.36920224 0.9966312 0.9982559 0.17746526] **yt.shape**: (2, 10) 1.2 - RNN forward pass You can see an RNN as the repetition of the cell you've just built. If your input sequence of data is carried over 10 time steps, then you will copy the RNN cell 10 times. Each cell takes as input the hidden state from the previous cell ($a^{\langle t-1 \rangle}$) and the current time-step's input data ($x^{\langle t \rangle}$). It outputs a hidden state ($a^{\langle t \rangle}$) and a prediction ($y^{\langle t \rangle}$) for this time-step. **Figure 3**: Basic RNN. The input sequence $x = (x^{\langle 1 \rangle}, x^{\langle 2 \rangle}, ..., x^{\langle T_x \rangle})$ is carried over $T_x$ time steps. The network outputs $y = (y^{\langle 1 \rangle}, y^{\langle 2 \rangle}, ..., y^{\langle T_x \rangle})$. **Exercise**: Code the forward propagation of the RNN described in Figure (3).**Instructions**:1. Create a vector of zeros ($a$) that will store all the hidden states computed by the RNN.2. Initialize the "next" hidden state as $a_0$ (initial hidden state).3. Start looping over each time step, your incremental index is $t$ : - Update the "next" hidden state and the cache by running `rnn_cell_forward` - Store the "next" hidden state in $a$ ($t^{th}$ position) - Store the prediction in y - Add the cache to the list of caches4. Return $a$, $y$ and caches | # GRADED FUNCTION: rnn_forward
def rnn_forward(x, a0, parameters):
"""
Implement the forward propagation of the recurrent neural network described in Figure (3).
Arguments:
x -- Input data for every time-step, of shape (n_x, m, T_x).
a0 -- Initial hidden state, of shape (n_a, m)
parameters -- python dictionary containing:
Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
y_pred -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
caches -- tuple of values needed for the backward pass, contains (list of caches, x)
"""
# Initialize "caches" which will contain the list of all caches
caches = []
# Retrieve dimensions from shapes of x and parameters["Wya"]
n_x, m, T_x = x.shape
n_y, n_a = parameters["Wya"].shape
### START CODE HERE ###
# initialize "a" and "y" with zeros (≈2 lines)
a = np.zeros((n_a, m, T_x))
y_pred = np.zeros((n_y, m, T_x))
# Initialize a_next (≈1 line)
a_next = a0
# loop over all time-steps
for t in range(T_x):
# Update next hidden state, compute the prediction, get the cache (≈1 line)
a_next, yt_pred, cache = rnn_cell_forward(x[:,:,t], a_next, parameters)
# Save the value of the new "next" hidden state in a (≈1 line)
a[:,:,t] = a_next
# Save the value of the prediction in y (≈1 line)
y_pred[:,:,t] = yt_pred
# Append "cache" to "caches" (≈1 line)
caches.append(cache)
### END CODE HERE ###
# store values needed for backward propagation in cache
caches = (caches, x)
return a, y_pred, caches
np.random.seed(1)
x = np.random.randn(3,10,4)
a0 = np.random.randn(5,10)
Waa = np.random.randn(5,5)
Wax = np.random.randn(5,3)
Wya = np.random.randn(2,5)
ba = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Waa": Waa, "Wax": Wax, "Wya": Wya, "ba": ba, "by": by}
a, y_pred, caches = rnn_forward(x, a0, parameters)
print("a[4][1] = ", a[4][1])
print("a.shape = ", a.shape)
print("y_pred[1][3] =", y_pred[1][3])
print("y_pred.shape = ", y_pred.shape)
print("caches[1][1][3] =", caches[1][1][3])
print("len(caches) = ", len(caches)) | a[4][1] = [-0.99999375 0.77911235 -0.99861469 -0.99833267]
a.shape = (5, 10, 4)
y_pred[1][3] = [ 0.79560373 0.86224861 0.11118257 0.81515947]
y_pred.shape = (2, 10, 4)
caches[1][1][3] = [-1.1425182 -0.34934272 -0.20889423 0.58662319]
len(caches) = 2
| MIT | Course5 - Sequence Models/week1 Recurrent Neural Networks/Building a recurrent neural network/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb | bheil123/DeepLearning |
**Expected Output**: **a[4][1]**: [-0.99999375 0.77911235 -0.99861469 -0.99833267] **a.shape**: (5, 10, 4) **y[1][3]**: [ 0.79560373 0.86224861 0.11118257 0.81515947] **y.shape**: (2, 10, 4) **cache[1][1][3]**: [-1.1425182 -0.34934272 -0.20889423 0.58662319] **len(cache)**: 2 Congratulations! You've successfully built the forward propagation of a recurrent neural network from scratch. This will work well enough for some applications, but it suffers from vanishing gradient problems. So it works best when each output $y^{\langle t \rangle}$ can be estimated using mainly "local" context (meaning information from inputs $x^{\langle t' \rangle}$ where $t'$ is not too far from $t$). In the next part, you will build a more complex LSTM model, which is better at addressing vanishing gradients. The LSTM will be better able to remember a piece of information and keep it saved for many timesteps. 2 - Long Short-Term Memory (LSTM) networkThis following figure shows the operations of an LSTM-cell. **Figure 4**: LSTM-cell. This tracks and updates a "cell state" or memory variable $c^{\langle t \rangle}$ at every time-step, which can be different from $a^{\langle t \rangle}$. Similar to the RNN example above, you will start by implementing the LSTM cell for a single time-step. Then you can iteratively call it from inside a for-loop to have it process an input with $T_x$ time-steps. About the gates - Forget gateFor the sake of this illustration, lets assume we are reading words in a piece of text, and want use an LSTM to keep track of grammatical structures, such as whether the subject is singular or plural. If the subject changes from a singular word to a plural word, we need to find a way to get rid of our previously stored memory value of the singular/plural state. In an LSTM, the forget gate lets us do this: $$\Gamma_f^{\langle t \rangle} = \sigma(W_f[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_f)\tag{1} $$Here, $W_f$ are weights that govern the forget gate's behavior. We concatenate $[a^{\langle t-1 \rangle}, x^{\langle t \rangle}]$ and multiply by $W_f$. The equation above results in a vector $\Gamma_f^{\langle t \rangle}$ with values between 0 and 1. This forget gate vector will be multiplied element-wise by the previous cell state $c^{\langle t-1 \rangle}$. So if one of the values of $\Gamma_f^{\langle t \rangle}$ is 0 (or close to 0) then it means that the LSTM should remove that piece of information (e.g. the singular subject) in the corresponding component of $c^{\langle t-1 \rangle}$. If one of the values is 1, then it will keep the information. - Update gateOnce we forget that the subject being discussed is singular, we need to find a way to update it to reflect that the new subject is now plural. Here is the formulat for the update gate: $$\Gamma_u^{\langle t \rangle} = \sigma(W_u[a^{\langle t-1 \rangle}, x^{\{t\}}] + b_u)\tag{2} $$ Similar to the forget gate, here $\Gamma_u^{\langle t \rangle}$ is again a vector of values between 0 and 1. This will be multiplied element-wise with $\tilde{c}^{\langle t \rangle}$, in order to compute $c^{\langle t \rangle}$. - Updating the cell To update the new subject we need to create a new vector of numbers that we can add to our previous cell state. The equation we use is: $$ \tilde{c}^{\langle t \rangle} = \tanh(W_c[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_c)\tag{3} $$Finally, the new cell state is: $$ c^{\langle t \rangle} = \Gamma_f^{\langle t \rangle}* c^{\langle t-1 \rangle} + \Gamma_u^{\langle t \rangle} *\tilde{c}^{\langle t \rangle} \tag{4} $$ - Output gateTo decide which outputs we will use, we will use the following two formulas: $$ \Gamma_o^{\langle t \rangle}= \sigma(W_o[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_o)\tag{5}$$ $$ a^{\langle t \rangle} = \Gamma_o^{\langle t \rangle}* \tanh(c^{\langle t \rangle})\tag{6} $$Where in equation 5 you decide what to output using a sigmoid function and in equation 6 you multiply that by the $\tanh$ of the previous state. 2.1 - LSTM cell**Exercise**: Implement the LSTM cell described in the Figure (3).**Instructions**:1. Concatenate $a^{\langle t-1 \rangle}$ and $x^{\langle t \rangle}$ in a single matrix: $concat = \begin{bmatrix} a^{\langle t-1 \rangle} \\ x^{\langle t \rangle} \end{bmatrix}$2. Compute all the formulas 1-6. You can use `sigmoid()` (provided) and `np.tanh()`.3. Compute the prediction $y^{\langle t \rangle}$. You can use `softmax()` (provided). | # GRADED FUNCTION: lstm_cell_forward
def lstm_cell_forward(xt, a_prev, c_prev, parameters):
"""
Implement a single forward step of the LSTM-cell as described in Figure (4)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
c_prev -- Memory state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:
Wf -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
bf -- Bias of the forget gate, numpy array of shape (n_a, 1)
Wi -- Weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
bi -- Bias of the update gate, numpy array of shape (n_a, 1)
Wc -- Weight matrix of the first "tanh", numpy array of shape (n_a, n_a + n_x)
bc -- Bias of the first "tanh", numpy array of shape (n_a, 1)
Wo -- Weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)
bo -- Bias of the output gate, numpy array of shape (n_a, 1)
Wy -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a_next -- next hidden state, of shape (n_a, m)
c_next -- next memory state, of shape (n_a, m)
yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
cache -- tuple of values needed for the backward pass, contains (a_next, c_next, a_prev, c_prev, xt, parameters)
Note: ft/it/ot stand for the forget/update/output gates, cct stands for the candidate value (c tilde),
c stands for the memory value
"""
# Retrieve parameters from "parameters"
Wf = parameters["Wf"]
bf = parameters["bf"]
Wi = parameters["Wi"]
bi = parameters["bi"]
Wc = parameters["Wc"]
bc = parameters["bc"]
Wo = parameters["Wo"]
bo = parameters["bo"]
Wy = parameters["Wy"]
by = parameters["by"]
# Retrieve dimensions from shapes of xt and Wy
n_x, m = xt.shape
n_y, n_a = Wy.shape
### START CODE HERE ###
# Concatenate a_prev and xt (≈3 lines)
concat = np.zeros((n_a+n_x, m))
concat[:n_a, :] = a_prev
concat[n_a:, :] = xt
# Compute values for ft, it, cct, c_next, ot, a_next using the formulas given figure (4) (≈6 lines)
ft = sigmoid(np.dot(Wf, concat) + bf)
it = sigmoid(np.dot(Wi, concat) + bi)
ctilda = np.tanh(np.dot(Wc, concat) + bc)
c_next = ft*c_prev + it* ctilda
ot = sigmoid(np.dot(Wo, concat) + bo)
a_next = ot*np.tanh(c_next)
# Compute prediction of the LSTM cell (≈1 line)
yt_pred = softmax(np.dot(Wy, a_next) + by)
### END CODE HERE ###
# store values needed for backward propagation in cache
#cache = (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters)
cache = (a_next, c_next, a_prev, c_prev, ft, it, ctilda, ot, xt, parameters)
return a_next, c_next, yt_pred, cache
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
c_prev = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
Wy = np.random.randn(2,5)
by = np.random.randn(2,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a_next, c_next, yt, cache = lstm_cell_forward(xt, a_prev, c_prev, parameters)
print("a_next[4] = ", a_next[4])
print("a_next.shape = ", c_next.shape)
print("c_next[2] = ", c_next[2])
print("c_next.shape = ", c_next.shape)
print("yt[1] =", yt[1])
print("yt.shape = ", yt.shape)
print("cache[1][3] =", cache[1][3])
print("len(cache) = ", len(cache)) | a_next[4] = [-0.66408471 0.0036921 0.02088357 0.22834167 -0.85575339 0.00138482
0.76566531 0.34631421 -0.00215674 0.43827275]
a_next.shape = (5, 10)
c_next[2] = [ 0.63267805 1.00570849 0.35504474 0.20690913 -1.64566718 0.11832942
0.76449811 -0.0981561 -0.74348425 -0.26810932]
c_next.shape = (5, 10)
yt[1] = [ 0.79913913 0.15986619 0.22412122 0.15606108 0.97057211 0.31146381
0.00943007 0.12666353 0.39380172 0.07828381]
yt.shape = (2, 10)
cache[1][3] = [-0.16263996 1.03729328 0.72938082 -0.54101719 0.02752074 -0.30821874
0.07651101 -1.03752894 1.41219977 -0.37647422]
len(cache) = 10
| MIT | Course5 - Sequence Models/week1 Recurrent Neural Networks/Building a recurrent neural network/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb | bheil123/DeepLearning |
**Expected Output**: **a_next[4]**: [-0.66408471 0.0036921 0.02088357 0.22834167 -0.85575339 0.00138482 0.76566531 0.34631421 -0.00215674 0.43827275] **a_next.shape**: (5, 10) **c_next[2]**: [ 0.63267805 1.00570849 0.35504474 0.20690913 -1.64566718 0.11832942 0.76449811 -0.0981561 -0.74348425 -0.26810932] **c_next.shape**: (5, 10) **yt[1]**: [ 0.79913913 0.15986619 0.22412122 0.15606108 0.97057211 0.31146381 0.00943007 0.12666353 0.39380172 0.07828381] **yt.shape**: (2, 10) **cache[1][3]**: [-0.16263996 1.03729328 0.72938082 -0.54101719 0.02752074 -0.30821874 0.07651101 -1.03752894 1.41219977 -0.37647422] **len(cache)**: 10 2.2 - Forward pass for LSTMNow that you have implemented one step of an LSTM, you can now iterate this over this using a for-loop to process a sequence of $T_x$ inputs. **Figure 4**: LSTM over multiple time-steps. **Exercise:** Implement `lstm_forward()` to run an LSTM over $T_x$ time-steps. **Note**: $c^{\langle 0 \rangle}$ is initialized with zeros. | # GRADED FUNCTION: lstm_forward
def lstm_forward(x, a0, parameters):
"""
Implement the forward propagation of the recurrent neural network using an LSTM-cell described in Figure (3).
Arguments:
x -- Input data for every time-step, of shape (n_x, m, T_x).
a0 -- Initial hidden state, of shape (n_a, m)
parameters -- python dictionary containing:
Wf -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
bf -- Bias of the forget gate, numpy array of shape (n_a, 1)
Wi -- Weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
bi -- Bias of the update gate, numpy array of shape (n_a, 1)
Wc -- Weight matrix of the first "tanh", numpy array of shape (n_a, n_a + n_x)
bc -- Bias of the first "tanh", numpy array of shape (n_a, 1)
Wo -- Weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)
bo -- Bias of the output gate, numpy array of shape (n_a, 1)
Wy -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
y -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
caches -- tuple of values needed for the backward pass, contains (list of all the caches, x)
"""
# Initialize "caches", which will track the list of all the caches
caches = []
### START CODE HERE ###
# Retrieve dimensions from shapes of x and parameters['Wy'] (≈2 lines)
n_x, m, T_x = x.shape
n_y, n_a = parameters['Wy'].shape
# initialize "a", "c" and "y" with zeros (≈3 lines)
a = np.zeros((n_a, m, T_x))
c = np.zeros((n_a, m, T_x))
y = np.zeros((n_y, m, T_x))
# Initialize a_next and c_next (≈2 lines)
a_next = a0
c_next = np.zeros((n_a, m))
# loop over all time-steps
for t in range(T_x):
# Update next hidden state, next memory state, compute the prediction, get the cache (≈1 line)
a_next, c_next, yt, cache = lstm_cell_forward(x[:,:,t], a_next, c_next, parameters)
# Save the value of the new "next" hidden state in a (≈1 line)
a[:,:,t] = a_next
# Save the value of the prediction in y (≈1 line)
y[:,:,t] = yt
# Save the value of the next cell state (≈1 line)
c[:,:,t] = c_next
# Append the cache into caches (≈1 line)
caches.append(cache)
### END CODE HERE ###
# store values needed for backward propagation in cache
caches = (caches, x)
return a, y, c, caches
np.random.seed(1)
x = np.random.randn(3,10,7)
a0 = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
Wy = np.random.randn(2,5)
by = np.random.randn(2,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a, y, c, caches = lstm_forward(x, a0, parameters)
print("a[4][3][6] = ", a[4][3][6])
print("a.shape = ", a.shape)
print("y[1][4][3] =", y[1][4][3])
print("y.shape = ", y.shape)
print("caches[1][1[1]] =", caches[1][1][1])
print("c[1][2][1]", c[1][2][1])
print("len(caches) = ", len(caches)) | a[4][3][6] = 0.172117767533
a.shape = (5, 10, 7)
y[1][4][3] = 0.95087346185
y.shape = (2, 10, 7)
caches[1][1[1]] = [ 0.82797464 0.23009474 0.76201118 -0.22232814 -0.20075807 0.18656139
0.41005165]
c[1][2][1] -0.855544916718
len(caches) = 2
| MIT | Course5 - Sequence Models/week1 Recurrent Neural Networks/Building a recurrent neural network/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb | bheil123/DeepLearning |
**Expected Output**: **a[4][3][6]** = 0.172117767533 **a.shape** = (5, 10, 7) **y[1][4][3]** = 0.95087346185 **y.shape** = (2, 10, 7) **caches[1][1][1]** = [ 0.82797464 0.23009474 0.76201118 -0.22232814 -0.20075807 0.18656139 0.41005165] **c[1][2][1]** = -0.855544916718 **len(caches)** = 2 Congratulations! You have now implemented the forward passes for the basic RNN and the LSTM. When using a deep learning framework, implementing the forward pass is sufficient to build systems that achieve great performance. The rest of this notebook is optional, and will not be graded. 3 - Backpropagation in recurrent neural networks (OPTIONAL / UNGRADED)In modern deep learning frameworks, you only have to implement the forward pass, and the framework takes care of the backward pass, so most deep learning engineers do not need to bother with the details of the backward pass. If however you are an expert in calculus and want to see the details of backprop in RNNs, you can work through this optional portion of the notebook. When in an earlier course you implemented a simple (fully connected) neural network, you used backpropagation to compute the derivatives with respect to the cost to update the parameters. Similarly, in recurrent neural networks you can to calculate the derivatives with respect to the cost in order to update the parameters. The backprop equations are quite complicated and we did not derive them in lecture. However, we will briefly present them below. 3.1 - Basic RNN backward passWe will start by computing the backward pass for the basic RNN-cell. **Figure 5**: RNN-cell's backward pass. Just like in a fully-connected neural network, the derivative of the cost function $J$ backpropagates through the RNN by following the chain-rule from calculas. The chain-rule is also used to calculate $(\frac{\partial J}{\partial W_{ax}},\frac{\partial J}{\partial W_{aa}},\frac{\partial J}{\partial b})$ to update the parameters $(W_{ax}, W_{aa}, b_a)$. Deriving the one step backward functions: To compute the `rnn_cell_backward` you need to compute the following equations. It is a good exercise to derive them by hand. The derivative of $\tanh$ is $1-\tanh(x)^2$. You can find the complete proof [here](https://www.wyzant.com/resources/lessons/math/calculus/derivative_proofs/tanx). Note that: $ \text{sech}(x)^2 = 1 - \tanh(x)^2$Similarly for $\frac{ \partial a^{\langle t \rangle} } {\partial W_{ax}}, \frac{ \partial a^{\langle t \rangle} } {\partial W_{aa}}, \frac{ \partial a^{\langle t \rangle} } {\partial b}$, the derivative of $\tanh(u)$ is $(1-\tanh(u)^2)du$. The final two equations also follow same rule and are derived using the $\tanh$ derivative. Note that the arrangement is done in a way to get the same dimensions to match. | def rnn_cell_backward(da_next, cache):
"""
Implements the backward pass for the RNN-cell (single time-step).
Arguments:
da_next -- Gradient of loss with respect to next hidden state
cache -- python dictionary containing useful values (output of rnn_cell_forward())
Returns:
gradients -- python dictionary containing:
dx -- Gradients of input data, of shape (n_x, m)
da_prev -- Gradients of previous hidden state, of shape (n_a, m)
dWax -- Gradients of input-to-hidden weights, of shape (n_a, n_x)
dWaa -- Gradients of hidden-to-hidden weights, of shape (n_a, n_a)
dba -- Gradients of bias vector, of shape (n_a, 1)
"""
# Retrieve values from cache
(a_next, a_prev, xt, parameters) = cache
# Retrieve values from parameters
Wax = parameters["Wax"]
Waa = parameters["Waa"]
Wya = parameters["Wya"]
ba = parameters["ba"]
by = parameters["by"]
### START CODE HERE ###
# compute the gradient of tanh with respect to a_next (≈1 line)
dtanh = (1 - a_next**2) * da_next
# compute the gradient of the loss with respect to Wax (≈2 lines)
dxt = np.dot(Wax.T, dtanh)
dWax = np.dot(dtanh, xt.T)
# compute the gradient with respect to Waa (≈2 lines)
da_prev = np.dot(Waa.T, dtanh)
dWaa = np.dot(dtanh, a_prev.T)
# compute the gradient with respect to b (≈1 line)
dba = np.sum(dtanh, 1, keepdims=True)
### END CODE HERE ###
# Store the gradients in a python dictionary
gradients = {"dxt": dxt, "da_prev": da_prev, "dWax": dWax, "dWaa": dWaa, "dba": dba}
return gradients
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
Wax = np.random.randn(5,3)
Waa = np.random.randn(5,5)
Wya = np.random.randn(2,5)
b = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "ba": ba, "by": by}
a_next, yt, cache = rnn_cell_forward(xt, a_prev, parameters)
da_next = np.random.randn(5,10)
gradients = rnn_cell_backward(da_next, cache)
print("gradients[\"dxt\"][1][2] =", gradients["dxt"][1][2])
print("gradients[\"dxt\"].shape =", gradients["dxt"].shape)
print("gradients[\"da_prev\"][2][3] =", gradients["da_prev"][2][3])
print("gradients[\"da_prev\"].shape =", gradients["da_prev"].shape)
print("gradients[\"dWax\"][3][1] =", gradients["dWax"][3][1])
print("gradients[\"dWax\"].shape =", gradients["dWax"].shape)
print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2])
print("gradients[\"dWaa\"].shape =", gradients["dWaa"].shape)
print("gradients[\"dba\"][4] =", gradients["dba"][4])
print("gradients[\"dba\"].shape =", gradients["dba"].shape) | gradients["dxt"][1][2] = -0.460564103059
gradients["dxt"].shape = (3, 10)
gradients["da_prev"][2][3] = 0.0842968653807
gradients["da_prev"].shape = (5, 10)
gradients["dWax"][3][1] = 0.393081873922
gradients["dWax"].shape = (5, 3)
gradients["dWaa"][1][2] = -0.28483955787
gradients["dWaa"].shape = (5, 5)
gradients["dba"][4] = [ 0.80517166]
gradients["dba"].shape = (5, 1)
| MIT | Course5 - Sequence Models/week1 Recurrent Neural Networks/Building a recurrent neural network/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb | bheil123/DeepLearning |
**Expected Output**: **gradients["dxt"][1][2]** = -0.460564103059 **gradients["dxt"].shape** = (3, 10) **gradients["da_prev"][2][3]** = 0.0842968653807 **gradients["da_prev"].shape** = (5, 10) **gradients["dWax"][3][1]** = 0.393081873922 **gradients["dWax"].shape** = (5, 3) **gradients["dWaa"][1][2]** = -0.28483955787 **gradients["dWaa"].shape** = (5, 5) **gradients["dba"][4]** = [ 0.80517166] **gradients["dba"].shape** = (5, 1) Backward pass through the RNNComputing the gradients of the cost with respect to $a^{\langle t \rangle}$ at every time-step $t$ is useful because it is what helps the gradient backpropagate to the previous RNN-cell. To do so, you need to iterate through all the time steps starting at the end, and at each step, you increment the overall $db_a$, $dW_{aa}$, $dW_{ax}$ and you store $dx$.**Instructions**:Implement the `rnn_backward` function. Initialize the return variables with zeros first and then loop through all the time steps while calling the `rnn_cell_backward` at each time timestep, update the other variables accordingly. | def rnn_backward(da, caches):
"""
Implement the backward pass for a RNN over an entire sequence of input data.
Arguments:
da -- Upstream gradients of all hidden states, of shape (n_a, m, T_x)
caches -- tuple containing information from the forward pass (rnn_forward)
Returns:
gradients -- python dictionary containing:
dx -- Gradient w.r.t. the input data, numpy-array of shape (n_x, m, T_x)
da0 -- Gradient w.r.t the initial hidden state, numpy-array of shape (n_a, m)
dWax -- Gradient w.r.t the input's weight matrix, numpy-array of shape (n_a, n_x)
dWaa -- Gradient w.r.t the hidden state's weight matrix, numpy-arrayof shape (n_a, n_a)
dba -- Gradient w.r.t the bias, of shape (n_a, 1)
"""
### START CODE HERE ###
# Retrieve values from the first cache (t=1) of caches (≈2 lines)
(caches, x) = caches
(a1, a0, x1, parameters) = caches[0]
# Retrieve dimensions from da's and x1's shapes (≈2 lines)
n_a, m, T_x = da.shape
n_x, m = x1.shape
# initialize the gradients with the right sizes (≈6 lines)
dx = np.zeros((n_x, m, T_x))
dWax = np.zeros((n_a, n_x))
dWaa = np.zeros((n_a, n_a))
dba = np.zeros((n_a, 1))
da0 = np.zeros((n_a, m))
da_prevt = np.zeros((n_a, m))
# Loop through all the time steps
for t in reversed(range(T_x)):
# Compute gradients at time step t. Choose wisely the "da_next" and the "cache" to use in the backward propagation step. (≈1 line)
gradients = rnn_cell_backward(da[:,:, t] + da_prevt, caches[t])
# Retrieve derivatives from gradients (≈ 1 line)
dxt, da_prevt, dWaxt, dWaat, dbat = gradients["dxt"], gradients["da_prev"], gradients["dWax"], gradients["dWaa"], gradients["dba"]
# Increment global derivatives w.r.t parameters by adding their derivative at time-step t (≈4 lines)
dx[:, :, t] = dxt
dWax += dWaxt
dWaa += dWaat
dba += dbat
# Set da0 to the gradient of a which has been backpropagated through all time-steps (≈1 line)
da0 = da_prevt
### END CODE HERE ###
# Store the gradients in a python dictionary
gradients = {"dx": dx, "da0": da0, "dWax": dWax, "dWaa": dWaa,"dba": dba}
return gradients
np.random.seed(1)
x = np.random.randn(3,10,4)
a0 = np.random.randn(5,10)
Wax = np.random.randn(5,3)
Waa = np.random.randn(5,5)
Wya = np.random.randn(2,5)
ba = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "ba": ba, "by": by}
a, y, caches = rnn_forward(x, a0, parameters)
da = np.random.randn(5, 10, 4)
gradients = rnn_backward(da, caches)
print("gradients[\"dx\"][1][2] =", gradients["dx"][1][2])
print("gradients[\"dx\"].shape =", gradients["dx"].shape)
print("gradients[\"da0\"][2][3] =", gradients["da0"][2][3])
print("gradients[\"da0\"].shape =", gradients["da0"].shape)
print("gradients[\"dWax\"][3][1] =", gradients["dWax"][3][1])
print("gradients[\"dWax\"].shape =", gradients["dWax"].shape)
print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2])
print("gradients[\"dWaa\"].shape =", gradients["dWaa"].shape)
print("gradients[\"dba\"][4] =", gradients["dba"][4])
print("gradients[\"dba\"].shape =", gradients["dba"].shape) | gradients["dx"][1][2] = [-2.07101689 -0.59255627 0.02466855 0.01483317]
gradients["dx"].shape = (3, 10, 4)
gradients["da0"][2][3] = -0.314942375127
gradients["da0"].shape = (5, 10)
gradients["dWax"][3][1] = 11.2641044965
gradients["dWax"].shape = (5, 3)
gradients["dWaa"][1][2] = 2.30333312658
gradients["dWaa"].shape = (5, 5)
gradients["dba"][4] = [-0.74747722]
gradients["dba"].shape = (5, 1)
| MIT | Course5 - Sequence Models/week1 Recurrent Neural Networks/Building a recurrent neural network/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb | bheil123/DeepLearning |
**Expected Output**: **gradients["dx"][1][2]** = [-2.07101689 -0.59255627 0.02466855 0.01483317] **gradients["dx"].shape** = (3, 10, 4) **gradients["da0"][2][3]** = -0.314942375127 **gradients["da0"].shape** = (5, 10) **gradients["dWax"][3][1]** = 11.2641044965 **gradients["dWax"].shape** = (5, 3) **gradients["dWaa"][1][2]** = 2.30333312658 **gradients["dWaa"].shape** = (5, 5) **gradients["dba"][4]** = [-0.74747722] **gradients["dba"].shape** = (5, 1) 3.2 - LSTM backward pass 3.2.1 One Step backwardThe LSTM backward pass is slighltly more complicated than the forward one. We have provided you with all the equations for the LSTM backward pass below. (If you enjoy calculus exercises feel free to try deriving these from scratch yourself.) 3.2.2 gate derivatives$$d \Gamma_o^{\langle t \rangle} = da_{next}*\tanh(c_{next}) * \Gamma_o^{\langle t \rangle}*(1-\Gamma_o^{\langle t \rangle})\tag{7}$$$$d\tilde c^{\langle t \rangle} = dc_{next}*\Gamma_u^{\langle t \rangle}+ \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * i_t * da_{next} * \tilde c^{\langle t \rangle} * (1-\tanh(\tilde c)^2) \tag{8}$$$$d\Gamma_u^{\langle t \rangle} = dc_{next}*\tilde c^{\langle t \rangle} + \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * \tilde c^{\langle t \rangle} * da_{next}*\Gamma_u^{\langle t \rangle}*(1-\Gamma_u^{\langle t \rangle})\tag{9}$$$$d\Gamma_f^{\langle t \rangle} = dc_{next}*\tilde c_{prev} + \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * c_{prev} * da_{next}*\Gamma_f^{\langle t \rangle}*(1-\Gamma_f^{\langle t \rangle})\tag{10}$$ 3.2.3 parameter derivatives $$ dW_f = d\Gamma_f^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{11} $$$$ dW_u = d\Gamma_u^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{12} $$$$ dW_c = d\tilde c^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{13} $$$$ dW_o = d\Gamma_o^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{14}$$To calculate $db_f, db_u, db_c, db_o$ you just need to sum across the horizontal (axis= 1) axis on $d\Gamma_f^{\langle t \rangle}, d\Gamma_u^{\langle t \rangle}, d\tilde c^{\langle t \rangle}, d\Gamma_o^{\langle t \rangle}$ respectively. Note that you should have the `keep_dims = True` option.Finally, you will compute the derivative with respect to the previous hidden state, previous memory state, and input.$$ da_{prev} = W_f^T*d\Gamma_f^{\langle t \rangle} + W_u^T * d\Gamma_u^{\langle t \rangle}+ W_c^T * d\tilde c^{\langle t \rangle} + W_o^T * d\Gamma_o^{\langle t \rangle} \tag{15}$$Here, the weights for equations 13 are the first n_a, (i.e. $W_f = W_f[:n_a,:]$ etc...)$$ dc_{prev} = dc_{next}\Gamma_f^{\langle t \rangle} + \Gamma_o^{\langle t \rangle} * (1- \tanh(c_{next})^2)*\Gamma_f^{\langle t \rangle}*da_{next} \tag{16}$$$$ dx^{\langle t \rangle} = W_f^T*d\Gamma_f^{\langle t \rangle} + W_u^T * d\Gamma_u^{\langle t \rangle}+ W_c^T * d\tilde c_t + W_o^T * d\Gamma_o^{\langle t \rangle}\tag{17} $$where the weights for equation 15 are from n_a to the end, (i.e. $W_f = W_f[n_a:,:]$ etc...)**Exercise:** Implement `lstm_cell_backward` by implementing equations $7-17$ below. Good luck! :) | def lstm_cell_backward(da_next, dc_next, cache):
"""
Implement the backward pass for the LSTM-cell (single time-step).
Arguments:
da_next -- Gradients of next hidden state, of shape (n_a, m)
dc_next -- Gradients of next cell state, of shape (n_a, m)
cache -- cache storing information from the forward pass
Returns:
gradients -- python dictionary containing:
dxt -- Gradient of input data at time-step t, of shape (n_x, m)
da_prev -- Gradient w.r.t. the previous hidden state, numpy array of shape (n_a, m)
dc_prev -- Gradient w.r.t. the previous memory state, of shape (n_a, m, T_x)
dWf -- Gradient w.r.t. the weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
dWi -- Gradient w.r.t. the weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
dWc -- Gradient w.r.t. the weight matrix of the memory gate, numpy array of shape (n_a, n_a + n_x)
dWo -- Gradient w.r.t. the weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)
dbf -- Gradient w.r.t. biases of the forget gate, of shape (n_a, 1)
dbi -- Gradient w.r.t. biases of the update gate, of shape (n_a, 1)
dbc -- Gradient w.r.t. biases of the memory gate, of shape (n_a, 1)
dbo -- Gradient w.r.t. biases of the output gate, of shape (n_a, 1)
"""
# Retrieve information from "cache"
(a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters) = cache
### START CODE HERE ###
# Retrieve dimensions from xt's and a_next's shape (≈2 lines)
n_x, m = xt.shape
n_a, m = a_next.shape
# Compute gates related derivatives, you can find their values can be found by looking carefully at equations (7) to (10) (≈4 lines)
dot = da_next * np.tanh(c_next) * ot * (1 - ot)
dcct = (dc_next * it + ot * (1 - np.square(np.tanh(c_next))) * it * da_next) * (1 - np.square(cct))
dit = (dc_next * cct + ot * (1 - np.square(np.tanh(c_next))) * cct * da_next) * it * (1 - it)
dft = (dc_next * c_prev + ot *(1 - np.square(np.tanh(c_next))) * c_prev * da_next) * ft * (1 - ft)
# Code equations (7) to (10) (≈4 lines)
#dit = None
#dft = None
#dot = None
#dcct = None
concat = np.concatenate((a_prev, xt), axis=0)
# Compute parameters related derivatives. Use equations (11)-(14) (≈8 lines)
dWf = np.dot(dft, concat.T)
dWi = np.dot(dit, concat.T)
dWc = np.dot(dcct, concat.T)
dWo = np.dot(dot, concat.T)
dbf = np.sum(dft, axis=1 ,keepdims = True)
dbi = np.sum(dit, axis=1, keepdims = True)
dbc = np.sum(dcct, axis=1, keepdims = True)
dbo = np.sum(dot, axis=1, keepdims = True)
# Compute derivatives w.r.t previous hidden state, previous memory state and input. Use equations (15)-(17). (≈3 lines)
da_prev = np.dot(parameters['Wf'][:, :n_a].T, dft) + np.dot(parameters['Wi'][:, :n_a].T, dit) + np.dot(parameters['Wc'][:, :n_a].T, dcct) + np.dot(parameters['Wo'][:, :n_a].T, dot)
dc_prev = dc_next * ft + ot * (1 - np.square(np.tanh(c_next))) * ft * da_next
dxt = np.dot(parameters['Wf'][:, n_a:].T, dft) + np.dot(parameters['Wi'][:, n_a:].T, dit) + np.dot(parameters['Wc'][:, n_a:].T, dcct) + np.dot(parameters['Wo'][:, n_a:].T, dot)
### END CODE HERE ###
# Save gradients in dictionary
gradients = {"dxt": dxt, "da_prev": da_prev, "dc_prev": dc_prev, "dWf": dWf,"dbf": dbf, "dWi": dWi,"dbi": dbi,
"dWc": dWc,"dbc": dbc, "dWo": dWo,"dbo": dbo}
return gradients
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
c_prev = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
Wy = np.random.randn(2,5)
by = np.random.randn(2,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a_next, c_next, yt, cache = lstm_cell_forward(xt, a_prev, c_prev, parameters)
da_next = np.random.randn(5,10)
dc_next = np.random.randn(5,10)
gradients = lstm_cell_backward(da_next, dc_next, cache)
print("gradients[\"dxt\"][1][2] =", gradients["dxt"][1][2])
print("gradients[\"dxt\"].shape =", gradients["dxt"].shape)
print("gradients[\"da_prev\"][2][3] =", gradients["da_prev"][2][3])
print("gradients[\"da_prev\"].shape =", gradients["da_prev"].shape)
print("gradients[\"dc_prev\"][2][3] =", gradients["dc_prev"][2][3])
print("gradients[\"dc_prev\"].shape =", gradients["dc_prev"].shape)
print("gradients[\"dWf\"][3][1] =", gradients["dWf"][3][1])
print("gradients[\"dWf\"].shape =", gradients["dWf"].shape)
print("gradients[\"dWi\"][1][2] =", gradients["dWi"][1][2])
print("gradients[\"dWi\"].shape =", gradients["dWi"].shape)
print("gradients[\"dWc\"][3][1] =", gradients["dWc"][3][1])
print("gradients[\"dWc\"].shape =", gradients["dWc"].shape)
print("gradients[\"dWo\"][1][2] =", gradients["dWo"][1][2])
print("gradients[\"dWo\"].shape =", gradients["dWo"].shape)
print("gradients[\"dbf\"][4] =", gradients["dbf"][4])
print("gradients[\"dbf\"].shape =", gradients["dbf"].shape)
print("gradients[\"dbi\"][4] =", gradients["dbi"][4])
print("gradients[\"dbi\"].shape =", gradients["dbi"].shape)
print("gradients[\"dbc\"][4] =", gradients["dbc"][4])
print("gradients[\"dbc\"].shape =", gradients["dbc"].shape)
print("gradients[\"dbo\"][4] =", gradients["dbo"][4])
print("gradients[\"dbo\"].shape =", gradients["dbo"].shape) | gradients["dxt"][1][2] = 3.23055911511
gradients["dxt"].shape = (3, 10)
gradients["da_prev"][2][3] = -0.0639621419711
gradients["da_prev"].shape = (5, 10)
gradients["dc_prev"][2][3] = 0.797522038797
gradients["dc_prev"].shape = (5, 10)
gradients["dWf"][3][1] = -0.147954838164
gradients["dWf"].shape = (5, 8)
gradients["dWi"][1][2] = 1.05749805523
gradients["dWi"].shape = (5, 8)
gradients["dWc"][3][1] = 2.30456216369
gradients["dWc"].shape = (5, 8)
gradients["dWo"][1][2] = 0.331311595289
gradients["dWo"].shape = (5, 8)
gradients["dbf"][4] = [ 0.18864637]
gradients["dbf"].shape = (5, 1)
gradients["dbi"][4] = [-0.40142491]
gradients["dbi"].shape = (5, 1)
gradients["dbc"][4] = [ 0.25587763]
gradients["dbc"].shape = (5, 1)
gradients["dbo"][4] = [ 0.13893342]
gradients["dbo"].shape = (5, 1)
| MIT | Course5 - Sequence Models/week1 Recurrent Neural Networks/Building a recurrent neural network/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb | bheil123/DeepLearning |
**Expected Output**: **gradients["dxt"][1][2]** = 3.23055911511 **gradients["dxt"].shape** = (3, 10) **gradients["da_prev"][2][3]** = -0.0639621419711 **gradients["da_prev"].shape** = (5, 10) **gradients["dc_prev"][2][3]** = 0.797522038797 **gradients["dc_prev"].shape** = (5, 10) **gradients["dWf"][3][1]** = -0.147954838164 **gradients["dWf"].shape** = (5, 8) **gradients["dWi"][1][2]** = 1.05749805523 **gradients["dWi"].shape** = (5, 8) **gradients["dWc"][3][1]** = 2.30456216369 **gradients["dWc"].shape** = (5, 8) **gradients["dWo"][1][2]** = 0.331311595289 **gradients["dWo"].shape** = (5, 8) **gradients["dbf"][4]** = [ 0.18864637] **gradients["dbf"].shape** = (5, 1) **gradients["dbi"][4]** = [-0.40142491] **gradients["dbi"].shape** = (5, 1) **gradients["dbc"][4]** = [ 0.25587763] **gradients["dbc"].shape** = (5, 1) **gradients["dbo"][4]** = [ 0.13893342] **gradients["dbo"].shape** = (5, 1) 3.3 Backward pass through the LSTM RNNThis part is very similar to the `rnn_backward` function you implemented above. You will first create variables of the same dimension as your return variables. You will then iterate over all the time steps starting from the end and call the one step function you implemented for LSTM at each iteration. You will then update the parameters by summing them individually. Finally return a dictionary with the new gradients. **Instructions**: Implement the `lstm_backward` function. Create a for loop starting from $T_x$ and going backward. For each step call `lstm_cell_backward` and update the your old gradients by adding the new gradients to them. Note that `dxt` is not updated but is stored. | def lstm_backward(da, caches):
"""
Implement the backward pass for the RNN with LSTM-cell (over a whole sequence).
Arguments:
da -- Gradients w.r.t the hidden states, numpy-array of shape (n_a, m, T_x)
dc -- Gradients w.r.t the memory states, numpy-array of shape (n_a, m, T_x)
caches -- cache storing information from the forward pass (lstm_forward)
Returns:
gradients -- python dictionary containing:
dx -- Gradient of inputs, of shape (n_x, m, T_x)
da0 -- Gradient w.r.t. the previous hidden state, numpy array of shape (n_a, m)
dWf -- Gradient w.r.t. the weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
dWi -- Gradient w.r.t. the weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
dWc -- Gradient w.r.t. the weight matrix of the memory gate, numpy array of shape (n_a, n_a + n_x)
dWo -- Gradient w.r.t. the weight matrix of the save gate, numpy array of shape (n_a, n_a + n_x)
dbf -- Gradient w.r.t. biases of the forget gate, of shape (n_a, 1)
dbi -- Gradient w.r.t. biases of the update gate, of shape (n_a, 1)
dbc -- Gradient w.r.t. biases of the memory gate, of shape (n_a, 1)
dbo -- Gradient w.r.t. biases of the save gate, of shape (n_a, 1)
"""
# Retrieve values from the first cache (t=1) of caches.
(caches, x) = caches
(a1, c1, a0, c0, f1, i1, cc1, o1, x1, parameters) = caches[0]
### START CODE HERE ###
# Retrieve dimensions from da's and x1's shapes (≈2 lines)
n_a, m, T_x = da.shape
n_x, m = x1.shape
# initialize the gradients with the right sizes (≈12 lines)
dx = np.zeros((n_x, m, T_x))
da0 = np.zeros((n_a, m))
da_prevt = np.zeros(da0.shape)
dc_prevt = np.zeros(da0.shape)
dWf = np.zeros((n_a, n_a + n_x))
dWi = np.zeros(dWf.shape)
dWc = np.zeros(dWf.shape)
dWo = np.zeros(dWf.shape)
dbf = np.zeros((n_a, 1))
dbi = np.zeros(dbf.shape)
dbc = np.zeros(dbf.shape)
dbo = np.zeros(dbf.shape)
# loop back over the whole sequence
for t in reversed(range(T_x)):
# Compute all gradients using lstm_cell_backward
gradients = lstm_cell_backward(da[:, :, t], dc_prevt, caches[t])
# Store or add the gradient to the parameters' previous step's gradient
dx[:,:,t] = gradients["dxt"]
dWf += gradients["dWf"]
dWi += gradients["dWi"]
dWc += gradients["dWc"]
dWo += gradients["dWo"]
dbf += gradients["dbf"]
dbi += gradients["dbi"]
dbc += gradients["dbc"]
dbo += gradients["dbo"]
# Set the first activation's gradient to the backpropagated gradient da_prev.
da0 = gradients["da_prev"]
### END CODE HERE ###
# Store the gradients in a python dictionary
gradients = {"dx": dx, "da0": da0, "dWf": dWf,"dbf": dbf, "dWi": dWi,"dbi": dbi,
"dWc": dWc,"dbc": dbc, "dWo": dWo,"dbo": dbo}
return gradients
np.random.seed(1)
x = np.random.randn(3,10,7)
a0 = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a, y, c, caches = lstm_forward(x, a0, parameters)
da = np.random.randn(5, 10, 4)
gradients = lstm_backward(da, caches)
print("gradients[\"dx\"][1][2] =", gradients["dx"][1][2])
print("gradients[\"dx\"].shape =", gradients["dx"].shape)
print("gradients[\"da0\"][2][3] =", gradients["da0"][2][3])
print("gradients[\"da0\"].shape =", gradients["da0"].shape)
print("gradients[\"dWf\"][3][1] =", gradients["dWf"][3][1])
print("gradients[\"dWf\"].shape =", gradients["dWf"].shape)
print("gradients[\"dWi\"][1][2] =", gradients["dWi"][1][2])
print("gradients[\"dWi\"].shape =", gradients["dWi"].shape)
print("gradients[\"dWc\"][3][1] =", gradients["dWc"][3][1])
print("gradients[\"dWc\"].shape =", gradients["dWc"].shape)
print("gradients[\"dWo\"][1][2] =", gradients["dWo"][1][2])
print("gradients[\"dWo\"].shape =", gradients["dWo"].shape)
print("gradients[\"dbf\"][4] =", gradients["dbf"][4])
print("gradients[\"dbf\"].shape =", gradients["dbf"].shape)
print("gradients[\"dbi\"][4] =", gradients["dbi"][4])
print("gradients[\"dbi\"].shape =", gradients["dbi"].shape)
print("gradients[\"dbc\"][4] =", gradients["dbc"][4])
print("gradients[\"dbc\"].shape =", gradients["dbc"].shape)
print("gradients[\"dbo\"][4] =", gradients["dbo"][4])
print("gradients[\"dbo\"].shape =", gradients["dbo"].shape) | gradients["dx"][1][2] = [-0.00173313 0.08287442 -0.30545663 -0.43281115]
gradients["dx"].shape = (3, 10, 4)
gradients["da0"][2][3] = -0.095911501954
gradients["da0"].shape = (5, 10)
gradients["dWf"][3][1] = -0.0698198561274
gradients["dWf"].shape = (5, 8)
gradients["dWi"][1][2] = 0.102371820249
gradients["dWi"].shape = (5, 8)
gradients["dWc"][3][1] = -0.0624983794927
gradients["dWc"].shape = (5, 8)
gradients["dWo"][1][2] = 0.0484389131444
gradients["dWo"].shape = (5, 8)
gradients["dbf"][4] = [-0.0565788]
gradients["dbf"].shape = (5, 1)
gradients["dbi"][4] = [-0.15399065]
gradients["dbi"].shape = (5, 1)
gradients["dbc"][4] = [-0.29691142]
gradients["dbc"].shape = (5, 1)
gradients["dbo"][4] = [-0.29798344]
gradients["dbo"].shape = (5, 1)
| MIT | Course5 - Sequence Models/week1 Recurrent Neural Networks/Building a recurrent neural network/Building+a+Recurrent+Neural+Network+-+Step+by+Step+-+v3.ipynb | bheil123/DeepLearning |
Computer Vision for Medical Imaging: Part 1. Train Model with Hyperparameter Tuning JobThis notebook is part 1 of a 4-part series of techniques and services offer by SageMaker to build a model which predicts if an image of cells contains cancer. This notebook shows how to build a model using hyperparameter tuning. DatasetThe dataset for this demo comes from the [Camelyon16 Challenge](https://camelyon16.grand-challenge.org/) made available under the CC0 licencse. The raw data provided by the challenge has been processed into 96x96 pixel tiles by [Bas Veeling](https://github.com/basveeling/pcam) and also made available under the CC0 license. For detailed information on each dataset please see the papers below:* Ehteshami Bejnordi et al. Diagnostic Assessment of Deep Learning Algorithms for Detection of Lymph Node Metastases in Women With Breast Cancer. JAMA: The Journal of the American Medical Association, 318(22), 2199–2210. [doi:jama.2017.14585](https://doi.org/10.1001/jama.2017.14585)* B. S. Veeling, J. Linmans, J. Winkens, T. Cohen, M. Welling. "Rotation Equivariant CNNs for Digital Pathology". [arXiv:1806.03962](http://arxiv.org/abs/1806.03962)The tiled dataset from Bas Veeling is over 6GB of data. In order to easily run this demo, the dataset has been pruned to the first 14,000 images of the tiled dataset and comes included in the repo with this notebook for convenience. Update Sagemaker SDK and Boto3NOTE You may get an error from pip's dependency resolver; you can ignore this error. | import pip
def import_or_install(package):
try:
__import__(package)
except ImportError:
pip.main(["install", package])
required_packages = ["sagemaker", "boto3", "mxnet", "h5py", "tqdm", "matplotlib"]
for package in required_packages:
import_or_install(package)
%store -r
%store | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Import Libraries | import io
import os
import h5py
import zipfile
import boto3
import sagemaker
import mxnet as mx
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import cv2 | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Configure Boto3 Clients and Sessions | region = "us-west-2" # Change region as needed
boto3.setup_default_session(region_name=region)
boto_session = boto3.Session(region_name=region)
s3_client = boto3.client("s3", region_name=region)
sagemaker_boto_client = boto_session.client("sagemaker")
sagemaker_session = sagemaker.session.Session(
boto_session=boto_session, sagemaker_client=sagemaker_boto_client
)
sagemaker_role = sagemaker.get_execution_role()
bucket = sagemaker.Session().default_bucket() | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Load Dataset | # check if directory exists
if not os.path.isdir("data"):
os.mkdir("data")
# download zip file from public s3 bucket
!wget -P data https://sagemaker-sample-files.s3.amazonaws.com/datasets/image/pcam/medical_images.zip
with zipfile.ZipFile("data/medical_images.zip") as zf:
zf.extractall()
with open("data/camelyon16_tiles.h5", "rb") as hf:
f = h5py.File(hf, "r")
X = f["x"][()]
y = f["y"][()]
print("Shape of X:", X.shape)
print("Shape of y:", y.shape)
# write to session s3 bucket
s3_client.upload_file("data/medical_images.zip", bucket, f"data/medical_images.zip")
# delete local copy
import os
if os.path.exists("data/medical_images.zip"):
os.remove("data/medical_images.zip")
else:
print("The file does not exist") | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
View Sample Images from Dataset | def preview_images(X, y, n, cols):
sample_images = X[:n]
sample_labels = y[:n]
rows = int(np.ceil(n / cols))
fig, axs = plt.subplots(rows, cols, figsize=(11.5, 7))
for i, ax in enumerate(axs.flatten()):
image = sample_images[i]
label = sample_labels[i]
ax.imshow(image)
ax.axis("off")
ax.set_title(f"Label: {label}")
plt.tight_layout()
preview_images(X, y, 15, 5) | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Shuffle and Split Dataset | from sklearn.model_selection import train_test_split
X_numpy = X[:]
y_numpy = y[:]
X_train, X_test, y_train, y_test = train_test_split(
X_numpy, y_numpy, test_size=1000, random_state=0
)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=2000, random_state=1)
print(X_train.shape)
print(X_val.shape)
print(X_test.shape) | (11000, 96, 96, 3)
(2000, 96, 96, 3)
(1000, 96, 96, 3)
| Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Convert Splits to RecordIO Format | def write_to_recordio(X: np.ndarray, y: np.ndarray, prefix: str):
record = mx.recordio.MXIndexedRecordIO(idx_path=f"{prefix}.idx", uri=f"{prefix}.rec", flag="w")
for idx, arr in enumerate(tqdm(X)):
header = mx.recordio.IRHeader(0, y[idx], idx, 0)
s = mx.recordio.pack_img(
header,
arr,
quality=95,
img_fmt=".jpg",
)
record.write_idx(idx, s)
record.close()
write_to_recordio(X_train, y_train, prefix="data/train")
write_to_recordio(X_val, y_val, prefix="data/val")
write_to_recordio(X_test, y_test, prefix="data/test") | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Upload Data Splits to S3 | prefix = "cv-metastasis"
try:
s3_client.create_bucket(
Bucket=bucket, ACL="private", CreateBucketConfiguration={"LocationConstraint": region}
)
print(f"Created S3 bucket: {bucket}")
except Exception as e:
if e.response["Error"]["Code"] == "BucketAlreadyOwnedByYou":
print(f"Using existing bucket: {bucket}")
else:
raise (e)
%store prefix
s3_client.upload_file("data/train.rec", bucket, f"{prefix}/data/train/train.rec")
s3_client.upload_file("data/val.rec", bucket, f"{prefix}/data/val/val.rec")
s3_client.upload_file("data/test.rec", bucket, f"{prefix}/data/test/test.rec") | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Configure the Estimator | training_image = sagemaker.image_uris.retrieve("image-classification", region)
num_training_samples = X_train.shape[0]
num_classes = len(np.unique(y_train))
hyperparameters = {
"num_layers": 18,
"use_pretrained_model": 1,
"augmentation_type": "crop_color_transform",
"image_shape": "3,96,96",
"num_classes": num_classes,
"num_training_samples": num_training_samples,
"mini_batch_size": 64,
"epochs": 5,
"learning_rate": 0.01,
"precision_dtype": "float32",
}
estimator_config = {
"hyperparameters": hyperparameters,
"image_uri": training_image,
"role": sagemaker.get_execution_role(),
"instance_count": 1,
"instance_type": "ml.p3.2xlarge",
"volume_size": 100,
"max_run": 360000,
"output_path": f"s3://{bucket}/{prefix}/training_jobs",
}
image_classifier = sagemaker.estimator.Estimator(**estimator_config)
%store num_training_samples | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Configure the Hyperparameter TunerAlthough we would prefer to tune for recall, the current HyperparameterTuner implementation for Image Classification only supports validation accuracy. | hyperparameter_ranges = {
"mini_batch_size": sagemaker.parameter.CategoricalParameter([16, 32, 64]),
"learning_rate": sagemaker.parameter.CategoricalParameter([0.001, 0.01]),
}
hyperparameter_tuner = sagemaker.tuner.HyperparameterTuner(
estimator=image_classifier,
objective_metric_name="validation:accuracy",
hyperparameter_ranges=hyperparameter_ranges,
max_jobs=6,
max_parallel_jobs=2,
base_tuning_job_name=prefix,
) | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Define the Data Channels | train_input = sagemaker.inputs.TrainingInput(
s3_data=f"s3://{bucket}/{prefix}/data/train",
content_type="application/x-recordio",
s3_data_type="S3Prefix",
input_mode="Pipe",
)
val_input = sagemaker.inputs.TrainingInput(
s3_data=f"s3://{bucket}/{prefix}/data/val",
content_type="application/x-recordio",
s3_data_type="S3Prefix",
input_mode="Pipe",
)
data_channels = {"train": train_input, "validation": val_input} | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Run Hyperparameter Tuning Jobs | if 'tuning_job_name' not in locals():
hyperparameter_tuner.fit(inputs=data_channels)
tuning_job_name = hyperparameter_tuner.describe().get('HyperParameterTuningJobName')
%store tuning_job_name
else:
print(f'Using previous tuning job: {tuning_job_name}')
%store tuning_job_name | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
Examine ResultsNOTE: If your kernel has restarted after running the hyperparameter tuning job, everyting you need has been persisted to SageMaker. You can continue on without having to run the tuning job again. | results = sagemaker.analytics.HyperparameterTuningJobAnalytics(tuning_job_name)
results_df = results.dataframe()
results_df
best_training_job_summary = results.description()["BestTrainingJob"]
best_training_job_name = best_training_job_summary["TrainingJobName"]
%store best_training_job_name | _____no_output_____ | Apache-2.0 | use-cases/computer_vision/1-metastases-detection-train-model.ipynb | sureindia-in/sagemaker-examples-good |
K-Means Clustering | # Import required packages
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from pandas import DataFrame
Data = {'x': [25,34,22,27,33,33,31,22,35,34,67,54,57,43,50,57,59,52,65,47,49,48,35,33,44,45,38,43,51,46],
'y': [79,51,53,78,59,74,73,57,69,75,51,32,40,47,53,36,35,58,59,50,25,20,14,12,20,5,29,27,8,7]
}
df = DataFrame(Data,columns=['x','y'])
df.head()
| _____no_output_____ | Apache-2.0 | K-MEANS CLUSTERING.ipynb | PrasannaDataBus/CLUSTERING |
Next you’ll see how to use sklearn to find the centroids for 3 clusters, and then for 4 clusters.K-Means Clustering in Python – 3 clustersOnce you created the DataFrame based on the above data, you’ll need to import 2 additional Python modules: matplotlib – for creating charts in Python sklearn – for applying the K-Means Clustering in PythonIn the code below, you can specify the number of clusters. For this example, assign 3 clusters as follows:KMeans(n_clusters=3).fit(df) | import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
mms = MinMaxScaler()
mms.fit(df)
data_transformed = mms.transform(df)
Sum_of_squared_distances = []
K = range(1,15)
for k in K:
km = KMeans(n_clusters=k)
km = km.fit(data_transformed)
Sum_of_squared_distances.append(km.inertia_)
plt.plot(K, Sum_of_squared_distances, 'bx-')
plt.xlabel('k')
plt.ylabel('Sum_of_squared_distances')
plt.title('Elbow Method For Optimal k')
plt.show()
kmeans = KMeans(n_clusters=5).fit(df)
centroids = kmeans.cluster_centers_
print(centroids)
plt.scatter(df['x'], df['y'], c= kmeans.labels_.astype(float), s=50, alpha=0.9)
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=100)
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
df = DataFrame(Data,columns=['x','y'])
kmeans = KMeans(n_clusters=3).fit(df)
centroids = kmeans.cluster_centers_
print(centroids)import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
df = DataFrame(Data,columns=['x','y'])
kmeans = KMeans(n_clusters=3).fit(df)
centroids = kmeans.cluster_centers_
print(centroids)
plt.scatter(df['x'], df['y'], c= kmeans.labels_.astype(float), s=50, alpha=0.5)
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=50)
plt.scatter(df['x'], df['y'], c= kmeans.labels_.astype(float), s=50, alpha=0.5)
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=50)
Note that the center of each cluster (in red) represents the mean of all the observations that belong to that cluster.
As you may also see, the observations that belong to a given cluster are closer to the center of that cluster, in comparison to the centers of other clusters.
K-Means Clustering in Python – 4 clusters
Let’s now see what would happen if you use 4 clusters instead. In that case, the only thing you’ll need to do is to change the n_clusters from 3 to 4:
KMeans(n_clusters=4).fit(df)
And so, your full Python code for 4 clusters would look like this:
kmeans = KMeans(n_clusters= 6).fit(df)
centroids = kmeans.cluster_centers_
print(centroids)
plt.scatter(df['x'], df['y'], c= kmeans.labels_.astype(float), s=50, alpha=0.5)
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=50)
Tkinter GUI to Display the Results
You can use the tkinter module in Python to display the clusters on a simple graphical user interface.
This is the code that you can use (for 3 clusters): | _____no_output_____ | Apache-2.0 | K-MEANS CLUSTERING.ipynb | PrasannaDataBus/CLUSTERING |
Aerospike Connect for Spark Tutorial for Python Tested with Spark connector 3.2.0, ASDB EE 5.7.0.7, Java 8, Apache Spark 3.0.2, Python 3.7 and Scala 2.12.11 and [Spylon]( https://pypi.org/project/spylon-kernel/) Setup Ensure Database Is RunningThis notebook requires that Aerospike datbase is running. | !asd >& /dev/null
!pgrep -x asd >/dev/null && echo "Aerospike database is running!" || echo "**Aerospike database is not running!**" | Aerospike database is running!
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Set Aerospike, Spark, and Spark Connector Paths and Parameters | # Directorie where spark related components are installed
SPARK_NB_DIR = '/opt/spark-nb'
SPARK_HOME = SPARK_NB_DIR + '/spark-3.0.3-bin-hadoop3.2'
# IP Address or DNS name for one host in your Aerospike cluster
AS_HOST ="localhost"
# Name of one of your namespaces. Type 'show namespaces' at the aql prompt if you are not sure
AS_NAMESPACE = "test"
AEROSPIKE_SPARK_JAR_VERSION="3.2.0"
AS_PORT = 3000 # Usually 3000, but change here if not
AS_CONNECTION_STRING = AS_HOST + ":"+ str(AS_PORT)
# Aerospike Spark Connector settings
import os
AEROSPIKE_JAR_PATH = SPARK_NB_DIR + '/' + "aerospike-spark-assembly-" + AEROSPIKE_SPARK_JAR_VERSION + ".jar"
os.environ["PYSPARK_SUBMIT_ARGS"] = '--jars ' + AEROSPIKE_JAR_PATH + ' pyspark-shell' | _____no_output_____ | MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Alternative Setup for Running Notebook in Different EnvironmentPlease follow the instructions below **instead of the setup above** if you are running this notebook in a different environment from the one provided by the Aerospike Intro-Notebooks container.``` IP Address or DNS name for one host in your Aerospike clusterAS_HOST = "" Name of one of your namespaces. Type 'show namespaces' at the aql prompt if you are not sureAS_NAMESPACE = "" AEROSPIKE_SPARK_JAR_VERSION=""AS_PORT = 3000 Usually 3000, but change here if notAS_CONNECTION_STRING = AS_HOST + ":"+ str(AS_PORT) Set SPARK_HOME path.SPARK_HOME = '' Please download the appropriate Aeropsike Connect for Spark from the [download page](https://enterprise.aerospike.com/enterprise/download/connectors/aerospike-spark/notes.html) Set `AEROSPIKE_JAR_PATH` with path to the downloaded binaryimport os AEROSPIKE_JAR_PATH= "/aerospike-spark-assembly-"+AEROSPIKE_SPARK_JAR_VERSION+".jar"os.environ["PYSPARK_SUBMIT_ARGS"] = '--jars ' + AEROSPIKE_JAR_PATH + ' pyspark-shell'``` Spark Initialization | # Next we locate the Spark installation - this will be found using the SPARK_HOME environment variable that you will have set
import findspark
findspark.init(SPARK_HOME)
import pyspark
from pyspark.sql.types import * | _____no_output_____ | MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Configure Aerospike properties in the Spark Session object. Please visit [Configuring Aerospike Connect for Spark](https://docs.aerospike.com/docs/connect/processing/spark/configuration.html) for more information about the properties used on this page. | from pyspark.sql import SparkSession
from pyspark import SparkContext
sc = SparkContext.getOrCreate()
conf=sc._conf.setAll([("aerospike.namespace",AS_NAMESPACE),("aerospike.seedhost",AS_CONNECTION_STRING), ("aerospike.log.level","info")])
sc.stop()
sc = pyspark.SparkContext(conf=conf)
spark = SparkSession(sc)
# sqlContext = SQLContext(sc) | _____no_output_____ | MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Schema in the Spark Connector- Aerospike is schemaless, however Spark adher to schema. After the schema is decided upon (either through inference or given), data within the bins must honor the types. - To infer schema, the connector samples a set of records (configurable through `aerospike.schema.scan`) to decide the name of bins/columns and their types. This implies that the derived schema depends entirely upon sampled records. - **Note that `__key` was not part of provided schema. So how can one query using `__key`? We can just add `__key` in provided schema with appropriate type. Similarly we can add `__gen` or `__ttl` etc.** schemaWithPK = StructType([ StructField("__key",IntegerType(), False), StructField("id", IntegerType(), False), StructField("name", StringType(), False), StructField("age", IntegerType(), False), StructField("salary",IntegerType(), False)]) - **We recommend that you provide schema for queries that involve [collection data types](https://docs.aerospike.com/docs/guide/cdt.html) such as lists, maps, and mixed types. Using schema inference for CDT may cause unexpected issues.** Flexible schema inference Spark assumes that the underlying data store (Aerospike in this case) follows a strict schema for all the records within a table. However, Aerospike is a No-SQL DB and is schemaless. For further information on the Spark connector reconciles those differences, visit [Flexible schema](https://docs.aerospike.com/docs/connect/processing/spark/configuration.htmlflexible-schemas) page - aerospike.schema.flexible = true (default) - aerospike.schema.flexible = false | import random
num_records=200
schema = StructType(
[
StructField("id", IntegerType(), True),
StructField("name", StringType(), True)
]
)
inputBuf = []
for i in range(1, num_records) :
name = "name" + str(i)
id_ = i
inputBuf.append((id_, name))
inputRDD = spark.sparkContext.parallelize(inputBuf)
inputDF=spark.createDataFrame(inputRDD,schema)
#Write the Sample Data to Aerospike
inputDF \
.write \
.mode('overwrite') \
.format("aerospike") \
.option("aerospike.writeset", "py_input_data")\
.option("aerospike.updateByKey", "id") \
.save() | _____no_output_____ | MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
aerospike.schema.flexible = true (default) If none of the column types in the user-specified schema match the bin types of a record in Aerospike, a record with NULLs is returned in the result set. Please use the filter() in Spark to filter out NULL records. For e.g. df.filter("gender == NULL").show(false), where df is a dataframe and gender is a field that was not specified in the user-specified schema. If the above mismatch is limited to fewer columns in the user-specified schema then NULL would be returned for those columns in the result set. **Note: there is no way to tell apart a NULL due to missing value in the original data set and the NULL due to mismatch, at this point. Hence, the user would have to treat all NULLs as missing values.** The columns that are not a part of the schema will be automatically filtered out in the result set by the connector.Please note that if any field is set to NOT nullable i.e. nullable = false, your query will error out if there’s a type mismatch between an Aerospike bin and the column type specified in the user-specified schema. | schemaIncorrect = StructType(
[
StructField("id", IntegerType(), True),
StructField("name", IntegerType(), True) ##Note incorrect type of name bin
]
)
flexSchemaInference=spark \
.read \
.format("aerospike") \
.schema(schemaIncorrect) \
.option("aerospike.set", "py_input_data").load()
flexSchemaInference.show(5)
##notice all the contents of name column is null due to schema mismatch and aerospike.schema.flexible = true (by default) | +---+----+
| id|name|
+---+----+
| 10|null|
| 50|null|
|185|null|
|117|null|
| 88|null|
+---+----+
only showing top 5 rows
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
aerospike.schema.flexible = false If a mismatch between the user-specified schema and the schema of a record in Aerospike is detected at the bin/column level, your query will error out. | #When strict matching is set, we will get an exception due to type mismatch with schema provided.
try:
errorDFStrictSchemaInference=spark \
.read \
.format("aerospike") \
.schema(schemaIncorrect) \
.option("aerospike.schema.flexible" ,"false") \
.option("aerospike.set", "py_input_data").load()
errorDFStrictSchemaInference.show(5)
except Exception as e:
pass
#This will throw error due to type mismatch | _____no_output_____ | MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Create sample data | # We create age vs salary data, using three different Gaussian distributions
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
# Make sure we get the same results every time this workbook is run
# Otherwise we are occasionally exposed to results not working out as expected
np.random.seed(12345)
# Create covariance matrix from std devs + correlation
def covariance_matrix(std_dev_1,std_dev_2,correlation):
return [[std_dev_1 ** 2, correlation * std_dev_1 * std_dev_2],
[correlation * std_dev_1 * std_dev_2, std_dev_2 ** 2]]
# Return a bivariate sample given means/std dev/correlation
def age_salary_sample(distribution_params,sample_size):
mean = [distribution_params["age_mean"], distribution_params["salary_mean"]]
cov = covariance_matrix(distribution_params["age_std_dev"],distribution_params["salary_std_dev"],
distribution_params["age_salary_correlation"])
return np.random.multivariate_normal(mean, cov, sample_size).T
# Define the characteristics of our age/salary distribution
age_salary_distribution_1 = {"age_mean":25,"salary_mean":50000,
"age_std_dev":1,"salary_std_dev":5000,"age_salary_correlation":0.3}
age_salary_distribution_2 = {"age_mean":45,"salary_mean":80000,
"age_std_dev":4,"salary_std_dev":8000,"age_salary_correlation":0.7}
age_salary_distribution_3 = {"age_mean":35,"salary_mean":70000,
"age_std_dev":2,"salary_std_dev":9000,"age_salary_correlation":0.1}
distribution_data = [age_salary_distribution_1,age_salary_distribution_2,age_salary_distribution_3]
# Sample age/salary data for each distributions
sample_size_1 = 100;
sample_size_2 = 120;
sample_size_3 = 80;
sample_sizes = [sample_size_1,sample_size_2,sample_size_3]
group_1_ages,group_1_salaries = age_salary_sample(age_salary_distribution_1,sample_size=sample_size_1)
group_2_ages,group_2_salaries = age_salary_sample(age_salary_distribution_2,sample_size=sample_size_2)
group_3_ages,group_3_salaries = age_salary_sample(age_salary_distribution_3,sample_size=sample_size_3)
ages=np.concatenate([group_1_ages,group_2_ages,group_3_ages])
salaries=np.concatenate([group_1_salaries,group_2_salaries,group_3_salaries])
print("Data created") | Data created
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Display simulated age/salary data | # Plot the sample data
group_1_colour, group_2_colour, group_3_colour ='red','blue', 'pink'
plt.xlabel('Age',fontsize=10)
plt.ylabel("Salary",fontsize=10)
plt.scatter(group_1_ages,group_1_salaries,c=group_1_colour,label="Group 1")
plt.scatter(group_2_ages,group_2_salaries,c=group_2_colour,label="Group 2")
plt.scatter(group_3_ages,group_3_salaries,c=group_3_colour,label="Group 3")
plt.legend(loc='upper left')
plt.show() | _____no_output_____ | MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Save data to Aerospike | # Turn the above records into a Data Frame
# First of all, create an array of arrays
inputBuf = []
for i in range(0, len(ages)) :
id = i + 1 # Avoid counting from zero
name = "Individual: {:03d}".format(id)
# Note we need to make sure values are typed correctly
# salary will have type numpy.float64 - if it is not cast as below, an error will be thrown
age = float(ages[i])
salary = int(salaries[i])
inputBuf.append((id, name,age,salary))
# Convert to an RDD
inputRDD = spark.sparkContext.parallelize(inputBuf)
# Convert to a data frame using a schema
schema = StructType([
StructField("id", IntegerType(), True),
StructField("name", StringType(), True),
StructField("age", DoubleType(), True),
StructField("salary",IntegerType(), True)
])
inputDF=spark.createDataFrame(inputRDD,schema)
#Write the data frame to Aerospike, the id field is used as the primary key
inputDF \
.write \
.mode('overwrite') \
.format("aerospike") \
.option("aerospike.set", "salary_data")\
.option("aerospike.updateByKey", "id") \
.save() | _____no_output_____ | MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Using Spark SQL syntax to insert data | #Aerospike DB needs a Primary key for record insertion. Hence, you must identify the primary key column
#using for example .option(“aerospike.updateByKey”, “id”), where “id” is the name of the column that you’d
#like to be the Primary key, while loading data from the DB.
insertDFWithSchema=spark \
.read \
.format("aerospike") \
.schema(schema) \
.option("aerospike.set", "salary_data") \
.option("aerospike.updateByKey", "id") \
.load()
sqlView="inserttable"
#
# V2 datasource doesn't allow insert into a view.
#
insertDFWithSchema.createTempView(sqlView)
spark.sql("select * from inserttable").show() | +---+---------------+------------------+------+
| id| name| age|salary|
+---+---------------+------------------+------+
|239|Individual: 239|34.652141285212814| 61747|
|101|Individual: 101| 46.53337694047585| 89019|
|194|Individual: 194| 45.57430980213645| 94548|
| 31|Individual: 031| 25.24920420954561| 54312|
|139|Individual: 139| 38.84745269824981| 69645|
| 14|Individual: 014|25.590430778495463| 51513|
|142|Individual: 142| 42.5606479932568| 80357|
|272|Individual: 272| 33.97918907293991| 66496|
| 76|Individual: 076|25.457857266022874| 46214|
|147|Individual: 147|43.186823515795496| 70158|
| 79|Individual: 079|25.887490702675912| 48162|
| 96|Individual: 096|24.084761701659602| 46328|
|132|Individual: 132| 50.3039623703105| 78746|
| 10|Individual: 010|25.082338749020728| 58345|
|141|Individual: 141| 43.67491677796685| 79076|
|140|Individual: 140|43.065120467057845| 78500|
|160|Individual: 160| 54.98712625322743| 97029|
|112|Individual: 112| 37.09568187885065| 72307|
|120|Individual: 120|45.189080979167926| 80007|
| 34|Individual: 034|22.794852985231497| 49882|
+---+---------------+------------------+------+
only showing top 20 rows
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Load data into a DataFrame without specifying any Schema (uses schema inference) | # Create a Spark DataFrame by using the Connector Schema inference mechanism
# The fields preceded with __ are metadata fields - key/digest/expiry/generation/ttl
# By default you just get everything, with no column ordering, which is why it looks untidy
# Note we don't get anything in the 'key' field as we have not chosen to save as a bin.
# Use .option("aerospike.sendKey", True) to do this
loadedDFWithoutSchema = (
spark.read.format("aerospike") \
.option("aerospike.set", "salary_data") \
.load()
)
loadedDFWithoutSchema.show(10) | +-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
|__key| __digest| __expiry|__generation| __ttl| age| name|salary| id|
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
| null|[03 50 2E 7F 70 9...|378341961| 2|2591999|34.652141285212814|Individual: 239| 61747|239|
| null|[0F 10 1A 93 B1 E...|378341961| 2|2591999| 45.57430980213645|Individual: 194| 94548|194|
| null|[04 C0 5E 9A 68 5...|378341961| 2|2591999| 46.53337694047585|Individual: 101| 89019|101|
| null|[1A E0 A8 A0 F2 3...|378341961| 2|2591999| 25.24920420954561|Individual: 031| 54312| 31|
| null|[23 20 78 35 5D 7...|378341961| 2|2591998| 38.84745269824981|Individual: 139| 69645|139|
| null|[35 00 8C 78 43 F...|378341961| 2|2591998|25.590430778495463|Individual: 014| 51513| 14|
| null|[37 00 6D 21 08 9...|378341961| 2|2591998| 42.5606479932568|Individual: 142| 80357|142|
| null|[59 00 4B C7 6D 9...|378341961| 2|2591998| 33.97918907293991|Individual: 272| 66496|272|
| null|[61 50 89 B1 EC 0...|378341961| 2|2591998|25.457857266022874|Individual: 076| 46214| 76|
| null|[6C 50 7F 9B FD C...|378341961| 2|2591998|43.186823515795496|Individual: 147| 70158|147|
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
only showing top 10 rows
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Load data into a DataFrame using user specified schema | # If we explicitly set the schema, using the previously created schema object
# we effectively type the rows in the Data Frame
loadedDFWithSchema=spark \
.read \
.format("aerospike") \
.schema(schema) \
.option("aerospike.set", "salary_data").load()
loadedDFWithSchema.show(5) | +---+---------------+------------------+------+
| id| name| age|salary|
+---+---------------+------------------+------+
|239|Individual: 239|34.652141285212814| 61747|
|101|Individual: 101| 46.53337694047585| 89019|
|194|Individual: 194| 45.57430980213645| 94548|
| 31|Individual: 031| 25.24920420954561| 54312|
|139|Individual: 139| 38.84745269824981| 69645|
+---+---------------+------------------+------+
only showing top 5 rows
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Sampling from Aerospike DB- Sample specified number of records from Aerospike to considerably reduce data movement between Aerospike and the Spark clusters. Depending on the aerospike.partition.factor setting, you may get more records than desired. Please use this property in conjunction with Spark `limit()` function to get the specified number of records. The sample read is not randomized, so sample more than you need and use the Spark `sample()` function to randomize if you see fit. You can use it in conjunction with `aerospike.recordspersecond` to control the load on the Aerospike server while sampling.- For more information, please see [documentation](https://docs.aerospike.com/docs/connect/processing/spark/configuration.html) page. | #number_of_spark_partitions (num_sp)=2^{aerospike.partition.factor}
#total number of records = Math.ceil((float)aerospike.sample.size/num_sp) * (num_sp)
#use lower partition factor for more accurate sampling
setname="py_input_data"
sample_size=101
df3=spark.read.format("aerospike") \
.option("aerospike.partition.factor","2") \
.option("aerospike.set",setname) \
.option("aerospike.sample.size","101") \
.load()
df4=spark.read.format("aerospike") \
.option("aerospike.partition.factor","6") \
.option("aerospike.set",setname) \
.option("aerospike.sample.size","101") \
.load()
#Notice that more records were read than requested due to the underlying partitioning logic related to the partition factor as described earlier, hence we use Spark limit() function additionally to return the desired number of records.
count3=df3.count()
count4=df4.count()
#Note how limit got only 101 records from df4.
dfWithLimit=df4.limit(101)
limitCount=dfWithLimit.count()
print("count3= ", count3, " count4= ", count4, " limitCount=", limitCount) | count3= 104 count4= 113 limitCount= 101
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Working with Collection Data Types (CDT) in Aerospike Save JSON into Aerospike using a schema | # Schema specification
aliases_type = StructType([
StructField("first_name",StringType(),False),
StructField("last_name",StringType(),False)
])
id_type = StructType([
StructField("first_name",StringType(),False),
StructField("last_name",StringType(),False),
StructField("aliases",ArrayType(aliases_type),False)
])
street_adress_type = StructType([
StructField("street_name",StringType(),False),
StructField("apt_number",IntegerType(),False)
])
address_type = StructType([
StructField("zip",LongType(),False),
StructField("street",street_adress_type,False),
StructField("city",StringType(),False)
])
workHistory_type = StructType([
StructField ("company_name",StringType(),False),
StructField( "company_address",address_type,False),
StructField("worked_from",StringType(),False)
])
person_type = StructType([
StructField("name",id_type,False),
StructField("SSN",StringType(),False),
StructField("home_address",ArrayType(address_type),False),
StructField("work_history",ArrayType(workHistory_type),False)
])
# JSON data location
complex_data_json="resources/nested_data.json"
# Read data in using prepared schema
cmplx_data_with_schema=spark.read.schema(person_type).json(complex_data_json)
# Save data to Aerospike
cmplx_data_with_schema \
.write \
.mode('overwrite') \
.format("aerospike") \
.option("aerospike.writeset", "complex_input_data") \
.option("aerospike.updateByKey", "SSN") \
.save() | _____no_output_____ | MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Retrieve CDT from Aerospike into a DataFrame using schema | loadedComplexDFWithSchema=spark \
.read \
.format("aerospike") \
.option("aerospike.set", "complex_input_data") \
.schema(person_type) \
.load()
loadedComplexDFWithSchema.show(5) | +--------------------+-----------+--------------------+--------------------+
| name| SSN| home_address| work_history|
+--------------------+-----------+--------------------+--------------------+
|[Carrie, Collier,...|611-70-8032|[[14908, [Frankli...|[[Russell Group, ...|
|[Ashley, Davis, [...|708-19-4933|[[44679, [Duarte ...|[[Gaines LLC, [57...|
|[Anthony, Dalton,...|466-55-4994|[[48032, [Mark Es...|[[Mora, Sherman a...|
|[Jennifer, Willia...|438-70-6995|[[6917, [Gates Vi...|[[Cox, Olsen and ...|
|[Robert, Robinson...|561-49-6700|[[29209, [Hernand...|[[Frye, Mckee and...|
+--------------------+-----------+--------------------+--------------------+
only showing top 5 rows
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Data Exploration with Aerospike | import pandas
import matplotlib
import matplotlib.pyplot as plt
#convert Spark df to pandas df
pdf = loadedDFWithSchema.toPandas()
# Describe the data
pdf.describe()
#Histogram - Age
age_min, age_max = int(np.amin(pdf['age'])), math.ceil(np.amax(pdf['age']))
age_bucket_size = 5
print(age_min,age_max)
pdf[['age']].plot(kind='hist',bins=range(age_min,age_max,age_bucket_size),rwidth=0.8)
plt.xlabel('Age',fontsize=10)
plt.legend(loc=None)
plt.show()
#Histogram - Salary
salary_min, salary_max = int(np.amin(pdf['salary'])), math.ceil(np.amax(pdf['salary']))
salary_bucket_size = 5000
pdf[['salary']].plot(kind='hist',bins=range(salary_min,salary_max,salary_bucket_size),rwidth=0.8)
plt.xlabel('Salary',fontsize=10)
plt.legend(loc=None)
plt.show()
# Heatmap
age_bucket_count = math.ceil((age_max - age_min)/age_bucket_size)
salary_bucket_count = math.ceil((salary_max - salary_min)/salary_bucket_size)
x = [[0 for i in range(salary_bucket_count)] for j in range(age_bucket_count)]
for i in range(len(pdf['age'])):
age_bucket = math.floor((pdf['age'][i] - age_min)/age_bucket_size)
salary_bucket = math.floor((pdf['salary'][i] - salary_min)/salary_bucket_size)
x[age_bucket][salary_bucket] += 1
plt.title("Salary/Age distribution heatmap")
plt.xlabel("Salary in '000s")
plt.ylabel("Age")
plt.imshow(x, cmap='YlOrRd', interpolation='nearest',extent=[salary_min/1000,salary_max/1000,age_min,age_max],
origin="lower")
plt.colorbar(orientation="horizontal")
plt.show() | 22 57
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Quering Aerospike Data using SparkSQL Note: 1. Queries that involve Primary Key or Digest in the predicate trigger aerospike_batch_get()( https://www.aerospike.com/docs/client/c/usage/kvs/batch.html) and run extremely fast. For e.g. a query containing `__key` or `__digest` with, with no `OR` between two bins. 2. All other queries may entail a full scan of the Aerospike DB if they can’t be converted to Aerospike batchget. Queries that include Primary Key in the PredicateWith batch get queries we can apply filters on metadata columns such as `__gen` or `__ttl`. To do this, these columns should be exposed through the schema. | # Basic PKey query
batchGet1= spark \
.read \
.format("aerospike") \
.option("aerospike.set", "salary_data") \
.option("aerospike.keyType", "int") \
.load().where("__key = 100") \
batchGet1.show()
#Note ASDB only supports equality test with PKs in primary key query.
#So, a where clause with "__key >10", would result in scan query!
# Batch get, primary key based query
from pyspark.sql.functions import col
somePrimaryKeys= list(range(1,10))
someMoreKeys= list(range(12,14))
batchGet2= spark \
.read \
.format("aerospike") \
.option("aerospike.set", "salary_data") \
.option("aerospike.keyType", "int") \
.load().where((col("__key").isin(somePrimaryKeys)) | ( col("__key").isin(someMoreKeys)))
batchGet2.show(5) | +-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
|__key| __digest| __expiry|__generation| __ttl| age| name|salary| id|
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
| 13|[27 B2 50 19 5B 5...|378341961| 2|2591985|24.945277952954463|Individual: 013| 47114| 13|
| 5|[CC 73 E2 C2 23 2...|378341961| 2|2591985| 26.41972973144744|Individual: 005| 53845| 5|
| 1|[85 36 18 55 4C B...|378341961| 2|2591985|25.395470523704972|Individual: 001| 48976| 1|
| 9|[EB 86 7C 94 AA 4...|378341961| 2|2591985| 24.04479361358856|Individual: 009| 39991| 9|
| 3|[B1 E9 BC 33 C7 9...|378341961| 2|2591985|26.918958635987867|Individual: 003| 59828| 3|
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
only showing top 5 rows
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
batchget query using `__digest` - `__digest` can have only two types `BinaryType`(default type) or `StringType`. - If schema is not provided and `__digest` is `StringType`, then set `aerospike.digestType` to `string`. - Records retrieved with `__digest` batchget call will have null primary key (i.e.`__key` is `null`). | #convert digests to a list of byte[]
digest_list=batchGet2.select("__digest").rdd.flatMap(lambda x: x).collect()
#convert digest to hex string for querying. Only digests of type hex string and byte[] array are allowed.
string_digest=[ ''.join(format(x, '02x') for x in m) for m in digest_list]
#option("aerospike.digestType", "string") hints to assume that __digest type is string in schema inference.
#please note that __key retrieved in this case is null. So be careful to use retrieved keys in downstream query!
batchGetWithDigest= spark \
.read \
.format("aerospike") \
.option("aerospike.set", "salary_data") \
.option("aerospike.digestType", "string") \
.load().where(col("__digest").isin(string_digest))
batchGetWithDigest.show()
#digests can be mixed with primary keys as well
batchGetWithDigestAndKey= spark \
.read \
.format("aerospike") \
.option("aerospike.set", "salary_data") \
.option("aerospike.digestType", "string") \
.option("aerospike.keyType", "int") \
.load().where(col("__digest").isin(string_digest[0:1]) | ( col("__key").isin(someMoreKeys)))
batchGetWithDigestAndKey.show()
#please note to the null in key columns in both dataframe | +-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
|__key| __digest| __expiry|__generation| __ttl| age| name|salary| id|
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
| null|27b250195b5a5ba13...|378341961| 2|2591977|24.945277952954463|Individual: 013| 47114| 13|
| null|cc73e2c2232b35c49...|378341961| 2|2591977| 26.41972973144744|Individual: 005| 53845| 5|
| null|853618554cb05c351...|378341961| 2|2591977|25.395470523704972|Individual: 001| 48976| 1|
| null|eb867c94aa487a039...|378341961| 2|2591977| 24.04479361358856|Individual: 009| 39991| 9|
| null|b1e9bc33c79b69e5c...|378341961| 2|2591977|26.918958635987867|Individual: 003| 59828| 3|
| null|5a4a6223f73814afe...|378341961| 2|2591977|24.065640693038556|Individual: 006| 55035| 6|
| null|db4ab2ffe4642f01c...|378341961| 2|2591976| 25.30086646117202|Individual: 007| 51374| 7|
| null|86bbb52ef3b7d61eb...|378341961| 2|2591976| 24.31403545898676|Individual: 002| 47402| 2|
| null|f84bdce243c7f1305...|378341961| 2|2591976|26.251474759555798|Individual: 008| 56764| 8|
| null|849cbbf34c5ca14ab...|378341961| 2|2591976|25.000494245766017|Individual: 012| 66244| 12|
| null|91dc5e91d4b9060f6...|378341961| 2|2591976|25.296641063103234|Individual: 004| 50464| 4|
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
|__key| __digest| __expiry|__generation| __ttl| age| name|salary| id|
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
| null|27b250195b5a5ba13...|378341961| 2|2591976|24.945277952954463|Individual: 013| 47114| 13|
| 12|849cbbf34c5ca14ab...|378341961| 2|2591975|25.000494245766017|Individual: 012| 66244| 12|
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Queries including non-primary key conditions | # This query will run as a scan, which will be slower
somePrimaryKeys= list(range(1,10))
scanQuery1= spark \
.read \
.format("aerospike") \
.option("aerospike.set", "salary_data") \
.option("aerospike.keyType", "int") \
.load().where((col("__key").isin(somePrimaryKeys)) | ( col("age") >50 ))
scanQuery1.show() | +-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
|__key| __digest| __expiry|__generation| __ttl| age| name|salary| id|
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
| null|[9A 80 6A A1 FC C...|378341961| 2|2591974| 50.3039623703105|Individual: 132| 78746|132|
| null|[EF A0 76 41 51 B...|378341961| 2|2591974| 54.98712625322743|Individual: 160| 97029|160|
| null|[6E 92 74 77 95 D...|378341961| 2|2591974| 56.51623471593584|Individual: 196| 80848|196|
| null|[71 65 79 9E 25 9...|378341961| 2|2591974| 50.4687163424899|Individual: 162| 96742|162|
| null|[7C 66 F5 9E 99 6...|378341961| 2|2591974| 50.57144124293668|Individual: 156| 88377|156|
| null|[7E A6 1C 30 4F 9...|378341961| 2|2591974| 50.58123004549132|Individual: 203| 91326|203|
| null|[AB AA F1 86 BF C...|378341961| 2|2591973| 50.82155356588119|Individual: 106| 91658|106|
| null|[BC 6A 1B 19 1A 9...|378341961| 2|2591973| 50.83291154818823|Individual: 187| 92796|187|
| null|[0E 7B 68 E5 9C 9...|378341961| 2|2591973|52.636460763338036|Individual: 149| 90797|149|
| null|[9E 5B 71 28 56 3...|378341961| 2|2591973|51.040523493441206|Individual: 214| 90306|214|
| null|[28 CC 1A A7 5E 2...|378341961| 2|2591973| 56.14454565605453|Individual: 220| 94943|220|
| null|[DF 6D 03 6F 18 2...|378341961| 2|2591973|51.405636565306544|Individual: 193| 97698|193|
| null|[4B AF 54 1F E5 2...|378341961| 2|2591973| 51.28350713525771|Individual: 178| 90077|178|
| null|[FD DF 68 1A 00 E...|378341961| 2|2591972|56.636218720385074|Individual: 206|105414|206|
+-----+--------------------+---------+------------+-------+------------------+---------------+------+---+
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Pushdown [Aerospike Expressions](https://docs.aerospike.com/docs/guide/expressions/) from within a Spark API. - Make sure that you do not use no the WHERE clause or spark filters while querying - See [Aerospike Expressions](https://docs.aerospike.com/docs/guide/expressions/) for more information on how to construct expressions. - Contstructed expressions must be converted to Base64 before using them in the Spark API | scala_predexp= sc._jvm.com.aerospike.spark.utility.AerospikePushdownExpressions
#id % 5 == 0 => get rows where mod(col("id")) ==0
#Equvalent java Exp: Exp.eq(Exp.mod(Exp.intBin("a"), Exp.`val`(5)), Exp.`val`(0))
expIntBin=scala_predexp.intBin("id") # id is the name of column
expMODIntBinEqualToZero=scala_predexp.eq(scala_predexp.mod(expIntBin, scala_predexp.val(5)),scala_predexp.val(0))
expMODIntBinToBase64= scala_predexp.build(expMODIntBinEqualToZero).getBase64()
#expMODIntBinToBase64= "kwGTGpNRAqJpZAUA"
pushdownset = "py_input_data"
pushDownDF =spark\
.read \
.format("aerospike") \
.schema(schema) \
.option("aerospike.set", pushdownset) \
.option("aerospike.pushdown.expressions", expMODIntBinToBase64) \
.load()
pushDownDF.count() #should get 39 records, we have 199/5 records whose id bin is divisble by 5
pushDownDF.show(2) | +---+------+----+------+
| id| name| age|salary|
+---+------+----+------+
| 10|name10|null| null|
| 50|name50|null| null|
+---+------+----+------+
only showing top 2 rows
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Parameters for tuning Aerospike / Spark performance - aerospike.partition.factor: number of logical aerospike partitions [0-15] - aerospike.maxthreadcount : maximum number of threads to use for writing data into Aerospike - aerospike.compression : compression of java client-server communication - aerospike.batchMax : maximum number of records per read request (default 5000) - aerospike.recordspersecond : same as java client Other useful parameters - aerospike.keyType : Primary key type hint for schema inference. Always set it properly if primary key type is not string See https://www.aerospike.com/docs/connect/processing/spark/reference.html for detailed description of the above properties Machine Learning using Aerospike / SparkIn this section we use the data we took from Aerospike and apply a clustering algorithm to it.We assume the data is composed of multiple data sets having a Gaussian multi-variate distributionWe don't know how many clusters there are, so we try clustering based on the assumption there are 1 through 20.We compare the quality of the results using the Bayesian Information Criterion - https://en.wikipedia.org/wiki/Bayesian_information_criterion and pick the best. Find Optimal Cluster Count | from sklearn.mixture import GaussianMixture
# We take the data we previously
ages=pdf['age']
salaries=pdf['salary']
#age_salary_matrix=np.matrix([ages,salaries]).T
age_salary_matrix=np.asarray([ages,salaries]).T
# Find the optimal number of clusters
optimal_cluster_count = 1
best_bic_score = GaussianMixture(1).fit(age_salary_matrix).bic(age_salary_matrix)
for count in range(1,20):
gm=GaussianMixture(count)
gm.fit(age_salary_matrix)
if gm.bic(age_salary_matrix) < best_bic_score:
best_bic_score = gm.bic(age_salary_matrix)
optimal_cluster_count = count
print("Optimal cluster count found to be "+str(optimal_cluster_count)) | Optimal cluster count found to be 4
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Estimate cluster distribution parametersNext we fit our cluster using the optimal cluster count, and print out the discovered means and covariance matrix | gm = GaussianMixture(optimal_cluster_count)
gm.fit(age_salary_matrix)
estimates = []
# Index
for index in range(0,optimal_cluster_count):
estimated_mean_age = round(gm.means_[index][0],2)
estimated_mean_salary = round(gm.means_[index][1],0)
estimated_age_std_dev = round(math.sqrt(gm.covariances_[index][0][0]),2)
estimated_salary_std_dev = round(math.sqrt(gm.covariances_[index][1][1]),0)
estimated_correlation = round(gm.covariances_[index][0][1] / ( estimated_age_std_dev * estimated_salary_std_dev ),3)
row = [estimated_mean_age,estimated_mean_salary,estimated_age_std_dev,estimated_salary_std_dev,estimated_correlation]
estimates.append(row)
pd.DataFrame(estimates,columns = ["Est Mean Age","Est Mean Salary","Est Age Std Dev","Est Salary Std Dev","Est Correlation"])
| _____no_output_____ | MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Original Distribution Parameters | distribution_data_as_rows = []
for distribution in distribution_data:
row = [distribution['age_mean'],distribution['salary_mean'],distribution['age_std_dev'],
distribution['salary_std_dev'],distribution['age_salary_correlation']]
distribution_data_as_rows.append(row)
pd.DataFrame(distribution_data_as_rows,columns = ["Mean Age","Mean Salary","Age Std Dev","Salary Std Dev","Correlation"]) | _____no_output_____ | MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
You can see that the algorithm provides good estimates of the original parameters PredictionWe generate new age/salary pairs for each of the distributions and look at how accurate the prediction is | def prediction_accuracy(model,age_salary_distribution,sample_size):
# Generate new values
new_ages,new_salaries = age_salary_sample(age_salary_distribution,sample_size)
#new_age_salary_matrix=np.matrix([new_ages,new_salaries]).T
new_age_salary_matrix=np.asarray([new_ages,new_salaries]).T
# Find which cluster the mean would be classified into
#mean = np.matrix([age_salary_distribution['age_mean'],age_salary_distribution['salary_mean']])
#mean = np.asarray([age_salary_distribution['age_mean'],age_salary_distribution['salary_mean']])
mean = np.asarray(np.matrix([age_salary_distribution['age_mean'],age_salary_distribution['salary_mean']]))
mean_cluster_index = model.predict(mean)[0]
# How would new samples be classified
classification = model.predict(new_age_salary_matrix)
# How many were classified correctly
correctly_classified = len([ 1 for x in classification if x == mean_cluster_index])
return correctly_classified / sample_size
prediction_accuracy_results = [None for x in range(3)]
for index, age_salary_distribution in enumerate(distribution_data):
prediction_accuracy_results[index] = prediction_accuracy(gm,age_salary_distribution,1000)
overall_accuracy = sum(prediction_accuracy_results)/ len(prediction_accuracy_results)
print("Accuracies for each distribution : "," ,".join(map('{:.2%}'.format,prediction_accuracy_results)))
print("Overall accuracy : ",'{:.2%}'.format(overall_accuracy))
| Accuracies for each distribution : 100.00% ,60.20% ,98.00%
Overall accuracy : 86.07%
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
aerolookup aerolookup allows you to look up records corresponding to a set of keys stored in a Spark DF, streaming or otherwise. It supports: - [Aerospike CDT](https://docs.aerospike.com/docs/guide/cdt.htmlarbitrary) - Quota and retry (these configurations are extracted from sparkconf) - [Flexible schema](https://docs.aerospike.com/docs/connect/processing/spark/configuration.htmlflexible-schemas). To enable, set `aerospike.schema.flexible` to true in the SparkConf object. - Aerospike Expressions Pushdown (Note: This must be specified through SparkConf object.) | alias = StructType([StructField("first_name", StringType(), False),
StructField("last_name", StringType(), False)])
name = StructType([StructField("first_name", StringType(), False),
StructField("aliases", ArrayType(alias), False)])
street_adress = StructType([StructField("street_name", StringType(), False),
StructField("apt_number", IntegerType(), False)])
address = StructType([StructField("zip", LongType(), False),
StructField("street", street_adress, False),
StructField("city", StringType(), False)])
work_history = StructType([StructField("company_name", StringType(), False),
StructField("company_address", address, False),
StructField("worked_from", StringType(), False)])
output_schema = StructType([StructField("name", name, False),
StructField("SSN", StringType(), False),
StructField("home_address", ArrayType(address), False)])
ssns = [["825-55-3247"], ["289-18-1554"], ["756-46-4088"],
["525-31-0299"], ["456-45-2200"], ["200-71-7765"]]
#Create a set of PKs whose records you'd like to look up in the Aerospike database
customerIdsDF=spark.createDataFrame(ssns,["SSN"])
from pyspark.sql import SQLContext
scala2_object= sc._jvm.com.aerospike.spark.PythonUtil #Import the scala object
gateway_df=scala2_object.aerolookup(customerIdsDF._jdf, #Please note ._jdf
'SSN',
'complex_input_data', #complex_input_data is the set in Aerospike database that you are using to look up the keys stored in SSN DF
output_schema.json(),
'test')
aerolookup_df=pyspark.sql.DataFrame(gateway_df,spark._wrapped)
#Note the wrapping of java object into python.sql.DataFrame
aerolookup_df.show() | +--------------------+-----------+--------------------+
| name| SSN| home_address|
+--------------------+-----------+--------------------+
|[Gary, [[Cameron,...|825-55-3247|[[66428, [Kim Mil...|
|[Megan, [[Robert,...|289-18-1554|[[81551, [Archer ...|
|[Melanie, [[Justi...|756-46-4088|[[61327, [Jeanett...|
|[Lisa, [[William,...|525-31-0299|[[98337, [Brittne...|
|[Ryan, [[Jonathon...|456-45-2200|[[97077, [Davis D...|
|[Lauren, [[Shaun,...|200-71-7765|[[6813, [Johnson ...|
+--------------------+-----------+--------------------+
| MIT | notebooks/spark/AerospikeSparkPython.ipynb | dotyjim-work/aerospike-interactive-notebooks |
Moon Data ClassificationIn this notebook, you'll be tasked with building and deploying a **custom model** in SageMaker. Specifically, you'll define and train a custom, PyTorch neural network to create a binary classifier for data that is separated into two classes; the data looks like two moon shapes when it is displayed, and is often referred to as **moon data**.The notebook will be broken down into a few steps:* Generating the moon data* Loading it into an S3 bucket* Defining a PyTorch binary classifier* Completing a training script* Training and deploying the custom model* Evaluating its performanceBeing able to train and deploy custom models is a really useful skill to have. Especially in applications that may not be easily solved by traditional algorithms like a LinearLearner.--- Load in required libraries, below. | # data
import pandas as pd
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
Generating Moon DataBelow, I have written code to generate some moon data, using sklearn's [make_moons](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html) and [train_test_split](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html).I'm specifying the number of data points and a noise parameter to use for generation. Then, displaying the resulting data. | # set data params
np.random.seed(0)
num_pts = 1000
noise_val = 0.25
# generate data
# X = 2D points, Y = class labels (0 or 1)
X, Y = make_moons(num_pts, noise=noise_val)
# Split into test and training data
X_train, X_test, Y_train, Y_test = train_test_split(X, Y,
test_size=0.25, random_state=1)
# plot
# points are colored by class, Y_train
# 0 labels = purple, 1 = yellow
plt.figure(figsize=(8,5))
plt.scatter(X_train[:,0], X_train[:,1], c=Y_train)
plt.title('Moon Data')
plt.show() | _____no_output_____ | MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
SageMaker ResourcesThe below cell stores the SageMaker session and role (for creating estimators and models), and creates a default S3 bucket. After creating this bucket, you can upload any locally stored data to S3. | # sagemaker
import boto3
import sagemaker
from sagemaker import get_execution_role
# SageMaker session and role
sagemaker_session = sagemaker.Session()
role = sagemaker.get_execution_role()
# default S3 bucket
bucket = sagemaker_session.default_bucket() | _____no_output_____ | MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
EXERCISE: Create csv filesDefine a function that takes in x (features) and y (labels) and saves them to one `.csv` file at the path `data_dir/filename`. SageMaker expects `.csv` files to be in a certain format, according to the [documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html):> Amazon SageMaker requires that a CSV file doesn't have a header record and that the target variable is in the first column.It may be useful to use pandas to merge your features and labels into one DataFrame and then convert that into a `.csv` file. When you create a `.csv` file, make sure to set `header=False`, and `index=False` so you don't include anything extraneous, like column names, in the `.csv` file. | import os
def make_csv(x, y, filename, data_dir):
'''Merges features and labels and converts them into one csv file with labels in the first column.
:param x: Data features
:param y: Data labels
:param file_name: Name of csv file, ex. 'train.csv'
:param data_dir: The directory where files will be saved
'''
# make data dir, if it does not exist
if not os.path.exists(data_dir):
os.makedirs(data_dir)
# your code here
pd.concat([pd.DataFrame(y), pd.DataFrame(x)], axis=1).to_csv(os.path.join(data_dir, filename), header=False, index=False)
# nothing is returned, but a print statement indicates that the function has run
print('Path created: '+str(data_dir)+'/'+str(filename)) | _____no_output_____ | MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
The next cell runs the above function to create a `train.csv` file in a specified directory. | data_dir = 'data_moon' # the folder we will use for storing data
name = 'train.csv'
# create 'train.csv'
make_csv(X_train, Y_train, name, data_dir) | Path created: data_moon/train.csv
| MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
Upload Data to S3Upload locally-stored `train.csv` file to S3 by using `sagemaker_session.upload_data`. This function needs to know: where the data is saved locally, and where to upload in S3 (a bucket and prefix). | # specify where to upload in S3
prefix = 'sagemaker/moon-data'
# upload to S3
input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix)
print(input_data) | s3://sagemaker-us-east-1-633655289115/sagemaker/moon-data
| MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
Check that you've uploaded the data, by printing the contents of the default bucket. | # iterate through S3 objects and print contents
for obj in boto3.resource('s3').Bucket(bucket).objects.all():
print(obj.key) | fraud_detection/linear-learner-2020-10-24-06-45-32-777/output/model.tar.gz
fraud_detection/linear-learner-2020-10-24-07-25-35-056/output/model.tar.gz
fraud_detection/linear-learner-2020-10-24-07-48-22-409/output/model.tar.gz
fraud_detection/linear-learner-2020-10-24-08-12-30-994/output/model.tar.gz
fraud_detection/linear-learner-2020-10-24-08-35-11-726/output/model.tar.gz
pytorch-inference-2020-10-24-18-31-29-473/model.tar.gz
pytorch-inference-2020-10-24-19-11-32-308/model.tar.gz
pytorch-training-2020-10-24-18-19-07-459/source/sourcedir.tar.gz
pytorch-training-2020-10-24-18-25-03-445/source/sourcedir.tar.gz
sagemaker-pytorch-2020-10-24-18-53-06-891/sourcedir.tar.gz
sagemaker-record-sets/LinearLearner-2020-10-24-06-36-33-183/.amazon.manifest
sagemaker-record-sets/LinearLearner-2020-10-24-06-36-33-183/matrix_0.pbr
sagemaker-record-sets/LinearLearner-2020-10-24-06-45-22-344/.amazon.manifest
sagemaker-record-sets/LinearLearner-2020-10-24-06-45-22-344/matrix_0.pbr
sagemaker-record-sets/LinearLearner-2020-10-24-07-02-18-578/.amazon.manifest
sagemaker-record-sets/LinearLearner-2020-10-24-07-02-18-578/matrix_0.pbr
sagemaker-record-sets/LinearLearner-2020-10-24-07-14-28-034/.amazon.manifest
sagemaker-record-sets/LinearLearner-2020-10-24-07-14-28-034/matrix_0.pbr
sagemaker-record-sets/LinearLearner-2020-10-24-08-10-34-997/.amazon.manifest
sagemaker-record-sets/LinearLearner-2020-10-24-08-10-34-997/matrix_0.pbr
sagemaker/moon-data/pytorch-training-2020-10-24-18-25-03-445/debug-output/claim.smd
sagemaker/moon-data/pytorch-training-2020-10-24-18-25-03-445/debug-output/collections/000000000/worker_0_collections.json
sagemaker/moon-data/pytorch-training-2020-10-24-18-25-03-445/debug-output/events/000000000000/000000000000_worker_0.tfevents
sagemaker/moon-data/pytorch-training-2020-10-24-18-25-03-445/debug-output/events/000000000500/000000000500_worker_0.tfevents
sagemaker/moon-data/pytorch-training-2020-10-24-18-25-03-445/debug-output/index/000000000/000000000000_worker_0.json
sagemaker/moon-data/pytorch-training-2020-10-24-18-25-03-445/debug-output/index/000000000/000000000500_worker_0.json
sagemaker/moon-data/pytorch-training-2020-10-24-18-25-03-445/debug-output/training_job_end.ts
sagemaker/moon-data/pytorch-training-2020-10-24-18-25-03-445/output/model.tar.gz
sagemaker/moon-data/train.csv
| MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
--- ModelingNow that you've uploaded your training data, it's time to define and train a model!In this notebook, you'll define and train a **custom PyTorch model**; a neural network that performs binary classification. EXERCISE: Define a model in `model.py`To implement a custom classifier, the first thing you'll do is define a neural network. You've been give some starting code in the directory `source`, where you can find the file, `model.py`. You'll need to complete the class `SimpleNet`; specifying the layers of the neural network and its feedforward behavior. It may be helpful to review the [code for a 3-layer MLP](https://github.com/udacity/deep-learning-v2-pytorch/blob/master/convolutional-neural-networks/mnist-mlp/mnist_mlp_solution.ipynb).This model should be designed to: * Accept a number of `input_dim` features* Create some linear, hidden layers of a desired size* Return **a single output value** that indicates the class scoreThe returned output value should be a [sigmoid-activated](https://pytorch.org/docs/stable/nn.htmlsigmoid) class score; a value between 0-1 that can be rounded to get a predicted, class label.Below, you can use !pygmentize to display the code in the `model.py` file. Read through the code; all of your tasks are marked with TODO comments. You should navigate to the file, and complete the tasks to define a `SimpleNet`. | !pygmentize source/model.py | [34mimport[39;49;00m [04m[36mtorch[39;49;00m
[34mimport[39;49;00m [04m[36mtorch[39;49;00m[04m[36m.[39;49;00m[04m[36mnn[39;49;00m [34mas[39;49;00m [04m[36mnn[39;49;00m
[34mimport[39;49;00m [04m[36mtorch[39;49;00m[04m[36m.[39;49;00m[04m[36mnn[39;49;00m[04m[36m.[39;49;00m[04m[36mfunctional[39;49;00m [34mas[39;49;00m [04m[36mF[39;49;00m
[37m## TODO: Complete this classifier[39;49;00m
[34mclass[39;49;00m [04m[32mSimpleNet[39;49;00m(nn.Module):
[37m## TODO: Define the init function[39;49;00m
[34mdef[39;49;00m [32m__init__[39;49;00m([36mself[39;49;00m, input_dim, hidden_dim, output_dim):
[33m'''Defines layers of a neural network.[39;49;00m
[33m :param input_dim: Number of input features[39;49;00m
[33m :param hidden_dim: Size of hidden layer(s)[39;49;00m
[33m :param output_dim: Number of outputs[39;49;00m
[33m '''[39;49;00m
[36msuper[39;49;00m(SimpleNet, [36mself[39;49;00m).[32m__init__[39;49;00m()
[37m# define all layers, here[39;49;00m
[37m# first layer[39;49;00m
hidden_1 = hidden_dim
[36mself[39;49;00m.fc1 = nn.Linear(input_dim, hidden_1)
[37m# second layer[39;49;00m
hidden_2 = [36mint[39;49;00m(hidden_dim/[34m2[39;49;00m)
[36mself[39;49;00m.fc2 = nn.Linear(hidden_1, hidden_2)
[37m# final layer[39;49;00m
[36mself[39;49;00m.fc3 = nn.Linear(hidden_2, output_dim)
[37m# dropout[39;49;00m
[36mself[39;49;00m.dropout = nn.Dropout([34m0.2[39;49;00m)
[37m# sigmoid layer[39;49;00m
[36mself[39;49;00m.sig = nn.Sigmoid()
[37m## TODO: Define the feedforward behavior of the network[39;49;00m
[34mdef[39;49;00m [32mforward[39;49;00m([36mself[39;49;00m, x):
[33m'''Feedforward behavior of the net.[39;49;00m
[33m :param x: A batch of input features[39;49;00m
[33m :return: A single, sigmoid activated value[39;49;00m
[33m '''[39;49;00m
[37m# your code, here[39;49;00m
[37m# Computing layers with activation functions and dropout[39;49;00m
[37m# add first layer[39;49;00m
x = F.relu([36mself[39;49;00m.fc1(x))
x = [36mself[39;49;00m.dropout(x)
[37m# add second layer[39;49;00m
x = F.relu([36mself[39;49;00m.fc2(x))
x = [36mself[39;49;00m.dropout(x)
[37m# add final layer[39;49;00m
x = [36mself[39;49;00m.fc3(x)
[37m# add sigmoid layer[39;49;00m
x = [36mself[39;49;00m.sig(x)
[34mreturn[39;49;00m x
| MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
Training ScriptTo implement a custom classifier, you'll also need to complete a `train.py` script. You can find this in the `source` directory.A typical training script:* Loads training data from a specified directory* Parses any training & model hyperparameters (ex. nodes in a neural network, training epochs, etc.)* Instantiates a model of your design, with any specified hyperparams* Trains that model* Finally, saves the model so that it can be hosted/deployed, later EXERCISE: Complete the `train.py` scriptMuch of the training script code is provided for you. Almost all of your work will be done in the if __name__ == '__main__': section. To complete the `train.py` file, you will:* Define any additional model training hyperparameters using `parser.add_argument`* Define a model in the if __name__ == '__main__': section* Train the model in that same sectionBelow, you can use !pygmentize to display an existing train.py file. Read through the code; all of your tasks are marked with TODO comments. | !pygmentize source/train.py | [34mfrom[39;49;00m [04m[36m__future__[39;49;00m [34mimport[39;49;00m print_function [37m# future proof[39;49;00m
[34mimport[39;49;00m [04m[36margparse[39;49;00m
[34mimport[39;49;00m [04m[36msys[39;49;00m
[34mimport[39;49;00m [04m[36mos[39;49;00m
[34mimport[39;49;00m [04m[36mjson[39;49;00m
[34mimport[39;49;00m [04m[36mpandas[39;49;00m [34mas[39;49;00m [04m[36mpd[39;49;00m
[37m# pytorch[39;49;00m
[34mimport[39;49;00m [04m[36mtorch[39;49;00m
[34mimport[39;49;00m [04m[36mtorch[39;49;00m[04m[36m.[39;49;00m[04m[36mnn[39;49;00m [34mas[39;49;00m [04m[36mnn[39;49;00m
[34mimport[39;49;00m [04m[36mtorch[39;49;00m[04m[36m.[39;49;00m[04m[36moptim[39;49;00m [34mas[39;49;00m [04m[36moptim[39;49;00m
[34mimport[39;49;00m [04m[36mtorch[39;49;00m[04m[36m.[39;49;00m[04m[36mutils[39;49;00m[04m[36m.[39;49;00m[04m[36mdata[39;49;00m
[37m# import model[39;49;00m
[34mfrom[39;49;00m [04m[36mmodel[39;49;00m [34mimport[39;49;00m SimpleNet
[34mdef[39;49;00m [32mmodel_fn[39;49;00m(model_dir):
[36mprint[39;49;00m([33m"[39;49;00m[33mLoading model.[39;49;00m[33m"[39;49;00m)
[37m# First, load the parameters used to create the model.[39;49;00m
model_info = {}
model_info_path = os.path.join(model_dir, [33m'[39;49;00m[33mmodel_info.pth[39;49;00m[33m'[39;49;00m)
[34mwith[39;49;00m [36mopen[39;49;00m(model_info_path, [33m'[39;49;00m[33mrb[39;49;00m[33m'[39;49;00m) [34mas[39;49;00m f:
model_info = torch.load(f)
[36mprint[39;49;00m([33m"[39;49;00m[33mmodel_info: [39;49;00m[33m{}[39;49;00m[33m"[39;49;00m.format(model_info))
[37m# Determine the device and construct the model.[39;49;00m
device = torch.device([33m"[39;49;00m[33mcuda[39;49;00m[33m"[39;49;00m [34mif[39;49;00m torch.cuda.is_available() [34melse[39;49;00m [33m"[39;49;00m[33mcpu[39;49;00m[33m"[39;49;00m)
model = SimpleNet(model_info[[33m'[39;49;00m[33minput_dim[39;49;00m[33m'[39;49;00m],
model_info[[33m'[39;49;00m[33mhidden_dim[39;49;00m[33m'[39;49;00m],
model_info[[33m'[39;49;00m[33moutput_dim[39;49;00m[33m'[39;49;00m])
[37m# Load the stored model parameters.[39;49;00m
model_path = os.path.join(model_dir, [33m'[39;49;00m[33mmodel.pth[39;49;00m[33m'[39;49;00m)
[34mwith[39;49;00m [36mopen[39;49;00m(model_path, [33m'[39;49;00m[33mrb[39;49;00m[33m'[39;49;00m) [34mas[39;49;00m f:
model.load_state_dict(torch.load(f))
[34mreturn[39;49;00m model.to(device)
[37m# Load the training data from a csv file[39;49;00m
[34mdef[39;49;00m [32m_get_train_loader[39;49;00m(batch_size, data_dir):
[36mprint[39;49;00m([33m"[39;49;00m[33mGet data loader.[39;49;00m[33m"[39;49;00m)
[37m# read in csv file[39;49;00m
train_data = pd.read_csv(os.path.join(data_dir, [33m"[39;49;00m[33mtrain.csv[39;49;00m[33m"[39;49;00m), header=[34mNone[39;49;00m, names=[34mNone[39;49;00m)
[37m# labels are first column[39;49;00m
train_y = torch.from_numpy(train_data[[[34m0[39;49;00m]].values).float().squeeze()
[37m# features are the rest[39;49;00m
train_x = torch.from_numpy(train_data.drop([[34m0[39;49;00m], axis=[34m1[39;49;00m).values).float()
[37m# create dataset[39;49;00m
train_ds = torch.utils.data.TensorDataset(train_x, train_y)
[34mreturn[39;49;00m torch.utils.data.DataLoader(train_ds, batch_size=batch_size)
[37m# Provided train function[39;49;00m
[34mdef[39;49;00m [32mtrain[39;49;00m(model, train_loader, epochs, optimizer, criterion, device):
[33m"""[39;49;00m
[33m This is the training method that is called by the PyTorch training script. The parameters[39;49;00m
[33m passed are as follows:[39;49;00m
[33m model - The PyTorch model that we wish to train.[39;49;00m
[33m train_loader - The PyTorch DataLoader that should be used during training.[39;49;00m
[33m epochs - The total number of epochs to train for.[39;49;00m
[33m optimizer - The optimizer to use during training.[39;49;00m
[33m criterion - The loss function used for training. [39;49;00m
[33m device - Where the model and data should be loaded (gpu or cpu).[39;49;00m
[33m """[39;49;00m
[34mfor[39;49;00m epoch [35min[39;49;00m [36mrange[39;49;00m([34m1[39;49;00m, epochs + [34m1[39;49;00m):
model.train()
total_loss = [34m0[39;49;00m
[34mfor[39;49;00m batch_idx, (data, target) [35min[39;49;00m [36menumerate[39;49;00m(train_loader, [34m1[39;49;00m):
[37m# prep data[39;49;00m
data, target = data.to(device), target.to(device)
optimizer.zero_grad() [37m# zero accumulated gradients[39;49;00m
[37m# get output of SimpleNet[39;49;00m
output = model(data)
[37m# calculate loss and perform backprop[39;49;00m
loss = criterion(output, target)
loss.backward()
optimizer.step()
total_loss += loss.item()
[37m# print loss stats[39;49;00m
[36mprint[39;49;00m([33m"[39;49;00m[33mEpoch: [39;49;00m[33m{}[39;49;00m[33m, Loss: [39;49;00m[33m{}[39;49;00m[33m"[39;49;00m.format(epoch, total_loss / [36mlen[39;49;00m(train_loader)))
[37m# save after all epochs[39;49;00m
save_model(model, args.model_dir)
[37m# Provided model saving functions[39;49;00m
[34mdef[39;49;00m [32msave_model[39;49;00m(model, model_dir):
[36mprint[39;49;00m([33m"[39;49;00m[33mSaving the model.[39;49;00m[33m"[39;49;00m)
path = os.path.join(model_dir, [33m'[39;49;00m[33mmodel.pth[39;49;00m[33m'[39;49;00m)
[37m# save state dictionary[39;49;00m
torch.save(model.cpu().state_dict(), path)
[34mdef[39;49;00m [32msave_model_params[39;49;00m(model, model_dir):
model_info_path = os.path.join(args.model_dir, [33m'[39;49;00m[33mmodel_info.pth[39;49;00m[33m'[39;49;00m)
[34mwith[39;49;00m [36mopen[39;49;00m(model_info_path, [33m'[39;49;00m[33mwb[39;49;00m[33m'[39;49;00m) [34mas[39;49;00m f:
model_info = {
[33m'[39;49;00m[33minput_dim[39;49;00m[33m'[39;49;00m: args.input_dim,
[33m'[39;49;00m[33mhidden_dim[39;49;00m[33m'[39;49;00m: args.hidden_dim,
[33m'[39;49;00m[33moutput_dim[39;49;00m[33m'[39;49;00m: args.output_dim
}
torch.save(model_info, f)
[37m## TODO: Complete the main code[39;49;00m
[34mif[39;49;00m [31m__name__[39;49;00m == [33m'[39;49;00m[33m__main__[39;49;00m[33m'[39;49;00m:
[37m# All of the model parameters and training parameters are sent as arguments[39;49;00m
[37m# when this script is executed, during a training job[39;49;00m
[37m# Here we set up an argument parser to easily access the parameters[39;49;00m
parser = argparse.ArgumentParser()
[37m# SageMaker parameters, like the directories for training data and saving models; set automatically[39;49;00m
[37m# Do not need to change[39;49;00m
parser.add_argument([33m'[39;49;00m[33m--hosts[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mlist[39;49;00m, default=json.loads(os.environ[[33m'[39;49;00m[33mSM_HOSTS[39;49;00m[33m'[39;49;00m]))
parser.add_argument([33m'[39;49;00m[33m--current-host[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mstr[39;49;00m, default=os.environ[[33m'[39;49;00m[33mSM_CURRENT_HOST[39;49;00m[33m'[39;49;00m])
parser.add_argument([33m'[39;49;00m[33m--model-dir[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mstr[39;49;00m, default=os.environ[[33m'[39;49;00m[33mSM_MODEL_DIR[39;49;00m[33m'[39;49;00m])
parser.add_argument([33m'[39;49;00m[33m--data-dir[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mstr[39;49;00m, default=os.environ[[33m'[39;49;00m[33mSM_CHANNEL_TRAIN[39;49;00m[33m'[39;49;00m])
[37m# Training Parameters, given[39;49;00m
parser.add_argument([33m'[39;49;00m[33m--batch-size[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mint[39;49;00m, default=[34m64[39;49;00m, metavar=[33m'[39;49;00m[33mN[39;49;00m[33m'[39;49;00m,
help=[33m'[39;49;00m[33minput batch size for training (default: 64)[39;49;00m[33m'[39;49;00m)
parser.add_argument([33m'[39;49;00m[33m--epochs[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mint[39;49;00m, default=[34m10[39;49;00m, metavar=[33m'[39;49;00m[33mN[39;49;00m[33m'[39;49;00m,
help=[33m'[39;49;00m[33mnumber of epochs to train (default: 10)[39;49;00m[33m'[39;49;00m)
parser.add_argument([33m'[39;49;00m[33m--lr[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mfloat[39;49;00m, default=[34m0.001[39;49;00m, metavar=[33m'[39;49;00m[33mLR[39;49;00m[33m'[39;49;00m,
help=[33m'[39;49;00m[33mlearning rate (default: 0.001)[39;49;00m[33m'[39;49;00m)
parser.add_argument([33m'[39;49;00m[33m--seed[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mint[39;49;00m, default=[34m1[39;49;00m, metavar=[33m'[39;49;00m[33mS[39;49;00m[33m'[39;49;00m,
help=[33m'[39;49;00m[33mrandom seed (default: 1)[39;49;00m[33m'[39;49;00m)
[37m## TODO: Add args for the three model parameters: input_dim, hidden_dim, output_dim[39;49;00m
[37m# Model parameters[39;49;00m
parser.add_argument([33m'[39;49;00m[33m--input_dim[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mint[39;49;00m, default=[34m2[39;49;00m, metavar=[33m'[39;49;00m[33mN[39;49;00m[33m'[39;49;00m,
help=[33m'[39;49;00m[33minput dimension for training (default: 2)[39;49;00m[33m'[39;49;00m)
parser.add_argument([33m'[39;49;00m[33m--hidden_dim[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mint[39;49;00m, default=[34m20[39;49;00m, metavar=[33m'[39;49;00m[33mN[39;49;00m[33m'[39;49;00m,
help=[33m'[39;49;00m[33mhidden dimension for training (default: 20)[39;49;00m[33m'[39;49;00m)
parser.add_argument([33m'[39;49;00m[33m--output_dim[39;49;00m[33m'[39;49;00m, [36mtype[39;49;00m=[36mint[39;49;00m, default=[34m1[39;49;00m, metavar=[33m'[39;49;00m[33mN[39;49;00m[33m'[39;49;00m,
help=[33m'[39;49;00m[33mnumber of classes (default: 1)[39;49;00m[33m'[39;49;00m)
args = parser.parse_args()
device = torch.device([33m"[39;49;00m[33mcuda[39;49;00m[33m"[39;49;00m [34mif[39;49;00m torch.cuda.is_available() [34melse[39;49;00m [33m"[39;49;00m[33mcpu[39;49;00m[33m"[39;49;00m)
[37m# set the seed for generating random numbers[39;49;00m
torch.manual_seed(args.seed)
[34mif[39;49;00m torch.cuda.is_available():
torch.cuda.manual_seed(args.seed)
[37m# get train loader[39;49;00m
train_loader = _get_train_loader(args.batch_size, args.data_dir) [37m# data_dir from above..[39;49;00m
[37m## TODO: Build the model by passing in the input params[39;49;00m
[37m# To get params from the parser, call args.argument_name, ex. args.epochs or ards.hidden_dim[39;49;00m
[37m# Don't forget to move your model .to(device) to move to GPU , if appropriate[39;49;00m
model = SimpleNet(args.input_dim, args.hidden_dim, args.output_dim).to(device)
[37m# Given: save the parameters used to construct the model[39;49;00m
save_model_params(model, args.model_dir)
[37m## TODO: Define an optimizer and loss function for training[39;49;00m
optimizer = optim.Adam(model.parameters(), lr=args.lr)
criterion = nn.BCELoss()
[37m# Trains the model (given line of code, which calls the above training function)[39;49;00m
[37m# This function *also* saves the model state dictionary[39;49;00m
train(model, train_loader, args.epochs, optimizer, criterion, device)
| MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
EXERCISE: Create a PyTorch EstimatorYou've had some practice instantiating built-in models in SageMaker. All estimators require some constructor arguments to be passed in. When a custom model is constructed in SageMaker, an **entry point** must be specified. The entry_point is the training script that will be executed when the model is trained; the `train.py` function you specified above! See if you can complete this task, instantiating a PyTorch estimator, using only the [PyTorch estimator documentation](https://sagemaker.readthedocs.io/en/stable/sagemaker.pytorch.html) as a resource. It is suggested that you use the **latest version** of PyTorch as the optional `framework_version` parameter. Instance TypesIt is suggested that you use instances that are available in the free tier of usage: `'ml.c4.xlarge'` for training and `'ml.t2.medium'` for deployment. | # import a PyTorch wrapper
from sagemaker.pytorch import PyTorch
# specify an output path
output_path = 's3://{}/{}'.format(bucket, prefix)
# instantiate a pytorch estimator
estimator = PyTorch(entry_point='train.py',
source_dir='source',
framework_version='1.0',
role=role,
train_instance_count=1,
train_instance_type='ml.c4.xlarge',
output_path=output_path,
sagemaker_session=sagemaker_session,
hyperparameters={
'epoch':80,
'input_dim':2,
'hidden_dim':20,
'output_dim':1
})
| _____no_output_____ | MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
Train the EstimatorAfter instantiating your estimator, train it with a call to `.fit()`. The `train.py` file explicitly loads in `.csv` data, so you do not need to convert the input data to any other format. | %%time
# train the estimator on S3 training data
estimator.fit({'train': input_data}) | 'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.
'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
| MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
Create a Trained ModelPyTorch models do not automatically come with `.predict()` functions attached (as many Scikit-learn models do, for example) and you may have noticed that you've been give a `predict.py` file. This file is responsible for loading a trained model and applying it to passed in, numpy data. When you created a PyTorch estimator, you specified where the training script, `train.py` was located. > How can we tell a PyTorch model where the `predict.py` file is?Before you can deploy this custom PyTorch model, you have to take one more step: creating a `PyTorchModel`. In earlier exercises you could see that a call to `.deploy()` created both a **model** and an **endpoint**, but for PyTorch models, these steps have to be separate. EXERCISE: Instantiate a `PyTorchModel`You can create a `PyTorchModel` (different that a PyTorch estimator) from your trained, estimator attributes. This model is responsible for knowing how to execute a specific `predict.py` script. And this model is what you'll deploy to create an endpoint. Model ParametersTo instantiate a `PyTorchModel`, ([documentation, here](https://sagemaker.readthedocs.io/en/stable/sagemaker.pytorch.htmlsagemaker.pytorch.model.PyTorchModel)) you pass in the same arguments as your PyTorch estimator, with a few additions/modifications:* **model_data**: The trained `model.tar.gz` file created by your estimator, which can be accessed as `estimator.model_data`.* **entry_point**: This time, this is the path to the Python script SageMaker runs for **prediction** rather than training, `predict.py`. | %%time
# importing PyTorchModel
from sagemaker.pytorch import PyTorchModel
# Create a model from the trained estimator data
# And point to the prediction script
model = PyTorchModel(model_data=estimator.model_data,
role=role,
framework_version='1.0',
entry_point='predict.py',
source_dir='source',
)
| Parameter image will be renamed to image_uri in SageMaker Python SDK v2.
| MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
EXERCISE: Deploy the trained modelDeploy your model to create a predictor. We'll use this to make predictions on our test data and evaluate the model. | %%time
# deploy and create a predictor
predictor = model.deploy(initial_instance_count=1, instance_type='ml.t2.medium') | 'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
| MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
--- Evaluating Your ModelOnce your model is deployed, you can see how it performs when applied to the test data.The provided function below, takes in a deployed predictor, some test features and labels, and returns a dictionary of metrics; calculating false negatives and positives as well as recall, precision, and accuracy. | # code to evaluate the endpoint on test data
# returns a variety of model metrics
def evaluate(predictor, test_features, test_labels, verbose=True):
"""
Evaluate a model on a test set given the prediction endpoint.
Return binary classification metrics.
:param predictor: A prediction endpoint
:param test_features: Test features
:param test_labels: Class labels for test data
:param verbose: If True, prints a table of all performance metrics
:return: A dictionary of performance metrics.
"""
# rounding and squeezing array
test_preds = np.squeeze(np.round(predictor.predict(test_features)))
# calculate true positives, false positives, true negatives, false negatives
tp = np.logical_and(test_labels, test_preds).sum()
fp = np.logical_and(1-test_labels, test_preds).sum()
tn = np.logical_and(1-test_labels, 1-test_preds).sum()
fn = np.logical_and(test_labels, 1-test_preds).sum()
# calculate binary classification metrics
recall = tp / (tp + fn)
precision = tp / (tp + fp)
accuracy = (tp + tn) / (tp + fp + tn + fn)
# print metrics
if verbose:
print(pd.crosstab(test_labels, test_preds, rownames=['actuals'], colnames=['predictions']))
print("\n{:<11} {:.3f}".format('Recall:', recall))
print("{:<11} {:.3f}".format('Precision:', precision))
print("{:<11} {:.3f}".format('Accuracy:', accuracy))
print()
return {'TP': tp, 'FP': fp, 'FN': fn, 'TN': tn,
'Precision': precision, 'Recall': recall, 'Accuracy': accuracy}
| _____no_output_____ | MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
Test ResultsThe cell below runs the `evaluate` function. The code assumes that you have a defined `predictor` and `X_test` and `Y_test` from previously-run cells. | # get metrics for custom predictor
metrics = evaluate(predictor, X_test, Y_test, True) | predictions 0.0 1.0
actuals
0 107 11
1 15 117
Recall: 0.886
Precision: 0.914
Accuracy: 0.896
| MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
Delete the EndpointFinally, I've add a convenience function to delete prediction endpoints after we're done with them. And if you're done evaluating the model, you should delete your model endpoint! | # Accepts a predictor endpoint as input
# And deletes the endpoint by name
def delete_endpoint(predictor):
try:
boto3.client('sagemaker').delete_endpoint(EndpointName=predictor.endpoint)
print('Deleted {}'.format(predictor.endpoint))
except:
print('Already deleted: {}'.format(predictor.endpoint))
# delete the predictor endpoint
delete_endpoint(predictor) | Deleted sagemaker-pytorch-2020-10-24-19-46-20-459
| MIT | Moon_classification_Exercise/Moon_Classification_Exercise.ipynb | NwekeChidi/Udacity_ML_with_SageMaker |
Loading Graphs in NetworkX | import networkx as nx
import numpy as np
import pandas as pd
%matplotlib notebook
# Instantiate the graph
G1 = nx.Graph()
# add node/edge pairs
G1.add_edges_from([(0, 1),
(0, 2),
(0, 3),
(0, 5),
(1, 3),
(1, 6),
(3, 4),
(4, 5),
(4, 7),
(5, 8),
(8, 9)])
# draw the network G1
nx.draw_networkx(G1)
import networkx as nx
G=nx.MultiGraph()
G.add_node('A',role='manager')
G.add_edge('A','B',relation = 'friend')
G.add_edge('A','C', relation = 'business partner')
G.add_edge('A','B', relation = 'classmate')
G.node['A']['role'] = 'team member'
G.node['B']['role'] = 'engineer'
G.node['A']['role'] | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Adjacency List `G_adjlist.txt` is the adjaceny list representation of G1.It can be read as follows:* `0 1 2 3 5` $\rightarrow$ node `0` is adjacent to nodes `1, 2, 3, 5`* `1 3 6` $\rightarrow$ node `1` is (also) adjacent to nodes `3, 6`* `2` $\rightarrow$ node `2` is (also) adjacent to no new nodes* `3 4` $\rightarrow$ node `3` is (also) adjacent to node `4` and so on. Note that adjacencies are only accounted for once (e.g. node `2` is adjacent to node `0`, but node `0` is not listed in node `2`'s row, because that edge has already been accounted for in node `0`'s row). | !cat G_adjlist.txt | 0 1 2 3 5
1 3 6
2
3 4
4 5 7
5 8
6
7
8 9
9
| MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
If we read in the adjacency list using `nx.read_adjlist`, we can see that it matches `G1`. | G2 = nx.read_adjlist('G_adjlist.txt', nodetype=int)
G2.edges() | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Adjacency MatrixThe elements in an adjacency matrix indicate whether pairs of vertices are adjacent or not in the graph. Each node has a corresponding row and column. For example, row `0`, column `1` corresponds to the edge between node `0` and node `1`. Reading across row `0`, there is a '`1`' in columns `1`, `2`, `3`, and `5`, which indicates that node `0` is adjacent to nodes 1, 2, 3, and 5 | G_mat = np.array([[0, 1, 1, 1, 0, 1, 0, 0, 0, 0],
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]])
G_mat | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
If we convert the adjacency matrix to a networkx graph using `nx.Graph`, we can see that it matches G1. | G3 = nx.Graph(G_mat)
G3.edges() | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Edgelist The edge list format represents edge pairings in the first two columns. Additional edge attributes can be added in subsequent columns. Looking at `G_edgelist.txt` this is the same as the original graph `G1`, but now each edge has a weight. For example, from the first row, we can see the edge between nodes `0` and `1`, has a weight of `4`. | !cat G_edgelist.txt | 0 1 4
0 2 3
0 3 2
0 5 6
1 3 2
1 6 5
3 4 3
4 5 1
4 7 2
5 8 6
8 9 1
| MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Using `read_edgelist` and passing in a list of tuples with the name and type of each edge attribute will create a graph with our desired edge attributes. | G4 = nx.read_edgelist('G_edgelist.txt', data=[('Weight', int)])
G4.edges(data=True) | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Pandas DataFrame Graphs can also be created from pandas dataframes if they are in edge list format. | G_df = pd.read_csv('G_edgelist.txt', delim_whitespace=True,
header=None, names=['n1', 'n2', 'weight'])
G_df
G5 = nx.from_pandas_dataframe(G_df, 'n1', 'n2', edge_attr='weight')
G5.edges(data=True) | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Chess Example Now let's load in a more complex graph and perform some basic analysis on it.We will be looking at chess_graph.txt, which is a directed graph of chess games in edge list format. | !head -5 chess_graph.txt | 1 2 0 885635999.999997
1 3 0 885635999.999997
1 4 0 885635999.999997
1 5 1 885635999.999997
1 6 0 885635999.999997
| MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Each node is a chess player, and each edge represents a game. The first column with an outgoing edge corresponds to the white player, the second column with an incoming edge corresponds to the black player.The third column, the weight of the edge, corresponds to the outcome of the game. A weight of 1 indicates white won, a 0 indicates a draw, and a -1 indicates black won.The fourth column corresponds to approximate timestamps of when the game was played.We can read in the chess graph using `read_edgelist`, and tell it to create the graph using a `nx.MultiDiGraph`. | chess = nx.read_edgelist('chess_graph.txt', data=[('outcome', int), ('timestamp', float)],
create_using=nx.MultiDiGraph())
chess.is_directed(), chess.is_multigraph()
chess
chess.edges(data=True) | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Looking at the degree of each node, we can see how many games each person played. A dictionary is returned where each key is the player, and each value is the number of games played. | games_played = chess.degree()
games_played | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Using list comprehension, we can find which player played the most games. | max_value = max(games_played.values())
max_key, = [i for i in games_played.keys() if games_played[i] == max_value]
print('player {}\n{} games'.format(max_key, max_value)) | player 461
280 games
| MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Let's use pandas to find out which players won the most games. First let's convert our graph to a DataFrame. | df = pd.DataFrame(chess.edges(data=True), columns=['white', 'black', 'outcome'])
df.head() | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Next we can use a lambda to pull out the outcome from the attributes dictionary. | df['outcome'] = df['outcome'].map(lambda x: x['outcome'])
df.head() | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
To count the number of times a player won as white, we find the rows where the outcome was '1', group by the white player, and sum.To count the number of times a player won as back, we find the rows where the outcome was '-1', group by the black player, sum, and multiply by -1.The we can add these together with a fill value of 0 for those players that only played as either black or white. | won_as_white = df[df['outcome']==1].groupby('white').sum()
won_as_black = -df[df['outcome']==-1].groupby('black').sum()
win_count = won_as_white.add(won_as_black, fill_value=0)
win_count.head() | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Using `nlargest` we find that player 330 won the most games at 109. | win_count.nlargest(5, 'outcome') | _____no_output_____ | MIT | C5-Applied Social Network Analysis with Python/Notebooks/Week1/Loading+Graphs+in+NetworkX.ipynb | nishamathi/coursera-data-science-python |
Counting Easter eggsOur experiment compares the classification approach and the regression approach. The selection is done with the `class_mode` option in Keras' ImageDataGenerator flow_from_directory. `categorical` is used for the one-hot encoding and `sparse` for integers as classes.Careful: While this is convention there, in other contexts, 'sparse' might mean a vector representation with more-than-one-hot entries, and rather the term 'binary' would be used for integers, generalizing a binary 0/1 problem to several possible classes.In the notebook, the class_mode is used as a switch for the different Net variants and evaluation scripting. | class_mode = "categorical" | _____no_output_____ | MIT | jupyter_notebooks/classification.ipynb | lightning485/osterai |
Imports and version numbers | import tensorflow as tf
from tensorflow.keras.preprocessing import image_dataset_from_directory
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from matplotlib import pyplot as plt
import os
import re
import numpy as np
from tensorflow.keras.preprocessing.image import load_img
# Python version: 3.8
print(tf.__version__)
# CUDA version:
!nvcc --version | nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Sun_Jul_28_19:12:52_Pacific_Daylight_Time_2019
Cuda compilation tools, release 10.1, V10.1.243
| MIT | jupyter_notebooks/classification.ipynb | lightning485/osterai |
Prepare data for the trainingIf you redo this notebook on your own, you'll need the images with 0..7 (without 5) eggs in the folders `./images/0` ... `./images/7` (`./images/5` must exist for the classification training, but be empty) | data_directory = "./images"
input_shape = [64,64,3] # 256
batch_size = 16
seed = 123 # for val split
train_datagen = ImageDataGenerator(
validation_split=0.2,
rescale=1.0/255.0
)
train_generator = train_datagen.flow_from_directory(
data_directory,
seed=seed,
target_size=(input_shape[0],input_shape[1]),
color_mode="rgb",
class_mode=class_mode,
batch_size=batch_size,
subset='training'
)
val_datagen = ImageDataGenerator(
validation_split=0.2,
rescale=1.0/255.0
)
val_generator = val_datagen.flow_from_directory(
data_directory,
seed=seed,
target_size=(input_shape[0],input_shape[1]),
color_mode="rgb",
class_mode=class_mode,
batch_size=batch_size,
subset='validation'
)
| Found 11200 images belonging to 8 classes.
Found 2800 images belonging to 8 classes.
| MIT | jupyter_notebooks/classification.ipynb | lightning485/osterai |
Prepare the model |
num_classes = 8 # because 0..7 eggs
if class_mode == "categorical":
num_output_dimensions = num_classes
if class_mode == "sparse":
num_output_dimensions = 1
model = tf.keras.Sequential()
model.add( tf.keras.layers.Conv2D(
filters = 4,
kernel_size = 5,
strides = 1,
padding = 'same',
activation = 'relu',
input_shape = input_shape
))
model.add( tf.keras.layers.MaxPooling2D(
pool_size = 2, strides = 2
))
model.add( tf.keras.layers.Conv2D(
filters = 8,
kernel_size = 5,
strides = 1,
padding = 'same',
activation = 'relu'
))
model.add( tf.keras.layers.MaxPooling2D(
pool_size = 2, strides = 2
))
model.add( tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(
units = 16, activation = 'relu'
))
if class_mode == "categorical":
last_activation = 'softmax'
if class_mode == "sparse":
last_activation = None
model.add(tf.keras.layers.Dense(
units = num_output_dimensions, activation = last_activation
))
if class_mode == "categorical":
loss = 'categorical_crossentropy'
if class_mode == "sparse":
loss = 'mse'
model.compile(
optimizer = 'adam',
loss = loss,
metrics = ['accuracy']
)
model.summary() | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 64, 64, 4) 304
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 32, 32, 4) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 32, 32, 8) 808
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 16, 16, 8) 0
_________________________________________________________________
flatten (Flatten) (None, 2048) 0
_________________________________________________________________
dense (Dense) (None, 16) 32784
_________________________________________________________________
dense_1 (Dense) (None, 8) 136
=================================================================
Total params: 34,032
Trainable params: 34,032
Non-trainable params: 0
_________________________________________________________________
| MIT | jupyter_notebooks/classification.ipynb | lightning485/osterai |
Train the model(on 0,1,2,3,4,6,7, but not 5 eggs) | epochs = 5
model.fit(
train_generator,
epochs=epochs,
validation_data=val_generator,
)
plt.figure()
if class_mode == "categorical":
plt.plot(model.history.history['accuracy'])
plt.plot(model.history.history['val_accuracy'])
plt.title('History')
plt.ylabel('Value')
plt.xlabel('Epoch')
plt.legend(['accuracy','val_accuracy'], loc='best')
plt.show()
if class_mode == "sparse":
plt.plot(model.history.history['loss'])
plt.plot(model.history.history['val_loss'])
plt.title('History')
plt.ylabel('Value')
plt.xlabel('Epoch')
plt.legend(['loss','val_loss'], loc='best')
plt.show() | _____no_output_____ | MIT | jupyter_notebooks/classification.ipynb | lightning485/osterai |
Illustrate performance on unknown and completely unknown input(5 eggs are completly unknown; all other numbers trained but at least the test image with 4 eggs was not used during training)If you are running this notebook on you own, you might have to adjust the filepaths, and you'll have to put the images with 5 eggs in the folder `./images_other/5` | filepath_known = './images_known_unknown/4/0.png'
filepath_unknown = './images_unknown/5/0.png'
# helper function to make the notebook more tidy
def make_prediction(filepath):
img = load_img(
filepath,
target_size=(input_shape[0],input_shape[1])
)
img = np.array(img)
img = img / 255.0
data = np.expand_dims(img, axis=0)
prediction = model.predict(data)[0]
predicted_class = np.argmax(prediction)
return img, prediction, predicted_class
if class_mode == "categorical":
img, prediction, predicted_class = make_prediction(filepath_known)
plt.figure()
plt.subplot(2,1,0+1)
plt.imshow(img)
plt.subplot(2,1,0+2)
plt.plot(prediction,'og')
plt.xlabel('Predicted "class"')
plt.ylabel('Score')
img, prediction, predicted_class = make_prediction(filepath_unknown)
plt.figure()
plt.subplot(2,1,0+1)
plt.imshow(img)
plt.subplot(2,1,0+2)
plt.plot(prediction,'og')
plt.xlabel('Predicted "class"')
plt.ylabel('Score')
if class_mode == "sparse":
img, prediction, predicted_class = make_prediction(filepath_known)
plt.figure()
plt.imshow(img)
_ = plt.title('Prediction: '+str(prediction[0])+' - '+str(round(prediction[0])))
img, prediction, predicted_class = make_prediction(filepath_unknown)
plt.figure()
plt.imshow(img)
_ = plt.title('Prediction: '+str(prediction[0])+' - '+str(round(prediction[0])))
data_test_directory = "./images_unknown"
test_datagen = ImageDataGenerator(
rescale=1.0/255.0
)
test_generator = test_datagen.flow_from_directory(
data_test_directory,
target_size=(input_shape[0],input_shape[1]),
color_mode="rgb",
class_mode=class_mode,
batch_size=1,
subset=None,
shuffle=False
)
all_predictions = model.predict(test_generator, verbose=1)
plt.figure()
if class_mode == 'categorical':
_ = plt.imshow(all_predictions, cmap='summer', aspect='auto', interpolation='none')
_ = plt.colorbar()
_ = plt.xlabel('Predicted class')
_ = plt.ylabel('Image number')
_ = plt.title('Score heatmap for true class 5')
if class_mode == 'sparse':
num_bins = 70
_ = plt.hist(all_predictions, num_bins, color='g')
_ = plt.xlabel('Regression value')
_ = plt.ylabel('Counts')
_ = plt.title('Histogram of output values for true number 5') | Found 2000 images belonging to 8 classes.
2000/2000 [==============================] - 5s 3ms/step
| MIT | jupyter_notebooks/classification.ipynb | lightning485/osterai |
Illustrate performance on completely known dataFor the sake of completeness, we repeat the last plots again for the known data used in the training phase. | data_test_directory = "./images"
test_datagen = ImageDataGenerator(
rescale=1.0/255.0
)
test_generator = test_datagen.flow_from_directory(
data_test_directory,
target_size=(input_shape[0],input_shape[1]),
color_mode="rgb",
class_mode=class_mode,
batch_size=1,
subset=None,
shuffle=False
)
test_labels = (test_generator.class_indices)
test_filenames = test_generator.filenames
all_predictions = model.predict(test_generator, verbose=1)
if class_mode == "categorical":
_ = plt.imshow(all_predictions, cmap='summer', aspect='auto', interpolation='none')
_ = plt.colorbar()
_ = plt.xlabel('Class')
_ = plt.ylabel('Image number')
_ = plt.title('Score heatmap')
if class_mode == "sparse":
plt.figure()
num_bins = 70
_ = plt.hist(all_predictions, num_bins, color='g')
_ = plt.xlabel('Regression value')
_ = plt.ylabel('Counts')
_ = plt.title('Histogram of output values') | Found 14000 images belonging to 8 classes.
14000/14000 [==============================] - 37s 3ms/step
| MIT | jupyter_notebooks/classification.ipynb | lightning485/osterai |
110. Balanced Binary Tree ContentGiven a binary tree, determine if it is height-balanced.For this problem, a height-balanced binary tree is defined as:a binary tree in which the left and right subtrees of every node differ in height by no more than 1. Example 1:Input: root = [3,9,20,null,null,15,7]Output: trueExample 2:Input: root = [1,2,2,3,3,null,null,4,4]Output: falseExample 3:Input: root = []Output: true Constraints: The number of nodes in the tree is in the range [0, 5000]. -104 <= Node.val <= 104 Difficulty: Easy, AC rate: 45.4% Question Tags:- Tree- Depth-First Search- Binary Tree Links: 🎁 [Question Detail](https://leetcode.com/problems/balanced-binary-tree/description/) | 🎉 [Question Solution](https://leetcode.com/problems/balanced-binary-tree/solution/) | 💬 [Question Discussion](https://leetcode.com/problems/balanced-binary-tree/discuss/?orderBy=most_votes) Hints: Sample Test Case[3,9,20,null,null,15,7] ---What's your idea?DFS一旦检测到左子树或者右子树已经不平衡了,则直接返回,不再检查另一棵子树否则,按照平衡树的定义,检查左右子树高度差--- | from typing import Tuple
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
balanced, _ = self.visitSubTree(root)
return balanced
def visitSubTree(self, sub_root: TreeNode) -> Tuple[bool, int]:
if not sub_root:
return [True, 0]
is_left_balanced, left_height = self.visitSubTree(sub_root.left)
if not is_left_balanced:
return [False, left_height + 1]
is_right_balanced, right_height = self.visitSubTree(sub_root.right)
if not is_right_balanced:
return [False, right_height + 1]
return [abs(left_height - right_height) <= 1, max(left_height, right_height)+1]
s = Solution()
n7 = TreeNode(7)
n15 = TreeNode(15)
n20 = TreeNode(20, n15, n7)
n9 = TreeNode(9)
n3 = TreeNode(3, n9, n20)
s.isBalanced(n3)
s.isBalanced(None)
n4l = TreeNode(4)
n4r = TreeNode(4)
n3l = TreeNode(3, n4l, n4r)
n3r = TreeNode(3)
n2l = TreeNode(2, n3l, n3r)
n2r = TreeNode(2)
n1 = TreeNode(1, n2l, n2r)
s.isBalanced(n1)
n4l = TreeNode(4)
n4r = TreeNode(4)
n3l = TreeNode(3, n4l, n4r)
n3r = TreeNode(3)
n3rr = TreeNode(3)
n2l = TreeNode(2, n3l, n3r)
n2r = TreeNode(2, n3rr)
n1 = TreeNode(1, n2l, n2r)
s.isBalanced(n1)
import sys, os; sys.path.append(os.path.abspath('..'))
from submitter import submit
submit(110) | _____no_output_____ | MIT | 101-150/110.balanced-binary-tree.ipynb | Sorosliu1029/LeetCode |
EmoDJ Music PlayerEmoDJ is a brand-new AI-powered offline music player desktop application that focuses on improving listeners' emotional wellness.This application is designed based on psychology theories. It is powered by machine learning to automatically identify music emotion of your songs.To start EmoDJ at first time, click Cell>Run AllTo restart EmoDJ after quit, click Kernel>Restart and Run AllSupported music file format: .wav.Sample music files in /musics folder are downloaded from Free Music Archive. Music Emotion Recognition EngineLoad trained models and predict arousal and valence value of the music | import os
import librosa
import sklearn
def preprocess_feature(file_name):
n_mfcc = 12
mfcc_all = []
#MFCC per time period (500ms)
x, sr = librosa.load(MUSIC_FOLDER + file_name)
for i in range(0, len(x), int(sr*500/1000)):
x_cont = x[i:i+int(sr*500/1000)]
mfccs = librosa.feature.mfcc(x_cont,sr=sr,n_mfcc=n_mfcc)
#append feature value for music interval shorter than 500ms
mfccs = np.hstack((mfccs, np.zeros((12,22 - mfccs.shape[1]))))
mfccs = mfccs.flatten()
mfcc_all.append(mfccs)
return np.vstack(mfcc_all)
def normalise(input_data, feature_matrix_mean, feature_matrix_std):
return (input_data - feature_matrix_mean) / feature_matrix_std
def emotion_predict(file_name):
#Load trained models
with open(MODEL_FOLDER + 'arousal_model.pkl', 'rb') as f:
arousal_model = pickle.load(f)
with open(MODEL_FOLDER + 'valence_model.pkl', 'rb') as f:
valence_model = pickle.load(f)
with open(MODEL_FOLDER + 'feature_matrix_mean.pkl', 'rb') as f:
feature_matrix_mean = pickle.load(f)
with open(MODEL_FOLDER + 'feature_matrix_std.pkl', 'rb') as f:
feature_matrix_std = pickle.load(f)
mfcc = preprocess_feature(file_name)
mfcc_norm = normalise(mfcc, feature_matrix_mean, feature_matrix_std)
#Predict arousal value per 5 second interval
music_aro = arousal_model.predict(mfcc_norm).flatten()
#Predict valence value per 5 second interval
music_val = valence_model.predict(mfcc_norm).flatten()
return music_aro, music_val
| _____no_output_____ | MIT | EmoDJ Music Player/EmoDJ_Music_Player_Code.ipynb | peggypytang/EmoDJ |
Music Emotion Retrieval PanelDisplay music by their valence and arousal value. Colour of marker represents colour association to average music emotion of that music piece.Listeners can see annotation (song name, valence value, arousal value) of particular music piece by hovering its marker.Listeners can retrieve and play the music piece by clicking on its marker.The music currently playing is shown in yellow colour, the music played is shown in grey colour. This would be reset if the listener select new music piece to play (reconstruct the playlist). | HAPPY_COLOUR = 'lawngreen'
SAD_COLOUR = 'darkblue'
TENSE_COLOUR = 'red'
CALM_COLOUR = 'darkcyan'
BASE_COLOUR = 'darkgrey'
PLAYING_COLOUR = 'gold'
FILE_FORMAT = '.wav'
#Start playing music when user pick the marker on scatter plot
def pick_music(event):
ind = event.ind
song_id = emotion_df.iloc[ind , :][ID_FIELD].values[0]
start_music(song_id)
#Show annotation when user hover the marker on scatter plot
#(song name, valence value, arousal value)
def update_annot(ind):
pos = scatter_panel.get_offsets()[ind["ind"][0]]
music_annot.xy = pos
(x,y) = pos
song_id = emotion_df[(emotion_df[VAL_FIELD]==x) & (emotion_df[ARO_FIELD]==y)][ID_FIELD].values[0]
music_annot.set_text(get_song_name(song_id) + \
'\nValence: '+ str(x.round(2)) + \
'\nArousal: '+ str(y.round(2)))
def hover_music(event):
vis = music_annot.get_visible()
if event.inaxes == ax_panel:
cont, ind = scatter_panel.contains(event)
if cont:
update_annot(ind)
music_annot.set_visible(True)
canvas_panel.draw_idle()
else:
if vis:
music_annot.set_visible(False)
canvas_panel.draw_idle()
#List marker colour for marks on scatter plot
#based on corresponding emotion of average arousal valence value of that music
def list_colour_panel(x_list, y_list):
colour_list = []
for x, y in zip(x_list,y_list):
if x >= 0 and y > 0:
colour_list.append(HAPPY_COLOUR)
elif x <= 0 and y < 0:
colour_list.append(SAD_COLOUR)
elif x < 0 and y >= 0:
colour_list.append(TENSE_COLOUR)
else:
colour_list.append(CALM_COLOUR)
return colour_list | _____no_output_____ | MIT | EmoDJ Music Player/EmoDJ_Music_Player_Code.ipynb | peggypytang/EmoDJ |
Music Visualisation EngineWhile playing the music, Fast Fourier Transform was performed on each 1024 frames to show amplitude (converted to dB) and frequency.Colour of line represents colour association to time vary music emotion. | #Initialise visualition
def init_vis():
line.set_ydata([0] * len(vis_x))
return line,
#Update the visualisation
#Line plot value based on real FFT (converted to dB)
#Line colour based on emotion of arousal valence value at that time period
def animate_vis(i):
global num_CHUNK
#Show visualisation when
#-music file is loaded
#-is playing (not paused)
#-the music file has not finished playing
if wf is not None and isplay and wf.getnframes()-CHUNK*num_CHUNK>0:
num_CHUNK += 1
data = wf.readframes(CHUNK)
audio_data = np.frombuffer(data, np.int16)
dfft = 10.*np.log10(abs(np.fft.rfft(audio_data)+1)) # +1 to avoid log0
line.set_xdata(np.arange(len(dfft))*10.)
line.set_ydata(dfft)
line.set_color(colour_vis.pop(0))
else:
line.set_xdata(vis_x)
line.set_ydata([0] * len(vis_x))
return line,
#List colour for marks on scatter plot
#Based on corresponding emotion of arousal valence value across time period
def list_colour_vis(song_id):
global colour_vis
colour_vis = []
valence_list = valence_df[valence_df[ID_FIELD]==song_id][VAL_FIELD].values[0]
arousal_list = arousal_df[arousal_df[ID_FIELD]==song_id][ARO_FIELD].values[0]
for x, y in zip(valence_list,arousal_list):
if x >= 0 and y > 0:
colour_vis.extend([HAPPY_COLOUR]*int(TIME_PERIOD*(RATE/CHUNK)))
elif x <= 0 and y < 0:
colour_vis.extend([SAD_COLOUR]*int(TIME_PERIOD*(RATE/CHUNK)))
elif x < 0 and y >= 0:
colour_vis.extend([TENSE_COLOUR]*int(TIME_PERIOD*(RATE/CHUNK)))
else:
colour_vis.extend([CALM_COLOUR]*int(TIME_PERIOD*(RATE/CHUNK)))
colour_vis = []
num_CHUNK = 0
TIME_PERIOD = 5 #5second | _____no_output_____ | MIT | EmoDJ Music Player/EmoDJ_Music_Player_Code.ipynb | peggypytang/EmoDJ |
Music Recommendation and Player EngineIn addition to standard functions (such as next, pause, resume), it provides recommended playlist based on similarity of music emotion with the music selection.It would play the next music piece in playlist automatically, starting from the most similar one, until it reaches the end of playlist. | from tkinter import messagebox
import pygame
def get_song_name(song_id):
return processed_music[processed_music[ID_FIELD]==song_id][NAME_FIELD].values[0]
def get_song_file_path(song_id):
return MUSIC_FOLDER + get_song_name(song_id)
#Construct playlist based on similarity with song selected
#Euclidean distance by valence and arousal value (square root is ignored)
def construct_playlist(song_id):
global playlist
playlist = []
playlist_dict = {}
curr_val = emotion_df[emotion_df[ID_FIELD]==song_id][VAL_FIELD].values[0]
curr_aro = emotion_df[emotion_df[ID_FIELD]==song_id][ARO_FIELD].values[0]
song_list = list(emotion_df[ID_FIELD].values)
song_list.remove(song_id)
for compare_song_id in song_list:
compare_val = emotion_df[emotion_df[ID_FIELD]==compare_song_id][VAL_FIELD].values[0]
compare_aro = emotion_df[emotion_df[ID_FIELD]==compare_song_id][ARO_FIELD].values[0]
playlist_dict[compare_song_id] = (curr_val-compare_val)**2 + (curr_aro-compare_aro)**2
playlist_dict = sorted(playlist_dict.items(), key = lambda kv:(kv[1], kv[0]))
playlist = [i[0] for i in playlist_dict]
#Update setting to play song
def update_music_setting(song_id):
global wf, num_CHUNK
mixer.music.load(get_song_file_path(song_id))
mixer.music.play()
wf = wave.open(get_song_file_path(song_id), 'rb')
songLabel.set(get_song_name(song_id))
list_colour_vis(song_id)
ax_panel.scatter(emotion_df[VAL_FIELD],emotion_df[ARO_FIELD], s=15,c=scatter_colour,picker=False)
#Played songs are displayed as BASE_COLOUR
ax_panel.scatter(emotion_df[emotion_df[ID_FIELD].isin(played_songs)][VAL_FIELD], \
emotion_df[emotion_df[ID_FIELD].isin(played_songs)][ARO_FIELD], s=16,c=BASE_COLOUR,picker=False)
#Playing songs are displayed as PLAYING_COLOUR
ax_panel.scatter(emotion_df[emotion_df[ID_FIELD]==song_id][VAL_FIELD], \
emotion_df[emotion_df[ID_FIELD]==song_id][ARO_FIELD], s=17,c=PLAYING_COLOUR,picker=False)
canvas_panel.draw()
played_songs.append(song_id)
num_CHUNK = 0
#User selected in panel to start song and construct new playlist
def start_music(song_id):
global isplay, played_songs
mixer.music.stop()
#Construct playlist
construct_playlist(song_id)
played_songs = []
#Load and play song selected
isplay = True
update_music_setting(song_id)
#User clicked next button to play next song in playlist
def next_music():
global wf, isplay
mixer.music.stop()
if playlist:
isplay = True
song_id = playlist.pop(0)
update_music_setting(song_id)
else:
wf = None
isplay = False
messagebox.showinfo('EmoDJ', 'Reach the end of playlist.')
#User clicked pause/resume button
def pause_music():
global isplay
if wf is None and isplay:
messagebox.showinfo('EmoDJ', 'Please select music in Emotion Panel.')
elif wf:
if isplay:
isplay = False
mixer.music.pause()
else:
isplay = True
mixer.music.unpause()
#Auto play next music in playlist
def auto_next_music():
global isplay, wf
#Check if the song completes
if isplay:
if wf is not None:
if wf.getnframes()-CHUNK*num_CHUNK<=0:
#End playing if playlist exhaust
if playlist == [] :
isplay = False
wf = None
songLabel.set('')
messagebox.showinfo('EmoDJ', 'Reach the end of playlist.')
#Play next song in playlist
elif isplay:
wf = None
song_id = playlist.pop(0)
update_music_setting(song_id)
window.after(2000, auto_next_music)
wf = None
played_songs = []
playlist = []
isnext = False
isplay = False | pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
| MIT | EmoDJ Music Player/EmoDJ_Music_Player_Code.ipynb | peggypytang/EmoDJ |
Create IndexCreate below search index files- Average emotion of musics - Time varying valence values of musics - Time varying arousal values of musics - Processed music (Music pieces with music emotion recognised) | import os
import pickle
import time, sys
from IPython.display import clear_output
def update_progress(processed, total):
bar_length = 20
progress = processed/total
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
if progress < 0:
progress = 0
if progress >= 1:
progress = 1
block = int(round(bar_length * progress))
clear_output(wait = True)
text = "Music Emotion Recognition Progress: [{0}] {1} / {2} songs processed".format( "#" * block + "-" * (bar_length - block), processed, total )
print(text)
def create_index(emotion_df, arousal_df, valence_df, processed_music, music_files):
#Remove music from processed music if it is not in the folder anymore
musics_remove = set(processed_music[NAME_FIELD].values) - set(music_files)
for music_name in musics_remove:
song_id = processed_music[processed_music[NAME_FIELD]==music_name][ID_FIELD].values[0]
processed_music = processed_music[processed_music.song_id != song_id]
emotion_df = emotion_df[emotion_df.song_id != song_id]
arousal_df = arousal_df[arousal_df.song_id != song_id]
valence_df = valence_df[valence_df.song_id != song_id]
#Process unprocessed musics in folder
#Only process .wav files
musics_new = set(music_files) - set(processed_music[NAME_FIELD].values)
num_proceeded = 0
for music_name in musics_new:
update_progress(num_proceeded, len(musics_new))
if music_name.find(FILE_FORMAT)>-1:
music_aro, music_val = emotion_predict(music_name)
new_song_id = int(np.nanmax([processed_music[ID_FIELD].max(),0])) +1
processed_music = processed_music.append({ID_FIELD:new_song_id,NAME_FIELD:music_name}, ignore_index=True)
arousal_df = arousal_df.append({ID_FIELD:new_song_id,ARO_FIELD:music_aro}, ignore_index=True)
valence_df = valence_df.append({ID_FIELD:new_song_id,VAL_FIELD:music_val}, ignore_index=True)
emotion_df = emotion_df.append({ID_FIELD:new_song_id,VAL_FIELD:music_val.mean(),ARO_FIELD:music_aro.mean()}, ignore_index=True)
num_proceeded += 1
#Save index
with open(INDEX_FOLDER+'average_emotion.pkl', 'wb') as f:
pickle.dump(emotion_df,f)
with open(INDEX_FOLDER+'arousal.pkl', 'wb') as f:
pickle.dump(arousal_df,f)
with open(INDEX_FOLDER+'valence.pkl', 'wb') as f:
pickle.dump(valence_df,f)
with open(INDEX_FOLDER+'processed_music.pkl', 'wb') as f:
pickle.dump(processed_music,f) | _____no_output_____ | MIT | EmoDJ Music Player/EmoDJ_Music_Player_Code.ipynb | peggypytang/EmoDJ |
Load IndexLoad indexes if any. Otherwise, create index folder and empty indexes.Folder structure:- musics/ (Music files)- index/ (Index files)- model/ (Music emotion recognition model) | import pandas as pd
import numpy as np
MUSIC_FOLDER = 'musics/'
INDEX_FOLDER = 'index/'
MODEL_FOLDER = 'model/'
VAL_FIELD = 'valence'
ARO_FIELD = 'arousal'
NAME_FIELD = 'song_name'
ID_FIELD = 'song_id'
def load_index():
#For first time using this program
#Create initial index
if not os.path.exists(INDEX_FOLDER):
os.makedirs(INDEX_FOLDER)
#Average emotion of the music
try:
with open(INDEX_FOLDER+'average_emotion.pkl', 'rb') as f:
emotion_df = pickle.load(f)
except:
emotion_df = pd.DataFrame(columns=[ID_FIELD, VAL_FIELD, ARO_FIELD])
#Dynamic arousal values of the music
try:
with open(INDEX_FOLDER+'arousal.pkl', 'rb') as f:
arousal_df = pickle.load(f)
except:
arousal_df = pd.DataFrame(columns=[ID_FIELD, ARO_FIELD])
#Dynamic valence values of the music
try:
with open(INDEX_FOLDER+'valence.pkl','rb') as f:
valence_df = pickle.load(f)
except:
valence_df = pd.DataFrame(columns=[ID_FIELD, VAL_FIELD])
#Processed music
try:
with open(INDEX_FOLDER+'processed_music.pkl','rb') as f:
processed_music = pickle.load(f)
except:
processed_music = pd.DataFrame(columns=[ID_FIELD, NAME_FIELD])
emotion_df = emotion_df.astype({ID_FIELD: int})
arousal_df = arousal_df.astype({ID_FIELD: int})
valence_df = valence_df.astype({ID_FIELD: int})
processed_music = processed_music.astype({ID_FIELD: int})
music_files = os.listdir(MUSIC_FOLDER)
if '.DS_Store' in music_files:
music_files.remove('.DS_Store')
return emotion_df, arousal_df, valence_df, processed_music, music_files | _____no_output_____ | MIT | EmoDJ Music Player/EmoDJ_Music_Player_Code.ipynb | peggypytang/EmoDJ |
GUI EngineGraphical user interface to interact with listener.Before launching GUI, it will check if there are unprocessed music. If so, process to get music emotion values of the unprocessed music and re-create of index. | #Due to system specification difference
#Parameter to ensure synchronisation of visualisation and sound
SYNC = 3.5
import tkinter as tk
import wave
from pygame import mixer
import matplotlib.animation as animation
from matplotlib import style
style.use('ggplot')
import matplotlib.pyplot as plt
import numpy as np
import math
import time
from PIL import ImageTk, Image
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.animation import FuncAnimation
def quit_window():
mixer.music.stop()
window.withdraw()
window.update()
window.destroy()
def cmdNext(): next_music()
def cmdPause(): pause_music()
def cmdQuit(): quit_window()
emotion_df, arousal_df, valence_df, processed_music, music_files = load_index()
#Check if there are unprocessed music
unprocessed_music = set(music_files).symmetric_difference(set(processed_music[NAME_FIELD].values))
if unprocessed_music:
print('Processing musics...')
create_index(emotion_df, arousal_df, valence_df, processed_music, music_files)
emotion_df, arousal_df, valence_df, processed_music, _ = load_index()
window = tk.Tk()
window.title("EmoDJ")
window.config(background='white')
window.geometry('1300x700')
#EmoDJ logo
logo_image = ImageTk.PhotoImage(Image.open(MODEL_FOLDER + 'logo.jpeg').resize((150, 80), Image.ANTIALIAS))
tk.Label(window, image = logo_image,background='white').grid(row = 0,column=0,sticky='W')
#Song name
songLabel = tk.StringVar()
songLabel.set('')
tk.Label(window, textvariable=songLabel,background='white').grid(row = 1, column=0)
#music visualisation
fig_vis, ax_vis = plt.subplots(figsize=(8,5))
RATE = 44100
CHUNK = 1024
max_x = CHUNK+1
max_y = 100
vis_x = np.arange(0, max_x)
ax_vis.set_xlim(0, max_x)
ax_vis.set_ylim(0, max_y)
ax_vis.set_axis_off()
line, = ax_vis.plot(vis_x, [0] * len(vis_x))
canvas_vis = FigureCanvasTkAgg(fig_vis, master=window)
canvas_vis.get_tk_widget().grid(row=2,column=0,rowspan=2,sticky='W'+'E'+'N'+'S')
ani = animation.FuncAnimation(fig_vis, animate_vis, init_func=init_vis, interval=int(math.ceil(1000/(RATE/CHUNK)))+SYNC, blit=True)
#music player
tk.Button(window, text="Quit", command=cmdQuit).grid(row = 0, column=2,sticky='E'+'N')
mixer.pre_init(frequency=RATE, size=-16, channels=2)
mixer.init()
tk.Button(window, text="Next", command=cmdNext).grid(row = 1, column=1,sticky='W'+'E'+'N'+'S')
tk.Button(window, text="Resume/Pause", command=cmdPause).grid(row = 1, column=2,sticky='W'+'E'+'N'+'S')
#music emotion panel
fig_panel, ax_panel = plt.subplots(figsize=(5,5))
scatter_colour = list_colour_panel(emotion_df[VAL_FIELD], emotion_df[ARO_FIELD])
scatter_panel = ax_panel.scatter(emotion_df[VAL_FIELD],emotion_df[ARO_FIELD], s=15,c=scatter_colour, picker=True)
ax_panel.axvline(x=0,c=BASE_COLOUR)
ax_panel.axhline(y=0,c=BASE_COLOUR)
ax_panel.set_xlim(-1, 1)
ax_panel.set_ylim(-1, 1)
ax_panel.text(-1,0.05,s='-1 Valence',fontsize=9,color=BASE_COLOUR)
ax_panel.text(0.75,0.05,s='+1 Valence',fontsize=9,color=BASE_COLOUR)
ax_panel.text(0.05,-1,s='-1 Arousal',fontsize=9,color=BASE_COLOUR)
ax_panel.text(0.05,1,s='+1 Arousal',fontsize=9,color=BASE_COLOUR)
ax_panel.set_axis_off()
music_annot = ax_panel.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",bbox=dict(boxstyle="round", fc="w"))
music_annot.set_visible(False)
canvas_panel = FigureCanvasTkAgg(fig_panel, master=window)
canvas_panel.get_tk_widget().grid(row=2,column=1,columnspan=2,sticky='W'+'E'+'N'+'S')
canvas_panel.mpl_connect('pick_event', pick_music)
canvas_panel.mpl_connect("motion_notify_event", hover_music)
tk.Label(window, text="Start playing music by clicking on the marker!",background='white').grid(row = 3,column=1,columnspan=2,sticky='W'+'E'+'N'+'S')
window.after(0, auto_next_music)
window.mainloop()
print('Enjoy music! See you next time.') | Enjoy music! See you next time.
| MIT | EmoDJ Music Player/EmoDJ_Music_Player_Code.ipynb | peggypytang/EmoDJ |
XGBoost-Ray with ModinThis notebook includes an example workflow using[XGBoost-Ray](https://docs.ray.io/en/latest/xgboost-ray.html) and[Modin](https://modin.readthedocs.io/en/latest/) for distributed modeltraining and prediction. Cluster SetupFirst, we'll set up our Ray Cluster. The provided ``modin_xgboost.yaml``cluster config can be used to set up an AWS cluster with 64 CPUs.The following steps assume you are in a directory with both``modin_xgboost.yaml`` and this file saved as ``modin_xgboost.ipynb``.**Step 1:** Bring up the Ray cluster.```bashpip install ray boto3ray up modin_xgboost.yaml```**Step 2:** Move ``modin_xgboost.ipynb`` to the cluster and start Jupyter.```bashray rsync_up modin_xgboost.yaml "./modin_xgboost.ipynb" \ "~/modin_xgboost.ipynb"ray exec modin_xgboost.yaml --port-forward=9999 "jupyter notebook \ --port=9999"```You can then access this notebook at the URL that is output:``http://localhost:9999/?token=`` Python SetupFirst, we'll import all the libraries we'll be using. This step also helps usverify that the environment is configured correctly. If any of the importsare missing, an exception will be raised. | import argparse
import time
import modin.pandas as pd
from modin.experimental.sklearn.model_selection import train_test_split
from xgboost_ray import RayDMatrix, RayParams, train, predict
import ray | _____no_output_____ | Apache-2.0 | doc/source/ray-core/examples/modin_xgboost/modin_xgboost.ipynb | richardsliu/ray |
Next, let's parse some arguments. This will be used for executing the ``.py``file, but not for the ``.ipynb``. If you are using the interactive notebook,you can directly override the arguments manually. | parser = argparse.ArgumentParser()
parser.add_argument(
"--address", type=str, default="auto", help="The address to use for Ray."
)
parser.add_argument(
"--smoke-test",
action="store_true",
help="Read a smaller dataset for quick testing purposes.",
)
parser.add_argument(
"--num-actors", type=int, default=4, help="Sets number of actors for training."
)
parser.add_argument(
"--cpus-per-actor",
type=int,
default=8,
help="The number of CPUs per actor for training.",
)
parser.add_argument(
"--num-actors-inference",
type=int,
default=16,
help="Sets number of actors for inference.",
)
parser.add_argument(
"--cpus-per-actor-inference",
type=int,
default=2,
help="The number of CPUs per actor for inference.",
)
# Ignore -f from ipykernel_launcher
args, _ = parser.parse_known_args() | _____no_output_____ | Apache-2.0 | doc/source/ray-core/examples/modin_xgboost/modin_xgboost.ipynb | richardsliu/ray |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.