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
The maximum value rises and falls smoothly, while the minimum seems to be a step function. Neither trend seems particularly likely, so either there's a mistake in our calculations or something is wrong with our data. This insight would have been difficult to reach by examining the numbers themselves without visualisati...
min_plot = matplotlib.pyplot.plot(numpy.min(data, axis=0))
_____no_output_____
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Grouping plotsYou can group similar plots in a single figure using subplots. This script below uses a number of new commands. The function `matplotlib.pyplot.figure()` creates a space into which we will place all of our plots. The parameter `figsize` tells Python how big to make this space. Each subplot is placed into...
import numpy import matplotlib.pyplot data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',') fig = matplotlib.pyplot.figure(figsize=(15.0, 5.0)) axes1 = fig.add_subplot(1, 3, 1) #(1,3,1 1つめのグラフ) axes2 = fig.add_subplot(1, 3, 2) axes3 = fig.add_subplot(1, 3, 3) #label の設定 axes1.set_ylabel('average') ...
_____no_output_____
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
The Previous Plots as SubplotsThe call to `loadtxt` reads our data, and the rest of the program tells the plotting library how large we want the figure to be, that we're creating three subplots, what to draw for each one, and that we want a tight layout. (If we leave out that call to `fig.tight_layout()`, the graphs w...
import numpy import matplotlib.pyplot data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',') fig = matplotlib.pyplot.figure(figsize=(5.0, 5.0)) axes1 = fig.add_subplot(1, 1, 1) #(1,3,1 1つめのグラフ) #label の設定 + #Days の設定 axes1.set_ylabel('average') axes1.set_xlabel('days') plot = axes1.plot(numpy.mea...
_____no_output_____
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Scientists Dislike Typing. We will always use the syntax `import numpy` to import NumPy. However, in order to save typing, it is often suggested to make a shortcut like so: `import numpy as np`. If you ever see Python code online using a NumPy function with np (for example, `np.loadtxt(...))`, it's because they've use...
import numpy as np np.random.rand() #
_____no_output_____
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Exercises Plot ScalingWhy do all of our plots stop just short of the upper end of our graph? Solution: If we want to change this, we can use the `set_ylim(min, max)` method of each ‘axes’, for example:```axes3.set_ylim(0,6)```Update your plotting code to automatically set a more appropriate scale. (Hint: you can make...
#see above
_____no_output_____
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Drawing Straight LinesIn the centre and right subplots above, we expect all lines to look like step functions because non-integer value are not realistic for the minimum and maximum values. However, you can see that the lines are not always vertical or horizontal, and in particular the step function in the subplot on ...
import numpy import matplotlib.pyplot data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',') fig = matplotlib.pyplot.figure(figsize=(15.0, 5.0)) axes1 = fig.add_subplot(1, 3, 1) #(1,3,1 1つめのグラフ) axes2 = fig.add_subplot(1, 3, 2) axes3 = fig.add_subplot(1, 3, 3) #label の設定 axes1.set_ylabel('average') ...
_____no_output_____
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Solution: Make Your Own PlotCreate a plot showing the standard deviation (using `numpy.std`) of the inflammation data for each day across all patients.
#standard deviation #help(numpy.std) # Example #a = np.array([[1, 2], [3, 4]]) #>>> np.std(a) # 1.1180339887498949 # may vary # >>> np.std(a, axis=0) # array([1., 1.]) #>>> np.std(a, axis=1) #array([0.5, 0.5]) numpy.std(data) numpy.std(data, axis=0) numpy.std(data, axis=1)
_____no_output_____
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Moving Plots AroundModify the program to display the three plots vertically rather than side by side.
import numpy import matplotlib.pyplot data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',') fig = matplotlib.pyplot.figure(figsize=(15.0, 15.0)) axes1 = fig.add_subplot(3, 3, 1) #(total no. of row,total no. of column, order starting from top left 1つめのグラフ) axes2 = fig.add_subplot(3, 3, 5) axes3 = fig...
_____no_output_____
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Stacking ArraysArrays can be concatenated and stacked on top of one another, using NumPy’s `vstack` and `hstack` functions for vertical and horizontal stacking, respectively.Run the following code to view `A`, `B` and `C`
import numpy A = numpy.array([[1,2,3], [4,5,6], [7, 8, 9]]) print('A = ') print(A) B = numpy.hstack([A, A]) print('B = ') print(B) C = numpy.vstack([A, A]) print('C = ') print(C)
A = [[1 2 3] [4 5 6] [7 8 9]] B = [[1 2 3 1 2 3] [4 5 6 4 5 6] [7 8 9 7 8 9]] C = [[1 2 3] [4 5 6] [7 8 9] [1 2 3] [4 5 6] [7 8 9]]
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Write some additional code that slices the first and last columns of `A`,and stacks them into a 3x2 array. Make sure to print the results to verify your solution.
print(A[:,0]) # all rows from first column #print(result)
[1 4 7]
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Change In InflammationThis patient data is longitudinal in the sense that each row represents a series of observations relating to one individual. This means that the change in inflammation over time is a meaningful concept.The `numpy.diff()` function takes a NumPy array and returns the differences between two success...
npdiff = numpy.array([ 0, 2, 5, 9, 14]) numpy.diff(npdiff)
_____no_output_____
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
In our `data` Which axis would it make sense to use this function along?
npdiff = numpy.array(data[0][0:4]) print(npdiff)
[0. 0. 1. 3.]
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Solution If the shape of an individual data file is (60, 40) (60 rows and 40 columns), what would the shape of the array be after you run the diff() function and why?
npdiff = numpy.array(data[0:60][0:39]) print(npdiff)
[[0. 0. 1. ... 3. 0. 0.] [0. 1. 2. ... 1. 0. 1.] [0. 1. 1. ... 2. 1. 1.] ... [0. 1. 2. ... 3. 2. 1.] [0. 1. 1. ... 0. 1. 0.] [0. 1. 0. ... 3. 0. 1.]]
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Solution How would you find the largest change in inflammation for each patient? Does it matter if the change in inflammation is an increase or a decrease? Hint: NumPy has a function called `numpy.absolute()`,
numpy.absolute(data)
_____no_output_____
MIT
lessons/python/ep1b-plotting-intro.ipynb
emichan14/2019-12-03-intro-to-python-workshop
Python Basics with Numpy (optional assignment)Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help familiarize you with functions we'll need. **Instructions:**- You will be using Python 3.- Avoid using for-loops and while-loops, un...
import numpy as np ### START CODE HERE ### (≈ 1 line of code) test = "Hello World" ### END CODE HERE ### print ("test: " + test)
test: Hello World
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
**Expected output**:test: Hello World **What you need to remember**:- Run your cells using SHIFT+ENTER (or "Run cell")- Write code in the designated areas using Python 3 only- Do not modify the code outside of the designated areas 1 - Building basic functions with numpy Numpy is the main package for scientific computi...
# GRADED FUNCTION: basic_sigmoid import math def basic_sigmoid(x): """ Compute sigmoid of x. Arguments: x -- A scalar Return: s -- sigmoid(x) """ ### START CODE HERE ### (≈ 1 line of code) s = 1 / (1 + math.exp(-x)) ### END CODE HERE ### return s basic_sigmoid(3...
_____no_output_____
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
**Expected Output**: ** basic_sigmoid(3) ** 0.9525741268224334 Actually, we rarely use the "math" library in deep learning because the inputs of the functions are real numbers. In deep learning we mostly use matrices and vectors. This is why numpy is more useful.
### One reason why we use "numpy" instead of "math" in Deep Learning ### x = [1, 2, 3] basic_sigmoid(x) # you will see this give an error when you run it, because x is a vector.
_____no_output_____
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
In fact, if $ x = (x_1, x_2, ..., x_n)$ is a row vector then $np.exp(x)$ will apply the exponential function to every element of x. The output will thus be: $np.exp(x) = (e^{x_1}, e^{x_2}, ..., e^{x_n})$
import numpy as np # example of np.exp x = np.array([1, 2, 3]) print(np.exp(x)) # result is (exp(1), exp(2), exp(3))
_____no_output_____
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
Furthermore, if x is a vector, then a Python operation such as $s = x + 3$ or $s = \frac{1}{x}$ will output s as a vector of the same size as x.
# example of vector operation x = np.array([1, 2, 3]) print (x + 3)
_____no_output_____
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
Any time you need more info on a numpy function, we encourage you to look at [the official documentation](https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.exp.html). You can also create a new cell in the notebook and write `np.exp?` (for example) to get quick access to the documentation.**Exercise**: I...
# GRADED FUNCTION: sigmoid import numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function() def sigmoid(x): """ Compute the sigmoid of x Arguments: x -- A scalar or numpy array of any size Return: s -- sigmoid(x) """ ### START C...
_____no_output_____
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
**Expected Output**: **sigmoid([1,2,3])** array([ 0.73105858, 0.88079708, 0.95257413]) 1.2 - Sigmoid gradientAs you've seen in lecture, you will need to compute gradients to optimize loss functions using backpropagation. Let's code your first gradient function.**Exercise**: Implement th...
# GRADED FUNCTION: sigmoid_derivative def sigmoid_derivative(x): """ Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x. You can store the output of the sigmoid function into variables and then use it to calculate the gradient. Arguments:...
_____no_output_____
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
**Expected Output**: **sigmoid_derivative([1,2,3])** [ 0.19661193 0.10499359 0.04517666] 1.3 - Reshaping arrays Two common numpy functions used in deep learning are [np.shape](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html) and [np.reshape()](https://docs....
# GRADED FUNCTION: image2vector def image2vector(image): """ Argument: image -- a numpy array of shape (length, height, depth) Returns: v -- a vector of shape (length*height*depth, 1) """ ### START CODE HERE ### (≈ 1 line of code) v = image v = v.reshape(v.shape[0] * v.shap...
_____no_output_____
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
**Expected Output**: **image2vector(image)** [[ 0.67826139] [ 0.29380381] [ 0.90714982] [ 0.52835647] [ 0.4215251 ] [ 0.45017551] [ 0.92814219] [ 0.96677647] [ 0.85304703] [ 0.52351845] [ 0.19981397] [ 0.27417313] [ 0.60659855] [ 0.00533165] [ 0.10820313] [ 0.49978937] [ 0.34144279] [ 0.94630077]...
# GRADED FUNCTION: normalizeRows def normalizeRows(x): """ Implement a function that normalizes each row of the matrix x (to have unit length). Argument: x -- A numpy matrix of shape (n, m) Returns: x -- The normalized (by row) numpy matrix. You are allowed to modify x. """ ...
_____no_output_____
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
**Expected Output**: **normalizeRows(x)** [[ 0. 0.6 0.8 ] [ 0.13736056 0.82416338 0.54944226]] **Note**:In normalizeRows(), you can try to print the shapes of x_norm and x, and then rerun the assessment. You'll find out that they have different shapes. This i...
# GRADED FUNCTION: softmax def softmax(x): """Calculates the softmax for each row of the input x. Your code should work for a row vector and also for matrices of shape (n, m). Argument: x -- A numpy matrix of shape (n,m) Returns: s -- A numpy matrix equal to the softmax of x, of shape (n,m) ...
_____no_output_____
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
**Expected Output**: **softmax(x)** [[ 9.80897665e-01 8.94462891e-04 1.79657674e-02 1.21052389e-04 1.21052389e-04] [ 8.78679856e-01 1.18916387e-01 8.01252314e-04 8.01252314e-04 8.01252314e-04]] **Note**:- If you print the shapes of x_exp, x_sum and s above and rerun the a...
import time x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0] x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0] ### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ### tic = time.process_time() dot = 0 for i in range(len(x1)): dot+= x1[i]*x2[i] toc = time.process_time() print ("dot = " + str(dot) + "\n ----- Comp...
_____no_output_____
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
As you may have noticed, the vectorized implementation is much cleaner and more efficient. For bigger vectors/matrices, the differences in running time become even bigger. **Note** that `np.dot()` performs a matrix-matrix or matrix-vector multiplication. This is different from `np.multiply()` and the `*` operator (whic...
# GRADED FUNCTION: L1 def L1(yhat, y): """ Arguments: yhat -- vector of size m (predicted labels) y -- vector of size m (true labels) Returns: loss -- the value of the L1 loss function defined above """ ### START CODE HERE ### (≈ 1 line of code) loss = np.sum(np.abs(yhat -...
L1 = 1.1
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
**Expected Output**: **L1** 1.1 **Exercise**: Implement the numpy vectorized version of the L2 loss. There are several way of implementing the L2 loss but you may find the function np.dot() useful. As a reminder, if $x = [x_1, x_2, ..., x_n]$, then `np.dot(x,x)` = $\sum_{j=0}^n x_j^{2}$. - ...
# GRADED FUNCTION: L2 def L2(yhat, y): """ Arguments: yhat -- vector of size m (predicted labels) y -- vector of size m (true labels) Returns: loss -- the value of the L2 loss function defined above """ ### START CODE HERE ### (≈ 1 line of code) loss = np.sum((y - yhat) **...
L2 = 0.43
MIT
NNs-and-deep-learning/jupyter/Week 2/Python Basics with Numpy/Python Basics With Numpy v3.ipynb
HaleTom/deeplearning.ai_notes
Your very own neural networkIn this programming assignment we're going to build a neural network using naught but pure numpy and steel nerves. It's going to be fun, we promise!__Disclaimer:__ This assignment is ungraded.
%%bash shred -u setup_colab.py wget https://raw.githubusercontent.com/hse-aml/intro-to-dl-pytorch/main/utils/setup_colab.py -O setup_colab.py import setup_colab setup_colab.setup_week02_honor() import tqdm_utils from __future__ import print_function import numpy as np np.random.seed(42)
_____no_output_____
MIT
02_PYTHON/week02/week02_numpy_neural_network.ipynb
milaan9/Deep_Learning_Algorithms_from_Scratch
Here goes our main class: a layer that can do .forward() and .backward() passes.
class Layer: """ A building block. Each layer is capable of performing two things: - Process input to get output: output = layer.forward(input) - Propagate gradients through itself: grad_input = layer.backward(input, grad_output) Some layers also have learnable parameters...
_____no_output_____
MIT
02_PYTHON/week02/week02_numpy_neural_network.ipynb
milaan9/Deep_Learning_Algorithms_from_Scratch
The road aheadWe're going to build a neural network that classifies MNIST digits. To do so, we'll need a few building blocks:- Dense layer - a fully-connected layer, $f(X)=W \cdot X + \vec{b}$- ReLU layer (or any other nonlinearity you want)- Loss function - crossentropy- Backprop algorithm - a stochastic gradient des...
class ReLU(Layer): def __init__(self): """ReLU layer simply applies elementwise rectified linear unit to all inputs""" pass def forward(self, input): """Apply elementwise ReLU to [batch, input_units] matrix""" # <your code. Try np.maximum> def backward(self, input, ...
_____no_output_____
MIT
02_PYTHON/week02/week02_numpy_neural_network.ipynb
milaan9/Deep_Learning_Algorithms_from_Scratch
Instant primer: lambda functionsIn python, you can define functions in one line using the `lambda` syntax: `lambda param1, param2: expression`For example: `f = lambda x, y: x+y` is equivalent to a normal function:```def f(x,y): return x+y```For more information, click [here](http://www.secnetix.de/olli/Python/lambd...
class Dense(Layer): def __init__(self, input_units, output_units, learning_rate=0.1): """ A dense layer is a layer which performs a learned affine transformation: f(x) = <W*x> + b """ self.learning_rate = learning_rate # initialize weights with small random n...
_____no_output_____
MIT
02_PYTHON/week02/week02_numpy_neural_network.ipynb
milaan9/Deep_Learning_Algorithms_from_Scratch
Testing the dense layerHere we have a few tests to make sure your dense layer works properly. You can just run them, get 3 "well done"s and forget they ever existed.... or not get 3 "well done"s and go fix stuff. If that is the case, here are some tips for you:* Make sure you compute gradients for W and b as __sum of ...
l = Dense(128, 150) assert -0.05 < l.weights.mean() < 0.05 and 1e-3 < l.weights.std() < 1e-1,\ "The initial weights must have zero mean and small variance. "\ "If you know what you're doing, remove this assertion." assert -0.05 < l.biases.mean() < 0.05, "Biases must be zero mean. Ignore if you have a reason to...
_____no_output_____
MIT
02_PYTHON/week02/week02_numpy_neural_network.ipynb
milaan9/Deep_Learning_Algorithms_from_Scratch
The loss functionSince we want to predict probabilities, it would be logical for us to define softmax nonlinearity on top of our network and compute loss given predicted probabilities. However, there is a better way to do so.If you write down the expression for crossentropy as a function of softmax logits (a), you'll ...
def softmax_crossentropy_with_logits(logits,reference_answers): """Compute crossentropy from logits[batch,n_classes] and ids of correct answers""" logits_for_answers = logits[np.arange(len(logits)),reference_answers] xentropy = - logits_for_answers + np.log(np.sum(np.exp(logits),axis=-1)) retu...
_____no_output_____
MIT
02_PYTHON/week02/week02_numpy_neural_network.ipynb
milaan9/Deep_Learning_Algorithms_from_Scratch
Full networkNow let's combine what we've just built into a working neural network. As we announced, we're gonna use this monster to classify handwritten digits, so let's get them loaded. We will download the data using pythorch.
!pip install torchvision # import numpy and matplotlib %pylab inline import torchvision transform = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Lambda(lambda x: x.flatten()) ]) train_dataset = torchvision.datasets.MNIST(root='.', train=True, ...
_____no_output_____
MIT
02_PYTHON/week02/week02_numpy_neural_network.ipynb
milaan9/Deep_Learning_Algorithms_from_Scratch
We'll define network as a list of layers, each applied on top of previous one. In this setting, computing predictions and training becomes trivial.
network = [] network.append(Dense(X_train.shape[1],100)) network.append(ReLU()) network.append(Dense(100,200)) network.append(ReLU()) network.append(Dense(200,10)) def forward(network, X): """ Compute activations of all network layers by applying them sequentially. Return a list of activations for each laye...
_____no_output_____
MIT
02_PYTHON/week02/week02_numpy_neural_network.ipynb
milaan9/Deep_Learning_Algorithms_from_Scratch
Instead of tests, we provide you with a training loop that prints training and validation accuracies on every epoch.If your implementation of forward and backward are correct, your accuracy should grow from 90~93% to >97% with the default network. Training loopAs usual, we split data into minibatches, feed each such m...
def iterate_minibatches(inputs, targets, batchsize, shuffle=False): assert len(inputs) == len(targets) if shuffle: indices = np.random.permutation(len(inputs)) for start_idx in tqdm_utils.tqdm_notebook_failsafe(range(0, len(inputs) - batchsize + 1, batchsize)): if shuffle: excerp...
_____no_output_____
MIT
02_PYTHON/week02/week02_numpy_neural_network.ipynb
milaan9/Deep_Learning_Algorithms_from_Scratch
E2E ML on GCP: MLOps stage 4 : formalization: get started with Google Artifact Registry View on GitHub Open in Vertex AI Workbench OverviewThis tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 4 : formalization: ...
ONCE_ONLY = False if ONCE_ONLY: ! pip3 install -U tensorflow==2.5 $USER_FLAG ! pip3 install -U tensorflow-data-validation==1.2 $USER_FLAG ! pip3 install -U tensorflow-transform==1.2 $USER_FLAG ! pip3 install -U tensorflow-io==0.18 $USER_FLAG ! pip3 install --upgrade google-cloud-aiplatform[tensorboa...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Restart the kernelOnce you've installed the additional packages, you need to restart the notebook kernel so it can find the packages.
import os if not os.getenv("IS_TESTING"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True)
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Set your project ID**If you don't know your project ID**, you may be able to get your project ID using `gcloud`.
PROJECT_ID = "[your-project-id]" # @param {type:"string"} if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID:"...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
RegionYou can also change the `REGION` variable, which is used for operationsthroughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.- Americas: `us-central1`- Europe: `europe-west4`- Asia Pacific: `asia-east1`You may not use a multi-regi...
REGION = "us-central1" # @param {type: "string"}
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
TimestampIf you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial.
from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Set up variablesNext, set up some variables used throughout the tutorial. Import libraries and define constants Introduction to Google Artifact RegistryThe `Google Artifact Registry` is a service for storing and managing artifacts in private repositories, including container images, Helm charts, and language packages...
! gcloud services enable artifactregistry.googleapis.com
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Create a private Docker repositoryYour first step is to create your own Docker repository in Google Artifact Registry.1. Run the `gcloud artifacts repositories create` command to create a new Docker repository with your region with the description "docker repository".2. Run the `gcloud artifacts repositories list` com...
PRIVATE_REPO = "my-docker-repo" ! gcloud artifacts repositories create {PRIVATE_REPO} --repository-format=docker --location={REGION} --description="Docker repository" ! gcloud artifacts repositories list
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Configure authentication to your private repoBefore you push or pull container images, configure Docker to use the `gcloud` command-line tool to authenticate requests to `Artifact Registry` for your region.
! gcloud auth configure-docker {REGION}-docker.pkg.dev --quiet
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Obtain an example container imageFor demonstration purposes, you obtain (pull) a local copy of our demonstration container image: `hello-app:1.0`
! docker pull us-docker.pkg.dev/google-samples/containers/gke/hello-app:1.0
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Tagging your container imageNow that you have your own container image, the first step is to tag your image.- Tagging the Docker image with a repository name configures the docker push command to push the image to a specific location, e.g., us-central1-docker.pkg.dev.- `:my-tag` is a tag you're adding to the Docker im...
CONTAINER_NAME = "my-image:my-tag" ! docker tag us-docker.pkg.dev/google-samples/containers/gke/hello-app:1.0 us-central1-docker.pkg.dev/{PROJECT_ID}/{PRIVATE_REPO}/{CONTAINER_NAME}
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Push your image to your private Docker repositoryNext, push your container to your private Docker repository.
! docker push {REGION}-docker.pkg.dev/{PROJECT_ID}/{PRIVATE_REPO}/{CONTAINER_NAME}
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Pull your image from your private Docker repostoryNow pull your container from your private Docker repository.
! docker pull {REGION}-docker.pkg.dev/{PROJECT_ID}/{PRIVATE_REPO}/{CONTAINER_NAME}
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Deleting your private Docker repostoryFinally, once your private repository becomes obsolete, use the command `gcloud artifacts repositories delete` to delete it `Google Artifact Registry`.
! gcloud artifacts repositories delete {PRIVATE_REPO} --location={REGION} --quiet
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage4/get_started_with_google_artifact_registry.ipynb
prodonjs/vertex-ai-samples
Introduzione pratica ai tipi di dati in PythonPer ulteriori esempi e riferimenti, si veda [An Informal Introduction to Python](https://docs.python.org/2/tutorial/introduction.html)
metadata = "Name;Identity;Birth place;Publisher;Height;Weight;Gender;First appearance;Eye color;Hair color;Strength;Intelligence" rowdata = 'Silver Surfer;Norrin Radd;Zenn-La;Marvel Comics;193.00999999999999;101.34;M;;White;No Hair;100;average'
_____no_output_____
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
StringheLe stringhe in Python sono collezioni di caratteri incluse fra i simboli "..." o '...'. Le due notazioni non hanno significative differenze se usiamo "..." non dobbiamo quotare il simbolo ' e viceversa.
print 'Ero "felice"' print 'Ero \'felice\'' print "Ero 'felice'" print "Ero \"felice\"\nDavvero!"
Ero "felice" Ero 'felice' Ero 'felice' Ero "felice" Davvero!
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Per evitare di interpretare il simbolo \ come un marcatore possiamo ricorrere alle 'raw strings'. In generale, le stringhe Python possono essere qialificate come stringhe speciali, anteponendo alla stringa un descrittore. Per conoscere il tipo di un dato esiste la funzione `type`.
print 'Bianco\nero' print r'Bianco\nero' print type('Bianco\nero'), type(r'Bianco\nero'), type(u'Bianco\nero')
Bianco ero Bianco\nero <type 'str'> <type 'str'> <type 'unicode'>
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Stringhe che occupano più linee e conservano la formattazione sono denotate dai simboli """...""" o '''...'''.
silverbio = """ Silver Surfer, alter ego di Norrin Radd, è un personaggio immaginario dei fumetti creato da Stan Lee e Jack Kirby nel 1966 \ e pubblicato dalla casa editrice statunitense Marvel Comics. Esordisce nella serie The Fantastic Four (Vol. 1[1]) n. 48 del 1966, nella Trilogia di Galactus, \ il cui riscontro ...
Silver Surfer, alter ego di Norrin Radd, è un personaggio immaginario dei fumetti creato da Stan Lee e Jack Kirby nel 1966 e pubblicato dalla casa editrice statunitense Marvel Comics. Esordisce nella serie The Fantastic Four (Vol. 1[1]) n. 48 del 1966, nella Trilogia di Galactus, il cui riscontro positivo da parte d...
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Concatenazione di stringheLe stringhe si concatenano con l'operatore `+`, si ripetono con `*`. I 'string literals' (le stringhe con '...' si concatenano anche solo giustapponendole
print 3 * "super " + "silver" print 'con' 'catenato' sentence = ('Se uso le parentesi e ' 'i literals ' 'è super comodo!') print sentence
super super super silver concatenato Se uso le parentesi e i literals è super comodo!
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Ma non si possono concatenare variabili e literals!
one = 'a ' print one 'string' print one + 'string' print 1 + 'string'
a string
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Indicizzazione delle stringheI caratteri di una stringa sono indicizzati e accessibili come in una lista, secondo lo schema:|S|i|l|v|e|r||:---:|:---:|:---:|:---:|:---:|:---:||0|1|2|3|4|5||-6|-5|-4|-3|-2|-1|
silver = 'Silver' print len(silver) print silver[0] print silver[5] print silver[-1] print silver[-6] print silver[6]
6 S r r S
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Possiamo perciò usare con le stringhe una tecnica molto usata anche per le liste e fondamentale in Python: lo 'slicing'
print silver[2:] print silver[:3] print silver[2:4] print silver[3:22] print silver[:-2]
lver Sil lv ver Silv
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Tuttavia, a differenza delle liste, le stringhe python sono **immutabili**
silver[1] = 'o' solver = silver[:1] + 'o' + silver[2:] print solver print " - ; | ".join(['A', 'B', 'C'])
A - ; | B - ; | C
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Metodi di utilità per le stringheIn Python, le stringhe sono oggetti dotati di un'ampia gamma di metodi per diverse funzioni (vedi [string methods](https://docs.python.org/2/library/stdtypes.htmlstring-methods)):
print 'find()', '->', silver.find('ver') print 'endswith()/startswith()', '->', silver.endswith('er'), silver.startswith('er') print 'lower()', '->', silver.lower() print 'lstrip()/rstrip()', '->', silver.lstrip('S'), silver.rstrip('S') print 'replace()', '->', silver.replace('er', 'an') print 'split()', '->', silver.s...
find() -> 3 endswith()/startswith() -> True False lower() -> silver lstrip()/rstrip() -> ilver Silver replace() -> Silvan split() -> ['Sil', 'er'] upper() -> SILVER join() -> A Silver hero
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Formattazione di stringheLe stringhe offrono anche l'operatore `%` (modulo). Si tratta di un operstore che consente di formattare e interpolare una stringa con diversi tipi di dato.
print u"%(superhero)s è stato creato da %(creator)s nel %(year)i" % { 'superhero': 'Silver Surfer', 'creator': ' e '.join(['Stan Lee', 'Jack Kirby']), 'year': 1966 } print u"{} è stato creato da {} nel {}".format('Silver Surfer', ' e '.join(['Stan Lee', 'Jack Kirby']), 1966)
_____no_output_____
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
UnicodeIn Python 2.* le stringhe sono intese come succesione di caratteri ASCII dove non esplicitamente codificate per mezzo dei metodi `encode()` e `decode()`. Le stringhe `unicode` vanno dichiarate come tali col carattere `u`.
u = u'Silver Surfer è nato a Zenn-La' u str(u) u.encode('utf-8') str(u.encode('utf-8'))
_____no_output_____
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
NumeriIn Python ci sono 4 tipi numerici principali: `plain integers`, `long integers`, `floating point numbers`, e `complex numbers`. I booleani sono un sottotipo di interi. - I `plain integers` hanno sempre almeno 32 bit di precisione (l'intero massimo è `sys.maxint` e il minimo `-sys.maxint - 1`). - I `Long integers...
import sys print sys.maxint print sys.float_info
_____no_output_____
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Operatori aritmetici
print 2 + 2 print 2 * 3 print 17 / 3 print 17 / 3.0 print 17 // 3.0 print 17 % 3 print 17 ** 3
4 6 5 5.66666666667 5.0 2 4913
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Conversioni
a, b, c = 2, 3.0, 3.5 print float(a), int(b), int(c), str(c), bool(c), bool(c - 3.5)
2.0 3 3 3.5 True False
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Gestione delle dateLe principali funzionalità per la gestione delle date sono incluse nei moduli `datetime`, `time` e `calendar` che si basano sullo standard Coordinated Universal Time (UTC). Le date sono **immutabili**.- `datetime.date` : date secondo il calendario gregoriano- `datetime.time` : tempo, considerando pe...
import datetime as dtt import time when = dtt.date(1966, 4, 28) now = dtt.time(16, 36) temp = dtt.datetime(when.year, when.month, when.day, now.hour, now.minute, now.second, now.microsecond) today = dtt.datetime.today() print when.day print when.month print when.year print now.hour, now.minute, now.second, now.microsec...
-18971 days, 4:40:04.205052 <type 'datetime.timedelta'> -1639077595.79 (2018, 14, 5) 2018-04-06 11:55:55.794948
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Conversione tra stringhe e date`strftime()` e `strptime()` convertono date in stringhe e viceversa secondo la seguente convenzione di formato.DirectiveMeaningExample%aWeekday as locale’sabbreviated name.Sun, Mon, …, Sat(en_US);So, Mo, …, Sa(de_DE)%AWeekday as locale’s full name.Sunday, Monday, …,Saturday (en_US);Sonnt...
print dtt.datetime.strftime(today, "%d/%m/%Y %I:%M:%S %p %z") from_string = dtt.datetime.strptime('6/12/1978 12:36:46', '%d/%m/%Y %H:%M:%S') print from_string
1978-12-06 12:36:46
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Put things together
silver_data = rowdata.split(';') print metadata.split(';') print silver_data
_____no_output_____
Apache-2.0
L02-datatypes.ipynb
dariomalchiodi/python-DS4EBF
Init Install packages
!pip install spacy !pip3 uninstall --quiet --yes tensorflow !pip3 install --quiet tensorflow-gpu==1.14.0 !pip3 install --quiet tensorflow-hub !pip3 install --quiet sentencepiece==0.1.83 !pip3 install --quiet tf-sentencepiece==0.1.83 !pip3 install --quiet simpleneighbors
Requirement already satisfied: spacy in /usr/local/lib/python3.6/dist-packages (2.1.8) Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.6/dist-packages (from spacy) (1.0.2) Requirement already satisfied: preshed<2.1.0,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from spacy) (2.0....
Unlicense
qa.ipynb
thingumajig/qa-prototype
Initialize grammar parser
import spacy nlp = spacy.load("en_core_web_sm") # doc = nlp("With respect to all losses caused by the peril of Flood, the Company shall not be liable, in the aggregate for any one Policy year, for more than its proportionate share of US$25,000,000.") # doc = nlp("The Program limit of liability is US$400,000,000.") # pr...
_____no_output_____
Unlicense
qa.ipynb
thingumajig/qa-prototype
Set up Tensorflow graph
%%time import tensorflow as tf import tensorflow_hub as hub import numpy as np import tf_sentencepiece # Set up graph. g = tf.Graph() with g.as_default(): questions_input = tf.placeholder(dtype=tf.string, shape=[None]) responses_input = tf.placeholder(dtype=tf.string, shape=[None]) contexts_input = tf.placeholde...
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /usr/local/lib/python3.6/dis...
Unlicense
qa.ipynb
thingumajig/qa-prototype
Run Initialize tensorflow session.
%%time # Initialize session. session = tf.Session(graph=g) session.run(init_op)
CPU times: user 10.5 s, sys: 2 s, total: 12.5 s Wall time: 14.3 s
Unlicense
qa.ipynb
thingumajig/qa-prototype
Tests
# %%time sentences = ''' F. PROGRAM LIMITS OF LIABILITY (1) The Program limit of liability is US$400,000,000. (2) Sublimits below are applicable to all direct physical loss, damage or destruction insured against, except an Accident. (a) With respect to all losses caused by the peril of Flood, the Company shall not...
Shape: (10, 512) Candidates: respect to all losses caused by the peril of Earthquake all losses caused by the peril of Earthquake the peril of Earthquake Earthquake the Company the aggregate for any one Policy year any one Policy year more than its proportionate share of US$ 50,000,000 its proportionate share ...
Unlicense
qa.ipynb
thingumajig/qa-prototype
Form
%%time #@title Question and answer text = "\u0410\u0441\u0442\u0440\u043E\u043D\u043E\u043C\u044B \u0418\u043D\u0441\u0442\u0438\u0442\u0443\u0442\u0430 \u0432\u043D\u0435\u0437\u0435\u043C\u043D\u043E\u0439 \u0444\u0438\u0437\u0438\u043A\u0438 \u041E\u0431\u0449\u0435\u0441\u0442\u0432\u0430 \u041C\u0430\u043A\u0441\...
Shape: (110, 512) Candidates: Астрономы Института внеземной физики Общества Макса Планка в Германии сообщили о всплеске активности неизвестного источника рентгеновских лучей в галактике NGC 300, расположенной в семи миллионах световых лет от Земли. Астрономы Института Института внеземной ...
Unlicense
qa.ipynb
thingumajig/qa-prototype
DAGVIZ Metro styling optionsThis notebook demonstrates the various Metro styling options.In order to apply styling we need to call `render_svg` by hand with the appropriate renderer and style configuration.
from dagviz import render_svg from dagviz.style.metro import svg_renderer, StyleConfig from IPython.display import HTML import networkx as nx
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
First we construct a simple graph that demonstrates all the visual aspects a rendering may have.
g = nx.DiGraph() g.add_node("a", label="switch(value)") g.add_node("b", label="case 1") g.add_node("c", label="case 2") g.add_node("d", label="case 3") g.add_node("e", label="end") g.add_edge("a", "b") g.add_edge("a", "c") g.add_edge("a", "d") g.add_edge("b", "e") g.add_edge("c", "e") g.add_edge("d", "e")
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Default renderingWithout any configuration, we get (of course) the default rendering:
HTML(render_svg(g))
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
ScaleThe *scale* setting determines the amount of space each node has:
HTML(render_svg(g, style=svg_renderer(StyleConfig(scale=20))))
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Node radiusThe *node radius* determines the size of the bubbles:
HTML(render_svg(g, style=svg_renderer(StyleConfig(node_radius=10))))
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Node fillBy default the node fill color is automatically selected. This can be overriden by specifying a fixed color:
HTML(render_svg(g, style=svg_renderer(StyleConfig(node_fill="black"))))
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Node strokeThe *node stroke* specifies the color of the border of the bubble:
HTML(render_svg(g, style=svg_renderer(StyleConfig(node_stroke="black"))))
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Node stroke widthThe *node stroke width* determines the width of the border of the bubbles:
HTML(render_svg(g, style=svg_renderer(StyleConfig(node_stroke="black", node_stroke_width=4))))
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Edge stroke widthThe *edge stroke width* determines the width of the edges:
HTML(render_svg(g, style=svg_renderer(StyleConfig(node_fill="black", edge_stroke_width=10))))
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Label font familyThe default font family for labels is "sans-serif". This can be changes too:
HTML(render_svg(g, style=svg_renderer(StyleConfig(label_font_family="serif"))))
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Label arrow strokeThe *label arrow stroke* determines the color of the line from node to label:
HTML(render_svg(g, style=svg_renderer(StyleConfig(label_arrow_stroke="black"))))
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Label arrow dash arrayThe *label arrow dash array* determines how the label arrow is dashed:
HTML(render_svg(g, style=svg_renderer(StyleConfig(label_arrow_dash_array="0"))))
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Arc radiusThe *arc radius* determines the radius of the arc from vertical line to a node:
HTML(render_svg(g, style=svg_renderer(StyleConfig(arc_radius=5)))) [".."]*4 "../"*4
_____no_output_____
Apache-2.0
notebooks/Metro styling.ipynb
WimYedema/dagviz
Copyright 2020 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/en-snapshot/addons/tutorials/time_stopping.ipynb
ilyaspiridonov/docs-l10n
TensorFlow Addons Callbacks: TimeStopping View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook OverviewThis notebook will demonstrate how to use TimeStopping Callback in TensorFlow Addons. Setup
import tensorflow_addons as tfa from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten
_____no_output_____
Apache-2.0
site/en-snapshot/addons/tutorials/time_stopping.ipynb
ilyaspiridonov/docs-l10n
Import and Normalize Data
# the data, split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() # normalize data x_train, x_test = x_train / 255.0, x_test / 255.0
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] - 0s 0us/step
Apache-2.0
site/en-snapshot/addons/tutorials/time_stopping.ipynb
ilyaspiridonov/docs-l10n
Build Simple MNIST CNN Model
# build the model using the Sequential API model = Sequential() model.add(Flatten(input_shape=(28, 28))) model.add(Dense(128, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(10, activation='softmax')) model.compile(optimizer='adam', loss = 'sparse_categorical_crossentropy', metr...
_____no_output_____
Apache-2.0
site/en-snapshot/addons/tutorials/time_stopping.ipynb
ilyaspiridonov/docs-l10n
Simple TimeStopping Usage
# initialize TimeStopping callback time_stopping_callback = tfa.callbacks.TimeStopping(seconds=5, verbose=1) # train the model with tqdm_callback # make sure to set verbose = 0 to disable # the default progress bar. model.fit(x_train, y_train, batch_size=64, epochs=100, callbacks=[time_s...
Train on 60000 samples, validate on 10000 samples Epoch 1/100 60000/60000 [==============================] - 5s 81us/sample - loss: 0.3432 - accuracy: 0.9003 - val_loss: 0.1601 - val_accuracy: 0.9529 Epoch 2/100 60000/60000 [==============================] - 4s 67us/sample - loss: 0.1651 - accuracy: 0.9515 - val_loss: ...
Apache-2.0
site/en-snapshot/addons/tutorials/time_stopping.ipynb
ilyaspiridonov/docs-l10n
Change to Quest for Orthologs 2019 data directory
cd ~/data_sm/kmer-hashing/quest-for-orthologs/data/2019/ ls -lha
total 2.6G drwxr-xr-x 5 olga root 4.0K Jan 10 08:02 ./ drwxr-xr-x 3 olga root 4.0K Dec 25 17:48 ../ drwxr-xr-x 5 olga czb 4.0K Dec 26 19:44 Archaea/ drwxr-xr-x 5 olga czb 16K Dec 26 19:44 Bacteria/ drwxr-xr-x 8 olga czb 32K Jan 8 08:13 Eukaryota/ -rw...
MIT
notebooks/521_subset_human_retina_genes.ipynb
czbiohub/kh-analysis
Get Retinal gene names from
s = 'RHO GNAT1 GNB1 GNGT1 OPN1SW OPN1MW GNAT2 GNB3 GNGT2 PDE6A PDE6B PDE6G PDE6C PDE6H SAG ARR3 RGS9 CNGA1 CNGA3 CNGB1 CNGB3 GRK1 GRK7 RCVRN GUCA1A GUCA1B GUCY2D GUCY2F' genes = s.split() genes len(genes) ensembl_rest.lookup_post(genes[0]) s = 'P08100 P11488 P62873 P63211 P03999 P04001 P19087 P16520 O14610 PDE6A PDE6B...
_____no_output_____
MIT
notebooks/521_subset_human_retina_genes.ipynb
czbiohub/kh-analysis
Read Human ID mapping
human_id_mapping = pd.read_csv('Eukaryota/UP000005640_9606.idmapping', sep='\t', header=None, names=['uniprot_id', 'id_type', 'db_id']) human_id_mapping.columns = 'source__' + human_id_mapping.columns print(human_id_mapping.shape) human_id_mapping.head()
(2668934, 3)
MIT
notebooks/521_subset_human_retina_genes.ipynb
czbiohub/kh-analysis
Extract with gene symbsls
human_id_mapping_symbols = human_id_mapping.query('source__db_id in @genes_to_ids.symbol') print(human_id_mapping_symbols.shape) human_id_mapping_symbols.head() human_id_mapping_symbols.source__db_id.nunique()
_____no_output_____
MIT
notebooks/521_subset_human_retina_genes.ipynb
czbiohub/kh-analysis
Extract with uniprot ids
human_id_mapping_uniprot = human_id_mapping.query('source__db_id in @genes_to_ids.uniprot_id') print(human_id_mapping_uniprot.shape) human_id_mapping_uniprot.head() "RHO" in human_id_mapping.source__db_id.values
_____no_output_____
MIT
notebooks/521_subset_human_retina_genes.ipynb
czbiohub/kh-analysis
Get ENSMBL ids
visual_uniprot_ids = set(human_id_mapping_uniprot.source__uniprot_id) | set(human_id_mapping_symbols.source__uniprot_id) len(visual_uniprot_ids) human_id_mapping_visual_system = human_id_mapping.query('source__uniprot_id in @visual_uniprot_ids') human_id_mapping_visual_system.head()
_____no_output_____
MIT
notebooks/521_subset_human_retina_genes.ipynb
czbiohub/kh-analysis
Concatenate all human mappings
human_retina_ids = pd.concat([human_id_mapping_symbols, human_id_mapping_uniprot], ignore_index=True) human_retina_ids = human_retina_ids.drop_duplicates() print(human_retina_ids.shape) human_retina_ids.head()
(202, 3)
MIT
notebooks/521_subset_human_retina_genes.ipynb
czbiohub/kh-analysis
Write human retinal genes with uniprot IDs to disk
pwd human_id_mapping_visual_system.to_csv("human_visual_transduction_with_uniprot_ids.csv", index=False) human_id_mapping_visual_system.to_csv("human_visual_transduction_with_uniprot_ids.csv.gz", index=False) human_id_mapping_visual_system.to_parquet("human_visual_transduction_with_uniprot_ids.parquet", index=False)
_____no_output_____
MIT
notebooks/521_subset_human_retina_genes.ipynb
czbiohub/kh-analysis
Read human proteins and subset to human tfs
retinal_uniprot = set(human_retina_ids.source__uniprot_id) len(retinal_uniprot) tf_records = [] for filename in glob.iglob('Eukaryota/human-protein-fastas/*.fasta'): with screed.open(filename) as records: for record in records: name = record['name'] record_id = name.split()[0] ...
_____no_output_____
MIT
notebooks/521_subset_human_retina_genes.ipynb
czbiohub/kh-analysis