markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Build the Neural Network You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below: - model_inputs - process_decoding_input - encoding_layer - decoding_layer_train - decoding_layer_infer - decoding_layer - seq2seq_model Input Implement the model_inputs() f...
def model_inputs(): """ Create TF Placeholders for input, targets, and learning rate. :return: Tuple (input, targets, learning rate, keep probability) """ inputs = tf.placeholder(tf.int32, [None, None], name = 'input') targets = tf.placeholder(tf.int32, [None, None], name = 'targets') l...
Udacity-Deep-Learning-Foundation-Nanodegree/Project-4/dlnd_language_translation.ipynb
joelowj/Udacity-Projects
apache-2.0
Process Decoding Input Implement process_decoding_input using TensorFlow to remove the last word id from each batch in target_data and concat the GO ID to the beginning of each batch.
def process_decoding_input(target_data, target_vocab_to_int, batch_size): """ Preprocess target data for dencoding :param target_data: Target Placehoder :param target_vocab_to_int: Dictionary to go from the target words to an id :param batch_size: Batch Size :return: Preprocessed target data ...
Udacity-Deep-Learning-Foundation-Nanodegree/Project-4/dlnd_language_translation.ipynb
joelowj/Udacity-Projects
apache-2.0
Encoding Implement encoding_layer() to create a Encoder RNN layer using tf.nn.dynamic_rnn().
def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob): """ Create encoding layer :param rnn_inputs: Inputs for the RNN :param rnn_size: RNN Size :param num_layers: Number of layers :param keep_prob: Dropout keep probability :return: RNN state """ encoding_cell = tf.con...
Udacity-Deep-Learning-Foundation-Nanodegree/Project-4/dlnd_language_translation.ipynb
joelowj/Udacity-Projects
apache-2.0
Decoding - Training Create training logits using tf.contrib.seq2seq.simple_decoder_fn_train() and tf.contrib.seq2seq.dynamic_rnn_decoder(). Apply the output_fn to the tf.contrib.seq2seq.dynamic_rnn_decoder() outputs.
def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope, output_fn, keep_prob): """ Create a decoding layer for training :param encoder_state: Encoder State :param dec_cell: Decoder RNN Cell :param dec_embed_input: Decoder embedded ...
Udacity-Deep-Learning-Foundation-Nanodegree/Project-4/dlnd_language_translation.ipynb
joelowj/Udacity-Projects
apache-2.0
Decoding - Inference Create inference logits using tf.contrib.seq2seq.simple_decoder_fn_inference() and tf.contrib.seq2seq.dynamic_rnn_decoder().
def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, maximum_length, vocab_size, decoding_scope, output_fn, keep_prob): """ Create a decoding layer for inference :param encoder_state: Encoder state :param dec_cell: Decoder R...
Udacity-Deep-Learning-Foundation-Nanodegree/Project-4/dlnd_language_translation.ipynb
joelowj/Udacity-Projects
apache-2.0
Build the Decoding Layer Implement decoding_layer() to create a Decoder RNN layer. Create RNN cell for decoding using rnn_size and num_layers. Create the output fuction using lambda to transform it's input, logits, to class logits. Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_le...
def decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size, sequence_length, rnn_size, num_layers, target_vocab_to_int, keep_prob): """ Create decoding layer :param dec_embed_input: Decoder embedded input :param dec_embeddings: Decoder embeddings :param encoder_...
Udacity-Deep-Learning-Foundation-Nanodegree/Project-4/dlnd_language_translation.ipynb
joelowj/Udacity-Projects
apache-2.0
Build the Neural Network Apply the functions you implemented above to: Apply embedding to the input data for the encoder. Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob). Process target data using your process_decoding_input(target_data, target_vocab_to_int, batch_size) function...
def seq2seq_model(input_data, target_data, keep_prob, batch_size, sequence_length, source_vocab_size, target_vocab_size, enc_embedding_size, dec_embedding_size, rnn_size, num_layers, target_vocab_to_int): """ Build the Sequence-to-Sequence part of the neural network :param input_data: Inpu...
Udacity-Deep-Learning-Foundation-Nanodegree/Project-4/dlnd_language_translation.ipynb
joelowj/Udacity-Projects
apache-2.0
Neural Network Training Hyperparameters Tune the following parameters: Set epochs to the number of epochs. Set batch_size to the batch size. Set rnn_size to the size of the RNNs. Set num_layers to the number of layers. Set encoding_embedding_size to the size of the embedding for the encoder. Set decoding_embedding_siz...
# Number of Epochs epochs = 4 # Batch Size batch_size = 512 # RNN Size rnn_size = 100 # Number of Layers num_layers = 2 # Embedding Size encoding_embedding_size = 50 decoding_embedding_size = 50 # Learning Rate learning_rate = 0.01 # Dropout Keep Probability keep_probability = 0.9
Udacity-Deep-Learning-Foundation-Nanodegree/Project-4/dlnd_language_translation.ipynb
joelowj/Udacity-Projects
apache-2.0
Sentence to Sequence To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences. Convert the sentence to lowercase Convert words into ids using vocab_to_int Convert words not in the vocabulary, to the <UNK> word id.
def sentence_to_seq(sentence, vocab_to_int): """ Convert a sentence to a sequence of ids :param sentence: String :param vocab_to_int: Dictionary to go from the words to an id :return: List of word ids """ sentence = sentence.lower() word_list = [vocab_to_int.get(word, vocab_to_int['...
Udacity-Deep-Learning-Foundation-Nanodegree/Project-4/dlnd_language_translation.ipynb
joelowj/Udacity-Projects
apache-2.0
Load the libstempo Python extension. It requires a source installation of tempo2, as well as current Python and compiler, and the numpy and Cython packages. (Both Python 2.7 and 3.4 are supported; this means that in Python 2.7 all returned strings will be unicode strings, while in Python 3 all function arguments should...
from libstempo.libstempo import * import libstempo libstempo.__path__ import libstempo as T T.data = T.__path__[0] + '/data/' # example files print("Python version :",sys.version.split()[0]) print("libstempo version:",T.__version__) print("Tempo2 version :",T.libstempo.tempo2version())
demo/libstempo-demo.ipynb
vallis/libstempo
mit
We load a single-pulsar object. Doing this will automatically run the tempo2 fit routine once.
psr = T.tempopulsar( parfile=T.data + "/J1909-3744_NANOGrav_dfg+12.par", timfile=T.data + "/J1909-3744_NANOGrav_dfg+12.tim" )
demo/libstempo-demo.ipynb
vallis/libstempo
mit
Let's start simple: what is the name of this pulsar? (You can change it, by the way.)
psr.name
demo/libstempo-demo.ipynb
vallis/libstempo
mit
Next, let's look at observations: there are psr.nobs of them; we can get numpy arrays of the site TOAs [in MJDs] with psr.stoas, of the TOA measurement errors [in microseconds] with psr.toaerrs, and of the measurement frequencies with psr.freqs. These arrays are views of the tempo2 data, so you can write to them (but y...
psr.nobs psr.stoas psr.toaerrs.min() psr.toaerrs psr.freqs
demo/libstempo-demo.ipynb
vallis/libstempo
mit
By contrast, barycentric TOAs and frequencies are computed on the basis of current pulsar parameters, so you get them by calling psr methods (with parentheses), and you get a copy of the current values. Writing to it has no effect on the tempo2 data.
psr.toas() psr.ssbfreqs()
demo/libstempo-demo.ipynb
vallis/libstempo
mit
Residuals (in seconds) are returned by residuals(). The method takes a few options... I'll let its docstring help describe them. libstempo is fully documented in this way (try help(T.tempopulsar)).
help(psr.residuals) psr.residuals().min() psr.residuals()
demo/libstempo-demo.ipynb
vallis/libstempo
mit
We can plot TOAs vs. residuals, but we should first sort the arrays; otherwise the array follow the order in the tim file, which may not be chronological.
# get sorted array of indices i = N.argsort(psr.toas()) # use numpy fancy indexing to order residuals P.errorbar(psr.toas()[i],psr.residuals()[i],yerr=1e-6*psr.toaerrs[i],fmt='.',alpha=0.2);
demo/libstempo-demo.ipynb
vallis/libstempo
mit
We can also see what flags have been set on the observations, and what their values are. The latter returns a numpy vector of strings. Flags are not currently writable.
psr.flags() psr.flagvals('chanid')
demo/libstempo-demo.ipynb
vallis/libstempo
mit
In fact, there's a commodity routine in libstempo.plot to plot residuals, taking flags into account.
import libstempo.plot as LP LP.plotres(psr,group='pta',alpha=0.2)
demo/libstempo-demo.ipynb
vallis/libstempo
mit
Timing-model parameters can be accessed by using psr as a Python dictionary. Each parameter is a special object with properties val, err (as well as fit, which is true is the parameter is currently being fitted, and set, which is true if the parameter was assigned a value).
psr['RAJ'].val, psr['RAJ'].err, psr['RAJ'].fit, psr['RAJ'].set
demo/libstempo-demo.ipynb
vallis/libstempo
mit
The names of all fitted parameters, of all set parameters, and of all parameters are returned by psr.pars(which='fit'). We show only the first few.
fitpars = psr.pars() # defaults to fitted parameters setpars = psr.pars(which='set') allpars = psr.pars(which='all') print(len(fitpars),len(setpars),len(allpars)) print(fitpars[:10])
demo/libstempo-demo.ipynb
vallis/libstempo
mit
The number of fitting parameters is psr.ndim.
psr.ndim
demo/libstempo-demo.ipynb
vallis/libstempo
mit
Changing the parameter values results in different residuals.
# look +/- 3 sigmas around the current value x0, dx = psr['RAJ'].val, psr['RAJ'].err xs = x0 + dx * N.linspace(-3,3,20) res = [] for x in xs: psr['RAJ'].val = x res.append(psr.rms()/1e-6) psr['RAJ'].val = x0 # restore the original value P.plot(xs,res)
demo/libstempo-demo.ipynb
vallis/libstempo
mit
We can also call a least-squares fitting routine, which will fit around the current parameter values, replacing them with their new best values. Individual parameters can be included or excluded in the fitting by setting their 'fit' field. (Note: as of version 2.3.0, libstempo provides its own fit, although it does cal...
psr['DM'].fit psr['DM'].fit = True print(psr['DM'].val) ret = psr.fit() print(psr['DM'].val,psr['DM'].err)
demo/libstempo-demo.ipynb
vallis/libstempo
mit
The fit returns a tuple consisting of best-fit vector, standard errors, covariance matrix, and linearized chisq. Note that these vectors and matrix are (ndim+1)- or (ndim+1)x(ndim+1)-dimensional, with the first row/column corresponding to a constant phase offset referenced to the first TOA (even if that point is not us...
fitvals = psr.vals() print(fitvals) psr.vals(which=['RAJ','DECJ','PMRA'])
demo/libstempo-demo.ipynb
vallis/libstempo
mit
To set parameter values in bulk, you give a first argument to vals. Or call it with a dictionary.
psr.vals([5.1,-0.6],which=['RAJ','DECJ','PMRA']) psr.vals({'PMRA': -9.5}) print(psr.vals(which=['RAJ','DECJ','PMRA'])) # restore original values psr.vals(fitvals)
demo/libstempo-demo.ipynb
vallis/libstempo
mit
Be careful about loss of precision; tempopar.val is a numpy longdouble, so you should be careful about assigning it a regular Python double. By contrast, doing arithmetics with numpy longdoubles will preserve their nature and precision. You can access errors in a similar way with psr.errs(...). It's also possible to ob...
d = psr.designmatrix()
demo/libstempo-demo.ipynb
vallis/libstempo
mit
These, for instance, are the derivatives with respect to RAJ and DECJ, evaluated at the TOAs.
# we need the sorted-index array compute above P.plot(psr.toas()[i]/365.25,d[i,1],'-x'); P.plot(psr.toas()[i]/365.25,d[i,2],'-x')
demo/libstempo-demo.ipynb
vallis/libstempo
mit
It's easy to save the current timing-model to a new par file. Omitting the argument will overwrite the original parfile.
psr.savepar('./foo.par') !head foo.par
demo/libstempo-demo.ipynb
vallis/libstempo
mit
Same for writing tim files.
psr.savetim('./foo.tim') !head foo.tim
demo/libstempo-demo.ipynb
vallis/libstempo
mit
With libstempo, it's easy to replicate some of the "toasim" plugin functionality. By subtracting the residuals from the site TOAs (psr.stoas, vs. the barycentered psr.toas) and refitting, we can create a "perfect" timing solution. (Note that 1 ns is roughly tempo2's claimed accuracy.)
print(math.sqrt(N.mean(psr.residuals()**2)) / 1e-6) psr.stoas[:] -= psr.residuals() / 86400.0 ret = psr.fit(iters = 4) print(math.sqrt(N.mean(psr.residuals()**2)) / 1e-6)
demo/libstempo-demo.ipynb
vallis/libstempo
mit
Then we can add, e.g., homoskedastic white measurement noise at 100 ns (remember the tempo units: days for TOAs, us for errors, s for residuals).
psr.stoas[:] += 0.1e-6 * N.random.randn(psr.nobs) / 86400.0 psr.toaerrs[:] = 0.1 ret = psr.fit() i = N.argsort(psr.toas()) P.errorbar(psr.toas()[i],psr.residuals()[i],yerr=1e-6*psr.toaerrs[i],fmt='.')
demo/libstempo-demo.ipynb
vallis/libstempo
mit
Reading and writing raw files In this example, we read a raw file. Plot a segment of MEG data restricted to MEG channels. And save these data in a new raw file.
# Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() fname = data_path + '/MEG/sample/sample_audvis_raw.fif' raw = mne.io.read_raw_fif(fname) # Set up pick list: MEG + STI 014 - b...
0.12/_downloads/plot_read_and_write_raw_data.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Show MEG data
raw.plot()
0.12/_downloads/plot_read_and_write_raw_data.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
The aim of our visualization is to illustrate the total number of posts by each community member, and the flows of posts between pairs of friends.
import platform, plotly import numpy as np from numpy import pi print(f'Python version: {platform.python_version()}') print(f'Plotly version: {plotly.__version__}')
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
Define the array of data:
matrix = np.array([[16, 3, 28, 0, 18], [18, 0, 12, 5, 29], [ 9, 11, 17, 27, 0], [19, 0, 31, 11, 12], [23, 17, 10, 0, 34]], dtype=int) def check_data(data_matrix): L, M = data_matrix.shape if L != M: raise ValueError('D...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
A chord diagram encodes information in two graphical objects: - ideograms, represented by distinctly colored arcs of circles; - ribbons, that are planar shapes bounded by two quadratic Bezier curves and two arcs of circle, that can degenerate to a point; Ideograms Summing up the entries on each matrix row, one ge...
from IPython.display import IFrame IFrame('https://plot.ly/~empet/12234/', width=377, height=420)
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
Now we are defining functions that process data in order to get the ideogram ends. As we pointed out, the unit circle is oriented counter-clockwise. In order to get an arc of circle of end angular coordinates $\theta_0<\theta_1$, we define the function, moduloAB, that resolves the case when an arc contains the poi...
def moduloAB(x, a, b): #maps a real number onto the unit circle identified with #the interval [a,b), b-a=2*PI if a>= b: raise ValueError('Incorrect interval ends') y = (x-a) % (b-a) return y+b if y < 0 else y+a def test_2PI(x): return 0 <= x < 2*pi
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
Compute the row sums and the lengths of corresponding ideograms:
row_sum = [matrix[k,:].sum() for k in range(L)] #set the gap between two consecutive ideograms gap = 2*pi*0.005 ideogram_length = 2*pi * np.asarray(row_sum) / sum(row_sum) - gap*np.ones(L)
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
The next function returns the list of end angular coordinates for each ideogram arc:
def get_ideogram_ends(ideogram_len, gap): ideo_ends = [] left = 0 for k in range(len(ideogram_len)): right = left + ideogram_len[k] ideo_ends.append([left, right]) left = right + gap return ideo_ends ideo_ends = get_ideogram_ends(ideogram_length, gap)
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
The function make_ideogram_arc returns equally spaced points on an ideogram arc, expressed as complex numbers in polar form:
def make_ideogram_arc(R, phi, a=50): # R is the circle radius # phi is the list of angle coordinates of an arc ends # a is a parameter that controls the number of points to be evaluated on an arc if not test_2PI(phi[0]) or not test_2PI(phi[1]): phi = [moduloAB(t, 0, 2*pi) for t in phi] leng...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
The real and imaginary parts of these complex numbers will be used to define the ideogram as a Plotly shape bounded by a SVG path.
make_ideogram_arc(1.3, [11*pi/6, pi/17])
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
Set ideograms labels and colors:
labels=['Emma', 'Isabella', 'Ava', 'Olivia', 'Sophia'] ideo_colors=['rgba(244, 109, 67, 0.75)', 'rgba(253, 174, 97, 0.75)', 'rgba(254, 224, 139, 0.75)', 'rgba(217, 239, 139, 0.75)', 'rgba(166, 217, 106, 0.75)']#brewer colors with alpha set on 0.75
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
Ribbons in a chord diagram While ideograms illustrate how many comments posted each member of the Facebook community, ribbons give a comparative information on the flows of comments from one friend to another. To illustrate this flow we map data onto the unit circle. More precisely, for each matrix row, $k$, the appli...
def map_data(data_matrix, row_value, ideogram_length): mapped = np.zeros(data_matrix.shape) for j in range(L): mapped[:, j] = ideogram_length * data_matrix[:,j] / row_value return mapped mapped_data = map_data(matrix, row_sum, ideogram_length) mapped_data
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
To each pair of values (mapped_data[k][j], mapped_data[j][k]), $k<=j$, one associates a ribbon, that is a curvilinear filled rectangle (that can be degenerate), having as opposite sides two subarcs of the $k^{th}$ ideogram, respectively $j^{th}$ ideogram, and two arcs of quadratic B&eacute;zier curves. Here we illust...
IFrame('https://plot.ly/~empet/12519/', width=420, height=420)
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
For a better looking chord diagram, Circos documentation recommends to sort increasingly each row of the mapped_data. The array idx_sort, defined below, has on each row the indices that sort the corresponding row in mapped_data:
idx_sort = np.argsort(mapped_data, axis=1) idx_sort
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
In the following we call ribbon ends, the lists l=[l[0], l[1]], r=[r[0], r[1]] having as elements the angular coordinates of the ends of arcs that are opposite sides in a ribbon. These arcs are sub-arcs in the internal boundaries of the ideograms, connected by the ribbon (see the image above). Compute the ribbon ends ...
def make_ribbon_ends(mapped_data, ideo_ends, idx_sort): L = mapped_data.shape[0] ribbon_boundary = np.zeros((L,L+1)) for k in range(L): start = ideo_ends[k][0] ribbon_boundary[k][0] = start for j in range(1,L+1): J = idx_sort[k][j-1] ribbon_boundary[k][j] = s...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
We note that ribbon_ends[k][j] corresponds to mapped_data[i][idx_sort[k][j]], i.e. the length of the arc of ends in ribbon_ends[k][j] is equal to mapped_data[i][idx_sort[k][j]]. Now we define a few functions that compute the control points for B&eacute;zier ribbon sides. The function control_pts returns the cartesian ...
def control_pts(angle, radius): #angle is a 3-list containing angular coordinates of the control points b0, b1, b2 #radius is the distance from b1 to the origin O(0,0) if len(angle) != 3: raise InvalidInputError('angle must have len =3') b_cplx = np.array([np.exp(1j*angle[k]) for k in range(...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
Each ribbon is colored with the color of one of the two ideograms it connects. We define an L-list of L-lists of colors for ribbons. Denote it by ribbon_color. ribbon_color[k][j] is the Plotly color string for the ribbon associated to mapped_data[k][j] and mapped_data[j][k], i.e. the ribbon connecting two subarcs in ...
ribbon_color = [L * [ideo_colors[k]] for k in range(L)]
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
and then eventually we are changing the color in a few positions. For our example we are perfotming the following color change:
ribbon_color[0][4]=ideo_colors[4] ribbon_color[1][2]=ideo_colors[2] ribbon_color[2][3]=ideo_colors[3] ribbon_color[2][4]=ideo_colors[4]
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
The symmetric locations are not modified, because we do not access ribbon_color[k][j], $k>j$, when drawing the ribbons. Functions that return the Plotly SVG paths that are ribbon boundaries:
def make_q_bezier(b):# defines the Plotly SVG path for a quadratic Bezier curve defined by the #list of its control points if len(b) != 3: raise valueError('control poligon must have 3 points') A, B, C = b return f'M {A[0]}, {A[1]} Q {B[0]}, {B[1]} {C[0]}, {C[1]}' b=[(1,4)...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
make_ribbon_arc returns the Plotly SVG path corresponding to an arc represented by its end angular coordinates, theta0, theta1.
def make_ribbon_arc(theta0, theta1): if test_2PI(theta0) and test_2PI(theta1): if theta0 < theta1: theta0 = moduloAB(theta0, -pi, pi) theta1 = moduloAB(theta1, -pi, pi) if theta0 *theta1 > 0: raise ValueError('incorrect angle coordinates for ribbon') ...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
Finally we are ready to define data and layout for the Plotly plot of the chord diagram.
import plotly.graph_objects as go def plot_layout(title, plot_size): return dict(title=title, xaxis=dict(visible=False), yaxis=dict(visible=False), showlegend=False, width=plot_size, height=plot_size, margin=dict(t=25,...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
Function that returns the Plotly shape of an ideogram:
def make_ideo_shape(path, line_color, fill_color): #line_color is the color of the shape boundary #fill_collor is the color assigned to an ideogram return dict(line=dict(color=line_color, width=0.45), path=path, layer='below', ...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
We generate two types of ribbons: a ribbon connecting subarcs in two distinct ideograms, respectively a ribbon from one ideogram to itself (it corresponds to mapped_data[k][k], i.e. it gives the flow of comments from a community member to herself).
def make_ribbon(l, r, line_color, fill_color, radius=0.2): #l=[l[0], l[1]], r=[r[0], r[1]] represent the opposite arcs in the ribbon #line_color is the color of the shape boundary #fill_color is the fill color for the ribbon shape poligon = ctrl_rib_chords(l,r, radius) b, c = poligon ...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
Now let us explain the key point of associating ribbons to right data: From the definition of ribbon_ends we notice that ribbon_ends[k][j] corresponds to data stored in matrix[k][sigma[j]], where sigma is the permutation of indices $0, 1, \ldots L-1$, that sort the row k in mapped_data. If sigma_inv is the inverse pe...
radii_sribb = [0.4, 0.30, 0.35, 0.39, 0.12]# these value are set after a few trials ribbon_info = [] shapes = [] for k in range(L): sigma = idx_sort[k] sigma_inv = invPerm(sigma) for j in range(k, L): if matrix[k][j] == 0 and matrix[j][k]==0: continue eta = idx_sort[j] eta_inv...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
ideograms is a list of dicts that set the position, and color of ideograms, as well as the information associated to each ideogram.
ideograms = [] for k in range(len(ideo_ends)): z = make_ideogram_arc(1.1, ideo_ends[k]) zi = make_ideogram_arc(1.0, ideo_ends[k]) m = len(z) n = len(zi) ideograms.append(go.Scatter(x=z.real, y=z.imag, mode='lines', ...
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
Here is a chord diagram associated to a community of 8 Facebook friends:
IFrame('https://plot.ly/~empet/12148/chord-diagram-of-facebook-comments-in-a-community/', width=500, height=500) from IPython.core.display import HTML def css_styling(): styles = open("./custom.css", "r").read() return HTML(styles) css_styling()
Chord-diagram.ipynb
empet/Plotly-plots
gpl-3.0
We take a peek at the training data with the head() method below.
X_train.head()
notebooks/ml_intermediate/raw/tut3.ipynb
Kaggle/learntools
apache-2.0
Next, we obtain a list of all of the categorical variables in the training data. We do this by checking the data type (or dtype) of each column. The object dtype indicates a column has text (there are other things it could theoretically be, but that's unimportant for our purposes). For this dataset, the columns with ...
# Get list of categorical variables s = (X_train.dtypes == 'object') object_cols = list(s[s].index) print("Categorical variables:") print(object_cols)
notebooks/ml_intermediate/raw/tut3.ipynb
Kaggle/learntools
apache-2.0
Define Function to Measure Quality of Each Approach We define a function score_dataset() to compare the three different approaches to dealing with categorical variables. This function reports the mean absolute error (MAE) from a random forest model. In general, we want the MAE to be as low as possible!
#$HIDE$ from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error # Function for comparing different approaches def score_dataset(X_train, X_valid, y_train, y_valid): model = RandomForestRegressor(n_estimators=100, random_state=0) model.fit(X_train, y_train) preds =...
notebooks/ml_intermediate/raw/tut3.ipynb
Kaggle/learntools
apache-2.0
Score from Approach 1 (Drop Categorical Variables) We drop the object columns with the select_dtypes() method.
drop_X_train = X_train.select_dtypes(exclude=['object']) drop_X_valid = X_valid.select_dtypes(exclude=['object']) print("MAE from Approach 1 (Drop categorical variables):") print(score_dataset(drop_X_train, drop_X_valid, y_train, y_valid))
notebooks/ml_intermediate/raw/tut3.ipynb
Kaggle/learntools
apache-2.0
Score from Approach 2 (Ordinal Encoding) Scikit-learn has a OrdinalEncoder class that can be used to get ordinal encodings. We loop over the categorical variables and apply the ordinal encoder separately to each column.
from sklearn.preprocessing import OrdinalEncoder # Make copy to avoid changing original data label_X_train = X_train.copy() label_X_valid = X_valid.copy() # Apply ordinal encoder to each column with categorical data ordinal_encoder = OrdinalEncoder() label_X_train[object_cols] = ordinal_encoder.fit_transform(X_train...
notebooks/ml_intermediate/raw/tut3.ipynb
Kaggle/learntools
apache-2.0
In the code cell above, for each column, we randomly assign each unique value to a different integer. This is a common approach that is simpler than providing custom labels; however, we can expect an additional boost in performance if we provide better-informed labels for all ordinal variables. Score from Approach 3 (...
from sklearn.preprocessing import OneHotEncoder # Apply one-hot encoder to each column with categorical data OH_encoder = OneHotEncoder(handle_unknown='ignore', sparse=False) OH_cols_train = pd.DataFrame(OH_encoder.fit_transform(X_train[object_cols])) OH_cols_valid = pd.DataFrame(OH_encoder.transform(X_valid[object_co...
notebooks/ml_intermediate/raw/tut3.ipynb
Kaggle/learntools
apache-2.0
2 - Outline of the Assignment To build your neural network, you will be implementing several "helper functions". These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. Each small helper function you will implement will have detailed instructions tha...
# GRADED FUNCTION: initialize_parameters def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: parameters -- python dictionary containing your parameters: W1 --...
Intro_to_Neural_Networks/Building+your+Deep+Neural+Network+-+Step+by+Step+v5.ipynb
radu941208/DeepLearning
mit
Expected output: <table style="width:80%"> <tr> <td> **W1** </td> <td> [[ 0.01624345 -0.00611756 -0.00528172] [-0.01072969 0.00865408 -0.02301539]] </td> </tr> <tr> <td> **b1**</td> <td>[[ 0.] [ 0.]]</td> </tr> <tr> <td>**W2**</td> <td> [[ 0.01744812 -0.00761207]]</td> </tr> ...
# GRADED FUNCTION: initialize_parameters_deep def initialize_parameters_deep(layer_dims): """ Arguments: layer_dims -- python array (list) containing the dimensions of each layer in our network Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": ...
Intro_to_Neural_Networks/Building+your+Deep+Neural+Network+-+Step+by+Step+v5.ipynb
radu941208/DeepLearning
mit
Expected output: <table style="width:80%"> <tr> <td> **W1** </td> <td>[[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388] [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218] [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034] [-0.00404677 -0.0054536 -0.01546477 0.00982367 -...
# GRADED FUNCTION: linear_forward def linear_forward(A, W, b): """ Implement the linear part of a layer's forward propagation. Arguments: A -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current la...
Intro_to_Neural_Networks/Building+your+Deep+Neural+Network+-+Step+by+Step+v5.ipynb
radu941208/DeepLearning
mit
Expected output: <table style="width:35%"> <tr> <td> **Z** </td> <td> [[ 3.26295337 -1.23429987]] </td> </tr> </table> 4.2 - Linear-Activation Forward In this notebook, you will use two activation functions: Sigmoid: $\sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}}$. We have provided you w...
# GRADED FUNCTION: linear_activation_forward def linear_activation_forward(A_prev, W, b, activation): """ Implement the forward propagation for the LINEAR->ACTIVATION layer Arguments: A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weigh...
Intro_to_Neural_Networks/Building+your+Deep+Neural+Network+-+Step+by+Step+v5.ipynb
radu941208/DeepLearning
mit
Expected output: <table style="width:35%"> <tr> <td> **With sigmoid: A ** </td> <td > [[ 0.96890023 0.11013289]]</td> </tr> <tr> <td> **With ReLU: A ** </td> <td > [[ 3.43896131 0. ]]</td> </tr> </table> Note: In deep learning, the "[LINEAR->ACTIVATION]" computation is counted as a s...
# GRADED FUNCTION: L_model_forward def L_model_forward(X, parameters): """ Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- data, numpy array of shape (input size, number of examples) parameters -- output of initialize_parameters_deep() ...
Intro_to_Neural_Networks/Building+your+Deep+Neural+Network+-+Step+by+Step+v5.ipynb
radu941208/DeepLearning
mit
<table style="width:50%"> <tr> <td> **AL** </td> <td > [[ 0.03921668 0.70498921 0.19734387 0.04728177]]</td> </tr> <tr> <td> **Length of caches list ** </td> <td > 3 </td> </tr> </table> Great! Now you have a full forward propagation that takes the input X and outputs a row vector $A^{[L]}...
# GRADED FUNCTION: compute_cost def compute_cost(AL, Y): """ Implement the cost function defined by equation (7). Arguments: AL -- probability vector corresponding to your label predictions, shape (1, number of examples) Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), sh...
Intro_to_Neural_Networks/Building+your+Deep+Neural+Network+-+Step+by+Step+v5.ipynb
radu941208/DeepLearning
mit
Expected Output: <table> <tr> <td>**cost** </td> <td> 0.41493159961539694</td> </tr> </table> 6 - Backward propagation module Just like with forward propagation, you will implement helper functions for backpropagation. Remember that back propagation is used to calculate the gradient of the loss funct...
# GRADED FUNCTION: linear_backward def linear_backward(dZ, cache): """ Implement the linear portion of backward propagation for a single layer (layer l) Arguments: dZ -- Gradient of the cost with respect to the linear output (of current layer l) cache -- tuple of values (A_prev, W, b) coming from ...
Intro_to_Neural_Networks/Building+your+Deep+Neural+Network+-+Step+by+Step+v5.ipynb
radu941208/DeepLearning
mit
Expected Output: <table style="width:90%"> <tr> <td> **dA_prev** </td> <td > [[ 0.51822968 -0.19517421] [-0.40506361 0.15255393] [ 2.37496825 -0.89445391]] </td> </tr> <tr> <td> **dW** </td> <td > [[-0.10076895 1.40685096 1.64992505]] </td> </tr> <tr> <td> **d...
# GRADED FUNCTION: linear_activation_backward def linear_activation_backward(dA, cache, activation): """ Implement the backward propagation for the LINEAR->ACTIVATION layer. Arguments: dA -- post-activation gradient for current layer l cache -- tuple of values (linear_cache, activation_cache)...
Intro_to_Neural_Networks/Building+your+Deep+Neural+Network+-+Step+by+Step+v5.ipynb
radu941208/DeepLearning
mit
Expected output with sigmoid: <table style="width:100%"> <tr> <td > dA_prev </td> <td >[[ 0.11017994 0.01105339] [ 0.09466817 0.00949723] [-0.05743092 -0.00576154]] </td> </tr> <tr> <td > dW </td> <td > [[ 0.10266786 0.09778551 -0.01968084]] </td> </tr> <tr> ...
# GRADED FUNCTION: L_model_backward def L_model_backward(AL, Y, caches): """ Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group Arguments: AL -- probability vector, output of the forward propagation (L_model_forward()) Y -- true "label" vector (contain...
Intro_to_Neural_Networks/Building+your+Deep+Neural+Network+-+Step+by+Step+v5.ipynb
radu941208/DeepLearning
mit
Expected Output <table style="width:60%"> <tr> <td > dW1 </td> <td > [[ 0.41010002 0.07807203 0.13798444 0.10502167] [ 0. 0. 0. 0. ] [ 0.05283652 0.01005865 0.01777766 0.0135308 ]] </td> </tr> <tr> <td > db1 </td> <td > [[-0.22007063]...
# GRADED FUNCTION: update_parameters def update_parameters(parameters, grads, learning_rate): """ Update parameters using gradient descent Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients, output of L_model_backward ...
Intro_to_Neural_Networks/Building+your+Deep+Neural+Network+-+Step+by+Step+v5.ipynb
radu941208/DeepLearning
mit
Making Python faster This homework provides practice in making Python code faster. Note that we start with functions that already use idiomatic numpy (which are about two orders of magnitude faster than the pure Python versions). Functions to optimize
def logistic(x): """Logistic function.""" return np.exp(x)/(1 + np.exp(x)) def gd(X, y, beta, alpha, niter): """Gradient descent algorihtm.""" n, p = X.shape Xt = X.T for i in range(niter): y_pred = logistic(X @ beta) epsilon = y - y_pred grad = Xt @ epsilon / n ...
homework/05_Making_Python_Faster_Solutions.ipynb
cliburn/sta-663-2017
mit
Data set for classification
n = 10000 p = 2 X, y = make_blobs(n_samples=n, n_features=p, centers=2, cluster_std=1.05, random_state=23) X = np.c_[np.ones(len(X)), X] y = y.astype('float')
homework/05_Making_Python_Faster_Solutions.ipynb
cliburn/sta-663-2017
mit
Using gradient descent for classification by logistic regression
# initial parameters niter = 1000 α = 0.01 β = np.zeros(p+1) # call gradient descent β = gd(X, y, β, α, niter) # assign labels to points based on prediction y_pred = logistic(X @ β) labels = y_pred > 0.5 # calculate separating plane sep = (-β[0] - β[1] * X)/β[2] plt.scatter(X[:, 1], X[:, 2], c=labels, cmap='winter'...
homework/05_Making_Python_Faster_Solutions.ipynb
cliburn/sta-663-2017
mit
1. Rewrite the logistic function so it only makes one np.exp call. Compare the time of both versions with the input x given below using the @timeit magic. (10 points)
np.random.seed(123) n = int(1e7) x = np.random.normal(0, 1, n) def logistic2(x): """Logistic function.""" return 1/(1 + np.exp(-x)) %timeit logistic(x) %timeit logistic2(x)
homework/05_Making_Python_Faster_Solutions.ipynb
cliburn/sta-663-2017
mit
2. (20 points) Use numba to compile the gradient descent function. Use the @vectorize decorator to create a ufunc version of the logistic function and call this logistic_numba_cpu with function signatures of float64(float64). Create another function called logistic_numba_parallel by giving an extra argument to the de...
@vectorize([float64(float64)], target='cpu') def logistic_numba_cpu(x): """Logistic function.""" return 1/(1 + math.exp(-x)) @vectorize([float64(float64)], target='parallel') def logistic_numba_parallel(x): """Logistic function.""" return 1/(1 + math.exp(-x)) np.testing.assert_array_almost_equal(logis...
homework/05_Making_Python_Faster_Solutions.ipynb
cliburn/sta-663-2017
mit
3. (30 points) Use cython to compile the gradient descent function. Cythonize the logistic function as logistic_cython. Use the --annotate argument to the cython magic function to find slow regions. Compare accuracy and performance. The final performance should be comparable to the numba cpu version. (10 points) Now ...
%%cython --annotate import cython import numpy as np cimport numpy as np from libc.math cimport exp @cython.boundscheck(False) @cython.wraparound(False) @cython.cdivision(True) def logistic_cython(double[:] x): """Logistic function.""" cdef int i cdef int n = x.shape[0] cdef double [:] s = np.empty(n)...
homework/05_Making_Python_Faster_Solutions.ipynb
cliburn/sta-663-2017
mit
4. (40 points) Wrapping modules in C++. Rewrite the logistic and gd functions in C++, using pybind11 to create Python wrappers. Compare accuracy and performance as usual. Replicate the plotted example using the C++ wrapped functions for logistic and gd Writing a vectorized logistic function callable from both C++ and...
import os if not os.path.exists('./eigen'): ! git clone https://github.com/RLovelett/eigen.git %%file wrap.cpp <% cfg['compiler_args'] = ['-std=c++11'] cfg['include_dirs'] = ['./eigen'] setup_pybind11(cfg) %> #include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <pybind11/eigen.h> namespace py = py...
homework/05_Making_Python_Faster_Solutions.ipynb
cliburn/sta-663-2017
mit
Guide to Building End-to-End Reinforcement Learning Application Pipelines using Vertex AI <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/tree/master/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_t...
import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: USER_FLAG = "--user" ! pip3 install {...
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Before you begin Select a GPU runtime Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select "Runtime --> Change runtime type > GPU" Set up your Google Cloud project The following steps are required, regardless of your notebook environment. Select or create a Google Cloud pr...
import os PROJECT_ID = "" # Get your Google Cloud project ID from gcloud if not os.getenv("IS_TESTING"): shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID: ", PROJECT_ID)
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Authenticate your Google Cloud account If you are using Google Cloud Notebooks, your environment is already authenticated. Skip this step. If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. Otherwise, follow these steps: In the Cloud Console, g...
import os import sys # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets you submit training jobs and prediction # requests. # The Google Cloud Notebook product has specific requirements...
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. In this tutorial, a Cloud Storage bucket holds the MovieLens dataset files to be used for model training. Vertex AI also saves the trained model that results from your training job in the same bucket. Using this mod...
BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"} REGION = "[your-region]" # @param {type:"string"} if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]": BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Import libraries and define constants
import os import sys from google.cloud import aiplatform from google_cloud_pipeline_components import aiplatform as gcc_aip from kfp.v2 import compiler, dsl from kfp.v2.google.client import AIPlatformClient
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Fill out the following configurations
# BigQuery parameters (used for the Generator, Ingester, Logger) BIGQUERY_DATASET_ID = f"{PROJECT_ID}.movielens_dataset" # @param {type:"string"} BigQuery dataset ID as `project_id.dataset_id`. BIGQUERY_LOCATION = "us" # @param {type:"string"} BigQuery dataset region. BIGQUERY_TABLE_ID = f"{BIGQUERY_DATASET_ID}.train...
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Set additional configurations You may use the default values below as is.
# Dataset parameters RAW_DATA_PATH = "gs://[your-bucket-name]/raw_data/u.data" # @param {type:"string"} # Download the sample data into your RAW_DATA_PATH ! gsutil cp "gs://cloud-samples-data/vertex-ai/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/u.data" $RAW_DATA_PATH # Pipeline...
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create the RL pipeline components This section consists of the following steps: 1. Create the Generator to generate MovieLens simulation data 2. Create the Ingester to ingest data 3. Create the Trainer to train the RL policy 4. Create the Deployer to deploy the trained policy to a Vertex AI endpoint After pipeline cons...
! python3 -m unittest src.generator.test_generator_component
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create the Ingester to ingest data Create the Ingester component to ingest data from BigQuery, package them as tf.train.Example objects, and output TFRecord files. Read more about tf.train.Example and TFRecord here. The Ingester component source code is in src/ingester/ingester_component.py. Run unit tests on the Inges...
! python3 -m unittest src.ingester.test_ingester_component
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create the Trainer to train the RL policy Create the Trainer component to train a RL policy on the training dataset, and then submit a remote custom training job to Vertex AI. This component trains a policy using the TF-Agents LinUCB agent on the MovieLens simulation dataset, and saves the trained policy as a SavedMode...
# Trainer parameters TRAINING_ARTIFACTS_DIR = ( f"{BUCKET_NAME}/artifacts" # Root directory for training artifacts. ) TRAINING_REPLICA_COUNT = 1 # Number of replica to run the custom training job. TRAINING_MACHINE_TYPE = ( "n1-standard-4" # Type of machine to run the custom training job. ) TRAINING_ACCELERAT...
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Run unit tests on the Trainer component
! python3 -m unittest src.trainer.test_trainer_component
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create the Deployer to deploy the trained policy to a Vertex AI endpoint Use google_cloud_pipeline_components.aiplatform components during pipeline construction to: 1. Upload the trained policy 2. Create a Vertex AI endpoint 3. Deploy the uploaded trained policy to the endpoint These 3 components formulate the Deployer...
# Deployer parameters TRAINED_POLICY_DISPLAY_NAME = ( "movielens-trained-policy" # Display name of the uploaded and deployed policy. ) TRAFFIC_SPLIT = {"0": 100} ENDPOINT_DISPLAY_NAME = "movielens-endpoint" # Display name of the prediction endpoint. ENDPOINT_MACHINE_TYPE = "n1-standard-4" # Type of machine of th...
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create a custom prediction container using Cloud Build Before setting up the Deployer, define and build a custom prediction container that serves predictions using the trained policy. The source code, Cloud Build YAML configuration file and Dockerfile are in src/prediction_container. This prediction container is the se...
# Prediction container parameters PREDICTION_CONTAINER = "prediction-container" # Name of the container image. PREDICTION_CONTAINER_DIR = "src/prediction_container"
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create a Cloud Build YAML file using Kaniko build Note: For this application, you are recommended to use E2_HIGHCPU_8 or other high resouce machine configurations instead of the standard machine type listed here to prevent out-of-memory errors.
cloudbuild_yaml = """steps: - name: "gcr.io/kaniko-project/executor:latest" args: ["--destination=gcr.io/{PROJECT_ID}/{PREDICTION_CONTAINER}:latest", "--cache=true", "--cache-ttl=99h"] env: ["AIP_STORAGE_URI={ARTIFACTS_DIR}", "PROJECT_ID={PROJECT_ID}", "LOGGER_PUBSUB_TOPIC={LOGGER_...
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Run unit tests on the prediction code
! python3 -m unittest src.prediction_container.test_main
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Build custom prediction container
! gcloud builds submit --config $PREDICTION_CONTAINER_DIR/cloudbuild.yaml $PREDICTION_CONTAINER_DIR
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Author and run the RL pipeline You author the pipeline using custom KFP components built from the previous section, and create a pipeline run using Vertex Pipelines. You can read more about whether to enable execution caching here. You can also specifically configure the worker pool spec for training if for instance yo...
from google_cloud_pipeline_components.experimental.custom_job import utils from kfp.components import load_component_from_url generate_op = load_component_from_url( "https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/62a2a7611499490b4b04d731d48a7ba87c2d636f/community-content/tf_agents_bandits_...
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create the Simulator to send simulated MovieLens prediction requests Create the Simulator to obtain observations from the MovieLens simulation environment, formats them, and sends prediction requests to the Vertex AI endpoint. The workflow is: Cloud Scheduler --> Pub/Sub --> Cloud Functions --> Endpoint In production, ...
# Simulator parameters SIMULATOR_PUBSUB_TOPIC = ( "simulator-pubsub-topic" # Pub/Sub topic name for the Simulator. ) SIMULATOR_CLOUD_FUNCTION = ( "simulator-cloud-function" # Cloud Functions name for the Simulator. ) SIMULATOR_SCHEDULER_JOB = ( "simulator-scheduler-job" # Cloud Scheduler cron job name fo...
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Run unit tests on the Simulator
! python3 -m unittest src.simulator.test_main
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create a Pub/Sub topic Read more about creating Pub/Sub topics here
! gcloud pubsub topics create $SIMULATOR_PUBSUB_TOPIC
community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0