markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Visualizando o histograma da imagem com realce de contraste
Observe que quanto menor a largura da janela, mais pixels terão valores 0 e 255.
Quando de visualiza seu histograma, aparecerá um grande pico nestes dois valores
que são o extremo do histograma. Para evitar que estes valores entrem no plot,
faz-se um fatiament... | hg = ia.histogram(g)
plt.figure(1)
plt.plot(hg),plt.title('Histograma da Imagens realçada')
plt.show()
plt.figure(2)
plt.plot(hg[1:-1]),plt.title('Idem, porém sem valores 0 e 255')
plt.show() | master/tutorial_contraste_iterativo_2.ipynb | robertoalotufo/ia898 | mit |
Loading a network is easy. caffe.Classifier takes care of everything. Note the arguments for configuring input preprocessing: mean subtraction switched on by giving a mean array, input channel swapping takes care of mapping RGB into the reference ImageNet model's BGR order, and raw scaling multiplies the feature scale ... | caffe.set_mode_cpu()
net = caffe.Classifier(MODEL_FILE, PRETRAINED,
mean=np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1),
channel_swap=(2,1,0),
raw_scale=255,
image_dims=(256, 256)) | examples/classification.ipynb | gogartom/caffe-textmaps | mit |
Let's take a look at our example image with Caffe's image loading helper. | input_image = caffe.io.load_image(IMAGE_FILE)
plt.imshow(input_image) | examples/classification.ipynb | gogartom/caffe-textmaps | mit |
Time to classify. The default is to actually do 10 predictions, cropping the center and corners of the image as well as their mirrored versions, and average over the predictions: | prediction = net.predict([input_image]) # predict takes any number of images, and formats them for the Caffe net automatically
print 'prediction shape:', prediction[0].shape
plt.plot(prediction[0])
print 'predicted class:', prediction[0].argmax() | examples/classification.ipynb | gogartom/caffe-textmaps | mit |
You can see that the prediction is 1000-dimensional, and is pretty sparse.
The predicted class 281 is "Tabby cat." Our pretrained model uses the synset ID ordering of the classes, as listed in ../data/ilsvrc12/synset_words.txt if you fetch the auxiliary imagenet data by ../data/ilsvrc12/get_ilsvrc_aux.sh. If you look a... | prediction = net.predict([input_image], oversample=False)
print 'prediction shape:', prediction[0].shape
plt.plot(prediction[0])
print 'predicted class:', prediction[0].argmax() | examples/classification.ipynb | gogartom/caffe-textmaps | mit |
Now, why don't we see how long it takes to perform the classification end to end? This result is run from an Intel i5 CPU, so you may observe some performance differences. | %timeit net.predict([input_image]) | examples/classification.ipynb | gogartom/caffe-textmaps | mit |
It may look a little slow, but note that time is spent on cropping, python interfacing, and running 10 images. For performance, if you really want to make prediction fast, you can optionally code in C++ and pipeline operations better. For experimenting and prototyping the current speed is fine.
Let's time classifying a... | # Resize the image to the standard (256, 256) and oversample net input sized crops.
input_oversampled = caffe.io.oversample([caffe.io.resize_image(input_image, net.image_dims)], net.crop_dims)
# 'data' is the input blob name in the model definition, so we preprocess for that input.
caffe_input = np.asarray([net.transfo... | examples/classification.ipynb | gogartom/caffe-textmaps | mit |
OK, so how about GPU? it is actually pretty easy: | caffe.set_mode_gpu() | examples/classification.ipynb | gogartom/caffe-textmaps | mit |
Voila! Now we are in GPU mode. Let's see if the code gives the same result: | prediction = net.predict([input_image])
print 'prediction shape:', prediction[0].shape
plt.plot(prediction[0]) | examples/classification.ipynb | gogartom/caffe-textmaps | mit |
Good, everything is the same. And how about time consumption? The following benchmark is obtained on the same machine with a GTX 770 GPU: | # Full pipeline timing.
%timeit net.predict([input_image])
# Forward pass timing.
%timeit net.forward(data=caffe_input) | examples/classification.ipynb | gogartom/caffe-textmaps | mit |
If you've set up your environment properly, this cell should run without problems: | import math
import numpy as np
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
from datascience import *
from client.api.notebook import Notebook
ok = Notebook('hw1.ok') | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Now, run this cell to log into OkPy.
This is the submission system for the class; you will use this
website to confirm that you've submitted your assignment. | ok.auth(inline=True) | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
2. Python
Python is the main programming language we'll use in this course. We assume you have some experience with Python or can learn it yourself, but here is a brief review.
Below are some simple Python code fragments.
You should feel confident explaining what each fragment is doing. If not,
please brush up on your... | 2 + 2
# This is a comment.
# In Python, the ** operator performs exponentiation.
math.e**(-2)
print("Hello" + ",", "world!")
"Hello, cell output!"
def add2(x):
"""This docstring explains what this function does: it adds 2 to a number."""
return x + 2
def makeAdder(amount):
"""Make a function that adds t... | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 1
Question 1a
Write a function nums_reversed that takes in an integer n and returns a string
containing the numbers 1 through n including n in reverse order, separated
by spaces. For example:
>>> nums_reversed(5)
'5 4 3 2 1'
Note: The ellipsis (...) indicates something you should fill in. It doesn't... | def nums_reversed(n):
...
_ = ok.grade('q01a')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 1b
Write a function string_splosion that takes in a non-empty string like
"Code" and returns a long string containing every prefix of the input.
For example:
>>> string_splosion('Code')
'CCoCodCode'
>>> string_splosion('data!')
'ddadatdatadata!'
>>> string_splosion('hi')
'hhi' | def string_splosion(string):
...
_ = ok.grade('q01b')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 1c
Write a function double100 that takes in a list of integers
and returns True only if the list has two 100s next to each other.
>>> double100([100, 2, 3, 100])
False
>>> double100([2, 3, 100, 100, 5])
True | def double100(nums):
...
_ = ok.grade('q01c')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 1d
Write a function median that takes in a list of numbers
and returns the median element of the list. If the list has even
length, it returns the mean of the two elements in the middle.
>>> median([5, 4, 3, 2, 1])
3
>>> median([ 40, 30, 10, 20 ])
25 | def median(number_list):
...
_ = ok.grade('q01d')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
3. NumPy
The NumPy library lets us do fast, simple computing with numbers in Python.
3.1. Arrays
The basic NumPy data type is the array, a homogeneously-typed sequential collection (a list of things that all have the same type). Arrays will most often contain strings, numbers, or other arrays.
Let's create some arrays... | array1 = np.array([2, 3, 4, 5])
array2 = np.arange(4)
array1, array2 | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Math operations on arrays happen element-wise. Here's what we mean: | array1 * 2
array1 * array2
array1 ** array2 | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
This is not only very convenient (fewer for loops!) but also fast. NumPy is designed to run operations on arrays much faster than equivalent Python code on lists. Data science sometimes involves working with large datasets where speed is important - even the constant factors!
Jupyter pro-tip: Pull up the docs for any f... | np.arange? | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Another Jupyter pro-tip: Pull up the docs for any function in Jupyter by typing the function
name, then <Shift>-<Tab> on your keyboard. Super convenient when you forget the order
of the arguments to a function. You can press <Tab> multiple tabs to expand the docs.
Try it on the function below: | np.linspace | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 2
Using the np.linspace function, create an array called xs that contains
100 evenly spaced points between 0 and 2 * np.pi. Then, create an array called ys that
contains the value of $ \sin{x} $ at each of those 100 points.
Hint: Use the np.sin function. You should be able to define each variable with one line... | xs = ...
ys = ...
_ = ok.grade('q02')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
The plt.plot function from another library called matplotlib lets us make plots. It takes in
an array of x-values and a corresponding array of y-values. It makes a scatter plot of the (x, y) pairs and connects points with line segments. If you give it enough points, it will appear to create a smooth curve.
Let's plot... | plt.plot(xs, ys) | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
This is a useful recipe for plotting any function:
1. Use linspace or arange to make a range of x-values.
2. Apply the function to each point to produce y-values.
3. Plot the points.
You might remember from calculus that the derivative of the sin function is the cos function. That means that the slope of the curve you... | # Try plotting cos here. | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Calculating derivatives is an important operation in data science, but it can be difficult. We can have computers do it for us using a simple idea called numerical differentiation.
Consider the ith point (xs[i], ys[i]). The slope of sin at xs[i] is roughly the slope of the line connecting (xs[i], ys[i]) to the nearby... | def derivative(xvals, yvals):
...
slopes = ...
slopes[:5]
_ = ok.grade('q03')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 4
Plot the slopes you computed. Then plot cos on top of your plot, calling plt.plot again in the same cell. Did numerical differentiation work?
Note: Since we have only 99 slopes, you'll need to take off the last x-value before plotting to avoid an error. | ...
... | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
In the plot above, it's probably not clear which curve is which. Examine the cell below to see how to plot your results with a legend. | plt.plot(xs[:-1], slopes, label="Numerical derivative")
plt.plot(xs[:-1], np.cos(xs[:-1]), label="True derivative")
# You can just call plt.legend(), but the legend will cover up
# some of the graph. Use bbox_to_anchor=(x,y) to set the x-
# and y-coordinates of the center-left point of the legend,
# where, for example... | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
3.2. Multidimensional Arrays
A multidimensional array is a primitive version of a table, containing only one kind of data and having no column labels. A 2-dimensional array is useful for working with matrices of numbers. | # The zeros function creates an array with the given shape.
# For a 2-dimensional array like this one, the first
# coordinate says how far the array goes *down*, and the
# second says how far it goes *right*.
array3 = np.zeros((4, 5))
array3
# The shape attribute returns the dimensions of the array.
array3.shape
# Yo... | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Arrays allow you to assign to multiple places at once. The special character : means "everything." | array4 = np.zeros((3, 5))
array4[:, 2] = 5
array4 | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
In fact, you can use arrays of indices to assign to multiple places. Study the next example and make sure you understand how it works. | array5 = np.zeros((3, 5))
rows = np.array([1, 0, 2])
cols = np.array([3, 1, 4])
# Indices (1,3), (0,1), and (2,4) will be set.
array5[rows, cols] = 3
array5 | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 5
Create a 50x50 array called twice_identity that contains all zeros except on the
diagonal, where it contains the value 2.
Start by making a 50x50 array of all zeros, then set the values. Use indexing, not a for loop! (Don't use np.eye either, though you might find that function useful later.) | twice_identity = ...
...
twice_identity
_ = ok.grade('q05')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
4. A Picture Puzzle
Your boss has given you some strange text files. He says they're images,
some of which depict a summer scene and the rest a winter scene.
He demands that you figure out how to determine whether a given
text file represents a summer scene or a winter scene.
You receive 10 files, 1.txt through 10.txt.... | def read_file_lines(filename):
...
...
file1 = ...
file1[:5]
_ = ok.grade('q07')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Each file begins with a line containing two numbers. After checking the length of
a file, you could notice that the product of these two numbers equals the number of
lines in each file (other than the first one).
This suggests the rows represent elements in a 2-dimensional grid. In fact, each
dataset represents an im... | def lines_to_image(file_lines):
...
image_array = ...
# Make sure to call astype like this on the 3-dimensional array
# you produce, before returning it.
return image_array.astype(np.uint8)
image1 = ...
image1.shape
_ = ok.grade('q08')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 9
Images in numpy are simply arrays, but we can also display them them as
actual images in this notebook.
Use the provided show_images function to display image1. You may call it
like show_images(image1). If you later have multiple images to display, you
can call show_images([image1, image2]) to display them a... | def show_images(images, ncols=2, figsize=(10, 7), **kwargs):
"""
Shows one or more color images.
images: Image or list of images. Each image is a 3-dimensional
array, where dimension 1 indexes height and dimension 2
the width. Dimension 3 indexes the 3 color values red,
... | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 10
If you look at the data, you'll notice all the numbers lie between 0 and 10.
In NumPy, a color intensity is an integer ranging from 0 to 255, where 0 is
no color (black). That's why the image is almost black. To see the image,
we'll need to rescale the numbers in the data to have a larger range.
Define a ... | # This array is provided for your convenience.
transformed = np.array([12, 37, 65, 89, 114, 137, 162, 187, 214, 240, 250])
def expand_image_range(image):
...
expanded1 = ...
show_images(expanded1)
_ = ok.grade('q10')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 11
Eureka! You've managed to reveal the image that the text file represents.
Now, define a function called reveal_file that takes in a filename
and returns an expanded image. This should be relatively easy since you've
defined functions for each step in the process.
Then, set expanded_images to a list of all t... | def reveal_file(filename):
...
filenames = ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt',
'6.txt', '7.txt', '8.txt', '9.txt', '10.txt']
expanded_images = ...
show_images(expanded_images, ncols=5) | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Notice that 5 of the above images are of summer scenes; the other 5
are of winter.
Think about how you'd distinguish between pictures of summer and winter. What
qualities of the image seem to signal to your brain that the image is one of
summer? Of winter?
One trait that seems specific to summer pictures is that the co... | def proportion_by_channel(image):
...
image_proportions = ...
image_proportions
_ = ok.grade('q12')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Let's plot the proportions you computed above on a bar chart: | # You'll learn about Pandas and DataFrames soon.
import pandas as pd
pd.DataFrame({
'red': image_proportions[:, 0],
'green': image_proportions[:, 1],
'blue': image_proportions[:, 2]
}, index=pd.Series(['Image {}'.format(n) for n in range(1, 11)], name='image'))\
.iloc[::-1]\
.plot.ba... | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Question 13
What do you notice about the colors present in the summer images compared to
the winter ones?
Use this info to write a function summer_or_winter. It takes in an image and
returns True if the image is a summer image and False if the image is a
winter image.
Do not hard-code the function to the 10 images you ... | def summer_or_winter(image):
...
_ = ok.grade('q13')
_ = ok.backup() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Congrats! You've created your very first classifier for this class.
Question 14
How do you think your classification function will perform
in general?
Why do you think it will perform that way?
What do you think would most likely give you false positives?
False negatives?
Write your answer here, replacing this tex... | import skimage as sk
import skimage.io as skio
def read_image(filename):
'''Reads in an image from a filename'''
return skio.imread(filename)
def compress_image(im):
'''Takes an image as an array and compresses it to look black.'''
res = im / 25
return res.astype(np.uint8)
def to_text_file(im, fi... | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
5. Submitting this assignment
First, run this cell to run all the autograder tests at once so you can double-
check your work. | _ = ok.grade_all() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
Now, run this code in your terminal to make a
git commit
that saves a snapshot of your changes in git. The last line of the cell
runs git push, which will send your work to your personal Github repo.
```
Tell git to commit all the changes so far
git add -A
Tell git to make the commit
git commit -m "hw1 finished"
Send y... | # Now, we'll submit to okpy
_ = ok.submit() | sp17/hw/hw1/hw1.ipynb | DS-100/sp17-materials | gpl-3.0 |
First: load and "featurize"
Featurization refers to the process of converting the conformational
snapshots from your MD trajectories into vectors in some space $\mathbb{R}^N$ that can be manipulated and modeled by subsequent analyses. The Gaussian HMM, for instance, uses Gaussian emission distributions, so it models th... | print(AlanineDipeptide.description())
dataset = AlanineDipeptide().get()
trajectories = dataset.trajectories
topology = trajectories[0].topology
indices = [atom.index for atom in topology.atoms if atom.element.symbol in ['C', 'O', 'N']]
featurizer = SuperposeFeaturizer(indices, trajectories[0][0])
sequences = featuri... | examples/hmm-and-msm.ipynb | dotsdl/msmbuilder | lgpl-2.1 |
Now sequences is our featurized data. | lag_times = [1, 10, 20, 30, 40]
hmm_ts0 = {}
hmm_ts1 = {}
n_states = [3, 5]
for n in n_states:
hmm_ts0[n] = []
hmm_ts1[n] = []
for lag_time in lag_times:
strided_data = [s[i::lag_time] for s in sequences for i in range(lag_time)]
hmm = GaussianFusionHMM(n_states=n, n_features=sequences[0].s... | examples/hmm-and-msm.ipynb | dotsdl/msmbuilder | lgpl-2.1 |
Vertex AI Pipelines: TPU model train, upload, and deploy using google-cloud-pipeline-components
<table align="left">
<td>
<a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy... | import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Install the latest GA version of google-cloud-pipeline-components library as well. | ! pip3 install $USER_FLAG kfp google-cloud-pipeline-components --upgrade | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
When you initialize the Vertex AI SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.
S... | BUCKET_URI = "gs://[your-bucket-name]" # @param {type:"string"}
if BUCKET_URI == "" or BUCKET_URI is None or BUCKET_URI == "gs://[your-bucket-name]":
BUCKET_URI = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Service Account
If you don't know your service account, try to get your service account using gcloud command by executing the second cell below. | SERVICE_ACCOUNT = "[your-service-account]" # @param {type:"string"}
if (
SERVICE_ACCOUNT == ""
or SERVICE_ACCOUNT is None
or SERVICE_ACCOUNT == "[your-service-account]"
):
# Get your GCP project id from gcloud
shell_output = !gcloud auth list 2>/dev/null
SERVICE_ACCOUNT = shell_output[2].strip... | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Set service account access for Vertex AI Pipelines
Run the following commands to grant your service account access to read and write pipeline artifacts in the bucket that you created in the previous step -- you only need to run these once per service account. | ! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator $BUCKET_URI
! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer $BUCKET_URI | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Vertex AI Pipelines constants
Setup up the following constants for Vertex AI Pipelines: | PIPELINE_ROOT = "{}/pipeline_root/tpu_cifar10_pipeline".format(BUCKET_URI) | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Additional imports. | import kfp
from google_cloud_pipeline_components import aiplatform as gcc_aip
from kfp.v2.dsl import component
from kfp.v2.google import experimental | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Initialize Vertex AI SDK for Python
Initialize the Vertex AI SDK for Python for your project and corresponding bucket. | aip.init(project=PROJECT_ID, staging_bucket=BUCKET_URI) | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Set up variables
Next, set up some variables used throughout the tutorial.
Set hardware accelerators
You can set hardware accelerators for both training and prediction.
Set the variables TRAIN_TPU/TRAIN_NTPU to use a container training image supporting a TPU and the number of TPUs allocated and DEPLOY_GPU/DEPLOY_NGPU t... | from google.cloud.aiplatform import gapic
# Use TPU Accelerators. Temporarily using numeric codes, until types are added to the SDK
# 6 = TPU_V2
# 7 = TPU_V3
TRAIN_TPU, TRAIN_NTPU = (7, 8) # Using TPU_V3 with 8 accelerators
DEPLOY_GPU, DEPLOY_NGPU = (gapic.AcceleratorType.NVIDIA_TESLA_K80, 1) | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Set pre-built containers
Vertex AI provides pre-built containers to run training and prediction.
For the latest list, see Pre-built containers for training and Pre-built containers for prediction | DEPLOY_VERSION = "tf2-gpu.2-6"
DEPLOY_IMAGE = "us-docker.pkg.dev/cloud-aiplatform/prediction/{}:latest".format(
DEPLOY_VERSION
)
print("Deployment:", DEPLOY_IMAGE, DEPLOY_GPU, DEPLOY_NGPU) | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Set machine types
Next, set the machine types to use for training and prediction.
Set the variables TRAIN_COMPUTE and DEPLOY_COMPUTE to configure your compute resources for training and prediction.
machine type
cloud-tpu : used for TPU training. See the TPU Architecture site for details
n1-standard: 3.75GB of memory p... | MACHINE_TYPE = "cloud-tpu"
# TPU VMs do not require VCPU definition
TRAIN_COMPUTE = MACHINE_TYPE
print("Train machine type", TRAIN_COMPUTE)
MACHINE_TYPE = "n1-standard"
VCPU = "4"
DEPLOY_COMPUTE = MACHINE_TYPE + "-" + VCPU
print("Deploy machine type", DEPLOY_COMPUTE)
if not TRAIN_NTPU or TRAIN_NTPU < 2:
TRAIN_S... | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Create a custom container
We will create a directory and write all of our container build artifacts into that folder. | CONTAINER_ARTIFACTS_DIR = "tpu-container-artifacts"
!mkdir {CONTAINER_ARTIFACTS_DIR}
import os | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Write the Dockerfile | dockerfile = """FROM python:3.8
WORKDIR /root
# Copies the trainer code to the docker image.
COPY train.py /root/train.py
RUN pip3 install tensorflow-datasets
# Install TPU Tensorflow and dependencies.
# libtpu.so must be under the '/lib' directory.
RUN wget https://storage.googleapis.com/cloud-tpu-tpuvm-artifacts/... | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Training script
In the next cell, you write the contents of the training script, train.py. In summary:
Get the directory where to save the model artifacts from the environment variable AIP_MODEL_DIR. This variable is set by the training service.
Loads CIFAR10 dataset from TF Datasets (tfds).
Builds a model using TF.Ke... | %%writefile {CONTAINER_ARTIFACTS_DIR}/train.py
# Single, Mirror and Multi-Machine Distributed Training for CIFAR-10
import tensorflow_datasets as tfds
import tensorflow as tf
from tensorflow.python.client import device_lib
import argparse
import os
import sys
tfds.disable_progress_bar()
parser = argparse.ArgumentPars... | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Build Container
Run these artifact registry and docker steps once | !gcloud services enable artifactregistry.googleapis.com
!sudo usermod -a -G docker ${USER}
REPOSITORY = "tpu-training-repository"
IMAGE = "tpu-train"
!gcloud auth configure-docker us-central1-docker.pkg.dev --quiet
!gcloud artifacts repositories create $REPOSITORY --repository-format=docker \
--location=us-central1... | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Build the training image | TRAIN_IMAGE = f"{REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}:latest"
print(TRAIN_IMAGE)
%cd $CONTAINER_ARTIFACTS_DIR
# Use quiet flag as the output is fairly large
!docker build --quiet \
--tag={TRAIN_IMAGE} \
.
!docker push {TRAIN_IMAGE}
%cd .. | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Define custom model pipeline that uses components from google_cloud_pipeline_components
Next, you define the pipeline.
The experimental.run_as_aiplatform_custom_job method takes as arguments the previously defined component, and the list of worker_pool_specs— in this case one— with which the custom training job is conf... | WORKER_POOL_SPECS = [
{
"containerSpec": {
"args": TRAINER_ARGS,
"env": [{"name": "AIP_MODEL_DIR", "value": WORKING_DIR}],
"imageUri": TRAIN_IMAGE,
},
"replicaCount": "1",
"machineSpec": {
"machineType": TRAIN_COMPUTE,
"acce... | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Define pipeline components
The following example define a custom pipeline component for this tutorial:
This component doesn't do anything (but run a print statement). | @component
def tpu_training_task_op(input1: str):
print("training task: {}".format(input1)) | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
The pipeline has four main steps:
1) The run_as_experimental_custom_job runs the docker container which will execute the training task
2) The ModelUploadOp uploads the trained model to Vertex
3) The EndpointCreateOp creates the model endpoint
4) Finally, the ModelDeployOp deploys the model to the endpoint | @kfp.dsl.pipeline(name="train-endpoint-deploy" + TIMESTAMP)
def pipeline(
project: str = PROJECT_ID,
model_display_name: str = MODEL_DISPLAY_NAME,
serving_container_image_uri: str = DEPLOY_IMAGE,
):
train_task = tpu_training_task_op("tpu model training")
experimental.run_as_aiplatform_custom_job(
... | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Compile the pipeline
Next, compile the pipeline. | from kfp.v2 import compiler # noqa: F811
compiler.Compiler().compile(
pipeline_func=pipeline,
package_path="tpu train cifar10_pipeline.json".replace(" ", "_"),
) | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Run the pipeline
Next, run the pipeline. | DISPLAY_NAME = "tpu_cifar10_training_" + TIMESTAMP
job = aip.PipelineJob(
display_name=DISPLAY_NAME,
template_path="tpu train cifar10_pipeline.json".replace(" ", "_"),
pipeline_root=PIPELINE_ROOT,
)
job.run()
! rm tpu_train_cifar10_pipeline.json | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Click on the generated link to see your run in the Cloud Console.
In the UI, many of the pipeline DAG nodes will expand or collapse when you click on them. Here is a partially-expanded view of the DAG (click image to see larger version).
Cleaning up
To clean up all Google Cloud resources used in this project, you can ... | delete_dataset = True
delete_pipeline = True
delete_model = True
delete_endpoint = True
delete_batchjob = True
delete_customjob = True
delete_hptjob = True
# Warning: Setting this to true will delete everything in your bucket
delete_bucket = False
try:
if delete_model and "DISPLAY_NAME" in globals():
mode... | notebooks/community/pipelines/google_cloud_pipeline_components_TPU_model_train_upload_deploy.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Loading Data
First, we want to create our word vectors. For simplicity, we're going to be using a pretrained model.
As one of the biggest players in the ML game, Google was able to train a Word2Vec model on a massive Google News dataset that contained over 100 billion different words! From that model, Google was able ... | # data from: http://ai.stanford.edu/~amaas/data/sentiment/
TRAIN_INPUT = 'data/train.csv'
TEST_INPUT = 'data/test.csv'
# data manually generated
MY_TEST_INPUT = 'data/mytest.csv'
# wordtovec
# https://nlp.stanford.edu/projects/glove/
# the matrix will contain 400,000 word vectors, each with a dimensionality of 50.
wo... | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
We can also search our word list for a word like "baseball", and then access its corresponding vector through the embedding matrix. | baseball_index = word_list.index('baseball')
print('Example: baseball')
print(word_vector[baseball_index]) | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Now that we have our vectors, our first step is taking an input sentence and then constructing the its vector representation. Let's say that we have the input sentence "I thought the movie was incredible and inspiring". In order to get the word vectors, we can use Tensorflow's embedding lookup function. This function t... | max_seq_length = 10 # maximum length of sentence
num_dims = 50 # dimensions for each word vector
first_sentence = np.zeros((max_seq_length), dtype='int32')
first_sentence[0] = word_list.index("i")
first_sentence[1] = word_list.index("thought")
first_sentence[2] = word_list.index("the")
first_sentence[3] = word_list.in... | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
TODO### Insert image
The 10 x 50 output should contain the 50 dimensional word vectors for each of the 10 words in the sequence. | with tf.Session() as sess:
print(tf.nn.embedding_lookup(word_vector, first_sentence).eval().shape) | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Before creating the ids matrix for the whole training set, let’s first take some time to visualize the type of data that we have. This will help us determine the best value for setting our maximum sequence length. In the previous example, we used a max length of 10, but this value is largely dependent on the inputs you... | from os import listdir
from os.path import isfile, join
positiveFiles = ['positiveReviews/' + f for f in listdir('positiveReviews/') if isfile(join('positiveReviews/', f))]
negativeFiles = ['negativeReviews/' + f for f in listdir('negativeReviews/') if isfile(join('negativeReviews/', f))]
numWords = []
for pf in positi... | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
We can also use the Matplot library to visualize this data in a histogram format. | import matplotlib.pyplot as plt
%matplotlib inline
plt.hist(numWords, 50)
plt.xlabel('Sequence Length')
plt.ylabel('Frequency')
plt.axis([0, 1200, 0, 8000])
plt.show() | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
From the histogram as well as the average number of words per file, we can safely say that most reviews will fall under 250 words, which is the max sequence length value we will set. | max_seq_len = 250 | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Data | ids_matrix = np.load('ids_matrix.npy').tolist() | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Parameters | # Parameters for training
STEPS = 100000
BATCH_SIZE = 64
# Parameters for data processing
REVIEW_KEY = 'review'
SEQUENCE_LENGTH_KEY = 'sequence_length' | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Separating train and test data
The training set we're going to use is the Imdb movie review dataset. This set has 25,000 movie reviews, with 12,500 positive reviews and 12,500 negative reviews.
Let's first give a positive label [1, 0] to the first 12500 reviews, and a negative label [0, 1] to the other reviews. | POSITIVE_REVIEWS = 12500
# copying sequences
data_sequences = [np.asarray(v, dtype=np.int32) for v in ids_matrix]
# generating labels
data_labels = [[1, 0] if i < POSITIVE_REVIEWS else [0, 1] for i in range(len(ids_matrix))]
# also creating a length column, this will be used by the Dynamic RNN
# see more about it here... | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Then, let's shuffle the data and use 90% of the reviews for training and the other 10% for testing. | data = list(zip(data_sequences, data_labels, data_length))
random.shuffle(data) # shuffle
data = np.asarray(data)
# separating train and test data
limit = int(len(data) * 0.9)
train_data = data[:limit]
test_data = data[limit:] | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Verifying if the train and test data have enough positive and negative examples | LABEL_INDEX = 1
def _number_of_pos_labels(df):
pos_labels = 0
for value in df:
if value[LABEL_INDEX] == [1, 0]:
pos_labels += 1
return pos_labels
pos_labels_train = _number_of_pos_labels(train_data)
total_labels_train = len(train_data)
pos_labels_test = _number_of_pos_labels(test_data)... | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Input functions | def get_input_fn(df, batch_size, num_epochs=1, shuffle=True):
def input_fn():
# https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/data
sequences = np.asarray([v for v in df[:,0]], dtype=np.int32)
labels = np.asarray([v for v in df[:,1]], dtype=np.int32)
length... | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Creating the Estimator model | def get_model_fn(rnn_cell_sizes,
label_dimension,
dnn_layer_sizes=[],
optimizer='SGD',
learning_rate=0.01,
embed_dim=128):
def model_fn(features, labels, mode):
review = features[REVIEW_KEY]
sequence_l... | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Create and Run Experiment | # create experiment
def generate_experiment_fn():
"""
Create an experiment function given hyperparameters.
Returns:
A function (output_dir) -> Experiment where output_dir is a string
representing the location of summaries, checkpoints, and exports.
this function is used by... | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Making Predictions
Let's generate our own sentence to see how the model classifies them. | def generate_data_row(sentence, label):
length = max_seq_length
sequence = np.zeros((length), dtype='int32')
for i, word in enumerate(sentence):
sequence[i] = word_list.index(word)
return sequence, label, length
data_sequences = [np.asarray(v, dtype=np.int32) for v in ids_matrix]
# gen... | code_samples/RNN/sentiment_analysis/.ipynb_checkpoints/SentimentAnalysis-batch_64-checkpoint.ipynb | mari-linhares/tensorflow-workshop | apache-2.0 |
Let's add a color column. | def addcolor(addition):
return additionToColor[addition]
wtb['color'] = np.vectorize(addcolor)(wtb['addition']) | notebooks/Colors.ipynb | jamesnw/wtb-data | mit |
Now group by the new color column, get the mean, and sort the values high to low. | wtb.groupby(by='color').mean().sort_values('vote',ascending=False) | notebooks/Colors.ipynb | jamesnw/wtb-data | mit |
There we have it. Blue is the best tasting color.
But brown is awfully close. I wonder how the ranges compare. Let's take a look at a histogram. | %matplotlib inline
wtb.groupby(by='color').boxplot(subplots=False,rot=45) | notebooks/Colors.ipynb | jamesnw/wtb-data | mit |
Create and convert a TensorFlow model
This notebook is designed to demonstrate the process of creating a TensorFlow model and converting it to use with TensorFlow Lite. The model created in this notebook is used in the hello_world sample for TensorFlow Lite for Microcontrollers.
<table class="tfo-notebook-buttons" alig... | # TensorFlow is an open source machine learning library
import tensorflow as tf
# Numpy is a math library
import numpy as np
# Matplotlib is a graphing library
import matplotlib.pyplot as plt
# math is Python's math library
import math | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Generate data
Deep learning networks learn to model patterns in underlying data. In this notebook, we're going to train a network to model data generated by a sine function. This will result in a model that can take a value, x, and predict its sine, y.
In a real world application, if you needed the sine of x, you could... | # We'll generate this many sample datapoints
SAMPLES = 1000
# Set a "seed" value, so we get the same random numbers each time we run this
# notebook
np.random.seed(1337)
# Generate a uniformly distributed set of random numbers in the range from
# 0 to 2π, which covers a complete sine wave oscillation
x_values = np.ra... | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Add some noise
Since it was generated directly by the sine function, our data fits a nice, smooth curve.
However, machine learning models are good at extracting underlying meaning from messy, real world data. To demonstrate this, we can add some noise to our data to approximate something more life-like.
In the followin... | # Add a small random number to each y value
y_values += 0.1 * np.random.randn(*y_values.shape)
# Plot our data
plt.plot(x_values, y_values, 'b.')
plt.show() | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Split our data
We now have a noisy dataset that approximates real world data. We'll be using this to train our model.
To evaluate the accuracy of the model we train, we'll need to compare its predictions to real data and check how well they match up. This evaluation happens during training (where it is referred to as v... | # We'll use 60% of our data for training and 20% for testing. The remaining 20%
# will be used for validation. Calculate the indices of each section.
TRAIN_SPLIT = int(0.6 * SAMPLES)
TEST_SPLIT = int(0.2 * SAMPLES + TRAIN_SPLIT)
# Use np.split to chop our data into three parts.
# The second argument to np.split is an... | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Design a model
We're going to build a model that will take an input value (in this case, x) and use it to predict a numeric output value (the sine of x). This type of problem is called a regression.
To achieve this, we're going to create a simple neural network. It will use layers of neurons to attempt to learn any pat... | # We'll use Keras to create a simple model architecture
from tensorflow.keras import layers
model_1 = tf.keras.Sequential()
# First layer takes a scalar input and feeds it through 16 "neurons". The
# neurons decide whether to activate based on the 'relu' activation function.
model_1.add(layers.Dense(16, activation='re... | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Train the model
Once we've defined the model, we can use our data to train it. Training involves passing an x value into the neural network, checking how far the network's output deviates from the expected y value, and adjusting the neurons' weights and biases so that the output is more likely to be correct the next ti... | # Train the model on our training data while validating on our validation set
history_1 = model_1.fit(x_train, y_train, epochs=1000, batch_size=16,
validation_data=(x_validate, y_validate)) | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Check the training metrics
During training, the model's performance is constantly being measured against both our training data and the validation data that we set aside earlier. Training produces a log of data that tells us how the model's performance changed over the course of the training process.
The following cell... | # Draw a graph of the loss, which is the distance between
# the predicted and actual values during training and validation.
loss = history_1.history['loss']
val_loss = history_1.history['val_loss']
epochs = range(1, len(loss) + 1)
plt.plot(epochs, loss, 'g.', label='Training loss')
plt.plot(epochs, val_loss, 'b', lab... | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Look closer at the data
The graph shows the loss (or the difference between the model's predictions and the actual data) for each epoch. There are several ways to calculate loss, and the method we have used is mean squared error. There is a distinct loss value given for the training and the validation data.
As we can s... | # Exclude the first few epochs so the graph is easier to read
SKIP = 50
plt.plot(epochs[SKIP:], loss[SKIP:], 'g.', label='Training loss')
plt.plot(epochs[SKIP:], val_loss[SKIP:], 'b.', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show() | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Further metrics
From the plot, we can see that loss continues to reduce until around 600 epochs, at which point it is mostly stable. This means that there's no need to train our network beyond 600 epochs.
However, we can also see that the lowest loss value is still around 0.155. This means that our network's prediction... | plt.clf()
# Draw a graph of mean absolute error, which is another way of
# measuring the amount of error in the prediction.
mae = history_1.history['mae']
val_mae = history_1.history['val_mae']
plt.plot(epochs[SKIP:], mae[SKIP:], 'g.', label='Training MAE')
plt.plot(epochs[SKIP:], val_mae[SKIP:], 'b.', label='Validat... | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
This graph of mean absolute error tells another story. We can see that training data shows consistently lower error than validation data, which means that the network may have overfit, or learned the training data so rigidly that it can't make effective predictions about new data.
In addition, the mean absolute error v... | # Use the model to make predictions from our validation data
predictions = model_1.predict(x_train)
# Plot the predictions along with to the test data
plt.clf()
plt.title('Training data predicted vs actual values')
plt.plot(x_test, y_test, 'b.', label='Actual')
plt.plot(x_train, predictions, 'r.', label='Predicted')
p... | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Oh dear! The graph makes it clear that our network has learned to approximate the sine function in a very limited way. From 0 <= x <= 1.1 the line mostly fits, but for the rest of our x values it is a rough approximation at best.
The rigidity of this fit suggests that the model does not have enough capacity to le... | model_2 = tf.keras.Sequential()
# First layer takes a scalar input and feeds it through 16 "neurons". The
# neurons decide whether to activate based on the 'relu' activation function.
model_2.add(layers.Dense(16, activation='relu', input_shape=(1,)))
# The new second layer may help the network learn more complex repr... | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
We'll now train the new model. To save time, we'll train for only 600 epochs: | history_2 = model_2.fit(x_train, y_train, epochs=600, batch_size=16,
validation_data=(x_validate, y_validate)) | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Evaluate our new model
Each training epoch, the model prints out its loss and mean absolute error for training and validation. You can read this in the output above (note that your exact numbers may differ):
Epoch 600/600
600/600 [==============================] - 0s 109us/sample - loss: 0.0124 - mae: 0.0892 - val_los... | # Draw a graph of the loss, which is the distance between
# the predicted and actual values during training and validation.
loss = history_2.history['loss']
val_loss = history_2.history['val_loss']
epochs = range(1, len(loss) + 1)
plt.plot(epochs, loss, 'g.', label='Training loss')
plt.plot(epochs, val_loss, 'b', lab... | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Great results! From these graphs, we can see several exciting things:
Our network has reached its peak accuracy much more quickly (within 200 epochs instead of 600)
The overall loss and MAE are much better than our previous network
Metrics are better for validation than training, which means the network is not overfit... | # Calculate and print the loss on our test dataset
loss = model_2.evaluate(x_test, y_test)
# Make predictions based on our test dataset
predictions = model_2.predict(x_test)
# Graph the predictions against the actual values
plt.clf()
plt.title('Comparison of predictions and actual values')
plt.plot(x_test, y_test, 'b... | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Much better! The evaluation metrics we printed show that the model has a low loss and MAE on the test data, and the predictions line up visually with our data fairly well.
The model isn't perfect; its predictions don't form a smooth sine curve. For instance, the line is almost straight when x is between 4.2 and 5.2. If... | # Convert the model to the TensorFlow Lite format without quantization
converter = tf.lite.TFLiteConverter.from_keras_model(model_2)
tflite_model = converter.convert()
# Save the model to disk
open("sine_model.tflite", "wb").write(tflite_model)
# Convert the model to the TensorFlow Lite format with quantization
conve... | tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb | gunan/tensorflow | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.