Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
7,900 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyQt5 QSettings Note
保存应用窗口大小和位置的例子
```
def read_settings(self)
Step1: 最简单的用法 | Python Code:
from PyQt5.QtCore import QSettings
Explanation: PyQt5 QSettings Note
保存应用窗口大小和位置的例子
```
def read_settings(self):
settings = QSettings("Dormouse", "LakeTai")
pos = settings.value("pos", QPoint(200, 200))
size = settings.value("size", QSize(400, 400))
self.resize(size)
self.move(pos)
def write_settings(self):
settings = QSettings("Dormouse", "LakeTai")
settings.setValue("pos", self.pos())
settings.setValue("size", self.size())
```
End of explanation
myOrganization = 'MyOrg' # 组织名称
myApplication = 'MyApp' # 应用名称
settings = QSettings(myOrganization, myApplication)
settings.setValue("editor/wrapMargin", 68)
print (settings.value("editor/wrapMargin"))
print (settings.value("editor/someth"))
# 如果在程序中多处用到 QSettings ,那么可以一次性定义,然后统一使用
from PyQt5.QtCore import QCoreApplication
QCoreApplication.setOrganizationName("MyOrg2nd")
QCoreApplication.setOrganizationDomain("MyOrg2nd.com")
QCoreApplication.setApplicationName("MyApp2nd")
settings_2nd = QSettings()
print (settings.applicationName())
print (settings_2nd.applicationName())
print (settings_2nd.organizationName())
# 测试键是否存在
settings.contains("editor")
settings.contains("editor/wrapMargin")
settings.remove("editor") #删除一个键,键不存在也不会报错
settings.contains("editor/wrapMargin")
settings.clear() #清空所有键(只是清空自己添加的,系统固有的还在)
settings.allKeys() #所有键
settings.fileName() #储存位置
settings_ini = QSettings("conf.ini", QSettings.IniFormat) #使用 ini 文件来储存
settings_ini.fileName()
Explanation: 最简单的用法
End of explanation |
7,901 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 39
Step1: Response objects can be checked via status codes
Step2: The response object has succeded, and all values are stored within it
Step3: A typical way to deal with status is to use a raise_for_status() statement, which will crash if a file is not found, and can be used in conjunction with boolean statements, and try and except statements.
Step4: Files downloaded in this way must be stored in wb or write-binary method, to preserve the unicode formatting of this text. An explanation of unicode and its relationship to Python can be found here.
To store this file, we therefore need to write it in 'byte' chunks to a binary file. A useful method to help do this is the response object's iter_content method. | Python Code:
# Test the requests module by importing it
import requests
# Store a website url in a response object that can be queried
res = requests.get('https://automatetheboringstuff.com/files/rj.txt')
Explanation: Lesson 39:
Downloading from the Web with the Requests Module
The requests module lets you easily download files from the web without complicated issues.
requests does not come with Python, so it must be installed manually with pip.
End of explanation
res.status_code
Explanation: Response objects can be checked via status codes:
'404' is the typical 'file not found' code.
'200' is the typical 'success' code.
End of explanation
# Print the first 100 lines
print(res.text[:1000])
Explanation: The response object has succeded, and all values are stored within it:
End of explanation
# Run method on existing response object; won't raise anything because no error
res.raise_for_status()
# An example bad request
badres = requests.get('https://automatetheboringstuff.com/134513135465614561456')
badres.raise_for_status()
Explanation: A typical way to deal with status is to use a raise_for_status() statement, which will crash if a file is not found, and can be used in conjunction with boolean statements, and try and except statements.
End of explanation
# Open/create a file to store the bytes, using a new name
playFile= open('files/RomeoAnd Juliet.txt', 'wb')
# Iteratively write each 100,000 byte 'chunk' of data into this file
for chunk in res.iter_content(100000):
playFile.write(chunk)
# Close to save file
playFile.close()
Explanation: Files downloaded in this way must be stored in wb or write-binary method, to preserve the unicode formatting of this text. An explanation of unicode and its relationship to Python can be found here.
To store this file, we therefore need to write it in 'byte' chunks to a binary file. A useful method to help do this is the response object's iter_content method.
End of explanation |
7,902 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sparkling Titanic
Step1: Here, I want to find the percentance of people that survived based on their class
pclass
Step2: As expected, most of the upper class survived, while the lower class had less odds to survive.
Now, I am interested on the average price per ticket for each class. | Python Code:
# imports
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
from pyspark.sql import functions as F
from graphframes import *
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# make graphs beautiful
plt.style.use('ggplot')
plt.rc('font', family='sans-serif')
%matplotlib inline
sqlContext = SQLContext(sc)
train = pd.read_csv('train.csv')
train.head()
sorted_by_age = train.sort_values(['Age'])
plt.plot(sorted_by_age.Age, sorted_by_age.Pclass, 'bo')
plt.title('Class per Age')
plt.ylim([0, 5])
plt.show()
# drop useless columns
drop_elements = ['PassengerId', 'Name']
train = train.drop(drop_elements, axis = 1)
train.head()
Explanation: Sparkling Titanic
End of explanation
total_elements = train.groupby(train.Pclass).Survived.count()
total_survived = train[train.Survived == 1].groupby(train.Pclass).Survived.count()
(total_survived / total_elements).plot.bar()
Explanation: Here, I want to find the percentance of people that survived based on their class
pclass: A proxy for socio-economic status (SES)
1st = Upper
2nd = Middle
3rd = Lower
End of explanation
avg_prices = train.groupby(train.Pclass).Fare.mean()
avg_prices.plot.bar()
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
df = spark.read.csv('train.csv', header='true', inferSchema='true')
df.limit(5).toPandas()
df.dtypes
df.filter((df.Survived == 1) & (df.Sex == 'male')).count() / df.filter(df.Sex == 'male').count()
df.filter((df.Survived == 1) & (df.Sex == 'female')).count() / df.filter(df.Sex == 'female').count()
total_by_sex = df.groupBy(df.Sex).count().withColumnRenamed('count', 'total')
survived_by_sex = df.filter(df.Survived == 1).groupBy(df.Sex).count()
survived_by_sex.join(total_by_sex, survived_by_sex.Sex == total_by_sex.Sex, 'outer')\
.rdd.map(lambda x: (x.Sex, x['count'] / x.total)).collect()
# best way to do this calculation
df[["Sex", "Survived"]].groupby('Sex').mean().show()
g = sns.FacetGrid(train, col='Survived')
g.map(plt.hist, 'Age', bins=40)
grid = sns.FacetGrid(train, col='Pclass', row='Survived')
grid.map(plt.hist, 'Age', bins=40)
grid.add_legend();
Explanation: As expected, most of the upper class survived, while the lower class had less odds to survive.
Now, I am interested on the average price per ticket for each class.
End of explanation |
7,903 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matching Market
This simple model consists of a buyer, a supplier, and a market.
The buyer represents a group of customers whose willingness to pay for a single unit of the good is captured by a vector of prices wta. You can initiate the buyer with a set_quantity function which randomly assigns the willingness to pay according to your specifications. You may ask for these willingness to pay quantities with a get_bid function.
The supplier is similiar, but instead the supplier is willing to be paid to sell a unit of technology. The supplier for instance may have non-zero variable costs that make them unwilling to produce the good unless they receive a specified price. Similarly the supplier has a get_ask function which returns a list of desired prices.
The willingness to pay or sell are set randomly using uniform random distributions. The resultant lists of bids are effectively a demand curve. Likewise the list of asks is effectively a supply curve. A more complex determination of bids and asks is possible, for instance using time of year to vary the quantities being demanded.
Microeconomic Foundations
The market assumes the presence of an auctioneer which will create a book, which seeks to match the bids and the asks as much as possible. If the auctioneer is neutral, then it is incentive compatible for the buyer and the supplier to truthfully announce their bids and asks. The auctioneer will find a single price which clears as much of the market as possible. Clearing the market means that as many willing swaps happens as possible. You may ask the market object at what price the market clears with the get_clearing_price function. You may also ask the market how many units were exchanged with the get_units_cleared function.
Agent-Based Objects
The following section presents three objects which can be used to make an agent-based model of an efficient, two-sided market.
Step1: Example Market
In the following code example we use the buyer and supplier objects to create a market. At the market a single price is announced which causes as many units of goods to be swapped as possible. The buyers and sellers stop trading when it is no longer in their own interest to continue. | Python Code:
import random as rnd
class Supplier():
def __init__(self):
self.wta = []
# the supplier has n quantities that they can sell
# they may be willing to sell this quantity anywhere from a lower price of l
# to a higher price of u
def set_quantity(self,n,l,u):
for i in range(n):
p = rnd.uniform(l,u)
self.wta.append(p)
# return the dictionary of willingness to ask
def get_ask(self):
return self.wta
class Buyer():
def __init__(self):
self.wtp = []
# the supplier has n quantities that they can buy
# they may be willing to sell this quantity anywhere from a lower price of l
# to a higher price of u
def set_quantity(self,n,l,u):
for i in range(n):
p = rnd.uniform(l,u)
self.wtp.append(p)
# return list of willingness to pay
def get_bid(self):
return self.wtp
class Market():
count = 0
last_price = ''
b = []
s = []
def __init__(self,b,s):
# buyer list sorted in descending order
self.b = sorted(b, reverse=True)
# seller list sorted in ascending order
self.s = sorted(s, reverse=False)
# return the price at which the market clears
# assume equal numbers of sincere buyers and sellers
def get_clearing_price(self):
# buyer makes a bid, starting with the buyer which wants it most
for i in range(len(self.b)):
if (self.b[i] > self.s[i]):
self.count +=1
self.last_price = self.b[i]
return self.last_price
def get_units_cleared(self):
return self.count
Explanation: Matching Market
This simple model consists of a buyer, a supplier, and a market.
The buyer represents a group of customers whose willingness to pay for a single unit of the good is captured by a vector of prices wta. You can initiate the buyer with a set_quantity function which randomly assigns the willingness to pay according to your specifications. You may ask for these willingness to pay quantities with a get_bid function.
The supplier is similiar, but instead the supplier is willing to be paid to sell a unit of technology. The supplier for instance may have non-zero variable costs that make them unwilling to produce the good unless they receive a specified price. Similarly the supplier has a get_ask function which returns a list of desired prices.
The willingness to pay or sell are set randomly using uniform random distributions. The resultant lists of bids are effectively a demand curve. Likewise the list of asks is effectively a supply curve. A more complex determination of bids and asks is possible, for instance using time of year to vary the quantities being demanded.
Microeconomic Foundations
The market assumes the presence of an auctioneer which will create a book, which seeks to match the bids and the asks as much as possible. If the auctioneer is neutral, then it is incentive compatible for the buyer and the supplier to truthfully announce their bids and asks. The auctioneer will find a single price which clears as much of the market as possible. Clearing the market means that as many willing swaps happens as possible. You may ask the market object at what price the market clears with the get_clearing_price function. You may also ask the market how many units were exchanged with the get_units_cleared function.
Agent-Based Objects
The following section presents three objects which can be used to make an agent-based model of an efficient, two-sided market.
End of explanation
# make a supplier and get the asks
supplier = Supplier()
supplier.set_quantity(60,10,30)
ask = supplier.get_ask()
# make a buyer and get the bids (n,l,u)
buyer = Buyer()
buyer.set_quantity(60,10,30)
bid = buyer.get_bid()
# make a market where the buyers and suppliers can meet
# the bids and asks are a list of prices
market = Market(bid,ask)
price = market.get_clearing_price()
quantity = market.get_units_cleared()
# output the results of the market
print("Goods cleared for a price of ",price)
print("Units sold are ", quantity)
Explanation: Example Market
In the following code example we use the buyer and supplier objects to create a market. At the market a single price is announced which causes as many units of goods to be swapped as possible. The buyers and sellers stop trading when it is no longer in their own interest to continue.
End of explanation |
7,904 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Style Transfer Tutorial
Our Changes
Step1: Imports
Step2: This was developed using Python 3.5.2 (Anaconda) and TensorFlow version
Step3: The VGG-16 model is downloaded from the internet. This is the default directory where you want to save the data-files. The directory will be created if it does not exist.
Step4: Helper-functions for image manipulation
This function loads an image and returns it as a numpy array of floating-points. The image can be automatically resized so the largest of the height or width equals max_size.
Step5: Save an image as a jpeg-file. The image is given as a numpy array with pixel-values between 0 and 255.
Step6: This function plots a large image. The image is given as a numpy array with pixel-values between 0 and 255.
This function plots the content-, mixed- and style-images.
Step10: Loss Functions
These helper-functions create the loss-functions that are used in optimization with TensorFlow.
This function creates a TensorFlow operation for calculating the Mean Squared Error between the two input tensors.
Step11: Example
This example shows how to transfer the style of various images onto a portrait.
First we load the content-image which has the overall contours that we want in the mixed-image.
Step12: Then we load the style-image which has the colours and textures we want in the mixed-image.
Step13: Then we define a list of integers which identify the layers in the neural network that we want to use for matching the content-image. These are indices into the layers in the neural network. For the VGG16 model, the 5th layer (index 4) seems to work well as the sole content-layer.
Step14: Then we define another list of integers for the style-layers. | Python Code:
from IPython.display import Image, display
Image('images/15_style_transfer_flowchart.png')
Explanation: Style Transfer Tutorial
Our Changes:
We have modified the create_denoise_loss function which denoises the mixed image. This function now shifts the input image by 50 pixels one axis at a time and then calculates the difference bwteen the input image and the original image. Takes the absolute value of the difference and then adds the values of each pixel to calculate the denoise loss.
End of explanation
%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import PIL.Image
Explanation: Imports
End of explanation
tf.__version__
import vgg16
Explanation: This was developed using Python 3.5.2 (Anaconda) and TensorFlow version:
End of explanation
# vgg16.data_dir = 'vgg16/'
vgg16.maybe_download()
Explanation: The VGG-16 model is downloaded from the internet. This is the default directory where you want to save the data-files. The directory will be created if it does not exist.
End of explanation
def load_image(filename, max_size=None):
image = PIL.Image.open(filename)
if max_size is not None:
# Calculate the appropriate rescale-factor for
# ensuring a max height and width, while keeping
# the proportion between them.
factor = max_size / np.max(image.size)
# Scale the image's height and width.
size = np.array(image.size) * factor
# The size is now floating-point because it was scaled.
# But PIL requires the size to be integers.
size = size.astype(int)
# Resize the image.
image = image.resize(size, PIL.Image.LANCZOS)
print(image)
# Convert to numpy floating-point array.
return np.float32(image)
Explanation: Helper-functions for image manipulation
This function loads an image and returns it as a numpy array of floating-points. The image can be automatically resized so the largest of the height or width equals max_size.
End of explanation
def save_image(image, filename):
# Ensure the pixel-values are between 0 and 255.
image = np.clip(image, 0.0, 255.0)
# Convert to bytes.
image = image.astype(np.uint8)
# Write the image-file in jpeg-format.
with open(filename, 'wb') as file:
PIL.Image.fromarray(image).save(file, 'jpeg')
Explanation: Save an image as a jpeg-file. The image is given as a numpy array with pixel-values between 0 and 255.
End of explanation
def plot_image_big(image):
# Ensure the pixel-values are between 0 and 255.
image = np.clip(image, 0.0, 255.0)
# Convert pixels to bytes.
image = image.astype(np.uint8)
# Convert to a PIL-image and display it.
display(PIL.Image.fromarray(image))
def plot_images(content_image, style_image, mixed_image):
# Create figure with sub-plots.
fig, axes = plt.subplots(1, 3, figsize=(10, 10))
# Adjust vertical spacing.
fig.subplots_adjust(hspace=0.1, wspace=0.1)
# Use interpolation to smooth pixels?
smooth = True
# Interpolation type.
if smooth:
interpolation = 'sinc'
else:
interpolation = 'nearest'
# Plot the content-image.
# Note that the pixel-values are normalized to
# the [0.0, 1.0] range by dividing with 255.
ax = axes.flat[0]
ax.imshow(content_image / 255.0, interpolation=interpolation)
ax.set_xlabel("Content")
# Plot the mixed-image.
ax = axes.flat[1]
ax.imshow(mixed_image / 255.0, interpolation=interpolation)
ax.set_xlabel("Mixed")
# Plot the style-image
ax = axes.flat[2]
ax.imshow(style_image / 255.0, interpolation=interpolation)
ax.set_xlabel("Style")
# Remove ticks from all the plots.
for ax in axes.flat:
ax.set_xticks([])
ax.set_yticks([])
# Ensure the plot is shown correctly with multiple plots
# in a single Notebook cell.
plt.show()
Explanation: This function plots a large image. The image is given as a numpy array with pixel-values between 0 and 255.
This function plots the content-, mixed- and style-images.
End of explanation
def mean_squared_error(a, b):
return tf.reduce_mean(tf.square(a - b))
def create_content_loss(session, model, content_image, layer_ids):
Create the loss-function for the content-image.
Parameters:
session: An open TensorFlow session for running the model's graph.
model: The model, e.g. an instance of the VGG16-class.
content_image: Numpy float array with the content-image.
layer_ids: List of integer id's for the layers to use in the model.
# Create a feed-dict with the content-image.
feed_dict = model.create_feed_dict(image=content_image)
# Get references to the tensors for the given layers.
layers = model.get_layer_tensors(layer_ids)
# Calculate the output values of those layers when
# feeding the content-image to the model.
values = session.run(layers, feed_dict=feed_dict)
# Set the model's graph as the default so we can add
# computational nodes to it. It is not always clear
# when this is necessary in TensorFlow, but if you
# want to re-use this code then it may be necessary.
with model.graph.as_default():
# Initialize an empty list of loss-functions.
layer_losses = []
# For each layer and its corresponding values
# for the content-image.
for value, layer in zip(values, layers):
# These are the values that are calculated
# for this layer in the model when inputting
# the content-image. Wrap it to ensure it
# is a const - although this may be done
# automatically by TensorFlow.
value_const = tf.constant(value)
# The loss-function for this layer is the
# Mean Squared Error between the layer-values
# when inputting the content- and mixed-images.
# Note that the mixed-image is not calculated
# yet, we are merely creating the operations
# for calculating the MSE between those two.
loss = mean_squared_error(layer, value_const)
# Add the loss-function for this layer to the
# list of loss-functions.
layer_losses.append(loss)
# The combined loss for all layers is just the average.
# The loss-functions could be weighted differently for
# each layer. You can try it and see what happens.
total_loss = tf.reduce_mean(layer_losses)
return total_loss
def gram_matrix(tensor):
shape = tensor.get_shape()
# Get the number of feature channels for the input tensor,
# which is assumed to be from a convolutional layer with 4-dim.
num_channels = int(shape[3])
# Reshape the tensor so it is a 2-dim matrix. This essentially
# flattens the contents of each feature-channel.
matrix = tf.reshape(tensor, shape=[-1, num_channels])
# Calculate the Gram-matrix as the matrix-product of
# the 2-dim matrix with itself. This calculates the
# dot-products of all combinations of the feature-channels.
gram = tf.matmul(tf.transpose(matrix), matrix)
return gram
def create_style_loss(session, model, style_image, layer_ids):
Create the loss-function for the style-image.
Parameters:
session: An open TensorFlow session for running the model's graph.
model: The model, e.g. an instance of the VGG16-class.
style_image: Numpy float array with the style-image.
layer_ids: List of integer id's for the layers to use in the model.
# Create a feed-dict with the style-image.
feed_dict = model.create_feed_dict(image=style_image)
# Get references to the tensors for the given layers.
layers = model.get_layer_tensors(layer_ids)
layerIdCount=len(layer_ids)
print('count of layer ids:',layerIdCount)
# Set the model's graph as the default so we can add
# computational nodes to it. It is not always clear
# when this is necessary in TensorFlow, but if you
# want to re-use this code then it may be necessary.
with model.graph.as_default():
# Construct the TensorFlow-operations for calculating
# the Gram-matrices for each of the layers.
gram_layers = [gram_matrix(layer) for layer in layers]
# Calculate the values of those Gram-matrices when
# feeding the style-image to the model.
values = session.run(gram_layers, feed_dict=feed_dict)
# Initialize an empty list of loss-functions.
layer_losses = []
# For each Gram-matrix layer and its corresponding values.
for value, gram_layer in zip(values, gram_layers):
# These are the Gram-matrix values that are calculated
# for this layer in the model when inputting the
# style-image. Wrap it to ensure it is a const,
# although this may be done automatically by TensorFlow.
value_const = tf.constant(value)
# The loss-function for this layer is the
# Mean Squared Error between the Gram-matrix values
# for the content- and mixed-images.
# Note that the mixed-image is not calculated
# yet, we are merely creating the operations
# for calculating the MSE between those two.
loss = mean_squared_error(gram_layer, value_const)
# Add the loss-function for this layer to the
# list of loss-functions.
layer_losses.append(loss)
# The combined loss for all layers is just the average.
# The loss-functions could be weighted differently for
# each layer. You can try it and see what happens.
total_loss = tf.reduce_mean(layer_losses)
return total_loss
def create_denoise_loss(model):
loss = tf.reduce_sum(tf.abs(model.input[:,50:,:,:] - model.input[:,:-50,:,:])) + \
tf.reduce_sum(tf.abs(model.input[:,:,50:,:] - model.input[:,:,:-50,:]))
return loss
def style_transfer(content_image, style_image,
content_layer_ids, style_layer_ids,
weight_content=1.5, weight_style=10.0,
weight_denoise=0.3,
num_iterations=120, step_size=10.0):
Use gradient descent to find an image that minimizes the
loss-functions of the content-layers and style-layers. This
should result in a mixed-image that resembles the contours
of the content-image, and resembles the colours and textures
of the style-image.
Parameters:
content_image: Numpy 3-dim float-array with the content-image.
style_image: Numpy 3-dim float-array with the style-image.
content_layer_ids: List of integers identifying the content-layers.
style_layer_ids: List of integers identifying the style-layers.
weight_content: Weight for the content-loss-function.
weight_style: Weight for the style-loss-function.
weight_denoise: Weight for the denoising-loss-function.
num_iterations: Number of optimization iterations to perform.
step_size: Step-size for the gradient in each iteration.
# Create an instance of the VGG16-model. This is done
# in each call of this function, because we will add
# operations to the graph so it can grow very large
# and run out of RAM if we keep using the same instance.
model = vgg16.VGG16()
# Create a TensorFlow-session.
session = tf.InteractiveSession(graph=model.graph)
# Print the names of the content-layers.
print("Content layers:")
print(model.get_layer_names(content_layer_ids))
print('Content Layers:',content_layer_ids)
print()
# Print the names of the style-layers.
print("Style layers:")
print(model.get_layer_names(style_layer_ids))
print('Style Layers:',style_layer_ids)
print()
#Printing the input paramenter to the function
print('Weight Content:',weight_content)
print('Weight Style:',weight_style)
print('Weight Denoise:',weight_denoise)
print('Number of Iterations:',num_iterations)
print('Step Size:',step_size)
print()
# Create the loss-function for the content-layers and -image.
loss_content = create_content_loss(session=session,
model=model,
content_image=content_image,
layer_ids=content_layer_ids)
# Create the loss-function for the style-layers and -image.
loss_style = create_style_loss(session=session,
model=model,
style_image=style_image,
layer_ids=style_layer_ids)
# Create the loss-function for the denoising of the mixed-image.
loss_denoise = create_denoise_loss(model)
# Create TensorFlow variables for adjusting the values of
# the loss-functions. This is explained below.
adj_content = tf.Variable(1e-10, name='adj_content')
adj_style = tf.Variable(1e-10, name='adj_style')
adj_denoise = tf.Variable(1e-10, name='adj_denoise')
# Initialize the adjustment values for the loss-functions.
session.run([adj_content.initializer,
adj_style.initializer,
adj_denoise.initializer])
# Create TensorFlow operations for updating the adjustment values.
# These are basically just the reciprocal values of the
# loss-functions, with a small value 1e-10 added to avoid the
# possibility of division by zero.
update_adj_content = adj_content.assign(1.0 / (loss_content + 1e-10))
update_adj_style = adj_style.assign(1.0 / (loss_style + 1e-10))
update_adj_denoise = adj_denoise.assign(1.0 / (loss_denoise + 1e-10))
# This is the weighted loss-function that we will minimize
# below in order to generate the mixed-image.
# Because we multiply the loss-values with their reciprocal
# adjustment values, we can use relative weights for the
# loss-functions that are easier to select, as they are
# independent of the exact choice of style- and content-layers.
loss_combined = weight_content * adj_content * loss_content + \
weight_style * adj_style * loss_style + \
weight_denoise * adj_denoise * loss_denoise
#loss_combined = loss_combined/3
# Use TensorFlow to get the mathematical function for the
# gradient of the combined loss-function with regard to
# the input image.
gradient = tf.gradients(loss_combined, model.input)
# List of tensors that we will run in each optimization iteration.
run_list = [gradient, update_adj_content, update_adj_style, \
update_adj_denoise]
# The mixed-image is initialized with random noise.
# It is the same size as the content-image.
mixed_image = np.random.rand(*content_image.shape) + 128
for i in range(num_iterations):
# Create a feed-dict with the mixed-image.
feed_dict = model.create_feed_dict(image=mixed_image)
# Use TensorFlow to calculate the value of the
# gradient, as well as updating the adjustment values.
grad, adj_content_val, adj_style_val, adj_denoise_val \
= session.run(run_list, feed_dict=feed_dict)
# Reduce the dimensionality of the gradient.
grad = np.squeeze(grad)
# Scale the step-size according to the gradient-values.
step_size_scaled = step_size / (np.std(grad) + 1e-8)
# Update the image by following the gradient.
mixed_image -= grad * step_size_scaled
# Ensure the image has valid pixel-values between 0 and 255.
mixed_image = np.clip(mixed_image, 0.0, 255.0)
# Print a little progress-indicator.
print(". ", end="")
# Display status once every 10 iterations, and the last.
if (i % 10 == 0) or (i == num_iterations - 1):
print()
print("Iteration:", i)
# Print adjustment weights for loss-functions.
msg = "Weight Adj. for Content: {0:.2e}, Style: {1:.2e}, Denoise: {2:.2e}"
print(msg.format(adj_content_val, adj_style_val, adj_denoise_val))
# Plot the content-, style- and mixed-images.
plot_images(content_image=content_image,
style_image=style_image,
mixed_image=mixed_image)
#Saving the mixed image after every 10 iterations
filename='images/outputs_StyleTransfer/Mixed_Iteration' + str(i) +'.jpg'
print(filename)
save_image(mixed_image, filename)
print()
print("Final image:")
plot_image_big(mixed_image)
# Close the TensorFlow session to release its resources.
session.close()
# Return the mixed-image.
return mixed_image
Explanation: Loss Functions
These helper-functions create the loss-functions that are used in optimization with TensorFlow.
This function creates a TensorFlow operation for calculating the Mean Squared Error between the two input tensors.
End of explanation
content_filename = 'images/elon_musk.jpg'
content_image = load_image(content_filename, max_size=300)
filenamecontent='images/outputs_StyleTransfer/Content.jpg'
print(filenamecontent)
save_image(content_image, filenamecontent)
Explanation: Example
This example shows how to transfer the style of various images onto a portrait.
First we load the content-image which has the overall contours that we want in the mixed-image.
End of explanation
style_filename = 'images/style9.jpg'
style_image = load_image(style_filename, max_size=300)
filenamestyle='images/outputs_StyleTransfer/Style.jpg'
print(filenamestyle)
save_image(style_image, filenamestyle)
Explanation: Then we load the style-image which has the colours and textures we want in the mixed-image.
End of explanation
content_layer_ids = [4,6]
Explanation: Then we define a list of integers which identify the layers in the neural network that we want to use for matching the content-image. These are indices into the layers in the neural network. For the VGG16 model, the 5th layer (index 4) seems to work well as the sole content-layer.
End of explanation
# The VGG16-model has 13 convolutional layers.
# This selects all those layers as the style-layers.
# This is somewhat slow to optimize.
style_layer_ids = list(range(13))
# You can also select a sub-set of the layers, e.g. like this:
# style_layer_ids = [1, 2, 3, 4]
%%time
img = style_transfer(content_image=content_image,
style_image=style_image,
content_layer_ids=content_layer_ids,
style_layer_ids=style_layer_ids,
weight_content=1.5,
weight_style=10.0,
weight_denoise=0.3,
num_iterations=150,
step_size=10.0)
# function for printing output image
filename='images/outputs_StyleTransfer/Mixed.jpg'
save_image(img, filename)
Explanation: Then we define another list of integers for the style-layers.
End of explanation |
7,905 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example of DOV search methods for interpretations (geotechnische codering)
Use cases explained below
Get 'geotechnische codering' in a bounding box
Get 'geotechnische codering' with specific properties within a distance from a point
Get 'geotechnische codering' in a bounding box with specific properties
Get 'geotechnische codering' based on fields not available in the standard output dataframe
Get 'geotechnische codering' data, returning fields not available in the standard output dataframe
Step1: Get information about the datatype 'Geotecnische codering'
Step2: A description is provided for the 'Geotechnische codering' datatype
Step3: The different fields that are available for objects of the 'Geotechnische codering' datatype can be requested with the get_fields() method
Step4: You can get more information of a field by requesting it from the fields dictionary
Step5: Example use cases
Get 'Geotechnische codering' in a bounding box
Get data for all the 'Geotechnische codering' interpretations that are geographically located within the bounds of the specified box.
The coordinates are in the Belgian Lambert72 (EPSG
Step6: The dataframe contains one 'Geotechnische codering' interpretation where ten layers ('laag') were identified. The available data are flattened to represent unique attributes per row of the dataframe.
Using the pkey_interpretatie field one can request the details of this interpretation in a webbrowser
Step7: Get 'Geotechnische codering' with specific properties within a distance from a point
Next to querying interpretations based on their geographic location within a bounding box, we can also search for interpretations matching a specific set of properties. For this we can build a query using a combination of the 'Geotechnische codering' fields and operators provided by the WFS protocol.
A list of possible operators can be found below
Step8: In this example we build a query using the PropertyIsGreaterThan and PropertyIsEqualTo operators to find all interpretations that are at least 20 m deep, that are deemed appropriate for a range of 1 km from a defined point
Step9: Once again we can use the pkey_interpretatie as a permanent link to the information of these interpretations
Step10: Get 'Geotechnische codering' in a bounding box based on specific properties
We can combine a query on attributes with a query on geographic location to get the interpretations within a bounding box that have specific properties.
The following example requests the interpretations of boreholes only, within the given bounding box.
(Note that the datatype of the literal parameter should be a string, regardless of the datatype of this field in the output dataframe.)
Step11: We can look at one of the interpretations in a webbrowser using its pkey_interpretatie
Step12: Get 'Geotechnische codering' based on fields not available in the standard output dataframe
To keep the output dataframe size acceptable, not all available WFS fields are included in the standard output. However, one can use this information to select interpretations as illustrated below.
For example, make a selection of the interpretations in municipality the of Antwerp, before 1/1/1990
Step13: Get 'Geotechnische codering' data, returning fields not available in the standard output dataframe
As denoted in the previous example, not all available fields are available in the default output frame to keep its size limited. However, you can request any available field by including it in the return_fields parameter of the search
Step14: Visualize results
Using Folium, we can display the results of our search on a map. | Python Code:
%matplotlib inline
import inspect, sys
# check pydov path
import pydov
Explanation: Example of DOV search methods for interpretations (geotechnische codering)
Use cases explained below
Get 'geotechnische codering' in a bounding box
Get 'geotechnische codering' with specific properties within a distance from a point
Get 'geotechnische codering' in a bounding box with specific properties
Get 'geotechnische codering' based on fields not available in the standard output dataframe
Get 'geotechnische codering' data, returning fields not available in the standard output dataframe
End of explanation
from pydov.search.interpretaties import GeotechnischeCoderingSearch
itp = GeotechnischeCoderingSearch()
Explanation: Get information about the datatype 'Geotecnische codering'
End of explanation
itp.get_description()
Explanation: A description is provided for the 'Geotechnische codering' datatype:
End of explanation
fields = itp.get_fields()
# print available fields
for f in fields.values():
print(f['name'])
Explanation: The different fields that are available for objects of the 'Geotechnische codering' datatype can be requested with the get_fields() method:
End of explanation
fields['Datum']
Explanation: You can get more information of a field by requesting it from the fields dictionary:
* name: name of the field
* definition: definition of this field
* cost: currently this is either 1 or 10, depending on the datasource of the field. It is an indication of the expected time it will take to retrieve this field in the output dataframe.
* notnull: whether the field is mandatory or not
* type: datatype of the values of this field
End of explanation
from pydov.util.location import Within, Box
df = itp.search(location=Within(Box(108281, 197850, 108282, 197851)))
df.head()
Explanation: Example use cases
Get 'Geotechnische codering' in a bounding box
Get data for all the 'Geotechnische codering' interpretations that are geographically located within the bounds of the specified box.
The coordinates are in the Belgian Lambert72 (EPSG:31370) coordinate system and are given in the order of lower left x, lower left y, upper right x, upper right y.
End of explanation
for pkey_interpretatie in set(df.pkey_interpretatie):
print(pkey_interpretatie)
Explanation: The dataframe contains one 'Geotechnische codering' interpretation where ten layers ('laag') were identified. The available data are flattened to represent unique attributes per row of the dataframe.
Using the pkey_interpretatie field one can request the details of this interpretation in a webbrowser:
End of explanation
[i for i,j in inspect.getmembers(sys.modules['owslib.fes'], inspect.isclass) if 'Property' in i]
Explanation: Get 'Geotechnische codering' with specific properties within a distance from a point
Next to querying interpretations based on their geographic location within a bounding box, we can also search for interpretations matching a specific set of properties. For this we can build a query using a combination of the 'Geotechnische codering' fields and operators provided by the WFS protocol.
A list of possible operators can be found below:
End of explanation
from owslib.fes import And, PropertyIsGreaterThan, PropertyIsEqualTo
from pydov.util.location import WithinDistance, Point
query = And([PropertyIsEqualTo(propertyname='Betrouwbaarheid',
literal='goed'),
PropertyIsGreaterThan(propertyname='diepte_tot_m',
literal='20'),
])
df = itp.search(query=query,
location=WithinDistance(Point(153145, 206930), 1000))
df.head()
Explanation: In this example we build a query using the PropertyIsGreaterThan and PropertyIsEqualTo operators to find all interpretations that are at least 20 m deep, that are deemed appropriate for a range of 1 km from a defined point:
End of explanation
for pkey_interpretatie in set(df.pkey_interpretatie):
print(pkey_interpretatie)
Explanation: Once again we can use the pkey_interpretatie as a permanent link to the information of these interpretations:
End of explanation
from owslib.fes import PropertyIsEqualTo
query = PropertyIsEqualTo(
propertyname='Type_proef',
literal='Boring')
df = itp.search(
location=Within(Box(153145, 206930, 154145, 207930)),
query=query
)
df.head()
Explanation: Get 'Geotechnische codering' in a bounding box based on specific properties
We can combine a query on attributes with a query on geographic location to get the interpretations within a bounding box that have specific properties.
The following example requests the interpretations of boreholes only, within the given bounding box.
(Note that the datatype of the literal parameter should be a string, regardless of the datatype of this field in the output dataframe.)
End of explanation
for pkey_interpretatie in set(df.pkey_interpretatie):
print(pkey_interpretatie)
Explanation: We can look at one of the interpretations in a webbrowser using its pkey_interpretatie:
End of explanation
from owslib.fes import And, PropertyIsEqualTo, PropertyIsLessThan
query = And([PropertyIsEqualTo(propertyname='gemeente',
literal='Antwerpen'),
PropertyIsLessThan(propertyname='Datum',
literal='2010-01-01')]
)
df = itp.search(query=query,
return_fields=('pkey_interpretatie', 'Datum'))
df.head()
Explanation: Get 'Geotechnische codering' based on fields not available in the standard output dataframe
To keep the output dataframe size acceptable, not all available WFS fields are included in the standard output. However, one can use this information to select interpretations as illustrated below.
For example, make a selection of the interpretations in municipality the of Antwerp, before 1/1/1990:
!remark: mind that the municipality attribute is merely an attribute that is defined by the person entering the data. It can be ok, empty, outdated or wrong!
End of explanation
query = PropertyIsEqualTo(
propertyname='gemeente',
literal='Leuven')
df = itp.search(query=query,
return_fields=('pkey_interpretatie', 'pkey_boring',
'x', 'y', 'Z_mTAW', 'gemeente', 'Auteurs', 'Proefnummer'))
df.head()
Explanation: Get 'Geotechnische codering' data, returning fields not available in the standard output dataframe
As denoted in the previous example, not all available fields are available in the default output frame to keep its size limited. However, you can request any available field by including it in the return_fields parameter of the search:
End of explanation
# import the necessary modules (not included in the requirements of pydov!)
import folium
from folium.plugins import MarkerCluster
from pyproj import Transformer
# convert the coordinates to lat/lon for folium
def convert_latlon(x1, y1):
transformer = Transformer.from_crs("epsg:31370", "epsg:4326", always_xy=True)
x2,y2 = transformer.transform(x1, y1)
return x2, y2
df['lon'], df['lat'] = zip(*map(convert_latlon, df['x'], df['y']))
# convert to list
loclist = df[['lat', 'lon']].values.tolist()
# initialize the Folium map on the centre of the selected locations, play with the zoom until ok
fmap = folium.Map(location=[df['lat'].mean(), df['lon'].mean()], zoom_start=12)
marker_cluster = MarkerCluster().add_to(fmap)
for loc in range(0, len(loclist)):
folium.Marker(loclist[loc], popup=df['Proefnummer'][loc]).add_to(marker_cluster)
fmap
Explanation: Visualize results
Using Folium, we can display the results of our search on a map.
End of explanation |
7,906 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ice - Albedo Feedback and runaway glaciation
Here we will use the 1-dimensional diffusive Energy Balance Model (EBM) to explore the effects of albedo feedback and heat transport on climate sensitivity.
Step1: Annual-mean model with albedo feedback
Step2: Let's look at what happens if we perturb the temperature -- make it 20ºC colder everywhere!
Step3: Let's take a look at how we have just perturbed the absorbed shortwave
Step4: So there is less absorbed shortwave now, because of the increased albedo. The global mean difference is
Step5: Less shortwave means that there is a tendency for the climate to cool down even more! In other words, the shortwave feedback is positive.
Recall that the net feedback for the EBM can be written
$\lambda = - B + \frac{\Delta <(1-\alpha) Q >}{\Delta <T>}$
where the second term is the change in the absorbed shortwave per degree global mean temperature change.
Plugging these numbers in gives
$\lambda = - 2 + \frac{-20.4}{-20} = -2 + 1 = -1$ W m$^{-2}$ $^{\circ}$C$^{-1}$
The feedback is negative, as we expect! The tendency to warm up from reduced OLR outweighs the tendency to cool down from reduced ASR. A negative net feedback means that the system will relax back towards the equilibrium.
Let's let the temperature evolve one year at a time and add extra lines to the graph
Step6: Temperature drifts back towards equilibrium, as we expected!
What if we cool the climate so much that the entire planet is ice covered?
Step7: Look again at the change in absorbed shortwave
Step8: It's much larger because we've covered so much more surface area with ice!
The feedback calculation now looks like
$\lambda = - 2 + \frac{-109}{-40} = -2 + 2.7 = +0.7$ W m$^{-2}$ $^{\circ}$C$^{-1}$
What? Looks like the positive albedo feedback is so strong here that it has outweighed the negative longwave feedback. What will happen to the system now? Let's find out...
Step9: Something very different happened! The climate drifted towards an entirely different equilibrium state, in which the entire planet is cold and ice-covered.
We will refer to this as the SNOWBALL EARTH.
Note that the warmest spot on the planet is still the equator, but it is now about -33ºC rather than +28ºC!
Here Comes the Sun! Where is the ice edge?
The ice edge in our model is always where the temperature crosses $T_f = -10^\circ$C. The system is at equilibrium when the temperature is such that there is a balance between ASR, OLR, and heat transport convergence everywhere.
Suppose that sun was hotter or cooler at different times (in fact it was significantly cooler during early Earth history). That would mean that the solar constant $S_0 = 4Q$ was larger or smaller. We should expect that the temperature (and thus the ice edge) should increase and decrease as we change $S_0$.
$S_0$ during the Neoproterozoic Snowball Earth events is believed to be about 93% of its present-day value, or about 1270 W m$^{-2}$.
We are going to look at how the equilibrium ice edge depends on $S_0$, by integrating the model out to equilibrium for lots of different values of $S_0$. We will start by slowly decreasing $S_0$, and then slowly increasing $S_0$.
Step10: For completeness
Step11: There are actually up to 3 different climates possible for a given value of $S_0$!
How to un-freeze the Snowball
The graph indicates that if the Earth were completely frozen over, it would be perfectly happy to stay that way even if the sun were brighter and hotter than it is today.
Our EBM predicts that (with present-day parameters) the equilibrium temperature at the equator in the Snowball state is about -33ºC, which is much colder than the threshold temperature $T_f = -10^\circ$C. How can we melt the Snowball?
We need to increase the avaible energy sufficiently to get the equatorial temperatures above this threshold! That is going to require a much larger increase in $S_0$ (could also increase the greenhouse gases, which would have a similar effect)!
Let's crank up the sun to 1830 W m$^{-2}$ (about a 34% increase from present-day).
Step12: Still a Snowball... but just barely! The temperature at the equator is just below the threshold.
Try to imagine what might happen once it starts to melt. The solar constant is huge, and if it weren't for the highly reflective ice and snow, the climate would be really really hot!
We're going to increase $S_0$ one more time...
Step13: Suddenly the climate looks very very different again! The global mean temperature is
Step14: A roasty 60ºC, and the poles are above 20ºC. A tiny increase in $S_0$ has led to a very drastic change in the climate.
Step15: Now we will complete the plot of ice edge versus solar constant. | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import climlab
from climlab import constants as const
from climlab import legendre
Explanation: Ice - Albedo Feedback and runaway glaciation
Here we will use the 1-dimensional diffusive Energy Balance Model (EBM) to explore the effects of albedo feedback and heat transport on climate sensitivity.
End of explanation
model1 = climlab.EBM_annual( num_points = 180, a0=0.3, a2=0.078, ai=0.62)
print(model1)
model1.integrate_years(5)
Tequil = np.array(model1.Ts)
ALBequil = np.array(model1.albedo)
OLRequil = np.array(model1.OLR)
ASRequil = np.array(model1.ASR)
Explanation: Annual-mean model with albedo feedback: adjustment to equilibrium
A version of the EBM in which albedo adjusts to the current position of the ice line, wherever $T < T_f$
End of explanation
model1.Ts -= 20.
model1.compute_diagnostics()
Explanation: Let's look at what happens if we perturb the temperature -- make it 20ºC colder everywhere!
End of explanation
my_ticks = [-90,-60,-30,0,30,60,90]
lat = model1.lat
fig = plt.figure( figsize=(12,5) )
ax1 = fig.add_subplot(1,2,1)
ax1.plot(lat, Tequil, label='equil')
ax1.plot(lat, model1.Ts, label='pert' )
ax1.grid()
ax1.legend()
ax1.set_xlim(-90,90)
ax1.set_xticks(my_ticks)
ax1.set_xlabel('Latitude')
ax1.set_ylabel('Temperature (degC)')
ax2 = fig.add_subplot(1,2,2)
ax2.plot( lat, ASRequil, label='equil')
ax2.plot( lat, model1.ASR, label='pert' )
ax2.grid()
ax2.legend()
ax2.set_xlim(-90,90)
ax2.set_xticks(my_ticks)
ax2.set_xlabel('Latitude')
ax2.set_ylabel('ASR (W m$^{-2}$)')
plt.show()
Explanation: Let's take a look at how we have just perturbed the absorbed shortwave:
End of explanation
climlab.global_mean( model1.ASR - ASRequil )
Explanation: So there is less absorbed shortwave now, because of the increased albedo. The global mean difference is:
End of explanation
plt.plot( lat, Tequil, 'k--', label='equil' )
plt.plot( lat, model1.Ts, 'k-', label='pert' )
plt.grid()
plt.xlim(-90,90)
plt.legend()
for n in range(5):
model1.integrate_years(years=1.0, verbose=False)
plt.plot(lat, model1.Ts)
Explanation: Less shortwave means that there is a tendency for the climate to cool down even more! In other words, the shortwave feedback is positive.
Recall that the net feedback for the EBM can be written
$\lambda = - B + \frac{\Delta <(1-\alpha) Q >}{\Delta <T>}$
where the second term is the change in the absorbed shortwave per degree global mean temperature change.
Plugging these numbers in gives
$\lambda = - 2 + \frac{-20.4}{-20} = -2 + 1 = -1$ W m$^{-2}$ $^{\circ}$C$^{-1}$
The feedback is negative, as we expect! The tendency to warm up from reduced OLR outweighs the tendency to cool down from reduced ASR. A negative net feedback means that the system will relax back towards the equilibrium.
Let's let the temperature evolve one year at a time and add extra lines to the graph:
End of explanation
model1.Ts -= 40.
model1.compute_diagnostics()
Explanation: Temperature drifts back towards equilibrium, as we expected!
What if we cool the climate so much that the entire planet is ice covered?
End of explanation
climlab.global_mean( model1.ASR - ASRequil )
Explanation: Look again at the change in absorbed shortwave:
End of explanation
plt.plot( lat, Tequil, 'k--', label='equil' )
plt.plot( lat, model1.Ts, 'k-', label='pert' )
plt.grid()
plt.xlim(-90,90)
plt.legend()
for n in range(5):
model1.integrate_years(years=1.0, verbose=False)
plt.plot(lat, model1.Ts)
Explanation: It's much larger because we've covered so much more surface area with ice!
The feedback calculation now looks like
$\lambda = - 2 + \frac{-109}{-40} = -2 + 2.7 = +0.7$ W m$^{-2}$ $^{\circ}$C$^{-1}$
What? Looks like the positive albedo feedback is so strong here that it has outweighed the negative longwave feedback. What will happen to the system now? Let's find out...
End of explanation
model2 = climlab.EBM_annual(num_points = 360, a0=0.3, a2=0.078, ai=0.62)
S0array = np.linspace(1400., 1200., 200)
model2.integrate_years(5)
print(model2.icelat)
icelat_cooling = np.empty_like(S0array)
icelat_warming = np.empty_like(S0array)
# First cool....
for n in range(S0array.size):
model2.subprocess['insolation'].S0 = S0array[n]
model2.integrate_years(10, verbose=False)
icelat_cooling[n] = np.max(model2.icelat)
# Then warm...
for n in range(S0array.size):
model2.subprocess['insolation'].S0 = np.flipud(S0array)[n]
model2.integrate_years(10, verbose=False)
icelat_warming[n] = np.max(model2.icelat)
Explanation: Something very different happened! The climate drifted towards an entirely different equilibrium state, in which the entire planet is cold and ice-covered.
We will refer to this as the SNOWBALL EARTH.
Note that the warmest spot on the planet is still the equator, but it is now about -33ºC rather than +28ºC!
Here Comes the Sun! Where is the ice edge?
The ice edge in our model is always where the temperature crosses $T_f = -10^\circ$C. The system is at equilibrium when the temperature is such that there is a balance between ASR, OLR, and heat transport convergence everywhere.
Suppose that sun was hotter or cooler at different times (in fact it was significantly cooler during early Earth history). That would mean that the solar constant $S_0 = 4Q$ was larger or smaller. We should expect that the temperature (and thus the ice edge) should increase and decrease as we change $S_0$.
$S_0$ during the Neoproterozoic Snowball Earth events is believed to be about 93% of its present-day value, or about 1270 W m$^{-2}$.
We are going to look at how the equilibrium ice edge depends on $S_0$, by integrating the model out to equilibrium for lots of different values of $S_0$. We will start by slowly decreasing $S_0$, and then slowly increasing $S_0$.
End of explanation
model3 = climlab.EBM_annual(num_points = 360, a0=0.3, a2=0.078, ai=0.62)
S0array3 = np.linspace(1350., 1400., 50)
icelat3 = np.empty_like(S0array3)
for n in range(S0array3.size):
model3.subprocess['insolation'].S0 = S0array3[n]
model3.integrate_years(10, verbose=False)
icelat3[n] = np.max(model3.icelat)
fig = plt.figure( figsize=(10,6) )
ax = fig.add_subplot(111)
ax.plot(S0array, icelat_cooling, 'r-', label='cooling' )
ax.plot(S0array, icelat_warming, 'b-', label='warming' )
ax.plot(S0array3, icelat3, 'g-', label='warming' )
ax.set_ylim(-10,100)
ax.set_yticks((0,15,30,45,60,75,90))
ax.grid()
ax.set_ylabel('Ice edge latitude', fontsize=16)
ax.set_xlabel('Solar constant (W m$^{-2}$)', fontsize=16)
ax.plot( [const.S0, const.S0], [-10, 100], 'k--', label='present-day' )
ax.legend(loc='upper left')
ax.set_title('Solar constant versus ice edge latitude in the EBM with albedo feedback', fontsize=16)
plt.show()
Explanation: For completeness: also start from present-day conditions and warm up.
End of explanation
model4 = climlab.process_like(model2) # initialize with cold Snowball temperature
model4.subprocess['insolation'].S0 = 1830.
model4.integrate_years(40)
#lat = model4.domains['Ts'].axes['lat'].points
plt.plot(model4.lat, model4.Ts)
plt.xlim(-90,90)
plt.ylabel('Temperature')
plt.xlabel('Latitude')
plt.grid()
plt.xticks(my_ticks)
plt.show()
print('The ice edge is at ' + str(model4.icelat) + 'degrees latitude.' )
Explanation: There are actually up to 3 different climates possible for a given value of $S_0$!
How to un-freeze the Snowball
The graph indicates that if the Earth were completely frozen over, it would be perfectly happy to stay that way even if the sun were brighter and hotter than it is today.
Our EBM predicts that (with present-day parameters) the equilibrium temperature at the equator in the Snowball state is about -33ºC, which is much colder than the threshold temperature $T_f = -10^\circ$C. How can we melt the Snowball?
We need to increase the avaible energy sufficiently to get the equatorial temperatures above this threshold! That is going to require a much larger increase in $S_0$ (could also increase the greenhouse gases, which would have a similar effect)!
Let's crank up the sun to 1830 W m$^{-2}$ (about a 34% increase from present-day).
End of explanation
model4.subprocess['insolation'].S0 = 1845.
model4.integrate_years(10)
plt.plot(lat, model4.state['Ts'])
plt.xlim(-90,90)
plt.ylabel('Temperature')
plt.xlabel('Latitude')
plt.grid()
plt.xticks(my_ticks)
plt.show()
Explanation: Still a Snowball... but just barely! The temperature at the equator is just below the threshold.
Try to imagine what might happen once it starts to melt. The solar constant is huge, and if it weren't for the highly reflective ice and snow, the climate would be really really hot!
We're going to increase $S_0$ one more time...
End of explanation
print( model4.global_mean_temperature() )
Explanation: Suddenly the climate looks very very different again! The global mean temperature is
End of explanation
S0array_snowballmelt = np.linspace(1400., 1900., 50)
icelat_snowballmelt = np.empty_like(S0array_snowballmelt)
icelat_snowballmelt_cooling = np.empty_like(S0array_snowballmelt)
for n in range(S0array_snowballmelt.size):
model2.subprocess['insolation'].S0 = S0array_snowballmelt[n]
model2.integrate_years(10, verbose=False)
icelat_snowballmelt[n] = np.max(model2.diagnostics['icelat'])
for n in range(S0array_snowballmelt.size):
model2.subprocess['insolation'].S0 = np.flipud(S0array_snowballmelt)[n]
model2.integrate_years(10, verbose=False)
icelat_snowballmelt_cooling[n] = np.max(model2.diagnostics['icelat'])
Explanation: A roasty 60ºC, and the poles are above 20ºC. A tiny increase in $S_0$ has led to a very drastic change in the climate.
End of explanation
fig = plt.figure( figsize=(10,6) )
ax = fig.add_subplot(111)
ax.plot(S0array, icelat_cooling, 'r-', label='cooling' )
ax.plot(S0array, icelat_warming, 'b-', label='warming' )
ax.plot(S0array3, icelat3, 'g-', label='warming' )
ax.plot(S0array_snowballmelt, icelat_snowballmelt, 'b-' )
ax.plot(S0array_snowballmelt, icelat_snowballmelt_cooling, 'r-' )
ax.set_ylim(-10,100)
ax.set_yticks((0,15,30,45,60,75,90))
ax.grid()
ax.set_ylabel('Ice edge latitude', fontsize=16)
ax.set_xlabel('Solar constant (W m$^{-2}$)', fontsize=16)
ax.plot( [const.S0, const.S0], [-10, 100], 'k--', label='present-day' )
ax.legend(loc='upper left')
ax.set_title('Solar constant versus ice edge latitude in the EBM with albedo feedback', fontsize=16)
plt.show()
Explanation: Now we will complete the plot of ice edge versus solar constant.
End of explanation |
7,907 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example - Customize the μs-ALEX histogram
This notebook is part of smFRET burst analysis software FRETBursts.
In this notebook shows how to plot different styles of μs-ALEX histograms and $E$ and $S$ marginal distributions.
For a complete tutorial on burst analysis see
FRETBursts - us-ALEX smFRET burst analysis.
Step1: Get and process data
Step2: ALEX joint plot
The alex_jointplot function allows plotting an ALEX histogram with marginals.
This is how it looks by default
Step3: The inner plot in an hexbin plot, basically a 2D histogram with hexagonal bins.
This kind of histograms resembles a scatter plot when sample size is small,
and is immune from grid artifacts typical of rectangular grids.
For more info for hexbin see this document.
The marginal plots are histograms with an overlay KDE plot.
The same FRETBursts function that plots standalone E and S histograms
is used here to plot the marginals in the joint plot.
Below I show how to customize appearance and type of this plot.
Changing colors
By default the colormap range is computed on the range S=[0.2, 0.8],
so that the FRET populations (S ~ 0.5) have more contrast.
To normalize the colormap to the whole data use the vmax argument
Step4: Or you can manually choose the max value mapped by the colormap (vmax)
Step5: Changing the colormap will affect both inner and marginal plots
Step6: To pick a different color from the colormap for the marginal histograms use histcolor_id
Step7: Kinds of joint-plots
The inner plot can be changed to a scatter plot or a KDE plot
Step8: No marginals
Finally, we can plot only the hexbin 2D histogram without marginals
Step9: Figure layout
You can get an handle of the different axes in the figure for layout customization
Step10: alex_jointplot returns g which contains the axis handles (g.ax_join, g.ax_marg_x, g.ax_marg_y).
The object g is a seaborn.JointGrid.
Step11: Arguments of inner plots
Additional arguments can be passed to the inner or marginal plots passing
a dictionary to joint_kws and marginal_kws respectively.
The marginal plots are created by hist_burst_data
which is the same function used to plot standalone E and S histograms
in FRETBursts.
For example, we can remove the KDE overlay like this
Step12: Interactive plot | Python Code:
from fretbursts import *
sns = init_notebook(apionly=True)
print('seaborn version: ', sns.__version__)
# Tweak here matplotlib style
import matplotlib as mpl
mpl.rcParams['font.sans-serif'].insert(0, 'Arial')
mpl.rcParams['font.size'] = 12
%config InlineBackend.figure_format = 'retina'
Explanation: Example - Customize the μs-ALEX histogram
This notebook is part of smFRET burst analysis software FRETBursts.
In this notebook shows how to plot different styles of μs-ALEX histograms and $E$ and $S$ marginal distributions.
For a complete tutorial on burst analysis see
FRETBursts - us-ALEX smFRET burst analysis.
End of explanation
url = 'http://files.figshare.com/2182601/0023uLRpitc_NTP_20dT_0.5GndCl.hdf5'
download_file(url, save_dir='./data')
full_fname = "./data/0023uLRpitc_NTP_20dT_0.5GndCl.hdf5"
d = loader.photon_hdf5(full_fname)
loader.alex_apply_period(d)
d.calc_bg(bg.exp_fit, time_s=1000, tail_min_us=(800, 4000, 1500, 1000, 3000))
d.burst_search(L=10, m=10, F=6)
ds = d.select_bursts(select_bursts.size, add_naa=True, th1=30)
Explanation: Get and process data
End of explanation
alex_jointplot(ds)
Explanation: ALEX joint plot
The alex_jointplot function allows plotting an ALEX histogram with marginals.
This is how it looks by default:
End of explanation
alex_jointplot(ds, vmax_fret=False)
alex_jointplot(ds, vmax_fret=False, marginal_color=8)
alex_jointplot(ds, vmax_fret=False, marginal_color=7)
alex_jointplot(ds, kind='kde')
Explanation: The inner plot in an hexbin plot, basically a 2D histogram with hexagonal bins.
This kind of histograms resembles a scatter plot when sample size is small,
and is immune from grid artifacts typical of rectangular grids.
For more info for hexbin see this document.
The marginal plots are histograms with an overlay KDE plot.
The same FRETBursts function that plots standalone E and S histograms
is used here to plot the marginals in the joint plot.
Below I show how to customize appearance and type of this plot.
Changing colors
By default the colormap range is computed on the range S=[0.2, 0.8],
so that the FRET populations (S ~ 0.5) have more contrast.
To normalize the colormap to the whole data use the vmax argument:
End of explanation
alex_jointplot(ds, vmax=40)
Explanation: Or you can manually choose the max value mapped by the colormap (vmax):
End of explanation
alex_jointplot(ds, cmap='plasma')
Explanation: Changing the colormap will affect both inner and marginal plots:
End of explanation
alex_jointplot(ds, cmap='plasma', marginal_color=83)
Explanation: To pick a different color from the colormap for the marginal histograms use histcolor_id:
End of explanation
alex_jointplot(ds, kind='scatter')
alex_jointplot(ds, kind='kde')
dsf = ds.select_bursts(select_bursts.naa, th1=40)
alex_jointplot(dsf, kind='kde',
joint_kws={'shade': False, 'n_levels': 12, 'bw': 0.04})
Explanation: Kinds of joint-plots
The inner plot can be changed to a scatter plot or a KDE plot:
End of explanation
plt.figure(figsize=(5,5))
hexbin_alex(ds)
Explanation: No marginals
Finally, we can plot only the hexbin 2D histogram without marginals:
End of explanation
g = alex_jointplot(ds)
g.ax_marg_x.grid(False)
g.ax_marg_y.grid(False)
g.ax_joint.set_xlim(-0.1, 1.1)
g.ax_joint.set_ylim(-0.1, 1.1)
Explanation: Figure layout
You can get an handle of the different axes in the figure for layout customization:
End of explanation
g = alex_jointplot(ds)
g.ax_marg_x.grid(False)
g.ax_marg_y.grid(False)
g.ax_joint.set_xlim(-0.19, 1.19)
g.ax_joint.set_ylim(-0.19, 1.19)
plt.subplots_adjust(wspace=0, hspace=0)
g.ax_marg_y.spines['bottom'].set_visible(True)
g.ax_marg_x.spines['left'].set_visible(True)
g.ax_marg_y.tick_params(reset=True, bottom=True, top=False, right=False, labelleft=False)
g.ax_marg_x.tick_params(reset=True, left=True, top=False, right=False, labelbottom=False)
g = alex_jointplot(ds)
g.ax_marg_x.grid(False)
g.ax_marg_y.grid(False)
g.ax_joint.set_xlim(-0.19, 1.19)
g.ax_joint.set_ylim(-0.19, 1.19)
plt.subplots_adjust(wspace=0, hspace=0)
g.ax_marg_y.tick_params(reset=True, bottom=True, top=False, right=False, labelleft=False)
g.ax_marg_x.tick_params(reset=True, left=True, top=False, right=False, labelbottom=False)
g = alex_jointplot(ds)
g.ax_marg_x.grid(False, axis='x')
g.ax_marg_y.grid(False, axis='y')
g.ax_joint.set_xlim(-0.19, 1.19)
g.ax_joint.set_ylim(-0.19, 1.19)
plt.subplots_adjust(wspace=0, hspace=0)
Explanation: alex_jointplot returns g which contains the axis handles (g.ax_join, g.ax_marg_x, g.ax_marg_y).
The object g is a seaborn.JointGrid.
End of explanation
alex_jointplot(ds, marginal_kws={'show_kde': False})
Explanation: Arguments of inner plots
Additional arguments can be passed to the inner or marginal plots passing
a dictionary to joint_kws and marginal_kws respectively.
The marginal plots are created by hist_burst_data
which is the same function used to plot standalone E and S histograms
in FRETBursts.
For example, we can remove the KDE overlay like this:
End of explanation
from ipywidgets import widgets, interact, interactive, fixed
from IPython.display import display, display_png, display_svg, clear_output
from IPython.core.pylabtools import print_figure
cmaps = ['viridis', 'plasma', 'inferno', 'magma',
'afmhot', 'Blues', 'BuGn', 'BuPu', 'GnBu', 'YlGnBu',
'coolwarm', 'RdYlBu', 'RdYlGn', 'Spectral',]# 'icefire'] uncomment if using seaborn 0.8
@interact(overlay = widgets.RadioButtons(options=['fit model', 'KDE'], value='KDE'),
binwidth = widgets.FloatText(value=0.03, min=0.01, max=1),
bandwidth = widgets.FloatText(value=0.03, min=0.01, max=1),
gridsize = (10, 100),
min_size=(10, 500, 5),
cmap=widgets.Dropdown(value='Spectral', options=cmaps),
reverse_cmap = True,
vmax_fret = True,
)
def plot_(min_size=50, overlay='KDE', binwidth=0.03, bandwidth=0.03,
gridsize=50, cmap='Spectral', reverse_cmap=False,
vmax_fret=True):
dx = d.select_bursts(select_bursts.size, add_naa=True, th1=min_size)
bext.bursts_fitter(dx, 'E', binwidth=binwidth, bandwidth=bandwidth,
model=mfit.factory_three_gaussians())
bext.bursts_fitter(dx, 'S', binwidth=binwidth, bandwidth=bandwidth,
model=mfit.factory_two_gaussians())
if reverse_cmap: cmap += '_r'
if binwidth < 0.01: binwidth = 0.01
if bandwidth < 0.01: bandwidth = 0.01
if overlay == 'fit model':
marginal_kws = dict(binwidth=binwidth, show_model=True, pdf=True,
show_kde=False)
else:
marginal_kws = dict(binwidth=binwidth, show_kde=True,
bandwidth=bandwidth)
alex_jointplot(dx, cmap=cmap, gridsize=gridsize, vmax_fret=vmax_fret,
marginal_kws=marginal_kws,)
fig = gcf()
plt.close()
display(fig)
Explanation: Interactive plot
End of explanation |
7,908 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> The effect of weather temperature on frequency of crimes </center>
In this notebook, I examine the relationship between weather temperature and frequency of crimes. This analysis is based on crimes data from January,1st 2012 until June, 7th 2017. This dataset was pulled from City of Chicago Data Portal link. I also collected historical weather data from January,1st 2012 until June, 7th 2017 link.
Step1: Trend of Temperature in the past 5 years
Step2: Most common types of crimes in the past 5 years (2012-2017)
Step3: Trend of crime in the past 5 years
Step4: Rate of crime per year as a function of temperature
Step5: Visualizing any linear relationship between temperature and frequency of crime
Step6: Crime on week vs. weekend | Python Code:
#importing libraries
import pandas as pd
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
import seaborn as sns
import glob
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
#Compiling multiple csv files present in a folder together in one dataframe.
data = pd.DataFrame()
for f in glob.glob('./crimeData/*.csv'):
data = pd.concat([data,pd.read_csv(f)])
#Reading in Weather Data (average daily temperature)
temp = pd.read_csv('./climate_Data_Jan_1_2012_up_to_Jun_7_2017.csv')
temp.columns
'''
cleanDate_W: cleans and re-formats the date column in the weather data
'''
def cleanDate_W(d):
return (datetime.strptime(str(d), '%m/%d/%y').date())
temp['Date'] = temp['Date'].apply(cleanDate_W)
temp['Date']= pd.to_datetime(temp['Date'],errors='coerce')
temp['Day']= temp['Date'].dt.day
temp['Month']= temp['Date'].dt.month
temp['Year']= temp['Date'].dt.year
'''
cleanDate_S: cleans and re-formats the date column in the shootings data
'''
def cleanDate_S(d):
if(d==''):
return (d)
else:
return (datetime.strptime(str(d) ,'%m/%d/%Y %H:%M:%S %p').date()) #converting dates from type string to type date and time
data['Date'] = data['Date'].apply(cleanDate_S)
data['Date'] = pd.to_datetime(data['Date'],errors='coerce')
#merging the shootings and temp data based on the Date column
crimeTemp = data.merge(temp,how='inner',left_on='Date',right_on='Date')
crimeTemp.shape
#checking if the new column (Mean_Temp) has been added
crimeTemp.columns
crimeTemp.head(4)
C_count = crimeTemp [['Date','Primary Type','Mean_Temp']]
C_count ['Year'] = C_count['Date'].dt.year
C_count ['Month'] = C_count['Date'].dt.month
C_count ['Day'] = C_count['Date'].dt.day
Explanation: <center> The effect of weather temperature on frequency of crimes </center>
In this notebook, I examine the relationship between weather temperature and frequency of crimes. This analysis is based on crimes data from January,1st 2012 until June, 7th 2017. This dataset was pulled from City of Chicago Data Portal link. I also collected historical weather data from January,1st 2012 until June, 7th 2017 link.
End of explanation
plt.figure()
fig, ax = plt.subplots(figsize=(15,10))
for y in C_count['Year'].unique().tolist():
dat = C_count[C_count['Year']==y]
dat = dat[['Year','Month','Mean_Temp']].drop_duplicates()
dat = pd.DataFrame(dat.groupby(['Year','Month'])['Mean_Temp'].mean()) #get the mean temperature for each month
temps = [x[0] for x in dat.values.tolist()]
dates = dat.index.levels[1].tolist() #fixing the format of dates
ax.plot(dates,temps,label=y)
plt.xticks(C_count[C_count['Year']==2012]['Month'].unique().tolist())
plt.xlabel('Month')
plt.ylabel("Average Temperature")
plt.legend()
plt.show()
#number of days with 80 degrees and higher in each year
temp[(temp['Mean_Temp']>=80) & (temp['Month']>5)].groupby('Year')['Month'].count()
#temp[(temp['Mean_Temp']>=80) & (temp['Month']>5)].groupby('Year')['Month'].count().value_counts() #uncomment this line for a break down by month
Explanation: Trend of Temperature in the past 5 years
End of explanation
#in general, what are the most common types of crimes in the past 5 years
plt.figure(figsize=(10,10))
sns.barplot(y=C_count['Primary Type'].value_counts().index.tolist(),
x=C_count['Primary Type'].value_counts().values.tolist(),data=C_count,color='royalblue',orient='h')
Explanation: Most common types of crimes in the past 5 years (2012-2017)
End of explanation
#total number of crimes during the summer
crime_peak = C_count.groupby(['Year','Month'])['Primary Type'].count().reset_index() #crime peak in the summer
crime_peak[(crime_peak['Month']>5) & (crime_peak['Month']<9)].groupby('Year')['Primary Type'].sum()
#getting the number of crimes, irrespective of crime type, in each month for each year
crime_monthly_count = C_count.groupby([C_count['Date'].dt.year,C_count['Date'].dt.month])['Primary Type'].count()
crime_monthly_count.index.names=['Year','Month']
crime_monthly_count = crime_monthly_count.reset_index()
crime_monthly_count.head(3)
# the drop in 2017 is due to the incomplete data..
plt.figure()
fig, ax = plt.subplots(figsize=(10,10))
for y in crime_monthly_count['Year'].unique().tolist():
dat = crime_monthly_count[crime_monthly_count['Year']==y]
ax.plot(dat['Month'], dat['Primary Type'], label = y)
plt.xticks(crime_monthly_count[crime_monthly_count['Year']==2012]['Month'].unique().tolist())
plt.xlabel('Month')
plt.ylabel("Number of Crimes")
plt.legend()
plt.show()
Explanation: Trend of crime in the past 5 years
End of explanation
#total number of crimes per day in each month for each year
#i.e for each day, the average daily temperature was X and there were Y number of crimes.
crime_weather = C_count
crime_daily_C_Temperature = crime_weather.groupby(['Year','Month','Day'])['Primary Type'].count()
crime_daily_C_Temperature = crime_daily_C_Temperature.reset_index()
crime_daily_C_Temperature = crime_daily_C_Temperature.merge(temp,on=['Year','Month','Day'],how='inner')
crime_daily_C_Temperature
plt.figure(figsize=(15,15))
ax = sns.lmplot(x='Mean_Temp',y='Primary Type',hue='Year',data=crime_daily_C_Temperature,scatter=False)
Explanation: Rate of crime per year as a function of temperature
End of explanation
#breaking down the total number of crimes per day by crime type.
#i.e the 1462 crimes in January 1st, 2012 is now broken down to 335 incidents of thefts, 263 incidents of battery,..etc.
crimeReg = C_count.groupby(['Year','Month','Day'])['Primary Type'].value_counts()
crimeReg = pd.DataFrame(crimeReg)
crimeReg.columns=['Count']
crimeReg = crimeReg.reset_index()
crimeReg.head(3)
crimeReg_Temperature = crimeReg.merge(temp,on=['Year','Month','Day'],how='inner')
crimeReg_Temperature.head(3)
#crimeReg.to_csv('temp_reg_analysis.csv')
sns.lmplot(x='Mean_Temp',y='Count',hue='Primary Type',col='Primary Type',col_wrap=3,data=crimeReg_Temperature,scatter=True,fit_reg=False)
Explanation: Visualizing any linear relationship between temperature and frequency of crime
End of explanation
crimeReg_Temperature.head(3)
'''
Convert dates (%Y-%m-%d) to days (Sunday, Monday...etc.)
'''
def toDay(d):
return (datetime.strptime(str(d),'%Y-%m-%d %H:%M:%S').date().strftime('%A'))
crimeReg_Temperature['Day_Words'] = crimeReg_Temperature['Date'].apply(toDay)
dictDay= {'Saturday':'Weekend','Sunday':'Weekend','Friday':'Weekend','Monday':'Weekday','Tuesday':'Weekday','Wednesday':'Weekday','Thursday':'Weekday','Friday':'Weekday'}
crimeReg_Temperature['Day_Words']= crimeReg_Temperature['Day_Words'].map(dictDay)
crimeReg_Temperature.head(3)
'''
Green: Weekday
Blue: Weekend
Trying to find if the relationship between crime and temperature changes between weekends and weekedays.
Only Battery and Criminal Damage tend to be high on weekends as the temperature increases.
Some of the remaining types of crimes, however, show an increase on weekdays, but not on weekends.
'''
plt.figure(figsize=(15,15))
sns.lmplot('Mean_Temp','Count',hue='Day_Words',data=crimeReg_Temperature,scatter=False,col='Primary Type',col_wrap=3)
#summary:
#results below show that only batter tend to occure more frequently on warm days especially on weekends (which is similar to the shootings pattern).
#However, remaining patterns are mainly happening on weekdays
Explanation: Crime on week vs. weekend
End of explanation |
7,909 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<H1>Bidirectional connections as a function of the distance </H1>
We will test whether bidirectionally connected inhibitory interneurons are over-represented as a function of the intersomatic distance.
Step2: <H2> Load all distances from connected PV cells</H2>
Step4: <H2>Distances in recurrently connected inhibitory neurons</H2> | Python Code:
%pylab inline
import warnings
from inet import DataLoader, __version__
from inet.motifs import iicounter
from inet.utils import II_slice
print('Inet version {}'.format(__version__))
# use filenames in the dataset to read list of distances to be read
mydataset = DataLoader('../data/PV')
pvfiles = [ i for i in range(len(mydataset)) if int(mydataset.filename(i)[0])>1 ]
print('{} experiments with 2 or more PV-cells'.format(len(pvfiles)))
Explanation: <H1>Bidirectional connections as a function of the distance </H1>
We will test whether bidirectionally connected inhibitory interneurons are over-represented as a function of the intersomatic distance.
End of explanation
# read distances from between inhibitory neurons
def read_dist(fname):
get distances between inhibitory pairs of neurons
from a matrix of intersomatic distances.
Argument:
fname: string
the matrix name to that contains the connected synapses (*.syn)
# take all non-diagonal elements
mypath = '../data/PV/' + fname[:-3] + 'dist'
try:
D = np.loadtxt(mypath)
D = II_slice(D, int(fname[0]))
idx = np.where(~np.eye(D.shape[0], dtype = bool))
mydist = np.abs(D[idx]).tolist()
return(mydist)
except IOError:
warnings.warn(mypath + ' not found!')
return([])
dist_tested = list()
for i in pvfiles:
dist_tested += read_dist(mydataset.filename(i))
print('{} total distances read'.format(len(dist_tested)))
mybins = arange(0,600, 50)
plt.hist(dist_tested, bins = mybins, facecolor='white', lw=2);
plt.ylim(ymax=50);
plt.ylabel('Inhbitory chemical synapses');
plt.xlabel('Intersomatic distance ($\mu$m)');
Explanation: <H2> Load all distances from connected PV cells</H2>
End of explanation
def read_rec_dist(fname):
get distances between bidirectionally connected interneurons
from a matrix of intersomatic distances.
Argument:
fname: string
the matrix name to that contains the connected synapses (*.syn)
# take all non-diagonal elements
mydistpath = '../data/PV/' + fname[:-3] + 'dist'
try:
D = II_slice(np.loadtxt(mydistpath), int(fname[0]))
except IOError:
warnings.warn(mydistpath + ' not found!')
return([])
try:
S = np.loadtxt('../data/PV/'+fname)
except IOError:
warnings.warn(fname + ' not found!')
return([])
S = II_slice(S, int(fname[0]))
S[S==2] = 0 # remove gaps
S[S==3] = 1 # remove gaps in chemical
x,y = np.nonzero(S)
ids = zip(x,y)
mydist = list()
if ids>0:
for i,j in ids:
if S[j,i] == 1:
mydist.append(D[i,j])
print(np.unique(np.abs(mydist)))
return( np.unique(np.abs(mydist)).tolist() )
# Number of bidirectionally connected interneurons
mydataset.motif['ii_c2']
# select experiments with bidirectional motifs
mybidirec = [i for i in range(len(mydataset)) if mydataset.motifs(i)['ii_c2']['found']>0 ]
for i in mybidirec:
print('Experiment {:3d}, filename: {}'.format(i, mydataset.filename(i)))
dist_found = list()
for i in mybidirec:
dist_found += read_rec_dist(mydataset.filename(i))
dist_found
mybins = arange(0,550, 50)
bid_tested = np.unique(dist_tested)
plt.hist(bid_tested, bins = mybins, facecolor='white', lw=2);
plt.ylim(ymax=20);
plt.ylabel('Inhbitory chemical synapses');
plt.xlabel('Intersomatic distance ($\mu$m)');
plt.hist(dist_found, bins = mybins, facecolor='gray', lw=2);
Explanation: <H2>Distances in recurrently connected inhibitory neurons</H2>
End of explanation |
7,910 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating Customer Segments
In this project we will analyze a dataset containing annual spending amounts for internal structure, to understand the variation in the different types of customers that a wholesale distributor interacts with.
The dataset can be downloaded from
Step1: Feature Transformation
The first PCA dimension is the dimension in the data with highest variance. Intuitively, it corresponds to the 'longest' vector one can find in the 6-dimensional feature space that captures the data, that is, the eigenvector with the largest eigenvalue.
The first component will carry a high load of the 'Fresh' feature, as this feature seems to vary more than any of the other features (according to the README.md-file, 'Fresh' has the highest variance). Moreover, this feature seems to vary independently of the others, that is, a high or low value of 'Fresh' is not very informative for the values of the other features. A pratical interpretation of these observations could be that some of the supplied customers focus on fresh items, whereas other focus on non-fresh items.
ICA, as opposed to PCA, finds the subcomponents that are statistically independent. ICA also finds 'Fresh' as one of the first components. The other components, however, may differ, as they need not be orthogonal in the feature space (in contrast to PCA).
PCA
Step2: The explained variance is high for the first two dimensions (45.96 % and 40.52 %, respectively), but drops significantly beginning with the third dimension (7.00 % for the third, 4.40 % for the fourth dimension). Thus, the first two components explain already 86.5 % of the variation in the data.
How many dimension to choose for the analysis really depends on the goal of the analysis. Even though PCA reduces the feature space (with all advantages that brings, such as faster computations) and makes interpreting the data easier for us by projecting them down to a lower dimension, it necessarily comes with a loss of information that may or may not be desired.
It the case at hand, assuming interpretation is the goal (creating customer segments) and given the sharp drop of the explained variance after the second component, we would choose the first two dimensions for analysis.
Step3: The first dimension seems to basically represent only the 'fresh'-feature, as this feature has a strong negative projection on the first dimension. The other features have rather weak (mostly negative) projections on the first dimension. That is, the first dimension basically tells us whether the 'fresh'-feature value is high or low, mixed with a little bit of information from the other features.
The second dimension is mainly represented by the features 'Grocery', 'Milk' and 'Detergents', in the order of decreasing importance, and has rather low correlation with the other features.
There are two main uses of this information. The first use is feature interpretation and hypothesis formation. We could form initial conjectures about the customer segments contained in the data. One conjecture could be that the bulk of customers can be split into customers ordering mainly 'fresh' items and customers mainly ordering 'Grocery', 'Milk' and 'Detergents' from the wholesale distributor. The second use is that, given knowledge of the PCA components, new features can be engineered for further analysis of the problem. These features could be generated by applying an exact PCA-transformation or by using some heuristic based on the feature combinations recovered in PCA.
ICA
Step4: The first vector [-0.04771087 0.00496636 0.00492989 0.00208307 -0.0059068 0.00159593] again represents mainly the 'fresh'-feature, with a coefficient of -0.0477. The other features have a rather weak projection on the first dimension.
The second vector [ 0.00182027 0.0571306 -0.04596392 -0.00113553 0.00928388 -0.00925863] corresponds mainly to the features 'Milk' and 'Grocery', but in different directions. This indicates that, other things equal, high 'Milk'-spending is associated with low 'Grocery'-spending and vice versa.
The third vector [ 0.00360762 -0.01311074 -0.09638513 0.00448148 0.08132511 0.00872532] has as strong association with the 'Grocery'- and 'Detergents_Paper'-features, again in opposite directions. This indicates a negative association between these features across the wholesalers customers.
The main charactistic of the fourth vector [ 0.00463807 0.00127625 0.00476776 0.00160491 -0.00146026 -0.02758939] is that this vector has a relatively strong negative association with 'delicatessen' (and only rather weak associations with the other features). Even though the coefficient are very low, the vector permits the interpretation that 'delicatessen' are negativly related to the 'fresh'- and 'grocery'-features.
Clustering
In this section we will choose either K Means clustering or Gaussian Mixed Models clustering, which implements expectation-maximization. Then we will sample elements from the clusters to understand their significance.
Choosing a Cluster Type
K Means Clustering or Gaussian Mixture Models?
Before discussing the advantages of K Means vs Gaussian Mixture models, it is helpful to observe that both methods are actually very similar. The main difference is that Gaussian Mixture models make a probabilistic assignment of points to classes depending on some distance metric, whereas K Means makes a deterministic assignment depending on some metric. Now, when the variance of the Gaussian mixtures is very small, this method becomes very similar to K Means, since the assignment probabilities to a specific cluster converge to 0 or 1 for any point in the domain. Because of the probabilistic assignment, Gaussian Mixtures (in contrast to K Means) are often characterized as soft clustering algorithms.
An advantage of Gaussian Mixture models is that, if there is some a priori uncertainty about the assignment of a point to a cluster, this uncertainty is inherently reflected in the probabilistic model (soft assignment) and assignment probabilities can be computed for any data point after the model is trained. On the other hand, if a priori the clusters assignments are expected to be deterministic, K Means has advantages. An example would be a data generating process that actually is a mixture of Gaussians. Applying a Gaussian mixture model is more natural given this data generating process. When it comes to processing speed, the EM algorithm with Gaussian mixtures is generally slightly slower than Lloyd's algorithm for K Means, since computing the normal probability (EM) is generally slower than computing the L2-norm (K Means). A disadvantage of both methods is that they can get stuck in local minima (this can be considered as the cost of solving NP-hard problems (global min for k-means) approximately).
Since there is no strong indication that the data are generated from a mixture of normals (this assesment may be different given more information about the nature of the spending data) and the goal is to "hard"-cluster them (and not assign probabilities), I decided the use the general-purpose k-means algorithm.
A decision on the number of clusters will be made by visualizing the final clustering and deciding whether k equals the number of data centers found by visual inspection. Note that many other approaches for this task could be utilized, such as silhoutte analysis (see for example http
Step5: The first cluster contains customers that have vastly (around 3 times) higher spendings in the 'Fresh'-category compared to the average, indicating that those customers specialize in selling fresh products. Also, customers in this cluster tend to place many orders in the 'Frozen'- and 'Delicatessen'-Category, but relatively few in the 'Detergents and Paper'-category.
Customers in the second cluster tend to spend the most overall, with particularly high spendings in the categories 'Milk', 'Grocery' and 'Detergents and Paper' and relatively low spendings in the 'Fresh' and 'Frozen' categories. Overall, this indicates that customers in this segment sell products that are more durable (i.e. not fresh).
The last cluster reflects small customers that have below-average annual spendings for each of the items. Appart from the low total spending, it is apparent that the spending distribution across categories is not pathological, that is, there is no category for which spendings are particularly low or high (given that spendings are low overall).
Regarding the question targeted at distinguishing the clusters visually
Step6: Quantifying the quality of clustering via silhouette plots
Another intrinsic metric to evaluate the quality of a clustering is silhouette analysis, which can also be applied to clustering algorithms other than k-means that we will discuss later in this chapter. Silhouette analysis can be used as a graphical tool to plot a measure of how tightly grouped the samples in the clusters are. To calculate the silhouette coefficient of a single sample in our dataset, we can apply the following three steps
Step7: Thus our clustering with 3 centroids is good.
Step8: Also the regions are 3 which validates our assumption.
Apply different unsupervised clustering techniques using Scikit-Learn
Applying agglomerative clustering via scikit-learn
Step9: K Means
Step10: Affinity Propogation
Step11: MeanShift
Step12: Mixture of Guassian Models
Step13: | Python Code:
# Import libraries: NumPy, pandas, matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Tell iPython to include plots inline in the notebook
%matplotlib inline
# read .csv from provided dataset
csv_filename="Wholesale customers data.csv"
# df=pd.read_csv(csv_filename,index_col=0)
df=pd.read_csv(csv_filename)
df.head()
features = df.columns[2:]
features
data = df[features]
print(data.head(5))
Explanation: Creating Customer Segments
In this project we will analyze a dataset containing annual spending amounts for internal structure, to understand the variation in the different types of customers that a wholesale distributor interacts with.
The dataset can be downloaded from : https://archive.ics.uci.edu/ml/datasets/Wholesale+customers
It contains the folliwing attributes:
1. FRESH: annual spending (m.u.) on fresh products (Continuous)
2. MILK: annual spending (m.u.) on milk products (Continuous)
3. GROCERY: annual spending (m.u.)on grocery products (Continuous)
4. FROZEN: annual spending (m.u.)on frozen products (Continuous)
5. DETERGENTS_PAPER: annual spending (m.u.) on detergents and paper products (Continuous)
6. DELICATESSEN: annual spending (m.u.)on and delicatessen products (Continuous)
7. CHANNEL: customer™ Channel - Horeca (Hotel/Restaurant/Cafe) or Retail channel (Nominal)
8. REGION: customers™ Region - Lisnon, Oporto or Other (Nominal)
We would not be using the 2 columns 'Channel' and 'Region' as they represent classes. Instead we would use the other 6 attributes for customer clustering.
End of explanation
# Apply PCA with the same number of dimensions as variables in the dataset
from sklearn.decomposition import PCA
pca = PCA(n_components=6) # 6 components for 6 variables
pca.fit(data)
# Print the components and the amount of variance in the data contained in each dimension
print(pca.components_)
print(pca.explained_variance_ratio_)
Explanation: Feature Transformation
The first PCA dimension is the dimension in the data with highest variance. Intuitively, it corresponds to the 'longest' vector one can find in the 6-dimensional feature space that captures the data, that is, the eigenvector with the largest eigenvalue.
The first component will carry a high load of the 'Fresh' feature, as this feature seems to vary more than any of the other features (according to the README.md-file, 'Fresh' has the highest variance). Moreover, this feature seems to vary independently of the others, that is, a high or low value of 'Fresh' is not very informative for the values of the other features. A pratical interpretation of these observations could be that some of the supplied customers focus on fresh items, whereas other focus on non-fresh items.
ICA, as opposed to PCA, finds the subcomponents that are statistically independent. ICA also finds 'Fresh' as one of the first components. The other components, however, may differ, as they need not be orthogonal in the feature space (in contrast to PCA).
PCA
End of explanation
plt.plot(list(pca.explained_variance_ratio_),'-o')
plt.title('Explained variance ratio as function of PCA components')
plt.ylabel('Explained variance ratio')
plt.xlabel('Component')
plt.show()
Explanation: The explained variance is high for the first two dimensions (45.96 % and 40.52 %, respectively), but drops significantly beginning with the third dimension (7.00 % for the third, 4.40 % for the fourth dimension). Thus, the first two components explain already 86.5 % of the variation in the data.
How many dimension to choose for the analysis really depends on the goal of the analysis. Even though PCA reduces the feature space (with all advantages that brings, such as faster computations) and makes interpreting the data easier for us by projecting them down to a lower dimension, it necessarily comes with a loss of information that may or may not be desired.
It the case at hand, assuming interpretation is the goal (creating customer segments) and given the sharp drop of the explained variance after the second component, we would choose the first two dimensions for analysis.
End of explanation
# Fit an ICA model to the data
# Note: Adjust the data to have center at the origin first!
def center_data(data, rescale = 0):
centeredData = data.copy()
for col in centeredData.columns:
centeredData[col] = (centeredData[col] - np.mean(centeredData[col]))/ (1 + rescale * np.std(centeredData[col]))
return centeredData
from sklearn.decomposition import FastICA
#data_centered = center_data(data)
ica = FastICA(n_components=6, whiten=True)
ica.fit(center_data(data,0))
# Print the independent components
print(ica.components_)
# Print the independent components (rescaled again)
print('Independent components scaled with mean')
print(np.multiply(ica.components_,list(np.mean(data))))
Explanation: The first dimension seems to basically represent only the 'fresh'-feature, as this feature has a strong negative projection on the first dimension. The other features have rather weak (mostly negative) projections on the first dimension. That is, the first dimension basically tells us whether the 'fresh'-feature value is high or low, mixed with a little bit of information from the other features.
The second dimension is mainly represented by the features 'Grocery', 'Milk' and 'Detergents', in the order of decreasing importance, and has rather low correlation with the other features.
There are two main uses of this information. The first use is feature interpretation and hypothesis formation. We could form initial conjectures about the customer segments contained in the data. One conjecture could be that the bulk of customers can be split into customers ordering mainly 'fresh' items and customers mainly ordering 'Grocery', 'Milk' and 'Detergents' from the wholesale distributor. The second use is that, given knowledge of the PCA components, new features can be engineered for further analysis of the problem. These features could be generated by applying an exact PCA-transformation or by using some heuristic based on the feature combinations recovered in PCA.
ICA
End of explanation
# Import clustering modules
from sklearn.cluster import KMeans
from sklearn.mixture import GMM
# First we reduce the data to two dimensions using PCA to capture variation
pca = PCA(n_components=2)
reduced_data = pca.fit_transform(data)
print(reduced_data[:10]) # print upto 10 elements
# Implement your clustering algorithm here, and fit it to the reduced data for visualization
# The visualizer below assumes your clustering object is named 'clusters'
# TRIED OUT 2,3,4,5,6 CLUSTERS AND CONCLUDED THAT 3 CLUSTERS ARE A SENSIBLE CHOICE BASED ON VISUAL INSPECTION, SINCE
# WE OBTAIN ONE CENTRAL CLUSTER AND TWO CLUSTERS THAT SPREAD FAR OUT IN TWO DIRECTIONS.
kmeans = KMeans(n_clusters=3)
clusters = kmeans.fit(reduced_data)
print(clusters)
# Plot the decision boundary by building a mesh grid to populate a graph.
x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
hx = (x_max-x_min)/1000.
hy = (y_max-y_min)/1000.
xx, yy = np.meshgrid(np.arange(x_min, x_max, hx), np.arange(y_min, y_max, hy))
# Obtain labels for each point in mesh. Use last trained model.
Z = clusters.predict(np.c_[xx.ravel(), yy.ravel()])
# Find the centroids for KMeans or the cluster means for GMM
centroids = kmeans.cluster_centers_
print('*** K MEANS CENTROIDS ***')
print(centroids)
# TRANSFORM DATA BACK TO ORIGINAL SPACE FOR ANSWERING 7
print('*** CENTROIDS TRANSFERED TO ORIGINAL SPACE ***')
print(pca.inverse_transform(centroids))
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1)
plt.clf()
plt.imshow(Z, interpolation='nearest',
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
cmap=plt.cm.Paired,
aspect='auto', origin='lower')
plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', s=169, linewidths=3,
color='w', zorder=10)
plt.title('Clustering on the wholesale grocery dataset (PCA-reduced data)\n'
'Centroids are marked with white cross')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()
Explanation: The first vector [-0.04771087 0.00496636 0.00492989 0.00208307 -0.0059068 0.00159593] again represents mainly the 'fresh'-feature, with a coefficient of -0.0477. The other features have a rather weak projection on the first dimension.
The second vector [ 0.00182027 0.0571306 -0.04596392 -0.00113553 0.00928388 -0.00925863] corresponds mainly to the features 'Milk' and 'Grocery', but in different directions. This indicates that, other things equal, high 'Milk'-spending is associated with low 'Grocery'-spending and vice versa.
The third vector [ 0.00360762 -0.01311074 -0.09638513 0.00448148 0.08132511 0.00872532] has as strong association with the 'Grocery'- and 'Detergents_Paper'-features, again in opposite directions. This indicates a negative association between these features across the wholesalers customers.
The main charactistic of the fourth vector [ 0.00463807 0.00127625 0.00476776 0.00160491 -0.00146026 -0.02758939] is that this vector has a relatively strong negative association with 'delicatessen' (and only rather weak associations with the other features). Even though the coefficient are very low, the vector permits the interpretation that 'delicatessen' are negativly related to the 'fresh'- and 'grocery'-features.
Clustering
In this section we will choose either K Means clustering or Gaussian Mixed Models clustering, which implements expectation-maximization. Then we will sample elements from the clusters to understand their significance.
Choosing a Cluster Type
K Means Clustering or Gaussian Mixture Models?
Before discussing the advantages of K Means vs Gaussian Mixture models, it is helpful to observe that both methods are actually very similar. The main difference is that Gaussian Mixture models make a probabilistic assignment of points to classes depending on some distance metric, whereas K Means makes a deterministic assignment depending on some metric. Now, when the variance of the Gaussian mixtures is very small, this method becomes very similar to K Means, since the assignment probabilities to a specific cluster converge to 0 or 1 for any point in the domain. Because of the probabilistic assignment, Gaussian Mixtures (in contrast to K Means) are often characterized as soft clustering algorithms.
An advantage of Gaussian Mixture models is that, if there is some a priori uncertainty about the assignment of a point to a cluster, this uncertainty is inherently reflected in the probabilistic model (soft assignment) and assignment probabilities can be computed for any data point after the model is trained. On the other hand, if a priori the clusters assignments are expected to be deterministic, K Means has advantages. An example would be a data generating process that actually is a mixture of Gaussians. Applying a Gaussian mixture model is more natural given this data generating process. When it comes to processing speed, the EM algorithm with Gaussian mixtures is generally slightly slower than Lloyd's algorithm for K Means, since computing the normal probability (EM) is generally slower than computing the L2-norm (K Means). A disadvantage of both methods is that they can get stuck in local minima (this can be considered as the cost of solving NP-hard problems (global min for k-means) approximately).
Since there is no strong indication that the data are generated from a mixture of normals (this assesment may be different given more information about the nature of the spending data) and the goal is to "hard"-cluster them (and not assign probabilities), I decided the use the general-purpose k-means algorithm.
A decision on the number of clusters will be made by visualizing the final clustering and deciding whether k equals the number of data centers found by visual inspection. Note that many other approaches for this task could be utilized, such as silhoutte analysis (see for example http://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html).
Below is some starter code to help you visualize some cluster data. The visualization is based on this demo from the sklearn documentation.
End of explanation
X = df[features]
y = df['Region']
distortions = []
for i in range(1, 11):
km = KMeans(n_clusters=i,
init='k-means++',
n_init=10,
max_iter=300,
random_state=0)
km.fit(X)
distortions .append(km.inertia_)
plt.plot(range(1,11), distortions , marker='o')
plt.xlabel('Number of clusters')
plt.ylabel('Distortion')
plt.tight_layout()
#plt.savefig('./figures/elbow.png', dpi=300)
plt.show()
Explanation: The first cluster contains customers that have vastly (around 3 times) higher spendings in the 'Fresh'-category compared to the average, indicating that those customers specialize in selling fresh products. Also, customers in this cluster tend to place many orders in the 'Frozen'- and 'Delicatessen'-Category, but relatively few in the 'Detergents and Paper'-category.
Customers in the second cluster tend to spend the most overall, with particularly high spendings in the categories 'Milk', 'Grocery' and 'Detergents and Paper' and relatively low spendings in the 'Fresh' and 'Frozen' categories. Overall, this indicates that customers in this segment sell products that are more durable (i.e. not fresh).
The last cluster reflects small customers that have below-average annual spendings for each of the items. Appart from the low total spending, it is apparent that the spending distribution across categories is not pathological, that is, there is no category for which spendings are particularly low or high (given that spendings are low overall).
Regarding the question targeted at distinguishing the clusters visually: I generally had no problems distinguishing the clusters. Besides that, one observation is that the PCA reduction does not result in clusters that are well separated from each other. Reducing the data to three or four dimensions only (instead of two) may result in clusters that have more separation, but adds the complexity of having to visually represent the data using an (hyper-)cube instead of a plane. Of course, one could try to improve cluster representation using a 3-component PCA and a cube.
CENTROIDS TRANSFERED TO ORIGINAL SPACE
[
[ 35908.28; 6409.09; 6027.84; 6808.70; 1088.15; 2904.19] (first cluster)
[ 7896.20; 18663.60; 27183.75; 2394.58; 12120.22; 2875.42] (second cluster)
[ 8276.38; 3689.87; 5320.73; 2495.45; 1776.40; 1063.97]] (third cluster)
<hr>
Elbow Method
Using the elbow method to find the optimal number of clusters
One of the main challenges in unsupervised learning is that we do not know the definitive answer. We don't have the ground truth class labels in our dataset that allow us to apply the techniques in order to evaluate the performance of a supervised model. Thus, in order to quantify the quality of clustering, we need to use intrinsic metrics—such as the within-cluster SSE (distortion) to compare the performance of different k-means clusterings. Conveniently, we don't need to compute the within-cluster SSE explicitly as it is already accessible via the inertia_ attribute after fitting a KMeans model.
Based on the within-cluster SSE, we can use a graphical tool, the so-called elbow method, to estimate the optimal number of clusters k for a given task. Intuitively,
we can say that, if k increases, the distortion will decrease. This is because the
samples will be closer to the centroids they are assigned to. The idea behind the elbow method is to identify the value of k where the distortion begins to increase most rapidly, which will become more clear if we plot distortion for different
values of k:
End of explanation
import numpy as np
from matplotlib import cm
from sklearn.metrics import silhouette_samples
km = KMeans(n_clusters=3,
init='k-means++',
n_init=10,
max_iter=300,
tol=1e-04,
random_state=0)
y_km = km.fit_predict(X)
cluster_labels = np.unique(y_km)
n_clusters = cluster_labels.shape[0]
silhouette_vals = silhouette_samples(X, y_km, metric='euclidean')
y_ax_lower, y_ax_upper = 0, 0
yticks = []
for i, c in enumerate(cluster_labels):
c_silhouette_vals = silhouette_vals[y_km == c]
c_silhouette_vals.sort()
y_ax_upper += len(c_silhouette_vals)
color = cm.jet(i / n_clusters)
plt.barh(range(y_ax_lower, y_ax_upper), c_silhouette_vals, height=1.0,
edgecolor='none', color=color)
yticks.append((y_ax_lower + y_ax_upper) / 2)
y_ax_lower += len(c_silhouette_vals)
silhouette_avg = np.mean(silhouette_vals)
plt.axvline(silhouette_avg, color="red", linestyle="--")
plt.yticks(yticks, cluster_labels + 1)
plt.ylabel('Cluster')
plt.xlabel('Silhouette coefficient')
plt.tight_layout()
# plt.savefig('./figures/silhouette.png', dpi=300)
plt.show()
Explanation: Quantifying the quality of clustering via silhouette plots
Another intrinsic metric to evaluate the quality of a clustering is silhouette analysis, which can also be applied to clustering algorithms other than k-means that we will discuss later in this chapter. Silhouette analysis can be used as a graphical tool to plot a measure of how tightly grouped the samples in the clusters are. To calculate the silhouette coefficient of a single sample in our dataset, we can apply the following three steps:
1. Calculate the cluster cohesion a(i) as the average distance between a sample x(i) and all other points in the same cluster.
2. Calculate the cluster separation b(i) from the next closest cluster as the average distance between the sample x(i) and all samples in the nearest cluster.
3. Calculate the silhouette s(i) as the difference between cluster cohesion and separation divided by the greater of the two as shown :
s(i) = b(i) - a(i) / max(b(i),a(i))
The silhouette coefficient is bounded in the range -1 to 1. Based on the preceding formula, we can see that the silhouette coefficient is 0 if the cluster separation and cohesion are equal (b(i)=a(i)). Furthermore, we get close to an ideal silhouette coefficient of 1 if (b(i)>>a(i)) since b(i) quantifies how dissimilar a sample is to other clusters, and a(i) tells us how similar it is to the other samples in its own cluster, respectively.
The silhouette coefficient is available as silhouette_samples from scikit-learn's metric module, and optionally the silhouette_scores can be imported. This calculates the average silhouette coefficient across all samples, which is equivalent to numpy.mean(silhouette_samples(…)). By executing the following code, we will now create a plot of the silhouette coefficients for a k-means clustering with k=3:
End of explanation
y.unique()
Explanation: Thus our clustering with 3 centroids is good.
End of explanation
from sklearn.cluster import AgglomerativeClustering
ac = AgglomerativeClustering(n_clusters=3, affinity='euclidean', linkage='complete')
labels = ac.fit_predict(X)
print('Cluster labels: %s' % labels)
from sklearn.cross_validation import train_test_split
X = df[features]
y = df['Region']
X_train, X_test, y_train, y_test = train_test_split(X, y ,test_size=0.25, random_state=42)
Explanation: Also the regions are 3 which validates our assumption.
Apply different unsupervised clustering techniques using Scikit-Learn
Applying agglomerative clustering via scikit-learn
End of explanation
from sklearn import cluster
clf = cluster.KMeans(init='k-means++', n_clusters=3, random_state=5)
clf.fit(X_train)
print (clf.labels_.shape)
print (clf.labels_)
# Predict clusters on testing data
y_pred = clf.predict(X_test)
from sklearn import metrics
print ("Addjusted rand score:{:.2}".format(metrics.adjusted_rand_score(y_test, y_pred)))
print ("Homogeneity score:{:.2} ".format(metrics.homogeneity_score(y_test, y_pred)) )
print ("Completeness score: {:.2} ".format(metrics.completeness_score(y_test, y_pred)))
print ("Confusion matrix")
print (metrics.confusion_matrix(y_test, y_pred))
Explanation: K Means
End of explanation
# Affinity propagation
aff = cluster.AffinityPropagation()
aff.fit(X_train)
print (aff.cluster_centers_indices_.shape)
y_pred = aff.predict(X_test)
from sklearn import metrics
print ("Addjusted rand score:{:.2}".format(metrics.adjusted_rand_score(y_test, y_pred)))
print ("Homogeneity score:{:.2} ".format(metrics.homogeneity_score(y_test, y_pred)) )
print ("Completeness score: {:.2} ".format(metrics.completeness_score(y_test, y_pred)))
print ("Confusion matrix")
print (metrics.confusion_matrix(y_test, y_pred))
Explanation: Affinity Propogation
End of explanation
ms = cluster.MeanShift()
ms.fit(X_train)
print (ms.cluster_centers_)
y_pred = ms.predict(X_test)
from sklearn import metrics
print ("Addjusted rand score:{:.2}".format(metrics.adjusted_rand_score(y_test, y_pred)))
print ("Homogeneity score:{:.2} ".format(metrics.homogeneity_score(y_test, y_pred)) )
print ("Completeness score: {:.2} ".format(metrics.completeness_score(y_test, y_pred)))
print ("Confusion matrix")
print (metrics.confusion_matrix(y_test, y_pred))
Explanation: MeanShift
End of explanation
from sklearn import mixture
# Define a heldout dataset to estimate covariance type
X_train_heldout, X_test_heldout, y_train_heldout, y_test_heldout = train_test_split(
X_train, y_train,test_size=0.25, random_state=42)
for covariance_type in ['spherical','tied','diag','full']:
gm=mixture.GMM(n_components=3, covariance_type=covariance_type, random_state=42, n_init=5)
gm.fit(X_train_heldout)
y_pred=gm.predict(X_test_heldout)
print ("Adjusted rand score for covariance={}:{:.2}".format(covariance_type,
metrics.adjusted_rand_score(y_test_heldout, y_pred)))
gm = mixture.GMM(n_components=3, covariance_type='tied', random_state=42)
gm.fit(X_train)
# Print train clustering and confusion matrix
y_pred = gm.predict(X_test)
print ("Addjusted rand score:{:.2}".format(metrics.adjusted_rand_score(y_test, y_pred)))
print ("Homogeneity score:{:.2} ".format(metrics.homogeneity_score(y_test, y_pred)) )
print ("Completeness score: {:.2} ".format(metrics.completeness_score(y_test, y_pred)))
print ("Confusion matrix")
print (metrics.confusion_matrix(y_test, y_pred))
Explanation: Mixture of Guassian Models
End of explanation
pl=plt
from sklearn import decomposition
# In this case the seeding of the centers is deterministic,
# hence we run the kmeans algorithm only once with n_init=1
pca = decomposition.PCA(n_components=2).fit(X_train)
reduced_X_train = pca.transform(X_train)
# Step size of the mesh. Decrease to increase the quality of the VQ.
h = .01 # point in the mesh [x_min, m_max]x[y_min, y_max].
# Plot the decision boundary. For that, we will asign a color to each
x_min, x_max = reduced_X_train[:, 0].min() + 1, reduced_X_train[:, 0].max() - 1
y_min, y_max = reduced_X_train[:, 1].min() + 1, reduced_X_train[:, 1].max() - 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
gm.fit(reduced_X_train)
#print np.c_[xx.ravel(),yy.ravel()]
Z = gm.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
pl.figure(1)
pl.clf()
pl.imshow(Z, interpolation='nearest',
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
cmap=pl.cm.Paired,
aspect='auto', origin='lower')
#print reduced_X_train.shape
pl.plot(reduced_X_train[:, 0], reduced_X_train[:, 1], 'k.', markersize=2)
# Plot the centroids as a white X
centroids = gm.means_
pl.scatter(centroids[:, 0], centroids[:, 1],
marker='.', s=169, linewidths=3,
color='w', zorder=10)
pl.title('Mixture of gaussian models on the seeds dataset (PCA-reduced data)\n'
'Means are marked with white dots')
pl.xlim(x_min, x_max)
pl.ylim(y_min, y_max)
pl.xticks(())
pl.yticks(())
pl.show()
Explanation:
End of explanation |
7,911 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sobreajuste
Les voy a mostrar algo mágico. Y después les voy a contar por qué le puse el título a este documento.
Déjenme importar primero algunas bibliotecas de manejo de datos y aprendizaje automático (sí, efectivamente
Step1: Por supuesto, voy a utilizar los datos de casos de COVID-19 en Uruguay. No los tengo completos completos, pero gracias a la gente de GUIAD-Covid-19, me puedo acercar. De esos datos, para más magia, voy a usar solamente dos atributos
Step2: Y voy a utilizar una función polinomial de orden 5, para ver si podemos ajustar a los datos y encontrar un patrón. Este procedimiento se llama regresión, y es una de las herramientas de la Inteligencia Artificial.
Step3: Por increíble que parezca, hemos encontrado una función que ajusta casi perfectamente a los casos que se han confirmado como positivos en Uruguay. Y ahora, el toque final | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
Explanation: Sobreajuste
Les voy a mostrar algo mágico. Y después les voy a contar por qué le puse el título a este documento.
Déjenme importar primero algunas bibliotecas de manejo de datos y aprendizaje automático (sí, efectivamente: Inteligencia Artificial). Así verán que no hay truco, que lo que hago no es magia, sino simplemente computación y un poco de álgebra.
End of explanation
covid=pd.read_csv('https://raw.githubusercontent.com/natydasilva/COVID19-UDELAR/master/Datos/Datos_Nacionales/estadisticasUY.csv?token=ABCA7RFDBSMT4PMGJMNCXQS6RUVRA')
covid
data=covid.loc[3:,['dia', 'acumTestPositivos']]
data
Explanation: Por supuesto, voy a utilizar los datos de casos de COVID-19 en Uruguay. No los tengo completos completos, pero gracias a la gente de GUIAD-Covid-19, me puedo acercar. De esos datos, para más magia, voy a usar solamente dos atributos: el día desde el que empezamos a medir, y la cantidad de casos.
End of explanation
degree=5
x=data['dia']
x_plot=np.linspace(4,19,20)
y=data['acumTestPositivos']
X=x[:,np.newaxis]
X_plot=x_plot[:,np.newaxis]
plt.scatter(x,y, color='cornflowerblue', linewidth=2,
label="ground truth")
model = make_pipeline(PolynomialFeatures(degree), Ridge())
model.fit(X, y)
y_plot = model.predict(X_plot)
plt.plot(x_plot, y_plot, color='teal', linewidth=2,
label="degree %d" % degree)
plt.title("Casos positivos de COVID-19 en Uruguay")
plt.xlabel("día")
plt.ylabel("casos confirmados")
Explanation: Y voy a utilizar una función polinomial de orden 5, para ver si podemos ajustar a los datos y encontrar un patrón. Este procedimiento se llama regresión, y es una de las herramientas de la Inteligencia Artificial.
End of explanation
x_plot=x_plot=np.linspace(0,30,30)
plt.scatter(x,y, color='cornflowerblue', linewidth=2,
label="ground truth")
X_plot=x_plot[:,np.newaxis]
y_plot = model.predict(X_plot)
plt.plot(x_plot, y_plot, color='teal', linewidth=2,
label="degree %d" % degree)
plt.title("Predicción:Casos positivos de COVID-19 en Uruguay")
plt.xlabel("día")
plt.ylabel("casos confirmados")
Explanation: Por increíble que parezca, hemos encontrado una función que ajusta casi perfectamente a los casos que se han confirmado como positivos en Uruguay. Y ahora, el toque final: utilicemos esta función para predecir cuántos casos habrá en 10 días, de continuar con este ritmo.
End of explanation |
7,912 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AmicalSat ShockBurst image packets processing
This notebook shows how to process ShockBurst S-band image packets to reassemble the image file
Step1: The data shockburst.u8 contains ShockBurst frames without the 0xE7E7E7E7E7 address header (including frame counter, image payload and CRC). It has been obtained with nrf24.grc.
Step2: The CRC used in ShockBurst frames CRC16_CCITT_FALSE from this online calculator. Since the 0xE7E7E7E7E7 address is included in the CRC calculation but is missing in our data, we take this into account by modifying the initial XOR value.
Step3: Number of skipped frames
Step4: Number of correct frames
Step5: Write frames to a file according to their frame number. We do a majority voting to select among different frames with the same frame number (there are corrupted frames with good CRC). The file has gaps with zeros where frames are missing. | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
Explanation: AmicalSat ShockBurst image packets processing
This notebook shows how to process ShockBurst S-band image packets to reassemble the image file
End of explanation
data = np.fromfile('/home/daniel/debian_testing_chroot/tmp/shockburst.u8', dtype = 'uint8').reshape((-1,34))
Explanation: The data shockburst.u8 contains ShockBurst frames without the 0xE7E7E7E7E7 address header (including frame counter, image payload and CRC). It has been obtained with nrf24.grc.
End of explanation
crc_table = [
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
]
def crc(frame):
c = 0xB95E # CRC of initial E7E7E7E7E7 address field
for b in frame:
tbl_idx = ((c >> 8) ^ b) & 0xff
c = (crc_table[tbl_idx] ^ (c << 8)) & 0xffff
return c & 0xffff
crc_ok = np.array([crc(d) == 0 for d in data])
frame_count = data[crc_ok,:2].ravel().view('uint16')
frame_count_unique = np.unique(frame_count)
Explanation: The CRC used in ShockBurst frames CRC16_CCITT_FALSE from this online calculator. Since the 0xE7E7E7E7E7 address is included in the CRC calculation but is missing in our data, we take this into account by modifying the initial XOR value.
End of explanation
np.sum(np.diff(frame_count_unique)-1)
np.where(np.diff(frame_count_unique)-1)
Explanation: Number of skipped frames:
End of explanation
len(frame_count_unique)
plt.plot(np.diff(frame_count_unique)!=1)
Explanation: Number of correct frames:
End of explanation
frame_size = 30
with open('/tmp/file', 'wb') as f:
for count in frame_count_unique:
valid_frames = data[crc_ok][frame_count == count]
counter = Counter([bytes(frame[2:]) for frame in valid_frames])
f.seek(count * frame_size)
f.write(counter.most_common()[0][0])
Explanation: Write frames to a file according to their frame number. We do a majority voting to select among different frames with the same frame number (there are corrupted frames with good CRC). The file has gaps with zeros where frames are missing.
End of explanation |
7,913 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We now have almost everything we need to process our data files, only thing missing is a library to grab files
Step1: glob contains function glob that finds files that match a pattern
* matches 0+ characters; ? matches any one char
Step2: results in a list of strings, we can loop oer
we want to create sets of plots
Step3: We can ask Python to take different actions, depending on a condition, with an if statement
Step4: second line of code above uses keyword if to denote choice
if the test after if is true, the body of the if are executed
if test false the body else is executed
conditional statements don't have to include else - if not present python does nothing
Step5: we can also chain several tests together using elif, short for else if
Step6: NOTE
Step7: while or is true if at least one part is true
Step8: Challenge - making choices
Step9: Checking out data
we can use conditionals to check for suspcioious features in our datat
first 2 plots mzx inflamm per day seemed to rise in straight line
we can chek for this inside the for loop
Step10: let's check for the minima like we saw on third day (flat)
Step11: if nether of the conditions are met we can use else for all clear
Step12: let's test!
Step13: asked python to do something depending on diff conditions; we can also imaging not using the else so messages are only printed whens omething is wrong
Challenge - making choices 2 | Python Code:
import glob
import numpy
import matplotlib.pyplot
Explanation: We now have almost everything we need to process our data files, only thing missing is a library to grab files
End of explanation
print(glob.glob('data/inflammation*.csv'))
Explanation: glob contains function glob that finds files that match a pattern
* matches 0+ characters; ? matches any one char
End of explanation
%matplotlib inline
# loop here
counter = 0
for filename in glob.glob('data/*.csv'):
#counter+=1
counter = counter + 1
print("number of files:", counter)
counter = 0
for filename in glob.glob('data/infl*.csv'):
#counter+=1
counter = counter + 1
print("number of files:", counter)
counter = 0
for filename in glob.glob('data/infl*.csv'):
#counter+=1
data = numpy.loadtxt(fname=filename, delimiter=',')
print(filename, "mean is: ", data.mean())
counter = counter + 1
print("number of files:", counter)
%matplotlib inline
counter = 0
for filename in glob.glob('data/infl*.csv')[0:3]:
counter+=1
print(filename)
data = numpy.loadtxt(fname = filename, delimiter=',')
fig = matplotlib.pyplot.figure(figsize=(10.0,3.0))
axes1 = fig.add_subplot(1,3,1)
axes2 = fig.add_subplot(1,3,2)
axes3 = fig.add_subplot(1,3,3)
axes1.set_ylabel('average')
axes1.plot(data.mean(axis=0))
axes2.set_ylabel('max')
axes2.plot(data.max(axis=0))
axes3.set_ylabel('min')
axes3.plot(data.min(axis=0))
fig.tight_layout()
matplotlib.pyplot.show(fig)
print("number of files:", counter)
Explanation: results in a list of strings, we can loop oer
we want to create sets of plots
End of explanation
#We use an if statement to take different actions
#based on conditions
num = 37
if num > 100:
print('greater')
else:
print('not greater')
print('done')
Explanation: We can ask Python to take different actions, depending on a condition, with an if statement:
Making choices
last lesson we discovereed something suspicious in our inflammatin data by drawing plots
how can python recognized these different features and act on it
we will write code that runs on certain conditions
End of explanation
num = 53
print('before conditional...')
if num > 100:
print('53 is greater than 100')
print('...after conditional')
Explanation: second line of code above uses keyword if to denote choice
if the test after if is true, the body of the if are executed
if test false the body else is executed
conditional statements don't have to include else - if not present python does nothing
End of explanation
num = -3
if num > 0:
print(num, "is positive")
elif num == 0:
print(num, "is zero")
else:
print(num, "is negative")
Explanation: we can also chain several tests together using elif, short for else if
End of explanation
if (1 > 0) and (-1 > 0):
print('both parts are true')
else:
print('at least one part is false')
Explanation: NOTE: we use == to test for equality rather than single equal b/c the later is the assignment operator
we can also combine tests using and and or. and is only true if both parts are true
End of explanation
if (1 < 0) or (-1 < 0):
print('at least one test is true')
Explanation: while or is true if at least one part is true:
End of explanation
if 4 > 5:
print('A')
elif 4 == 5:
print('B')
elif 4 < 5:
print('C')
Explanation: Challenge - making choices:
Which of the following would be printed if you were to run this code? Why did you pick this answer?
A
B
C
B and C
python
if 4 > 5:
print('A')
elif 4 == 5:
print('B')
elif 4 < 5:
print('C')
End of explanation
if data.max(axis=0)[0] == 0 and data.max(axis=0)[20] == 20:
print('Suspicious looking maxima!')
Explanation: Checking out data
we can use conditionals to check for suspcioious features in our datat
first 2 plots mzx inflamm per day seemed to rise in straight line
we can chek for this inside the for loop
End of explanation
elif data.min(axis=0).sum() == 0:
print('Minima add up to zero!')
Explanation: let's check for the minima like we saw on third day (flat)
End of explanation
else:
print('seems OK!')
Explanation: if nether of the conditions are met we can use else for all clear
End of explanation
data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')
if data.max(axis=0)[0] == 0 and data.max(axis=0)[20] == 20:
print('Suspicious looking maxima!')
elif data.min(axis=0).sum() == 0:
print('Minima add up to zero!')
else:
print('Seems OK!')
data = numpy.loadtxt(fname='data/inflammation-03.csv', delimiter=',')
if data.max(axis=0)[0] == 0 and data.max(axis=0)[20] == 20:
print('Suspicious looking maxima!')
elif data.min(axis=0).sum() == 0:
print('Minima add up to zero!')
else:
print('Seems OK!')
Explanation: let's test!
End of explanation
if '':
print('empty string is true')
if 'word':
print('word is true')
if []:
print('empty list is true')
if [1, 2, 3]:
print('non-empty list is true')
if 0:
print('zero is true')
if 1:
print('one is true')
Explanation: asked python to do something depending on diff conditions; we can also imaging not using the else so messages are only printed whens omething is wrong
Challenge - making choices 2:
True and False are special words in Python called booleans which represent true and false statements. However, they aren’t the only values in Python that are true and false. In fact, any value can be used in an if or elif. After reading and running the code below, explain what the rule is for which values are considered true and which are considered false.
python
if '':
print('empty string is true')
if 'word':
print('word is true')
if []:
print('empty list is true')
if [1, 2, 3]:
print('non-empty list is true')
if 0:
print('zero is true')
if 1:
print('one is true')
End of explanation |
7,914 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Zenodo data downloads
20/07/20
Quick tests for data IO with Zenodo.
(See also epsman for Zenodo API stuff (in development) for packaging & uploading to Zenodo + ePSdata.)
Options
Step2: With Zenodo API
This should be neater than above method... but some methods require (personal) access token to work.
https
Step3: With class
Above now implemented in epsproc.utils.epsdata.ePSdata class
Step4: Test for larger file-set (ABCO)
https
Step5: Additional multipart-zip testing (move/delete files and dirs)
Step6: Function testing
Step7: Testing HTML parsing & display
For URL extraction.
Best notes
Step8: With zenodo_get wrapper
For details, see Zenodo https
Step9: Test homedir stuff | Python Code:
import requests
# From doi
urlDOI = 'http://dx.doi.org/10.5281/zenodo.3629721'
r = requests.get(urlDOI)
r.ok
dir(r)
# r.json() Throws an error, not sure why!
# import json
# json.loads(r.text) # Ah, same error - seems to be formatting issue?
# JSONDecodeError: Expecting value: line 2 column 1 (char 1)
print(r.text) # This is OK, just HTML for Zenodo record page.
r.text
# OPTIONS: parse this text for file links & download, or use API
Explanation: Zenodo data downloads
20/07/20
Quick tests for data IO with Zenodo.
(See also epsman for Zenodo API stuff (in development) for packaging & uploading to Zenodo + ePSdata.)
Options:
Basic requests.get() with Zenodo API should be fine.
Python wrappers, e.g. zenodo_get
Testing with record: http://dx.doi.org/10.5281/zenodo.3629721
Basic requests usage from URL
End of explanation
import os
from pathlib import Path
# Set record IDs, starting from DOI
recordID = {}
recordID['doi'] = '10.5281/zenodo.3629721'
recordID['url'] = {'doi':'http://dx.doi.org/' + recordID['doi']}
recordID['zenID'] = int(recordID['doi'].rsplit('.',1)[-1])
recordID['url']['get'] = 'https://zenodo.org/record/' + str(recordID['zenID'])
# Set also local paths, working dir or other
# recordID['downloadBase'] = Path(os.getcwd())
recordID['downloadBase'] = Path('/home/femtolab/Downloads')
recordID['downloadDir'] = recordID['downloadBase']/str(recordID['zenID'])
try:
os.mkdir(recordID['downloadDir'])
except FileExistsError:
print(f"*** Directory {recordID['downloadDir']} already exists, contents will be overwritten.")
testStr = 'http://dx.doi.org/10.5281/zenodo.3629721'
# testStr.find("dx.doi") #.startswith('http://dx.doi')
"dx.doi" in testStr
# With url parser, see https://docs.python.org/3/library/urllib.parse.html
from urllib.parse import urlparse
urlparse(testStr).path.strip('/')
testURL2 = "https://zenodo.org/record/3629721"
ID = urlparse(testURL2).path.rsplit('/')[-1]
from urllib.parse import urljoin
urljoin('http://dx.doi.org/10.5281/zenodo.', ID)
type(ID)
# '10.5281/zenodo.'.join(ID)
'10.5281/zenodo.' + ID
# 'tets' + 'TTTT'
recordID
# r = requests.get('https://zenodo.org/api/deposit/depositions/3629721/files') # Needs token
# r = requests.get('https://zenodo.org/api/records/3629721') # OK
r = requests.get(recordID['url']['get']) # OK
if r.ok:
print(f"Found Zenodo record {recordID['zenID']}: {r.json()['metadata']['title']}")
r
type(r.json()['files'])
# Try getting a file with wget
import wget
wget.download(r.json()['files'][0]['links']['self'], out=recordID['downloadDir'].as_posix())
# Basic bytes to KB/Mb... conversion, from https://stackoverflow.com/questions/2104080/how-to-check-file-size-in-python
def convert_bytes(num):
This function will convert bytes to MB.... GB... etc
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
# return [num, x]
num /= 1024.0
# Pull all files
# downloadSize = sum(item['size'] for item in r.json()['files'])
# fList = []
# print(f"Record {recordID['zenID']}: {len(r.json()['files'])} files, {convert_bytes(downloadSize)}")
# for n, item in enumerate(r.json()['files']):
# print(f"Getting item {item['links']['self']}")
# fout = wget.download(item['links']['self'], out=recordID['downloadDir'].as_posix())
# print(f"Pulled to file: {fout}")
# fList.append(Path(fout)) # Log local file list
dir(fList[0])
# Unzip if required
import zipfile
for n, item in enumerate(fList):
if item.suffix == '.zip':
with zipfile.ZipFile(item,"r") as zipObj:
zipFiles = zipObj.namelist()
zipObj.extractall(recordID['downloadDir'])
# print(zip_ref)
(zipFiles)
wget.download
Explanation: With Zenodo API
This should be neater than above method... but some methods require (personal) access token to work.
https://developers.zenodo.org/#quickstart-upload
End of explanation
import sys
# ePSproc test codebase (local)
if sys.platform == "win32":
modPath = r'D:\code\github\ePSproc' # Win test machine
else:
modPath = r'/home/femtolab/github/ePSproc/' # Linux test machine
sys.path.append(modPath)
# import epsproc as ep
from epsproc.util.epsdata import ePSdata
dataObj = ePSdata(doi='10.5281/zenodo.3629721', downloadDir=r'/home/femtolab/Downloads')
# dir(dataObj)
# dataObj.downloadSize
# dataObj.r.json()['files']
dataObj.downloadFiles(overwriteFlag=False, overwritePromptFlag=True)
dataObj.fList
dataObj.fList[0].parent
dataObj.unzipFiles()
sum([item.file_size for item in dataObj.zip[0]['info']])
# [print(item) for item in dataObj.zip[0]['info']]
dataObj.zip
Explanation: With class
Above now implemented in epsproc.utils.epsdata.ePSdata class
End of explanation
import sys
# ePSproc test codebase (local)
if sys.platform == "win32":
modPath = r'D:\code\github\ePSproc' # Win test machine
else:
modPath = r'/home/femtolab/github/ePSproc/' # Linux test machine
sys.path.append(modPath)
# import epsproc as ep
from epsproc.util.epsdata import ePSdata
ABCOdata = ePSdata(URL='https://zenodo.org/record/3627347', downloadDir=r'/home/femtolab/Downloads')
ABCOdata.r.ok
ABCOdata.downloadFiles()
from pathlib import Path
# Path(ABCOdata.fList[4].stem + '_joined.zip')
ABCOdata.fList[5]
ABCOdata.fList[5].with_suffix('.zip')
ABCOdata.unzipFiles()
# TODO finish fixing file logic!!!
# Now unzipping OK, including case with extra path info.
# NEED TO MOVE FILES in this case.
# 'pkg' in ABCOdata.zip[0]['zipfile'].relative_to(ABCOdata.zip[0]['path']).parts
ABCOdata.zip
ABCOdata.recordID['downloadDir']/ABCOdata.zip[0]['files'][0]
# dir(ABCOdata)
ABCOdata.fList
# Testing file sorting etc.
# See epsman._repo for prototypes
from collections import Counter
import pprint
fileListTest = ABCOdata.zip[0]['files']
suffixList = [Path(item).suffix for item in fileListTest]
c = Counter(suffixList)
pprint.pprint(c, width=50)
ePSout = [item for item in fileListTest if Path(item).suffix == '.out']
ePSout
# Checking subdirs
import os
path = ABCOdata.recordID['downloadDir']
test = list(os.walk(path))
# [f.path for f in os.scandir(path) if f.is_dir()]
# import glob
# glob.glob(path.as_posix() + '/**/', recursive=True)
len(test)
# list(item[0] for item in test)
[item[0] for item in test]
list_subfolders_with_paths = []
for root, dirs, files in os.walk(path):
for dir in dirs:
list_subfolders_with_paths.append( os.path.join(root, dir) )
# list_subfolders_with_paths.append(dir)
break
list_subfolders_with_paths
Explanation: Test for larger file-set (ABCO)
https://zenodo.org/record/3627347
End of explanation
ABCOdata.zipMP[0]
# Path(ABCOdata.zipMP[0]['files'][0]).parts
# Test file move/copy
# With shutil
# import shutil
# testOut = shutil.move((ABCOdata.zipMP[0]['path']/ABCOdata.zipMP[0]['files'][0]).as_posix(), ABCOdata.zipMP[0]['path'].as_posix())
# testOut
# (ABCOdata.zipMP[0]['path']/Path(ABCOdata.zipMP[0]['files'][0]).parts[0])
# With Path
# testOut = (ABCOdata.zipMP[0]['path']/ABCOdata.zipMP[0]['files'][0]).rename(ABCOdata.zipMP[0]['path']/Path(ABCOdata.zipMP[0]['files'][0]).name)
ABCOdata.zipMP[0]['path']/Path(ABCOdata.zipMP[0]['files'][0]).name
list((ABCOdata.zipMP[0]['path']/Path(ABCOdata.zipMP[0]['files'][0])).parent.parent.iterdir()) #.parent.rmdir()
Path(Path(ABCOdata.zipMP[0]['files'][0]).parts[-1]).parent
root = ABCOdata.zipMP[0]['path']
os.listdir(root)
import os
# list(os.walk((ABCOdata.zipMP[0]['path']/Path(ABCOdata.zipMP[0]['files'][0]).parent.parts[0]),topdown=False))
list(os.walk((ABCOdata.zipMP[0]['path']/'.'), topdown=False))
# Recursive dir deletion with Path
# In this case pass top-level dir, contents to be removed
# Modified version of code from https://stackoverflow.com/a/49782093
# ABANDONED - just use os.removedirs!!!!!
# from pathlib import Path
# def rmdir(directory):
# directory = Path(directory)
# for item in directory.iterdir():
# if item.is_dir():
# rmdir(item)
# # else:
# # item.unlink()
# try:
# directory.rmdir()
# return 0
# except OSError as e:
# if e == "[Errno 39] Directory not empty":
# print(f"{})
# rmdir(Path("dir/"))
# Path(ABCOdata.zipMP[0]['files'][0]).parent.is_dir()
# Path(ABCOdata.zipMP[0]['files'][0]).is_file()
# Path(ABCOdata.zipMP[0]['files'][0]).relative_to(ABCOdata.zip[0]['path'])
# Test dir removal
# ABCOdata.zipMP[0]['path']/Path(ABCOdata.zipMP[0]['files'][0]).parent # .parts[0:2]
# os.getcwd()
# With Path.rmdir()
# (ABCOdata.zipMP[0]['path']/Path(ABCOdata.zipMP[0]['files'][0]).parts[0]).rmdir() # This requires dir to be empty, so could be run recursively and safely
# Returns OSError: [Errno 39] Directory not empty: '/home/femtolab/Downloads/3627347/mnt'
# With SHUTIL
# This works. Could be dangerous however! Doesn't require dir to be empty.
# shutil.rmtree(ABCOdata.zipMP[0]['path']/Path(ABCOdata.zipMP[0]['files'][0]).parts[0])
# With os.removedirs - works recursively until non-empty dir found.
# os.removedirs(ABCOdata.zipMP[0]['path']/Path(ABCOdata.zipMP[0]['files'][0]).parts[0])
try:
# Basic case, just use full path
os.removedirs(ABCOdata.zipMP[0]['path']/Path(ABCOdata.zipMP[0]['files'][0]).parent)
# With chdir for extra safety (?)
# currDir = os.getcwd()
# os.chdir(ABCOdata.zipMP[0]['path'])
# os.removedirs(Path(ABCOdata.zipMP[0]['files'][0]).parent)
except OSError as e:
# if e.startswith("[Errno 39] Directory not empty"):
# print(e)
# print(type(e))
# print(dir(e))
# print(e.filename)
# print(e.errno)
if e.errno == 39:
print(f'Pruned dir tree back to {e.filename}')
# return e.filename
else:
raise
currDir
print(os.getcwd())
os.chdir(currDir)
print(os.getcwd())
os.chdir('/home/femtolab/github/ePSproc/epsproc/tests/utilDev')
Path(ABCOdata.zipMP[0]['files'][0]).parent
import os
os.getcwd()
Explanation: Additional multipart-zip testing (move/delete files and dirs)
End of explanation
# FUNCTION TESTING
# Check if file exists
item = dataObj.r.json()['files'][2]
localFile = dataObj.recordID['downloadDir']/item['key']
overwriteFlag = False
overwritePromptFlag = True
downloadFlag = True
if localFile.is_file():
sizeCheck = localFile.stat().st_size - item['size'] # Quick file size check
if (not sizeCheck):
print('Local file size incomensurate with remote by {sizeCheck} bytes. File will be downloaded again.')
downloadFlag = True
else:
print('Local file already exists, file size OK.')
if not (overwriteFlag and overwritePromptFlag):
downloadFlag = False
elif (overwriteFlag and overwritePromptFlag):
test = input("Download file again (y/n)?: ")
if test == 'y':
downloadFlag = True
else:
downloadFlag = False
else:
downloadFlag = True
if downloadFlag:
print('File will be downloaded again.')
else:
print('Skipping download.')
# print(localFile.stat().st_size)
# print(sizeCheck)
# dir(localFile)
Explanation: Function testing
End of explanation
import re
myString = dataObj.r.json()['metadata']['description']
# print(re.search("(?P<url>https?://[^\s]+)", myString).group("url")) # This pulls full <a href .....</a>, ugh.
# re.findall(r'(https?://\S+)', myString) # Gets all URLs, but not correct.
# urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', myString) # This gets only base URL
# urls
# This works.
# https://stackoverflow.com/a/6883228
from html.parser import HTMLParser
class MyParser(HTMLParser):
def __init__(self, output_list=None):
HTMLParser.__init__(self)
if output_list is None:
self.output_list = []
else:
self.output_list = output_list
def handle_starttag(self, tag, attrs):
if tag == 'a':
self.output_list.append(dict(attrs).get('href'))
p = MyParser()
p.feed(myString)
p.output_list
# With Beautiful Soup
# https://www.crummy.com/software/BeautifulSoup/bs4/doc/
from bs4 import BeautifulSoup
# Set object
soup = BeautifulSoup(myString, 'html.parser')
# Find all tags <a
soup.find_all('a')
# Extract URLs
for link in soup.find_all('a'):
print(link.get('href'))
# Test job info summary - HTML rendering
from IPython.core.display import HTML
jobInfo = HTML(dataObj.r.json()['metadata']['description'])
display(jobInfo)
Explanation: Testing HTML parsing & display
For URL extraction.
Best notes: https://stackoverflow.com/questions/6883049/regex-to-extract-urls-from-href-attribute-in-html-with-python
NOTE - use HTML parsers, not regex!
Either inbuilt html.parser, or BeautifulSoup, are suggested.
See also https://github.com/lipoja/URLExtract for another alternative.
End of explanation
# Install with pip
!pip install zenodo_get
# import zenodo_get as zget # Seems to be OK, but empty - issue with import here (designed for CLI?)
from zenodo_get import __main__ as zget # This seems to work.
dir(zget)
# zget.zenodo_get(['','-d http://dx.doi.org/10.5281/zenodo.3629721']) # Throws KeyError at 'files'
# zget.zenodo_get(['','-d 10.5281/zenodo.3629721']) # Throws KeyError at 'files'
zget.zenodo_get(['','-r 3629721']) # Throws KeyError at 'files'
!zenodo_get.py -c
Explanation: With zenodo_get wrapper
For details, see Zenodo https://doi.org/10.5281/zenodo.3676567 or GitLab page
End of explanation
import os
os.path.expanduser('~')
os.mkdir(os.path.expanduser(r'~/Testmkdir')) # OK
os.mkdir(os.path.expanduser(r'/home/femtolab/Testmkdir2')) # OK
# os.path.expanduser(r'/home/femtolab/Testmkdir2')
os.path.expanduser(r'/etc')
testPath = Path('~/etc')
# os.path.expanduser(testPath)
testPath.expanduser()
Explanation: Test homedir stuff
End of explanation |
7,915 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Median Edge Coverage
Step1: Current Fuzzbench default report ranking
use the mean edges covered per benchmark
rank each fuzzer by their mean ranking for all benchmarks
Step2: Other ranking measures
exp_pivot_df is the result of using the median coverage as a benchmark ranking algorithm
- Number of firsts (best median coverage for a benchmark)
- Percent coverage (median coverage / max coverage per benchmark)
- Average rank (simple mean of benchmark ranking)
- Statistical tests wins (only count cases where the coverage improvement was statistically significant (p_value < 0.05))
Step3: Ranking comparison chart | Python Code:
exp_snapshot_df.pivot_table(index='benchmark', columns='fuzzer', values='edges_covered', aggfunc='median')
Explanation: Median Edge Coverage
End of explanation
default_report_rank = data_utils.experiment_level_ranking(
exp_snapshot_df,
data_utils.benchmark_rank_by_mean,
data_utils.experiment_rank_by_average_rank)
default_report_rank
Explanation: Current Fuzzbench default report ranking
use the mean edges covered per benchmark
rank each fuzzer by their mean ranking for all benchmarks
End of explanation
firsts_ranked = data_utils.experiment_rank_by_num_firsts(exp_pivot_df)
firsts_ranked
percent_coverage = data_utils.experiment_rank_by_average_normalized_score(exp_pivot_df)
percent_coverage
average_rank = data_utils.experiment_rank_by_average_rank(exp_pivot_df)
average_rank
stats_wins = data_utils.experiment_level_ranking(
exp_snapshot_df,
data_utils.benchmark_rank_by_stat_test_wins,
data_utils.experiment_rank_by_average_rank
)
stats_wins
Explanation: Other ranking measures
exp_pivot_df is the result of using the median coverage as a benchmark ranking algorithm
- Number of firsts (best median coverage for a benchmark)
- Percent coverage (median coverage / max coverage per benchmark)
- Average rank (simple mean of benchmark ranking)
- Statistical tests wins (only count cases where the coverage improvement was statistically significant (p_value < 0.05))
End of explanation
rankings = {
"Default Ranking (mean coverage)": default_report_rank,
"Stats Wins (p_value wins)": stats_wins,
"% Coverage Ranking": percent_coverage,
"Average Rank (median coverage)": average_rank
}
fig, axes = plt.subplots(1,len(rankings), figsize=(30,7))
for i, (title, ranking_series) in enumerate(rankings.items()):
ax = sns.barplot(x=ranking_series.values, y=ranking_series.index, ax=axes[i])
ax.set_title(title)
ax.set_ylabel("")
fig.suptitle("Comparison of Ranking Methods")
fig.show()
Explanation: Ranking comparison chart
End of explanation |
7,916 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook 9
Step1: Download the sequence data
Sequence data for this study are archived on the NCBI sequence read archive (SRA). Below I read in SraRunTable.txt for this project which contains all of the information we need to download the data.
Project DRA
Step3: For each ERS (individuals) get all of the ERR (sequence file accessions).
Step4: Here we pass the SRR number and the sample name to the wget_download function so that the files are saved with their sample names.
Step5: Make a params file
Step6: Note
Step7: Trimming the barcode
In this data set the data were uploaded separated by sample, but with the barcode still attached to the sequences. The python code below will remove the 5bp barcode from each sequence.
Step8: Assemble in pyrad
Step9: Results
We are interested in the relationship between the amount of input (raw) data between any two samples, the average coverage they recover when clustered together, and the phylogenetic distances separating samples.
Raw data amounts
The average number of raw reads per sample is 1.36M.
Step10: Look at distributions of coverage
pyrad v.3.0.63 outputs depth information for each sample which I read in here and plot. First let's ask which sample has the highest depth of coverage. The std of coverages is pretty low in this data set compared to several others.
Step11: Plot the coverage for the sample with highest mean coverage
Green shows the loci that were discarded and orange the loci that were retained. The majority of data were discarded for being too low of coverage.
Step12: Print final stats table
Step13: Infer ML phylogeny in raxml as an unrooted tree
Step14: Plot the tree in R using ape
Step15: Get phylo distances (GTRgamma dist) | Python Code:
### Notebook 9
### Data set 9 (Ohomopterus)
### Authors: Takahashi et al. 2014
### Data Location: DRP001067
Explanation: Notebook 9:
This is an IPython notebook. Most of the code is composed of bash scripts, indicated by %%bash at the top of the cell, otherwise it is IPython code. This notebook includes code to download, assemble and analyze a published RADseq data set.
End of explanation
%%bash
## make a new directory for this analysis
mkdir -p empirical_9/fastq/
Explanation: Download the sequence data
Sequence data for this study are archived on the NCBI sequence read archive (SRA). Below I read in SraRunTable.txt for this project which contains all of the information we need to download the data.
Project DRA: DRA001025
Study: DRP001067
SRA link: http://trace.ddbj.nig.ac.jp/DRASearch/study?acc=DRP001067
End of explanation
import os
def wget_download_ddbj(SRR, outdir):
Python function to get sra data from ncbi and write to
outdir with a new name using bash call wget
## create a call string
call = "wget -q -r -nH --cut-dirs=9 -P "+outdir+" "+\
"ftp://ftp.ddbj.nig.ac.jp/ddbj_database/dra/sra/ByExp/"+\
"sra/DRX/DRX011/DRX011{:03d}".format(SRR)
## run wget call
! $call
for ID in range(602,634):
wget_download_ddbj(ID, "empirical_9/fastq/")
Explanation: For each ERS (individuals) get all of the ERR (sequence file accessions).
End of explanation
%%bash
## convert sra files to fastq using fastq-dump tool
## output as gzipped into the fastq directory
fastq-dump --gzip -O empirical_9/fastq/ empirical_9/fastq/*.sra
## remove .sra files
rm empirical_9/fastq/*.sra
%%bash
ls -lh empirical_9/fastq/
Explanation: Here we pass the SRR number and the sample name to the wget_download function so that the files are saved with their sample names.
End of explanation
%%bash
pyrad --version
%%bash
## remove old params file if it exists
rm params.txt
## create a new default params file
pyrad -n
Explanation: Make a params file
End of explanation
%%bash
## substitute new parameters into file
sed -i '/## 1. /c\empirical_9/ ## 1. working directory ' params.txt
sed -i '/## 6. /c\TGCAG ## 6. cutters ' params.txt
sed -i '/## 7. /c\20 ## 7. N processors ' params.txt
sed -i '/## 9. /c\6 ## 9. NQual ' params.txt
sed -i '/## 10./c\.85 ## 10. clust threshold ' params.txt
sed -i '/## 12./c\4 ## 12. MinCov ' params.txt
sed -i '/## 13./c\10 ## 13. maxSH ' params.txt
sed -i '/## 14./c\empirical_9_m4 ## 14. output name ' params.txt
sed -i '/## 18./c\empirical_9/fastq/*.gz ## 18. data location ' params.txt
sed -i '/## 29./c\2,2 ## 29. trim overhang ' params.txt
sed -i '/## 30./c\p,n,s ## 30. output formats ' params.txt
cat params.txt
Explanation: Note:
The data here are from Illumina Casava <1.8, so the phred scores are offset by 64 instead of 33, so we use that in the params file below.
End of explanation
os.path.splitext(fil)
import glob
import itertools
import gzip
import os
for infile in glob.glob("empirical_9/fastq/DRR*"):
iofile = gzip.open(infile, 'rb')
dire, fil = os.path.split(infile)
fastq = os.path.splitext(fil)[0]
outhandle = os.path.join(dire, "T_"+fastq)
outfile = open(outhandle, 'wb')
data = iter(iofile)
store = []
while 1:
try:
line = data.next()
except StopIteration:
break
if len(line) < 80:
store.append(line)
else:
store.append(line[5:])
if len(store) == 10000:
outfile.write("".join(store))
store = []
iofile.close()
outfile.close()
! gzip $outhandle
Explanation: Trimming the barcode
In this data set the data were uploaded separated by sample, but with the barcode still attached to the sequences. The python code below will remove the 5bp barcode from each sequence.
End of explanation
%%bash
pyrad -p params.txt -s 234567 >> log.txt 2>&1
%%bash
sed -i '/## 12./c\2 ## 12. MinCov ' params.txt
sed -i '/## 14./c\empirical_9_m2 ## 14. output name ' params.txt
%%bash
pyrad -p params.txt -s 7 >> log.txt 2>&1
Explanation: Assemble in pyrad
End of explanation
import pandas as pd
import numpy as np
## read in the data
s2dat = pd.read_table("empirical_9/stats/s2.rawedit.txt", header=0, nrows=32)
## print summary stats
print s2dat["passed.total"].describe()
## find which sample has the most raw data
maxraw = s2dat["passed.total"].max()
print "\nmost raw data in sample:"
print s2dat['sample '][s2dat['passed.total']==maxraw]
Explanation: Results
We are interested in the relationship between the amount of input (raw) data between any two samples, the average coverage they recover when clustered together, and the phylogenetic distances separating samples.
Raw data amounts
The average number of raw reads per sample is 1.36M.
End of explanation
## read in the s3 results
s9dat = pd.read_table("empirical_9/stats/s3.clusters.txt", header=0, nrows=33)
## print summary stats
print "summary of means\n=================="
print s9dat['dpt.me'].describe()
## print summary stats
print "\nsummary of std\n=================="
print s9dat['dpt.sd'].describe()
## print summary stats
print "\nsummary of proportion lowdepth\n=================="
print pd.Series(1-s9dat['d>5.tot']/s9dat["total"]).describe()
## find which sample has the greatest depth of retained loci
max_hiprop = (s9dat["d>5.tot"]/s9dat["total"]).max()
print "\nhighest coverage in sample:"
print s9dat['taxa'][s9dat['d>5.tot']/s9dat["total"]==max_hiprop]
maxprop =(s9dat['d>5.tot']/s9dat['total']).max()
print "\nhighest prop coverage in sample:"
print s9dat['taxa'][s9dat['d>5.tot']/s9dat['total']==maxprop]
## print mean and std of coverage for the highest coverage sample
with open("empirical_9/clust.85/T_DRR021966.depths", 'rb') as indat:
depths = np.array(indat.read().strip().split(","), dtype=int)
print "Means for sample T_DRR021966"
print depths.mean(), depths.std()
print depths[depths>5].mean(), depths[depths>5].std()
Explanation: Look at distributions of coverage
pyrad v.3.0.63 outputs depth information for each sample which I read in here and plot. First let's ask which sample has the highest depth of coverage. The std of coverages is pretty low in this data set compared to several others.
End of explanation
import toyplot
import toyplot.svg
import numpy as np
## read in the depth information for this sample
with open("empirical_9/clust.85/T_DRR021966.depths", 'rb') as indat:
depths = np.array(indat.read().strip().split(","), dtype=int)
## make a barplot in Toyplot
canvas = toyplot.Canvas(width=350, height=300)
axes = canvas.axes(xlabel="Depth of coverage (N reads)",
ylabel="N loci",
label="dataset9/sample=T_DRR021966")
## select the loci with depth > 5 (kept)
keeps = depths[depths>5]
## plot kept and discarded loci
edat = np.histogram(depths, range(30)) # density=True)
kdat = np.histogram(keeps, range(30)) #, density=True)
axes.bars(edat)
axes.bars(kdat)
#toyplot.svg.render(canvas, "empirical_9_depthplot.svg")
Explanation: Plot the coverage for the sample with highest mean coverage
Green shows the loci that were discarded and orange the loci that were retained. The majority of data were discarded for being too low of coverage.
End of explanation
cat empirical_9/stats/empirical_9_m4.stats
%%bash
head -n 20 empirical_9/stats/empirical_9_m2.stats
Explanation: Print final stats table
End of explanation
%%bash
## raxml argumement w/ ...
raxmlHPC-PTHREADS-AVX -f a -m GTRGAMMA -N 100 -x 12345 -p 12345 -T 20 \
-w /home/deren/Documents/RADmissing/empirical_9/ \
-n empirical_9_m4 -s empirical_9/outfiles/empirical_9_m4.phy
%%bash
## raxml argumement w/ ...
raxmlHPC-PTHREADS-AVX -f a -m GTRGAMMA -N 100 -x 12345 -p 12345 -T 20 \
-w /home/deren/Documents/RADmissing/empirical_9/ \
-n empirical_9_m2 -s empirical_9/outfiles/empirical_9_m2.phy
%%bash
head -n 20 empirical_9/RAxML_info.empirical_9_m4
%%bash
head -n 20 empirical_9/RAxML_info.empirical_9_m2
Explanation: Infer ML phylogeny in raxml as an unrooted tree
End of explanation
%load_ext rpy2.ipython
%%R -h 800 -w 800
library(ape)
tre <- read.tree("empirical_9/RAxML_bipartitions.empirical_9")
ltre <- ladderize(tre)
par(mfrow=c(1,2))
plot(ltre, use.edge.length=F)
nodelabels(ltre$node.label)
plot(ltre, type='u')
Explanation: Plot the tree in R using ape
End of explanation
%%R
mean(cophenetic.phylo(ltre))
Explanation: Get phylo distances (GTRgamma dist)
End of explanation |
7,917 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computation of voltage divider
It could happen that the mains voltage fluctuates because of voltage collapses. Nevertheless, the resulting signal has to be stable enough so that the fluctuations don't influence the final result. A usual voltage divider with 2 resistors wouldn't achieve that. Therefore, adding an additional source from the microcontroller and resistor will make the signal more resistant to voltage flucutations. Furthermore, the microcontroller can only "read" positive voltages. The additional DC voltage source lifts the sine to an only positive range.
Step1: Parameters
Step2: Currents
$$I_1 = \frac{U_0R_2sin(2\pi f t) + U_BR_1}{R_1(R_2+R_3)+R_2R_3}$$
$$I_2 = \frac{U_0R_3sin(2\pi f t) - U_B(R_1+R_3)}{R_1(R_2+R_3)+R_2R_3}$$
$$I_0 = I_1 + I_2$$
Step3: Voltages
$$U_{R_1}=I_0R_1$$
$$U_{R_2}=I_2R_2$$
$$U_{R_3}=I_1R_3$$
Step4: Offset of signal voltage
Step5: Dependency of signal voltage on the mains voltage
Step6: Evaluation
The computation shows a good stability of the signal voltage if the mains voltage fluctuates. A change of 1V in the mains voltage results just in an approx. 100mV deviation of the signal.
Schmitt Trigger
Step7: Source
Step8: $$U_{High} = \frac{\frac{R_4}{R_4 + R_5} U_{a_L} - U_{ref}} {\frac{R_4}{R_4 + R_5} -1} $$
$$U_{Low} = \frac{\frac{R_4}{R_4 + R_5}U_{a_H} - U_{ref}} {\frac{R_4}{R_4 + R_5} -1} $$
$$U_{ref} = U_B \frac{R_6}{R_6 + R_7}$$
Voltage Divider
Step9: Turn-on Threshold
Step10: Turn-off Threshold
Step11: Hysteresis of a non-inverting Schmitt Trigger | Python Code:
from IPython.display import Image
Image(filename='circuit.png')
# %matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from IPython.display import HTML, display
# For tables
def tableit(data):
display(HTML(
'<table><tr>{}</tr></table>'.format(
'</tr><tr>'.join(
'<td>{}</td>'.format('</td><td>'.join(str(_) for _ in row)) for row in data)
)
))
Explanation: Computation of voltage divider
It could happen that the mains voltage fluctuates because of voltage collapses. Nevertheless, the resulting signal has to be stable enough so that the fluctuations don't influence the final result. A usual voltage divider with 2 resistors wouldn't achieve that. Therefore, adding an additional source from the microcontroller and resistor will make the signal more resistant to voltage flucutations. Furthermore, the microcontroller can only "read" positive voltages. The additional DC voltage source lifts the sine to an only positive range.
End of explanation
U0 = 17.1 # mains voltage in Volt (transformed from 230 V ~ to 17.1 V ~)
U_B = 5 # DC voltage from an external supply in Volts
R1 = 10000 # Ohm
R2 = 2400 # Ohm
R3 = 3000 # Ohm
f = 50 # Hz
fs = 44100 # Hz
duration = 0.06 # Duration of plots in seconds
t = np.arange(0, duration, 1 / fs)
Explanation: Parameters
End of explanation
I1 = (U0 * np.sin(2 * np.pi * f * t) * R2 + U_B * R1) / (R1 * (R2 + R3) + R2 * R3)
I2 = (U0 * np.sin(2 * np.pi * f * t) * R3 - U_B * (R1 + R3)) / (R1 * (R2 + R3) + R2 * R3)
I0 = I1 + I2
plt.plot(t * 1000, I0 * 1000, label="I0")
plt.plot(t * 1000, I1 * 1000, label="I1")
plt.plot(t * 1000, I2 * 1000, label="I2")
plt.title("Currents")
plt.ylabel("I / mA")
plt.xlabel("t / ms")
plt.legend(loc='upper left', bbox_to_anchor=(1.1, 0.6))
plt.grid()
plt.show()
Explanation: Currents
$$I_1 = \frac{U_0R_2sin(2\pi f t) + U_BR_1}{R_1(R_2+R_3)+R_2R_3}$$
$$I_2 = \frac{U_0R_3sin(2\pi f t) - U_B(R_1+R_3)}{R_1(R_2+R_3)+R_2R_3}$$
$$I_0 = I_1 + I_2$$
End of explanation
U_R1 = I0 * R1
U_R2 = I2 * R2
U_R3 = I1 * R3
signal = U_R3 # U_R3 == signal voltage
plt.plot(t * 1000, U_R1, label="U_R1")
plt.plot(t * 1000, U_R2, label="U_R2")
plt.plot(t * 1000, signal, label="signal")
plt.title("Voltages")
plt.ylabel("U / V")
plt.xlabel("t / ms")
plt.legend(loc='upper left', bbox_to_anchor=(1.1, 0.6))
plt.grid()
plt.show()
Explanation: Voltages
$$U_{R_1}=I_0R_1$$
$$U_{R_2}=I_2R_2$$
$$U_{R_3}=I_1R_3$$
End of explanation
signal_max = np.max(signal)
signal_min = np.min(signal)
signal_pp = signal_max - signal_min
offset = (signal_max + signal_min) / 2
tableit([["signal_max / V", "signal_min / V","signal_pp / V", "Offset / V"],
[np.around(signal_max, 2), np.around(signal_min, 2), np.around(signal_pp, 2), np.around(offset, 2)],
])
plt.plot(t * 1000, signal, label="Signal Voltage")
plt.title("Signal Voltage")
plt.ylabel("U / V")
plt.xlabel("t / ms")
plt.axhline(y=offset, color='r', linestyle='-', label='Offset')
plt.legend(loc='upper left', bbox_to_anchor=(1.1, 0.6))
plt.ylim(-0.1, signal_max + 0.2)
plt.grid()
plt.show()
Explanation: Offset of signal voltage
End of explanation
voltage_range = np.arange(U0 - 8, U0 + 8 ,0.1) # mains voltage fluctuations
I1_DC = (voltage_range * R2 + U_B * R1) / (R1 * (R3 + R2) + R3 * R2)
signal_DC = I1_DC * R3
plt.plot(voltage_range, signal_DC)
plt.title('Mains voltage fluctuations and the effect on the signal')
plt.xlabel('Mains Voltage / V')
plt.ylabel('Signal Voltage (DC) / V')
plt.grid()
plt.show()
Explanation: Dependency of signal voltage on the mains voltage
End of explanation
Image(filename='schmitt.png')
Explanation: Evaluation
The computation shows a good stability of the signal voltage if the mains voltage fluctuates. A change of 1V in the mains voltage results just in an approx. 100mV deviation of the signal.
Schmitt Trigger
End of explanation
Image(filename='schmitt_drawing.png')
R4 = 10000 # Ohm
R5 = 34800 # Ohm
R6 = 10000 # Ohm
R7 = 10000 # Ohm
U_aH = U_B
U_aL = 0
Explanation: Source: http://www.mikrocontroller.net/articles/Schmitt-Trigger
Laws
1) If U_e (= input voltage) exceeds U_H, then U_a (= output voltage) = HIGH
2) If U_e comes below U_L, then U_a = LOW
3) If the range of Ue is between U_L and U_H, then U_a = const.
4) The transition from LOW to HiGH or rather from HIGH to LOW has always a steep edge
Computation of a non-inverting Schmitt Trigger
End of explanation
U_ref = U_B * R6 / (R6 + R7)
Explanation: $$U_{High} = \frac{\frac{R_4}{R_4 + R_5} U_{a_L} - U_{ref}} {\frac{R_4}{R_4 + R_5} -1} $$
$$U_{Low} = \frac{\frac{R_4}{R_4 + R_5}U_{a_H} - U_{ref}} {\frac{R_4}{R_4 + R_5} -1} $$
$$U_{ref} = U_B \frac{R_6}{R_6 + R_7}$$
Voltage Divider
End of explanation
U_High = (R4 / (R4 + R5) * U_aL - U_ref) / (R4 / (R4 + R5) -1)
Explanation: Turn-on Threshold
End of explanation
U_Low = (R4 / (R4 + R5) * U_aH - U_ref) / (R4 / (R4 + R5) -1)
tableit([["U_ref / V", "U_Low / V","U_High / V"],
[U_ref, np.around(U_Low, 2), np.around(U_High, 2)],
])
Explanation: Turn-off Threshold
End of explanation
def hyst(x, th_lo, th_hi, initial = False):
hi = x >= th_hi
lo_or_hi = (x <= th_lo) | hi
ind = np.nonzero(lo_or_hi)[0]
if not ind.size: # prevent index error if ind is empty
return np.zeros_like(x, dtype=bool) | initial
cnt = np.cumsum(lo_or_hi) # from 0 to len(x)
return np.where(cnt, hi[ind[cnt-1]], initial)
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.add_patch(patches.Rectangle((U_Low, 0), U_High - U_Low, U_B, fill=False))
ax.set_title('Hysteresis')
ax.set_xlim([0,U_Low + 2]);
ax.set_ylim([0, U_B + 1]);
ax.set_xlabel('Ue / V')
ax.set_ylabel('Ua / V')
ax.arrow(U_High, U_B / 2 , 0, 0, head_width=0.2, head_length=0.3, fc='k', ec='k')
ax.arrow(U_Low, U_B / 2 , 0, -0.01, head_width=0.2, head_length=0.3, fc='k', ec='k')
ax.arrow((U_High + U_Low) / 2, U_B - 0.03 , -0.001, 0, head_width=0.2, head_length=0.3, fc='k', ec='k')
ax.arrow((U_High + U_Low) / 2, 0 , 0.001, 0, head_width=0.2, head_length=0.3, fc='k', ec='k')
plt.grid()
plt.show()
h1 = hyst(signal, U_Low, U_High)
plt.plot(t * 1000, signal, label='Signal Voltage')
plt.plot(t * 1000, U_B * h1, label='U_a')
plt.axhline(y=U_Low, color='k', linestyle='-', label='U_Low')
plt.axhline(y=U_High, color='r', linestyle='-', label='U_High')
plt.axhline(y=U_ref, color='y', linestyle='-', label='U_ref')
plt.title('Schmitt Trigger Result')
plt.xlabel('t / ms')
plt.ylabel('U / V')
plt.legend(loc='upper left', bbox_to_anchor=(1.1, 0.6))
plt.ylim([0, U_aH + 0.5])
plt.grid()
plt.show()
Explanation: Hysteresis of a non-inverting Schmitt Trigger
End of explanation |
7,918 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get Data
API
Step1: Load Data
Step2: Preprocessing
Step3: Transformation
Create column target with class [UP, KEEP, DOWN]
Step4: Create columns from Timestamp to Date, Year, Month, Hour, etc.
Feature Engineering
Step5: Technical Analysis
https
Step6: Trend indicators
Step8: Momentum Indicators
Step9: Price-based indicators
Step10: Split
Step11: xgboost | Python Code:
# get_data.get('data/datas.csv', period=settings.PERIOD, market=settings.MARKET)
Explanation: Get Data
API: http://bitcoincharts.com/charts
period = ['1-min', '5-min', '15-min', '30-min', 'Hourly', '2-hour', '6-hour', '12-hour', 'Daily', 'Weekly']
market = ['krakenEUR', 'bitstampUSD'] -> list of markets: https://bitcoincharts.com/charts/volumepie/
End of explanation
df = pd.read_csv('data/datas.csv', sep=',')
# add next row
last_timestamp = df['Timestamp'].iloc[-1]
if settings.PERIOD == 'Hourly':
next_timestamp = last_timestamp + 3600
df_next = pd.DataFrame([next_timestamp], columns=['Timestamp'])
df = df.append(df_next, ignore_index=True)
df.iloc[-1] = df.iloc[-1].fillna(1)
print('Number of rows: {}, Number of columns: {}'.format(*df.shape))
Explanation: Load Data
End of explanation
df = utils.dropna(df)
print('Number of rows: {}, Number of columns: {}'.format(*df.shape))
Explanation: Preprocessing
End of explanation
df['Target'] = 0 # 'KEEP'
df.loc[df.Open + (df.Open * settings.PERCENT_UP) < df.Close, 'Target'] = 1 # 'UP'
df.loc[df.Open - (df.Open * settings.PERCENT_DOWN) > df.Close, 'Target'] = 2 # 'DOWN'
print('Number of rows: {}, Number of columns: {}'.format(*df.shape))
print('Number of UP rows: {}, Number of DOWN rows: {}'.format(len(df[df.Target == 1]), len(df[df.Target == 2])))
Explanation: Transformation
Create column target with class [UP, KEEP, DOWN]
End of explanation
df['Date'] = df['Timestamp'].apply(utils.timestamptodate)
df['Date'] = pd.to_datetime(df['Date'])
df['Year'] = df['Date'].dt.year
df['Month'] = df['Date'].dt.month
df['Week'] = df['Date'].dt.weekofyear
df['Weekday'] = df['Date'].dt.weekday
df['Day'] = df['Date'].dt.day
df['Hour'] = df['Date'].dt.hour
# extra dates
# df["yearmonth"] = df["Date"].dt.year*100 + df["Date"].dt.month
# df["yearweek"] = df["Date"].dt.year*100 + df["Date"].dt.weekofyear
# df["yearweekday"] = df["Date"].dt.year*10 + df["Date"].dt.weekday
# shift
cols = ['Open', 'High', 'Low', 'Close', 'Volume_BTC', 'Volume_Currency', 'Weighted_Price']
for col in cols:
df[col] = df[col].shift(1)
df = df.dropna()
df['High-low'] = df['High'] - df['Low']
df['Close-open'] = df['Close'] - df['Open']
df['Up_or_Down'] = 0 # 'UP' or 'DOWN' if diff > settings.PERCENT_UP
df.loc[( df.Open + (df.Open * settings.PERCENT_UP) ) < df.Close, 'Up_or_Down'] = 1 # 'UP'
df.loc[( df.Open - (df.Open * settings.PERCENT_DOWN) ) > df.Close, 'Up_or_Down'] = 2 # 'DOWN'
df['Up_or_Down_2'] = 0 # 'UP' or 'DOWN' if diff > settings.PERCENT_UP * 2
df.loc[df.Open + (df.Open * settings.PERCENT_UP * 2 ) < df.Close, 'Up_or_Down_2'] = 1 # 'UP'
df.loc[df.Open - (df.Open * settings.PERCENT_DOWN * 2) > df.Close, 'Up_or_Down_2'] = 2 # 'DOWN'
df['Up_or_Down_3'] = 0 # 'UP' or 'DOWN' if diff > 0
df.loc[df.Open < df.Close, 'Up_or_Down_3'] = 1 # 'UP'
df.loc[df.Open > df.Close, 'Up_or_Down_3'] = 2 # 'DOWN'
df['Up_or_Down_4'] = 0 # 'UP' or 'DOWN' if diff > settings.PERCENT_UP / 2
df.loc[df.Open + (df.Open * settings.PERCENT_UP / 2 ) < df.Close, 'Up_or_Down_4'] = 1 # 'UP'
df.loc[df.Open - (df.Open * settings.PERCENT_DOWN / 2) > df.Close, 'Up_or_Down_4'] = 2 # 'DOWN'
# Fundamental analysis
# daily return
df['Daily_return'] = (df['Close'] / df['Close'].shift(1)) - 1
df['Daily_return_100'] = ((df['Close'] / df['Close'].shift(1)) - 1) * 100
# cumulative return
df = df.dropna()
df['Cumulative_return'] = (df['Close'] / df['Close'].iloc[0]) - 1
df['Cumulative_return_100'] = ((df['Close'] / df['Close'].iloc[0]) - 1) * 100
# TODO: cumulative return week, month, year...
print('Number of rows: {}, Number of columns: {}'.format(*df.shape))
Explanation: Create columns from Timestamp to Date, Year, Month, Hour, etc.
Feature Engineering
End of explanation
# Accumulation/Distribution index
df['Acc_Dist_Roc_BTC'] = acc_dist_roc(df, 'Volume_BTC', 2)
df['Acc_Dist_Roc_Currency'] = acc_dist_roc(df, 'Volume_Currency', 2)
df['Acc_Dist_BTC'] = acc_dist_index(df, 'Volume_BTC')
df['Acc_Dist_Currency'] = acc_dist_index(df, 'Volume_Currency')
# Chaikin Money Flow
df['Chaikin_Money_Flow_1_BTC'] = chaikin_money_flow1(df, 'Volume_BTC')
df['Chaikin_Money_Flow_2_BTC'] = chaikin_money_flow2(df, 'Volume_BTC', 20)
df['Chaikin_Money_Flow_3_BTC'] = chaikin_money_flow3(df, 'Volume_BTC', 20)
df['Chaikin_Money_Flow_1_Currency'] = chaikin_money_flow1(df, 'Volume_Currency')
df['Chaikin_Money_Flow_2_Currency'] = chaikin_money_flow2(df, 'Volume_Currency', 20)
df['Chaikin_Money_Flow_3_Currency'] = chaikin_money_flow3(df, 'Volume_Currency', 20)
# Money Flow Index
df['Money_Flow_BTC'] = money_flow_index(df, 'Volume_BTC', 14)
df['Money_Flow_Currency'] = money_flow_index(df, 'Volume_Currency', 14)
# On-balance volume
df['OBV_BTC'] = on_balance_volume(df, 'Volume_BTC')
df['OBV_BTC_mean'] = on_balance_volume_mean(df, 'Volume_BTC')
df['OBV_Currency'] = on_balance_volume(df, 'Volume_Currency')
df['OBV_Currency_mean'] = on_balance_volume_mean(df, 'Volume_Currency')
# Force Index
df['Force_Index_BTC'] = force(df, 'Volume_BTC', 2)
df['Force_Index_Currency'] = force(df, 'Volume_Currency', 2)
# delete intermediate columns
df.drop('OBV', axis=1, inplace=True)
Explanation: Technical Analysis
https://en.wikipedia.org/wiki/Technical_analysis
Volume-based indicators
End of explanation
# Moving Average Convergence Divergence
df[['MACD', 'MACD_sign', 'MACD_diff']] = macd(df, 12, 26, 9)
# Average directional movement index
df[['ADX', 'ADX_pos', 'ADX_neg']] = adx(df, 14)
# Vortex indicator
df[['Vortex_pos', 'Vortex_neg']] = vortex(df, 14)
Explanation: Trend indicators
End of explanation
df['RSI'] = rsi(df, 14)
for c in df.columns:
print str(c) + u' - ' + str(df[c].isnull().sum())
Explanation: Momentum Indicators
End of explanation
# Momentum
for idx in range(9):
m = idx+2
df['Momentum_'+str(m)] = ((df['Close'] / df['Close'].shift(m)) - 1)
# Rollings
for idx in range(9):
m = idx+2
df['Rolling_mean_'+str(m)] = (df.set_index('Date')['Close'].rolling(window=m).mean()).values
df['Rolling_std_'+str(m)] = (df.set_index('Date')['Close'].rolling(window=m).std()).values
df['Rolling_cov_'+str(m)] = (df.set_index('Date')['Close'].rolling(window=m).cov()).values
# Bollinger bands
for idx in range(9):
m = idx+2
df['Bollinger_band_mean_'+str(m)+'_max'] = df['Rolling_mean_'+str(m)] + (2*df['Rolling_std_'+str(m)])
df['Bollinger_band_mean_'+str(m)+'_min'] = df['Rolling_mean_'+str(m)] - (2*df['Rolling_std_'+str(m)])
print('Number of rows: {}, Number of columns: {}'.format(*df.shape))
df = df.dropna()
print('Number of rows: {}, Number of columns: {}'.format(*df.shape))
Explanation: Price-based indicators
End of explanation
train, test = utils.split_df(df)
excl = ['Target', 'Date', 'Timestamp']
cols = [c for c in df.columns if c not in excl]
Explanation: Split
End of explanation
y_train = train['Target']
y_mean = np.mean(y_train)
xgb_params = {
'n_trees': 800,
'eta': 0.0045,
'max_depth': 20,
'subsample': 0.95,
'colsample_bytree': 0.95,
'colsample_bylevel': 0.95,
'objective': 'multi:softmax',
'num_class' : 3,
'eval_metric': 'mlogloss', # 'merror', # 'rmse',
'base_score': 0,
'silent': 1
}
dtrain = xgb.DMatrix(train[cols], y_train)
dtest = xgb.DMatrix(test[cols])
cv_result = xgb.cv(xgb_params, dtrain)
# xgboost, cross-validation
cv_result = xgb.cv(xgb_params,
dtrain,
num_boost_round=5000,
early_stopping_rounds=50,
verbose_eval=50,
show_stdv=False
)
num_boost_rounds = len(cv_result)
# num_boost_rounds = 1000
print(num_boost_rounds)
# train
model = xgb.train(xgb_params, dtrain, num_boost_round=num_boost_rounds)
# predict
y_pred = model.predict(dtest)
y_true = test['Target']
prediction_value = y_true.tolist()[0]
if prediction_value == 1.0:
print("Prediction: UP")
elif prediction_value == 2.0:
print("Prediction: DOWN")
else: # 0.0
print("Prediction: KEEP")
print "\n \n \n \n \n \n ********** WEIGHT ************"
importance = model.get_fscore()
importance = sorted(importance.items(), key=operator.itemgetter(1))
for i in importance:
print i
print "\n \n \n \n \n \n ********** GAIN ************"
importance = model.get_score(fmap='', importance_type='gain')
importance = sorted(importance.items(), key=operator.itemgetter(1))
for i in importance:
print i
Explanation: xgboost
End of explanation |
7,919 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Define Global Variables and Helper Functions
Step1: Load Resources
Step2: NLTK
Step3: Pre-process comments
Step4: Replace Insults
We are going to replace any appearance of an insult with a 'fakeinsult' keyword. The intention of this is to concentrate the frequency of any insult into the same token
Step5: Let's check which percentage of comments of each class contains an insult
Step6: A First Attempt. Naive Classifier using insult presence
As baseline, we are going to use a naive classifier which will classify a comment as offensive if the comment contains an insult keyword
Step7: As suspected from the outcome of the previous section, there is a huge number of false positives (35,7%) for NoInsult class as many comments containing insults keywords are not really offenses to a particular user. We will need to work that out in the following approaches
A Simple TF-IDF based classifier
Step8: Using a simple TF-IDF based classifier (using stochastic gradient descent estimator) improves the global accuracy a lot and, in particular, the model seems to fix the NoInsult category prediction. But now we have more than 50% of false negatives for Insult category.
Working with unbalanced training sets
Following https
Step9: A Custom Classifier
We can continue playing with the class weights and other classifier's parameters, but eventually we will realize that we need to capture more semantics of the problem in the shape of features. We need specific features to capture when a comment is being offensive for another user.
A grammar to detect insults to another user
Step10: Custom Features
n_words
Step11: Ensemble Voting Classifier
The goal of ensemble methods is to combine the predictions of several base estimators built with a given learning algorithm in order to improve generalizability / robustness over a single estimator.
We are going to combine the TF-IDF classifier and the custom classifier using a majority vote classifier. Most of the ensemble methods build several instances of a black-box estimator on random subsets of the original training set and then aggregate their individual predictions to form a final prediction. In this case, we need to combine estimators of different nature. Sklearn Voting classifier can help in this situation. The idea behind the VotingClassifier is to combine conceptually different machine learning classifiers and use a majority vote or the average predicted probabilities (soft vote) to predict the class labels. Such a classifier can be useful for a set of equally well performing model in order to balance out their individual weaknesses.
Step12: Feature Union
To finish with classic estimators based solutions, we are going to make a final attempt by merging the features for both classifiers making use of sklearn FeatureUnion. This estimator applies a list of transformer objects in parallel to the input data, then concatenates the results. This is useful to combine several feature extraction mechanisms into a single transformer.
Step13: Word Embeddings
Word Embedding is the collective name for feature learning techniques where words from the vocabulary are mapped to vectors of real numbers. These vectors are calculated from the probability distribution for each word appearing before or after another. To put it another way, words of the same context usually appear together in the corpus, so they will be close in the vector space as well.
Step14: Word2Vec based classifier with Keras
Step15: Same Classifier but replacing insults with 'fakeinsult'
Step16: Language Models. BERT
In the field of computer vision, researchers have repeatedly shown the value of transfer learning — pre-training a neural network model on a known task, for instance ImageNet, and then performing fine-tuning — using the trained neural network as the basis of a new purpose-specific model. In recent years, researchers have been showing that a similar technique can be useful in many natural language tasks.
BERT makes use of Transformer, an attention mechanism that learns contextual relations between words (or sub-words) in a text. In its vanilla form, Transformer includes two separate mechanisms — an encoder that reads the text input and a decoder that produces a prediction for the task. Since BERT’s goal is to generate a language model, only the encoder mechanism is necessary.
As opposed to directional models, which read the text input sequentially (left-to-right or right-to-left), the Transformer encoder reads the entire sequence of words at once. Therefore it is considered bidirectional, though it would be more accurate to say that it’s non-directional. This characteristic allows the model to learn the context of a word based on all of its surroundings (left and right of the word). | Python Code:
# Global Imports
import numpy as np
from sklearn import metrics
import pandas as pd
import os
import matplotlib.pyplot as plt
# Helpers
TRAIN_FILE = "resources/train/train.csv"
TEST_FILE = "resources/test/test_with_solutions.csv"
BAD_WORDS_FILE = "resources/badwords.txt"
NO_INSULT = 'NoInsult'
INSULT = 'Insult'
# Comments preprocessing
def preprocess_comment(comment):
import re
comment = comment.strip().strip('"')
comment = comment.replace('_', ' ')
comment = comment.replace("\\\\", "\\")
comment = comment.replace('\\n', ' ')
comment = comment.replace('\\n', ' ')
comment = comment.lower()
comment = re.sub(r'^https?:\/\/.*[\r\n]*', 'URL', comment, flags=re.MULTILINE)
comment = comment.encode('utf-8').decode('unicode-escape')
return comment
# Predictions Accuracy Report
def predictions_report(pred, ground_truth):
print("Accuracy: " + str(np.mean(pred == ground_truth)) + "\n")
print(metrics.classification_report(ground_truth, pred,
target_names=['NoInsult', 'Insult']))
# Predictions Proba Accuracy Report
def predictions_report_proba(pred, ground_truth, threshold=0.5):
# Extract Plain Estimations
labels = []
for index, prediction in enumerate(pred):
if isinstance(prediction, list) or type(prediction) is np.ndarray:
if len(prediction) == 1:
if prediction[0] >= threshold:
labels.append(1)
else:
labels.append(0)
else:
if prediction[0] > prediction[1]:
labels.append(0)
else:
labels.append(1)
else:
if prediction >= threshold:
labels.append(1)
else:
labels.append(0)
labels = np.array(labels)
print("Accuracy: " + str(np.mean(labels==ground_truth)) + "\n")
print(metrics.classification_report(ground_truth, labels,
target_names=['NoInsult', 'Insult']))
# Load Bad Words Helper
def load_bad_words(badwords_file):
with open(badwords_file) as f:
lines = f.readlines()
return [badword[:-1] for badword in lines]
Explanation: Define Global Variables and Helper Functions
End of explanation
# Load list of badwords
badwords = load_bad_words(BAD_WORDS_FILE)
# Load Train Data
train_df = pd.read_csv(TRAIN_FILE)
# Load Test Data
test_df = pd.read_csv(TEST_FILE)
raw_train_comments = train_df['Comment'].apply(lambda comment: preprocess_comment(comment))
raw_test_comments = test_df['Comment'].apply(lambda comment: preprocess_comment(comment))
print(len(train_df.index))
train_df.head()
# Categories Balance
x = [NO_INSULT, INSULT]
ni_count, icount = train_df['Insult'].value_counts()
y = [ni_count, icount]
plt.barh(x, y)
for index, value in enumerate(y):
plt.text(value, index, str(value))
train_df['Insult'].value_counts(normalize=True)
print(len(test_df.index))
test_df.head()
ni_count, icount = test_df['Insult'].value_counts()
y = [ni_count, icount]
plt.barh(x, y)
for index, value in enumerate(y):
plt.text(value, index, str(value))
# Test Dataset Balance
test_df['Insult'].value_counts(normalize=True)
train_labels = train_df["Insult"]
train_comments = train_df["Comment"]
test_labels = test_df["Insult"]
test_comments = test_df["Comment"]
assert len(train_labels) == len(train_comments) == 3947
Explanation: Load Resources
End of explanation
from feature_extraction import corpus_stats, tf_idf_stats
corpus_stats(train_comments)
tf_idf_stats(train_comments)
Explanation: NLTK: Corpus Stats
Raw Corpus
First, let's take a look to the Frequency Distribution and TF-IDF distribution of the training set without any preprocessing.
Note: the tokenizer applied remove stopwords, normalize the text to lowercase and filter tokens of size < 3 characters
End of explanation
train_comments = train_comments.apply(lambda comment: preprocess_comment(comment))
corpus_stats(train_comments)
tf_idf_stats(train_comments)
test_comments = test_comments.apply(lambda comment: preprocess_comment(comment))
print(len(train_comments), len(test_comments))
Explanation: Pre-process comments
End of explanation
from feature_extraction import replace_badwords
train_comments = train_comments.apply(lambda comment: replace_badwords(comment, badwords))
test_comments = test_comments.apply(lambda comment: replace_badwords(comment, badwords))
corpus_stats(train_comments)
Explanation: Replace Insults
We are going to replace any appearance of an insult with a 'fakeinsult' keyword. The intention of this is to concentrate the frequency of any insult into the same token
End of explanation
train_df['Comment'] = train_comments
train_df[train_df['Comment'].str.contains('fakeinsult')]['Insult'].value_counts(normalize=True)
Explanation: Let's check which percentage of comments of each class contains an insult
End of explanation
from sklearn.metrics import plot_confusion_matrix
from sklearn.base import is_classifier
from training import NaiveClassifier
naive_classifier = NaiveClassifier(badwords)
naive_predictions = naive_classifier.predict(test_comments)
print("\nNaive Model Result\n")
predictions_report(naive_predictions, test_labels)
plot_confusion_matrix(naive_classifier, test_comments, test_labels, display_labels=[NO_INSULT, INSULT])
plt.show()
Explanation: A First Attempt. Naive Classifier using insult presence
As baseline, we are going to use a naive classifier which will classify a comment as offensive if the comment contains an insult keyword
End of explanation
from training import train_tfidf
tf_idf_classifier = train_tfidf(train_comments, train_labels)
predictions = tf_idf_classifier.predict(test_comments)
print("\nTF-IDF Model Result\n")
predictions_report(predictions, test_labels)
plot_confusion_matrix(tf_idf_classifier, test_comments, test_labels, display_labels=[NO_INSULT, INSULT])
plt.show()
Explanation: As suspected from the outcome of the previous section, there is a huge number of false positives (35,7%) for NoInsult class as many comments containing insults keywords are not really offenses to a particular user. We will need to work that out in the following approaches
A Simple TF-IDF based classifier
End of explanation
tf_idf_classifier = train_tfidf(train_comments, train_labels, class_weight={0: 1, 1: 2})
predictions = tf_idf_classifier.predict(test_comments)
print("\nTF-IDF Model Result\n")
predictions_report(predictions, test_labels)
plot_confusion_matrix(tf_idf_classifier, test_comments, test_labels, display_labels=[NO_INSULT, INSULT])
plt.show()
Explanation: Using a simple TF-IDF based classifier (using stochastic gradient descent estimator) improves the global accuracy a lot and, in particular, the model seems to fix the NoInsult category prediction. But now we have more than 50% of false negatives for Insult category.
Working with unbalanced training sets
Following https://scikit-learn.org/stable/auto_examples/svm/plot_separating_hyperplane_unbalanced.html we are going to try to tweak the SGD classifier by assigning different weights to each class. Most of the models in scikit-learn have a parameter class_weight. This parameter will affect the computation of the loss in linear model or the criterion in the tree-based model to penalize differently a false classification from the minority and majority class.
End of explanation
pd.set_option('display.max_colwidth', -1)
train_df[train_df['Insult'] == 1].head(20)
import spacy
from spacy.matcher import Matcher
nlp = spacy.load("en_core_web_sm")
matcher = Matcher(nlp.vocab)
pattern1 = [{"LEMMA": "-PRON-", "LOWER": {"IN": ["you", "your"]}},
{"LEMMA": {"IN": ["be", "sound"]}},{"OP": "*", "LENGTH": {"<=": 10}},
{"LOWER": "fakeinsult"}]
matcher.add("insult1", None, pattern1)
pattern2 = [{"LEMMA": "-PRON-", "LOWER": {"IN": ["you", "your"]}},
{"OP": "*", "LENGTH": {"<=": 4}},
{"LOWER": "fakeinsult"}]
matcher.add("insult2", None, pattern2)
doc = nlp("Either you are fake or extremely fakeinsult...maybe both...")
matches = matcher(doc)
for match_id, start, end in matches:
string_id = nlp.vocab.strings[match_id] # Get string representation
span = doc[start:end] # The matched span
print(match_id, string_id, start, end, span.text)
doc = nlp("your such a fakeinsult head...")
matches = matcher(doc)
for match_id, start, end in matches:
string_id = nlp.vocab.strings[match_id] # Get string representation
span = doc[start:end] # The matched span
print(match_id, string_id, start, end, span.text)
insults = train_df[train_df['Insult'] == 1]['Comment']
total_matches = 0
for insult in insults:
doc = nlp(insult)
matches = matcher(doc)
if len(matches) > 0:
total_matches += 1
print("Total offensive comments %d" % len(insults))
print("Total with pattern %d" % total_matches)
Explanation: A Custom Classifier
We can continue playing with the class weights and other classifier's parameters, but eventually we will realize that we need to capture more semantics of the problem in the shape of features. We need specific features to capture when a comment is being offensive for another user.
A grammar to detect insults to another user
End of explanation
from training import train_custom
custom_classifier = train_custom(train_comments, train_labels)
predictions = custom_classifier.predict(test_comments)
print("\nCustom Model Result\n")
predictions_report(predictions, test_labels)
plot_confusion_matrix(custom_classifier, test_comments, test_labels, display_labels=[NO_INSULT, INSULT])
plt.show()
Explanation: Custom Features
n_words: total number of words (tokens) in the comment
n_chars: total number of characters in the comment
n_dwords: total number of words in the comment that appears in an English dictionary
you_re: number of insults patterns matches found in the comment
!: number of exclamation symbols
allcaps: number of uppercase characters
@: number of 'addressing' symbols
bad_ratio: ratio of insults used in the comment
n_bad: number of insults in the comment
capsratio: ratio of uppercased characters
dicratio: ratio of dictionary words in the comment
sent: lexicon sentiment score
End of explanation
from training import train_assembling_voting
voting_classifier = train_assembling_voting(train_comments, train_labels)
predictions = voting_classifier.predict_proba(test_comments)
print("\nMajority Vote Model Result\n")
predictions_report_proba(predictions, test_labels)
plot_confusion_matrix(voting_classifier, test_comments, test_labels, display_labels=[NO_INSULT, INSULT])
plt.show()
Explanation: Ensemble Voting Classifier
The goal of ensemble methods is to combine the predictions of several base estimators built with a given learning algorithm in order to improve generalizability / robustness over a single estimator.
We are going to combine the TF-IDF classifier and the custom classifier using a majority vote classifier. Most of the ensemble methods build several instances of a black-box estimator on random subsets of the original training set and then aggregate their individual predictions to form a final prediction. In this case, we need to combine estimators of different nature. Sklearn Voting classifier can help in this situation. The idea behind the VotingClassifier is to combine conceptually different machine learning classifiers and use a majority vote or the average predicted probabilities (soft vote) to predict the class labels. Such a classifier can be useful for a set of equally well performing model in order to balance out their individual weaknesses.
End of explanation
from training import train_feature_union
fu_classifier = train_feature_union(train_comments, train_labels)
predictions = fu_classifier.predict(test_comments)
print("\nFeature Union Model Result\n")
predictions_report(predictions, test_labels)
plot_confusion_matrix(fu_classifier, test_comments, test_labels, display_labels=[NO_INSULT, INSULT])
plt.show()
Explanation: Feature Union
To finish with classic estimators based solutions, we are going to make a final attempt by merging the features for both classifiers making use of sklearn FeatureUnion. This estimator applies a list of transformer objects in parallel to the input data, then concatenates the results. This is useful to combine several feature extraction mechanisms into a single transformer.
End of explanation
import gensim
from feature_extraction import word2vec_model, tokenize_document
raw_tokenized_corpus = [tokenize_document(comment) for comment in raw_train_comments]
dim = 300
max_len = 15
raw_w2v_model = word2vec_model(raw_tokenized_corpus, n_dim=dim)
print(raw_w2v_model.wv.similarity('retarded', 'loser'))
print(raw_w2v_model.wv.most_similar('retarded', topn=20))
tokenized_corpus = [tokenize_document(comment) for comment in train_comments]
test_tokenized_corpus = [tokenize_document(comment) for comment in test_comments]
w2v_model = word2vec_model(tokenized_corpus, n_dim=dim)
w2v_model.wv.most_similar('fakeinsult', topn=20)
# Repeat the process for test corpus
test_raw_tokenized_corpus = [tokenize_document(comment) for comment in raw_test_comments]
Explanation: Word Embeddings
Word Embedding is the collective name for feature learning techniques where words from the vocabulary are mapped to vectors of real numbers. These vectors are calculated from the probability distribution for each word appearing before or after another. To put it another way, words of the same context usually appear together in the corpus, so they will be close in the vector space as well.
End of explanation
## tokenize text for Keras network
import tensorflow as tf
ktokenizer = tf.keras.preprocessing.text.Tokenizer(lower=True, split=' ',
oov_token="NaN",
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n')
ktokenizer.fit_on_texts(raw_tokenized_corpus)
dic_vocabulary = ktokenizer.word_index
## create sequence
lst_text2seq= ktokenizer.texts_to_sequences(raw_tokenized_corpus)
## padding sequence
X_train = tf.keras.preprocessing.sequence.pad_sequences(lst_text2seq,
maxlen=max_len)
## text to sequence with the fitted tokenizer
lst_text2seq = ktokenizer.texts_to_sequences(test_raw_tokenized_corpus)
## padding sequence
X_test = tf.keras.preprocessing.sequence.pad_sequences(lst_text2seq, maxlen=max_len,
padding="post", truncating="post")
# Prepare the matrix of embeddings for the embeddings layer
embeddings = np.zeros((len(dic_vocabulary)+1, dim))
for word,idx in dic_vocabulary.items():
## update the row with vector
try:
embeddings[idx] = raw_w2v_model.wv[word]
## if word not in model then skip and the row stays all 0s
except:
pass
# Build the Network
from keras import layers, models
import keras
x_in = layers.Input(shape=(max_len,))
#Embedding
x = layers.Embedding(input_dim=embeddings.shape[0],
output_dim=embeddings.shape[1],
weights=[embeddings],
input_length=max_len, trainable=False)(x_in)
## LSTM
x = layers.Bidirectional(layers.LSTM(max_len, dropout=0.2, return_sequences=True))(x)
x = layers.Bidirectional(layers.LSTM(max_len, dropout=0.2))(x)
x = layers.Dense(64, activation='relu')(x)
y_out = layers.Dense(1, activation='sigmoid')(x)
## compile
model = models.Model(x_in, y_out)
model.compile(loss='binary_crossentropy',
optimizer=keras.optimizers.Adam(), metrics=['accuracy'])
model.summary()
# Train the model
callbacks = [tf.keras.callbacks.EarlyStopping(monitor='accuracy', patience=3)]
training = model.fit(x=X_train, y=train_labels, batch_size=64,
epochs=20, validation_split=0.3, class_weight={0: 1., 1: 2.5}, callbacks=callbacks)
# Evaluate Model
predictions = model.predict(X_test)
predictions_report_proba(predictions, test_labels)
Explanation: Word2Vec based classifier with Keras
End of explanation
ktokenizer = tf.keras.preprocessing.text.Tokenizer(lower=True, split=' ',
oov_token="NaN",
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n')
ktokenizer.fit_on_texts(tokenized_corpus)
dic_vocabulary = ktokenizer.word_index
## create sequence
lst_text2seq= ktokenizer.texts_to_sequences(tokenized_corpus)
## padding sequence
X_train = tf.keras.preprocessing.sequence.pad_sequences(lst_text2seq,
maxlen=max_len)
## text to sequence with the fitted tokenizer
lst_text2seq = ktokenizer.texts_to_sequences(test_tokenized_corpus)
## padding sequence
X_test = tf.keras.preprocessing.sequence.pad_sequences(lst_text2seq, maxlen=max_len,
padding="post", truncating="post")
# Prepare the matrix of embeddings for the embeddings layer
embeddings = np.zeros((len(dic_vocabulary)+1, dim))
for word,idx in dic_vocabulary.items():
## update the row with vector
try:
embeddings[idx] = w2v_model.wv[word]
## if word not in model then skip and the row stays all 0s
except:
pass
x_in = layers.Input(shape=(max_len,))
#Embedding
x = layers.Embedding(input_dim=embeddings.shape[0],
output_dim=embeddings.shape[1],
weights=[embeddings],
input_length=max_len, trainable=False)(x_in)
## LSTM
x = layers.Bidirectional(layers.LSTM(max_len, dropout=0.2, return_sequences=True))(x)
x = layers.Bidirectional(layers.LSTM(max_len, dropout=0.2))(x)
x = layers.Dense(64, activation='relu')(x)
y_out = layers.Dense(1, activation='sigmoid')(x)
## compile
model = models.Model(x_in, y_out)
model.compile(loss='binary_crossentropy',
optimizer=keras.optimizers.Adam(), metrics=['accuracy'])
model.summary()
callbacks = [tf.keras.callbacks.EarlyStopping(monitor='accuracy', patience=3)]
training = model.fit(x=X_train, y=train_labels, batch_size=64,
epochs=20, validation_split=0.3, class_weight={0: 1., 1: 2.5}, callbacks=callbacks)
# Evaluate Model
predictions = model.predict(X_test)
predictions_report_proba(predictions, test_labels)
Explanation: Same Classifier but replacing insults with 'fakeinsult'
End of explanation
import transformers
## bert tokenizer
tokenizer = transformers.BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
maxlen = 50
tokens_train = tokenizer.batch_encode_plus(
train_comments,
add_special_tokens = True, # add [CLS], [SEP]
max_length = maxlen,
pad_to_max_length=True, # add [PAD] tokens
truncation=True,
return_attention_mask = True, # add attention mask to not focus on pad tokens
)
## feature matrix
X_train = [np.asarray(tokens_train['input_ids'], dtype='int32'),
np.asarray(tokens_train['attention_mask'], dtype='int32'),
np.asarray(tokens_train['token_type_ids'], dtype='int32')]
tokens_test = tokenizer.batch_encode_plus(
test_comments,
add_special_tokens = True, # add [CLS], [SEP]
max_length = maxlen,
pad_to_max_length=True, # add [PAD] tokens
truncation=True,
return_attention_mask = True, # add attention mask to not focus on pad tokens
)
## feature matrix
X_test = [np.asarray(tokens_test['input_ids'], dtype='int32'),
np.asarray(tokens_test['attention_mask'], dtype='int32'),
np.asarray(tokens_test['token_type_ids'], dtype='int32')]
## inputs
idx = layers.Input((50), dtype="int32", name="input_idx")
masks = layers.Input((50), dtype="int32", name="input_masks")
segments = layers.Input((50), dtype="int32", name="input_segments")
## pre-trained bert
bert_model = transformers.TFBertModel.from_pretrained("bert-base-uncased")
bert_model.trainable = False
bert_out, _ = bert_model([idx, masks, segments])
## fine-tuning
# Add trainable layers on top of frozen layers to adapt the pretrained features on the new data.
bi_lstm = tf.keras.layers.Bidirectional(
tf.keras.layers.LSTM(64, return_sequences=True)
)(bert_out)
# Applying hybrid pooling approach to bi_lstm sequence output.
avg_pool = tf.keras.layers.GlobalAveragePooling1D()(bi_lstm)
max_pool = tf.keras.layers.GlobalMaxPooling1D()(bi_lstm)
concat = tf.keras.layers.concatenate([avg_pool, max_pool])
dropout = tf.keras.layers.Dropout(0.3)(concat)
#x = layers.GlobalAveragePooling1D()(bert_out)
#x = layers.Dense(64, activation="relu")(x)
y_out = layers.Dense(1, activation='sigmoid')(dropout)
## compile
model = models.Model([idx, masks, segments], y_out)
for layer in model.layers[:4]:
layer.trainable = False
model.compile(loss='binary_crossentropy',
optimizer='adam', metrics=['accuracy'])
model.summary()
training = model.fit(x=X_train, y=train_labels, batch_size=64,
epochs=1, validation_split=0.3, class_weight={0: 1., 1: 2.5})
# Evaluate Model
predictions = model.predict(X_test)
predictions_report_proba(predictions, test_labels)
Explanation: Language Models. BERT
In the field of computer vision, researchers have repeatedly shown the value of transfer learning — pre-training a neural network model on a known task, for instance ImageNet, and then performing fine-tuning — using the trained neural network as the basis of a new purpose-specific model. In recent years, researchers have been showing that a similar technique can be useful in many natural language tasks.
BERT makes use of Transformer, an attention mechanism that learns contextual relations between words (or sub-words) in a text. In its vanilla form, Transformer includes two separate mechanisms — an encoder that reads the text input and a decoder that produces a prediction for the task. Since BERT’s goal is to generate a language model, only the encoder mechanism is necessary.
As opposed to directional models, which read the text input sequentially (left-to-right or right-to-left), the Transformer encoder reads the entire sequence of words at once. Therefore it is considered bidirectional, though it would be more accurate to say that it’s non-directional. This characteristic allows the model to learn the context of a word based on all of its surroundings (left and right of the word).
End of explanation |
7,920 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
数据抓取:
抓取47年政府工作报告
王成军
wangchengjun@nju.edu.cn
计算传播网 http
Step1: Inspect
<td width="274" class="bl">· <a href="./d12qgrdzfbg/201603/t20160318_369509.html" target="_blank" title="2016年政府工作报告">2016年政府工作报告</a></td>
<td width="274" class="bl">·&nbsp;<a href="./d12qgrdzfbg/201603/t20160318_369509.html" target="_blank" title="2016年政府工作报告">2016年政府工作报告</a></td>
Step2: decode
urllib2.urlopen(url).read().decode('gb18030')
html.parser
BeautifulSoup(content, 'html.parser')
Step3: Inspect 下一页
<a href="t20090818_27775_1.html"><span style="color | Python Code:
import urllib2
from bs4 import BeautifulSoup
from IPython.display import display_html, HTML
HTML('<iframe src=http://www.hprc.org.cn/wxzl/wxysl/lczf/ width=1000 height=500></iframe>')
# the webpage we would like to crawl
Explanation: 数据抓取:
抓取47年政府工作报告
王成军
wangchengjun@nju.edu.cn
计算传播网 http://computational-communication.com
End of explanation
# get the link for each year
url = "http://www.hprc.org.cn/wxzl/wxysl/lczf/"
content = urllib2.urlopen(url).read().decode('gb18030')
soup = BeautifulSoup(content, 'html.parser')
links = soup.find_all('td', {'class', 'bl'})
Explanation: Inspect
<td width="274" class="bl">· <a href="./d12qgrdzfbg/201603/t20160318_369509.html" target="_blank" title="2016年政府工作报告">2016年政府工作报告</a></td>
<td width="274" class="bl">·&nbsp;<a href="./d12qgrdzfbg/201603/t20160318_369509.html" target="_blank" title="2016年政府工作报告">2016年政府工作报告</a></td>
End of explanation
links = soup.find_all('td', class_='bl')
print len(links)
print links[0]
print links[0].a
print links[0].a['href']
print links[0].a['href'].split('./')
print links[0].a['href'].split('./')[1]
print url + links[0].a['href'].split('./')[1]
hyperlinks = [url + i.a['href'].split('./')[1] for i in links]
hyperlinks
hyperlinks[9] # 2007年有分页
from IPython.display import display_html, HTML
HTML('<iframe src=http://www.hprc.org.cn/wxzl/wxysl/lczf/dishiyijie_1/200908/t20090818_27775.html \
width=1000 height=500></iframe>')
# 2007年有分页
Explanation: decode
urllib2.urlopen(url).read().decode('gb18030')
html.parser
BeautifulSoup(content, 'html.parser')
End of explanation
url_i = 'http://www.hprc.org.cn/wxzl/wxysl/lczf/dishiyijie_1/200908/t20090818_27775.html'
content = urllib2.urlopen(url_i).read().decode('gb18030')
soup = BeautifulSoup(content, 'html.parser')
scripts = soup.find_all('script')
scripts[0]
print scripts[1].text
from pyjsparser import PyJsParser
p = PyJsParser()
p.parse('var $ = "Hello!"')
jp = p.parse(scripts[1].text)
jp
jp['type']
len(jp['body'])
jp['body'][3]
jp['body'][3]['declarations'][0]['init']['value']
countPage = int(''.join(scripts[1]).split('countPage = ')[1].split('//')[0])
countPage
def crawler(url_i):
content = urllib2.urlopen(url_i).read().decode('gb18030')
soup = BeautifulSoup(content, 'html.parser')
year = soup.find('span', {'class', 'huang16c'}).text[:4]
year = int(year)
report = ''.join(s.text for s in soup('p'))
# 找到分页信息
scripts = soup.find_all('script')
countPage = int(''.join(scripts[1]).split('countPage = ')[1].split('//')[0])
if countPage == 1:
pass
else:
for i in range(1, countPage):
url_child = url_i.split('.html')[0] +'_'+str(i)+'.html'
content = urllib2.urlopen(url_child).read().decode('gb18030')
soup = BeautifulSoup(content)
report_child = ''.join(s.text for s in soup('p'))
report = report + report_child
return year, report
# 抓取47年政府工作报告内容
reports = {}
for link in hyperlinks:
year, report = crawler(link)
print year
reports[year] = report
url2016 = 'http://news.xinhuanet.com/fortune/2016-03/05/c_128775704.htm'
content = urllib2.urlopen(url2016).read()
soup = BeautifulSoup(content, 'html.parser')
report2016 = ''.join(s.text for s in soup('p'))
with open('/Users/chengjun/github/cjc2016/data/gov_reports1954-2016.txt', 'wb') as f:
for r in reports:
line = str(r)+'\t'+reports[r].replace('\n', '\t') +'\n'
f.write(line.encode('utf-8'))
Explanation: Inspect 下一页
<a href="t20090818_27775_1.html"><span style="color:#0033FF;font-weight:bold">下一页</span></a>
<a href="t20090818_27775_1.html"><span style="color:#0033FF;font-weight:bold">下一页</span></a>
a
script
td
End of explanation |
7,921 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: Where Am I?
Startup.ML Conference - San Francisco - Jan 20, 2017
Who Am I?
Chris Fregly
Research Scientist @ PipelineIO
Video Series Author "High Performance Tensorflow in Production" @ OReilly (Coming Soon)
Founder @ Advanced Spark and Tensorflow Meetup
Github Repo
DockerHub Repo
Slideshare
YouTube
Who Was I?
Software Engineer @ Netflix, Databricks, IBM Spark Tech Center
1. Infrastructure and Tools
Docker
Images, Containers
Useful Docker Image
Step5: Commit and Deploy New Tensorflow AI Model
Commit Model to Github
Step6: Airflow Workflow Deploys New Model through Github Post-Commit Webhook to Triggers
Step7: Train and Deploy Spark ML Model (Airbnb Model, Mutable Deploy)
Scale Out Spark Training Cluster
Kubernetes CLI
Step8: Weavescope Kubernetes AWS Cluster Visualization
Step9: Generate PMML from Spark ML Model
Step10: Step 0
Step14: Step 1
Step15: Step 2
Step16: Step 3
Step17: Step 4
Step18: Step 5
Step19: Step 6
Step20: Step 7
Step21: Step 8
Step22: Push PMML to Live, Running Spark ML Model Server (Mutable)
Step23: Deploy Java-based Model (Simple Model, Mutable Deploy)
Step24: Deploy Java Model (HttpClient Model, Mutable Deploy)
Step25: Load Test and Compare Cloud Providers (AWS and Google)
Monitor Performance Across Cloud Providers
NetflixOSS Services Dashboard (Hystrix)
Step26: Start Load Tests
Run JMeter Tests from Local Laptop (Limited by Laptop)
Run Headless JMeter Tests from Training Clusters in Cloud
Step27: End Load Tests
Step28: Rolling Deploy Tensorflow AI (Simple Model, Immutable Deploy)
Kubernetes CLI | Python Code:
import numpy as np
import os
import tensorflow as tf
from tensorflow.contrib.session_bundle import exporter
import time
# make things wide
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
from IPython.display import clear_output, Image, display, HTML
def strip_consts(graph_def, max_const_size=32):
Strip large constant values from graph_def.
strip_def = tf.GraphDef()
for n0 in graph_def.node:
n = strip_def.node.add()
n.MergeFrom(n0)
if n.op == 'Const':
tensor = n.attr['value'].tensor
size = len(tensor.tensor_content)
if size > max_const_size:
tensor.tensor_content = "<stripped %d bytes>"%size
return strip_def
def show_graph(graph_def=None, width=1200, height=800, max_const_size=32, ungroup_gradients=False):
if not graph_def:
graph_def = tf.get_default_graph().as_graph_def()
Visualize TensorFlow graph.
if hasattr(graph_def, 'as_graph_def'):
graph_def = graph_def.as_graph_def()
strip_def = strip_consts(graph_def, max_const_size=max_const_size)
data = str(strip_def)
if ungroup_gradients:
data = data.replace('"gradients/', '"b_')
#print(data)
code =
<script>
function load() {{
document.getElementById("{id}").pbtxt = {data};
}}
</script>
<link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
<div style="height:600px">
<tf-graph-basic id="{id}"></tf-graph-basic>
</div>
.format(data=repr(data), id='graph'+str(np.random.rand()))
iframe =
<iframe seamless style="width:{}px;height:{}px;border:0" srcdoc="{}"></iframe>
.format(width, height, code.replace('"', '"'))
display(HTML(iframe))
# If this errors out, increment the `export_version` variable, restart the Kernel, and re-run
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer("batch_size", 10, "The batch size to train")
flags.DEFINE_integer("epoch_number", 10, "Number of epochs to run trainer")
flags.DEFINE_integer("steps_to_validate", 1,
"Steps to validate and print loss")
flags.DEFINE_string("checkpoint_dir", "./checkpoint/",
"indicates the checkpoint dirctory")
#flags.DEFINE_string("model_path", "./model/", "The export path of the model")
flags.DEFINE_string("model_path", "/root/pipeline/prediction.ml/tensorflow/models/tensorflow_minimal/export/", "The export path of the model")
#flags.DEFINE_integer("export_version", 27, "The version number of the model")
from datetime import datetime
seconds_since_epoch = int(datetime.now().strftime("%s"))
export_version = seconds_since_epoch
# If this errors out, increment the `export_version` variable, restart the Kernel, and re-run
def main():
# Define training data
x = np.ones(FLAGS.batch_size)
y = np.ones(FLAGS.batch_size)
# Define the model
X = tf.placeholder(tf.float32, shape=[None], name="X")
Y = tf.placeholder(tf.float32, shape=[None], name="yhat")
w = tf.Variable([1.0], name="weight")
b = tf.Variable([1.0], name="bias")
loss = tf.square(Y - tf.matmul(X, w) - b)
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
predict_op = tf.mul(X, w) + b
saver = tf.train.Saver()
checkpoint_dir = FLAGS.checkpoint_dir
checkpoint_file = checkpoint_dir + "/checkpoint.ckpt"
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
# Start the session
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
print("Continue training from the model {}".format(ckpt.model_checkpoint_path))
saver.restore(sess, ckpt.model_checkpoint_path)
saver_def = saver.as_saver_def()
print(saver_def.filename_tensor_name)
print(saver_def.restore_op_name)
# Start training
start_time = time.time()
for epoch in range(FLAGS.epoch_number):
sess.run(train_op, feed_dict={X: x, Y: y})
# Start validating
if epoch % FLAGS.steps_to_validate == 0:
end_time = time.time()
print("[{}] Epoch: {}".format(end_time - start_time, epoch))
saver.save(sess, checkpoint_file)
tf.train.write_graph(sess.graph_def, checkpoint_dir, 'trained_model.pb', as_text=False)
tf.train.write_graph(sess.graph_def, checkpoint_dir, 'trained_model.txt', as_text=True)
start_time = end_time
# Print model variables
w_value, b_value = sess.run([w, b])
print("The model of w: {}, b: {}".format(w_value, b_value))
# Export the model
print("Exporting trained model to {}".format(FLAGS.model_path))
model_exporter = exporter.Exporter(saver)
model_exporter.init(
sess.graph.as_graph_def(),
named_graph_signatures={
'inputs': exporter.generic_signature({"features": X}),
'outputs': exporter.generic_signature({"prediction": predict_op})
})
model_exporter.export(FLAGS.model_path, tf.constant(export_version), sess)
print('Done exporting!')
if __name__ == "__main__":
main()
show_graph()
Explanation: Where Am I?
Startup.ML Conference - San Francisco - Jan 20, 2017
Who Am I?
Chris Fregly
Research Scientist @ PipelineIO
Video Series Author "High Performance Tensorflow in Production" @ OReilly (Coming Soon)
Founder @ Advanced Spark and Tensorflow Meetup
Github Repo
DockerHub Repo
Slideshare
YouTube
Who Was I?
Software Engineer @ Netflix, Databricks, IBM Spark Tech Center
1. Infrastructure and Tools
Docker
Images, Containers
Useful Docker Image: AWS + GPU + Docker + Tensorflow + Spark
Kubernetes
Container Orchestration Across Clusters
Weavescope
Kubernetes Cluster Visualization
Jupyter Notebooks
What We're Using Here for Everything!
Airflow
Invoke Any Type of Workflow on Any Type of Schedule
Github
Commit New Model to Github, Airflow Workflow Triggered for Continuous Deployment
DockerHub
Maintains Docker Images
Continuous Deployment
Not Just for Code, Also for ML/AI Models!
Canary Release
Deploy and Compare New Model Alongside Existing
Metrics and Dashboards
Not Just System Metrics, ML/AI Model Prediction Metrics
NetflixOSS-based
Prometheus
Grafana
Elasticsearch
Separate Cluster Concerns
Training/Admin Cluster
Prediction Cluster
Hybrid Cloud Deployment for eXtreme High Availability (XHA)
AWS and Google Cloud
Apache Spark
Tensorflow + Tensorflow Serving
2. Model Deployment Bundles
KeyValue
ie. Recommendations
In-memory: Redis, Memcache
On-disk: Cassandra, RocksDB
First-class Servable in Tensorflow Serving
PMML
It's Useful and Well-Supported
Apple, Cisco, Airbnb, HomeAway, etc
Please Don't Re-build It - Reduce Your Technical Debt!
Native Code
Hand-coded (Python + Pickling)
Generate Java Code from PMML?
Tensorflow Model Exports
freeze_graph.py: Combine Tensorflow Graph (Static) with Trained Weights (Checkpoints) into Single Deployable Model
3. Model Deployments and Rollbacks
Mutable
Each New Model is Deployed to Live, Running Container
Immutable
Each New Model is a New Docker Image
4. Optimizing Tensorflow Models for Serving
Python Scripts
optimize_graph_for_inference.py
Pete Warden's Blog
Graph Transform Tool
Compile (Tensorflow 1.0+)
XLA Compiler
Compiles 3 graph operations (input, operation, output) into 1 operation
Removes need for Tensorflow Runtime (20 MB is significant on tiny devices)
Allows new backends for hardware-specific optimizations (better portability)
tfcompile
Convert Graph into executable code
Compress/Distill Ensemble Models
Convert ensembles or other complex models into smaller models
Re-score training data with output of model being distilled
Train smaller model to produce same output
Output of smaller model learns more information than original label
5. Optimizing Serving Runtime Environment
Throughput
Option 1: Add more Tensorflow Serving servers behind load balancer
Option 2: Enable request batching in each Tensorflow Serving
Option Trade-offs: Higher Latency (bad) for Higher Throughput (good)
$TENSORFLOW_SERVING_HOME/bazel-bin/tensorflow_serving/model_servers/tensorflow_model_server
--port=9000
--model_name=tensorflow_minimal
--model_base_path=/root/models/tensorflow_minimal/export
--enable_batching=true
--max_batch_size=1000000
--batch_timeout_micros=10000
--max_enqueued_batches=1000000
Latency
The deeper the model, the longer the latency
Start inference in parallel where possible (ie. user inference in parallel with item inference)
Pre-load common inputs from database (ie. user attributes, item attributes)
Pre-compute/partial-compute common inputs (ie. popular word embeddings)
Memory
Word embeddings are huge!
Use hashId for each word
Off-load embedding matrices to parameter server and share between serving servers
6. Demos!!
Train and Deploy Tensorflow AI Model (Simple Model, Immutable Deploy)
Train Tensorflow AI Model
End of explanation
!ls -l /root/pipeline/prediction.ml/tensorflow/models/tensorflow_minimal/export
!ls -l /root/pipeline/prediction.ml/tensorflow/models/tensorflow_minimal/export/00000027
!git status
!git add --all /root/pipeline/prediction.ml/tensorflow/models/tensorflow_minimal/export/00000027/
!git status
!git commit -m "updated tensorflow model"
!git status
# If this fails with "Permission denied", use terminal within jupyter to manually `git push`
!git push
Explanation: Commit and Deploy New Tensorflow AI Model
Commit Model to Github
End of explanation
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
from IPython.display import clear_output, Image, display, HTML
html = '<iframe width=100% height=500px src="http://demo.pipeline.io:8080/admin">'
display(HTML(html))
Explanation: Airflow Workflow Deploys New Model through Github Post-Commit Webhook to Triggers
End of explanation
!kubectl scale --context=awsdemo --replicas=2 rc spark-worker-2-0-1
!kubectl get pod --context=awsdemo
Explanation: Train and Deploy Spark ML Model (Airbnb Model, Mutable Deploy)
Scale Out Spark Training Cluster
Kubernetes CLI
End of explanation
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
from IPython.display import clear_output, Image, display, HTML
html = '<iframe width=100% height=500px src="http://kubernetes-aws.demo.pipeline.io">'
display(HTML(html))
Explanation: Weavescope Kubernetes AWS Cluster Visualization
End of explanation
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler, StandardScaler
from pyspark.ml.feature import OneHotEncoder, StringIndexer
from pyspark.ml import Pipeline, PipelineModel
from pyspark.ml.regression import LinearRegression
# You may need to Reconnect (more than Restart) the Kernel to pick up changes to these sett
import os
master = '--master spark://spark-master-2-1-0:7077'
conf = '--conf spark.cores.max=1 --conf spark.executor.memory=512m'
packages = '--packages com.amazonaws:aws-java-sdk:1.7.4,org.apache.hadoop:hadoop-aws:2.7.1'
jars = '--jars /root/lib/jpmml-sparkml-package-1.0-SNAPSHOT.jar'
py_files = '--py-files /root/lib/jpmml.py'
os.environ['PYSPARK_SUBMIT_ARGS'] = master \
+ ' ' + conf \
+ ' ' + packages \
+ ' ' + jars \
+ ' ' + py_files \
+ ' ' + 'pyspark-shell'
print(os.environ['PYSPARK_SUBMIT_ARGS'])
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
Explanation: Generate PMML from Spark ML Model
End of explanation
df = spark.read.format("csv") \
.option("inferSchema", "true").option("header", "true") \
.load("s3a://datapalooza/airbnb/airbnb.csv.bz2")
df.registerTempTable("df")
print(df.head())
print(df.count())
Explanation: Step 0: Load Libraries and Data
End of explanation
df_filtered = df.filter("price >= 50 AND price <= 750 AND bathrooms > 0.0 AND bedrooms is not null")
df_filtered.registerTempTable("df_filtered")
df_final = spark.sql(
select
id,
city,
case when state in('NY', 'CA', 'London', 'Berlin', 'TX' ,'IL', 'OR', 'DC', 'WA')
then state
else 'Other'
end as state,
space,
cast(price as double) as price,
cast(bathrooms as double) as bathrooms,
cast(bedrooms as double) as bedrooms,
room_type,
host_is_super_host,
cancellation_policy,
cast(case when security_deposit is null
then 0.0
else security_deposit
end as double) as security_deposit,
price_per_bedroom,
cast(case when number_of_reviews is null
then 0.0
else number_of_reviews
end as double) as number_of_reviews,
cast(case when extra_people is null
then 0.0
else extra_people
end as double) as extra_people,
instant_bookable,
cast(case when cleaning_fee is null
then 0.0
else cleaning_fee
end as double) as cleaning_fee,
cast(case when review_scores_rating is null
then 80.0
else review_scores_rating
end as double) as review_scores_rating,
cast(case when square_feet is not null and square_feet > 100
then square_feet
when (square_feet is null or square_feet <=100) and (bedrooms is null or bedrooms = 0)
then 350.0
else 380 * bedrooms
end as double) as square_feet
from df_filtered
).persist()
df_final.registerTempTable("df_final")
df_final.select("square_feet", "price", "bedrooms", "bathrooms", "cleaning_fee").describe().show()
print(df_final.count())
print(df_final.schema)
# Most popular cities
spark.sql(
select
state,
count(*) as ct,
avg(price) as avg_price,
max(price) as max_price
from df_final
group by state
order by count(*) desc
).show()
# Most expensive popular cities
spark.sql(
select
city,
count(*) as ct,
avg(price) as avg_price,
max(price) as max_price
from df_final
group by city
order by avg(price) desc
).filter("ct > 25").show()
Explanation: Step 1: Clean, Filter, and Summarize the Data
End of explanation
continuous_features = ["bathrooms", \
"bedrooms", \
"security_deposit", \
"cleaning_fee", \
"extra_people", \
"number_of_reviews", \
"square_feet", \
"review_scores_rating"]
categorical_features = ["room_type", \
"host_is_super_host", \
"cancellation_policy", \
"instant_bookable", \
"state"]
Explanation: Step 2: Define Continous and Categorical Features
End of explanation
[training_dataset, validation_dataset] = df_final.randomSplit([0.8, 0.2])
Explanation: Step 3: Split Data into Training and Validation
End of explanation
continuous_feature_assembler = VectorAssembler(inputCols=continuous_features, outputCol="unscaled_continuous_features")
continuous_feature_scaler = StandardScaler(inputCol="unscaled_continuous_features", outputCol="scaled_continuous_features", \
withStd=True, withMean=False)
Explanation: Step 4: Continous Feature Pipeline
End of explanation
categorical_feature_indexers = [StringIndexer(inputCol=x, \
outputCol="{}_index".format(x)) \
for x in categorical_features]
categorical_feature_one_hot_encoders = [OneHotEncoder(inputCol=x.getOutputCol(), \
outputCol="oh_encoder_{}".format(x.getOutputCol() )) \
for x in categorical_feature_indexers]
Explanation: Step 5: Categorical Feature Pipeline
End of explanation
feature_cols_lr = [x.getOutputCol() \
for x in categorical_feature_one_hot_encoders]
feature_cols_lr.append("scaled_continuous_features")
feature_assembler_lr = VectorAssembler(inputCols=feature_cols_lr, \
outputCol="features_lr")
Explanation: Step 6: Assemble our Features and Feature Pipeline
End of explanation
linear_regression = LinearRegression(featuresCol="features_lr", \
labelCol="price", \
predictionCol="price_prediction", \
maxIter=10, \
regParam=0.3, \
elasticNetParam=0.8)
estimators_lr = \
[continuous_feature_assembler, continuous_feature_scaler] \
+ categorical_feature_indexers + categorical_feature_one_hot_encoders \
+ [feature_assembler_lr] + [linear_regression]
pipeline = Pipeline(stages=estimators_lr)
pipeline_model = pipeline.fit(training_dataset)
print(pipeline_model)
Explanation: Step 7: Train a Linear Regression Model
End of explanation
from jpmml import toPMMLBytes
model_bytes = toPMMLBytes(spark, training_dataset, pipeline_model)
print(model_bytes.decode("utf-8"))
Explanation: Step 8: Convert PipelineModel to PMML
End of explanation
import urllib.request
namespace = 'default'
model_name = 'airbnb'
version = '1'
update_url = 'http://prediction-pmml-aws.demo.pipeline.io/update-pmml-model/%s/%s/%s' % (namespace, model_name, version)
update_headers = {}
update_headers['Content-type'] = 'application/xml'
req = urllib.request.Request(update_url, \
headers=update_headers, \
data=model_bytes)
resp = urllib.request.urlopen(req)
print(resp.status) # Should return Http Status 200
import urllib.request
update_url = 'http://prediction-pmml-gcp.demo.pipeline.io/update-pmml/pmml_airbnb'
update_headers = {}
update_headers['Content-type'] = 'application/xml'
req = urllib.request.Request(update_url, \
headers=update_headers, \
data=pmmlBytes)
resp = urllib.request.urlopen(req)
print(resp.status) # Should return Http Status 200
import urllib.parse
import json
namespace = 'default'
model_name = 'airbnb'
version = '1'
evaluate_url = 'http://prediction-pmml-aws.demo.pipeline.io/evaluate-pmml-model/%s/%s/%s' % (namespace, model_name, version)
evaluate_headers = {}
evaluate_headers['Content-type'] = 'application/json'
input_params = '{"bathrooms":5.0, \
"bedrooms":4.0, \
"security_deposit":175.00, \
"cleaning_fee":25.0, \
"extra_people":1.0, \
"number_of_reviews": 2.0, \
"square_feet": 250.0, \
"review_scores_rating": 2.0, \
"room_type": "Entire home/apt", \
"host_is_super_host": "0.0", \
"cancellation_policy": "flexible", \
"instant_bookable": "1.0", \
"state": "CA"}'
encoded_input_params = input_params.encode('utf-8')
req = urllib.request.Request(evaluate_url, \
headers=evaluate_headers, \
data=encoded_input_params)
resp = urllib.request.urlopen(req)
print(resp.read())
Explanation: Push PMML to Live, Running Spark ML Model Server (Mutable)
End of explanation
from urllib import request
sourceBytes = ' \n\
private String str; \n\
\n\
public void initialize(Map<String, Object> args) { \n\
} \n\
\n\
public Object predict(Map<String, Object> inputs) { \n\
String id = (String)inputs.get("id"); \n\
\n\
return id.equals("21619"); \n\
} \n\
'.encode('utf-8')
from urllib import request
namespace = 'default'
model_name = 'java_equals'
version = '1'
update_url = 'http://prediction-java-aws.demo.pipeline.io/update-java/%s/%s/%s' % (namespace, model_name, version)
update_headers = {}
update_headers['Content-type'] = 'text/plain'
req = request.Request("%s" % update_url, headers=update_headers, data=sourceBytes)
resp = request.urlopen(req)
generated_code = resp.read()
print(generated_code.decode('utf-8'))
from urllib import request
namespace = 'default'
model_name = 'java_equals'
version = '1'
evaluate_url = 'http://prediction-java-aws.demo.pipeline.io/evaluate-java/%s/%s/%s' % (namespace, model_name, version)
evaluate_headers = {}
evaluate_headers['Content-type'] = 'application/json'
input_params = '{"id":"21618"}'
encoded_input_params = input_params.encode('utf-8')
req = request.Request(evaluate_url, headers=evaluate_headers, data=encoded_input_params)
resp = request.urlopen(req)
print(resp.read()) # Should return false
from urllib import request
namespace = 'default'
model_name = 'java_equals'
version = '1'
evaluate_url = 'http://prediction-java-aws.demo.pipeline.io/evaluate-java/%s/%s/%s' % (namespace, model_name, version)
evaluate_headers = {}
evaluate_headers['Content-type'] = 'application/json'
input_params = '{"id":"21619"}'
encoded_input_params = input_params.encode('utf-8')
req = request.Request(evaluate_url, headers=evaluate_headers, data=encoded_input_params)
resp = request.urlopen(req)
print(resp.read()) # Should return true
Explanation: Deploy Java-based Model (Simple Model, Mutable Deploy)
End of explanation
from urllib import request
sourceBytes = ' \n\
public Map<String, Object> data = new HashMap<String, Object>(); \n\
\n\
public void initialize(Map<String, Object> args) { \n\
data.put("url", "http://demo.pipeline.io:9040/prediction/"); \n\
} \n\
\n\
public Object predict(Map<String, Object> inputs) { \n\
try { \n\
String userId = (String)inputs.get("userId"); \n\
String itemId = (String)inputs.get("itemId"); \n\
String url = data.get("url") + "/" + userId + "/" + itemId; \n\
\n\
return org.apache.http.client.fluent.Request \n\
.Get(url) \n\
.execute() \n\
.returnContent(); \n\
\n\
} catch(Exception exc) { \n\
System.out.println(exc); \n\
throw exc; \n\
} \n\
} \n\
'.encode('utf-8')
from urllib import request
name = 'codegen_httpclient'
# Note: Must have trailing '/'
update_url = 'http://prediction-codegen-aws.demo.pipeline.io/update-codegen/%s/' % name
update_headers = {}
update_headers['Content-type'] = 'text/plain'
req = request.Request("%s" % update_url, headers=update_headers, data=sourceBytes)
resp = request.urlopen(req)
generated_code = resp.read()
print(generated_code.decode('utf-8'))
from urllib import request
name = 'codegen_httpclient'
# Note: Must have trailing '/'
update_url = 'http://prediction-codegen-gcp.demo.pipeline.io/update-codegen/%s/' % name
update_headers = {}
update_headers['Content-type'] = 'text/plain'
req = request.Request("%s" % update_url, headers=update_headers, data=sourceBytes)
resp = request.urlopen(req)
generated_code = resp.read()
print(generated_code.decode('utf-8'))
from urllib import request
name = 'codegen_httpclient'
evaluate_url = 'http://prediction-codegen-aws.demo.pipeline.io/evaluate-codegen/%s' % name
evaluate_headers = {}
evaluate_headers['Content-type'] = 'application/json'
input_params = '{"userId":"21619", "itemId":"10006"}'
encoded_input_params = input_params.encode('utf-8')
req = request.Request(evaluate_url, headers=evaluate_headers, data=encoded_input_params)
resp = request.urlopen(req)
print(resp.read()) # Should return float
from urllib import request
name = 'codegen_httpclient'
evaluate_url = 'http://prediction-codegen-gcp.demo.pipeline.io/evaluate-codegen/%s' % name
evaluate_headers = {}
evaluate_headers['Content-type'] = 'application/json'
input_params = '{"userId":"21619", "itemId":"10006"}'
encoded_input_params = input_params.encode('utf-8')
req = request.Request(evaluate_url, headers=evaluate_headers, data=encoded_input_params)
resp = request.urlopen(req)
print(resp.read()) # Should return float
Explanation: Deploy Java Model (HttpClient Model, Mutable Deploy)
End of explanation
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
from IPython.display import clear_output, Image, display, HTML
html = '<iframe width=100% height=500px src="http://hystrix.demo.pipeline.io/hystrix-dashboard/monitor/monitor.html?streams=%5B%7B%22name%22%3A%22Predictions%20-%20AWS%22%2C%22stream%22%3A%22http%3A%2F%2Fturbine-aws.demo.pipeline.io%2Fturbine.stream%22%2C%22auth%22%3A%22%22%2C%22delay%22%3A%22%22%7D%2C%7B%22name%22%3A%22Predictions%20-%20GCP%22%2C%22stream%22%3A%22http%3A%2F%2Fturbine-gcp.demo.pipeline.io%2Fturbine.stream%22%2C%22auth%22%3A%22%22%2C%22delay%22%3A%22%22%7D%5D">'
display(HTML(html))
Explanation: Load Test and Compare Cloud Providers (AWS and Google)
Monitor Performance Across Cloud Providers
NetflixOSS Services Dashboard (Hystrix)
End of explanation
# Spark ML - PMML - Airbnb
!kubectl create --context=awsdemo -f /root/pipeline/loadtest.ml/loadtest-aws-airbnb-rc.yaml
!kubectl create --context=gcpdemo -f /root/pipeline/loadtest.ml/loadtest-aws-airbnb-rc.yaml
# Codegen - Java - Simple
!kubectl create --context=awsdemo -f /root/pipeline/loadtest.ml/loadtest-aws-equals-rc.yaml
!kubectl create --context=gcpdemo -f /root/pipeline/loadtest.ml/loadtest-aws-equals-rc.yaml
# Tensorflow AI - Tensorflow Serving - Simple
!kubectl create --context=awsdemo -f /root/pipeline/loadtest.ml/loadtest-aws-minimal-rc.yaml
!kubectl create --context=gcpdemo -f /root/pipeline/loadtest.ml/loadtest-aws-minimal-rc.yaml
Explanation: Start Load Tests
Run JMeter Tests from Local Laptop (Limited by Laptop)
Run Headless JMeter Tests from Training Clusters in Cloud
End of explanation
!kubectl delete --context=awsdemo rc loadtest-aws-airbnb
!kubectl delete --context=gcpdemo rc loadtest-aws-airbnb
!kubectl delete --context=awsdemo rc loadtest-aws-equals
!kubectl delete --context=gcpdemo rc loadtest-aws-equals
!kubectl delete --context=awsdemo rc loadtest-aws-minimal
!kubectl delete --context=gcpdemo rc loadtest-aws-minimal
Explanation: End Load Tests
End of explanation
!kubectl rolling-update prediction-tensorflow --context=awsdemo --image-pull-policy=Always --image=fluxcapacitor/prediction-tensorflow
!kubectl get pod --context=awsdemo
!kubectl rolling-update prediction-tensorflow --context=gcpdemo --image-pull-policy=Always --image=fluxcapacitor/prediction-tensorflow
!kubectl get pod --context=gcpdemo
Explanation: Rolling Deploy Tensorflow AI (Simple Model, Immutable Deploy)
Kubernetes CLI
End of explanation |
7,922 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABU量化系统使用文档
<center>
<img src="./image/abu_logo.png" alt="" style="vertical-align
Step1: 1. 参数取值范围
Grid Search实际上是蒙特卡洛方法的一种实现子集,它首先固定了几组参数取值范围,把无限个解问题先缩小到有限个解的问题,然后对排列组合的各个参数组合迭代进行运算,得到最优结果。
既然是在给定参数范围内寻找最优,所以首先要给定一个合理的参数范围,下面首先寻找AbuFactorAtrNStop的参数组合如下所示:
Step2: 之前小节构造因子对象的序列使用字典形式装载参数和class,如下所示
{'stop_loss_n'
Step3: 在参数参数设置范围确定了的前提下即可以开始对参数进行组合,代码如下所示:
Step4: 上述代码使用ABuGridHelper.gen_factor_grid对参数进行组合,结果共组合出477种包括不同参数的组合,不同因子的组合,也有完全不使用任何因子的组合。
相似方式使用ABuGridHelper生成不同买入参数的因子排列组合, 这里只使用42日、60日作为备选参数。读者可使用类似bk_days = np.arange(20, 130, 10)方式生成更多的买入参数,更可以自己实现其它的买入策略与AbuFactorBuyBreak一同做grid,但是在之后阶段运行Grid Search速度就会越慢。
Step5: 由于只选用42d、60d为参数,所以只有三种排列组合,也就是分别为:
只使用42d突破因子
只使用60d突破因子
同时使用42d、60d突破因子
买入因子有477种组合,卖出因子有3种组合,两者再组合将有477 x 3 = 1431中因子组合
Step6: 2. Grid Search寻找最优参数
下面代码使用abupy中的GridSearch类进行最优参数寻找,从GridSearch类参数可以看到除了buy_factors_product、sell_factors_product外,还有stock_pickers_product(选股因子排列组合)本例没有用到,读者可自行尝试。
Step8: 下面开始通过fit函数开始寻找最优,第一次运行select:run gird search,然后点击run select,如果已经运行过可select:load score cache直接从缓存数据读取
备注:如果第一次运行选择run gird search下面的运行耗时大约1小时多,建议电脑空闲时运行
Step9: 下面使用type查看返回的score_tuple_array类型为list,score_tuple_array中的元素类型为AbuScoreTuple:
Step10: 上面说过组合数量477 x 3 = 1431中因子组合:
最终的评分结果也应该scores是有1431种,下面开始验证:
Step11: grid_search中保存了得到分数最高的对象best_score_tuple_grid,可以利用它直接用AbuMetricsBase可视化最优参数结果,如图:
Step12: 3. 度量结果的评分
读者可能会有的疑问1:哪里来的分数,怎么评定的分数。
在GridSearch类 fit()函数中可以看到第二个参数score_class需要一个判分类,在fit()中最后几行使用ABuMetricsScore.make_scorer()函数将所有返回的结果score_tuple_array使用判分类WrsmScorer对结果打分数。
打分数实现的基本思路为:如果想根据sharpe值的结果来对最优参数下判断,但是sharpe值多大可以判定为100分?多大可以判断为50分呢?我们无法确定,所以将所有sharpe结果排序,由于sharpe值越大越好,所以排序结果对应分数由0至1,这样就可以得到某一个具体参数组合的sharpe值的分数。这样的话使用多个评分标准, 比如这里使用'win_rate'、 'returns'、 'sharpe'、'max_drawdown'四种,就可以分别计算出某个参数组合对应的度量指标评分,再乘以分配给它们的权重就可以得到最终结果分数。
具体请阅读GridSearch.fit,AbuBaseScorer,WrsmScorer源代码实现
如下代码我们实例化一个评分类WrsmScorer,它的参数为之前GridSearch返回的score_tuple_array对象:
Step13: 如下可以看到scorer中的score_pd是由评分的度量指标数值,以及这个具体数据对应项所得的分数组成:
Step14: 由于AbuBaseScorer 中fit_score()函数的实现只是对score_pd的'score'项进行排序后返回score,这样最终的结果为分数及对应score_tuple_array的序列号,从上面输出可以看出665为最优参数序号。
4. 不同权重的评分
读者可能会有的疑问2:为什么从度量可视化看到的这个最优的投资回报还没有上一节的那个回测高?
因为由于默认的WrsmScorer使用:胜率、sharpe、投资回报、最大回撤这四个因素,综合评定策略的分数,并且类GridSearch默认为四项等权重评分,我们下面可以仍然使用WrsmScorer但是通过调整权重来达到各种评定效果。
Step15: 可以看到只考虑投资回报来评分的话,上面策略收益
Step16: 下面看一下只考虑胜率来评分的结果,从结果可以看到虽然胜率达到了85%以上,但是收益并不高:
Step19: 从输出可以看到买入策略只使用60天突破买入作为买入信号,卖出只以保护利润的止盈ABuFactorCloseAtrNStop发出卖出信号,其实这种策略就是没有止损的策略。很像大多数普通交易者的交易模式,亏损了的交易不卖出,持有直到可以再次盈利为。这样的方式投资者的胜率非常高,我之前看过几个朋友的交易账户,发现他们交易的胜率非常高,但他们的账户最终都是亏损的,我认为交易中最虚幻的就是胜率,但是大多数人追求的反而是胜率。如果说股票市场最终的投资结果90%的人将亏损收场话,那我相信这90%的人胜率大多数都为超过50%甚至更高,那么如果我们想最终战胜市场的话,我们的有效投资策略是不是应该是胜率低于50%的呢?
5. 自定义评分类的实现
上面的评分全部都是使用abupy中内置的WrsmScorer做为评分类,其从四个维度:胜率、sharpe、投资回报、最大回撤综合评定策略的分数,通过调整权重来达到各种评定效果,但是如果用户想要从其它的维度来综合评分的话就需要自定义评分类。
上一节中最后示例扩展自定义度量类中编写了MetricsDemo度量类,它扩展了AbuMetricsBase度量类,添加了交易手续费相关度量值,以及可视化方法
,下面的示例编写评分类将使用手续费做为一个度量维度对grid结果进行评分,代码如下所示
Step20: 上面的代码DemoScorer即实现了自定义评分类:
自定义评分类需要继承AbuBaseScorer
自定义评分类需要实现_init_self_begin,声明自己要度量metrics中的那些度量值
自定义评分类需要实现_init_self_end,在这里将需要反转结果的度量值进行反转
本例_init_self_end中使用:
self.score_pd['commission'] = -self.score_pd['commission']
将手续费数值进行反转,因为本例度量的标准是手续费的花销越小代表结果越好,所以需要在_init_self_end中将手续费这一列变成负数。
下面构建DemoScorer,注意传递了关键字参数metrics_class,使用MetricsDemo,默认不传递metrics_class将使用AbuMetricsBase做为度量类提供度量值,但是DemoScorer中需要使用metrics.commission_sum,所以这里必须使用MetricsDemo,代码如下所示:
备注:已将MetricsDemo做为abupy内置策略示例因子在项目中,所以本节不重复编写,直接从abupy中import,如下所示
Step21: 上面代码使用DemoScorer对grid的结果进行评分,从score_pd.tail()中最后一行可以看到commission=-1179.97, 即手续费总开销为1179.97的score_commission评分结果在手续费评分结果中是满分1 | Python Code:
# 基础库导入
from __future__ import print_function
from __future__ import division
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import ipywidgets
import os
import sys
# 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题
sys.path.insert(0, os.path.abspath('../'))
import abupy
# 使用沙盒数据,目的是和书中一样的数据环境
abupy.env.enable_example_env_ipython()
Explanation: ABU量化系统使用文档
<center>
<img src="./image/abu_logo.png" alt="" style="vertical-align:middle;padding:10px 20px;"><font size="6" color="black"><b>第7节 寻找策略最优参数和评分</b></font>
</center>
作者: 阿布
阿布量化版权所有 未经允许 禁止转载
abu量化系统github地址 (您的star是我的动力!)
本节ipython notebook
上一节主要讲解了如何使用abupy中度量模块对回测的结果进行度量,本节将主要讲解使用grid search模块对策略参数寻找最优。
最优参数的意思是比如上一节使用的卖出因子组合使用:
sell_factors = [
{'stop_loss_n': 1.0, 'stop_win_n': 3.0,
'class': AbuFactorAtrNStop},
{'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.5},
{'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5}
]
AbuFactorAtrNStop止盈止损策略的止盈阀值是3.0,止损阀值是1.0,那么止盈参数设置成2.0或者止损阀值设置为0.5是不是回测交易效果更好呢,
AbuFactorPreAtrNStop风险控制止损pre_atr_n参数设置的是1.5,如果设置为1.0回测结果将如何,grid search模块对策略寻找最优参数就是要在给定的参数组合范畴内,寻找到策略参数最佳的设置。
首先导入abupy中本节使用的模块:
End of explanation
from abupy import AbuFactorAtrNStop, AbuFactorPreAtrNStop, AbuFactorCloseAtrNStop, AbuFactorBuyBreak
from abupy import abu, ABuFileUtil, ABuGridHelper, GridSearch, AbuBlockProgress, ABuProgress
stop_win_range = np.arange(2.0, 4.5, 0.5)
stop_loss_range = np.arange(0.5, 2, 0.5)
sell_atr_nstop_factor_grid = {
'class': [AbuFactorAtrNStop],
'stop_loss_n' : stop_loss_range,
'stop_win_n' : stop_win_range
}
print('AbuFactorAtrNStop止盈参数stop_win_n设置范围:{}'.format(stop_win_range))
print('AbuFactorAtrNStop止损参数stop_loss_n设置范围:{}'.format(stop_loss_range))
Explanation: 1. 参数取值范围
Grid Search实际上是蒙特卡洛方法的一种实现子集,它首先固定了几组参数取值范围,把无限个解问题先缩小到有限个解的问题,然后对排列组合的各个参数组合迭代进行运算,得到最优结果。
既然是在给定参数范围内寻找最优,所以首先要给定一个合理的参数范围,下面首先寻找AbuFactorAtrNStop的参数组合如下所示:
End of explanation
close_atr_range = np.arange(1.0, 4.0, 0.5)
pre_atr_range = np.arange(1.0, 3.5, 0.5)
sell_atr_pre_factor_grid = {
'class': [AbuFactorPreAtrNStop],
'pre_atr_n' : pre_atr_range
}
sell_atr_close_factor_grid = {
'class': [AbuFactorCloseAtrNStop],
'close_atr_n' : close_atr_range
}
print('暴跌保护止损参数pre_atr_n设置范围:{}'.format(pre_atr_range))
print('盈利保护止盈参数close_atr_n设置范围:{}'.format(close_atr_range))
Explanation: 之前小节构造因子对象的序列使用字典形式装载参数和class,如下所示
{'stop_loss_n': 1.0, 'stop_win_n': 3.0,
'class': AbuFactorAtrNStop},
上面sell_atr_nstop_factor_grid使用类似的方法构造字典对象,区别就是所有字典中的元素都变成可迭代的序列了。
使用类似的方式设置AbuFactorPreAtrNStop与AbuFactorCloseAtrNStop参数设置范围,如下所示:
End of explanation
sell_factors_product = ABuGridHelper.gen_factor_grid(
ABuGridHelper.K_GEN_FACTOR_PARAMS_SELL,
[sell_atr_nstop_factor_grid, sell_atr_pre_factor_grid, sell_atr_close_factor_grid], need_empty_sell=True)
print('卖出因子参数共有{}种组合方式'.format(len(sell_factors_product)))
print('卖出因子组合0: 形式为{}'.format(sell_factors_product[0]))
Explanation: 在参数参数设置范围确定了的前提下即可以开始对参数进行组合,代码如下所示:
End of explanation
buy_bk_factor_grid1 = {
'class': [AbuFactorBuyBreak],
'xd': [42]
}
buy_bk_factor_grid2 = {
'class': [AbuFactorBuyBreak],
'xd': [60]
}
buy_factors_product = ABuGridHelper.gen_factor_grid(
ABuGridHelper.K_GEN_FACTOR_PARAMS_BUY, [buy_bk_factor_grid1, buy_bk_factor_grid2])
print('买入因子参数共有{}种组合方式'.format(len(buy_factors_product)))
print('买入因子组合形式为{}'.format(buy_factors_product))
Explanation: 上述代码使用ABuGridHelper.gen_factor_grid对参数进行组合,结果共组合出477种包括不同参数的组合,不同因子的组合,也有完全不使用任何因子的组合。
相似方式使用ABuGridHelper生成不同买入参数的因子排列组合, 这里只使用42日、60日作为备选参数。读者可使用类似bk_days = np.arange(20, 130, 10)方式生成更多的买入参数,更可以自己实现其它的买入策略与AbuFactorBuyBreak一同做grid,但是在之后阶段运行Grid Search速度就会越慢。
End of explanation
print('组合因子参数数量{}'.format(len(buy_factors_product) * len(sell_factors_product) ))
Explanation: 由于只选用42d、60d为参数,所以只有三种排列组合,也就是分别为:
只使用42d突破因子
只使用60d突破因子
同时使用42d、60d突破因子
买入因子有477种组合,卖出因子有3种组合,两者再组合将有477 x 3 = 1431中因子组合
End of explanation
read_cash = 1000000
choice_symbols = ['usNOAH', 'usSFUN', 'usBIDU', 'usAAPL', 'usGOOG',
'usTSLA', 'usWUBA', 'usVIPS']
grid_search = GridSearch(read_cash, choice_symbols,
buy_factors_product=buy_factors_product,
sell_factors_product=sell_factors_product)
Explanation: 2. Grid Search寻找最优参数
下面代码使用abupy中的GridSearch类进行最优参数寻找,从GridSearch类参数可以看到除了buy_factors_product、sell_factors_product外,还有stock_pickers_product(选股因子排列组合)本例没有用到,读者可自行尝试。
End of explanation
scores = None
score_tuple_array = None
def run_grid_search():
global scores, score_tuple_array
# 运行GridSearch n_jobs=-1启动cpu个数的进程数
scores, score_tuple_array = grid_search.fit(n_jobs=-1)
# 运行完成输出的score_tuple_array可以使用dump_pickle保存在本地,以方便之后使用
ABuFileUtil.dump_pickle(score_tuple_array, '../gen/score_tuple_array')
def load_score_cache():
有本地数据score_tuple_array后,即可以从本地缓存读取score_tuple_array
global scores, score_tuple_array
with AbuBlockProgress('load score cache'):
score_tuple_array = ABuFileUtil.load_pickle('../gen/score_tuple_array')
if not hasattr(grid_search, 'best_score_tuple_grid'):
# load_pickle的grid_search没有赋予best_score_tuple_grid,这里补上
from abupy import make_scorer, WrsmScorer
scores = make_scorer(score_tuple_array, WrsmScorer)
grid_search.best_score_tuple_grid = score_tuple_array[scores.index[-1]]
print('load complete!')
def select(select):
if select == 'run gird search':
run_grid_search()
else: # load score cache
load_score_cache()
_ = ipywidgets.interact_manual(select, select=['run gird search', 'load score cache'])
Explanation: 下面开始通过fit函数开始寻找最优,第一次运行select:run gird search,然后点击run select,如果已经运行过可select:load score cache直接从缓存数据读取
备注:如果第一次运行选择run gird search下面的运行耗时大约1小时多,建议电脑空闲时运行
End of explanation
type(score_tuple_array), type(score_tuple_array[0])
Explanation: 下面使用type查看返回的score_tuple_array类型为list,score_tuple_array中的元素类型为AbuScoreTuple:
End of explanation
print('最终评分结果数量{}'.format(len(scores)))
Explanation: 上面说过组合数量477 x 3 = 1431中因子组合:
最终的评分结果也应该scores是有1431种,下面开始验证:
End of explanation
from abupy import AbuMetricsBase
best_score_tuple_grid = grid_search.best_score_tuple_grid
AbuMetricsBase.show_general(best_score_tuple_grid.orders_pd, best_score_tuple_grid.action_pd,
best_score_tuple_grid.capital, best_score_tuple_grid.benchmark)
Explanation: grid_search中保存了得到分数最高的对象best_score_tuple_grid,可以利用它直接用AbuMetricsBase可视化最优参数结果,如图:
End of explanation
from abupy import WrsmScorer
scorer = WrsmScorer(score_tuple_array)
Explanation: 3. 度量结果的评分
读者可能会有的疑问1:哪里来的分数,怎么评定的分数。
在GridSearch类 fit()函数中可以看到第二个参数score_class需要一个判分类,在fit()中最后几行使用ABuMetricsScore.make_scorer()函数将所有返回的结果score_tuple_array使用判分类WrsmScorer对结果打分数。
打分数实现的基本思路为:如果想根据sharpe值的结果来对最优参数下判断,但是sharpe值多大可以判定为100分?多大可以判断为50分呢?我们无法确定,所以将所有sharpe结果排序,由于sharpe值越大越好,所以排序结果对应分数由0至1,这样就可以得到某一个具体参数组合的sharpe值的分数。这样的话使用多个评分标准, 比如这里使用'win_rate'、 'returns'、 'sharpe'、'max_drawdown'四种,就可以分别计算出某个参数组合对应的度量指标评分,再乘以分配给它们的权重就可以得到最终结果分数。
具体请阅读GridSearch.fit,AbuBaseScorer,WrsmScorer源代码实现
如下代码我们实例化一个评分类WrsmScorer,它的参数为之前GridSearch返回的score_tuple_array对象:
End of explanation
scorer.fit_score()
scorer.score_pd.tail()
Explanation: 如下可以看到scorer中的score_pd是由评分的度量指标数值,以及这个具体数据对应项所得的分数组成:
End of explanation
# 实例化WrsmScorer,参数weights,只有第二项为1,其他都是0,
# 代表只考虑投资回报来评分
scorer = WrsmScorer(score_tuple_array, weights=[0, 1, 0, 0])
# 返回排序后的队列
scorer_returns_max = scorer.fit_score()
# 因为是倒序排序,所以index最后一个为最优参数
best_score_tuple_grid = score_tuple_array[scorer_returns_max.index[-1]]
# 由于篇幅,最优结果只打印文字信息
AbuMetricsBase.show_general(best_score_tuple_grid.orders_pd,
best_score_tuple_grid.action_pd,
best_score_tuple_grid.capital,
best_score_tuple_grid.benchmark,
only_info=True)
Explanation: 由于AbuBaseScorer 中fit_score()函数的实现只是对score_pd的'score'项进行排序后返回score,这样最终的结果为分数及对应score_tuple_array的序列号,从上面输出可以看出665为最优参数序号。
4. 不同权重的评分
读者可能会有的疑问2:为什么从度量可视化看到的这个最优的投资回报还没有上一节的那个回测高?
因为由于默认的WrsmScorer使用:胜率、sharpe、投资回报、最大回撤这四个因素,综合评定策略的分数,并且类GridSearch默认为四项等权重评分,我们下面可以仍然使用WrsmScorer但是通过调整权重来达到各种评定效果。
End of explanation
best_score_tuple_grid.buy_factors, best_score_tuple_grid.sell_factors
Explanation: 可以看到只考虑投资回报来评分的话,上面策略收益: 50.44%为最高。
下面通过best_score_tuple_grid.buy_factors,best_score_tuple_grid.sell_factors看一下这个收益的买入因子参数、卖出因子参数,如下所示,可以发现它的因子参数组合与我在上一节开始使用的参数是一摸一样的。
End of explanation
# 只有第一项为1,其他都是0代表只考虑胜率来评分
scorer = WrsmScorer(score_tuple_array, weights=[1, 0, 0, 0])
# 返回按照评分排序后的队列
scorer_returns_max = scorer.fit_score()
# index[-1]为最优参数序号
best_score_tuple_grid = score_tuple_array[scorer_returns_max.index[-1]]
AbuMetricsBase.show_general(best_score_tuple_grid.orders_pd,
best_score_tuple_grid.action_pd,
best_score_tuple_grid.capital,
best_score_tuple_grid.benchmark,
only_info=False)
# 最后打印出只考虑胜率下最优结果使用的买入策略和卖出策略
best_score_tuple_grid.buy_factors, best_score_tuple_grid.sell_factors
Explanation: 下面看一下只考虑胜率来评分的结果,从结果可以看到虽然胜率达到了85%以上,但是收益并不高:
End of explanation
from abupy import AbuBaseScorer
class DemoScorer(AbuBaseScorer):
def _init_self_begin(self, *arg, **kwargs):
胜率,策略收益,手续费组成select_score_func
self.select_score_func = lambda metrics: [metrics.win_rate, metrics.algorithm_period_returns,
metrics.commission_sum]
self.columns_name = ['win_rate', 'returns', 'commission']
self.weights_cnt = len(self.columns_name)
def _init_self_end(self, *arg, **kwargs):
_init_self_end这里一般的任务是将score_pd中需要反转的反转,默认是数据越大越好,有些是越小越好,
类似make_scorer(xxx, greater_is_better=True)中的参数greater_is_better的作用:
sign = 1 if greater_is_better else -1
self.score_pd['commission'] = -self.score_pd['commission']
Explanation: 从输出可以看到买入策略只使用60天突破买入作为买入信号,卖出只以保护利润的止盈ABuFactorCloseAtrNStop发出卖出信号,其实这种策略就是没有止损的策略。很像大多数普通交易者的交易模式,亏损了的交易不卖出,持有直到可以再次盈利为。这样的方式投资者的胜率非常高,我之前看过几个朋友的交易账户,发现他们交易的胜率非常高,但他们的账户最终都是亏损的,我认为交易中最虚幻的就是胜率,但是大多数人追求的反而是胜率。如果说股票市场最终的投资结果90%的人将亏损收场话,那我相信这90%的人胜率大多数都为超过50%甚至更高,那么如果我们想最终战胜市场的话,我们的有效投资策略是不是应该是胜率低于50%的呢?
5. 自定义评分类的实现
上面的评分全部都是使用abupy中内置的WrsmScorer做为评分类,其从四个维度:胜率、sharpe、投资回报、最大回撤综合评定策略的分数,通过调整权重来达到各种评定效果,但是如果用户想要从其它的维度来综合评分的话就需要自定义评分类。
上一节中最后示例扩展自定义度量类中编写了MetricsDemo度量类,它扩展了AbuMetricsBase度量类,添加了交易手续费相关度量值,以及可视化方法
,下面的示例编写评分类将使用手续费做为一个度量维度对grid结果进行评分,代码如下所示:
End of explanation
from abupy import MetricsDemo
scorer = DemoScorer(score_tuple_array, metrics_class=MetricsDemo)
# 返回按照评分排序后的队列
scorer_returns_max = scorer.fit_score()
scorer.score_pd.sort_values(by='score_commission').tail()
Explanation: 上面的代码DemoScorer即实现了自定义评分类:
自定义评分类需要继承AbuBaseScorer
自定义评分类需要实现_init_self_begin,声明自己要度量metrics中的那些度量值
自定义评分类需要实现_init_self_end,在这里将需要反转结果的度量值进行反转
本例_init_self_end中使用:
self.score_pd['commission'] = -self.score_pd['commission']
将手续费数值进行反转,因为本例度量的标准是手续费的花销越小代表结果越好,所以需要在_init_self_end中将手续费这一列变成负数。
下面构建DemoScorer,注意传递了关键字参数metrics_class,使用MetricsDemo,默认不传递metrics_class将使用AbuMetricsBase做为度量类提供度量值,但是DemoScorer中需要使用metrics.commission_sum,所以这里必须使用MetricsDemo,代码如下所示:
备注:已将MetricsDemo做为abupy内置策略示例因子在项目中,所以本节不重复编写,直接从abupy中import,如下所示
End of explanation
scorer.score_pd.sort_values(by='score_commission').head()
Explanation: 上面代码使用DemoScorer对grid的结果进行评分,从score_pd.tail()中最后一行可以看到commission=-1179.97, 即手续费总开销为1179.97的score_commission评分结果在手续费评分结果中是满分1
End of explanation |
7,923 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recurrent Neural Networks (RNN) with Keras
Learning Objectives
Add built-in RNN layers.
Build bidirectional RNNs.
Using CuDNN kernels when available.
Build a RNN model with nested input/output.
Introduction
Recurrent neural networks (RNN) are a class of neural networks that is powerful for
modeling sequence data such as time series or natural language.
Schematically, a RNN layer uses a for loop to iterate over the timesteps of a
sequence, while maintaining an internal state that encodes information about the
timesteps it has seen so far.
The Keras RNN API is designed with a focus on
Step1: Built-in RNN layers
Step2: Built-in RNNs support a number of useful features
Step3: In addition, a RNN layer can return its final internal state(s). The returned states
can be used to resume the RNN execution later, or
to initialize another RNN.
This setting is commonly used in the
encoder-decoder sequence-to-sequence model, where the encoder final state is used as
the initial state of the decoder.
To configure a RNN layer to return its internal state, set the return_state parameter
to True when creating the layer. Note that LSTM has 2 state tensors, but GRU
only has one.
To configure the initial state of the layer, just call the layer with additional
keyword argument initial_state.
Note that the shape of the state needs to match the unit size of the layer, like in the
example below.
Step4: RNN layers and RNN cells
In addition to the built-in RNN layers, the RNN API also provides cell-level APIs.
Unlike RNN layers, which processes whole batches of input sequences, the RNN cell only
processes a single timestep.
The cell is the inside of the for loop of a RNN layer. Wrapping a cell inside a
keras.layers.RNN layer gives you a layer capable of processing batches of
sequences, e.g. RNN(LSTMCell(10)).
Mathematically, RNN(LSTMCell(10)) produces the same result as LSTM(10). In fact,
the implementation of this layer in TF v1.x was just creating the corresponding RNN
cell and wrapping it in a RNN layer. However using the built-in GRU and LSTM
layers enable the use of CuDNN and you may see better performance.
There are three built-in RNN cells, each of them corresponding to the matching RNN
layer.
keras.layers.SimpleRNNCell corresponds to the SimpleRNN layer.
keras.layers.GRUCell corresponds to the GRU layer.
keras.layers.LSTMCell corresponds to the LSTM layer.
The cell abstraction, together with the generic keras.layers.RNN class, make it
very easy to implement custom RNN architectures for your research.
Cross-batch statefulness
When processing very long sequences (possibly infinite), you may want to use the
pattern of cross-batch statefulness.
Normally, the internal state of a RNN layer is reset every time it sees a new batch
(i.e. every sample seen by the layer is assumed to be independent of the past). The
layer will only maintain a state while processing a given sample.
If you have very long sequences though, it is useful to break them into shorter
sequences, and to feed these shorter sequences sequentially into a RNN layer without
resetting the layer's state. That way, the layer can retain information about the
entirety of the sequence, even though it's only seeing one sub-sequence at a time.
You can do this by setting stateful=True in the constructor.
If you have a sequence s = [t0, t1, ... t1546, t1547], you would split it into e.g.
s1 = [t0, t1, ... t100]
s2 = [t101, ... t201]
...
s16 = [t1501, ... t1547]
Then you would process it via
Step5: RNN State Reuse
<a id="rnn_state_reuse"></a>
The recorded states of the RNN layer are not included in the layer.weights(). If you
would like to reuse the state from a RNN layer, you can retrieve the states value by
layer.states and use it as the
initial state for a new layer via the Keras functional API like new_layer(inputs,
initial_state=layer.states), or model subclassing.
Please also note that sequential model might not be used in this case since it only
supports layers with single input and output, the extra input of initial state makes
it impossible to use here.
Step6: Bidirectional RNNs
For sequences other than time series (e.g. text), it is often the case that a RNN model
can perform better if it not only processes sequence from start to end, but also
backwards. For example, to predict the next word in a sentence, it is often useful to
have the context around the word, not only just the words that come before it.
Keras provides an easy API for you to build such bidirectional RNNs
Step7: Under the hood, Bidirectional will copy the RNN layer passed in, and flip the
go_backwards field of the newly copied layer, so that it will process the inputs in
reverse order.
The output of the Bidirectional RNN will be, by default, the concatenation of the forward layer
output and the backward layer output. If you need a different merging behavior, e.g.
concatenation, change the merge_mode parameter in the Bidirectional wrapper
constructor. For more details about Bidirectional, please check
the API docs.
Performance optimization and CuDNN kernels
In TensorFlow 2.0, the built-in LSTM and GRU layers have been updated to leverage CuDNN
kernels by default when a GPU is available. With this change, the prior
keras.layers.CuDNNLSTM/CuDNNGRU layers have been deprecated, and you can build your
model without worrying about the hardware it will run on.
Since the CuDNN kernel is built with certain assumptions, this means the layer will
not be able to use the CuDNN kernel if you change the defaults of the built-in LSTM or
GRU layers. E.g.
Step8: Let's load the MNIST dataset
Step9: Let's create a model instance and train it.
We choose sparse_categorical_crossentropy as the loss function for the model. The
output of the model has shape of [batch_size, 10]. The target for the model is an
integer vector, each of the integer is in the range of 0 to 9.
Step10: Now, let's compare to a model that does not use the CuDNN kernel
Step11: When running on a machine with a NVIDIA GPU and CuDNN installed,
the model built with CuDNN is much faster to train compared to the
model that uses the regular TensorFlow kernel.
The same CuDNN-enabled model can also be used to run inference in a CPU-only
environment. The tf.device annotation below is just forcing the device placement.
The model will run on CPU by default if no GPU is available.
You simply don't have to worry about the hardware you're running on anymore. Isn't that
pretty cool?
Step12: RNNs with list/dict inputs, or nested inputs
Nested structures allow implementers to include more information within a single
timestep. For example, a video frame could have audio and video input at the same
time. The data shape in this case could be
Step13: Build a RNN model with nested input/output
Let's build a Keras model that uses a keras.layers.RNN layer and the custom cell
we just defined.
Step14: Train the model with randomly generated data
Since there isn't a good candidate dataset for this model, we use random Numpy data for
demonstration. | Python Code:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
Explanation: Recurrent Neural Networks (RNN) with Keras
Learning Objectives
Add built-in RNN layers.
Build bidirectional RNNs.
Using CuDNN kernels when available.
Build a RNN model with nested input/output.
Introduction
Recurrent neural networks (RNN) are a class of neural networks that is powerful for
modeling sequence data such as time series or natural language.
Schematically, a RNN layer uses a for loop to iterate over the timesteps of a
sequence, while maintaining an internal state that encodes information about the
timesteps it has seen so far.
The Keras RNN API is designed with a focus on:
Ease of use: the built-in keras.layers.RNN, keras.layers.LSTM,
keras.layers.GRU layers enable you to quickly build recurrent models without
having to make difficult configuration choices.
Ease of customization: You can also define your own RNN cell layer (the inner
part of the for loop) with custom behavior, and use it with the generic
keras.layers.RNN layer (the for loop itself). This allows you to quickly
prototype different research ideas in a flexible way with minimal code.
Each learning objective will correspond to a #TODO in the student lab notebook -- try to complete that notebook first before reviewing this solution notebook.
Setup
End of explanation
model = keras.Sequential()
# Add an Embedding layer expecting input vocab of size 1000, and
# output embedding dimension of size 64.
model.add(layers.Embedding(input_dim=1000, output_dim=64))
# Add a LSTM layer with 128 internal units.
# TODO
model.add(layers.LSTM(128))
# Add a Dense layer with 10 units.
# TODO
model.add(layers.Dense(10))
model.summary()
Explanation: Built-in RNN layers: a simple example
There are three built-in RNN layers in Keras:
keras.layers.SimpleRNN, a fully-connected RNN where the output from previous
timestep is to be fed to next timestep.
keras.layers.GRU, first proposed in
Cho et al., 2014.
keras.layers.LSTM, first proposed in
Hochreiter & Schmidhuber, 1997.
In early 2015, Keras had the first reusable open-source Python implementations of LSTM
and GRU.
Here is a simple example of a Sequential model that processes sequences of integers,
embeds each integer into a 64-dimensional vector, then processes the sequence of
vectors using a LSTM layer.
End of explanation
model = keras.Sequential()
model.add(layers.Embedding(input_dim=1000, output_dim=64))
# The output of GRU will be a 3D tensor of shape (batch_size, timesteps, 256)
model.add(layers.GRU(256, return_sequences=True))
# The output of SimpleRNN will be a 2D tensor of shape (batch_size, 128)
model.add(layers.SimpleRNN(128))
model.add(layers.Dense(10))
model.summary()
Explanation: Built-in RNNs support a number of useful features:
Recurrent dropout, via the dropout and recurrent_dropout arguments
Ability to process an input sequence in reverse, via the go_backwards argument
Loop unrolling (which can lead to a large speedup when processing short sequences on
CPU), via the unroll argument
...and more.
For more information, see the
RNN API documentation.
Outputs and states
By default, the output of a RNN layer contains a single vector per sample. This vector
is the RNN cell output corresponding to the last timestep, containing information
about the entire input sequence. The shape of this output is (batch_size, units)
where units corresponds to the units argument passed to the layer's constructor.
A RNN layer can also return the entire sequence of outputs for each sample (one vector
per timestep per sample), if you set return_sequences=True. The shape of this output
is (batch_size, timesteps, units).
End of explanation
encoder_vocab = 1000
decoder_vocab = 2000
encoder_input = layers.Input(shape=(None,))
encoder_embedded = layers.Embedding(input_dim=encoder_vocab, output_dim=64)(
encoder_input
)
# Return states in addition to output
output, state_h, state_c = layers.LSTM(64, return_state=True, name="encoder")(
encoder_embedded
)
encoder_state = [state_h, state_c]
decoder_input = layers.Input(shape=(None,))
decoder_embedded = layers.Embedding(input_dim=decoder_vocab, output_dim=64)(
decoder_input
)
# Pass the 2 states to a new LSTM layer, as initial state
decoder_output = layers.LSTM(64, name="decoder")(
decoder_embedded, initial_state=encoder_state
)
output = layers.Dense(10)(decoder_output)
model = keras.Model([encoder_input, decoder_input], output)
model.summary()
Explanation: In addition, a RNN layer can return its final internal state(s). The returned states
can be used to resume the RNN execution later, or
to initialize another RNN.
This setting is commonly used in the
encoder-decoder sequence-to-sequence model, where the encoder final state is used as
the initial state of the decoder.
To configure a RNN layer to return its internal state, set the return_state parameter
to True when creating the layer. Note that LSTM has 2 state tensors, but GRU
only has one.
To configure the initial state of the layer, just call the layer with additional
keyword argument initial_state.
Note that the shape of the state needs to match the unit size of the layer, like in the
example below.
End of explanation
paragraph1 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph2 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph3 = np.random.random((20, 10, 50)).astype(np.float32)
lstm_layer = layers.LSTM(64, stateful=True)
output = lstm_layer(paragraph1)
output = lstm_layer(paragraph2)
output = lstm_layer(paragraph3)
# reset_states() will reset the cached state to the original initial_state.
# If no initial_state was provided, zero-states will be used by default.
# TODO
lstm_layer.reset_states()
Explanation: RNN layers and RNN cells
In addition to the built-in RNN layers, the RNN API also provides cell-level APIs.
Unlike RNN layers, which processes whole batches of input sequences, the RNN cell only
processes a single timestep.
The cell is the inside of the for loop of a RNN layer. Wrapping a cell inside a
keras.layers.RNN layer gives you a layer capable of processing batches of
sequences, e.g. RNN(LSTMCell(10)).
Mathematically, RNN(LSTMCell(10)) produces the same result as LSTM(10). In fact,
the implementation of this layer in TF v1.x was just creating the corresponding RNN
cell and wrapping it in a RNN layer. However using the built-in GRU and LSTM
layers enable the use of CuDNN and you may see better performance.
There are three built-in RNN cells, each of them corresponding to the matching RNN
layer.
keras.layers.SimpleRNNCell corresponds to the SimpleRNN layer.
keras.layers.GRUCell corresponds to the GRU layer.
keras.layers.LSTMCell corresponds to the LSTM layer.
The cell abstraction, together with the generic keras.layers.RNN class, make it
very easy to implement custom RNN architectures for your research.
Cross-batch statefulness
When processing very long sequences (possibly infinite), you may want to use the
pattern of cross-batch statefulness.
Normally, the internal state of a RNN layer is reset every time it sees a new batch
(i.e. every sample seen by the layer is assumed to be independent of the past). The
layer will only maintain a state while processing a given sample.
If you have very long sequences though, it is useful to break them into shorter
sequences, and to feed these shorter sequences sequentially into a RNN layer without
resetting the layer's state. That way, the layer can retain information about the
entirety of the sequence, even though it's only seeing one sub-sequence at a time.
You can do this by setting stateful=True in the constructor.
If you have a sequence s = [t0, t1, ... t1546, t1547], you would split it into e.g.
s1 = [t0, t1, ... t100]
s2 = [t101, ... t201]
...
s16 = [t1501, ... t1547]
Then you would process it via:
python
lstm_layer = layers.LSTM(64, stateful=True)
for s in sub_sequences:
output = lstm_layer(s)
When you want to clear the state, you can use layer.reset_states().
Note: In this setup, sample i in a given batch is assumed to be the continuation of
sample i in the previous batch. This means that all batches should contain the same
number of samples (batch size). E.g. if a batch contains [sequence_A_from_t0_to_t100,
sequence_B_from_t0_to_t100], the next batch should contain
[sequence_A_from_t101_to_t200, sequence_B_from_t101_to_t200].
Here is a complete example:
End of explanation
paragraph1 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph2 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph3 = np.random.random((20, 10, 50)).astype(np.float32)
lstm_layer = layers.LSTM(64, stateful=True)
output = lstm_layer(paragraph1)
output = lstm_layer(paragraph2)
existing_state = lstm_layer.states
new_lstm_layer = layers.LSTM(64)
new_output = new_lstm_layer(paragraph3, initial_state=existing_state)
Explanation: RNN State Reuse
<a id="rnn_state_reuse"></a>
The recorded states of the RNN layer are not included in the layer.weights(). If you
would like to reuse the state from a RNN layer, you can retrieve the states value by
layer.states and use it as the
initial state for a new layer via the Keras functional API like new_layer(inputs,
initial_state=layer.states), or model subclassing.
Please also note that sequential model might not be used in this case since it only
supports layers with single input and output, the extra input of initial state makes
it impossible to use here.
End of explanation
model = keras.Sequential()
# Add Bidirectional layers
# TODO
model.add(
layers.Bidirectional(layers.LSTM(64, return_sequences=True), input_shape=(5, 10))
)
model.add(layers.Bidirectional(layers.LSTM(32)))
model.add(layers.Dense(10))
model.summary()
Explanation: Bidirectional RNNs
For sequences other than time series (e.g. text), it is often the case that a RNN model
can perform better if it not only processes sequence from start to end, but also
backwards. For example, to predict the next word in a sentence, it is often useful to
have the context around the word, not only just the words that come before it.
Keras provides an easy API for you to build such bidirectional RNNs: the
keras.layers.Bidirectional wrapper.
End of explanation
batch_size = 64
# Each MNIST image batch is a tensor of shape (batch_size, 28, 28).
# Each input sequence will be of size (28, 28) (height is treated like time).
input_dim = 28
units = 64
output_size = 10 # labels are from 0 to 9
# Build the RNN model
def build_model(allow_cudnn_kernel=True):
# CuDNN is only available at the layer level, and not at the cell level.
# This means `LSTM(units)` will use the CuDNN kernel,
# while RNN(LSTMCell(units)) will run on non-CuDNN kernel.
if allow_cudnn_kernel:
# The LSTM layer with default options uses CuDNN.
lstm_layer = keras.layers.LSTM(units, input_shape=(None, input_dim))
else:
# Wrapping a LSTMCell in a RNN layer will not use CuDNN.
lstm_layer = keras.layers.RNN(
keras.layers.LSTMCell(units), input_shape=(None, input_dim)
)
model = keras.models.Sequential(
[
lstm_layer,
keras.layers.BatchNormalization(),
keras.layers.Dense(output_size),
]
)
return model
Explanation: Under the hood, Bidirectional will copy the RNN layer passed in, and flip the
go_backwards field of the newly copied layer, so that it will process the inputs in
reverse order.
The output of the Bidirectional RNN will be, by default, the concatenation of the forward layer
output and the backward layer output. If you need a different merging behavior, e.g.
concatenation, change the merge_mode parameter in the Bidirectional wrapper
constructor. For more details about Bidirectional, please check
the API docs.
Performance optimization and CuDNN kernels
In TensorFlow 2.0, the built-in LSTM and GRU layers have been updated to leverage CuDNN
kernels by default when a GPU is available. With this change, the prior
keras.layers.CuDNNLSTM/CuDNNGRU layers have been deprecated, and you can build your
model without worrying about the hardware it will run on.
Since the CuDNN kernel is built with certain assumptions, this means the layer will
not be able to use the CuDNN kernel if you change the defaults of the built-in LSTM or
GRU layers. E.g.:
Changing the activation function from tanh to something else.
Changing the recurrent_activation function from sigmoid to something else.
Using recurrent_dropout > 0.
Setting unroll to True, which forces LSTM/GRU to decompose the inner
tf.while_loop into an unrolled for loop.
Setting use_bias to False.
Using masking when the input data is not strictly right padded (if the mask
corresponds to strictly right padded data, CuDNN can still be used. This is the most
common case).
For the detailed list of constraints, please see the documentation for the
LSTM and
GRU layers.
Using CuDNN kernels when available
Let's build a simple LSTM model to demonstrate the performance difference.
We'll use as input sequences the sequence of rows of MNIST digits (treating each row of
pixels as a timestep), and we'll predict the digit's label.
End of explanation
mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
sample, sample_label = x_train[0], y_train[0]
Explanation: Let's load the MNIST dataset:
End of explanation
model = build_model(allow_cudnn_kernel=True)
# Compile the model
# TODO
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer="sgd",
metrics=["accuracy"],
)
model.fit(
x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1
)
Explanation: Let's create a model instance and train it.
We choose sparse_categorical_crossentropy as the loss function for the model. The
output of the model has shape of [batch_size, 10]. The target for the model is an
integer vector, each of the integer is in the range of 0 to 9.
End of explanation
noncudnn_model = build_model(allow_cudnn_kernel=False)
noncudnn_model.set_weights(model.get_weights())
noncudnn_model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer="sgd",
metrics=["accuracy"],
)
noncudnn_model.fit(
x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1
)
Explanation: Now, let's compare to a model that does not use the CuDNN kernel:
End of explanation
import matplotlib.pyplot as plt
with tf.device("CPU:0"):
cpu_model = build_model(allow_cudnn_kernel=True)
cpu_model.set_weights(model.get_weights())
result = tf.argmax(cpu_model.predict_on_batch(tf.expand_dims(sample, 0)), axis=1)
print(
"Predicted result is: %s, target result is: %s" % (result.numpy(), sample_label)
)
plt.imshow(sample, cmap=plt.get_cmap("gray"))
Explanation: When running on a machine with a NVIDIA GPU and CuDNN installed,
the model built with CuDNN is much faster to train compared to the
model that uses the regular TensorFlow kernel.
The same CuDNN-enabled model can also be used to run inference in a CPU-only
environment. The tf.device annotation below is just forcing the device placement.
The model will run on CPU by default if no GPU is available.
You simply don't have to worry about the hardware you're running on anymore. Isn't that
pretty cool?
End of explanation
class NestedCell(keras.layers.Layer):
def __init__(self, unit_1, unit_2, unit_3, **kwargs):
self.unit_1 = unit_1
self.unit_2 = unit_2
self.unit_3 = unit_3
self.state_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])]
self.output_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])]
super(NestedCell, self).__init__(**kwargs)
def build(self, input_shapes):
# expect input_shape to contain 2 items, [(batch, i1), (batch, i2, i3)]
i1 = input_shapes[0][1]
i2 = input_shapes[1][1]
i3 = input_shapes[1][2]
self.kernel_1 = self.add_weight(
shape=(i1, self.unit_1), initializer="uniform", name="kernel_1"
)
self.kernel_2_3 = self.add_weight(
shape=(i2, i3, self.unit_2, self.unit_3),
initializer="uniform",
name="kernel_2_3",
)
def call(self, inputs, states):
# inputs should be in [(batch, input_1), (batch, input_2, input_3)]
# state should be in shape [(batch, unit_1), (batch, unit_2, unit_3)]
input_1, input_2 = tf.nest.flatten(inputs)
s1, s2 = states
output_1 = tf.matmul(input_1, self.kernel_1)
output_2_3 = tf.einsum("bij,ijkl->bkl", input_2, self.kernel_2_3)
state_1 = s1 + output_1
state_2_3 = s2 + output_2_3
output = (output_1, output_2_3)
new_states = (state_1, state_2_3)
return output, new_states
def get_config(self):
return {"unit_1": self.unit_1, "unit_2": unit_2, "unit_3": self.unit_3}
Explanation: RNNs with list/dict inputs, or nested inputs
Nested structures allow implementers to include more information within a single
timestep. For example, a video frame could have audio and video input at the same
time. The data shape in this case could be:
[batch, timestep, {"video": [height, width, channel], "audio": [frequency]}]
In another example, handwriting data could have both coordinates x and y for the
current position of the pen, as well as pressure information. So the data
representation could be:
[batch, timestep, {"location": [x, y], "pressure": [force]}]
The following code provides an example of how to build a custom RNN cell that accepts
such structured inputs.
Define a custom cell that supports nested input/output
See Making new Layers & Models via subclassing
for details on writing your own layers.
End of explanation
unit_1 = 10
unit_2 = 20
unit_3 = 30
i1 = 32
i2 = 64
i3 = 32
batch_size = 64
num_batches = 10
timestep = 50
cell = NestedCell(unit_1, unit_2, unit_3)
rnn = keras.layers.RNN(cell)
input_1 = keras.Input((None, i1))
input_2 = keras.Input((None, i2, i3))
outputs = rnn((input_1, input_2))
model = keras.models.Model([input_1, input_2], outputs)
model.compile(optimizer="adam", loss="mse", metrics=["accuracy"])
Explanation: Build a RNN model with nested input/output
Let's build a Keras model that uses a keras.layers.RNN layer and the custom cell
we just defined.
End of explanation
input_1_data = np.random.random((batch_size * num_batches, timestep, i1))
input_2_data = np.random.random((batch_size * num_batches, timestep, i2, i3))
target_1_data = np.random.random((batch_size * num_batches, unit_1))
target_2_data = np.random.random((batch_size * num_batches, unit_2, unit_3))
input_data = [input_1_data, input_2_data]
target_data = [target_1_data, target_2_data]
model.fit(input_data, target_data, batch_size=batch_size)
Explanation: Train the model with randomly generated data
Since there isn't a good candidate dataset for this model, we use random Numpy data for
demonstration.
End of explanation |
7,924 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Index - Back - Next
Widget List
Step1: Numeric widgets
There are 10 widgets distributed with IPython that are designed to display numeric values. Widgets exist for displaying integers and floats, both bounded and unbounded. The integer widgets share a similar naming scheme to their floating point counterparts. By replacing Float with Int in the widget name, you can find the Integer equivalent.
IntSlider
Step2: FloatSlider
Step3: Sliders can also be displayed vertically.
Step4: IntRangeSlider
Step5: FloatRangeSlider
Step6: IntProgress
Step7: FloatProgress
Step8: The numerical text boxes that impose some limit on the data (range, integer-only) impose that restriction when the user presses enter.
BoundedIntText
Step9: BoundedFloatText
Step10: IntText
Step11: FloatText
Step12: Boolean widgets
There are three widgets that are designed to display a boolean value.
ToggleButton
Step13: Checkbox
Step14: Valid
The valid widget provides a read-only indicator.
Step15: Selection widgets
There are several widgets that can be used to display single selection lists, and two that can be used to select multiple values. All inherit from the same base class. You can specify the enumeration of selectable options by passing a list (options are either (label, value) pairs, or simply values for which the labels are derived by calling str). You can also specify the enumeration as a dictionary, in which case the keys will be used as the item displayed in the list and the corresponding value will be used when an item is selected (in this case, since dictionaries are unordered, the displayed order of items in the widget is unspecified).
Dropdown
Step16: The following is also valid
Step17: RadioButtons
Step18: Select
Step19: SelectionSlider
Step20: SelectionRangeSlider
The value, index, and label keys are 2-tuples of the min and max values selected. The options must be nonempty.
Step21: ToggleButtons
Step22: SelectMultiple
Multiple values can be selected with <kbd>shift</kbd> and/or <kbd>ctrl</kbd> (or <kbd>command</kbd>) pressed and mouse clicks or arrow keys.
Step23: String widgets
There are several widgets that can be used to display a string value. The Text and Textarea widgets accept input. The HTML and HTMLMath widgets display a string as HTML (HTMLMath also renders math). The Label widget can be used to construct a custom control label.
Text
Step24: Textarea
Step25: Label
The Label widget is useful if you need to build a custom description next to a control using similar styling to the built-in control descriptions.
Step26: HTML
Step27: HTML Math
Step28: Image
Step29: Button
Step30: Play (Animation) widget
The Play widget is useful to perform animations by iterating on a sequence of integers with a certain speed. The value of the slider below is linked to the player.
Step31: Date picker
The date picker widget works in Chrome and IE Edge, but does not currently work in Firefox or Safari because they do not support the HTML date input field.
Step32: Color picker
Step33: Controller
The Controller allows a game controller to be used as an input device.
Step34: Container/Layout widgets
These widgets are used to hold other widgets, called children. Each has a children property that may be set either when the widget is created or later.
Box
Step35: HBox
Step36: VBox
Step37: Accordion
Step38: Tabs
In this example the children are set after the tab is created. Titles for the tabes are set in the same way they are for Accordion. | Python Code:
import ipywidgets as widgets
Explanation: Index - Back - Next
Widget List
End of explanation
widgets.IntSlider(
value=7,
min=0,
max=10,
step=1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='i'
)
Explanation: Numeric widgets
There are 10 widgets distributed with IPython that are designed to display numeric values. Widgets exist for displaying integers and floats, both bounded and unbounded. The integer widgets share a similar naming scheme to their floating point counterparts. By replacing Float with Int in the widget name, you can find the Integer equivalent.
IntSlider
End of explanation
widgets.FloatSlider(
value=7.5,
min=0,
max=10.0,
step=0.1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.1f',
)
Explanation: FloatSlider
End of explanation
widgets.FloatSlider(
value=7.5,
min=0,
max=10.0,
step=0.1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='vertical',
readout=True,
readout_format='.1f',
)
Explanation: Sliders can also be displayed vertically.
End of explanation
widgets.IntRangeSlider(
value=[5, 7],
min=0,
max=10,
step=1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='i',
)
Explanation: IntRangeSlider
End of explanation
widgets.FloatRangeSlider(
value=[5, 7.5],
min=0,
max=10.0,
step=0.1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='i',
)
Explanation: FloatRangeSlider
End of explanation
widgets.IntProgress(
value=7,
min=0,
max=10,
step=1,
description='Loading:',
bar_style='', # 'success', 'info', 'warning', 'danger' or ''
orientation='horizontal'
)
Explanation: IntProgress
End of explanation
widgets.FloatProgress(
value=7.5,
min=0,
max=10.0,
step=0.1,
description='Loading:',
bar_style='info',
orientation='horizontal'
)
Explanation: FloatProgress
End of explanation
widgets.BoundedIntText(
value=7,
min=0,
max=10,
step=1,
description='Text:',
disabled=False
)
Explanation: The numerical text boxes that impose some limit on the data (range, integer-only) impose that restriction when the user presses enter.
BoundedIntText
End of explanation
widgets.BoundedFloatText(
value=7.5,
min=0,
max=10.0,
step=0.1,
description='Text:',
disabled=False
)
Explanation: BoundedFloatText
End of explanation
widgets.IntText(
value=7,
description='Any:',
disabled=False
)
Explanation: IntText
End of explanation
widgets.FloatText(
value=7.5,
description='Any:',
disabled=False
)
Explanation: FloatText
End of explanation
widgets.ToggleButton(
value=False,
description='Click me',
disabled=False,
button_style='', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Description',
icon='check'
)
Explanation: Boolean widgets
There are three widgets that are designed to display a boolean value.
ToggleButton
End of explanation
widgets.Checkbox(
value=False,
description='Check me',
disabled=False
)
Explanation: Checkbox
End of explanation
widgets.Valid(
value=False,
description='Valid!',
disabled=False
)
Explanation: Valid
The valid widget provides a read-only indicator.
End of explanation
widgets.Dropdown(
options=['1', '2', '3'],
value='2',
description='Number:',
disabled=False,
)
Explanation: Selection widgets
There are several widgets that can be used to display single selection lists, and two that can be used to select multiple values. All inherit from the same base class. You can specify the enumeration of selectable options by passing a list (options are either (label, value) pairs, or simply values for which the labels are derived by calling str). You can also specify the enumeration as a dictionary, in which case the keys will be used as the item displayed in the list and the corresponding value will be used when an item is selected (in this case, since dictionaries are unordered, the displayed order of items in the widget is unspecified).
Dropdown
End of explanation
widgets.Dropdown(
options={'One': 1, 'Two': 2, 'Three': 3},
value=2,
description='Number:',
)
Explanation: The following is also valid:
End of explanation
widgets.RadioButtons(
options=['pepperoni', 'pineapple', 'anchovies'],
# value='pineapple',
description='Pizza topping:',
disabled=False
)
Explanation: RadioButtons
End of explanation
widgets.Select(
options=['Linux', 'Windows', 'OSX'],
value='OSX',
# rows=10,
description='OS:',
disabled=False
)
Explanation: Select
End of explanation
widgets.SelectionSlider(
options=['scrambled', 'sunny side up', 'poached', 'over easy'],
value='sunny side up',
description='I like my eggs ...',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True
)
Explanation: SelectionSlider
End of explanation
import datetime
dates = [datetime.date(2015,i,1) for i in range(1,13)]
options = [(i.strftime('%b'), i) for i in dates]
widgets.SelectionRangeSlider(
options=options,
index=(0,11),
description='Months (2015)'
)
Explanation: SelectionRangeSlider
The value, index, and label keys are 2-tuples of the min and max values selected. The options must be nonempty.
End of explanation
widgets.ToggleButtons(
options=['Slow', 'Regular', 'Fast'],
description='Speed:',
disabled=False,
button_style='', # 'success', 'info', 'warning', 'danger' or ''
tooltips=['Description of slow', 'Description of regular', 'Description of fast'],
# icons=['check'] * 3
)
Explanation: ToggleButtons
End of explanation
widgets.SelectMultiple(
options=['Apples', 'Oranges', 'Pears'],
value=['Oranges'],
#rows=10,
description='Fruits',
disabled=False
)
Explanation: SelectMultiple
Multiple values can be selected with <kbd>shift</kbd> and/or <kbd>ctrl</kbd> (or <kbd>command</kbd>) pressed and mouse clicks or arrow keys.
End of explanation
widgets.Text(
value='Hello World',
placeholder='Type something',
description='String:',
disabled=False
)
Explanation: String widgets
There are several widgets that can be used to display a string value. The Text and Textarea widgets accept input. The HTML and HTMLMath widgets display a string as HTML (HTMLMath also renders math). The Label widget can be used to construct a custom control label.
Text
End of explanation
widgets.Textarea(
value='Hello World',
placeholder='Type something',
description='String:',
disabled=False
)
Explanation: Textarea
End of explanation
widgets.HBox([widgets.Label(value="The $m$ in $E=mc^2$:"), widgets.FloatSlider()])
Explanation: Label
The Label widget is useful if you need to build a custom description next to a control using similar styling to the built-in control descriptions.
End of explanation
widgets.HTML(
value="Hello <b>World</b>",
placeholder='Some HTML',
description='Some HTML',
disabled=False
)
Explanation: HTML
End of explanation
widgets.HTMLMath(
value=r"Some math and <i>HTML</i>: \(x^2\) and $$\frac{x+1}{x-1}$$",
placeholder='Some HTML',
description='Some HTML',
disabled=False
)
Explanation: HTML Math
End of explanation
file = open("images/WidgetArch.png", "rb")
image = file.read()
widgets.Image(
value=image,
format='png',
width=300,
height=400,
)
Explanation: Image
End of explanation
widgets.Button(
description='Click me',
disabled=False,
button_style='', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Click me',
icon='check'
)
Explanation: Button
End of explanation
play = widgets.Play(
# interval=10,
value=50,
min=0,
max=100,
step=1,
description="Press play",
disabled=False
)
slider = widgets.IntSlider()
widgets.jslink((play, 'value'), (slider, 'value'))
widgets.HBox([play, slider])
Explanation: Play (Animation) widget
The Play widget is useful to perform animations by iterating on a sequence of integers with a certain speed. The value of the slider below is linked to the player.
End of explanation
widgets.DatePicker(
description='Pick a Date'
)
Explanation: Date picker
The date picker widget works in Chrome and IE Edge, but does not currently work in Firefox or Safari because they do not support the HTML date input field.
End of explanation
widgets.ColorPicker(
concise=False,
description='Pick a color',
value='blue'
)
Explanation: Color picker
End of explanation
widgets.Controller(
index=0,
)
Explanation: Controller
The Controller allows a game controller to be used as an input device.
End of explanation
items = [widgets.Label(str(i)) for i in range(4)]
widgets.Box(items)
Explanation: Container/Layout widgets
These widgets are used to hold other widgets, called children. Each has a children property that may be set either when the widget is created or later.
Box
End of explanation
items = [widgets.Label(str(i)) for i in range(4)]
widgets.HBox(items)
Explanation: HBox
End of explanation
items = [widgets.Label(str(i)) for i in range(4)]
left_box = widgets.VBox([items[0], items[1]])
right_box = widgets.VBox([items[2], items[3]])
widgets.HBox([left_box, right_box])
Explanation: VBox
End of explanation
accordion = widgets.Accordion(children=[widgets.IntSlider(), widgets.Text()])
accordion.set_title(0, 'Slider')
accordion.set_title(1, 'Text')
accordion
Explanation: Accordion
End of explanation
tab_contents = ['P0', 'P1', 'P2', 'P3', 'P4']
children = [widgets.Text(description=name) for name in tab_contents]
tab = widgets.Tab()
tab.children = children
for i in range(len(children)):
tab.set_title(i, str(i))
tab
Explanation: Tabs
In this example the children are set after the tab is created. Titles for the tabes are set in the same way they are for Accordion.
End of explanation |
7,925 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quandl
Step1: The data goes all the way back to 1947 and is updated quarterly.
Blaze provides us with the first 10 rows of the data for display. Just to confirm, let's just count the number of rows in the Blaze expression
Step2: Let's go plot it for fun. This data set is definitely small enough to just put right into a Pandas DataFrame | Python Code:
# import the dataset
from quantopian.interactive.data.quandl import fred_gdpdef
# Since this data is public domain and provided by Quandl for free, there is no _free version of this
# data set, as found in the premium sets. This import gets you the entirety of this data set.
# import data operations
from odo import odo
# import other libraries we will use
import pandas as pd
import matplotlib.pyplot as plt
fred_gdpdef.sort('asof_date')
Explanation: Quandl: US GDP, Implicit Price Deflator
In this notebook, we'll take a look at data set , available on Quantopian. This dataset spans from 1947 through the current day. It contains the value for the United States GDP, using the implicit price deflator by the US Federal Reserve via the FRED data initiative. We access this data via the API provided by Quandl. More details on this dataset can be found on Quandl's website.
Blaze
Before we dig into the data, we want to tell you about how you generally access Quantopian partner data sets. These datasets are available using the Blaze library. Blaze provides the Quantopian user with a convenient interface to access very large datasets.
Some of these sets (though not this one) are many millions of records. Bringing that data directly into Quantopian Research directly just is not viable. So Blaze allows us to provide a simple querying interface and shift the burden over to the server side.
To learn more about using Blaze and generally accessing Quantopian partner data, clone this tutorial notebook.
With preamble in place, let's get started:
End of explanation
fred_gdpdef.count()
Explanation: The data goes all the way back to 1947 and is updated quarterly.
Blaze provides us with the first 10 rows of the data for display. Just to confirm, let's just count the number of rows in the Blaze expression:
End of explanation
gdpdef_df = odo(fred_gdpdef, pd.DataFrame)
gdpdef_df.plot(x='asof_date', y='value')
plt.xlabel("As Of Date (asof_date)")
plt.ylabel("GDP Rate")
plt.title("US GDP, Implicit Price Deflator")
plt.legend().set_visible(False)
Explanation: Let's go plot it for fun. This data set is definitely small enough to just put right into a Pandas DataFrame
End of explanation |
7,926 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
End-To-End Example
Step1: First we need to find the latitude and longitude of Syracuse, then estimate the appropriate zoom level...
Step2: We get the data from the RoadsChallange github account
Step3: Now we take the latitude and longitude of each pothole and show them on a map using circle markers | Python Code:
import folium
import pandas as pd
Explanation: End-To-End Example: Plotting and Mapping Potholes
Let's do a data analysis of Syracuse Potholes based on data from the civic hackathon https://cityofsyracuse.github.io/RoadsChallenge/
We will plot data and display pothole locations on a map!
End of explanation
SYR = (43.0481, -76.1474)
map = folium.Map(location=SYR, zoom_start=14)
map
Explanation: First we need to find the latitude and longitude of Syracuse, then estimate the appropriate zoom level...
End of explanation
data = pd.read_csv('https://cityofsyracuse.github.io/RoadsChallenge/data/potholes.csv')
data.sample(5)
Explanation: We get the data from the RoadsChallange github account
End of explanation
# NOTE: to_dict('records') converts a pandas dataframe back to a list of dict!
SYR = (43.0481, -76.1474)
map = folium.Map(location=SYR, zoom_start=14)
subset = data.sample(500)
for row in subset.to_records():
coords = (row['Longitude'],row['Latitude'])
loc = str(row['strLocation']) + ' ' + str(row['dtTime'])
marker = folium.Circle(location=coords, radius=15, popup=loc,color='#3186cc',fill_color='#3186cc')
map.add_child(marker)
map
Explanation: Now we take the latitude and longitude of each pothole and show them on a map using circle markers
End of explanation |
7,927 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple notebook pipeline
Welcome to your first steps with Kubeflow Pipelines (KFP). This notebook demos
Step1: Setup
Step2: Create pipeline component
Create a python function
Step3: Build a pipeline component from the function
Step4: Build a pipeline using the component
Step5: Compile and run the pipeline
Kubeflow Pipelines lets you group pipeline runs by Experiments. You can create a new experiment, or call kfp.Client().list_experiments() to see existing ones.
If you don't specify the experiment name, the Default experiment will be used.
You can directly run a pipeline given its function definition
Step6: Alternately, you can separately compile the pipeline and then upload and run it as follows
Step7: Submit the compiled pipeline for execution | Python Code:
# You may need to restart your notebook kernel after updating the kfp sdk
!python3 -m pip install kfp --upgrade --user
Explanation: Simple notebook pipeline
Welcome to your first steps with Kubeflow Pipelines (KFP). This notebook demos:
Defining a Kubeflow pipeline with the KFP SDK
Creating an experiment and submitting pipelines to the KFP run time environment using the KFP SDK
Reference documentation:
* https://www.kubeflow.org/docs/pipelines/sdk/sdk-overview/
* https://www.kubeflow.org/docs/pipelines/sdk/build-component/
Prerequisites: Install or update the pipelines SDK
You may need to restart your notebook kernel after updating the KFP sdk.
This notebook is intended to be run from a Kubeflow notebook server. (From other environments, you would need to pass different arguments to the kfp.Client constructor.)
End of explanation
EXPERIMENT_NAME = 'Simple notebook pipeline' # Name of the experiment in the UI
BASE_IMAGE = 'tensorflow/tensorflow:2.0.0b0-py3' # Base image used for components in the pipeline
import kfp
import kfp.dsl as dsl
from kfp import compiler
from kfp import components
Explanation: Setup
End of explanation
@dsl.python_component(
name='add_op',
description='adds two numbers',
base_image=BASE_IMAGE # you can define the base image here, or when you build in the next step.
)
def add(a: float, b: float) -> float:
'''Calculates sum of two arguments'''
print(a, '+', b, '=', a + b)
return a + b
Explanation: Create pipeline component
Create a python function
End of explanation
# Convert the function to a pipeline operation.
add_op = components.func_to_container_op(
add,
base_image=BASE_IMAGE,
)
Explanation: Build a pipeline component from the function
End of explanation
@dsl.pipeline(
name='Calculation pipeline',
description='A toy pipeline that performs arithmetic calculations.'
)
def calc_pipeline(
a: float =0,
b: float =7
):
#Passing pipeline parameter and a constant value as operation arguments
add_task = add_op(a, 4) #Returns a dsl.ContainerOp class instance.
#You can create explicit dependency between the tasks using xyz_task.after(abc_task)
add_2_task = add_op(a, b)
add_3_task = add_op(add_task.output, add_2_task.output)
Explanation: Build a pipeline using the component
End of explanation
# Specify pipeline argument values
arguments = {'a': '7', 'b': '8'}
# Launch a pipeline run given the pipeline function definition
kfp.Client().create_run_from_pipeline_func(calc_pipeline, arguments=arguments,
experiment_name=EXPERIMENT_NAME)
# The generated links below lead to the Experiment page and the pipeline run details page, respectively
Explanation: Compile and run the pipeline
Kubeflow Pipelines lets you group pipeline runs by Experiments. You can create a new experiment, or call kfp.Client().list_experiments() to see existing ones.
If you don't specify the experiment name, the Default experiment will be used.
You can directly run a pipeline given its function definition:
End of explanation
# Compile the pipeline
pipeline_func = calc_pipeline
pipeline_filename = pipeline_func.__name__ + '.pipeline.zip'
compiler.Compiler().compile(pipeline_func, pipeline_filename)
# Get or create an experiment
client = kfp.Client()
experiment = client.create_experiment(EXPERIMENT_NAME)
Explanation: Alternately, you can separately compile the pipeline and then upload and run it as follows:
End of explanation
# Specify pipeline argument values
arguments = {'a': '7', 'b': '8'}
# Submit a pipeline run
run_name = pipeline_func.__name__ + ' run'
run_result = client.run_pipeline(experiment.id, run_name, pipeline_filename, arguments)
# The generated link below leads to the pipeline run information page.
Explanation: Submit the compiled pipeline for execution:
End of explanation |
7,928 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Metadata
Step1: Este pequeño script muestra algunos aspectos importantes de la sintaxis de Python.
Comentarios
Los comentarios en Python empiezan con un "pound", "hash" o numeral # y cualquier cosa que lo siga hasta el final de la línea es ignorada por el intérprete. Es decir, pueden tener comentarios que toman toda la línea, o sólo parte de ella.
En el ejemplo de arriba hay tres comentarios
Step2: Los parentesis también se usan para pasar parámetros a una función cuando se llama. En el siguiente snippet de código, la función print() se usa para mostrar, por ej, los contenidos de una variable. La función se "llama" con un par de parentesis con los argumentos de la función adentro.
Step3: Algunas funciones se llaman sin argumentos y actuan sobre el objeto que evalúan. Los parentesis deben ser usados igual, aunque la función tenga argumentos. | Python Code:
# set the midpoint
midpoint = 5
# make two empty lists
lower = []; upper = []
# split the numbers into lower and upper
for i in range(10):
if (i < midpoint):
lower.append(i)
else:
upper.append(i)
print("lower:", lower)
print("upper:", upper)
Explanation: Metadata: Estos notebooks están (más que) inspirados en el excelente trabajo de Jake van der Plass y su Whirlwind Tour Of Python. Ver A Whirlwind Tour of Python by Jake VanderPlas (O’Reilly). Copyright 2016 O’Reilly Media, Inc., 978-1-491-96465-1.". Estos notebooks están protegidos con la misma licencia de los originales, Creative Commons 0. Todas las notas están disponibles en PrograUDD1.
La sintaxis de Python
La sintaxis de Python es considerada tan limpia que a veces a Python se le dice "executable pseudo-code", e hizo que su adaptación haya sido muy extensa.
Considere el siguiente código:
End of explanation
print(2*(3+4))
print(2*3+4)
print((2*3)+4)
Explanation: Este pequeño script muestra algunos aspectos importantes de la sintaxis de Python.
Comentarios
Los comentarios en Python empiezan con un "pound", "hash" o numeral # y cualquier cosa que lo siga hasta el final de la línea es ignorada por el intérprete. Es decir, pueden tener comentarios que toman toda la línea, o sólo parte de ella.
En el ejemplo de arriba hay tres comentarios:
```python
set the midpoint
make two empty lists
lower = []; upper = []
or
lower = []; upper = [] # make two empty lists
split the numbers into lower and upper
```
Python no tiene una manera de hacer comentarios multilínea como C, por ejemplo (/* ... */).
"Enter" termina una línea ejecutable (una sentencia, ?)
The line
Python
midpoint = 5
Esta operación se llama asignación, y básicamente consiste en crear una variable y darle un valor en particular: 5, en este caso. Noten que no hay nada que marque el final de la sentencia, ni {...} ni ; ni nada por el estilo (solo Enter). Esto es bastante diferente de los lenguajes de programación como C o Java, que necesitaban los ; (a lo mejor razones históricas?)
Sin embargo si por alguna razón necesitan de hecho "span" más de una línea.
Python
x = 1 + 2 + 3 + 4 +\
5 + 6 + 7 + 8
también es posible continuar en la siguiente línea si existen paréntesis, y sin usar el operador \, así:
Python
x = (1 + 2 + 3 + 4 +
5 + 6 + 7 + 8)
Los dioses del Python igual recomiendan el segundo método, en vez del símbolo de continuación: \. Alguno se anima a decir por qué?
Los espacios importan!
Vean el siguiente snippet de código:
Python
for i in range(10):
if i < midpoint:
lower.append(i)
else:
upper.append(i)
Aqui hay varias cosas que notar. Lo primero es que hay un condicional (el scope introducido por el if), y un "loop" (o ciclo), el scope introducido por el for. No es tan importante a esta altura, pero nos presenta lo que ha sido la caracteristica mas controversial de la sintaxis de Python: el espacio en blanco tiene semántica!
En otros lenguajes de programación, un bloque (scope) se define explicitamente con algun símbolo. Cuál es el simbolo que define scope en el siguiente código?
C
// C code
for(int i=0; i<100; i++) {
// curly braces indicate code block
total += i;}
y en este:
Go
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
}
En Python los scope (o bloques de código) se determinan por indentación.
Python
for i in range(100):
# indentation indicates code block
total += i
y el scope siempre se precede con : en la línea anterior.
A mí me gusta como queda la indentación... es más limpia que la {}, pero al mismo puede producir confusion en los n00bs. Lo siguiente produce diferentes resultados:
```
if x < 4: >>> if x < 4:
........y = x * 2 ........y = x * 2
........print(x) ....print(x)
```
El código de la izquierda va a ser ejecutado sólo si el valor de x es menor que 4, mientras que el de la derecha se va a ejecutar no importa el valor de x.
A mí me parece más leible el código con espacios que con curlies, a ustedes?
Por último, el número de espacios en blanco no es importante. Sólo es necesario que sean sistemáticos, es decir, no pueden ir cambiando en un script entre 2 y 4 espacios, digamos. La convención es usar 4 espacios (y nunca "tabs"), y esta es la convención que usamos en estos notebooks. (Aunque a mí me guste los 2 espacios en C :( ).
Los espacios en blanco adentro de las líneas no tienen efecto, sólo antes de empezar la línea. Lo siguiente es equivalente:
Python
x=1+2
x = 1 + 2
x = 1 + 2
Obviamente, abusar esta flexibilidad del lenguaje afecta la legibilidad del código. La tercera línea se ve bastante espantosa. La primera en menor medida, y la del medio es la que (a mi) me hace más sentido. Comparen por ejemplo
Python
x=10**-2
con
Python
x = 10 ** -2
De hecho se sugiere poner espacios entre los operadores binarios.
Parentesis
Los parentesis son para agrupar términos y para hacer llamada a funciones con parametros. Primero, se usan para agrupar los términos de los operadores matemáticos:
End of explanation
x = 3
print('first value:', x)
print('second value:', 2)
Explanation: Los parentesis también se usan para pasar parámetros a una función cuando se llama. En el siguiente snippet de código, la función print() se usa para mostrar, por ej, los contenidos de una variable. La función se "llama" con un par de parentesis con los argumentos de la función adentro.
End of explanation
L = [4,2,3,1]
L.sort()
print(L)
Explanation: Algunas funciones se llaman sin argumentos y actuan sobre el objeto que evalúan. Los parentesis deben ser usados igual, aunque la función tenga argumentos.
End of explanation |
7,929 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset of English and French sentences that can translate new sentences from English to French.
Get the Data
Since translating the whole language of English to French will take lots of time to train, we have provided you with a small portion of the English corpus.
Step3: Explore the Data
Play around with view_sentence_range to view different parts of the data.
Step6: Implement Preprocessing Function
Text to Word Ids
As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the <EOS> word id at the end of each sentence from target_text. This will help the neural network predict when the sentence should end.
You can get the <EOS> word id by doing
Step8: Preprocess all the data and save it
Running the code cell below will preprocess all the data and save it to file.
Step10: Check Point
This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
Step12: Check the Version of TensorFlow and Access to GPU
This will check to make sure you have the correct version of TensorFlow and access to a GPU
Step15: Build the Neural Network
You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below
Step18: Process Decoding Input
Implement process_decoding_input using TensorFlow to remove the last word id from each batch in target_data and concat the GO ID to the beginning of each batch.
Step21: Encoding
Implement encoding_layer() to create a Encoder RNN layer using tf.nn.dynamic_rnn().
Step24: Decoding - Training
Create training logits using tf.contrib.seq2seq.simple_decoder_fn_train() and tf.contrib.seq2seq.dynamic_rnn_decoder(). Apply the output_fn to the tf.contrib.seq2seq.dynamic_rnn_decoder() outputs.
Step27: Decoding - Inference
Create inference logits using tf.contrib.seq2seq.simple_decoder_fn_inference() and tf.contrib.seq2seq.dynamic_rnn_decoder().
Step30: Build the Decoding Layer
Implement decoding_layer() to create a Decoder RNN layer.
Create RNN cell for decoding using rnn_size and num_layers.
Create the output fuction using lambda to transform it's input, logits, to class logits.
Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope, output_fn, keep_prob) function to get the training logits.
Use your decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, maximum_length, vocab_size, decoding_scope, output_fn, keep_prob) function to get the inference logits.
Note
Step33: Build the Neural Network
Apply the functions you implemented above to
Step34: Neural Network Training
Hyperparameters
Tune the following parameters
Step36: Build the Graph
Build the graph using the neural network you implemented.
Step39: Train
Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forums to see if anyone is having the same problem.
Step41: Save Parameters
Save the batch_size and save_path parameters for inference.
Step43: Checkpoint
Step46: Sentence to Sequence
To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences.
Convert the sentence to lowercase
Convert words into ids using vocab_to_int
Convert words not in the vocabulary, to the <UNK> word id.
Step48: Translate
This will translate translate_sentence from English to French. | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset of English and French sentences that can translate new sentences from English to French.
Get the Data
Since translating the whole language of English to French will take lots of time to train, we have provided you with a small portion of the English corpus.
End of explanation
view_sentence_range = (0, 10)
DON'T MODIFY ANYTHING IN THIS CELL
import numpy as np
print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in source_text.split()})))
sentences = source_text.split('\n')
word_counts = [len(sentence.split()) for sentence in sentences]
print('Number of sentences: {}'.format(len(sentences)))
print('Average number of words in a sentence: {}'.format(np.average(word_counts)))
print()
print('English sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(source_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))
print()
print('French sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(target_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))
Explanation: Explore the Data
Play around with view_sentence_range to view different parts of the data.
End of explanation
def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):
Convert source and target text to proper word ids
:param source_text: String that contains all the source text.
:param target_text: String that contains all the target text.
:param source_vocab_to_int: Dictionary to go from the source words to an id
:param target_vocab_to_int: Dictionary to go from the target words to an id
:return: A tuple of lists (source_id_text, target_id_text)
# TODO: Implement Function
# print(target_vocab_to_int["EOS"])
# print(target_vocab_to_int)
# print(target_vocab_to_int['<EOS>'])
source_id_text = [ [source_vocab_to_int.get(word,source_vocab_to_int['<UNK>']) for word in sentence.split()]for sentence in source_text.split('\n') ]
target_id_text = [ [target_vocab_to_int.get(word,target_vocab_to_int['<UNK>']) for word in sentence.split()] + [target_vocab_to_int['<EOS>']] for sentence in target_text.split('\n') ]
# print(target_id_text)
return source_id_text, target_id_text
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_text_to_ids(text_to_ids)
Explanation: Implement Preprocessing Function
Text to Word Ids
As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the <EOS> word id at the end of each sentence from target_text. This will help the neural network predict when the sentence should end.
You can get the <EOS> word id by doing:
python
target_vocab_to_int['<EOS>']
You can get other word ids using source_vocab_to_int and target_vocab_to_int.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
helper.preprocess_and_save_data(source_path, target_path, text_to_ids)
Explanation: Preprocess all the data and save it
Running the code cell below will preprocess all the data and save it to file.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
import numpy as np
import helper
(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()
Explanation: Check Point
This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
# Check TensorFlow Version
assert LooseVersion(tf.__version__) in [LooseVersion('1.0.0'), LooseVersion('1.0.1')], 'This project requires TensorFlow version 1.0 You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))
# Check for a GPU
if not tf.test.gpu_device_name():
warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
Explanation: Check the Version of TensorFlow and Access to GPU
This will check to make sure you have the correct version of TensorFlow and access to a GPU
End of explanation
def model_inputs():
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate, keep probability)
# TODO: Implement Function
inputs = tf.placeholder(tf.int32,[None,None],name='input')
targets = tf.placeholder(tf.int32,[None,None])
lr = tf.placeholder(tf.float32)
keep_prob = tf.placeholder(tf.float32,None,name='keep_prob')
return (inputs, targets, lr, keep_prob)
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_model_inputs(model_inputs)
Explanation: Build the Neural Network
You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below:
- model_inputs
- process_decoding_input
- encoding_layer
- decoding_layer_train
- decoding_layer_infer
- decoding_layer
- seq2seq_model
Input
Implement the model_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:
Input text placeholder named "input" using the TF Placeholder name parameter with rank 2.
Targets placeholder with rank 2.
Learning rate placeholder with rank 0.
Keep probability placeholder named "keep_prob" using the TF Placeholder name parameter with rank 0.
Return the placeholders in the following the tuple (Input, Targets, Learing Rate, Keep Probability)
End of explanation
def process_decoding_input(target_data, target_vocab_to_int, batch_size):
Preprocess target data for decoding
:param target_data: Target Placeholder
:param target_vocab_to_int: Dictionary to go from the target words to an id
:param batch_size: Batch Size
:return: Preprocessed target data
# target_data has shape [batch_size, seq_length]
# TODO: Implement Function
# batch_size,_ = target_data.shape.as_list()
# target_shape = tf.shape(target_data)
# print("target_shape is:",target_shape)
# print(target_data)
# batch_size = target_shape[0]
# print(batch_size)
ending = tf.strided_slice(target_data, [0, 0], [batch_size, -1], [1, 1])
# print(ending)
dec_input = tf.concat([tf.fill([batch_size, 1], target_vocab_to_int['<GO>']), ending], 1)
# shape_input = tf.reshape(dec_input,target_shape)
# print(dec_input)
# print(shape_input)
# print(shape_input)
# return shape_input
return dec_input
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_process_decoding_input(process_decoding_input)
Explanation: Process Decoding Input
Implement process_decoding_input using TensorFlow to remove the last word id from each batch in target_data and concat the GO ID to the beginning of each batch.
End of explanation
def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob):
Create encoding layer
:param rnn_inputs: Inputs for the RNN
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param keep_prob: Dropout keep probability
:return: RNN state
# TODO: Implement Function
cell = tf.contrib.rnn.BasicLSTMCell(rnn_size)
drop = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=keep_prob)
enc_cell = tf.contrib.rnn.MultiRNNCell([drop] * num_layers)
_, enc_state = tf.nn.dynamic_rnn(enc_cell, rnn_inputs, dtype=tf.float32)
return enc_state
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_encoding_layer(encoding_layer)
Explanation: Encoding
Implement encoding_layer() to create a Encoder RNN layer using tf.nn.dynamic_rnn().
End of explanation
def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope,
output_fn, keep_prob):
Create a decoding layer for training
:param encoder_state: Encoder State
:param dec_cell: Decoder RNN Cell
:param dec_embed_input: Decoder embedded input
:param sequence_length: Sequence Length
:param decoding_scope: TenorFlow Variable Scope for decoding
:param output_fn: Function to apply the output layer
:param keep_prob: Dropout keep probability
:return: Train Logits
# TODO: Implement Function
train_decoder_fn = tf.contrib.seq2seq.simple_decoder_fn_train(encoder_state)
# drop = tf.contrib.rnn.DropoutWrapper(dec_cell, output_keep_prob=keep_prob)
# (outputs, final_state, final_context_state)
train_pred, _, _ = tf.contrib.seq2seq.dynamic_rnn_decoder(
dec_cell, train_decoder_fn, dec_embed_input, sequence_length, scope=decoding_scope)
# Apply output function
train_logits = output_fn(train_pred)
return train_logits
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_decoding_layer_train(decoding_layer_train)
Explanation: Decoding - Training
Create training logits using tf.contrib.seq2seq.simple_decoder_fn_train() and tf.contrib.seq2seq.dynamic_rnn_decoder(). Apply the output_fn to the tf.contrib.seq2seq.dynamic_rnn_decoder() outputs.
End of explanation
def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id,
maximum_length, vocab_size, decoding_scope, output_fn, keep_prob):
Create a decoding layer for inference
:param encoder_state: Encoder state
:param dec_cell: Decoder RNN Cell
:param dec_embeddings: Decoder embeddings
:param start_of_sequence_id: GO ID
:param end_of_sequence_id: EOS Id
:param maximum_length: The maximum allowed time steps to decode
:param vocab_size: Size of vocabulary
:param decoding_scope: TensorFlow Variable Scope for decoding
:param output_fn: Function to apply the output layer
:param keep_prob: Dropout keep probability
:return: Inference Logits
# TODO: Implement Function
# Inference Decoder
infer_decoder_fn = tf.contrib.seq2seq.simple_decoder_fn_inference(
output_fn, encoder_state, dec_embeddings, start_of_sequence_id, end_of_sequence_id,
maximum_length, vocab_size)
# drop = tf.contrib.rnn.DropoutWrapper(dec_cell, output_keep_prob=keep_prob)
inference_logits, _, _ = tf.contrib.seq2seq.dynamic_rnn_decoder(dec_cell, infer_decoder_fn, scope=decoding_scope)
return inference_logits
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_decoding_layer_infer(decoding_layer_infer)
Explanation: Decoding - Inference
Create inference logits using tf.contrib.seq2seq.simple_decoder_fn_inference() and tf.contrib.seq2seq.dynamic_rnn_decoder().
End of explanation
def decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size, sequence_length, rnn_size,
num_layers, target_vocab_to_int, keep_prob):
Create decoding layer
:param dec_embed_input: Decoder embedded input
:param dec_embeddings: Decoder embeddings
:param encoder_state: The encoded state
:param vocab_size: Size of vocabulary
:param sequence_length: Sequence Length
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param target_vocab_to_int: Dictionary to go from the target words to an id
:param keep_prob: Dropout keep probability
:return: Tuple of (Training Logits, Inference Logits)
# TODO: Implement Function
cell = tf.contrib.rnn.BasicLSTMCell(rnn_size)
drop = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=keep_prob)
dec_cell = tf.contrib.rnn.MultiRNNCell([drop] * num_layers)
# print(sequence_length)
maximum_length = sequence_length
with tf.variable_scope("decoding") as decoding_scope:
output_fn = lambda x: tf.contrib.layers.fully_connected(x, vocab_size, None, scope=decoding_scope,
weights_initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1),
biases_initializer=tf.zeros_initializer())
train_logits = decoding_layer_train(encoder_state,dec_cell,dec_embed_input,
sequence_length,decoding_scope,output_fn,keep_prob)
decoding_scope.reuse_variables()
inference_logits = decoding_layer_infer(encoder_state, dec_cell, dec_embeddings,
target_vocab_to_int['<GO>'], target_vocab_to_int["<EOS>"],
maximum_length, vocab_size, decoding_scope, output_fn, keep_prob)
return train_logits, inference_logits
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_decoding_layer(decoding_layer)
Explanation: Build the Decoding Layer
Implement decoding_layer() to create a Decoder RNN layer.
Create RNN cell for decoding using rnn_size and num_layers.
Create the output fuction using lambda to transform it's input, logits, to class logits.
Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope, output_fn, keep_prob) function to get the training logits.
Use your decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, maximum_length, vocab_size, decoding_scope, output_fn, keep_prob) function to get the inference logits.
Note: You'll need to use tf.variable_scope to share variables between training and inference.
End of explanation
def seq2seq_model(input_data, target_data, keep_prob, batch_size, sequence_length, source_vocab_size, target_vocab_size,
enc_embedding_size, dec_embedding_size, rnn_size, num_layers, target_vocab_to_int):
Build the Sequence-to-Sequence part of the neural network
:param input_data: Input placeholder
:param target_data: Target placeholder
:param keep_prob: Dropout keep probability placeholder
:param batch_size: Batch Size
:param sequence_length: Sequence Length
:param source_vocab_size: Source vocabulary size
:param target_vocab_size: Target vocabulary size
:param enc_embedding_size: Decoder embedding size
:param dec_embedding_size: Encoder embedding size
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param target_vocab_to_int: Dictionary to go from the target words to an id
:return: Tuple of (Training Logits, Inference Logits)
# TODO: Implement Function
# Encoder Embedding
enc_embeddings = tf.Variable(tf.truncated_normal([source_vocab_size, enc_embedding_size],mean=0.0, stddev=0.1))
enc_embed_input = tf.nn.embedding_lookup(enc_embeddings, input_data)
# decoder Embedding
dec_embeddings = tf.Variable(tf.truncated_normal([target_vocab_size, dec_embedding_size],mean=0.0, stddev=0.1))
dec_input = process_decoding_input(target_data, target_vocab_to_int, batch_size)
dec_embed_input = tf.nn.embedding_lookup(dec_embeddings, dec_input)
enc_state = encoding_layer(enc_embed_input,rnn_size,num_layers,keep_prob)
return decoding_layer(dec_embed_input,dec_embeddings,enc_state,target_vocab_size,sequence_length,
rnn_size, num_layers, target_vocab_to_int, keep_prob)
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_seq2seq_model(seq2seq_model)
Explanation: Build the Neural Network
Apply the functions you implemented above to:
Apply embedding to the input data for the encoder.
Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob).
Process target data using your process_decoding_input(target_data, target_vocab_to_int, batch_size) function.
Apply embedding to the target data for the decoder.
Decode the encoded input using your decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size, sequence_length, rnn_size, num_layers, target_vocab_to_int, keep_prob).
End of explanation
# Number of Epochs
epochs = 10
# Batch Size
batch_size = 1000
# RNN Size
rnn_size = 128
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 100
decoding_embedding_size = 100
# Learning Rate
learning_rate = 0.01
# Dropout Keep Probability
keep_probability = 0.5
Explanation: Neural Network Training
Hyperparameters
Tune the following parameters:
Set epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set num_layers to the number of layers.
Set encoding_embedding_size to the size of the embedding for the encoder.
Set decoding_embedding_size to the size of the embedding for the decoder.
Set learning_rate to the learning rate.
Set keep_probability to the Dropout keep probability
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
save_path = 'checkpoints/dev'
(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()
# input_shape [batch_size, seq_len]
max_source_sentence_length = max([len(sentence) for sentence in source_int_text])
train_graph = tf.Graph()
with train_graph.as_default():
input_data, targets, lr, keep_prob = model_inputs()
sequence_length = tf.placeholder_with_default(max_source_sentence_length, None, name='sequence_length')
input_shape = tf.shape(input_data)
train_logits, inference_logits = seq2seq_model(
tf.reverse(input_data, [-1]), targets, keep_prob, batch_size, sequence_length, len(source_vocab_to_int), len(target_vocab_to_int),
encoding_embedding_size, decoding_embedding_size, rnn_size, num_layers, target_vocab_to_int)
tf.identity(inference_logits, 'logits')
with tf.name_scope("optimization"):
# Loss function
cost = tf.contrib.seq2seq.sequence_loss(
train_logits,
targets,
tf.ones([input_shape[0], sequence_length]))
# Optimizer
optimizer = tf.train.AdamOptimizer(lr)
# Gradient Clipping
gradients = optimizer.compute_gradients(cost)
capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]
train_op = optimizer.apply_gradients(capped_gradients)
Explanation: Build the Graph
Build the graph using the neural network you implemented.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
import time
def get_accuracy(target, logits):
Calculate accuracy
max_seq = max(target.shape[1], logits.shape[1])
if max_seq - target.shape[1]:
target = np.pad(
target,
[(0,0),(0,max_seq - target.shape[1])],
'constant')
if max_seq - logits.shape[1]:
logits = np.pad(
logits,
[(0,0),(0,max_seq - logits.shape[1]), (0,0)],
'constant')
return np.mean(np.equal(target, np.argmax(logits, 2)))
train_source = source_int_text[batch_size:]
train_target = target_int_text[batch_size:]
valid_source = helper.pad_sentence_batch(source_int_text[:batch_size])
valid_target = helper.pad_sentence_batch(target_int_text[:batch_size])
with tf.Session(graph=train_graph) as sess:
sess.run(tf.global_variables_initializer())
for epoch_i in range(epochs):
for batch_i, (source_batch, target_batch) in enumerate(
helper.batch_data(train_source, train_target, batch_size)):
start_time = time.time()
# print(source_batch)
# print(target_batch.shape[1])
_, loss = sess.run(
[train_op, cost],
{input_data: source_batch,
targets: target_batch,
lr: learning_rate,
sequence_length: target_batch.shape[1],
keep_prob: keep_probability})
batch_train_logits = sess.run(
inference_logits,
{input_data: source_batch, keep_prob: 1.0})
batch_valid_logits = sess.run(
inference_logits,
{input_data: valid_source, keep_prob: 1.0})
train_acc = get_accuracy(target_batch, batch_train_logits)
valid_acc = get_accuracy(np.array(valid_target), batch_valid_logits)
end_time = time.time()
print('Epoch {:>3} Batch {:>4}/{} - Train Accuracy: {:>6.3f}, Validation Accuracy: {:>6.3f}, Loss: {:>6.3f}'
.format(epoch_i, batch_i, len(source_int_text) // batch_size, train_acc, valid_acc, loss))
# Save Model
saver = tf.train.Saver()
saver.save(sess, save_path)
print('Model Trained and Saved')
# slice index 0 of dimension 0 out of bounds.
# encoding_embedding_size, decoding_embedding_size, rnn_size, num_layers, target_vocab_to_int)
# File "<ipython-input-15-8888a89f5a5f>", line 33, in seq2seq_model
# rnn_size, num_layers, target_vocab_to_int, keep_prob)
# File "<ipython-input-14-e26eb46fd08a>", line 25, in decoding_layer
# sequence_length,decoding_scope,output_fn,keep_prob)
# File "<ipython-input-12-e3037e3ad4b7>", line 19, in decoding_layer_train
Explanation: Train
Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forums to see if anyone is having the same problem.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
# Save parameters for checkpoint
helper.save_params(save_path)
Explanation: Save Parameters
Save the batch_size and save_path parameters for inference.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
import tensorflow as tf
import numpy as np
import helper
import problem_unittests as tests
_, (source_vocab_to_int, target_vocab_to_int), (source_int_to_vocab, target_int_to_vocab) = helper.load_preprocess()
load_path = helper.load_params()
Explanation: Checkpoint
End of explanation
def sentence_to_seq(sentence, vocab_to_int):
Convert a sentence to a sequence of ids
:param sentence: String
:param vocab_to_int: Dictionary to go from the words to an id
:return: List of word ids
# TODO: Implement Function
return [vocab_to_int.get(word,vocab_to_int['<UNK>']) for word in sentence.lower().split()]
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_sentence_to_seq(sentence_to_seq)
Explanation: Sentence to Sequence
To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences.
Convert the sentence to lowercase
Convert words into ids using vocab_to_int
Convert words not in the vocabulary, to the <UNK> word id.
End of explanation
translate_sentence = 'he saw a old yellow truck .'
DON'T MODIFY ANYTHING IN THIS CELL
translate_sentence = sentence_to_seq(translate_sentence, source_vocab_to_int)
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
# Load saved model
loader = tf.train.import_meta_graph(load_path + '.meta')
loader.restore(sess, load_path)
input_data = loaded_graph.get_tensor_by_name('input:0')
logits = loaded_graph.get_tensor_by_name('logits:0')
keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')
translate_logits = sess.run(logits, {input_data: [translate_sentence], keep_prob: 1.0})[0]
print('Input')
print(' Word Ids: {}'.format([i for i in translate_sentence]))
print(' English Words: {}'.format([source_int_to_vocab[i] for i in translate_sentence]))
print('\nPrediction')
print(' Word Ids: {}'.format([i for i in np.argmax(translate_logits, 1)]))
print(' French Words: {}'.format([target_int_to_vocab[i] for i in np.argmax(translate_logits, 1)]))
Explanation: Translate
This will translate translate_sentence from English to French.
End of explanation |
7,930 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: TFX Keras コンポーネントのチュートリアル
TensorFlow Extended (TFX) の各コンポーネントの紹介
注:この例は、Jupyter スタイルのノートブックで今すぐ実行できます。セットアップは必要ありません。「Google Colab で実行」をクリックするだけです
<div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: TFX をインストールする
注:Google Colab では、パッケージが更新されるため、このセルを初めて実行するときに、ランタイムを再起動する必要があります([ランタイム]> [ランタイムの再起動...])。
Step3: ランタイムを再起動しましたか?
Google Colab を使用している場合は、上記のセルを初めて実行するときにランタイムを再起動する必要があります([ランタイム]> [ランタイムの再起動...])。 これは、Colab がパッケージを読み込むために必要ですです。
パッケージをインポートする
標準の TFX コンポーネント クラスを含む必要なパッケージをインポートします。
Step4: ライブラリのバージョンを確認します。
Step5: パイプライン パスを設定
Step6: サンプルデータのダウンロード
TFX パイプラインで使用するサンプル データセットをダウンロードします。
使用しているデータセットは、シカゴ市がリリースした タクシートリップデータセットです。 このデータセットの列は次のとおりです。
<table>
<tr>
<td>pickup_community_area</td>
<td>fare</td>
<td>trip_start_month</td>
</tr>
<tr>
<td>trip_start_hour</td>
<td>trip_start_day</td>
<td>trip_start_timestamp</td>
</tr>
<tr>
<td>pickup_latitude</td>
<td>pickup_longitude</td>
<td>dropoff_latitude</td>
</tr>
<tr>
<td>dropoff_longitude</td>
<td>trip_miles</td>
<td>pickup_census_tract</td>
</tr>
<tr>
<td>dropoff_census_tract</td>
<td>payment_type</td>
<td>company</td>
</tr>
<tr>
<td>trip_seconds</td>
<td>dropoff_community_area</td>
<td>tips</td>
</tr>
</table>
このデータセットを使用して、タクシー乗車のtipsを予測するモデルを構築します。
Step7: CSV ファイルを見てみましょう。
Step8: 注:このWeb サイトは、シカゴ市の公式 Web サイト www.cityofchicago.org で公開されたデータを変更して使用するアプリケーションを提供します。シカゴ市は、この Web サイトで提供されるデータの内容、正確性、適時性、または完全性について一切の表明を行いません。この Web サイトで提供されるデータは、いつでも変更される可能性があります。かかる Web サイトで提供されるデータはユーザーの自己責任で利用されるものとします。
InteractiveContext を作成する
最後に、このノートブックで TFX コンポーネントをインタラクティブに実行できるようにする InteractiveContext を作成します。
Step9: TFX コンポーネントをインタラクティブに実行する
次のセルでは、TFX コンポーネントを 1 つずつ作成し、それぞれを実行して、出力アーティファクトを視覚化します。
ExampleGen
ExampleGen コンポーネントは通常、TFX パイプラインの先頭にあり、以下を実行します。
データをトレーニング セットと評価セットに分割します (デフォルトでは、2/3 トレーニング + 1/3 評価)。
データを tf.Example 形式に変換します。 (詳細はこちら)
他のコンポーネントがアクセスできるように、データを _tfx_root ディレクトリにコピーします。
ExampleGen は、データソースへのパスを入力として受け取ります。 ここでは、これはダウンロードした CSV を含む _data_root パスです。
注意
Step10: ExampleGenの出力アーティファクトを調べてみましょう。このコンポーネントは、トレーニングサンプルと評価サンプルの 2 つのアーティファクトを生成します。
Step11: また、最初の 3 つのトレーニングサンプルも見てみます。
Step12: ExampleGenがデータの取り込みを完了したので、次のステップ、データ分析に進みます。
StatisticsGen
StatisticsGenコンポーネントは、データ分析用のデータセットの統計を計算し、ダウンストリームのコンポーネントで使用します。これは、TensorFlow Data Validation ライブラリを使用します。
StatisticsGenコンポーネントは、データ分析用のデータセットの統計を計算し、ダウンストリーム コンポーネントで使用します。
Step13: StatisticsGen の実行が完了すると、出力された統計を視覚化できます。 色々なプロットを試してみてください!
Step14: SchemaGen
SchemaGen コンポーネントは、データ統計に基づいてスキーマを生成します。(スキーマは、データセット内の特徴の予想される境界、タイプ、プロパティを定義します。)また、TensorFlow データ検証ライブラリも使用します。
注意
Step15: SchemaGen の実行が完了すると、生成されたスキーマをテーブルとして視覚化できます。
Step16: データセットのそれぞれの特徴は、スキーマ テーブルのプロパティの横に行として表示されます。スキーマは、ドメインとして示される、カテゴリ特徴が取るすべての値もキャプチャします。
スキーマの詳細については、SchemaGen のドキュメントをご覧ください。
ExampleValidator
ExampleValidator コンポーネントは、スキーマで定義された期待に基づいて、データの異常を検出します。また、TensorFlow Data Validation ライブラリも使用します。
ExampleValidator は、Statistics Gen{/code 1} からの統計と <code data-md-type="codespan">SchemaGen からのスキーマを入力として受け取ります。
Step17: ExampleValidator の実行が完了すると、異常をテーブルとして視覚化できます。
Step19: 異常テーブルでは、異常がないことがわかります。これは、分析した最初のデータセットで、スキーマはこれに合わせて調整されているため、異常がないことが予想されます。このスキーマを確認する必要があります。予期されないものは、データに異常があることを意味します。確認されたスキーマを使用して将来のデータを保護できます。ここで生成された異常は、モデルのパフォーマンスをデバッグし、データが時間の経過とともにどのように変化するかを理解し、データ エラーを特定するために使用できます。
変換
Transformコンポーネントは、トレーニングとサービングの両方で特徴量エンジニアリングを実行します。これは、 TensorFlow Transform ライブラリを使用します。
Transformは、ExampleGenからのデータ、SchemaGenからのスキーマ、ユーザー定義の Transform コードを含むモジュールを入力として受け取ります。
以下のユーザー定義の Transform コードの例を見てみましょう(TensorFlow Transform API の概要については、チュートリアルを参照してください)。まず、特徴量エンジニアリングのいくつかの定数を定義します。
注意
Step23: 次に、生データを入力として受け取り、モデルがトレーニングできる変換された特徴量を返す {code 0}preprocessing _fn を記述します。
Step24: 次に、この特徴量エンジニアリング コードを Transformコンポーネントに渡し、実行してデータを変換します。
Step25: Transformの出力アーティファクトを調べてみましょう。このコンポーネントは、2 種類の出力を生成します。
transform_graph は、前処理演算を実行できるグラフです (このグラフは、サービングモデルと評価モデルに含まれます)。
transformed_examplesは前処理されたトレーニングおよび評価データを表します。
Step26: transform_graph アーティファクトを見てみましょう。これは、3 つのサブディレクトリを含むディレクトリを指しています。
Step27: transformed_metadata サブディレクトリには、前処理されたデータのスキーマが含まれています。transform_fnサブディレクトリには、実際の前処理グラフが含まれています。metadataサブディレクトリには、元のデータのスキーマが含まれています。
また、最初の 3 つの変換された例も見てみます。
Step36: Transformコンポーネントがデータを特徴量に変換したら、次にモデルをトレーニングします。
トレーナー
Trainerコンポーネントは、TensorFlow で定義したモデルをトレーニングします。デフォルトでは、Trainer は Estimator API をサポートします。Keras API を使用するには、トレーナーのコンストラクターでcustom_executor_spec=executor_spec.ExecutorClassSpec(GenericExecutor)をセットアップして Generic Trainer を指定する必要があります。
Trainer は、SchemaGenからのスキーマ、Transformからの変換されたデータとグラフ、トレーニング パラメータ、およびユーザー定義されたモデル コードを含むモジュールを入力として受け取ります。
以下のユーザー定義モデル コードの例を見てみましょう(TensorFlow Keras API の概要については、チュートリアルを参照してください)。
Step37: 次に、このモデル コードをTrainerコンポーネントに渡し、それを実行してモデルをトレーニングします。
Step38: TensorBoard でトレーニングを分析する
トレーナーのアーティファクトを見てみましょう。これはモデルのサブディレクトリを含むディレクトリを指しています。
Step39: オプションで、TensorBoard を Trainer に接続して、モデルの学習曲線を分析できます。
Step40: Evaluator
Evaluator コンポーネントは、評価セットに対してモデル パフォーマンス指標を計算します。TensorFlow Model Analysisライブラリを使用します。Evaluatorは、オプションで、新しくトレーニングされたモデルが以前のモデルよりも優れていることを検証できます。これは、モデルを毎日自動的にトレーニングおよび検証する実稼働環境のパイプライン設定で役立ちます。このノートブックでは 1 つのモデルのみをトレーニングするため、Evaluatorはモデルに自動的に「good」というラベルを付けます。
Evaluatorは、ExampleGenからのデータ、Trainerからのトレーニング済みモデル、およびスライス構成を入力として受け取ります。スライス構成により、特徴値に関する指標をスライスすることができます (たとえば、午前 8 時から午後 8 時までのタクシー乗車でモデルがどのように動作するかなど)。 この構成の例は、以下を参照してください。
Step41: 次に、この構成を Evaluatorに渡して実行します。
Step42: Evaluator の出力アーティファクトを調べてみましょう。
Step43: evaluation出力を使用すると、評価セット全体のグローバル指標のデフォルトの視覚化を表示できます。
Step44: スライスされた評価メトリクスの視覚化を表示するには、TensorFlow Model Analysis ライブラリを直接呼び出します。
Step45: この視覚化は同じ指標を示していますが、評価セット全体ではなく、trip_start_hourのすべての特徴値で計算されています。
TensorFlow モデル分析は、公平性インジケーターやモデル パフォーマンスの時系列のプロットなど、他の多くの視覚化をサポートしています。 詳細については、チュートリアルを参照してください。
構成にしきい値を追加したため、検証出力も利用できます。{code 0}blessing{/code 0} アーティファクトの存在は、モデルが検証に合格したことを示しています。これは実行される最初の検証であるため、候補は自動的に bless されます。
Step46: 検証結果レコードを読み込み、成功を確認することもできます。
Step47: Pusher
Pusher コンポーネントは通常、TFX パイプラインの最後にあります。このコンポーネントはモデルが検証に合格したかどうかをチェックし、合格した場合はモデルを _serving_model_dirにエクスポートします。
Step48: 次にPusherの出力アーティファクトを調べてみましょう。
Step49: 特に、Pusher はモデルを次のような SavedModel 形式でエクスポートします。 | Python Code:
#@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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Explanation: Copyright 2021 The TensorFlow Authors.
End of explanation
import sys
if 'google.colab' in sys.modules:
!pip install --upgrade pip
Explanation: TFX Keras コンポーネントのチュートリアル
TensorFlow Extended (TFX) の各コンポーネントの紹介
注:この例は、Jupyter スタイルのノートブックで今すぐ実行できます。セットアップは必要ありません。「Google Colab で実行」をクリックするだけです
<div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/tfx/tutorials/tfx/components_keras"> <img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/tfx/tutorials/tfx/components_keras.ipynb"> <img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab で実行</a></td>
<td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/tfx/tutorials/tfx/components_keras.ipynb"> <img width="32px" src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub でソースを表示</a></td>
<td><a target="_blank" href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/tfx/tutorials/tfx/components_keras.ipynb"> <img width="32px" src="https://www.tensorflow.org/images/download_logo_32px.png">ノートブックをダウンロード</a></td>
</table></div>
この Colab ベースのチュートリアルでは、TensorFlow Extended (TFX) のそれぞれの組み込みコンポーネントをインタラクティブに説明します。
ここではデータの取り込みからモデルのプッシュ、サービングまで、エンド ツー エンドの機械学習パイプラインのすべてのステップを見ていきます。
完了したら、このノートブックのコンテンツを TFX パイプライン ソース コードとして自動的にエクスポートできます。これは、Apache Airflow および Apache Beam とオーケストレーションできます。
注意: このノートブックは、TFX パイプラインでのネイティブ Keras モデルの使用を示しています。TFX は TensorFlow 2 バージョンの Keras のみをサポートします。
背景情報
このノートブックは、Jupyter/Colab 環境で TFX を使用する方法を示しています。 ここでは、インタラクティブなノートブックでシカゴのタクシーの例を見ていきます。
TFX パイプラインの構造に慣れるのには、インタラクティブなノートブックで作業するのが便利です。独自のパイプラインを軽量の開発環境として開発する場合にも役立ちますが、インタラクティブ ノートブックのオーケストレーションとメタデータ アーティファクトへのアクセス方法には違いがあるので注意してください。
オーケストレーション
TFX の実稼働デプロイメントでは、Apache Airflow、Kubeflow Pipelines、Apache Beam などのオーケストレーターを使用して、TFX コンポーネントの事前定義済みパイプライン グラフをオーケストレーションします。インタラクティブなノートブックでは、ノートブック自体がオーケストレーターであり、ノートブック セルを実行するときにそれぞれの TFX コンポーネントを実行します。
メタデータ
TFX の実稼働デプロイメントでは、ML Metadata(MLMD)API を介してメタデータにアクセスします。MLMD は、メタデータ プロパティを MySQL や SQLite などのデータベースに格納し、メタデータ ペイロードをファイル システムなどの永続ストアに保存します。インタラクティブなノートブックでは、プロパティとペイロードの両方が、Jupyter ノートブックまたは Colab サーバーの /tmp ディレクトリにあるエフェメラル SQLite データベースに保存されます。
セットアップ
まず、必要なパッケージをインストールしてインポートし、パスを設定して、データをダウンロードします。
Pip のアップグレード
ローカルで実行する場合にシステム Pipをアップグレードしないようにするには、Colab で実行していることを確認してください。もちろん、ローカルシステムは個別にアップグレードできます。
End of explanation
!pip install -U tfx
Explanation: TFX をインストールする
注:Google Colab では、パッケージが更新されるため、このセルを初めて実行するときに、ランタイムを再起動する必要があります([ランタイム]> [ランタイムの再起動...])。
End of explanation
import os
import pprint
import tempfile
import urllib
import absl
import tensorflow as tf
import tensorflow_model_analysis as tfma
tf.get_logger().propagate = False
pp = pprint.PrettyPrinter()
from tfx import v1 as tfx
from tfx.orchestration.experimental.interactive.interactive_context import InteractiveContext
%load_ext tfx.orchestration.experimental.interactive.notebook_extensions.skip
Explanation: ランタイムを再起動しましたか?
Google Colab を使用している場合は、上記のセルを初めて実行するときにランタイムを再起動する必要があります([ランタイム]> [ランタイムの再起動...])。 これは、Colab がパッケージを読み込むために必要ですです。
パッケージをインポートする
標準の TFX コンポーネント クラスを含む必要なパッケージをインポートします。
End of explanation
print('TensorFlow version: {}'.format(tf.__version__))
print('TFX version: {}'.format(tfx.__version__))
Explanation: ライブラリのバージョンを確認します。
End of explanation
# This is the root directory for your TFX pip package installation.
_tfx_root = tfx.__path__[0]
# This is the directory containing the TFX Chicago Taxi Pipeline example.
_taxi_root = os.path.join(_tfx_root, 'examples/chicago_taxi_pipeline')
# This is the path where your model will be pushed for serving.
_serving_model_dir = os.path.join(
tempfile.mkdtemp(), 'serving_model/taxi_simple')
# Set up logging.
absl.logging.set_verbosity(absl.logging.INFO)
Explanation: パイプライン パスを設定
End of explanation
_data_root = tempfile.mkdtemp(prefix='tfx-data')
DATA_PATH = 'https://raw.githubusercontent.com/tensorflow/tfx/master/tfx/examples/chicago_taxi_pipeline/data/simple/data.csv'
_data_filepath = os.path.join(_data_root, "data.csv")
urllib.request.urlretrieve(DATA_PATH, _data_filepath)
Explanation: サンプルデータのダウンロード
TFX パイプラインで使用するサンプル データセットをダウンロードします。
使用しているデータセットは、シカゴ市がリリースした タクシートリップデータセットです。 このデータセットの列は次のとおりです。
<table>
<tr>
<td>pickup_community_area</td>
<td>fare</td>
<td>trip_start_month</td>
</tr>
<tr>
<td>trip_start_hour</td>
<td>trip_start_day</td>
<td>trip_start_timestamp</td>
</tr>
<tr>
<td>pickup_latitude</td>
<td>pickup_longitude</td>
<td>dropoff_latitude</td>
</tr>
<tr>
<td>dropoff_longitude</td>
<td>trip_miles</td>
<td>pickup_census_tract</td>
</tr>
<tr>
<td>dropoff_census_tract</td>
<td>payment_type</td>
<td>company</td>
</tr>
<tr>
<td>trip_seconds</td>
<td>dropoff_community_area</td>
<td>tips</td>
</tr>
</table>
このデータセットを使用して、タクシー乗車のtipsを予測するモデルを構築します。
End of explanation
!head {_data_filepath}
Explanation: CSV ファイルを見てみましょう。
End of explanation
# Here, we create an InteractiveContext using default parameters. This will
# use a temporary directory with an ephemeral ML Metadata database instance.
# To use your own pipeline root or database, the optional properties
# `pipeline_root` and `metadata_connection_config` may be passed to
# InteractiveContext. Calls to InteractiveContext are no-ops outside of the
# notebook.
context = InteractiveContext()
Explanation: 注:このWeb サイトは、シカゴ市の公式 Web サイト www.cityofchicago.org で公開されたデータを変更して使用するアプリケーションを提供します。シカゴ市は、この Web サイトで提供されるデータの内容、正確性、適時性、または完全性について一切の表明を行いません。この Web サイトで提供されるデータは、いつでも変更される可能性があります。かかる Web サイトで提供されるデータはユーザーの自己責任で利用されるものとします。
InteractiveContext を作成する
最後に、このノートブックで TFX コンポーネントをインタラクティブに実行できるようにする InteractiveContext を作成します。
End of explanation
example_gen = tfx.components.CsvExampleGen(input_base=_data_root)
context.run(example_gen, enable_cache=True)
Explanation: TFX コンポーネントをインタラクティブに実行する
次のセルでは、TFX コンポーネントを 1 つずつ作成し、それぞれを実行して、出力アーティファクトを視覚化します。
ExampleGen
ExampleGen コンポーネントは通常、TFX パイプラインの先頭にあり、以下を実行します。
データをトレーニング セットと評価セットに分割します (デフォルトでは、2/3 トレーニング + 1/3 評価)。
データを tf.Example 形式に変換します。 (詳細はこちら)
他のコンポーネントがアクセスできるように、データを _tfx_root ディレクトリにコピーします。
ExampleGen は、データソースへのパスを入力として受け取ります。 ここでは、これはダウンロードした CSV を含む _data_root パスです。
注意: このノートブックでは、コンポーネントを 1 つずつインスタンス化し、InteractiveContext.run() で実行しますが、実稼働環境では、すべてのコンポーネントを事前に Pipelineで指定して、オーケストレーターに渡します(TFX パイプライン ガイドの構築を参照してください)。
キャッシュを有効にする
ノートブックで InteractiveContext を使用してパイプラインを作成している場合、個別のコンポーネントが出力をキャッシュするタイミングを制御することができます。コンポーネントが前に生成した出力アーティファクトを再利用する場合は、enable_cache を True に設定します。コードを変更するなどにより、コンポーネントの出力アーティファクトを再計算する場合は、enable_cache を False に設定します。
End of explanation
artifact = example_gen.outputs['examples'].get()[0]
print(artifact.split_names, artifact.uri)
Explanation: ExampleGenの出力アーティファクトを調べてみましょう。このコンポーネントは、トレーニングサンプルと評価サンプルの 2 つのアーティファクトを生成します。
End of explanation
# Get the URI of the output artifact representing the training examples, which is a directory
train_uri = os.path.join(example_gen.outputs['examples'].get()[0].uri, 'Split-train')
# Get the list of files in this directory (all compressed TFRecord files)
tfrecord_filenames = [os.path.join(train_uri, name)
for name in os.listdir(train_uri)]
# Create a `TFRecordDataset` to read these files
dataset = tf.data.TFRecordDataset(tfrecord_filenames, compression_type="GZIP")
# Iterate over the first 3 records and decode them.
for tfrecord in dataset.take(3):
serialized_example = tfrecord.numpy()
example = tf.train.Example()
example.ParseFromString(serialized_example)
pp.pprint(example)
Explanation: また、最初の 3 つのトレーニングサンプルも見てみます。
End of explanation
statistics_gen = tfx.components.StatisticsGen(
examples=example_gen.outputs['examples'])
context.run(statistics_gen, enable_cache=True)
Explanation: ExampleGenがデータの取り込みを完了したので、次のステップ、データ分析に進みます。
StatisticsGen
StatisticsGenコンポーネントは、データ分析用のデータセットの統計を計算し、ダウンストリームのコンポーネントで使用します。これは、TensorFlow Data Validation ライブラリを使用します。
StatisticsGenコンポーネントは、データ分析用のデータセットの統計を計算し、ダウンストリーム コンポーネントで使用します。
End of explanation
context.show(statistics_gen.outputs['statistics'])
Explanation: StatisticsGen の実行が完了すると、出力された統計を視覚化できます。 色々なプロットを試してみてください!
End of explanation
schema_gen = tfx.components.SchemaGen(
statistics=statistics_gen.outputs['statistics'],
infer_feature_shape=False)
context.run(schema_gen, enable_cache=True)
Explanation: SchemaGen
SchemaGen コンポーネントは、データ統計に基づいてスキーマを生成します。(スキーマは、データセット内の特徴の予想される境界、タイプ、プロパティを定義します。)また、TensorFlow データ検証ライブラリも使用します。
注意: 生成されたスキーマはベストエフォートのもので、データの基本的なプロパティだけを推論しようとします。確認し、必要に応じて修正する必要があります。
SchemaGen は、StatisticsGen で生成した統計を入力として受け取り、デフォルトでトレーニング分割を参照します。
End of explanation
context.show(schema_gen.outputs['schema'])
Explanation: SchemaGen の実行が完了すると、生成されたスキーマをテーブルとして視覚化できます。
End of explanation
example_validator = tfx.components.ExampleValidator(
statistics=statistics_gen.outputs['statistics'],
schema=schema_gen.outputs['schema'])
context.run(example_validator, enable_cache=True)
Explanation: データセットのそれぞれの特徴は、スキーマ テーブルのプロパティの横に行として表示されます。スキーマは、ドメインとして示される、カテゴリ特徴が取るすべての値もキャプチャします。
スキーマの詳細については、SchemaGen のドキュメントをご覧ください。
ExampleValidator
ExampleValidator コンポーネントは、スキーマで定義された期待に基づいて、データの異常を検出します。また、TensorFlow Data Validation ライブラリも使用します。
ExampleValidator は、Statistics Gen{/code 1} からの統計と <code data-md-type="codespan">SchemaGen からのスキーマを入力として受け取ります。
End of explanation
context.show(example_validator.outputs['anomalies'])
Explanation: ExampleValidator の実行が完了すると、異常をテーブルとして視覚化できます。
End of explanation
_taxi_constants_module_file = 'taxi_constants.py'
%%writefile {_taxi_constants_module_file}
NUMERICAL_FEATURES = ['trip_miles', 'fare', 'trip_seconds']
BUCKET_FEATURES = [
'pickup_latitude', 'pickup_longitude', 'dropoff_latitude',
'dropoff_longitude'
]
# Number of buckets used by tf.transform for encoding each feature.
FEATURE_BUCKET_COUNT = 10
CATEGORICAL_NUMERICAL_FEATURES = [
'trip_start_hour', 'trip_start_day', 'trip_start_month',
'pickup_census_tract', 'dropoff_census_tract', 'pickup_community_area',
'dropoff_community_area'
]
CATEGORICAL_STRING_FEATURES = [
'payment_type',
'company',
]
# Number of vocabulary terms used for encoding categorical features.
VOCAB_SIZE = 1000
# Count of out-of-vocab buckets in which unrecognized categorical are hashed.
OOV_SIZE = 10
# Keys
LABEL_KEY = 'tips'
FARE_KEY = 'fare'
def t_name(key):
Rename the feature keys so that they don't clash with the raw keys when
running the Evaluator component.
Args:
key: The original feature key
Returns:
key with '_xf' appended
return key + '_xf'
Explanation: 異常テーブルでは、異常がないことがわかります。これは、分析した最初のデータセットで、スキーマはこれに合わせて調整されているため、異常がないことが予想されます。このスキーマを確認する必要があります。予期されないものは、データに異常があることを意味します。確認されたスキーマを使用して将来のデータを保護できます。ここで生成された異常は、モデルのパフォーマンスをデバッグし、データが時間の経過とともにどのように変化するかを理解し、データ エラーを特定するために使用できます。
変換
Transformコンポーネントは、トレーニングとサービングの両方で特徴量エンジニアリングを実行します。これは、 TensorFlow Transform ライブラリを使用します。
Transformは、ExampleGenからのデータ、SchemaGenからのスキーマ、ユーザー定義の Transform コードを含むモジュールを入力として受け取ります。
以下のユーザー定義の Transform コードの例を見てみましょう(TensorFlow Transform API の概要については、チュートリアルを参照してください)。まず、特徴量エンジニアリングのいくつかの定数を定義します。
注意: %%writefile セル マジックは、セルの内容をディスク上の.pyファイルとして保存します。これにより、Transform コンポーネントはコードをモジュールとして読み込むことができます。
End of explanation
_taxi_transform_module_file = 'taxi_transform.py'
%%writefile {_taxi_transform_module_file}
import tensorflow as tf
import tensorflow_transform as tft
# Imported files such as taxi_constants are normally cached, so changes are
# not honored after the first import. Normally this is good for efficiency, but
# during development when we may be iterating code it can be a problem. To
# avoid this problem during development, reload the file.
import taxi_constants
import sys
if 'google.colab' in sys.modules: # Testing to see if we're doing development
import importlib
importlib.reload(taxi_constants)
_NUMERICAL_FEATURES = taxi_constants.NUMERICAL_FEATURES
_BUCKET_FEATURES = taxi_constants.BUCKET_FEATURES
_FEATURE_BUCKET_COUNT = taxi_constants.FEATURE_BUCKET_COUNT
_CATEGORICAL_NUMERICAL_FEATURES = taxi_constants.CATEGORICAL_NUMERICAL_FEATURES
_CATEGORICAL_STRING_FEATURES = taxi_constants.CATEGORICAL_STRING_FEATURES
_VOCAB_SIZE = taxi_constants.VOCAB_SIZE
_OOV_SIZE = taxi_constants.OOV_SIZE
_FARE_KEY = taxi_constants.FARE_KEY
_LABEL_KEY = taxi_constants.LABEL_KEY
def _make_one_hot(x, key):
Make a one-hot tensor to encode categorical features.
Args:
X: A dense tensor
key: A string key for the feature in the input
Returns:
A dense one-hot tensor as a float list
integerized = tft.compute_and_apply_vocabulary(x,
top_k=_VOCAB_SIZE,
num_oov_buckets=_OOV_SIZE,
vocab_filename=key, name=key)
depth = (
tft.experimental.get_vocabulary_size_by_name(key) + _OOV_SIZE)
one_hot_encoded = tf.one_hot(
integerized,
depth=tf.cast(depth, tf.int32),
on_value=1.0,
off_value=0.0)
return tf.reshape(one_hot_encoded, [-1, depth])
def _fill_in_missing(x):
Replace missing values in a SparseTensor.
Fills in missing values of `x` with '' or 0, and converts to a dense tensor.
Args:
x: A `SparseTensor` of rank 2. Its dense shape should have size at most 1
in the second dimension.
Returns:
A rank 1 tensor where missing values of `x` have been filled in.
if not isinstance(x, tf.sparse.SparseTensor):
return x
default_value = '' if x.dtype == tf.string else 0
return tf.squeeze(
tf.sparse.to_dense(
tf.SparseTensor(x.indices, x.values, [x.dense_shape[0], 1]),
default_value),
axis=1)
def preprocessing_fn(inputs):
tf.transform's callback function for preprocessing inputs.
Args:
inputs: map from feature keys to raw not-yet-transformed features.
Returns:
Map from string feature key to transformed feature operations.
outputs = {}
for key in _NUMERICAL_FEATURES:
# If sparse make it dense, setting nan's to 0 or '', and apply zscore.
outputs[taxi_constants.t_name(key)] = tft.scale_to_z_score(
_fill_in_missing(inputs[key]), name=key)
for key in _BUCKET_FEATURES:
outputs[taxi_constants.t_name(key)] = tf.cast(tft.bucketize(
_fill_in_missing(inputs[key]), _FEATURE_BUCKET_COUNT, name=key),
dtype=tf.float32)
for key in _CATEGORICAL_STRING_FEATURES:
outputs[taxi_constants.t_name(key)] = _make_one_hot(_fill_in_missing(inputs[key]), key)
for key in _CATEGORICAL_NUMERICAL_FEATURES:
outputs[taxi_constants.t_name(key)] = _make_one_hot(tf.strings.strip(
tf.strings.as_string(_fill_in_missing(inputs[key]))), key)
# Was this passenger a big tipper?
taxi_fare = _fill_in_missing(inputs[_FARE_KEY])
tips = _fill_in_missing(inputs[_LABEL_KEY])
outputs[_LABEL_KEY] = tf.where(
tf.math.is_nan(taxi_fare),
tf.cast(tf.zeros_like(taxi_fare), tf.int64),
# Test if the tip was > 20% of the fare.
tf.cast(
tf.greater(tips, tf.multiply(taxi_fare, tf.constant(0.2))), tf.int64))
return outputs
Explanation: 次に、生データを入力として受け取り、モデルがトレーニングできる変換された特徴量を返す {code 0}preprocessing _fn を記述します。
End of explanation
transform = tfx.components.Transform(
examples=example_gen.outputs['examples'],
schema=schema_gen.outputs['schema'],
module_file=os.path.abspath(_taxi_transform_module_file))
context.run(transform, enable_cache=True)
Explanation: 次に、この特徴量エンジニアリング コードを Transformコンポーネントに渡し、実行してデータを変換します。
End of explanation
transform.outputs
Explanation: Transformの出力アーティファクトを調べてみましょう。このコンポーネントは、2 種類の出力を生成します。
transform_graph は、前処理演算を実行できるグラフです (このグラフは、サービングモデルと評価モデルに含まれます)。
transformed_examplesは前処理されたトレーニングおよび評価データを表します。
End of explanation
train_uri = transform.outputs['transform_graph'].get()[0].uri
os.listdir(train_uri)
Explanation: transform_graph アーティファクトを見てみましょう。これは、3 つのサブディレクトリを含むディレクトリを指しています。
End of explanation
# Get the URI of the output artifact representing the transformed examples, which is a directory
train_uri = os.path.join(transform.outputs['transformed_examples'].get()[0].uri, 'Split-train')
# Get the list of files in this directory (all compressed TFRecord files)
tfrecord_filenames = [os.path.join(train_uri, name)
for name in os.listdir(train_uri)]
# Create a `TFRecordDataset` to read these files
dataset = tf.data.TFRecordDataset(tfrecord_filenames, compression_type="GZIP")
# Iterate over the first 3 records and decode them.
for tfrecord in dataset.take(3):
serialized_example = tfrecord.numpy()
example = tf.train.Example()
example.ParseFromString(serialized_example)
pp.pprint(example)
Explanation: transformed_metadata サブディレクトリには、前処理されたデータのスキーマが含まれています。transform_fnサブディレクトリには、実際の前処理グラフが含まれています。metadataサブディレクトリには、元のデータのスキーマが含まれています。
また、最初の 3 つの変換された例も見てみます。
End of explanation
_taxi_trainer_module_file = 'taxi_trainer.py'
%%writefile {_taxi_trainer_module_file}
from typing import Dict, List, Text
import os
import glob
from absl import logging
import datetime
import tensorflow as tf
import tensorflow_transform as tft
from tfx import v1 as tfx
from tfx_bsl.public import tfxio
from tensorflow_transform import TFTransformOutput
# Imported files such as taxi_constants are normally cached, so changes are
# not honored after the first import. Normally this is good for efficiency, but
# during development when we may be iterating code it can be a problem. To
# avoid this problem during development, reload the file.
import taxi_constants
import sys
if 'google.colab' in sys.modules: # Testing to see if we're doing development
import importlib
importlib.reload(taxi_constants)
_LABEL_KEY = taxi_constants.LABEL_KEY
_BATCH_SIZE = 40
def _input_fn(file_pattern: List[Text],
data_accessor: tfx.components.DataAccessor,
tf_transform_output: tft.TFTransformOutput,
batch_size: int = 200) -> tf.data.Dataset:
Generates features and label for tuning/training.
Args:
file_pattern: List of paths or patterns of input tfrecord files.
data_accessor: DataAccessor for converting input to RecordBatch.
tf_transform_output: A TFTransformOutput.
batch_size: representing the number of consecutive elements of returned
dataset to combine in a single batch
Returns:
A dataset that contains (features, indices) tuple where features is a
dictionary of Tensors, and indices is a single Tensor of label indices.
return data_accessor.tf_dataset_factory(
file_pattern,
tfxio.TensorFlowDatasetOptions(
batch_size=batch_size, label_key=_LABEL_KEY),
tf_transform_output.transformed_metadata.schema)
def _get_tf_examples_serving_signature(model, tf_transform_output):
Returns a serving signature that accepts `tensorflow.Example`.
# We need to track the layers in the model in order to save it.
# TODO(b/162357359): Revise once the bug is resolved.
model.tft_layer_inference = tf_transform_output.transform_features_layer()
@tf.function(input_signature=[
tf.TensorSpec(shape=[None], dtype=tf.string, name='examples')
])
def serve_tf_examples_fn(serialized_tf_example):
Returns the output to be used in the serving signature.
raw_feature_spec = tf_transform_output.raw_feature_spec()
# Remove label feature since these will not be present at serving time.
raw_feature_spec.pop(_LABEL_KEY)
raw_features = tf.io.parse_example(serialized_tf_example, raw_feature_spec)
transformed_features = model.tft_layer_inference(raw_features)
logging.info('serve_transformed_features = %s', transformed_features)
outputs = model(transformed_features)
# TODO(b/154085620): Convert the predicted labels from the model using a
# reverse-lookup (opposite of transform.py).
return {'outputs': outputs}
return serve_tf_examples_fn
def _get_transform_features_signature(model, tf_transform_output):
Returns a serving signature that applies tf.Transform to features.
# We need to track the layers in the model in order to save it.
# TODO(b/162357359): Revise once the bug is resolved.
model.tft_layer_eval = tf_transform_output.transform_features_layer()
@tf.function(input_signature=[
tf.TensorSpec(shape=[None], dtype=tf.string, name='examples')
])
def transform_features_fn(serialized_tf_example):
Returns the transformed_features to be fed as input to evaluator.
raw_feature_spec = tf_transform_output.raw_feature_spec()
raw_features = tf.io.parse_example(serialized_tf_example, raw_feature_spec)
transformed_features = model.tft_layer_eval(raw_features)
logging.info('eval_transformed_features = %s', transformed_features)
return transformed_features
return transform_features_fn
def export_serving_model(tf_transform_output, model, output_dir):
Exports a keras model for serving.
Args:
tf_transform_output: Wrapper around output of tf.Transform.
model: A keras model to export for serving.
output_dir: A directory where the model will be exported to.
# The layer has to be saved to the model for keras tracking purpases.
model.tft_layer = tf_transform_output.transform_features_layer()
signatures = {
'serving_default':
_get_tf_examples_serving_signature(model, tf_transform_output),
'transform_features':
_get_transform_features_signature(model, tf_transform_output),
}
model.save(output_dir, save_format='tf', signatures=signatures)
def _build_keras_model(tf_transform_output: TFTransformOutput
) -> tf.keras.Model:
Creates a DNN Keras model for classifying taxi data.
Args:
tf_transform_output: [TFTransformOutput], the outputs from Transform
Returns:
A keras Model.
feature_spec = tf_transform_output.transformed_feature_spec().copy()
feature_spec.pop(_LABEL_KEY)
inputs = {}
for key, spec in feature_spec.items():
if isinstance(spec, tf.io.VarLenFeature):
inputs[key] = tf.keras.layers.Input(
shape=[None], name=key, dtype=spec.dtype, sparse=True)
elif isinstance(spec, tf.io.FixedLenFeature):
# TODO(b/208879020): Move into schema such that spec.shape is [1] and not
# [] for scalars.
inputs[key] = tf.keras.layers.Input(
shape=spec.shape or [1], name=key, dtype=spec.dtype)
else:
raise ValueError('Spec type is not supported: ', key, spec)
output = tf.keras.layers.Concatenate()(tf.nest.flatten(inputs))
output = tf.keras.layers.Dense(100, activation='relu')(output)
output = tf.keras.layers.Dense(70, activation='relu')(output)
output = tf.keras.layers.Dense(50, activation='relu')(output)
output = tf.keras.layers.Dense(20, activation='relu')(output)
output = tf.keras.layers.Dense(1)(output)
return tf.keras.Model(inputs=inputs, outputs=output)
# TFX Trainer will call this function.
def run_fn(fn_args: tfx.components.FnArgs):
Train the model based on given args.
Args:
fn_args: Holds args used to train the model as name/value pairs.
tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)
train_dataset = _input_fn(fn_args.train_files, fn_args.data_accessor,
tf_transform_output, _BATCH_SIZE)
eval_dataset = _input_fn(fn_args.eval_files, fn_args.data_accessor,
tf_transform_output, _BATCH_SIZE)
model = _build_keras_model(tf_transform_output)
model.compile(
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
metrics=[tf.keras.metrics.BinaryAccuracy()])
tensorboard_callback = tf.keras.callbacks.TensorBoard(
log_dir=fn_args.model_run_dir, update_freq='batch')
model.fit(
train_dataset,
steps_per_epoch=fn_args.train_steps,
validation_data=eval_dataset,
validation_steps=fn_args.eval_steps,
callbacks=[tensorboard_callback])
# Export the model.
export_serving_model(tf_transform_output, model, fn_args.serving_model_dir)
Explanation: Transformコンポーネントがデータを特徴量に変換したら、次にモデルをトレーニングします。
トレーナー
Trainerコンポーネントは、TensorFlow で定義したモデルをトレーニングします。デフォルトでは、Trainer は Estimator API をサポートします。Keras API を使用するには、トレーナーのコンストラクターでcustom_executor_spec=executor_spec.ExecutorClassSpec(GenericExecutor)をセットアップして Generic Trainer を指定する必要があります。
Trainer は、SchemaGenからのスキーマ、Transformからの変換されたデータとグラフ、トレーニング パラメータ、およびユーザー定義されたモデル コードを含むモジュールを入力として受け取ります。
以下のユーザー定義モデル コードの例を見てみましょう(TensorFlow Keras API の概要については、チュートリアルを参照してください)。
End of explanation
trainer = tfx.components.Trainer(
module_file=os.path.abspath(_taxi_trainer_module_file),
examples=transform.outputs['transformed_examples'],
transform_graph=transform.outputs['transform_graph'],
schema=schema_gen.outputs['schema'],
train_args=tfx.proto.TrainArgs(num_steps=10000),
eval_args=tfx.proto.EvalArgs(num_steps=5000))
context.run(trainer, enable_cache=True)
Explanation: 次に、このモデル コードをTrainerコンポーネントに渡し、それを実行してモデルをトレーニングします。
End of explanation
model_artifact_dir = trainer.outputs['model'].get()[0].uri
pp.pprint(os.listdir(model_artifact_dir))
model_dir = os.path.join(model_artifact_dir, 'Format-Serving')
pp.pprint(os.listdir(model_dir))
Explanation: TensorBoard でトレーニングを分析する
トレーナーのアーティファクトを見てみましょう。これはモデルのサブディレクトリを含むディレクトリを指しています。
End of explanation
model_run_artifact_dir = trainer.outputs['model_run'].get()[0].uri
%load_ext tensorboard
%tensorboard --logdir {model_run_artifact_dir}
Explanation: オプションで、TensorBoard を Trainer に接続して、モデルの学習曲線を分析できます。
End of explanation
# Imported files such as taxi_constants are normally cached, so changes are
# not honored after the first import. Normally this is good for efficiency, but
# during development when we may be iterating code it can be a problem. To
# avoid this problem during development, reload the file.
import taxi_constants
import sys
if 'google.colab' in sys.modules: # Testing to see if we're doing development
import importlib
importlib.reload(taxi_constants)
eval_config = tfma.EvalConfig(
model_specs=[
# This assumes a serving model with signature 'serving_default'. If
# using estimator based EvalSavedModel, add signature_name: 'eval' and
# remove the label_key.
tfma.ModelSpec(
signature_name='serving_default',
label_key=taxi_constants.LABEL_KEY,
preprocessing_function_names=['transform_features'],
)
],
metrics_specs=[
tfma.MetricsSpec(
# The metrics added here are in addition to those saved with the
# model (assuming either a keras model or EvalSavedModel is used).
# Any metrics added into the saved model (for example using
# model.compile(..., metrics=[...]), etc) will be computed
# automatically.
# To add validation thresholds for metrics saved with the model,
# add them keyed by metric name to the thresholds map.
metrics=[
tfma.MetricConfig(class_name='ExampleCount'),
tfma.MetricConfig(class_name='BinaryAccuracy',
threshold=tfma.MetricThreshold(
value_threshold=tfma.GenericValueThreshold(
lower_bound={'value': 0.5}),
# Change threshold will be ignored if there is no
# baseline model resolved from MLMD (first run).
change_threshold=tfma.GenericChangeThreshold(
direction=tfma.MetricDirection.HIGHER_IS_BETTER,
absolute={'value': -1e-10})))
]
)
],
slicing_specs=[
# An empty slice spec means the overall slice, i.e. the whole dataset.
tfma.SlicingSpec(),
# Data can be sliced along a feature column. In this case, data is
# sliced along feature column trip_start_hour.
tfma.SlicingSpec(
feature_keys=['trip_start_hour'])
])
Explanation: Evaluator
Evaluator コンポーネントは、評価セットに対してモデル パフォーマンス指標を計算します。TensorFlow Model Analysisライブラリを使用します。Evaluatorは、オプションで、新しくトレーニングされたモデルが以前のモデルよりも優れていることを検証できます。これは、モデルを毎日自動的にトレーニングおよび検証する実稼働環境のパイプライン設定で役立ちます。このノートブックでは 1 つのモデルのみをトレーニングするため、Evaluatorはモデルに自動的に「good」というラベルを付けます。
Evaluatorは、ExampleGenからのデータ、Trainerからのトレーニング済みモデル、およびスライス構成を入力として受け取ります。スライス構成により、特徴値に関する指標をスライスすることができます (たとえば、午前 8 時から午後 8 時までのタクシー乗車でモデルがどのように動作するかなど)。 この構成の例は、以下を参照してください。
End of explanation
# Use TFMA to compute a evaluation statistics over features of a model and
# validate them against a baseline.
# The model resolver is only required if performing model validation in addition
# to evaluation. In this case we validate against the latest blessed model. If
# no model has been blessed before (as in this case) the evaluator will make our
# candidate the first blessed model.
model_resolver = tfx.dsl.Resolver(
strategy_class=tfx.dsl.experimental.LatestBlessedModelStrategy,
model=tfx.dsl.Channel(type=tfx.types.standard_artifacts.Model),
model_blessing=tfx.dsl.Channel(
type=tfx.types.standard_artifacts.ModelBlessing)).with_id(
'latest_blessed_model_resolver')
context.run(model_resolver, enable_cache=True)
evaluator = tfx.components.Evaluator(
examples=example_gen.outputs['examples'],
model=trainer.outputs['model'],
baseline_model=model_resolver.outputs['model'],
eval_config=eval_config)
context.run(evaluator, enable_cache=True)
Explanation: 次に、この構成を Evaluatorに渡して実行します。
End of explanation
evaluator.outputs
Explanation: Evaluator の出力アーティファクトを調べてみましょう。
End of explanation
context.show(evaluator.outputs['evaluation'])
Explanation: evaluation出力を使用すると、評価セット全体のグローバル指標のデフォルトの視覚化を表示できます。
End of explanation
import tensorflow_model_analysis as tfma
# Get the TFMA output result path and load the result.
PATH_TO_RESULT = evaluator.outputs['evaluation'].get()[0].uri
tfma_result = tfma.load_eval_result(PATH_TO_RESULT)
# Show data sliced along feature column trip_start_hour.
tfma.view.render_slicing_metrics(
tfma_result, slicing_column='trip_start_hour')
Explanation: スライスされた評価メトリクスの視覚化を表示するには、TensorFlow Model Analysis ライブラリを直接呼び出します。
End of explanation
blessing_uri = evaluator.outputs['blessing'].get()[0].uri
!ls -l {blessing_uri}
Explanation: この視覚化は同じ指標を示していますが、評価セット全体ではなく、trip_start_hourのすべての特徴値で計算されています。
TensorFlow モデル分析は、公平性インジケーターやモデル パフォーマンスの時系列のプロットなど、他の多くの視覚化をサポートしています。 詳細については、チュートリアルを参照してください。
構成にしきい値を追加したため、検証出力も利用できます。{code 0}blessing{/code 0} アーティファクトの存在は、モデルが検証に合格したことを示しています。これは実行される最初の検証であるため、候補は自動的に bless されます。
End of explanation
PATH_TO_RESULT = evaluator.outputs['evaluation'].get()[0].uri
print(tfma.load_validation_result(PATH_TO_RESULT))
Explanation: 検証結果レコードを読み込み、成功を確認することもできます。
End of explanation
pusher = tfx.components.Pusher(
model=trainer.outputs['model'],
model_blessing=evaluator.outputs['blessing'],
push_destination=tfx.proto.PushDestination(
filesystem=tfx.proto.PushDestination.Filesystem(
base_directory=_serving_model_dir)))
context.run(pusher, enable_cache=True)
Explanation: Pusher
Pusher コンポーネントは通常、TFX パイプラインの最後にあります。このコンポーネントはモデルが検証に合格したかどうかをチェックし、合格した場合はモデルを _serving_model_dirにエクスポートします。
End of explanation
pusher.outputs
Explanation: 次にPusherの出力アーティファクトを調べてみましょう。
End of explanation
push_uri = pusher.outputs['pushed_model'].get()[0].uri
model = tf.saved_model.load(push_uri)
for item in model.signatures.items():
pp.pprint(item)
Explanation: 特に、Pusher はモデルを次のような SavedModel 形式でエクスポートします。
End of explanation |
7,931 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulating with FBA
Simulations using flux balance analysis can be solved using Model.optimize(). This will maximize or minimize (maximizing is the default) flux through the objective reactions.
Step1: Running FBA
Step2: The Model.optimize() function will return a Solution object. A solution object has several attributes
Step3: The solvers that can be used with cobrapy are so fast that for many small to mid-size models computing the solution can be even faster than it takes to collect the values from the solver and convert to them python objects. With model.optimize, we gather values for all reactions and metabolites and that can take a significant amount of time if done repeatedly. If we are only interested in the flux value of a single reaction or the objective, it is faster to instead use model.slim_optimize which only does the optimization and returns the objective value leaving it up to you to fetch other values that you may need.
Step4: Analyzing FBA solutions
Models solved using FBA can be further analyzed by using summary methods, which output printed text to give a quick representation of model behavior. Calling the summary method on the entire model displays information on the input and output behavior of the model, along with the optimized objective.
Step5: In addition, the input-output behavior of individual metabolites can also be inspected using summary methods. For instance, the following commands can be used to examine the overall redox balance of the model
Step6: Or to get a sense of the main energy production and consumption reactions
Step7: Changing the Objectives
The objective function is determined from the objective_coefficient attribute of the objective reaction(s). Generally, a "biomass" function which describes the composition of metabolites which make up a cell is used.
Step8: Currently in the model, there is only one reaction in the objective (the biomass reaction), with an linear coefficient of 1.
Step9: The objective function can be changed by assigning Model.objective, which can be a reaction object (or just it's name), or a dict of {Reaction
Step10: We can also have more complicated objectives including quadratic terms.
Running FVA
FBA will not give always give unique solution, because multiple flux states can achieve the same optimum. FVA (or flux variability analysis) finds the ranges of each metabolic flux at the optimum.
Step11: Setting parameter fraction_of_optimium=0.90 would give the flux ranges for reactions at 90% optimality.
Step12: The standard FVA may contain loops, i.e. high absolute flux values that only can be high if they are allowed to participate in loops (a mathematical artifact that cannot happen in vivo). Use the loopless argument to avoid such loops. Below, we can see that FRD7 and SUCDi reactions can participate in loops but that this is avoided when using the looplesss FVA.
Step13: Running FVA in summary methods
Flux variability analysis can also be embedded in calls to summary methods. For instance, the expected variability in substrate consumption and product formation can be quickly found by
Step14: Similarly, variability in metabolite mass balances can also be checked with flux variability analysis.
Step15: In these summary methods, the values are reported as a the center point +/- the range of the FVA solution, calculated from the maximum and minimum values.
Running pFBA
Parsimonious FBA (often written pFBA) finds a flux distribution which gives the optimal growth rate, but minimizes the total sum of flux. This involves solving two sequential linear programs, but is handled transparently by cobrapy. For more details on pFBA, please see Lewis et al. (2010).
Step16: These functions should give approximately the same objective value. | Python Code:
import cobra.test
model = cobra.test.create_test_model("textbook")
Explanation: Simulating with FBA
Simulations using flux balance analysis can be solved using Model.optimize(). This will maximize or minimize (maximizing is the default) flux through the objective reactions.
End of explanation
solution = model.optimize()
print(solution)
Explanation: Running FBA
End of explanation
solution.objective_value
Explanation: The Model.optimize() function will return a Solution object. A solution object has several attributes:
objective_value: the objective value
status: the status from the linear programming solver
fluxes: a pandas series with flux indexed by reaction identifier. The flux for a reaction variable is the difference of the primal values for the forward and reverse reaction variables.
shadow_prices: a pandas series with shadow price indexed by the metabolite identifier.
For example, after the last call to model.optimize(), if the optimization succeeds it's status will be optimal. In case the model is infeasible an error is raised.
End of explanation
%%time
model.optimize().objective_value
%%time
model.slim_optimize()
Explanation: The solvers that can be used with cobrapy are so fast that for many small to mid-size models computing the solution can be even faster than it takes to collect the values from the solver and convert to them python objects. With model.optimize, we gather values for all reactions and metabolites and that can take a significant amount of time if done repeatedly. If we are only interested in the flux value of a single reaction or the objective, it is faster to instead use model.slim_optimize which only does the optimization and returns the objective value leaving it up to you to fetch other values that you may need.
End of explanation
model.summary()
Explanation: Analyzing FBA solutions
Models solved using FBA can be further analyzed by using summary methods, which output printed text to give a quick representation of model behavior. Calling the summary method on the entire model displays information on the input and output behavior of the model, along with the optimized objective.
End of explanation
model.metabolites.nadh_c.summary()
Explanation: In addition, the input-output behavior of individual metabolites can also be inspected using summary methods. For instance, the following commands can be used to examine the overall redox balance of the model
End of explanation
model.metabolites.atp_c.summary()
Explanation: Or to get a sense of the main energy production and consumption reactions
End of explanation
biomass_rxn = model.reactions.get_by_id("Biomass_Ecoli_core")
Explanation: Changing the Objectives
The objective function is determined from the objective_coefficient attribute of the objective reaction(s). Generally, a "biomass" function which describes the composition of metabolites which make up a cell is used.
End of explanation
from cobra.util.solver import linear_reaction_coefficients
linear_reaction_coefficients(model)
Explanation: Currently in the model, there is only one reaction in the objective (the biomass reaction), with an linear coefficient of 1.
End of explanation
# change the objective to ATPM
model.objective = "ATPM"
# The upper bound should be 1000, so that we get
# the actual optimal value
model.reactions.get_by_id("ATPM").upper_bound = 1000.
linear_reaction_coefficients(model)
model.optimize().objective_value
Explanation: The objective function can be changed by assigning Model.objective, which can be a reaction object (or just it's name), or a dict of {Reaction: objective_coefficient}.
End of explanation
from cobra.flux_analysis import flux_variability_analysis
flux_variability_analysis(model, model.reactions[:10])
Explanation: We can also have more complicated objectives including quadratic terms.
Running FVA
FBA will not give always give unique solution, because multiple flux states can achieve the same optimum. FVA (or flux variability analysis) finds the ranges of each metabolic flux at the optimum.
End of explanation
cobra.flux_analysis.flux_variability_analysis(
model, model.reactions[:10], fraction_of_optimum=0.9)
Explanation: Setting parameter fraction_of_optimium=0.90 would give the flux ranges for reactions at 90% optimality.
End of explanation
loop_reactions = [model.reactions.FRD7, model.reactions.SUCDi]
flux_variability_analysis(model, reaction_list=loop_reactions, loopless=False)
flux_variability_analysis(model, reaction_list=loop_reactions, loopless=True)
Explanation: The standard FVA may contain loops, i.e. high absolute flux values that only can be high if they are allowed to participate in loops (a mathematical artifact that cannot happen in vivo). Use the loopless argument to avoid such loops. Below, we can see that FRD7 and SUCDi reactions can participate in loops but that this is avoided when using the looplesss FVA.
End of explanation
model.optimize()
model.summary(fva=0.95)
Explanation: Running FVA in summary methods
Flux variability analysis can also be embedded in calls to summary methods. For instance, the expected variability in substrate consumption and product formation can be quickly found by
End of explanation
model.metabolites.pyr_c.summary(fva=0.95)
Explanation: Similarly, variability in metabolite mass balances can also be checked with flux variability analysis.
End of explanation
model.objective = 'Biomass_Ecoli_core'
fba_solution = model.optimize()
pfba_solution = cobra.flux_analysis.pfba(model)
Explanation: In these summary methods, the values are reported as a the center point +/- the range of the FVA solution, calculated from the maximum and minimum values.
Running pFBA
Parsimonious FBA (often written pFBA) finds a flux distribution which gives the optimal growth rate, but minimizes the total sum of flux. This involves solving two sequential linear programs, but is handled transparently by cobrapy. For more details on pFBA, please see Lewis et al. (2010).
End of explanation
abs(fba_solution.fluxes["Biomass_Ecoli_core"] - pfba_solution.fluxes[
"Biomass_Ecoli_core"])
Explanation: These functions should give approximately the same objective value.
End of explanation |
7,932 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Two Tables, Criminals And Crimes
Step2: Inner Join
Returns all rows whose merge-on id appears in both tables.
Step3: Left Join
Returns all rows from the left table but only the rows from the right left that match the left table. | Python Code:
# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False
Explanation: Title: Merge Tables
Slug: merge_tables
Summary: Merge tables in SQL.
Date: 2016-05-01 12:00
Category: SQL
Tags: Basics
Authors: Chris Albon
Note: This tutorial was written using Catherine Devlin's SQL in Jupyter Notebooks library. If you have not using a Jupyter Notebook, you can ignore the two lines of code below and any line containing %%sql. Furthermore, this tutorial uses SQLite's flavor of SQL, your version might have some differences in syntax.
For more, check out Learning SQL by Alan Beaulieu.
End of explanation
%%sql
-- Create a table of criminals
CREATE TABLE criminals (pid, name, age, sex, city, minor);
INSERT INTO criminals VALUES (412, 'James Smith', 15, 'M', 'Santa Rosa', 1);
INSERT INTO criminals VALUES (234, 'Bill James', 22, 'M', 'Santa Rosa', 0);
INSERT INTO criminals VALUES (632, 'Stacy Miller', 23, 'F', 'Santa Rosa', 0);
INSERT INTO criminals VALUES (621, 'Betty Bob', NULL, 'F', 'Petaluma', 1);
INSERT INTO criminals VALUES (162, 'Jaden Ado', 49, 'M', NULL, 0);
INSERT INTO criminals VALUES (901, 'Gordon Ado', 32, 'F', 'Santa Rosa', 0);
INSERT INTO criminals VALUES (512, 'Bill Byson', 21, 'M', 'Santa Rosa', 0);
INSERT INTO criminals VALUES (411, 'Bob Iton', NULL, 'M', 'San Francisco', 0);
-- Create a table of crimes
CREATE TABLE crimes (cid, crime, city, pid_arrested, cash_stolen);
INSERT INTO crimes VALUES (1, 'fraud', 'Santa Rosa', 412, 40000);
INSERT INTO crimes VALUES (2, 'burglary', 'Petaluma', 234, 2000);
INSERT INTO crimes VALUES (3, 'burglary', 'Santa Rosa', 632, 2000);
INSERT INTO crimes VALUES (4, NULL, NULL, 621, 3500);
INSERT INTO crimes VALUES (5, 'burglary', 'Santa Rosa', 162, 1000);
INSERT INTO crimes VALUES (6, NULL, 'Petaluma', 901, 50000);
INSERT INTO crimes VALUES (7, 'fraud', 'San Francisco', 412, 60000);
INSERT INTO crimes VALUES (8, 'burglary', 'Santa Rosa', 512, 7000);
INSERT INTO crimes VALUES (9, 'burglary', 'San Francisco', 411, 3000);
INSERT INTO crimes VALUES (10, 'robbery', 'Santa Rosa', 632, 2500);
INSERT INTO crimes VALUES (11, 'robbery', 'Santa Rosa', 512, 3000);
Explanation: Create Two Tables, Criminals And Crimes
End of explanation
%%sql
-- Select everything
SELECT *
-- Left table
FROM criminals
-- Right table
INNER JOIN crimes
-- Merged on `pid` in the criminals table and `pid_arrested` in the crimes table
ON criminals.pid=crimes.pid_arrested;
Explanation: Inner Join
Returns all rows whose merge-on id appears in both tables.
End of explanation
%%sql
-- Select everything
SELECT *
-- Left table
FROM criminals
-- Right table
LEFT JOIN crimes
-- Merged on `pid` in the criminals table and `pid_arrested` in the crimes table
ON criminals.pid=crimes.pid_arrested;
Explanation: Left Join
Returns all rows from the left table but only the rows from the right left that match the left table.
End of explanation |
7,933 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstration of the topic coherence pipeline in Gensim
Introduction
We will be using the u_mass and c_v coherence for two different LDA models
Step1: Set up logging
Step2: Set up corpus
As stated in table 2 from this paper, this corpus essentially has two classes of documents. First five are about human-computer interaction and the other four are about graphs. We will be setting up two LDA models. One with 50 iterations of training and the other with just 1. Hence the one with 50 iterations ("better" model) should be able to capture this underlying pattern of the corpus better than the "bad" LDA model. Therefore, in theory, our topic coherence for the good LDA model should be greater than the one for the bad LDA model.
Step3: Set up two topic models
We'll be setting up two different LDA Topic models. A good one and bad one. To build a "good" topic model, we'll simply train it using more iterations than the bad one. Therefore the u_mass coherence should in theory be better for the good model than the bad one since it would be producing more "human-interpretable" topics.
Step4: Using U_Mass Coherence
Step5: View the pipeline parameters for one coherence model
Following are the pipeline parameters for u_mass coherence. By pipeline parameters, we mean the functions being used to calculate segmentation, probability estimation, confirmation measure and aggregation as shown in figure 1 in this paper.
Step6: Interpreting the topics
As we will see below using LDA visualization, the better model comes up with two topics composed of the following words
Step7: Using C_V coherence
Step8: Pipeline parameters for C_V coherence
Step9: Print coherence values
Step10: Support for wrappers
This API supports gensim's ldavowpalwabbit and ldamallet wrappers as input parameter to model.
Step11: Support for other topic models
The gensim topics coherence pipeline can be used with other topics models too. Only the tokenized topics should be made available for the pipeline. Eg. with the gensim HDP model | Python Code:
import numpy as np
import logging
try:
import pyLDAvis.gensim
except ImportError:
ValueError("SKIP: please install pyLDAvis")
import json
import warnings
warnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity
from gensim.models.coherencemodel import CoherenceModel
from gensim.models.ldamodel import LdaModel
from gensim.models.hdpmodel import HdpModel
from gensim.models.wrappers import LdaVowpalWabbit, LdaMallet
from gensim.corpora.dictionary import Dictionary
from numpy import array
Explanation: Demonstration of the topic coherence pipeline in Gensim
Introduction
We will be using the u_mass and c_v coherence for two different LDA models: a "good" and a "bad" LDA model. The good LDA model will be trained over 50 iterations and the bad one for 1 iteration. Hence in theory, the good LDA model will be able come up with better or more human-understandable topics. Therefore the coherence measure output for the good LDA model should be more (better) than that for the bad LDA model. This is because, simply, the good LDA model usually comes up with better topics that are more human interpretable.
End of explanation
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.debug("test")
Explanation: Set up logging
End of explanation
texts = [['human', 'interface', 'computer'],
['survey', 'user', 'computer', 'system', 'response', 'time'],
['eps', 'user', 'interface', 'system'],
['system', 'human', 'system', 'eps'],
['user', 'response', 'time'],
['trees'],
['graph', 'trees'],
['graph', 'minors', 'trees'],
['graph', 'minors', 'survey']]
dictionary = Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
Explanation: Set up corpus
As stated in table 2 from this paper, this corpus essentially has two classes of documents. First five are about human-computer interaction and the other four are about graphs. We will be setting up two LDA models. One with 50 iterations of training and the other with just 1. Hence the one with 50 iterations ("better" model) should be able to capture this underlying pattern of the corpus better than the "bad" LDA model. Therefore, in theory, our topic coherence for the good LDA model should be greater than the one for the bad LDA model.
End of explanation
goodLdaModel = LdaModel(corpus=corpus, id2word=dictionary, iterations=50, num_topics=2)
badLdaModel = LdaModel(corpus=corpus, id2word=dictionary, iterations=1, num_topics=2)
Explanation: Set up two topic models
We'll be setting up two different LDA Topic models. A good one and bad one. To build a "good" topic model, we'll simply train it using more iterations than the bad one. Therefore the u_mass coherence should in theory be better for the good model than the bad one since it would be producing more "human-interpretable" topics.
End of explanation
goodcm = CoherenceModel(model=goodLdaModel, corpus=corpus, dictionary=dictionary, coherence='u_mass')
badcm = CoherenceModel(model=badLdaModel, corpus=corpus, dictionary=dictionary, coherence='u_mass')
Explanation: Using U_Mass Coherence
End of explanation
print goodcm
Explanation: View the pipeline parameters for one coherence model
Following are the pipeline parameters for u_mass coherence. By pipeline parameters, we mean the functions being used to calculate segmentation, probability estimation, confirmation measure and aggregation as shown in figure 1 in this paper.
End of explanation
pyLDAvis.enable_notebook()
pyLDAvis.gensim.prepare(goodLdaModel, corpus, dictionary)
pyLDAvis.gensim.prepare(badLdaModel, corpus, dictionary)
print goodcm.get_coherence()
print badcm.get_coherence()
Explanation: Interpreting the topics
As we will see below using LDA visualization, the better model comes up with two topics composed of the following words:
1. goodLdaModel:
- Topic 1: More weightage assigned to words such as "system", "user", "eps", "interface" etc which captures the first set of documents.
- Topic 2: More weightage assigned to words such as "graph", "trees", "survey" which captures the topic in the second set of documents.
2. badLdaModel:
- Topic 1: More weightage assigned to words such as "system", "user", "trees", "graph" which doesn't make the topic clear enough.
- Topic 2: More weightage assigned to words such as "system", "trees", "graph", "user" which is similar to the first topic. Hence both topics are not human-interpretable.
Therefore, the topic coherence for the goodLdaModel should be greater for this than the badLdaModel since the topics it comes up with are more human-interpretable. We will see this using u_mass and c_v topic coherence measures.
Visualize topic models
End of explanation
goodcm = CoherenceModel(model=goodLdaModel, texts=texts, dictionary=dictionary, coherence='c_v')
badcm = CoherenceModel(model=badLdaModel, texts=texts, dictionary=dictionary, coherence='c_v')
Explanation: Using C_V coherence
End of explanation
print goodcm
Explanation: Pipeline parameters for C_V coherence
End of explanation
print goodcm.get_coherence()
print badcm.get_coherence()
Explanation: Print coherence values
End of explanation
model1 = LdaVowpalWabbit('/home/devashish/vw-8', corpus=corpus, num_topics=2, id2word=dictionary, passes=50)
model2 = LdaVowpalWabbit('/home/devashish/vw-8', corpus=corpus, num_topics=2, id2word=dictionary, passes=1)
cm1 = CoherenceModel(model=model1, corpus=corpus, coherence='u_mass')
cm2 = CoherenceModel(model=model2, corpus=corpus, coherence='u_mass')
print cm1.get_coherence()
print cm2.get_coherence()
model1 = LdaMallet('/home/devashish/mallet-2.0.8RC3/bin/mallet',corpus=corpus , num_topics=2, id2word=dictionary, iterations=50)
model2 = LdaMallet('/home/devashish/mallet-2.0.8RC3/bin/mallet',corpus=corpus , num_topics=2, id2word=dictionary, iterations=1)
cm1 = CoherenceModel(model=model1, texts=texts, coherence='c_v')
cm2 = CoherenceModel(model=model2, texts=texts, coherence='c_v')
print cm1.get_coherence()
print cm2.get_coherence()
Explanation: Support for wrappers
This API supports gensim's ldavowpalwabbit and ldamallet wrappers as input parameter to model.
End of explanation
hm = HdpModel(corpus=corpus, id2word=dictionary)
# To get the topic words from the model
topics = []
for topic_id, topic in hm.show_topics(num_topics=10, formatted=False):
topic = [word for word, _ in topic]
topics.append(topic)
topics[:2]
# Initialize CoherenceModel using `topics` parameter
cm = CoherenceModel(topics=topics, corpus=corpus, dictionary=dictionary, coherence='u_mass')
cm.get_coherence()
Explanation: Support for other topic models
The gensim topics coherence pipeline can be used with other topics models too. Only the tokenized topics should be made available for the pipeline. Eg. with the gensim HDP model
End of explanation |
7,934 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homogenization with fiber-like structures
Introduction
This example demonstrates the use of the homogenization model from pyMKS on a set of fiber-like structures. These structures are simulated to emulate fiber-reinforced polymer samples. For a summary of homogenization theory and its use with effective stiffness properties please see the Effective Siffness example. This example will first generate a series of random microstructures with various fiber lengths and volume fraction. The ability to vary the volume fraction is a new functionality of this example. Then the generated stuctures will be used to calibrate and test the model based on simulated effective stress values. Finally we will show that the simulated response compare favorably with those generated by the model.
Generating Structures
These first lines inport important packages that will be used to run pymks.
Step1: Now we are defining the parameters which we will use to create the microstructures. n_samples will determine how many microstructures of a particular volume fraction we want to create. size determines the number of pixels we want to be included in the microstructure. We will define the material properties to be used in the finite element in elastic_modulus, poissons_ratio and macro_strain. n_phases and grain_size will determine the physical characteristics of the microstructure. We are using a high aspect ratio in creating our microstructures to simulate fiber-like structures. The volume_fraction variable will be used to vary the fraction of each phase. The sum of the volume fractions must be equal to 1. The percent_variance variable introduces some variation in the volume fraction up to the specified percentage.
Step2: Now we will create the microstructures and generate their responses using the make_elastic_stress_random function from pyMKS. Four datasets are created to create the four different volume fractions that we are simulating. Then the datasets are combined into one variable. The volume fractions are listed in the variable v_frac. Variation around the specified volume fraction can be obtained by varying per_ch. The variation is randomly generated according a uniform distribution around the specified volume fraction.
Step3: Now we are going to print out a few microstructres to look at how the fiber length, orientation and volume fraction are varied.
Step4: Creating the Model
Next we are going to initiate the model. The MKSHomogenizationModel takes in microstructures and runs two-point statistics on them to get a statistical representation of the microstructures. An expalnation of the use of two-point statistics can be found in the Checkerboard Microstructure Example. Then the model uses PCA and regression models to create a linkage between the calcualted properties and structures.
Here we simply initiate the model.
Step5: Now we are going to split our data into testing and training segments so we can test and see if our model is effective. In a previous example we used sklearn to optimize the n_components and degree but for this example we will just use 4 components and a second order regression. Then we fit the model with our training data.
Step6: Structures in PCA space
Now we want to draw how the samples are spread out in PCA space and look at how the testing and training data line up.
Step7: It looks like there is pretty good agreement between the testing and the training data. We can also see that the four different fiber sizes are seperated in the PC space.
Draw Goodness of fit
Now we are going to look at how well our model predicts the properties of the structures. The calculated properties will be plotted against the properties generated by the model. We should see a linear realtionship with a slope of 1. | Python Code:
import numpy as np
%matplotlib inline
%load_ext autoreload
%autoreload 2
import matplotlib.pyplot as plt
Explanation: Homogenization with fiber-like structures
Introduction
This example demonstrates the use of the homogenization model from pyMKS on a set of fiber-like structures. These structures are simulated to emulate fiber-reinforced polymer samples. For a summary of homogenization theory and its use with effective stiffness properties please see the Effective Siffness example. This example will first generate a series of random microstructures with various fiber lengths and volume fraction. The ability to vary the volume fraction is a new functionality of this example. Then the generated stuctures will be used to calibrate and test the model based on simulated effective stress values. Finally we will show that the simulated response compare favorably with those generated by the model.
Generating Structures
These first lines inport important packages that will be used to run pymks.
End of explanation
sample_size = 100
n_samples = 4 * [sample_size]
size = (101, 101)
elastic_modulus = (1.3, 75)
poissons_ratio = (0.42, .22)
macro_strain = 0.001
n_phases = 2
grain_size = [(40, 2), (10, 2), (2, 40), (2, 10)]
v_frac = [(0.7, 0.3), (0.6, 0.4), (0.3, 0.7), (0.4, 0.6)]
per_ch = 0.1
Explanation: Now we are defining the parameters which we will use to create the microstructures. n_samples will determine how many microstructures of a particular volume fraction we want to create. size determines the number of pixels we want to be included in the microstructure. We will define the material properties to be used in the finite element in elastic_modulus, poissons_ratio and macro_strain. n_phases and grain_size will determine the physical characteristics of the microstructure. We are using a high aspect ratio in creating our microstructures to simulate fiber-like structures. The volume_fraction variable will be used to vary the fraction of each phase. The sum of the volume fractions must be equal to 1. The percent_variance variable introduces some variation in the volume fraction up to the specified percentage.
End of explanation
from pymks.datasets import make_elastic_stress_random
dataset, stresses = make_elastic_stress_random(n_samples=n_samples, size=size, grain_size=grain_size,
elastic_modulus=elastic_modulus, poissons_ratio=poissons_ratio,
macro_strain=macro_strain, volume_fraction=v_frac,
percent_variance=per_ch)
Explanation: Now we will create the microstructures and generate their responses using the make_elastic_stress_random function from pyMKS. Four datasets are created to create the four different volume fractions that we are simulating. Then the datasets are combined into one variable. The volume fractions are listed in the variable v_frac. Variation around the specified volume fraction can be obtained by varying per_ch. The variation is randomly generated according a uniform distribution around the specified volume fraction.
End of explanation
from pymks.tools import draw_microstructures
examples = dataset[::sample_size]
draw_microstructures(examples)
Explanation: Now we are going to print out a few microstructres to look at how the fiber length, orientation and volume fraction are varied.
End of explanation
from pymks import MKSHomogenizationModel
from pymks import PrimitiveBasis
p_basis = PrimitiveBasis(n_states=2, domain=[0, 1])
model = MKSHomogenizationModel(basis=p_basis, correlations=[(0, 0)])
Explanation: Creating the Model
Next we are going to initiate the model. The MKSHomogenizationModel takes in microstructures and runs two-point statistics on them to get a statistical representation of the microstructures. An expalnation of the use of two-point statistics can be found in the Checkerboard Microstructure Example. Then the model uses PCA and regression models to create a linkage between the calcualted properties and structures.
Here we simply initiate the model.
End of explanation
from sklearn.cross_validation import train_test_split
flat_shape = (dataset.shape[0],) + (np.prod(dataset.shape[1:]),)
data_train, data_test, stress_train, stress_test = train_test_split(
dataset.reshape(flat_shape), stresses, test_size=0.2, random_state=3)
model.n_components = 6
model.degree = 3
shapes = (data_test.shape[0],) + (dataset.shape[1:])
shapes2 = (data_train.shape[0],) + (dataset.shape[1:])
data_train = data_train.reshape(shapes2)
data_test = data_test.reshape(shapes)
model.fit(data_train, stress_train, periodic_axes=[0, 1])
Explanation: Now we are going to split our data into testing and training segments so we can test and see if our model is effective. In a previous example we used sklearn to optimize the n_components and degree but for this example we will just use 4 components and a second order regression. Then we fit the model with our training data.
End of explanation
from pymks.tools import draw_components
stress_predict = model.predict(data_test, periodic_axes=[0, 1])
draw_components([model.fit_data[:, :3],
model.reduced_predict_data[:, :3]],
['Training Data', 'Testing Data'])
Explanation: Structures in PCA space
Now we want to draw how the samples are spread out in PCA space and look at how the testing and training data line up.
End of explanation
from pymks.tools import draw_goodness_of_fit
fit_data = np.array([stresses, model.predict(dataset, periodic_axes=[0, 1])])
pred_data = np.array([stress_test, stress_predict])
draw_goodness_of_fit(fit_data, pred_data, ['Training Data', 'Testing Data'])
Explanation: It looks like there is pretty good agreement between the testing and the training data. We can also see that the four different fiber sizes are seperated in the PC space.
Draw Goodness of fit
Now we are going to look at how well our model predicts the properties of the structures. The calculated properties will be plotted against the properties generated by the model. We should see a linear realtionship with a slope of 1.
End of explanation |
7,935 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decoding sensor space data with generalization across time and conditions
This example runs the analysis described in
Step1: We will train the classifier on all left visual vs auditory trials
and test on all right visual vs auditory trials.
Step2: Score on the epochs where the stimulus was presented to the right.
Step3: Plot | Python Code:
# Authors: Jean-Remi King <jeanremi.king@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD-3-Clause
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
import mne
from mne.datasets import sample
from mne.decoding import GeneralizingEstimator
print(__doc__)
# Preprocess data
data_path = sample.data_path()
# Load and filter data, set up epochs
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
events_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
raw = mne.io.read_raw_fif(raw_fname, preload=True)
picks = mne.pick_types(raw.info, meg=True, exclude='bads') # Pick MEG channels
raw.filter(1., 30., fir_design='firwin') # Band pass filtering signals
events = mne.read_events(events_fname)
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2,
'Visual/Left': 3, 'Visual/Right': 4}
tmin = -0.050
tmax = 0.400
# decimate to make the example faster to run, but then use verbose='error' in
# the Epochs constructor to suppress warning about decimation causing aliasing
decim = 2
epochs = mne.Epochs(raw, events, event_id=event_id, tmin=tmin, tmax=tmax,
proj=True, picks=picks, baseline=None, preload=True,
reject=dict(mag=5e-12), decim=decim, verbose='error')
Explanation: Decoding sensor space data with generalization across time and conditions
This example runs the analysis described in :footcite:KingDehaene2014. It
illustrates how one can
fit a linear classifier to identify a discriminatory topography at a given time
instant and subsequently assess whether this linear model can accurately
predict all of the time samples of a second set of conditions.
End of explanation
clf = make_pipeline(StandardScaler(), LogisticRegression(solver='lbfgs'))
time_gen = GeneralizingEstimator(clf, scoring='roc_auc', n_jobs=1,
verbose=True)
# Fit classifiers on the epochs where the stimulus was presented to the left.
# Note that the experimental condition y indicates auditory or visual
time_gen.fit(X=epochs['Left'].get_data(),
y=epochs['Left'].events[:, 2] > 2)
Explanation: We will train the classifier on all left visual vs auditory trials
and test on all right visual vs auditory trials.
End of explanation
scores = time_gen.score(X=epochs['Right'].get_data(),
y=epochs['Right'].events[:, 2] > 2)
Explanation: Score on the epochs where the stimulus was presented to the right.
End of explanation
fig, ax = plt.subplots(1)
im = ax.matshow(scores, vmin=0, vmax=1., cmap='RdBu_r', origin='lower',
extent=epochs.times[[0, -1, 0, -1]])
ax.axhline(0., color='k')
ax.axvline(0., color='k')
ax.xaxis.set_ticks_position('bottom')
ax.set_xlabel('Testing Time (s)')
ax.set_ylabel('Training Time (s)')
ax.set_title('Generalization across time and condition')
plt.colorbar(im, ax=ax)
plt.show()
Explanation: Plot
End of explanation |
7,936 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to bruges
This page gives a quick look at some of the things bruges can do.
This library does all sorts of things so it's hard to show you a single workflow and say, "here's how to use bruges". But making a simple wedge model will let us show you several features, and maybe it will help you see how to use bruges in your own work.
Seismic wedge models provide seismic interpreters a quantitative way of studying thin-bed stratigraphy at or below seismic resolution. Here's the workflow
Step1: The wedge function returns a tuple containing the model m, as well as the a top, base and ref denoting some key boundaries in the model. Let's put these objects on a plot.
Step2: The model m is a 2-D NumPy array where each element is an index corresponding to each layer. The purple layer region has 0, the green layer has 1 and the yellow layer is 2 . top and base, shown in red, are the depths down to the "top" of wedge layer and "base" of the wedge layer respectively. ref stands for "reference trace" and it denotes the position where the wedge has a thickness factor of 1.
Make an earth
The model is filled with integers, but the earth is filled with rock properties. We need to replace those integers with rock properties.
Let's define P-wave velocity, S-wave velocity, and rho (density) for our 3 rock types
Step3: We can use these to make vp and rho earth models. We can use NumPy's fancy indexing by passing our array of indicies to access the rock properties (in this case acoustic impedance) for every element at once.
Step4: And plot the acoustic impedance to check it looks reasonable
Step5: Acoustic reflectivity
We don't actually need impedance, we need reflectivity. We can use bruges to create a section of normal incidence reflection coefficient; this will be what we convolve with a wavelet.
Here's how to get the acoustic reflectivity
Step6: The reflections coeffients are zero almost everywhere, except at the layer boundaries. The reflection coefficient between layer 1 and layer 2 is a negative, and between layer 2 and layer 3 is a positive number. This will determine the scale and polarity of the seismic amplitudes.
Offset reflectivity
We can also calculate the exact Zoeppritz offset reflectivity. For example, to compute the reflectivity at 10 degrees of offset — note that this results in complex numbers, so we'll only use the real part in the plot
Step7: As with the elastic impedance calculation, we can create a range of angles at once
Step8: The 10-degree reflectivity we computed before is in there as rc[10], but we can also see how reflectivity varies with angle
Step9: A 1D wavelet
Let's create a Ricker wavelet to serve as our seismic pulse. We specify it has a length of 0.256 s, a sample interval of 0.002 s, and corner frequencies of 8, 12, 20, and 40 Hz
Step10: A 2D wavelet bank
There are several wavelet functions; they can all take a sequence of frequencies and produce all of them at once as a filter bank
Step11: A 1D convolution
We can use bruges to perform a convolution.
Remember our RC series is 3D. Let's keep it simple for now and look at a single waveform from the reference location ref in our model. The synthetic seismic trace is band-limited filtering of the reflectivity spikes. When these spikes get closer together the waveforms will "tune" with one another and won't necessarily line up with the reflectivity series.
Step12: In the 1D case, it would have been easy enough to use np.convolve to do this. The equivalent code is
Step13: Remember those are offsets in the first dimension. Let's look at the zero-offset synthetic alongside the 30-degree panel
Step14: Or we could look at a single 'angle gather'
Step15: Bend your mind
The convolution function will also accept a filter bank (a collection of wavelets at different frequencies). We made one earlier called w_bank.
Watch out
Step16: Notice that the time axis has moved back to dimension 2 as a result of the wavelet having two dimensions
Step17: But we could also look at how the amplitude varies in the stratigraphic middle (timeslice 50) of the thickest part of the wedge (trace ref), when we vary frequency and offset | Python Code:
import bruges as bg
m, top, base, ref = bg.models.wedge(width=120)
Explanation: Welcome to bruges
This page gives a quick look at some of the things bruges can do.
This library does all sorts of things so it's hard to show you a single workflow and say, "here's how to use bruges". But making a simple wedge model will let us show you several features, and maybe it will help you see how to use bruges in your own work.
Seismic wedge models provide seismic interpreters a quantitative way of studying thin-bed stratigraphy at or below seismic resolution. Here's the workflow:
Define the layer geometries.
Give those layers rock properties.
Calculate reflection coefficients.
Make a seismic wavelet.
Model the seismic response by convolving the reflectivities with the wavelet.
Let's get started!
Make a wedge
The wedge function in models submodule allows you to generate a variety of stratigraphic geometries. The default gives us a model m which is a 2-D NumPy array of size (100, 100). It has 3 layers in it.
End of explanation
import matplotlib.pyplot as plt
plt.imshow(m)
plt.plot(top, 'r', lw=4)
plt.plot(base, 'r', lw=4)
plt.axvline(ref, c='k', ls='--')
plt.show()
Explanation: The wedge function returns a tuple containing the model m, as well as the a top, base and ref denoting some key boundaries in the model. Let's put these objects on a plot.
End of explanation
import numpy as np
vps = np.array([2320, 2350, 2350])
vss = np.array([1150, 1250, 1200])
rhos = np.array([2650, 2600, 2620])
Explanation: The model m is a 2-D NumPy array where each element is an index corresponding to each layer. The purple layer region has 0, the green layer has 1 and the yellow layer is 2 . top and base, shown in red, are the depths down to the "top" of wedge layer and "base" of the wedge layer respectively. ref stands for "reference trace" and it denotes the position where the wedge has a thickness factor of 1.
Make an earth
The model is filled with integers, but the earth is filled with rock properties. We need to replace those integers with rock properties.
Let's define P-wave velocity, S-wave velocity, and rho (density) for our 3 rock types:
End of explanation
vp = vps[m]
vs = vss[m]
rho = rhos[m]
Explanation: We can use these to make vp and rho earth models. We can use NumPy's fancy indexing by passing our array of indicies to access the rock properties (in this case acoustic impedance) for every element at once.
End of explanation
impedance = vp * rho
plt.imshow(impedance, interpolation='none')
plt.colorbar()
plt.show()
Explanation: And plot the acoustic impedance to check it looks reasonable:
End of explanation
rc = bg.reflection.acoustic_reflectivity(vp, rho)
plt.imshow(rc)
plt.colorbar()
plt.show()
Explanation: Acoustic reflectivity
We don't actually need impedance, we need reflectivity. We can use bruges to create a section of normal incidence reflection coefficient; this will be what we convolve with a wavelet.
Here's how to get the acoustic reflectivity:
End of explanation
rc_10 = bg.reflection.reflectivity(vp, vs, rho, theta=10)
plt.imshow(rc_10.real)
plt.colorbar()
plt.show()
Explanation: The reflections coeffients are zero almost everywhere, except at the layer boundaries. The reflection coefficient between layer 1 and layer 2 is a negative, and between layer 2 and layer 3 is a positive number. This will determine the scale and polarity of the seismic amplitudes.
Offset reflectivity
We can also calculate the exact Zoeppritz offset reflectivity. For example, to compute the reflectivity at 10 degrees of offset — note that this results in complex numbers, so we'll only use the real part in the plot:
End of explanation
rc = bg.reflection.reflectivity(vp, vs, rho, theta=np.arange(60), method='shuey')
rc.shape
Explanation: As with the elastic impedance calculation, we can create a range of angles at once:
End of explanation
offset = 10 # degrees
trace = 60
fig, axs = plt.subplots(ncols=2, figsize=(12, 5), sharey=True)
axs[0].imshow(rc[offset].real, vmin=-0.01, vmax=0.01)
axs[0].axvline(trace, c='k', ls='--')
axs[1].imshow(rc[:, :, trace].real.T, vmin=-0.01, vmax=0.01)
axs[1].axvline(offset, c='k', ls='--')
plt.show()
Explanation: The 10-degree reflectivity we computed before is in there as rc[10], but we can also see how reflectivity varies with angle:
End of explanation
w, t = bg.filters.ricker(0.064, 0.001, 40)
plt.plot(t, w)
Explanation: A 1D wavelet
Let's create a Ricker wavelet to serve as our seismic pulse. We specify it has a length of 0.256 s, a sample interval of 0.002 s, and corner frequencies of 8, 12, 20, and 40 Hz:
End of explanation
w_bank, t = bg.filters.ricker(0.096, 0.001, np.arange(12, 80))
plt.imshow(w_bank)
plt.xlabel('time [samples]')
plt.ylabel('frequency [Hz]')
Explanation: A 2D wavelet bank
There are several wavelet functions; they can all take a sequence of frequencies and produce all of them at once as a filter bank:
End of explanation
rc_ref = rc[0, :, ref]
syn = bg.filters.convolve(rc_ref, w)
plt.plot(rc_ref)
plt.plot(syn)
plt.show()
Explanation: A 1D convolution
We can use bruges to perform a convolution.
Remember our RC series is 3D. Let's keep it simple for now and look at a single waveform from the reference location ref in our model. The synthetic seismic trace is band-limited filtering of the reflectivity spikes. When these spikes get closer together the waveforms will "tune" with one another and won't necessarily line up with the reflectivity series.
End of explanation
syn = bg.filters.convolve(rc, w, axis=1)
syn.shape
Explanation: In the 1D case, it would have been easy enough to use np.convolve to do this. The equivalent code is:
syn = np.convolve(rc_ref, w, mode='same')
2D convolution
But when the reflectivity is two-dimensional (or more!), you need to use np.apply_along_axis or some other trick to essentially loop over the traces. But don't worry! The bruges function will compute the convolution for you over all of the dimensions at once.
There's a small catch, because of how models are organized. For plotting convenience, time is on the first axis of a model slice or profile, not the last axis (as is usual with, say, seismic data — with the result that you typically have to transpose such data for display). So we have to tell the convolve() function which is our Z (time) axis:
End of explanation
# A quick way to set a sensible max, so both panels have the same colours.
ma = np.percentile(syn, 99.9)
near, far = 0, 30
fig, axs = plt.subplots(ncols=2, figsize=(12, 5))
axs[0].imshow(syn[near], cmap='seismic_r', vmin=-ma, vmax=ma)
axs[0].set_title(f'{near} degrees')
axs[1].imshow(syn[far], cmap='seismic_r', vmin=-ma, vmax=ma)
axs[1].set_title(f'{far} degrees')
plt.show()
Explanation: Remember those are offsets in the first dimension. Let's look at the zero-offset synthetic alongside the 30-degree panel:
End of explanation
trace = 70
plt.imshow(syn[:, :, trace].T)
plt.xlabel('angle')
Explanation: Or we could look at a single 'angle gather':
End of explanation
syn = bg.filters.convolve(rc, w_bank, axis=1)
syn.shape
Explanation: Bend your mind
The convolution function will also accept a filter bank (a collection of wavelets at different frequencies). We made one earlier called w_bank.
Watch out: the result of this convolution will be 4-dimensional!
End of explanation
plt.imshow(syn[10, 30])
Explanation: Notice that the time axis has moved back to dimension 2 as a result of the wavelet having two dimensions: its frequency dimension is now in dimension 0 of the array.
So we can look at the synthetic created with a 22 Hz wavelet (the wavelet bank started at 12 Hz, so this is slice 10 in the first dimension), and at 30 degrees of offset (slice 30 in the second dimension):
End of explanation
plt.imshow(syn[:, :, 50, ref])
plt.xlabel('offset')
plt.ylabel('frequency')
Explanation: But we could also look at how the amplitude varies in the stratigraphic middle (timeslice 50) of the thickest part of the wedge (trace ref), when we vary frequency and offset:
End of explanation |
7,937 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Python-Pi-Day-2017" data-toc-modified-id="Python-Pi-Day-2017-1"><span class="toc-item-num">1 </span>Python Pi Day 2017</a></div><div class="lev1 toc-item"><a href="#Computing-a-lot-of-digits-of-$\pi$?" data-toc-modified-id="Computing-a-lot-of-digits-of-$\pi$?-2"><span class="toc-item-num">2 </span>Computing a lot of digits of <span class="MathJax_Preview" style="color
Step1: This method is extremely limited, and will not give you more than 13 correct digits, as math.pi is stored as a float number (limited precision).
Step2: If we know the digits, we can directly print them
Step4: A simple Monte-Carlo method
A simple Monte Carlo method for computing $\pi$ is to draw a circle inscribed in a square, and randomly place dots in the square.
The ratio of dots inside the circle to the total number of dots will approximately equal $\pi / 4$, which is also the ratio of the area of the circle by the area of the square
Step5: It is an interesting method, but it is just too limited for approximating digits of $\pi$.
The previous two methods are quite limited, and not efficient enough if you want more than 13 digits (resp. 4 digits for the Monte-Carlo method).
$100$ first digits of $\pi$
$\pi \simeq 3.1415926535 ~ 8979323846 ~ 2643383279 ~ 5028841971 \\ 6939937510 ~ 5820974944 ~ 5923078164 ~ 9862803482 ~ 53421170679$ when computed to the first $100$ digits.
Can you compute up to $1000$ digits? Up to $10000$ digits? Up to $100000$ digits? Up to 1 million digits?
Using mpmath
This is a simple and lazy method, using the mpmath module.
MPmath is a Python library for arbitrary-precision floating-point arithmetic (Multi-Precision), and it has a builtin highly-optimized algorithm to compute digits of $\pi$.
It works really fine up-to 1000000 digits (56 ms), from 1 million digits to be printed, printing them starts to get too time consuming (the IDE or the system might freeze).
Step6: We can arbitrarily set the precision, with the constant mp.dps (digit numbers).
Step7: Let save it for further comparison of simpler methods.
Step8: We can solve the initial challenge easily
Step9: And it will most probably be the quickest method presented here
Step10: Asking for $10$ times more digits take about $100$ more of time (that's a bad news).
Step12: The Gauss–Legendre iterative algorithm
More details can be found on this page.
The first method given here is explained in detail.
This algorithm is called the Gauss-Legendre method, and for example it was used to compute the first $206 158 430 000$ decimal digits of $\pi$ on September 18th to 20th, $1999$.
It is a very simply iterative algorithm (ie. step by step, you update the variables, as long as you want)
Step14: This first implementation of the Gauss-Legendre algorithm is limited to a precision of 13 or 14 digits. But it converges quickly ! (4 steps here).
Using decimal.Decimal to improve precision
The limitation of this first algorithm came from using simple float numbers.
Let us now use Decimal numbers to keep as many digits after the decimal as we need.
Step15: The second implementation of the Gauss-Legendre algorithm is now working better (when we adapt the precision). And it converges quickly ! (8 steps give a precision upto the 697th digits).
How much did we lost in term of performance by using decimal numbers? About a factor $1000$, but that's normal as the second solution stores a lot of digits. They don't even compute the same response.
Step17: Methods based on a convergent series
For the following formulae, you can try to write a program that computes the partial sum of the series, up to a certain number of term ($N \geq 1$).
Basically, the bigger the $N$, the more digits you get (but the longer the program will run).
Some methods might be really efficient, only needing a few number of steps (a small $N$) for computing many digits.
Try to implement and compare at least two of these methods.
You can use the function sum (or math.fsum) to compute the sum, or a simple while/for loop.
All these partial sums are written up to an integer $N \geq 1$.
A Leibniz formula (easy)
Step19: This first formula is very inefficient!
Bailey-Borwein-Plouffe series (medium)
Step20: That's pretty impressive, in only $10$ steps!
But that algorithm is highly dependent on the precision we ask, and on the number of terms in the sum.
Step21: It is, of course, slower than the optimized algorithm from mpmath.
And it does not scale well with the precision
Step23: Bellard's formula (hard)
Step24: That's pretty impressive, in only $10$ steps!
But that algorithm is again highly dependent on the precision we ask, and on the number of terms in the sum.
Step25: It is, of course, slower than the optimized algorithm from mpmath.
And it does not scale well with the precision
Step27: It is also slower than BBP formula.
One Ramanujan's formula (hard)
Step28: $1595$ correct digits with $200$ terms, that's quite good!!
Step29: Let's try to answer my initial question, using this naive implementation.
Step31: ... It was too slow!
Chudnovsky brothers' formula (hard)
Step32: It is very efficient, as Ramanujan's formula.
Step33: It gets $2834$ correct numbers in $200$ steps!
It is more efficient that Ramanujan's formula, but slower to compute.
Step35: About $2$ seconds to find correctly the first $5671$ digits? That's slow! But hey, it's Python (dynamic typing etc).
Other methods
Trigonometric methods (hard)
Some methods are based on the $\mathrm{arccot}$ or $\arctan$ functions, and use the appropriate Taylor series to approximate these functions.
The best example is Machin's formula
Step37: Applying Machin's formula
Finally, the main function uses Machin's formula to compute $\pi$ using the necessary level of precision, by using this high precision $\mathrm{arccot}$ function
Step38: So we got the first $9995$ digits correctly... in $45$ seconds.
That will still be too slow to have the digits at position $130317$.
Step39: The program can be used to compute tens of thousands of digits in just a few seconds on a modern computer.
Typical implementation will be in highly efficient compiled language; like C or maybe Julia.
Many Machin-like formulas also exist, like
Step40: It was too slow too! But at least it worked!
My manual implementation of Machin's formula took about $10$ minutes, on an old laptop with $1$ core running Python 3.5, to find the $10$ digits of $\pi$ at index $140317$.
Conclusion
$\implies$ To the question "What are the $10$ digits of $\pi$ at index $140317..140326$", the answer is $9341076406$.
For more, see http
Step41: It does not use Decimal numbers. | Python Code:
print(" pi ~= 3.14 (two first digits).")
print(" pi ~= 22/7 = {} (two first digits).".format(22.0 / 7.0))
print(" pi ~= 355/113 = {} (six first digits).".format(355.0 / 113.0))
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Python-Pi-Day-2017" data-toc-modified-id="Python-Pi-Day-2017-1"><span class="toc-item-num">1 </span>Python Pi Day 2017</a></div><div class="lev1 toc-item"><a href="#Computing-a-lot-of-digits-of-$\pi$?" data-toc-modified-id="Computing-a-lot-of-digits-of-$\pi$?-2"><span class="toc-item-num">2 </span>Computing a lot of digits of <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-388-Frame" tabindex="0" style="position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>&#x03C0;</mi></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2745" role="math" style="width: 0.702em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.554em; height: 0px; font-size: 125%;"><span style="position: absolute; clip: rect(1.941em, 1000.55em, 2.572em, -1000em); top: -2.462em; left: 0em;"><span class="mrow" id="MathJax-Span-2746"><span class="mi" id="MathJax-Span-2747" style="font-family: STIXMathJax_Main; font-style: italic;">π<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.032em;"></span></span></span><span style="display: inline-block; width: 0px; height: 2.462em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.061em; border-left: 0px solid; width: 0px; height: 0.634em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>π</mi></math></span></span><script type="math/tex" id="MathJax-Element-388">\pi</script>?</a></div><div class="lev2 toc-item"><a href="#Two-simple-methods-for-finding-the-first-digits-of-$\pi$" data-toc-modified-id="Two-simple-methods-for-finding-the-first-digits-of-$\pi$-21"><span class="toc-item-num">2.1 </span>Two simple methods for finding the first digits of <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-391-Frame" tabindex="0" style="position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>&#x03C0;</mi></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2754" role="math" style="width: 0.693em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.541em; height: 0px; font-size: 126%;"><span style="position: absolute; clip: rect(1.953em, 1000.54em, 2.615em, -1000em); top: -2.489em; left: 0em;"><span class="mrow" id="MathJax-Span-2755"><span class="mi" id="MathJax-Span-2756" style="font-family: STIXMathJax_Main; font-style: italic;">π<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.032em;"></span></span></span><span style="display: inline-block; width: 0px; height: 2.489em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 0.653em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>π</mi></math></span></span><script type="math/tex" id="MathJax-Element-391">\pi</script></a></div><div class="lev3 toc-item"><a href="#Fraction-approximations,-and-$\pi$-imported-from-the-math-module" data-toc-modified-id="Fraction-approximations,-and-$\pi$-imported-from-the-math-module-211"><span class="toc-item-num">2.1.1 </span>Fraction approximations, and <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-392-Frame" tabindex="0" style="position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>&#x03C0;</mi></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2757" role="math" style="width: 0.736em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.56em; height: 0px; font-size: 129%;"><span style="position: absolute; clip: rect(1.898em, 1000.56em, 2.602em, -1000em); top: -2.455em; left: 0em;"><span class="mrow" id="MathJax-Span-2758"><span class="mi" id="MathJax-Span-2759" style="font-family: STIXMathJax_Main; font-style: italic;">π<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.032em;"></span></span></span><span style="display: inline-block; width: 0px; height: 2.455em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.079em; border-left: 0px solid; width: 0px; height: 0.686em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>π</mi></math></span></span><script type="math/tex" id="MathJax-Element-392">\pi</script> imported from the <code>math</code> module</a></div><div class="lev3 toc-item"><a href="#A-simple-Monte-Carlo-method" data-toc-modified-id="A-simple-Monte-Carlo-method-212"><span class="toc-item-num">2.1.2 </span>A simple <a href="https://en.wikipedia.org/wiki/Pi#Monte_Carlo_methods" target="_blank">Monte-Carlo method</a></a></div><div class="lev2 toc-item"><a href="#$100$-first-digits-of-$\pi$" data-toc-modified-id="$100$-first-digits-of-$\pi$-22"><span class="toc-item-num">2.2 </span><span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-397-Frame" tabindex="0" style="position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mn>100</mn></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2778" role="math" style="width: 1.92em; display: inline-block;"><span style="display: inline-block; position: relative; width: 1.515em; height: 0px; font-size: 126%;"><span style="position: absolute; clip: rect(1.885em, 1001.49em, 2.792em, -1000em); top: -2.67em; left: 0em;"><span class="mrow" id="MathJax-Span-2779"><span class="mn" id="MathJax-Span-2780" style="font-family: STIXMathJax_Main;">100</span></span><span style="display: inline-block; width: 0px; height: 2.67em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.063em; border-left: 0px solid; width: 0px; height: 0.96em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mn>100</mn></math></span></span><script type="math/tex" id="MathJax-Element-397">100</script> first digits of <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-398-Frame" tabindex="0" style="position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>&#x03C0;</mi></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2781" role="math" style="width: 0.693em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.541em; height: 0px; font-size: 126%;"><span style="position: absolute; clip: rect(1.953em, 1000.54em, 2.615em, -1000em); top: -2.489em; left: 0em;"><span class="mrow" id="MathJax-Span-2782"><span class="mi" id="MathJax-Span-2783" style="font-family: STIXMathJax_Main; font-style: italic;">π<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.032em;"></span></span></span><span style="display: inline-block; width: 0px; height: 2.489em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 0.653em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>π</mi></math></span></span><script type="math/tex" id="MathJax-Element-398">\pi</script></a></div><div class="lev2 toc-item"><a href="#Using-mpmath" data-toc-modified-id="Using-mpmath-23"><span class="toc-item-num">2.3 </span>Using <a href="http://mpmath.org/" target="_blank"><code>mpmath</code></a></a></div><div class="lev2 toc-item"><a href="#The-Gauss–Legendre-iterative-algorithm" data-toc-modified-id="The-Gauss–Legendre-iterative-algorithm-24"><span class="toc-item-num">2.4 </span>The Gauss–Legendre iterative algorithm</a></div><div class="lev3 toc-item"><a href="#Using-float-numbers" data-toc-modified-id="Using-float-numbers-241"><span class="toc-item-num">2.4.1 </span>Using float numbers</a></div><div class="lev3 toc-item"><a href="#Using-decimal.Decimal-to-improve-precision" data-toc-modified-id="Using-decimal.Decimal-to-improve-precision-242"><span class="toc-item-num">2.4.2 </span>Using <code>decimal.Decimal</code> to improve precision</a></div><div class="lev2 toc-item"><a href="#Methods-based-on-a-convergent-series" data-toc-modified-id="Methods-based-on-a-convergent-series-25"><span class="toc-item-num">2.5 </span>Methods based on a convergent series</a></div><div class="lev3 toc-item"><a href="#A-Leibniz-formula-(easy):" data-toc-modified-id="A-Leibniz-formula-(easy):-251"><span class="toc-item-num">2.5.1 </span><a href="https://en.wikipedia.org/wiki/Leibniz_formula_for_pi" target="_blank">A Leibniz formula</a> (<em>easy</em>):</a></div><div class="lev3 toc-item"><a href="#Bailey-Borwein-Plouffe-series-(medium):" data-toc-modified-id="Bailey-Borwein-Plouffe-series-(medium):-252"><span class="toc-item-num">2.5.2 </span><a href="https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula" target="_blank">Bailey-Borwein-Plouffe series</a> (<em>medium</em>):</a></div><div class="lev3 toc-item"><a href="#Bellard's-formula-(hard):" data-toc-modified-id="Bellard's-formula-(hard):-253"><span class="toc-item-num">2.5.3 </span><a href="https://en.wikipedia.org/wiki/Bellard%27s_formula" target="_blank">Bellard's formula</a> (<em>hard</em>):</a></div><div class="lev3 toc-item"><a href="#One-Ramanujan's-formula-(hard):" data-toc-modified-id="One-Ramanujan's-formula-(hard):-254"><span class="toc-item-num">2.5.4 </span>One <a href="https://en.wikipedia.org/wiki/Approximations_of_%CF%80#Efficient_methods" target="_blank">Ramanujan's formula</a> (<em>hard</em>):</a></div><div class="lev3 toc-item"><a href="#Chudnovsky-brothers'-formula-(hard):" data-toc-modified-id="Chudnovsky-brothers'-formula-(hard):-255"><span class="toc-item-num">2.5.5 </span><a href="https://en.wikipedia.org/wiki/Chudnovsky_algorithm" target="_blank">Chudnovsky brothers' formula</a> (<em>hard</em>):</a></div><div class="lev2 toc-item"><a href="#Other-methods" data-toc-modified-id="Other-methods-26"><span class="toc-item-num">2.6 </span>Other methods</a></div><div class="lev3 toc-item"><a href="#Trigonometric-methods-(hard)" data-toc-modified-id="Trigonometric-methods-(hard)-261"><span class="toc-item-num">2.6.1 </span>Trigonometric methods (<em>hard</em>)</a></div><div class="lev4 toc-item"><a href="#High-precision-arccot-computation" data-toc-modified-id="High-precision-arccot-computation-2611"><span class="toc-item-num">2.6.1.1 </span><a href="http://en.literateprograms.org/Pi_with_Machin%27s_formula_%28Python%29#High-precision_arccot_computation" target="_blank">High-precision arccot computation</a></a></div><div class="lev4 toc-item"><a href="#Applying-Machin's-formula" data-toc-modified-id="Applying-Machin's-formula-2612"><span class="toc-item-num">2.6.1.2 </span>Applying Machin's formula</a></div><div class="lev4 toc-item"><a href="#Trying-to-solve-my-question!" data-toc-modified-id="Trying-to-solve-my-question!-2613"><span class="toc-item-num">2.6.1.3 </span>Trying to solve my question!</a></div><div class="lev4 toc-item"><a href="#Conclusion" data-toc-modified-id="Conclusion-2614"><span class="toc-item-num">2.6.1.4 </span>Conclusion</a></div><div class="lev3 toc-item"><a href="#(hard)-Unbounded-Spigot-Algorithm" data-toc-modified-id="(hard)-Unbounded-Spigot-Algorithm-262"><span class="toc-item-num">2.6.2 </span>(<em>hard</em>) <a href="http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf" target="_blank">Unbounded Spigot Algorithm</a></a></div><div class="lev3 toc-item"><a href="#(hard)-Borwein's-algorithm" data-toc-modified-id="(hard)-Borwein's-algorithm-263"><span class="toc-item-num">2.6.3 </span>(<em>hard</em>) <a href="https://en.wikipedia.org/wiki/Borwein%27s_algorithm#Nonic_convergence" target="_blank">Borwein's algorithm</a></a></div><div class="lev2 toc-item"><a href="#Examples-and-references" data-toc-modified-id="Examples-and-references-27"><span class="toc-item-num">2.7 </span>Examples and references</a></div><div class="lev3 toc-item"><a href="#Links" data-toc-modified-id="Links-271"><span class="toc-item-num">2.7.1 </span>Links</a></div><div class="lev3 toc-item"><a href="#Pie-!" data-toc-modified-id="Pie-!-272"><span class="toc-item-num">2.7.2 </span>Pie !</a></div>
# Python Pi Day 2017
> This is heavily inspired by what I did two years ago, see this page [cs101/hackhaton/14_03/2015](http://perso.crans.org/besson/cs101/hackathon/14_03_2015) on my website.
Today is [Pi Day 2017](http://www.piday.org/), the day celebrating the number $\pi$.
For more details on this number, see [this Wikipedia page](https://en.wikipedia.org/wiki/Pi).
----
Let us use this occasion to showcase a few different approaches to compute the digits of the number $\pi$.
I will use the [Python](https://www.python.org/) programming language, and you are reading a [Jupyter notebook](https://www.jupyter.org/).
[](http://jupyter.org/)[](https://www.python.org/)
# Computing a lot of digits of $\pi$?
- **What to do ?** I will present and implement some methods that can be used to compute the first digits of the irrational number $\pi$.
- **How ?** One method is based on random numbers, but all the other are simple (or not so simple) iterative algorithm: the more steps you compute, the more digits you will have!
- **How to compare / assess the result ?** It is simple: the more digits you got, the better. We will also test the different methods implemented, and for the most efficient, see how fast it is to go up-to $140000$ digits.
The simple goal is to write a *small* function that computes digits of pi, as fast as possible, and find the 10 digits from position 140317 to 140327!
(that's the challenge I posted on Facebook)
----
## Two simple methods for finding the first digits of $\pi$
### Fraction approximations, and $\pi$ imported from the `math` module
Three approximations, using fractions, were known from a very long time (Aristote used $\frac{355}{113}$ !).
The first three approximations of pi are:
End of explanation
def mathpi():
from math import pi
return pi
print("First method: using math.pi gives pi ~= {:.17f} (17 digits are displayed here).".format(mathpi()))
Explanation: This method is extremely limited, and will not give you more than 13 correct digits, as math.pi is stored as a float number (limited precision).
End of explanation
from decimal import Decimal
bigpi = Decimal('3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679')
print("The first 100 digits of pi are {}.".format(bigpi))
Explanation: If we know the digits, we can directly print them:
End of explanation
from random import uniform
def montecarlo_pi(nbPoints=10000):
Returns a probabilist estimate of pi, as a float number.
nbInside = 0
# we pick a certain number of points (nbPoints)
for i in range(nbPoints):
x = uniform(0, 1)
y = uniform(0, 1)
# (x, y) is now a random point in the square [0, 1] × [0, 1]
if (x**2 + y**2) < 1:
# This point (x, y) is inside the circle C(0, 1)
nbInside += 1
return 4 * float(nbInside) / floor(nbPoints)
print("The simple Monte-Carlo method with {} random points gave pi = {}".format(10000, montecarlo_pi(10000)))
Explanation: A simple Monte-Carlo method
A simple Monte Carlo method for computing $\pi$ is to draw a circle inscribed in a square, and randomly place dots in the square.
The ratio of dots inside the circle to the total number of dots will approximately equal $\pi / 4$, which is also the ratio of the area of the circle by the area of the square:
In Python, such simulation can basically be implemented like this:
End of explanation
import mpmath
# from sympy import mpmath # on older sympy versions
mp = mpmath.mp
Explanation: It is an interesting method, but it is just too limited for approximating digits of $\pi$.
The previous two methods are quite limited, and not efficient enough if you want more than 13 digits (resp. 4 digits for the Monte-Carlo method).
$100$ first digits of $\pi$
$\pi \simeq 3.1415926535 ~ 8979323846 ~ 2643383279 ~ 5028841971 \\ 6939937510 ~ 5820974944 ~ 5923078164 ~ 9862803482 ~ 53421170679$ when computed to the first $100$ digits.
Can you compute up to $1000$ digits? Up to $10000$ digits? Up to $100000$ digits? Up to 1 million digits?
Using mpmath
This is a simple and lazy method, using the mpmath module.
MPmath is a Python library for arbitrary-precision floating-point arithmetic (Multi-Precision), and it has a builtin highly-optimized algorithm to compute digits of $\pi$.
It works really fine up-to 1000000 digits (56 ms), from 1 million digits to be printed, printing them starts to get too time consuming (the IDE or the system might freeze).
End of explanation
mp.dps = 1000 # number of digits
my_pi = mp.pi # Gives pi to a thousand places
print("A lazy method using the mpmath module:\npi is approximatly {} (with {} digits).".format(my_pi, mp.dps))
Explanation: We can arbitrarily set the precision, with the constant mp.dps (digit numbers).
End of explanation
mp.dps = 100000 # number of digits
len(str(mp.pi))
mpmath_pi = Decimal(str(mp.pi))
Explanation: Let save it for further comparison of simpler methods.
End of explanation
mp.dps = 140330
print(str(mp.pi)[2:][140317:140317+10])
Explanation: We can solve the initial challenge easily:
End of explanation
%timeit mp.dps=140330;print(str(mp.pi)[2:][140317:140317+10])
Explanation: And it will most probably be the quickest method presented here:
End of explanation
%timeit mp.dps=1403230;print(str(mp.pi)[2:][1403217:1403217+10])
Explanation: Asking for $10$ times more digits take about $100$ more of time (that's a bad news).
End of explanation
import math
def gauss_legendre_1(max_step):
Float number implementation of the Gauss-Legendre algorithm, for max_step steps.
a = 1.
b = 1./math.sqrt(2)
t = 1./4.0
p = 1.
for i in range(max_step):
at = (a + b) / 2.0
bt = math.sqrt(a*b)
tt = t - p*(a-at)**2
pt = 2.0 * p
a, b, t, p = at, bt, tt, pt
my_pi = ((a+b)**2)/(4.0*t)
return my_pi
my_pi = gauss_legendre_1(4)
my_pi
print("pi is approximately: {:.15f} (as a float number, precision is limited).".format(my_pi))
accuracy = 100*abs(math.pi - my_pi)/math.pi
print("Accuracy % with math.pi: {:.4g}".format(accuracy))
accuracy = 100*abs(float(mpmath_pi) - my_pi)/float(mpmath_pi)
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
my_pi = gauss_legendre_1(40)
my_pi
print("pi is approximately: {:.15f} (as a float number, precision is limited).".format(my_pi))
accuracy = 100*abs(math.pi - my_pi)/math.pi
print("Accuracy % with math.pi: {:.4g}".format(accuracy))
accuracy = 100*abs(float(mpmath_pi) - my_pi)/float(mpmath_pi)
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
Explanation: The Gauss–Legendre iterative algorithm
More details can be found on this page.
The first method given here is explained in detail.
This algorithm is called the Gauss-Legendre method, and for example it was used to compute the first $206 158 430 000$ decimal digits of $\pi$ on September 18th to 20th, $1999$.
It is a very simply iterative algorithm (ie. step by step, you update the variables, as long as you want):
First, start with 4 variables $a_0, b_0, t_0, p_0$, and their initial values are $a_0 = 1, b_0 = 1/\sqrt{2}, t_0 = 1/4, p_0 = 1$.
Then, update the variables (or create 4 new ones $a_{n+1}, b_{n+1}, t_{n+1}, p_{n+1}$) by repeating the following instructions (in this order) until the difference of $a_{n}$ and $b_{n}$, is within the desired accuracy:
$a_{n+1} = \frac{a_n + b_n}{2}$,
$b_{n+1} = \sqrt{a_n \times b_n}$,
$t_{n+1} = t_n - p_n (a_n - a_{n+1})^2$,
$p_{n+1} = 2 p_n$.
Finally, the desired approximation of $\pi$ is: $$\pi \simeq \frac{(a_{n+1} + b_{n+1})^2}{4 t_{n+1}}.$$
Using float numbers
The first three iterations give (approximations given up to and including the first incorrect digit):
3.140 …
3.14159264 …
3.1415926535897932382 …
The algorithm has second-order convergent nature, which essentially means that the number of correct digits doubles with each step of the algorithm.
Try to see how far it can go in less than 120 seconds (print the approximation of $\pi$ after every step, and stop/kill the program after 2 minutes).
This method is based on computing the limits of the arithmetic–geometric mean of some well-chosen number (see on Wikipédia for more mathematical details).
End of explanation
from decimal import Decimal, getcontext
def gauss_legendre_2(max_step):
Decimal number implementation of the Gauss-Legendre algorithm, for max_step steps.
# trick to improve precision
getcontext().prec = 3 + 2**(max_step + 2)
cst_2 = Decimal(2.0)
cst_4 = Decimal(4.0)
a = Decimal(1.0)
b = Decimal(0.5).sqrt()
t = Decimal(0.25)
p = Decimal(1.0)
for i in range(max_step):
new_a = (a+b)/cst_2
new_b = (a*b).sqrt()
new_t = Decimal(t - p*(a - new_a)**2)
new_p = cst_2*p
a, b, t, p = new_a, new_b, new_t, new_p
my_pi = Decimal(((a+b)**2)/(cst_4*t))
return my_pi
my_pi = gauss_legendre_2(5)
print("pi is approximately: {}.".format(my_pi.to_eng_string()[:2**(5+1)]))
accuracy = 100*abs(Decimal(math.pi) - my_pi)/Decimal(math.pi)
print("Accuracy % with math.pi: {:.4g}".format(accuracy))
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
Explanation: This first implementation of the Gauss-Legendre algorithm is limited to a precision of 13 or 14 digits. But it converges quickly ! (4 steps here).
Using decimal.Decimal to improve precision
The limitation of this first algorithm came from using simple float numbers.
Let us now use Decimal numbers to keep as many digits after the decimal as we need.
End of explanation
%timeit gauss_legendre_1(8)
%timeit gauss_legendre_2(8)
Explanation: The second implementation of the Gauss-Legendre algorithm is now working better (when we adapt the precision). And it converges quickly ! (8 steps give a precision upto the 697th digits).
How much did we lost in term of performance by using decimal numbers? About a factor $1000$, but that's normal as the second solution stores a lot of digits. They don't even compute the same response.
End of explanation
def leibniz(max_step):
Computing an approximation of pi with Leibniz series.
my_pi = Decimal(0)
for k in range(max_step):
my_pi += Decimal((-1)**k) / Decimal(2*k+1)
return Decimal(4) * my_pi
getcontext().prec = 20 # trick to improve precision
my_pi = leibniz(1000)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
getcontext().prec = 20 # trick to improve precision
my_pi = leibniz(10000)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
Explanation: Methods based on a convergent series
For the following formulae, you can try to write a program that computes the partial sum of the series, up to a certain number of term ($N \geq 1$).
Basically, the bigger the $N$, the more digits you get (but the longer the program will run).
Some methods might be really efficient, only needing a few number of steps (a small $N$) for computing many digits.
Try to implement and compare at least two of these methods.
You can use the function sum (or math.fsum) to compute the sum, or a simple while/for loop.
All these partial sums are written up to an integer $N \geq 1$.
A Leibniz formula (easy):
It has a number of digits sub-linear in the number $N$ of terms in the sum: we need $10$ times more terms to win just one digit.
$$\pi \simeq 4\sum_{n=0}^{N} \cfrac {(-1)^n}{2n+1}. $$
End of explanation
def bbp(max_step):
Computing an approximation of pi with Bailey-Borwein-Plouffe series.
my_pi = Decimal(0)
for k in range(max_step):
my_pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1))-(Decimal(2)/(8*k+4))-(Decimal(1)/(8*k+5))-(Decimal(1)/(8*k+6)))
return my_pi
getcontext().prec = 20 # trick to improve precision
my_pi = bbp(10)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
Explanation: This first formula is very inefficient!
Bailey-Borwein-Plouffe series (medium):
It also has a number of digits linear in the number $N$ of terms in the sum.
$$\pi \simeq \sum_{n = 1}^{N} \left( \frac{1}{16^{n}} \left( \frac{4}{8n+1} - \frac{2}{8n+4} - \frac{1}{8n+5} - \frac{1}{8n+6} \right) \right). $$
End of explanation
getcontext().prec = 200 # trick to improve precision
my_pi = bbp(200)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
getcontext().prec = 500 # trick to improve precision
my_pi = bbp(500)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
Explanation: That's pretty impressive, in only $10$ steps!
But that algorithm is highly dependent on the precision we ask, and on the number of terms in the sum.
End of explanation
getcontext().prec = 10 + 1000 # trick to improve precision
%timeit bbp(1000)
getcontext().prec = 10 + 2000 # trick to improve precision
%timeit bbp(2000)
Explanation: It is, of course, slower than the optimized algorithm from mpmath.
And it does not scale well with the precision:
End of explanation
def bellard(max_step):
Computing an approximation of pi with Bellard series.
my_pi = Decimal(0)
for k in range(max_step):
my_pi += (Decimal(-1)**k/(1024**k))*( Decimal(256)/(10*k+1) + Decimal(1)/(10*k+9) - Decimal(64)/(10*k+3) - Decimal(32)/(4*k+1) - Decimal(4)/(10*k+5) - Decimal(4)/(10*k+7) -Decimal(1)/(4*k+3))
return my_pi * Decimal(1.0/(2**6))
getcontext().prec = 40 # trick to improve precision
my_pi = bellard(10)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
Explanation: Bellard's formula (hard):
It is a more efficient formula.
$$\pi \simeq \frac1{2^6} \sum_{n=0}^N \frac{(-1)^n}{2^{10n}} \, \left(-\frac{2^5}{4n+1} - \frac1{4n+3} + \frac{2^8}{10n+1} - \frac{2^6}{10n+3} - \frac{2^2}{10n+5} - \frac{2^2}{10n+7} + \frac1{10n+9} \right). $$
End of explanation
getcontext().prec = 800 # trick to improve precision
my_pi = bellard(200)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
Explanation: That's pretty impressive, in only $10$ steps!
But that algorithm is again highly dependent on the precision we ask, and on the number of terms in the sum.
End of explanation
getcontext().prec = 10 + 1000 # trick to improve precision
%timeit bellard(1000)
getcontext().prec = 10 + 2000 # trick to improve precision
%timeit bellard(2000)
Explanation: It is, of course, slower than the optimized algorithm from mpmath.
And it does not scale well with the precision:
End of explanation
from math import factorial
def ramanujan(max_step):
Computing an approximation of pi with a Ramanujan's formula.
my_pi = Decimal(0)
d_1103 = Decimal(1103)
d_26390 = Decimal(26390)
d_396 = Decimal(396)
for k in range(max_step):
my_pi += ((Decimal(factorial(4 * k))) * (d_1103 + d_26390 * Decimal(k))) / ( (Decimal(factorial(k)))**4 * (d_396**(4*k)))
my_pi = my_pi * 2 * Decimal(2).sqrt() / Decimal(9801)
my_pi = my_pi**(-1)
return my_pi
getcontext().prec = 40 # trick to improve precision
my_pi = ramanujan(4)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
getcontext().prec = 400 # trick to improve precision
my_pi = ramanujan(40)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
getcontext().prec = 2000 # trick to improve precision
my_pi = ramanujan(200)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
Explanation: It is also slower than BBP formula.
One Ramanujan's formula (hard):
It is efficient but harder to compute easily with high precision, due to the factorial.
But hopefully, the function math.factorial works with Python integers, of arbitrary size, so this won't be an issue.
$$\frac{1}{\pi} \simeq \frac{2\sqrt{2}}{9801} \sum_{n=0}^N \frac{(4n)!(1103+26390n)}{(n!)^4 396^{4n}}. $$
Remark: This method and the next one compute approximation of $\frac{1}{\pi}$, not $\pi$.
This method has a quadratic precision (the number of correct digits is of the order $\mathcal{O}(N^2)$.
End of explanation
getcontext().prec = 10 + 2000 # trick to improve precision
%timeit ramanujan(200)
getcontext().prec = 10 + 5000 # trick to improve precision
%timeit ramanujan(400)
Explanation: $1595$ correct digits with $200$ terms, that's quite good!!
End of explanation
%%time
getcontext().prec = 140350 # trick to improve precision
i = 140317
my_pi = ramanujan(10000)
print(str(my_pi)[2:][i:i+10])
mp.dps=140330
print(str(mp.pi)[2:][i:i+10])
Explanation: Let's try to answer my initial question, using this naive implementation.
End of explanation
from math import factorial
def chudnovsky(max_step):
Computing an approximation of pi with Bellard series.
my_pi = Decimal(0)
for k in range(max_step):
my_pi += (Decimal(-1)**k)*(Decimal(factorial(6*k))/((factorial(k)**3)*(factorial(3*k)))* (13591409+545140134*k)/(640320**(3*k)))
my_pi = my_pi * Decimal(10005).sqrt()/4270934400
my_pi = my_pi**(-1)
return my_pi
Explanation: ... It was too slow!
Chudnovsky brothers' formula (hard):
$$\frac{1}{\pi} \simeq 12 \sum_{n=0}^N \frac {(-1)^{n}(6n)!(545140134n+13591409)}{(3n)!(n!)^{3}640320^{{3n+3/2}}}. $$
In 2015, the best method is still the Chudnovsky brothers's formula.
Be careful when you use these formulae, check carefully the constants you wrote (545140134 will work well, 545140135 might not work as well!).
This formula is used as the logo of the French agrégation of Mathematics website agreg.org :
End of explanation
getcontext().prec = 3000 # trick to improve precision
my_pi = chudnovsky(200)
my_pi
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
Explanation: It is very efficient, as Ramanujan's formula.
End of explanation
getcontext().prec = 6000 # trick to improve precision
my_pi = chudnovsky(400)
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
getcontext().prec = 3000 # trick to improve precision
%timeit chudnovsky(200)
getcontext().prec = 6000 # trick to improve precision
%timeit chudnovsky(400)
Explanation: It gets $2834$ correct numbers in $200$ steps!
It is more efficient that Ramanujan's formula, but slower to compute.
End of explanation
def arccot(x, unity):
Compute arccot(x) with a certain level of precision.
x = Decimal(x)
unity = Decimal(unity)
mysum = xpower = unity / x
n = 3
sign = -1
while True:
xpower = xpower / (x*x)
term = xpower / n
if not term:
break
mysum += sign * term
sign = -sign # we alternate the sign
n += 2
return mysum
Explanation: About $2$ seconds to find correctly the first $5671$ digits? That's slow! But hey, it's Python (dynamic typing etc).
Other methods
Trigonometric methods (hard)
Some methods are based on the $\mathrm{arccot}$ or $\arctan$ functions, and use the appropriate Taylor series to approximate these functions.
The best example is Machin's formula:
$$\pi = 16 \;\mathrm{arccot}(5) - 4 \;\mathrm{arccot}(239).$$
And we use the Taylor series to approximate $\mathrm{arccot}(x)$:
$$\mathrm{arccot}(x) = \frac{1}{x} - \frac{1}{3x^3} + \frac{1}{5x^5} - \frac{1}{7x^7} + \dots = \sum_{n=0}^{+\infty} \frac{(-1)^n}{(2n+1) x^{2n+1}} .$$
This method is also explained here with some details.
In order to obtain $n$ digits, we will use fixed-point arithmetic to compute $\pi \times 10^n$ as a Python long integer.
High-precision arccot computation
To calculate $\mathrm{arccot}$ of an argument $x$, we start by dividing the number $1$ (represented by $10^n$, which we provide as the argument unity) by $x$ to obtain the first term.
We then repeatedly divide by $x^2$ and a counter value that runs over $3$, $5$, $7$ etc, to obtain each next term.
The summation is stopped at the first zero term, which in this fixed-point representation corresponds to a real value less than $10^{-n}$:
python
def arccot(x, unity):
xpower = unity / x
sum = xpower
n = 3
sign = -1
while True:
xpower = xpower / (x*x)
term = xpower / n
if term == 0:
break # we are done
sum += sign * term
sign = -sign
n += 2
return sum
Adapting it to use Decimal numbers is easy:
End of explanation
def machin(digits):
Compute pi with Machin's formula, with precision at least digits.
unity = 10**(digits + 10)
my_pi = Decimal(4) * (Decimal(4)*arccot(5, unity) - arccot(239, unity))
return my_pi / Decimal(unity)
getcontext().prec = 10000 # trick to improve precision
my_pi = machin(100)
accuracy = 100*abs(mpmath_pi - my_pi)/mpmath_pi
print("Accuracy % with mpmath_pi: {:.4g}".format(accuracy))
Explanation: Applying Machin's formula
Finally, the main function uses Machin's formula to compute $\pi$ using the necessary level of precision, by using this high precision $\mathrm{arccot}$ function:
$$\pi = 16 \;\mathrm{arccot}(5) - 4 \;\mathrm{arccot}(239).$$
python
def machin(digits):
unity = 10**(digits + 10)
pi = 4 * (4*arccot(5, unity) - arccot(239, unity))
return pi / unity
To avoid rounding errors in the result, we use 10 guard digits internally during the calculation.
We may now reproduce the historical result obtained by Machin in 1706.
End of explanation
getcontext().prec = 5000 # trick to improve precision
%timeit machin(50)
getcontext().prec = 10000 # trick to improve precision
%timeit machin(100)
Explanation: So we got the first $9995$ digits correctly... in $45$ seconds.
That will still be too slow to have the digits at position $130317$.
End of explanation
%%time
i = 14031
getcontext().prec = i + 20 # trick to improve precision
mp.dps = i + 20
print(str(mp.pi)[2:][i:i+10])
my_pi = machin(11)
print(str(my_pi)[2:][i:i+10])
%%time
i = 140317
getcontext().prec = i + 20 # trick to improve precision
mp.dps = i + 20
print(str(mp.pi)[2:][i:i+10])
my_pi = machin(50)
print(str(my_pi)[2:][i:i+10])
Explanation: The program can be used to compute tens of thousands of digits in just a few seconds on a modern computer.
Typical implementation will be in highly efficient compiled language; like C or maybe Julia.
Many Machin-like formulas also exist, like:
$$\pi = 4\arctan\left(\frac{1}{2}\right) + 4 \arctan\left(\frac{1}{3}\right).$$
Trying to solve my question!
The important parameter to tune is not the precision given to machin() but the Decimal.prec precision.
End of explanation
def next_pi_digit(max_step):
q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
for j in range(max_step):
if 4 * q + r - t < m * t:
yield m
# More details on Python generators can be found here http://stackoverflow.com/a/231855
q, r, t, k, m, x = 10*q, 10*(r-m*t), t, k, (10*(3*q+r))//t - 10*m, x
else:
q, r, t, k, m, x = q*k, (2*q+r)*x, t*x, k+1, (q*(7*k+2)+r*x)//(t*x), x+2
def generator_pi(max_step):
big_str = ''.join(str(d) for d in next_pi_digit(max_step))
return Decimal(big_str[0] + '.' + big_str[1:])
Explanation: It was too slow too! But at least it worked!
My manual implementation of Machin's formula took about $10$ minutes, on an old laptop with $1$ core running Python 3.5, to find the $10$ digits of $\pi$ at index $140317$.
Conclusion
$\implies$ To the question "What are the $10$ digits of $\pi$ at index $140317..140326$", the answer is $9341076406$.
For more, see http://fredrikj.net/blog/2011/03/100-mpmath-one-liners-for-pi/.
(hard) Unbounded Spigot Algorithm
This algorithm is quite efficient, but not easy to explain. Go check on-line if you want.
See this page (http://codepad.org/3yDnw0n9) for a 1-line C program that uses a simpler Spigot algorithm for computing the first 15000 digits
A nice method, with a generator yielding the next digit each time, comes from http://stackoverflow.com/a/9005163.
It uses only integer, so no need to do any Decimal trick here.
End of explanation
getcontext().prec = 50 # trick to improve precision
generator_pi(1000)
getcontext().prec = 5000 # trick to improve precision
generator_pi(1000)
Explanation: It does not use Decimal numbers.
End of explanation |
7,938 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Federated Learning for Text Generation
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Load a pre-trained model
We load a model that was pre-trained following the TensorFlow tutorial
Text generation using a RNN with eager execution. However,
rather than training on The Complete Works of Shakespeare, we pre-trained the model on the text from the Charles Dickens'
A Tale of Two Cities
and
A Christmas Carol.
Other than expanding the vocabulary, we didn't modify the original tutorial, so this initial model isn't state-of-the-art, but it produces reasonable predictions and is sufficient for our tutorial purposes. The final model was saved with tf.keras.models.save_model(include_optimizer=False).
We will use federated learning to fine-tune this model for Shakespeare in this tutorial, using a federated version of the data provided by TFF.
Generate the vocab lookup tables
Step3: Load the pre-trained model and generate some text
Step4: Load and Preprocess the Federated Shakespeare Data
The tff.simulation.datasets package provides a variety of datasets that are split into "clients", where each client corresponds to a dataset on a particular device that might participate in federated learning.
These datasets provide realistic non-IID data distributions that replicate in simulation the challenges of training on real decentralized data. Some of the pre-processing of this data was done using tools from the Leaf project (github).
Step5: The datasets provided by shakespeare.load_data() consist of a sequence of
string Tensors, one for each line spoken by a particular character in a
Shakespeare play. The client keys consist of the name of the play joined with
the name of the character, so for example MUCH_ADO_ABOUT_NOTHING_OTHELLO corresponds to the lines for the character Othello in the play Much Ado About Nothing. Note that in a real federated learning scenario
clients are never identified or tracked by ids, but for simulation it is useful
to work with keyed datasets.
Here, for example, we can look at some data from King Lear
Step6: We now use tf.data.Dataset transformations to prepare this data for training the char RNN loaded above.
Step7: Note that in the formation of the original sequences and in the formation of
batches above, we use drop_remainder=True for simplicity. This means that any
characters (clients) that don't have at least (SEQ_LENGTH + 1) * BATCH_SIZE
chars of text will have empty datasets. A typical approach to address this would
be to pad the batches with a special token, and then mask the loss to not take
the padding tokens into account.
This would complicate the example somewhat, so for this tutorial we only use full batches, as in the
standard tutorial.
However, in the federated setting this issue is more significant, because many
users might have small datasets.
Now we can preprocess our raw_example_dataset, and check the types
Step8: Compile the model and test on the preprocessed data
We loaded an uncompiled keras model, but in order to run keras_model.evaluate, we need to compile it with a loss and metrics. We will also compile in an optimizer, which will be used as the on-device optimizer in Federated Learning.
The original tutorial didn't have char-level accuracy (the fraction
of predictions where the highest probability was put on the correct
next char). This is a useful metric, so we add it.
However, we need to define a new metric class for this because
our predictions have rank 3 (a vector of logits for each of the
BATCH_SIZE * SEQ_LENGTH predictions), and SparseCategoricalAccuracy
expects only rank 2 predictions.
Step9: Now we can compile a model, and evaluate it on our example_dataset.
Step10: Fine-tune the model with Federated Learning
TFF serializes all TensorFlow computations so they can potentially be run in a
non-Python environment (even though at the moment, only a simulation runtime implemented in Python is available). Even though we are running in eager mode, (TF 2.0), currently TFF serializes TensorFlow computations by constructing the
necessary ops inside the context of a "with tf.Graph.as_default()" statement.
Thus, we need to provide a function that TFF can use to introduce our model into
a graph it controls. We do this as follows
Step11: Now we are ready to construct a Federated Averaging iterative process, which we will use to improve the model (for details on the Federated Averaging algorithm, see the paper Communication-Efficient Learning of Deep Networks from Decentralized Data).
We use a compiled Keras model to perform standard (non-federated) evaluation after each round of federated training. This is useful for research purposes when doing simulated federated learning and there is a standard test dataset.
In a realistic production setting this same technique might be used to take models trained with federated learning and evaluate them on a centralized benchmark dataset for testing or quality assurance purposes.
Step12: Here is the simplest possible loop, where we run federated averaging for one round on a single client on a single batch
Step13: Now let's write a slightly more interesting training and evaluation loop.
So that this simulation still runs relatively quickly, we train on the same three clients each round, only considering two minibatches for each.
Step14: The initial state of the model produced by fed_avg.initialize() is based
on the random initializers for the Keras model, not the weights that were loaded,
since clone_model() does not clone the weights. To start training
from a pre-trained model, we set the model weights in the server state
directly from the loaded model.
Step15: With the default changes, we haven't done enough training to make a big difference, but if you train longer on more Shakespeare data, you should see a difference in the style of the text generated with the updated model | Python Code:
#@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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Explanation: Copyright 2019 The TensorFlow Authors.
End of explanation
#@test {"skip": true}
!pip install --quiet --upgrade tensorflow-federated
!pip install --quiet --upgrade nest-asyncio
import nest_asyncio
nest_asyncio.apply()
import collections
import functools
import os
import time
import numpy as np
import tensorflow as tf
import tensorflow_federated as tff
np.random.seed(0)
# Test the TFF is working:
tff.federated_computation(lambda: 'Hello, World!')()
Explanation: Federated Learning for Text Generation
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/federated/tutorials/federated_learning_for_text_generation"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/federated/blob/v0.27.0/docs/tutorials/federated_learning_for_text_generation.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/federated/blob/v0.27.0/docs/tutorials/federated_learning_for_text_generation.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/federated/docs/tutorials/federated_learning_for_text_generation.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
NOTE: This colab has been verified to work with the latest released version of the tensorflow_federated pip package, but the Tensorflow Federated project is still in pre-release development and may not work on main.
This tutorial builds on the concepts in the Federated Learning for Image Classification tutorial, and demonstrates several other useful approaches for federated learning.
In particular, we load a previously trained Keras model, and refine it using federated training on a (simulated) decentralized dataset. This is practically important for several reasons . The ability to use serialized models makes it easy to mix federated learning with other ML approaches. Further, this allows use of an increasing range of pre-trained models --- for example, training language models from scratch is rarely necessary, as numerous pre-trained models are now widely available (see, e.g., TF Hub). Instead, it makes more sense to start from a pre-trained model, and refine it using Federated Learning, adapting to the particular characteristics of the decentralized data for a particular application.
For this tutorial, we start with a RNN that generates ASCII characters, and refine it via federated learning. We also show how the final weights can be fed back to the original Keras model, allowing easy evaluation and text generation using standard tools.
End of explanation
# A fixed vocabularly of ASCII chars that occur in the works of Shakespeare and Dickens:
vocab = list('dhlptx@DHLPTX $(,048cgkoswCGKOSW[_#\'/37;?bfjnrvzBFJNRVZ"&*.26:\naeimquyAEIMQUY]!%)-159\r')
# Creating a mapping from unique characters to indices
char2idx = {u:i for i, u in enumerate(vocab)}
idx2char = np.array(vocab)
Explanation: Load a pre-trained model
We load a model that was pre-trained following the TensorFlow tutorial
Text generation using a RNN with eager execution. However,
rather than training on The Complete Works of Shakespeare, we pre-trained the model on the text from the Charles Dickens'
A Tale of Two Cities
and
A Christmas Carol.
Other than expanding the vocabulary, we didn't modify the original tutorial, so this initial model isn't state-of-the-art, but it produces reasonable predictions and is sufficient for our tutorial purposes. The final model was saved with tf.keras.models.save_model(include_optimizer=False).
We will use federated learning to fine-tune this model for Shakespeare in this tutorial, using a federated version of the data provided by TFF.
Generate the vocab lookup tables
End of explanation
def load_model(batch_size):
urls = {
1: 'https://storage.googleapis.com/tff-models-public/dickens_rnn.batch1.kerasmodel',
8: 'https://storage.googleapis.com/tff-models-public/dickens_rnn.batch8.kerasmodel'}
assert batch_size in urls, 'batch_size must be in ' + str(urls.keys())
url = urls[batch_size]
local_file = tf.keras.utils.get_file(os.path.basename(url), origin=url)
return tf.keras.models.load_model(local_file, compile=False)
def generate_text(model, start_string):
# From https://www.tensorflow.org/tutorials/sequences/text_generation
num_generate = 200
input_eval = [char2idx[s] for s in start_string]
input_eval = tf.expand_dims(input_eval, 0)
text_generated = []
temperature = 1.0
model.reset_states()
for i in range(num_generate):
predictions = model(input_eval)
predictions = tf.squeeze(predictions, 0)
predictions = predictions / temperature
predicted_id = tf.random.categorical(
predictions, num_samples=1)[-1, 0].numpy()
input_eval = tf.expand_dims([predicted_id], 0)
text_generated.append(idx2char[predicted_id])
return (start_string + ''.join(text_generated))
# Text generation requires a batch_size=1 model.
keras_model_batch1 = load_model(batch_size=1)
print(generate_text(keras_model_batch1, 'What of TensorFlow Federated, you ask? '))
Explanation: Load the pre-trained model and generate some text
End of explanation
train_data, test_data = tff.simulation.datasets.shakespeare.load_data()
Explanation: Load and Preprocess the Federated Shakespeare Data
The tff.simulation.datasets package provides a variety of datasets that are split into "clients", where each client corresponds to a dataset on a particular device that might participate in federated learning.
These datasets provide realistic non-IID data distributions that replicate in simulation the challenges of training on real decentralized data. Some of the pre-processing of this data was done using tools from the Leaf project (github).
End of explanation
# Here the play is "The Tragedy of King Lear" and the character is "King".
raw_example_dataset = train_data.create_tf_dataset_for_client(
'THE_TRAGEDY_OF_KING_LEAR_KING')
# To allow for future extensions, each entry x
# is an OrderedDict with a single key 'snippets' which contains the text.
for x in raw_example_dataset.take(2):
print(x['snippets'])
Explanation: The datasets provided by shakespeare.load_data() consist of a sequence of
string Tensors, one for each line spoken by a particular character in a
Shakespeare play. The client keys consist of the name of the play joined with
the name of the character, so for example MUCH_ADO_ABOUT_NOTHING_OTHELLO corresponds to the lines for the character Othello in the play Much Ado About Nothing. Note that in a real federated learning scenario
clients are never identified or tracked by ids, but for simulation it is useful
to work with keyed datasets.
Here, for example, we can look at some data from King Lear:
End of explanation
# Input pre-processing parameters
SEQ_LENGTH = 100
BATCH_SIZE = 8
BUFFER_SIZE = 100 # For dataset shuffling
# Construct a lookup table to map string chars to indexes,
# using the vocab loaded above:
table = tf.lookup.StaticHashTable(
tf.lookup.KeyValueTensorInitializer(
keys=vocab, values=tf.constant(list(range(len(vocab))),
dtype=tf.int64)),
default_value=0)
def to_ids(x):
s = tf.reshape(x['snippets'], shape=[1])
chars = tf.strings.bytes_split(s).values
ids = table.lookup(chars)
return ids
def split_input_target(chunk):
input_text = tf.map_fn(lambda x: x[:-1], chunk)
target_text = tf.map_fn(lambda x: x[1:], chunk)
return (input_text, target_text)
def preprocess(dataset):
return (
# Map ASCII chars to int64 indexes using the vocab
dataset.map(to_ids)
# Split into individual chars
.unbatch()
# Form example sequences of SEQ_LENGTH +1
.batch(SEQ_LENGTH + 1, drop_remainder=True)
# Shuffle and form minibatches
.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)
# And finally split into (input, target) tuples,
# each of length SEQ_LENGTH.
.map(split_input_target))
Explanation: We now use tf.data.Dataset transformations to prepare this data for training the char RNN loaded above.
End of explanation
example_dataset = preprocess(raw_example_dataset)
print(example_dataset.element_spec)
Explanation: Note that in the formation of the original sequences and in the formation of
batches above, we use drop_remainder=True for simplicity. This means that any
characters (clients) that don't have at least (SEQ_LENGTH + 1) * BATCH_SIZE
chars of text will have empty datasets. A typical approach to address this would
be to pad the batches with a special token, and then mask the loss to not take
the padding tokens into account.
This would complicate the example somewhat, so for this tutorial we only use full batches, as in the
standard tutorial.
However, in the federated setting this issue is more significant, because many
users might have small datasets.
Now we can preprocess our raw_example_dataset, and check the types:
End of explanation
class FlattenedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
def __init__(self, name='accuracy', dtype=tf.float32):
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
y_true = tf.reshape(y_true, [-1, 1])
y_pred = tf.reshape(y_pred, [-1, len(vocab), 1])
return super().update_state(y_true, y_pred, sample_weight)
Explanation: Compile the model and test on the preprocessed data
We loaded an uncompiled keras model, but in order to run keras_model.evaluate, we need to compile it with a loss and metrics. We will also compile in an optimizer, which will be used as the on-device optimizer in Federated Learning.
The original tutorial didn't have char-level accuracy (the fraction
of predictions where the highest probability was put on the correct
next char). This is a useful metric, so we add it.
However, we need to define a new metric class for this because
our predictions have rank 3 (a vector of logits for each of the
BATCH_SIZE * SEQ_LENGTH predictions), and SparseCategoricalAccuracy
expects only rank 2 predictions.
End of explanation
BATCH_SIZE = 8 # The training and eval batch size for the rest of this tutorial.
keras_model = load_model(batch_size=BATCH_SIZE)
keras_model.compile(
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[FlattenedCategoricalAccuracy()])
# Confirm that loss is much lower on Shakespeare than on random data
loss, accuracy = keras_model.evaluate(example_dataset.take(5), verbose=0)
print(
'Evaluating on an example Shakespeare character: {a:3f}'.format(a=accuracy))
# As a sanity check, we can construct some completely random data, where we expect
# the accuracy to be essentially random:
random_guessed_accuracy = 1.0 / len(vocab)
print('Expected accuracy for random guessing: {a:.3f}'.format(
a=random_guessed_accuracy))
random_indexes = np.random.randint(
low=0, high=len(vocab), size=1 * BATCH_SIZE * (SEQ_LENGTH + 1))
data = collections.OrderedDict(
snippets=tf.constant(
''.join(np.array(vocab)[random_indexes]), shape=[1, 1]))
random_dataset = preprocess(tf.data.Dataset.from_tensor_slices(data))
loss, accuracy = keras_model.evaluate(random_dataset, steps=10, verbose=0)
print('Evaluating on completely random data: {a:.3f}'.format(a=accuracy))
Explanation: Now we can compile a model, and evaluate it on our example_dataset.
End of explanation
# Clone the keras_model inside `create_tff_model()`, which TFF will
# call to produce a new copy of the model inside the graph that it will
# serialize. Note: we want to construct all the necessary objects we'll need
# _inside_ this method.
def create_tff_model():
# TFF uses an `input_spec` so it knows the types and shapes
# that your model expects.
input_spec = example_dataset.element_spec
keras_model_clone = tf.keras.models.clone_model(keras_model)
return tff.learning.from_keras_model(
keras_model_clone,
input_spec=input_spec,
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[FlattenedCategoricalAccuracy()])
Explanation: Fine-tune the model with Federated Learning
TFF serializes all TensorFlow computations so they can potentially be run in a
non-Python environment (even though at the moment, only a simulation runtime implemented in Python is available). Even though we are running in eager mode, (TF 2.0), currently TFF serializes TensorFlow computations by constructing the
necessary ops inside the context of a "with tf.Graph.as_default()" statement.
Thus, we need to provide a function that TFF can use to introduce our model into
a graph it controls. We do this as follows:
End of explanation
# This command builds all the TensorFlow graphs and serializes them:
fed_avg = tff.learning.build_federated_averaging_process(
model_fn=create_tff_model,
client_optimizer_fn=lambda: tf.keras.optimizers.SGD(lr=0.5))
Explanation: Now we are ready to construct a Federated Averaging iterative process, which we will use to improve the model (for details on the Federated Averaging algorithm, see the paper Communication-Efficient Learning of Deep Networks from Decentralized Data).
We use a compiled Keras model to perform standard (non-federated) evaluation after each round of federated training. This is useful for research purposes when doing simulated federated learning and there is a standard test dataset.
In a realistic production setting this same technique might be used to take models trained with federated learning and evaluate them on a centralized benchmark dataset for testing or quality assurance purposes.
End of explanation
state = fed_avg.initialize()
state, metrics = fed_avg.next(state, [example_dataset.take(5)])
train_metrics = metrics['train']
print('loss={l:.3f}, accuracy={a:.3f}'.format(
l=train_metrics['loss'], a=train_metrics['accuracy']))
Explanation: Here is the simplest possible loop, where we run federated averaging for one round on a single client on a single batch:
End of explanation
def data(client, source=train_data):
return preprocess(source.create_tf_dataset_for_client(client)).take(5)
clients = [
'ALL_S_WELL_THAT_ENDS_WELL_CELIA', 'MUCH_ADO_ABOUT_NOTHING_OTHELLO',
]
train_datasets = [data(client) for client in clients]
# We concatenate the test datasets for evaluation with Keras by creating a
# Dataset of Datasets, and then identity flat mapping across all the examples.
test_dataset = tf.data.Dataset.from_tensor_slices(
[data(client, test_data) for client in clients]).flat_map(lambda x: x)
Explanation: Now let's write a slightly more interesting training and evaluation loop.
So that this simulation still runs relatively quickly, we train on the same three clients each round, only considering two minibatches for each.
End of explanation
NUM_ROUNDS = 5
# The state of the FL server, containing the model and optimization state.
state = fed_avg.initialize()
# Load our pre-trained Keras model weights into the global model state.
state = tff.learning.state_with_new_model_weights(
state,
trainable_weights=[v.numpy() for v in keras_model.trainable_weights],
non_trainable_weights=[
v.numpy() for v in keras_model.non_trainable_weights
])
def keras_evaluate(state, round_num):
# Take our global model weights and push them back into a Keras model to
# use its standard `.evaluate()` method.
keras_model = load_model(batch_size=BATCH_SIZE)
keras_model.compile(
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[FlattenedCategoricalAccuracy()])
state.model.assign_weights_to(keras_model)
loss, accuracy = keras_model.evaluate(example_dataset, steps=2, verbose=0)
print('\tEval: loss={l:.3f}, accuracy={a:.3f}'.format(l=loss, a=accuracy))
for round_num in range(NUM_ROUNDS):
print('Round {r}'.format(r=round_num))
keras_evaluate(state, round_num)
state, metrics = fed_avg.next(state, train_datasets)
train_metrics = metrics['train']
print('\tTrain: loss={l:.3f}, accuracy={a:.3f}'.format(
l=train_metrics['loss'], a=train_metrics['accuracy']))
print('Final evaluation')
keras_evaluate(state, NUM_ROUNDS + 1)
Explanation: The initial state of the model produced by fed_avg.initialize() is based
on the random initializers for the Keras model, not the weights that were loaded,
since clone_model() does not clone the weights. To start training
from a pre-trained model, we set the model weights in the server state
directly from the loaded model.
End of explanation
# Set our newly trained weights back in the originally created model.
keras_model_batch1.set_weights([v.numpy() for v in keras_model.weights])
# Text generation requires batch_size=1
print(generate_text(keras_model_batch1, 'What of TensorFlow Federated, you ask? '))
Explanation: With the default changes, we haven't done enough training to make a big difference, but if you train longer on more Shakespeare data, you should see a difference in the style of the text generated with the updated model:
End of explanation |
7,939 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vectors
Create a vector
Step1: Convert it into a row vector
Step2: Convert it into a column vector
Step3: Vectors can be considered as a single feature matrix
Step4: Multiple Feature Matrices
Create a multiple feature matrix
Step5: Load datasets for demonstration
Step6: Load modules for demonstration
Step7: The Probability Density Function (PDF)
Step8: The Mean
Step9: The mean can also be calculated using a NumPy function
Step10: Squared Sum of Errors
Step11: Most errors in the dataset are close to zero.
Correlation
Correlation is a measure of how two variables relate to each other (how much and in what direction?).
Z-score standardization involves subtracting each score from its mean and then dividing by the standard deviation. This measure has a mean of 0 and a standard deviation of 1.
The standardization formula is
Step12: Calculate the correlation by summing all of the squared differences and divide by the number of observations. This will yield a number between -1 and 1 with positive indicating proportionality (direct/positive--both grow together; indirect/negative--one grows, other shrinks).
Covariance
Step13: Visually, a correlation approaches a straight line when plotted as a scatterplot. Correlation is a measure of linear association, i.e., how close to a straight line your data is. | Python Code:
import numpy as np
vector = np.array([1, 2, 3, 4, 5])
vector
Explanation: Vectors
Create a vector:
End of explanation
vector.reshape((5, 1))
Explanation: Convert it into a row vector:
End of explanation
vector.reshape((1, 5))
Explanation: Convert it into a column vector:
End of explanation
vector.reshape((1, 5))
Explanation: Vectors can be considered as a single feature matrix:
End of explanation
multiple_feature_matrix = np.array([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]])
multiple_feature_matrix
Explanation: Multiple Feature Matrices
Create a multiple feature matrix:
End of explanation
from sklearn.datasets import fetch_california_housing
from sklearn.datasets import load_boston
boston = load_boston()
california = fetch_california_housing()
Explanation: Load datasets for demonstration
End of explanation
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib as mpl
%matplotlib inline
dataset = pd.DataFrame(boston.data, columns=boston.feature_names)
dataset['target'] = boston.target
Explanation: Load modules for demonstration
End of explanation
x = np.linspace(-4, 4, 100)
for mean, variance in [(0, 0.7), (0, 1), (1, 1.5), (-2, 0.5)]:
plt.plot(x, mlab.normpdf(x, mean, variance))
Explanation: The Probability Density Function (PDF)
End of explanation
dataset.head()
mean_expected_value = dataset['target'].mean()
mean_expected_value
Explanation: The Mean
End of explanation
np.mean(dataset['target'])
Explanation: The mean can also be calculated using a NumPy function:
End of explanation
Squared_errors = pd.Series(mean_expected_value - dataset['target'])**2
SSE = np.sum(Squared_errors)
print('Sum of Squared Errors (SSE): {0}'.format(SSE))
density_plot = Squared_errors.plot('hist')
Explanation: Squared Sum of Errors
End of explanation
def standardize(x):
return (x - np.mean(x)) / np.std(x)
standardize(dataset['target']).head()
Explanation: Most errors in the dataset are close to zero.
Correlation
Correlation is a measure of how two variables relate to each other (how much and in what direction?).
Z-score standardization involves subtracting each score from its mean and then dividing by the standard deviation. This measure has a mean of 0 and a standard deviation of 1.
The standardization formula is:
End of explanation
def covariance(var1, var2, bias=0):
observations = float(len(var1))
return np.sum((var1 - np.mean(var1)) * (var2 - np.mean(var2))) / (observations - min(bias, 1))
def standardize(var):
return (var - np.mean(var)) / np.std(var)
def correlation(var1, var2, bias=0):
return covariance(standardize(var1), standardize(var2), bias)
print('Our correlation estimate: {0}'.format(correlation(dataset['RM'], dataset['target'])))
from scipy.stats.stats import pearsonr
print('Correlation from Scipy pearsonr: {0}'.format(pearsonr(dataset['RM'], dataset['target'])[0]))
Explanation: Calculate the correlation by summing all of the squared differences and divide by the number of observations. This will yield a number between -1 and 1 with positive indicating proportionality (direct/positive--both grow together; indirect/negative--one grows, other shrinks).
Covariance:
Pearson's correlation:
End of explanation
x_range = [dataset['RM'].min(), dataset['RM'].max()]
y_range = [dataset['target'].min(), dataset['target'].max()]
scatterplot = dataset.plot(kind='scatter', x='RM', y='target', xlim=x_range, ylim=y_range)
mean_y = scatterplot.plot(x_range, [dataset['target'].mean(), dataset['target'].mean()], '--', color='red', linewidth=1)
mean_x = scatterplot.plot([dataset['RM'].mean(), dataset['RM'].mean()], y_range, '--', color='red', linewidth=1)
Explanation: Visually, a correlation approaches a straight line when plotted as a scatterplot. Correlation is a measure of linear association, i.e., how close to a straight line your data is.
End of explanation |
7,940 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table align="left">
<td>
<a href="https
Step1: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
Step2: Before you begin
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the Vertex AI API and Dataflow API.
If you are running this notebook locally, you will need to install the Cloud SDK.
Enter your project ID in the cell below. Then run the cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.
Note
Step3: Otherwise, set your project ID here.
Step4: Timestamp
If 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 it onto the name of resources you create in this tutorial.
Step5: Authenticate your Google Cloud account
If you are using Google Cloud Notebooks, your environment is already
authenticated. Skip this step.
If you are using Colab, run the cell below and follow the instructions
when prompted to authenticate your account via oAuth.
Otherwise, follow these steps
Step6: Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
When you submit a built-in Swivel job using the Cloud SDK, you need a Cloud Storage bucket for storing the input dataset and pipeline artifacts (the trained model).
Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.
You may also change the REGION variable, which is used for operations
throughout the rest of this notebook. Make sure to choose a region where Vertex AI services are
available. You may
not use a Multi-Regional Storage bucket for training with Vertex AI.
Step7: Only if your bucket doesn't already exist
Step8: Finally, validate access to your Cloud Storage bucket by examining its contents
Step9: 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.
Step10: 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.
Step11: Import libraries and define constants
Define constants used in this tutorial.
Step12: Import packages used in this tutorial.
Step13: Copy and configure the Swivel template
Download the Swivel template and configuration script.
Step14: Change your pipeline configurations
Step15: Both swivel_pipeline_basic.json and swivel_pipeline.json are generated.
Create the Swivel job for MovieLens items embeddings
You will submit the pipeline job by passing the compiled spec to the create_run_from_job_spec() method. Note that you are passing a parameter_values dict that specifies the pipeline input parameters to use.
The following table shows the runtime parameters required by the Swivel job
Step16: Submit the pipeline to Vertex AI
Step17: After the job is submitted successfully, you can view its details (including run name that you'll need below) and logs.
Use TensorBoard to check the model
You may use the TensorBoard to check the model training process. In order to do that, you need to find the path to the trained model artifact. After the job finishes successfully (~ a few hours), you can view the trained model output path in the Vertex ML Metadata browser. It is going to have the following format
Step18: When the training starts, you can view the logs in TensorBoard
Step19: For Google Cloud Notebooks, you can do the following
Step20: Load the movie ids and titles for querying embeddings
Step21: Look up embedding by making an online prediction request
Step22: Explore movie embedding similarities
Step23: Create the Swivel job for Wikipedia text embedding (Optional)
This section shows you how to create embeddings for the movies in the wikipedia dataset using Swivel. You need to do the following steps
Step24: Submit the pipeline job through aiplatform.PipelineJob object.
After the job finishes successfully (~a few hours), you can view the trained model in your CLoud Storage browser. It is going to have the following format
Step25: Explore the trained text embeddings
Load the SavedModel to lookup embeddings for items. Note the following
Step26: You can use the TensorBoard Embedding Projector to graphically represent high dimensional embeddings, which can be helpful in examining and understanding your embeddings.
Cleaning up
To clean up all Google Cloud resources used in this project, you can delete the Google Cloud
project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
!pip3 install {USER_FLAG} --upgrade pip
!pip3 install {USER_FLAG} --upgrade scikit-learn
!pip3 install {USER_FLAG} --upgrade google-cloud-aiplatform tensorboard-plugin-profile
!pip3 install {USER_FLAG} --upgrade tensorflow
Explanation: <table align="left">
<td>
<a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/matching_engine/intro-swivel.ipynb"">
<img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab
</a>
</td>
<td>
<a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/matching_engine/intro-swivel.ipynb">
<img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">
View on GitHub
</a>
</td>
</table>
Overview
This notebook demonstrate how to train an embedding with Submatrix-wise Vector Embedding Learner (Swivel) using Vertex Pipelines. The purpose of the embedding learner is to compute cooccurrences between tokens in a given dataset and to use the cooccurrences to generate embeddings.
Vertex AI provides a pipeline template
for training with Swivel, so you don't need to design your own pipeline or write
your own training code.
It will require you provide a bucket where the dataset will be stored.
Note: you may incur charges for training, storage or usage of other GCP products (Dataflow) in connection with testing this SDK.
Dataset
You will use the following sample datasets in the public bucket gs://cloud-samples-data/vertex-ai/matching-engine/swivel:
movielens_25m: A movie rating dataset for the items input type that you can use to create embeddings for movies. This dataset is processed so that each line contains the movies that have same rating by the same user. The directory also includes movies.csv, which maps the movie ids to their names.
wikipedia: A text corpus dataset created from a Wikipedia dump that you can use to create word embeddings.
Objective
In this notebook, you will learn how to train custom embeddings using Vertex Pipelines and deploy the model for serving. The steps performed include:
Setup: Importing the required libraries and setting your global variables.
Configure parameters: Setting the appropriate parameter values for the pipeline job.
Train on Vertex Pipelines: Create a Swivel job to Vertex Pipelines using pipeline template.
Deploy on Vertex Prediction: Importing and deploying the trained model to a callable endpoint.
Predict: Calling the deployed endpoint using online prediction.
Cleaning up: Deleting resources created by this tutorial.
Costs
This tutorial uses billable components of Google Cloud:
Vertex AI
Dataflow
Cloud Storage
Learn about Vertex AI
pricing, Cloud Storage
pricing, and Dataflow pricing, and use the Pricing
Calculator
to generate a cost estimate based on your projected usage.
Set up your local development environment
If you are using Colab or Google Cloud Notebooks, your environment already meets
all the requirements to run this notebook. You can skip this step.
Otherwise, make sure your environment meets this notebook's requirements.
You need the following:
The Google Cloud SDK
Git
Python 3
virtualenv
Jupyter notebook running in a virtual environment with Python 3
The Google Cloud guide to Setting up a Python development
environment and the Jupyter
installation guide provide detailed instructions
for meeting these requirements. The following steps provide a condensed set of
instructions:
Install and initialize the Cloud SDK.
Install Python 3.
Install
virtualenv
and create a virtual environment that uses Python 3. Activate the virtual environment.
To install Jupyter, run pip3 install jupyter on the
command-line in a terminal shell.
To launch Jupyter, run jupyter notebook on the command-line in a terminal shell.
Open this notebook in the Jupyter Notebook Dashboard.
Install additional packages
Install additional package dependencies not installed in your notebook environment, such as google-cloud-aiplatform, tensorboard-plugin-profile. Use the latest major GA version of each package.
End of explanation
# Automatically restart kernel after installs
import os
if not os.getenv("IS_TESTING"):
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
Explanation: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
End of explanation
import os
PROJECT_ID = ""
# Get your Google Cloud project ID and project number from gcloud
if not os.getenv("IS_TESTING"):
shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
print("Project ID: ", PROJECT_ID)
shell_output = !gcloud projects list --filter="$(gcloud config get-value project)" --format="value(PROJECT_NUMBER)" 2>/dev/null
PROJECT_NUMBER = shell_output[0]
print("Project number: ", PROJECT_NUMBER)
Explanation: Before you begin
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the Vertex AI API and Dataflow API.
If you are running this notebook locally, you will need to install the Cloud SDK.
Enter your project ID in the cell below. Then run the cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.
Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $ into these commands.
Set your project ID
If you don't know your project ID, you may be able to get your project ID using gcloud.
End of explanation
if PROJECT_ID == "" or PROJECT_ID is None:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
Explanation: Otherwise, set your project ID here.
End of explanation
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
Explanation: Timestamp
If 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 it onto the name of resources you create in this tutorial.
End of explanation
import os
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# If on Google Cloud Notebooks, then don't execute this code
if not IS_GOOGLE_CLOUD_NOTEBOOK:
if "google.colab" in sys.modules:
from google.colab import auth as google_auth
google_auth.authenticate_user()
# If you are running this notebook locally, replace the string below with the
# path to your service account key and run this cell to authenticate your GCP
# account.
elif not os.getenv("IS_TESTING"):
%env GOOGLE_APPLICATION_CREDENTIALS ''
Explanation: Authenticate your Google Cloud account
If you are using Google Cloud Notebooks, your environment is already
authenticated. Skip this step.
If you are using Colab, run the cell below and follow the instructions
when prompted to authenticate your account via oAuth.
Otherwise, follow these steps:
In the Cloud Console, go to the Create service account key
page.
Click Create service account.
In the Service account name field, enter a name, and
click Create.
In the Grant this service account access to project section, click the Role drop-down list. Type "Vertex AI"
into the filter box, and select
Vertex AI Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin.
Click Create. A JSON file that contains your key downloads to your
local environment.
Enter the path to your service account key as the
GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell.
End of explanation
BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"}
REGION = "us-central1" # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP
Explanation: Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
When you submit a built-in Swivel job using the Cloud SDK, you need a Cloud Storage bucket for storing the input dataset and pipeline artifacts (the trained model).
Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.
You may also change the REGION variable, which is used for operations
throughout the rest of this notebook. Make sure to choose a region where Vertex AI services are
available. You may
not use a Multi-Regional Storage bucket for training with Vertex AI.
End of explanation
! gsutil mb -l $REGION $BUCKET_NAME
Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket.
End of explanation
! gsutil ls -al $BUCKET_NAME
Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents:
End of explanation
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].split()[1]
print("Service Account:", SERVICE_ACCOUNT)
Explanation: 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.
End of explanation
!gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator $BUCKET_NAME
!gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer $BUCKET_NAME
Explanation: 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.
End of explanation
SOURCE_DATA_PATH = "{}/swivel".format(BUCKET_NAME)
PIPELINE_ROOT = "{}/pipeline_root".format(BUCKET_NAME)
Explanation: Import libraries and define constants
Define constants used in this tutorial.
End of explanation
import pandas as pd
import tensorflow as tf
from google.cloud import aiplatform
from sklearn.metrics.pairwise import cosine_similarity
Explanation: Import packages used in this tutorial.
End of explanation
!gsutil cp gs://cloud-samples-data/vertex-ai/matching-engine/swivel/pipeline/* .
Explanation: Copy and configure the Swivel template
Download the Swivel template and configuration script.
End of explanation
YOUR_PIPELINE_SUFFIX = "swivel-pipeline-movie" # @param {type:"string"}
MACHINE_TYPE = "n1-standard-16" # @param {type:"string"}
ACCELERATOR_COUNT = 2 # @param {type:"integer"}
ACCELERATOR_TYPE = "NVIDIA_TESLA_V100" # @param {type:"string"}
BUCKET = BUCKET_NAME[5:] # remove "gs://" for the following command.
!chmod +x swivel_template_configuration*
!./swivel_template_configuration_basic.sh -pipeline_suffix {YOUR_PIPELINE_SUFFIX} -project_number {PROJECT_NUMBER} -project_id {PROJECT_ID} -machine_type {MACHINE_TYPE} -accelerator_count {ACCELERATOR_COUNT} -accelerator_type {ACCELERATOR_TYPE} -pipeline_root {BUCKET}
!./swivel_template_configuration.sh -pipeline_suffix {YOUR_PIPELINE_SUFFIX} -project_number {PROJECT_NUMBER} -project_id {PROJECT_ID} -machine_type {MACHINE_TYPE} -accelerator_count {ACCELERATOR_COUNT} -accelerator_type {ACCELERATOR_TYPE} -pipeline_root {BUCKET}
Explanation: Change your pipeline configurations:
pipeline_suffix: Suffix of your pipeline name (lowercase and hyphen are allowed).
machine_type: e.g. n1-standard-16.
accelerator_count: Number of GPUs in each machine.
accelerator_type: e.g. NVIDIA_TESLA_P100, NVIDIA_TESLA_V100.
region: e.g. us-east1 (optional, default is us-central1)
network_name: e.g., my_network_name (optional, otherwise it uses "default" network).
VPC Network peering, subnetwork and private IP address configuration
Executing the following cell will generate two files:
1. swivel_pipeline_basic.json: The basic template allows public IPs and default network for the Dataflow job, and doesn't require setting up VPC Network peering for Vertex AI and you will use it in this notebook sample.
1. swivel_pipeline.json: This template enables private IPs and subnet configuration for the Dataflow job, also requires setting up VPC Network peering for the Vertex custom training. This template includes the following args:
* "--subnetwork=regions/%REGION%/subnetworks/%NETWORK_NAME%",
* "--no_use_public_ips",
* \"network\": \"projects/%PROJECT_NUMBER%/global/networks/%NETWORK_NAME%\"
WARNING In order to specify private IPs and configure VPC network, you need to set up VPC Network peering for Vertex AI for your subnetwork (e.g. "default" network on "us-central1") before submitting the following job. This is required for using private IP addresses for DataFlow and Vertex AI.
End of explanation
# Copy the MovieLens sample dataset
! gsutil cp -r gs://cloud-samples-data/vertex-ai/matching-engine/swivel/movielens_25m/train/* {SOURCE_DATA_PATH}/movielens_25m
# MovieLens items embedding sample
PARAMETER_VALUES = {
"embedding_dim": 100, # <---CHANGE THIS (OPTIONAL)
"input_base": "{}/movielens_25m/train".format(SOURCE_DATA_PATH),
"input_type": "items", # For movielens sample
"max_vocab_size": 409600, # <---CHANGE THIS (OPTIONAL)
"num_epochs": 5, # <---CHANGE THIS (OPTIONAL)
}
Explanation: Both swivel_pipeline_basic.json and swivel_pipeline.json are generated.
Create the Swivel job for MovieLens items embeddings
You will submit the pipeline job by passing the compiled spec to the create_run_from_job_spec() method. Note that you are passing a parameter_values dict that specifies the pipeline input parameters to use.
The following table shows the runtime parameters required by the Swivel job:
| Parameter |Data type | Description | Required |
|----------------------------|----------|--------------------------------------------------------------------|------------------------|
| embedding_dim | int | Dimensions of the embeddings to train. | No - Default is 100 |
| input_base | string | Cloud Storage path where the input data is stored. | Yes |
| input_type | string | Type of the input data. Can be either 'text' (for wikipedia sample) or 'items'(for movielens sample). | Yes |
| max_vocab_size | int | Maximum vocabulary size to generate embeddings for. | No - Default is 409600 |
|num_epochs | int | Number of epochs for training. | No - Default is 20 |
In short, the items input type means that each line of your input data should be space-separated item ids. Each line is tokenized by splitting on whitespace. The text input type means that each line of your input data should be equivalent to a sentence. Each line is tokenized by lowercasing, and splitting on whitespace.
End of explanation
# Instantiate PipelineJob object
pl = aiplatform.PipelineJob(
display_name=YOUR_PIPELINE_SUFFIX,
# Whether or not to enable caching
# True = always cache pipeline step result
# False = never cache pipeline step result
# None = defer to cache option for each pipeline component in the pipeline definition
enable_caching=False,
# Local or GCS path to a compiled pipeline definition
template_path="swivel_pipeline_basic.json",
# Dictionary containing input parameters for your pipeline
parameter_values=PARAMETER_VALUES,
# GCS path to act as the pipeline root
pipeline_root=PIPELINE_ROOT,
)
# Submit the Pipeline to Vertex AI
# Optionally you may specify the service account below: submit(service_account=SERVICE_ACCOUNT)
# You must have iam.serviceAccounts.actAs permission on the service account to use it
pl.submit()
Explanation: Submit the pipeline to Vertex AI:
End of explanation
! gsutil -m cp -r gs://cloud-samples-data/vertex-ai/matching-engine/swivel/models/movielens/model {SOURCE_DATA_PATH}/movielens_model
SAVEDMODEL_DIR = os.path.join(SOURCE_DATA_PATH, "movielens_model/model")
LOGS_DIR = os.path.join(SOURCE_DATA_PATH, "movielens_model/tensorboard")
Explanation: After the job is submitted successfully, you can view its details (including run name that you'll need below) and logs.
Use TensorBoard to check the model
You may use the TensorBoard to check the model training process. In order to do that, you need to find the path to the trained model artifact. After the job finishes successfully (~ a few hours), you can view the trained model output path in the Vertex ML Metadata browser. It is going to have the following format:
{BUCKET_NAME}/pipeline_root/{PROJECT_NUMBER}/swivel-{TIMESTAMP}/EmbTrainerComponent_-{SOME_NUMBER}/model/
You may copy this path for the MODELOUTPUT_DIR below.
Alternatively, you can download a pretrained model to {SOURCE_DATA_PATH}/movielens_model and proceed. This pretrained model is for demo purpose and not optimized for production usage.
End of explanation
# If on Google Cloud Notebooks, then don't execute this code.
if not IS_GOOGLE_CLOUD_NOTEBOOK:
if "google.colab" in sys.modules:
# Load the TensorBoard notebook extension.
%load_ext tensorboard
# If on Google Cloud Notebooks, then don't execute this code.
if not IS_GOOGLE_CLOUD_NOTEBOOK:
if "google.colab" in sys.modules:
%tensorboard --logdir $LOGS_DIR
Explanation: When the training starts, you can view the logs in TensorBoard:
End of explanation
ENDPOINT_NAME = "swivel_embedding" # <---CHANGE THIS (OPTIONAL)
MODEL_VERSION_NAME = "movie-tf2-cpu-2.4" # <---CHANGE THIS (OPTIONAL)
aiplatform.init(project=PROJECT_ID, location=REGION)
# Create a model endpoint
endpoint = aiplatform.Endpoint.create(display_name=ENDPOINT_NAME)
# Upload the trained model to Model resource
model = aiplatform.Model.upload(
display_name=MODEL_VERSION_NAME,
artifact_uri=SAVEDMODEL_DIR,
serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-4:latest",
)
# Deploy the Model to the Endpoint
model.deploy(
endpoint=endpoint,
machine_type="n1-standard-2",
)
Explanation: For Google Cloud Notebooks, you can do the following:
Open Cloud Shell from the Google Cloud Console.
Install dependencies: pip3 install tensorflow tensorboard-plugin-profile
Run the following command: tensorboard --logdir {LOGS_DIR}. You will see a message "TensorBoard 2.x.0 at http://localhost:<PORT>/ (Press CTRL+C to quit)" as the output. Take note of the port number.
You can click on the Web Preview button and view the TensorBoard dashboard and profiling results. You need to configure Web Preview's port to be the same port as you receive from step 3.
Deploy the embedding model for online serving
To deploy the trained model, you will perform the following steps:
* Create a model endpoint (if needed).
* Upload the trained model to Model resource.
* Deploy the Model to the endpoint.
End of explanation
!gsutil cp gs://cloud-samples-data/vertex-ai/matching-engine/swivel/movielens_25m/movies.csv ./movies.csv
movies = pd.read_csv("movies.csv")
print(f"Movie count: {len(movies.index)}")
movies.head()
# Change to your favourite movies.
query_movies = [
"Lion King, The (1994)",
"Aladdin (1992)",
"Star Wars: Episode IV - A New Hope (1977)",
"Star Wars: Episode VI - Return of the Jedi (1983)",
"Terminator 2: Judgment Day (1991)",
"Aliens (1986)",
"Godfather, The (1972)",
"Goodfellas (1990)",
]
def get_movie_id(title):
return list(movies[movies.title == title].movieId)[0]
input_items = [str(get_movie_id(title)) for title in query_movies]
Explanation: Load the movie ids and titles for querying embeddings
End of explanation
predictions = endpoint.predict(instances=input_items)
embeddings = predictions.predictions
print(len(embeddings))
Explanation: Look up embedding by making an online prediction request
End of explanation
for idx1 in range(0, len(input_items) - 1, 2):
item1 = input_items[idx1]
title1 = query_movies[idx1]
print(title1)
print("==================")
embedding1 = embeddings[idx1]
for idx2 in range(0, len(input_items)):
item2 = input_items[idx2]
embedding2 = embeddings[idx2]
similarity = round(cosine_similarity([embedding1], [embedding2])[0][0], 5)
title1 = query_movies[idx1]
title2 = query_movies[idx2]
print(f" - Similarity to '{title2}' = {similarity}")
print()
Explanation: Explore movie embedding similarities:
End of explanation
# Copy the wikipedia sample dataset
! gsutil -m cp -r gs://cloud-samples-data/vertex-ai/matching-engine/swivel/wikipedia/* {SOURCE_DATA_PATH}/wikipedia
YOUR_PIPELINE_SUFFIX = "my-first-pipeline-wiki" # @param {type:"string"}
!./swivel_template_configuration.sh -pipeline_suffix {YOUR_PIPELINE_SUFFIX} -project_id {PROJECT_ID} -machine_type {MACHINE_TYPE} -accelerator_count {ACCELERATOR_COUNT} -accelerator_type {ACCELERATOR_TYPE} -pipeline_root {BUCKET}
# wikipedia text embedding sample
PARAMETER_VALUES = {
"embedding_dim": 100, # <---CHANGE THIS (OPTIONAL)
"input_base": "{}/wikipedia".format(SOURCE_DATA_PATH),
"input_type": "text", # For wikipedia sample
"max_vocab_size": 409600, # <---CHANGE THIS (OPTIONAL)
"num_epochs": 20, # <---CHANGE THIS (OPTIONAL)
}
Explanation: Create the Swivel job for Wikipedia text embedding (Optional)
This section shows you how to create embeddings for the movies in the wikipedia dataset using Swivel. You need to do the following steps:
1. Configure the swivel template (using the text input_type) and create a pipeline job.
2. Run the following item embedding exploration code.
The following cell overwrites swivel_pipeline_template.json; the new pipeline template file is almost identical, but it's labeled with your new pipeline suffix to distinguish it. This job will take a few hours.
End of explanation
! gsutil -m cp -r gs://cloud-samples-data/vertex-ai/matching-engine/swivel/models/wikipedia/model {SOURCE_DATA_PATH}/wikipedia_model
SAVEDMODEL_DIR = os.path.join(SOURCE_DATA_PATH, "wikipedia_model/model")
embedding_model = tf.saved_model.load(SAVEDMODEL_DIR)
Explanation: Submit the pipeline job through aiplatform.PipelineJob object.
After the job finishes successfully (~a few hours), you can view the trained model in your CLoud Storage browser. It is going to have the following format:
{BUCKET_NAME}/{PROJECT_NUMBER}/swivel-{TIMESTAMP}/EmbTrainerComponent_-{SOME_NUMBER}/model/
You may copy this path for the MODELOUTPUT_DIR below. For demo purpose, you can download a pretrained model to {SOURCE_DATA_PATH}/wikipedia_model and proceed. This pretrained model is for demo purpose and not optimized for production usage.
End of explanation
input_items = ["horror", "film", '"HORROR! Film"', "horror-film"]
output_embeddings = embedding_model(input_items)
horror_film_embedding = tf.math.reduce_mean(output_embeddings[:2], axis=0)
# Average of embeddings for 'horror' and 'film' equals that for '"HORROR! Film"'
# since preprocessing cleans punctuation and lowercases.
assert tf.math.reduce_all(tf.equal(horror_film_embedding, output_embeddings[2])).numpy()
# Embedding for '"HORROR! Film"' equal that for 'horror-film' since the
# latter contains a hyphenation and thus is a separate token.
assert not tf.math.reduce_all(
tf.equal(output_embeddings[2], output_embeddings[3])
).numpy()
# Change input_items with your own item tokens
input_items = ["apple", "orange", "hammer", "nails"]
output_embeddings = embedding_model(input_items)
for idx1 in range(len(input_items)):
item1 = input_items[idx1]
embedding1 = output_embeddings[idx1].numpy()
for idx2 in range(idx1 + 1, len(input_items)):
item2 = input_items[idx2]
embedding2 = output_embeddings[idx2].numpy()
similarity = round(cosine_similarity([embedding1], [embedding2])[0][0], 5)
print(f"Similarity between '{item1}' and '{item2}' = {similarity}")
Explanation: Explore the trained text embeddings
Load the SavedModel to lookup embeddings for items. Note the following:
* The SavedModel expects a list of string inputs.
* Each string input is treated as a list of space-separated tokens.
* If the input is text, the string input is lowercased with punctuation removed.
* An embedding is generated for each input by looking up the embedding of each token in the input and computing the average embedding per string input.
* The embedding of an out-of-vocabulary (OOV) token is a vector of zeros.
For example, if the input is ['horror', 'film', 'HORROR! Film'], the output will be three embedding vectors, where the third is the average of the first two.
End of explanation
# Delete endpoint resource
# If force is set to True, all deployed models on this Endpoint will be undeployed first.
endpoint.delete(force=True)
# Delete model resource
MODEL_RESOURCE_NAME = model.resource_name
! gcloud ai models delete $MODEL_RESOURCE_NAME --region $REGION --quiet
# Delete Cloud Storage objects that were created
! gsutil -m rm -r $SOURCE_DATA_PATH
Explanation: You can use the TensorBoard Embedding Projector to graphically represent high dimensional embeddings, which can be helpful in examining and understanding your embeddings.
Cleaning up
To clean up all Google Cloud resources used in this project, you can delete the Google Cloud
project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial:
End of explanation |
7,941 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting a Python CASTable Object from an Existing CAS Table
Many of the examples in the Python series of articles here use a CASTable object to invoke actions or apply DataFrame-like syntax to CAS tables. In those examples, the CASTable object is generally the result of an action that loads the CAS table from a data file or other data source. But what if you have a CAS table already loaded in a session and you want to create a new CASTable object that points to it?
The first thing you need is a connection to CAS.
Step1: We'll load a table of data here so we have something to work with. We'll also specify a table name and caslib so they are easier to reference in the next step.
Step2: Using the tableinfo action, we can see that the table exists, however, we didn't store the output of the read_csv method, so we don't have a CASTable object pointing to it.
Step3: The solution is fairly simple, you use the CASTable method of the CAS connection object. You just pass it the name of the table and the name of the CASLib just as it is printed in In[2] above.
Step4: We now have a CASTable object that we can use to interact with. | Python Code:
import swat
conn = swat.CAS(host, port, username, password)
Explanation: Getting a Python CASTable Object from an Existing CAS Table
Many of the examples in the Python series of articles here use a CASTable object to invoke actions or apply DataFrame-like syntax to CAS tables. In those examples, the CASTable object is generally the result of an action that loads the CAS table from a data file or other data source. But what if you have a CAS table already loaded in a session and you want to create a new CASTable object that points to it?
The first thing you need is a connection to CAS.
End of explanation
conn.read_csv('https://raw.githubusercontent.com/sassoftware/sas-viya-programming/master/data/class.csv',
casout=dict(name='class', caslib='casuser'))
Explanation: We'll load a table of data here so we have something to work with. We'll also specify a table name and caslib so they are easier to reference in the next step.
End of explanation
conn.tableinfo(caslib='casuser')
Explanation: Using the tableinfo action, we can see that the table exists, however, we didn't store the output of the read_csv method, so we don't have a CASTable object pointing to it.
End of explanation
cls = conn.CASTable('class', caslib='CASUSER')
cls
Explanation: The solution is fairly simple, you use the CASTable method of the CAS connection object. You just pass it the name of the table and the name of the CASLib just as it is printed in In[2] above.
End of explanation
cls.to_frame()
conn.close()
Explanation: We now have a CASTable object that we can use to interact with.
End of explanation |
7,942 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FLIGHT TRUST
Summary
Simple python script that runs a regression to predict actual flight time and probability of delay of airlines by route. This document takes you through each of the steps to run the regression for both of these predictions. The document is divided into two main sections
Step1: 2. Extract Data
Step2: 3. Select Data
We start by filtering the columns that were considered the most important based on a data analysis made prior to the development of the regression.
We filter by the relevant columns.
Step3: Afterwards, we filter by the important airports (ATL, DFW, JFK, LAX and ORD)
Step4: 4. Sample Data
We now get a random sample Data from the big data set
Step5: 5. Clean Data
Having the sample data, we proceed to clean the data and make sure there are no invalid data in the dataset
First, we trim the string columns to avoid any unexpected error
Step6: Second, we delete any rows with null values
Step7: Third, we change the Actual Elapse Time column to an integer
Step8: Finally, we clean any invalid Data - any flight that has negative time
Step9: 6. Add new Columns
We can now calculate the new columns we need for the regression. Based on a prior data analysis we found that the period of the day is relevant for the delay and flight time of a flight.
So, we first calculate the flight periods columns, where Morning is from 6 to 12 , Afternoon is from 12 to 19, Night is from 19 to 24, and Dawn is from 24 to 6
Step10: We also calculate the delay column, which is one if a flight was cancelled, diverted, or has delayed over 30 min
Step11: 7. Dummy Variables
Now we need to create all of the dummy variables for each of the columns
Step12: Using the dummy variables, we create a table for the regression by concatenating all of the dummy columns and the dependant variable
Step13: 8. Split Test & Learn Datasets
Then, we split the sample data in training and test data set -- Test size is 20% of the hole data set
Step14: And we make sure all variables are an integer for the regression
Step15: 9. 50-50 Data
We now split the data set to make sure that 50% of the rows are delayed flights and 50% are non-delayed flights
We do it for the training data set
Step16: And for the testing data set
Step17: 10. Regression - Delayed
We can finally run the regression for the Delayed dependent Variable
Step18: 11. Regression - Predicted Total Time (Flight time + taxi)
We run the regression to predict the flight time
Step19: VALIDATION AND TESTING
Validate with Test Data -- Delayed Prediction
Using the regression, we predict the outcome for the testing data set for the delay prediction.
Step20: Validate with Test Data -- Predicted Total Time (Flight time + taxi)
Using the regression, we predict the outcome for the testing data set for the flight time prediction.
Step21: Predicted Total Time Graph (Testing set is used here)
Now we create a testing graph where we can see how much if the data is under a specific difference of time.
Step22: Calculate ROC -- Predicted Delay (Testing set is used here)
We calculated the Truth Table
Step23: Finally, we graph the ROC line | Python Code:
import pandas as pd
import statsmodels.api as sm
from sklearn.cross_validation import train_test_split
import math
import numpy as np
import matplotlib.pyplot as plt
Explanation: FLIGHT TRUST
Summary
Simple python script that runs a regression to predict actual flight time and probability of delay of airlines by route. This document takes you through each of the steps to run the regression for both of these predictions. The document is divided into two main sections: the development, which show the development of the regression, and the Validations, which shows how we validated the data and created the ROC curves.
Development
1. Import
First, we start by importing all the neccesary libraries to the project
End of explanation
gdf = pd.read_csv("./CSV/merged.csv")
Explanation: 2. Extract Data
End of explanation
df1 = gdf[['AIRLINE_ID','ORIGIN', 'DEST', 'DEP_TIME','ARR_TIME','DEP_DELAY','ARR_DELAY','CANCELLED','DIVERTED','ACTUAL_ELAPSED_TIME']]
Explanation: 3. Select Data
We start by filtering the columns that were considered the most important based on a data analysis made prior to the development of the regression.
We filter by the relevant columns.
End of explanation
df2 = df1.query('(ORIGIN == "ATL" or ORIGIN == "DFW" or ORIGIN == "JFK" or ORIGIN == "LAX" or ORIGIN == "ORD") and (DEST == "ATL" or DEST == "DFW" or DEST == "JFK" or DEST == "LAX" or DEST == "ORD")')
Explanation: Afterwards, we filter by the important airports (ATL, DFW, JFK, LAX and ORD)
End of explanation
sampledf = df2.sample(n=10000)
print("Sample Size:" + str(len(sampledf.axes[0])))
Explanation: 4. Sample Data
We now get a random sample Data from the big data set
End of explanation
sampledf["AIRLINE_ID"] = sampledf.apply(lambda row: str.strip(str(row.AIRLINE_ID)), axis=1)
sampledf["ORIGIN"] = sampledf.apply(lambda row: str.strip(str(row.ORIGIN)), axis=1)
sampledf["DEST"] = sampledf.apply(lambda row: str.strip(str(row.DEST)), axis=1)
Explanation: 5. Clean Data
Having the sample data, we proceed to clean the data and make sure there are no invalid data in the dataset
First, we trim the string columns to avoid any unexpected error
End of explanation
sampledf = sampledf.dropna()
Explanation: Second, we delete any rows with null values
End of explanation
sampledf["ACTUAL_ELAPSED_TIME"] = sampledf.apply(lambda row: int(float(row.ACTUAL_ELAPSED_TIME)), axis=1)
Explanation: Third, we change the Actual Elapse Time column to an integer
End of explanation
sampledf = sampledf[sampledf.ACTUAL_ELAPSED_TIME >= 0]
Explanation: Finally, we clean any invalid Data - any flight that has negative time
End of explanation
sampledf["Morning"] = sampledf.apply(lambda row: 1 if(not row.CANCELLED and int(row.DEP_TIME) >= 600 and int(row.DEP_TIME) < 1200) else 0, axis=1)
sampledf["Afternoon"] = sampledf.apply(lambda row: 1 if(not row.CANCELLED and int(row.DEP_TIME) >= 1200 and int(row.DEP_TIME) < 1900) else 0, axis=1)
sampledf["Night"] = sampledf.apply(lambda row: 1 if(not row.CANCELLED and int(row.DEP_TIME) >= 1900 and int(row.DEP_TIME) < 2400) else 0, axis=1)
sampledf["Dawn"] = sampledf.apply(lambda row: 1 if(not row.CANCELLED and int(row.DEP_TIME) >= 2400 and int(row.DEP_TIME) < 600) else 0, axis=1)
Explanation: 6. Add new Columns
We can now calculate the new columns we need for the regression. Based on a prior data analysis we found that the period of the day is relevant for the delay and flight time of a flight.
So, we first calculate the flight periods columns, where Morning is from 6 to 12 , Afternoon is from 12 to 19, Night is from 19 to 24, and Dawn is from 24 to 6
End of explanation
sampledf["Delayed"] = sampledf.apply(lambda row: 1 if(row.CANCELLED or row.DIVERTED or row.ARR_DELAY > 30) else 0 , axis=1)
sampledf.columns
Explanation: We also calculate the delay column, which is one if a flight was cancelled, diverted, or has delayed over 30 min
End of explanation
originDummy = pd.get_dummies(sampledf["ORIGIN"], prefix="ORG", drop_first=True)
destDummy = pd.get_dummies(sampledf["DEST"], prefix="DST", drop_first=True)
airlineDummy = pd.get_dummies(sampledf["AIRLINE_ID"], prefix="AIRLN", drop_first=True)
Explanation: 7. Dummy Variables
Now we need to create all of the dummy variables for each of the columns
End of explanation
dummyDf = pd.DataFrame()
dummyDf = pd.concat([originDummy,destDummy,airlineDummy,sampledf['Morning'], sampledf['Afternoon'], sampledf['Night'],sampledf['Delayed'],sampledf['ACTUAL_ELAPSED_TIME']], axis=1)
dummyDf.head()
Explanation: Using the dummy variables, we create a table for the regression by concatenating all of the dummy columns and the dependant variable
End of explanation
trainingDF, testDF = train_test_split(dummyDf, test_size = 0.2)
Explanation: 8. Split Test & Learn Datasets
Then, we split the sample data in training and test data set -- Test size is 20% of the hole data set
End of explanation
trainingDF = trainingDF.applymap(np.int)
testDF = testDF.applymap(np.int)
Explanation: And we make sure all variables are an integer for the regression
End of explanation
trainingDFDelayed = trainingDF[trainingDF.Delayed == 1].head(500)
trainingDFNotDelayed = trainingDF[trainingDF.Delayed == 0].head(500)
allTraining = [trainingDFNotDelayed,trainingDFDelayed]
trainingDF = pd.concat(allTraining)
print("Training Size:" + str(len(trainingDF.axes[0])))
Explanation: 9. 50-50 Data
We now split the data set to make sure that 50% of the rows are delayed flights and 50% are non-delayed flights
We do it for the training data set
End of explanation
testDFDelayed = testDF[testDF.Delayed == 1].head(100)
testDFNotDelayed = testDF[testDF.Delayed == 0].head(100)
allTest = [testDFDelayed,testDFNotDelayed]
testDF = pd.concat(allTest)
print("Testing Size:" + str(len(testDF.axes[0])))
Explanation: And for the testing data set
End of explanation
XValues = sm.add_constant(trainingDF[trainingDF.columns.difference(['Delayed','ACTUAL_ELAPSED_TIME'])], prepend=False)
resultDelayed = sm.OLS(trainingDF['Delayed'], XValues).fit()
print(resultDelayed.summary())
Explanation: 10. Regression - Delayed
We can finally run the regression for the Delayed dependent Variable
End of explanation
XValues = sm.add_constant(trainingDF[trainingDF.columns.difference(['Delayed','ACTUAL_ELAPSED_TIME'])])
resultTime = sm.OLS(trainingDF['ACTUAL_ELAPSED_TIME'], XValues ).fit()
print(resultTime.summary())
Explanation: 11. Regression - Predicted Total Time (Flight time + taxi)
We run the regression to predict the flight time
End of explanation
#Copy of the testing data set
validateDataDelay = testDF.copy()
#Get a subset of the data without the validation data
subsetPredictDelay = validateDataDelay[validateDataDelay.columns.difference(['Delayed','ACTUAL_ELAPSED_TIME'])]
#Predict the outcome with the regression and put the result in a new column
subsetPredictDelay['Calculated_Delay'] = subsetPredictDelay.apply(lambda row: (row * resultDelayed.params).sum(),axis=1)
#Add the real outcome in a new column
subsetPredictDelay["Real_Delayed"] = testDF["Delayed"]
subsetPredictDelay.head()[["Real_Delayed","Calculated_Delay"]]
Explanation: VALIDATION AND TESTING
Validate with Test Data -- Delayed Prediction
Using the regression, we predict the outcome for the testing data set for the delay prediction.
End of explanation
#Copy of the testing data set
validateDataTime = testDF.copy()
subsetPredictTime = validateDataTime[validateDataTime.columns.difference(['Delayed','ACTUAL_ELAPSED_TIME'])]
subsetPredictTime["const"] = 1
subsetPredictTime['Calculated'] = subsetPredictTime.apply(lambda row: (row * resultTime.params).sum(),axis=1)
subsetPredictTime["ACTUAL_ELAPSED_TIME"] = validateDataTime["ACTUAL_ELAPSED_TIME"]
subsetPredictTime["Difference"] = subsetPredictTime.apply(lambda row: abs(row.ACTUAL_ELAPSED_TIME - row.Calculated), axis=1)
subsetPredictTime.head()[["ACTUAL_ELAPSED_TIME","Calculated","Difference"]]
Explanation: Validate with Test Data -- Predicted Total Time (Flight time + taxi)
Using the regression, we predict the outcome for the testing data set for the flight time prediction.
End of explanation
#Create dataframe with the difference ranges
roicTime = pd.DataFrame({"Values":range(int(subsetPredictTime["Difference"].min()),int(subsetPredictTime["Difference"].max()),10)})
roicTime["Percentage"] = roicTime.apply(lambda row: len(subsetPredictTime[subsetPredictTime.Difference < row.Values]["Difference"]) / len(subsetPredictTime["Difference"]) * 100, axis=1 )
plt.plot(roicTime.Values,roicTime.Percentage)
plt.xlabel("Time Difference between actual and predicted (min)")
plt.ylabel("% of Data covered")
plt.title('Predict Time Validation Graph')
plt.show()
Explanation: Predicted Total Time Graph (Testing set is used here)
Now we create a testing graph where we can see how much if the data is under a specific difference of time.
End of explanation
roicDelay = pd.DataFrame({"Values": np.arange(subsetPredictDelay["Calculated_Delay"].min(),subsetPredictDelay["Calculated_Delay"].max(),0.1)})
#True Positive
roicDelay["T_P"] = roicDelay.apply(lambda row:len(subsetPredictDelay[(subsetPredictDelay.Calculated_Delay > row.Values) & (subsetPredictDelay.Real_Delayed == 1)]),axis=1)
#False Positive
roicDelay["F_P"] = roicDelay.apply(lambda row:len(subsetPredictDelay[(subsetPredictDelay.Calculated_Delay > row.Values) & (subsetPredictDelay.Real_Delayed == 0)]),axis=1)
#True Negative
roicDelay["T_N"] = roicDelay.apply(lambda row:len(subsetPredictDelay[(subsetPredictDelay.Calculated_Delay < row.Values) & (subsetPredictDelay.Real_Delayed == 0)]),axis=1)
#False Negative
roicDelay["F_N"] = roicDelay.apply(lambda row:len(subsetPredictDelay[(subsetPredictDelay.Calculated_Delay < row.Values) & (subsetPredictDelay.Real_Delayed == 1)]),axis=1)
roicDelay
Explanation: Calculate ROC -- Predicted Delay (Testing set is used here)
We calculated the Truth Table
End of explanation
#False Posive Ration
roicDelay["F_P_R"] = roicDelay.apply(lambda row: row["F_P"]/(row["F_P"] + row["T_N"]),axis=1)
#Recall Ration
roicDelay["Recall"] = roicDelay.apply(lambda row: row["T_P"]/(row["T_P"] + row["F_N"]),axis=1)
plt.plot(roicDelay["F_P_R"],roicDelay["Recall"] )
plt.xlabel("False Positive Relation")
plt.ylabel("Recall")
plt.title('ROC Chart')
plt.show()
Explanation: Finally, we graph the ROC line
End of explanation |
7,943 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Previous
2.6 字符串忽略大小写的搜索替换
问题
你需要以忽略大小写的方式搜索与替换文本字符串
解决方案
为了在文本操作时忽略大小写,你需要在使用 re 模块的时候给这些操作提供 re.IGNORECASE 标志参数。比如:
Step1: 最后的那个例子揭示了一个小缺陷,替换字符串并不会自动跟被匹配字符串的大小写保持一致。 为了修复这个,你可能需要一个辅助函数,就像下面的这样:
Step2: 下面是使用上述函数的方法: | Python Code:
import re
text = "UPPER PYTHON, lower python, Mixed Python"
re.findall("python", text, flags = re.IGNORECASE)
re.sub("python", "snake", text, flags = re.IGNORECASE)
Explanation: Previous
2.6 字符串忽略大小写的搜索替换
问题
你需要以忽略大小写的方式搜索与替换文本字符串
解决方案
为了在文本操作时忽略大小写,你需要在使用 re 模块的时候给这些操作提供 re.IGNORECASE 标志参数。比如:
End of explanation
def matchcase(word):
def replace(m):
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
return word.capitalize()
else:
return word
return replace
Explanation: 最后的那个例子揭示了一个小缺陷,替换字符串并不会自动跟被匹配字符串的大小写保持一致。 为了修复这个,你可能需要一个辅助函数,就像下面的这样:
End of explanation
re.sub("python", matchcase("snake"), text, flags=re.IGNORECASE)
Explanation: 下面是使用上述函数的方法:
End of explanation |
7,944 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating Simple TFX Pipeline for Vertex Pipelines
Learning objectives
Prepare example data.
Create a pipeline.
Run the pipeline on Vertex Pipelines.
Introduction
In this notebook, you will create a simple TFX pipeline and run it using
Google Cloud Vertex Pipelines. This notebook is based on the TFX pipeline
you built in
Simple TFX Pipeline Tutorial.
If you are not familiar with TFX and you have not read that tutorial yet, you
should read it before proceeding with this notebook.
Google Cloud Vertex Pipelines helps you to automate, monitor, and govern
your ML systems by orchestrating your ML workflow in a serverless manner. You
can define your ML pipelines using Python with TFX, and then execute your
pipelines on Google Cloud. See
Vertex Pipelines introduction
to learn more about Vertex Pipelines.
Each learning objective will correspond to a #TODO in this student lab notebook -- try to complete this notebook first and then review the solution notebook
Install python packages
You will install required Python packages including TFX and KFP to author ML
pipelines and submit jobs to Vertex Pipelines.
Step1: Did you restart the runtime?
You can restart runtime with following cell.
Step2: Check the package versions
Step3: Set up variables
You will set up some variables used to customize the pipelines below. Following
information is required
Step4: Set gcloud to use your project.
Step5: Prepare example data
You will use the same
Palmer Penguins dataset
as
Simple TFX Pipeline Tutorial.
There are four numeric features in this dataset which were already normalized
to have range [0,1]. You will build a classification model which predicts the
species of penguins.
You need to make your own copy of the dataset. Because TFX ExampleGen reads
inputs from a directory, You need to create a directory and copy dataset to it
on GCS.
Step6: Take a quick look at the CSV file.
Step10: Create a pipeline
TFX pipelines are defined using Python APIs. You will define a pipeline which
consists of three components, CsvExampleGen, Trainer and Pusher. The pipeline
and model definition is almost the same as
Simple TFX Pipeline Tutorial.
The only difference is that you don't need to set metadata_connection_config
which is used to locate
ML Metadata database. Because
Vertex Pipelines uses a managed metadata service, users don't need to care
of it, and you don't need to specify the parameter.
Before actually define the pipeline, you need to write a model code for the
Trainer component first.
Write model code.
You will use the same model code as in the
Simple TFX Pipeline Tutorial.
Step11: Copy the module file to GCS which can be accessed from the pipeline components.
Because model training happens on GCP, you need to upload this model definition.
Otherwise, you might want to build a container image including the module file
and use the image to run the pipeline.
Step13: Write a pipeline definition
You will define a function to create a TFX pipeline.
Step14: Run the pipeline on Vertex Pipelines.
You used LocalDagRunner which runs on local environment in
Simple TFX Pipeline Tutorial.
TFX provides multiple orchestrators to run your pipeline. In this tutorial you
will use the Vertex Pipelines together with the Kubeflow V2 dag runner.
You need to define a runner to actually run the pipeline. You will compile
your pipeline into our pipeline definition format using TFX APIs.
Step15: The generated definition file can be submitted using kfp client. | Python Code:
# Use the latest version of pip.
!pip install --upgrade pip
!pip install --upgrade "tfx[kfp]<2"
Explanation: Creating Simple TFX Pipeline for Vertex Pipelines
Learning objectives
Prepare example data.
Create a pipeline.
Run the pipeline on Vertex Pipelines.
Introduction
In this notebook, you will create a simple TFX pipeline and run it using
Google Cloud Vertex Pipelines. This notebook is based on the TFX pipeline
you built in
Simple TFX Pipeline Tutorial.
If you are not familiar with TFX and you have not read that tutorial yet, you
should read it before proceeding with this notebook.
Google Cloud Vertex Pipelines helps you to automate, monitor, and govern
your ML systems by orchestrating your ML workflow in a serverless manner. You
can define your ML pipelines using Python with TFX, and then execute your
pipelines on Google Cloud. See
Vertex Pipelines introduction
to learn more about Vertex Pipelines.
Each learning objective will correspond to a #TODO in this student lab notebook -- try to complete this notebook first and then review the solution notebook
Install python packages
You will install required Python packages including TFX and KFP to author ML
pipelines and submit jobs to Vertex Pipelines.
End of explanation
# docs_infra: no_execute
import sys
if not 'google.colab' in sys.modules:
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
Explanation: Did you restart the runtime?
You can restart runtime with following cell.
End of explanation
import tensorflow as tf
print('TensorFlow version: {}'.format(tf.__version__))
from tfx import v1 as tfx
print('TFX version: {}'.format(tfx.__version__))
import kfp
print('KFP version: {}'.format(kfp.__version__))
Explanation: Check the package versions
End of explanation
GOOGLE_CLOUD_PROJECT = 'qwiklabs-gcp-01-2e305ff9c72b' # Replace this with your Project-ID
GOOGLE_CLOUD_REGION = 'us-central1' # Replace this with your region
GCS_BUCKET_NAME = 'qwiklabs-gcp-01-2e305ff9c72b' # Replace this with your Cloud Storage bucket
if not (GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_REGION and GCS_BUCKET_NAME):
from absl import logging
logging.error('Please set all required parameters.')
Explanation: Set up variables
You will set up some variables used to customize the pipelines below. Following
information is required:
GCP Project id. See
Identifying your project id.
GCP Region to run pipelines. For more information about the regions that
Vertex Pipelines is available in, see the
Vertex AI locations guide.
Google Cloud Storage Bucket to store pipeline outputs.
Enter required values in the cell below before running it.
End of explanation
!gcloud config set project {GOOGLE_CLOUD_PROJECT}
PIPELINE_NAME = 'penguin-vertex-pipelines'
# Path to various pipeline artifact.
PIPELINE_ROOT = 'gs://{}/pipeline_root/{}'.format(
GCS_BUCKET_NAME, PIPELINE_NAME)
# Paths for users' Python module.
MODULE_ROOT = 'gs://{}/pipeline_module/{}'.format(
GCS_BUCKET_NAME, PIPELINE_NAME)
# Paths for input data.
DATA_ROOT = 'gs://{}/data/{}'.format(GCS_BUCKET_NAME, PIPELINE_NAME)
# This is the path where your model will be pushed for serving.
SERVING_MODEL_DIR = 'gs://{}/serving_model/{}'.format(
GCS_BUCKET_NAME, PIPELINE_NAME)
print('PIPELINE_ROOT: {}'.format(PIPELINE_ROOT))
Explanation: Set gcloud to use your project.
End of explanation
!gsutil cp gs://download.tensorflow.org/data/palmer_penguins/penguins_processed.csv {DATA_ROOT}/
Explanation: Prepare example data
You will use the same
Palmer Penguins dataset
as
Simple TFX Pipeline Tutorial.
There are four numeric features in this dataset which were already normalized
to have range [0,1]. You will build a classification model which predicts the
species of penguins.
You need to make your own copy of the dataset. Because TFX ExampleGen reads
inputs from a directory, You need to create a directory and copy dataset to it
on GCS.
End of explanation
# Review the contents of the CSV file
# TODO 1: Your code goes here
Explanation: Take a quick look at the CSV file.
End of explanation
_trainer_module_file = 'penguin_trainer.py'
%%writefile {_trainer_module_file}
# Copied from https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple
from typing import List
from absl import logging
import tensorflow as tf
from tensorflow import keras
from tensorflow_transform.tf_metadata import schema_utils
from tfx import v1 as tfx
from tfx_bsl.public import tfxio
from tensorflow_metadata.proto.v0 import schema_pb2
_FEATURE_KEYS = [
'culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm', 'body_mass_g'
]
_LABEL_KEY = 'species'
_TRAIN_BATCH_SIZE = 20
_EVAL_BATCH_SIZE = 10
# Since you're not generating or creating a schema, you will instead create
# a feature spec. Since there are a fairly small number of features this is
# manageable for this dataset.
_FEATURE_SPEC = {
**{
feature: tf.io.FixedLenFeature(shape=[1], dtype=tf.float32)
for feature in _FEATURE_KEYS
},
_LABEL_KEY: tf.io.FixedLenFeature(shape=[1], dtype=tf.int64)
}
def _input_fn(file_pattern: List[str],
data_accessor: tfx.components.DataAccessor,
schema: schema_pb2.Schema,
batch_size: int) -> tf.data.Dataset:
Generates features and label for training.
Args:
file_pattern: List of paths or patterns of input tfrecord files.
data_accessor: DataAccessor for converting input to RecordBatch.
schema: schema of the input data.
batch_size: representing the number of consecutive elements of returned
dataset to combine in a single batch
Returns:
A dataset that contains (features, indices) tuple where features is a
dictionary of Tensors, and indices is a single Tensor of label indices.
return data_accessor.tf_dataset_factory(
file_pattern,
tfxio.TensorFlowDatasetOptions(
batch_size=batch_size, label_key=_LABEL_KEY),
schema=schema).repeat()
def _make_keras_model() -> tf.keras.Model:
Creates a DNN Keras model for classifying penguin data.
Returns:
A Keras Model.
# The model below is built with Functional API, please refer to
# https://www.tensorflow.org/guide/keras/overview for all API options.
inputs = [keras.layers.Input(shape=(1,), name=f) for f in _FEATURE_KEYS]
d = keras.layers.concatenate(inputs)
for _ in range(2):
d = keras.layers.Dense(8, activation='relu')(d)
outputs = keras.layers.Dense(3)(d)
model = keras.Model(inputs=inputs, outputs=outputs)
model.compile(
optimizer=keras.optimizers.Adam(1e-2),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[keras.metrics.SparseCategoricalAccuracy()])
model.summary(print_fn=logging.info)
return model
# TFX Trainer will call this function.
def run_fn(fn_args: tfx.components.FnArgs):
Train the model based on given args.
Args:
fn_args: Holds args used to train the model as name/value pairs.
# This schema is usually either an output of SchemaGen or a manually-curated
# version provided by pipeline author. A schema can also derived from TFT
# graph if a Transform component is used. In the case when either is missing,
# `schema_from_feature_spec` could be used to generate schema from very simple
# feature_spec, but the schema returned would be very primitive.
schema = schema_utils.schema_from_feature_spec(_FEATURE_SPEC)
train_dataset = _input_fn(
fn_args.train_files,
fn_args.data_accessor,
schema,
batch_size=_TRAIN_BATCH_SIZE)
eval_dataset = _input_fn(
fn_args.eval_files,
fn_args.data_accessor,
schema,
batch_size=_EVAL_BATCH_SIZE)
model = _make_keras_model()
model.fit(
train_dataset,
steps_per_epoch=fn_args.train_steps,
validation_data=eval_dataset,
validation_steps=fn_args.eval_steps)
# The result of the training should be saved in `fn_args.serving_model_dir`
# directory.
model.save(fn_args.serving_model_dir, save_format='tf')
Explanation: Create a pipeline
TFX pipelines are defined using Python APIs. You will define a pipeline which
consists of three components, CsvExampleGen, Trainer and Pusher. The pipeline
and model definition is almost the same as
Simple TFX Pipeline Tutorial.
The only difference is that you don't need to set metadata_connection_config
which is used to locate
ML Metadata database. Because
Vertex Pipelines uses a managed metadata service, users don't need to care
of it, and you don't need to specify the parameter.
Before actually define the pipeline, you need to write a model code for the
Trainer component first.
Write model code.
You will use the same model code as in the
Simple TFX Pipeline Tutorial.
End of explanation
!gsutil cp {_trainer_module_file} {MODULE_ROOT}/
Explanation: Copy the module file to GCS which can be accessed from the pipeline components.
Because model training happens on GCP, you need to upload this model definition.
Otherwise, you might want to build a container image including the module file
and use the image to run the pipeline.
End of explanation
# Copied from https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple and
# slightly modified because you don't need `metadata_path` argument.
def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str,
module_file: str, serving_model_dir: str,
) -> tfx.dsl.Pipeline:
Creates a three component penguin pipeline with TFX.
# Brings data into the pipeline.
example_gen = # TODO 2: Your code goes here
# Uses user-provided Python function that trains a model.
trainer = tfx.components.Trainer(
module_file=module_file,
examples=example_gen.outputs['examples'],
train_args=tfx.proto.TrainArgs(num_steps=100),
eval_args=tfx.proto.EvalArgs(num_steps=5))
# Pushes the model to a filesystem destination.
pusher = tfx.components.Pusher(
model=trainer.outputs['model'],
push_destination=tfx.proto.PushDestination(
filesystem=tfx.proto.PushDestination.Filesystem(
base_directory=serving_model_dir)))
# Following three components will be included in the pipeline.
components = [
example_gen,
trainer,
pusher,
]
return tfx.dsl.Pipeline(
pipeline_name=pipeline_name,
pipeline_root=pipeline_root,
components=components)
Explanation: Write a pipeline definition
You will define a function to create a TFX pipeline.
End of explanation
import os
PIPELINE_DEFINITION_FILE = PIPELINE_NAME + '_pipeline.json'
runner = tfx.orchestration.experimental.KubeflowV2DagRunner(
config=tfx.orchestration.experimental.KubeflowV2DagRunnerConfig(),
output_filename=PIPELINE_DEFINITION_FILE)
# Following function will write the pipeline definition to PIPELINE_DEFINITION_FILE.
_ = runner.run(
_create_pipeline(
pipeline_name=PIPELINE_NAME,
pipeline_root=PIPELINE_ROOT,
data_root=DATA_ROOT,
module_file=os.path.join(MODULE_ROOT, _trainer_module_file),
serving_model_dir=SERVING_MODEL_DIR))
Explanation: Run the pipeline on Vertex Pipelines.
You used LocalDagRunner which runs on local environment in
Simple TFX Pipeline Tutorial.
TFX provides multiple orchestrators to run your pipeline. In this tutorial you
will use the Vertex Pipelines together with the Kubeflow V2 dag runner.
You need to define a runner to actually run the pipeline. You will compile
your pipeline into our pipeline definition format using TFX APIs.
End of explanation
# docs_infra: no_execute
from google.cloud import aiplatform
from google.cloud.aiplatform import pipeline_jobs
import logging
logging.getLogger().setLevel(logging.INFO)
aiplatform.init(project=GOOGLE_CLOUD_PROJECT, location=GOOGLE_CLOUD_REGION)
# Create a job to submit the pipeline
job = # TODO 3: Your code goes here
job.submit()
Explanation: The generated definition file can be submitted using kfp client.
End of explanation |
7,945 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id="top"></a>
UN SDG Indicator 11.3.1
Step3: Population Growth Rate
For calculating the indicator value for this SDG, the formula is the simple average yearly change in population.
For calculating the average yearly population growth rate as a percent (e.g. to show on maps), the following formula
is used
Step5: Land Consumption Rate
For calculating the indicator value for this SDG, the formula is the simple average yearly change in land consumption.
Step6: <a id="import"></a>Import Dependencies and Connect to the Data Cube ▴
Step7: <a id="show_area"></a>Show the Area ▴
Step9: <a id="pop_rate"></a>Determine Population Growth Rate ▴
Load Population Data
<br>Shape files are based on GPW estimates. You can derive similar population figures from AidData GeoQuery at
- http
Step10: Show the Survey Region in the Context of the Country
Step11: Show the Survey Region Alone
Step12: Determine the Shape that Masks the Survey Region
Step13: Calculate Population Growth Rate
Calcuate Population Growth Rate for All Regions Individually
Step14: Visualize Population Growth Rate
Step15: <a id="land_consumption_rate"></a>Determine Land Consumption Rate ▴
Specify Load Parameters
Step16: <a id="false_color_composites"></a>Build Composites for the First and Last Years ▴
Step17: First Year
False Color Composite [nir, swir1, blue]
Step18: Last Year
False Color Composite [nir, swir1, blue]
Step19: <a id="filter_survey_region"></a>Filter Out Everything Except the Survey Region ▴
Step20: First Year Survey Region
False Color Composite [nir, swir1, blue]
Step21: Last Year Survey Region
False Color Composite [nir, swir1, blue]
Step22: <a id="urban_extent"></a>Determine Urban Extent ▴
Urbanization Index Option 1
Step23: Urbanization Index Option 2
Step24: Choose the Urbanization Index to Use
Step25: First Year Urban Composite
Step26: Last Year Urban Composite
Step27: Defining Binary Urbanization
Step28: First Year
Urbanization product overlayed on false color composite
Step29: Last Year
Urbanization Product overlayed on false color composite
Step30: Urbanization Change
Step31: <a id="indicator"></a>SDG Indicator 11.3.1 ▴ | Python Code:
def sdg_11_3_1(land_consumption, population_growth_rate):
return land_consumption/population_growth_rate
Explanation: <a id="top"></a>
UN SDG Indicator 11.3.1:<br> Ratio of Land Consumption Rate to Population Growth Rate
<hr>
Notebook Summary
The United Nations have prescribed 17 "Sustainable Development Goals" (SDGs). This notebook attempts to monitor SDG Indicator 11.3.1 - ratio of land consumption rate to population growth rate.
UN SDG Indicator 11.3.1 provides a metric for determining wether or not land consumption is scaling responsibly with the growth of the population in a given region.
Case Study
This notebook conducts analysis in the Dar es Salaam, Tanzania with reference years of 2000 and 2015.
Index
Define Formulas for Calculating the Indicator
Import Dependencies and Connect to the Data Cube
Show the Area
Determine Population Growth Rate
Determine Land Consumption Rate
Build Composites for the First and Last Years
Filter Out Everything Except the Survey Region
Determine Urban Extent
SDG Indicator 11.3.1
<a id="define_formulas"></a>Define Formulas for Calculating the Indicator ▴
SDG Indicator 11.3.1
The ratio between land consumption and population growth rate.
$$ SDG_{11.1.3} = \frac{LandConsumptionRate}{PopulationGrowthRate} $$
End of explanation
import numpy as np
def population_growth_rate_pct(pop_t1 = None, pop_t2 = None, y = None):
Calculates the average percent population growth rate per year.
Parameters
----------
pop_t1: numeric
The population of the first year.
pop_t2: numberic
The population of the last year.
y: int
The numbers of years between t1 and t2.
Returns
-------
pop_growth_rate: float
The average percent population growth rate per year.
return 10**(np.log10(pop_t2/pop_t1)/y) - 1
def population_growth_rate(pop_t1 = None, pop_t2 = None, y = None):
Calculates the average increase in population per year.
Parameters
----------
pop_t1: numeric
The population of the first year.
pop_t2: numberic
The population of the last year.
y: int
The numbers of years between t1 and t2.
Returns
-------
pop_growth_rate: float
The average increase in population per year.
return (pop_t2 - pop_t1) / y
Explanation: Population Growth Rate
For calculating the indicator value for this SDG, the formula is the simple average yearly change in population.
For calculating the average yearly population growth rate as a percent (e.g. to show on maps), the following formula
is used:
$$ PopulationGrowthRate = 10 ^ {LOG( Pop_{t_2} \space / \space Pop_{t_1}) \space / \space {y}} - 1 $$
Where:
$Pop_{t_2}$ - Total population within the area in the current/final year
$Pop_{t_1}$ - Total population within the area in the past/initial year
$y$ - The number of years between the two measurement periods $t = Year_{t_2} - Year_{t_1}$
End of explanation
def land_consumption_rate(area_t1 = None, area_t2 = None, y = None):
Calculates the average increase in land consumption per year.
Parameters
----------
area_t1: numeric
The number of urbanized pixels for the first year.
area_t2: numberic
The number of urbanized pixels for the last year.
y: int
The numbers of years between t1 and t2.
Returns
-------
pop_growth_rate: float
The average increase in land consumption per year.
return (area_t2 - area_t1) / y
Explanation: Land Consumption Rate
For calculating the indicator value for this SDG, the formula is the simple average yearly change in land consumption.
End of explanation
# Supress Some Warnings
import warnings
warnings.filterwarnings('ignore')
# Allow importing of our utilities.
import sys
import os
sys.path.append(os.environ.get('NOTEBOOK_ROOT'))
# Prepare for plotting.
import matplotlib.pyplot as plt
%matplotlib inline
import datacube
dc = datacube.Datacube()
Explanation: <a id="import"></a>Import Dependencies and Connect to the Data Cube ▴
End of explanation
# Dar es Salaam, Tanzania
latitude_extents = (-6.95, -6.70)
longitude_extents = (39.05, 39.45)
from utils.data_cube_utilities.dc_display_map import display_map
display_map(latitude = latitude_extents, longitude = longitude_extents)
Explanation: <a id="show_area"></a>Show the Area ▴
End of explanation
CSV_FILE_PATH = "../data/Tanzania/population_shape/ADM2_GPWV4_population.csv"
SHAPE_FILE_PATH = "../data/Tanzania/population_shape/TZA_ADM2.geojson"
import geopandas as gpd
import pandas as pd
first_year, last_year = 2000, 2015
first_year_pop_col = 'gpw_v4_count.{}.sum'.format(first_year)
last_year_pop_col = 'gpw_v4_count.{}.sum'.format(last_year)
shape_data = gpd.read_file(SHAPE_FILE_PATH)
shape_data = shape_data[['Name', 'geometry']]
pop_data = pd.read_csv(CSV_FILE_PATH)
pop_data = pop_data[[first_year_pop_col, last_year_pop_col, 'Name']]
pop_data = pop_data.rename({first_year_pop_col: 'pop_t1',
last_year_pop_col: 'pop_t2'}, axis='columns')
country_data = shape_data.merge(pop_data, on='Name')
def shapely_geom_intersects_rect(geom, x, y):
Determines whether the bounding box of a Shapely polygon intesects
a rectangle defined by `x` and `y` extents.
Parameters
----------
geom: shapely.geometry.polygon.Polygon
The object to determine intersection with the region defined by `x` and `y`.
x, y: list-like
The x and y extents, expressed as 2-tuples.
Returns
-------
intersects: bool
Whether the bounding box of `geom` intersects the rectangle.
geom_bounds = np.array(list(geom.bounds))
x_shp, y_shp = geom_bounds[[0,2]], geom_bounds[[1,3]]
x_in_range = (x_shp[0] < x[1]) & (x[0] < x_shp[1])
y_in_range = (y_shp[0] < y[1]) & (y[0] < y_shp[1])
return x_in_range & y_in_range
# `intersecting_shapes` can be examined to determine which districts to ultimately keep.
intersecting_shapes = country_data[country_data.apply(
lambda row: shapely_geom_intersects_rect(row.geometry, longitude_extents, latitude_extents),
axis=1).values]
Explanation: <a id="pop_rate"></a>Determine Population Growth Rate ▴
Load Population Data
<br>Shape files are based on GPW estimates. You can derive similar population figures from AidData GeoQuery at
- http://geo.aiddata.org/query
End of explanation
districts = ['Kinondoni', 'Ilala', 'Temeke']
districts_mask = country_data.Name.isin(districts)
country_data.plot(column=districts_mask, cmap='jet', figsize=(10,10))
survey_region = country_data[districts_mask]
plt.show()
Explanation: Show the Survey Region in the Context of the Country
End of explanation
survey_region.plot( figsize = (10,10))
plt.show()
Explanation: Show the Survey Region Alone
End of explanation
from shapely.ops import cascaded_union
disjoint_areas = cascaded_union([*survey_region.geometry]) ## Top Right is 'disjoint' from bottom left.
Explanation: Determine the Shape that Masks the Survey Region
End of explanation
time_range = last_year - first_year
country_data = country_data.assign(population_growth_rate = \
population_growth_rate_pct(country_data["pop_t1"], country_data["pop_t2"], time_range))
Explanation: Calculate Population Growth Rate
Calcuate Population Growth Rate for All Regions Individually
End of explanation
fig, ax = plt.subplots(figsize = (10, 10))
ax.set_title("Population Growth Rate {}-{}".format(first_year, last_year))
ax1 = country_data.plot(column = "population_growth_rate", ax = ax, legend=True)
survey_region_total_pop_t1 = survey_region["pop_t1"].sum()
survey_region_total_pop_t2 = survey_region["pop_t2"].sum()
pop_growth = population_growth_rate(pop_t1 = survey_region_total_pop_t1,
pop_t2 = survey_region_total_pop_t2,
y = time_range)
print("Annual Population Growth Rate of the Survey Region: {:.2f} People per Year".format(pop_growth))
Explanation: Visualize Population Growth Rate
End of explanation
measurements = ["red", "green", "blue", "nir", "swir1", "swir2", "pixel_qa"]
# Determine the bounding box of the survey region to load data for.
min_lon, min_lat, max_lon, max_lat = disjoint_areas.bounds
lat = (min_lat, max_lat)
lon = (min_lon, max_lon)
product_1 = 'ls7_usgs_sr_scene'
platform_1 = 'LANDSAT_7'
collection_1 = 'c1'
level_1 = 'l2'
product_2 = 'ls8_usgs_sr_scene'
platform_2 = 'LANDSAT_8'
collection_2 = 'c1'
level_2 = 'l2'
# For a full test, each time extent should be 1 full year.
time_extents_t1 = ('2000-01-01', '2000-01-31')
time_extents_t2 = ('2017-01-01', '2017-01-31')
load_params = dict(measurements = measurements,
latitude = lat, longitude = lon, \
dask_chunks={'time':1, 'latitude':1000, 'longitude':1000})
Explanation: <a id="land_consumption_rate"></a>Determine Land Consumption Rate ▴
Specify Load Parameters
End of explanation
from utils.data_cube_utilities.aggregate import xr_scale_res
from utils.data_cube_utilities.clean_mask import landsat_clean_mask_full
from utils.data_cube_utilities.dc_mosaic import create_median_mosaic
# The fraction of the original resolution to use to reduce memory consumption.
frac_res = 0.25
dataset_t1 = dc.load(**load_params, product=product_1, time=time_extents_t1)
clean_mask_t1 = landsat_clean_mask_full(dc, dataset_t1, product=product_1, platform=platform_1,
collection=collection_1, level=level_1)
composite_t1 = create_median_mosaic(dataset_t1, clean_mask_t1.data).compute()
composite_t1 = xr_scale_res(composite_t1, frac_res=frac_res)
composite_t1.attrs = dataset_t1.attrs
del dataset_t1, clean_mask_t1
dataset_t2 = dc.load(**load_params, product=product_2, time=time_extents_t2)
clean_mask_t2 = landsat_clean_mask_full(dc, dataset_t2, product=product_2, platform=platform_2,
collection=collection_2, level=level_2)
composite_t2 = create_median_mosaic(dataset_t2, clean_mask_t2.data).compute()
composite_t2 = xr_scale_res(composite_t2, frac_res=frac_res)
composite_t2.attrs = dataset_t2.attrs
del dataset_t2, clean_mask_t2
Explanation: <a id="false_color_composites"></a>Build Composites for the First and Last Years ▴
End of explanation
from utils.data_cube_utilities.dc_rgb import rgb
rgb(composite_t1, bands = ["nir","swir1","blue"], width = 15)
plt.title('Year {}'.format(first_year))
plt.show()
Explanation: First Year
False Color Composite [nir, swir1, blue]
End of explanation
rgb(composite_t2, bands = ["nir","swir1","blue"], width = 15)
plt.title('Year {}'.format(last_year))
plt.show()
Explanation: Last Year
False Color Composite [nir, swir1, blue]
End of explanation
import rasterio.features
from datacube.utils import geometry
import xarray as xr
def generate_mask(loaded_dataset:xr.Dataset,
geo_polygon: datacube.utils.geometry ):
return rasterio.features.geometry_mask(
[geo_polygon],
out_shape = loaded_dataset.geobox.shape,
transform = loaded_dataset.geobox.affine,
all_touched = False,
invert = True)
mask = generate_mask(composite_t1, disjoint_areas)
filtered_composite_t1 = composite_t1.where(mask)
del composite_t1
filtered_composite_t2 = composite_t2.where(mask)
del composite_t2
Explanation: <a id="filter_survey_region"></a>Filter Out Everything Except the Survey Region ▴
End of explanation
rgb(filtered_composite_t1, bands = ["nir","swir1","blue"],width = 15)
plt.show()
Explanation: First Year Survey Region
False Color Composite [nir, swir1, blue]
End of explanation
rgb(filtered_composite_t2, bands = ["nir","swir1","blue"],width = 15)
plt.show()
Explanation: Last Year Survey Region
False Color Composite [nir, swir1, blue]
End of explanation
def NDBI(dataset):
return (dataset.swir1 - dataset.nir)/(dataset.swir1 + dataset.nir)
Explanation: <a id="urban_extent"></a>Determine Urban Extent ▴
Urbanization Index Option 1: NDBI
The Normalized Difference Built-up Index (NDBI) is quick to calculate, but is sometimes inaccurate (e.g. in very arid regions).
End of explanation
from utils.data_cube_utilities.dc_fractional_coverage_classifier import frac_coverage_classify
Explanation: Urbanization Index Option 2: Fractional Cover Bare Soil
The fractional cover bare soil index is very slow to calculate in its current implementation, but is often more accurate than NDBI.
End of explanation
# Can be 'NDBI' or 'Fractional Cover Bare Soil'.
urbanization_index = 'Fractional Cover Bare Soil'
urban_index_func = None
urban_index_range = None
if urbanization_index == 'NDBI':
urban_index_func = NDBI
urban_index_range = [-1, 1]
if urbanization_index == 'Fractional Cover Bare Soil':
urban_index_func = lambda dataset: frac_coverage_classify(dataset).bs
urban_index_range = [0, 100]
plot_kwargs = dict(vmin=urban_index_range[0], vmax=urban_index_range[1])
Explanation: Choose the Urbanization Index to Use
End of explanation
urban_composite_t1 = urban_index_func(filtered_composite_t1)
plt.figure(figsize = (19.5, 14))
urban_composite_t1.plot(**plot_kwargs)
plt.show()
Explanation: First Year Urban Composite
End of explanation
urban_composite_t2 = urban_index_func(filtered_composite_t2)
plt.figure(figsize = (19.5, 14))
urban_composite_t2.plot(**plot_kwargs)
plt.show()
Explanation: Last Year Urban Composite
End of explanation
def urbanizaton(urban_index: xr.Dataset, urbanization_index) -> xr.DataArray:
bounds = None
if urbanization_index == 'NDBI':
bounds = (0,0.3)
if urbanization_index == 'Fractional Cover Bare Soil':
bounds = (20, 100)
urban = np.logical_and(urban_index > min(bounds), urban_index < max(bounds))
is_clean = np.isfinite(urban_index)
urban = urban.where(is_clean)
return urban
urban_product_t1 = urbanizaton(urban_composite_t1, urbanization_index)
urban_product_t2 = urbanizaton(urban_composite_t2, urbanization_index)
Explanation: Defining Binary Urbanization
End of explanation
rgb(filtered_composite_t1,
bands = ["nir","swir1","blue"],
paint_on_mask = [(np.logical_and(urban_product_t1.astype(bool), mask), [255,0,0])],
width = 15)
plt.show()
Explanation: First Year
Urbanization product overlayed on false color composite
End of explanation
rgb(filtered_composite_t2,
bands = ["nir","swir1","blue"],
paint_on_mask = [(np.logical_and(urban_product_t2.astype(bool), mask),[255,0,0])],
width = 15)
plt.show()
Explanation: Last Year
Urbanization Product overlayed on false color composite
End of explanation
fig = plt.figure(figsize = (15,5))
#T1 (LEFT)
ax1 = fig.add_subplot(121)
urban_product_t1.plot(cmap = "Reds")
ax1.set_title("Urbanization Extent {}".format(first_year))
#T2 (RIGHT)
ax2 = fig.add_subplot(122)
urban_product_t2.plot(cmap = "Reds")
ax2.set_title("Urbanization Extent {}".format(last_year))
plt.show()
comp_lat = filtered_composite_t1.latitude
meters_per_deg_lat = 111000 # 111 km per degree latitude
deg_lat = np.abs(np.diff(comp_lat[[0, -1]])[0])
meters_lat = meters_per_deg_lat * deg_lat
sq_meters_per_px = (meters_lat / len(comp_lat))**2
# Calculation the square meters of urbanized area.
urbanized_area_t1 = float( urban_product_t1.sum() * sq_meters_per_px )
urbanized_area_t2 = float( urban_product_t2.sum() * sq_meters_per_px )
consumption_rate = land_consumption_rate(area_t1 = urbanized_area_t1, area_t2 = urbanized_area_t2, y = time_range)
print("Land Consumption Rate of the Survey Region: {:.2f} Square Meters per Year".format(consumption_rate))
Explanation: Urbanization Change
End of explanation
indicator_val = sdg_11_3_1(consumption_rate,pop_growth)
print("The UN SDG 11.3.1 Indicator value (ratio of land consumption rate to population growth rate) "\
"for this survey region for the specified parameters "\
"is {:.2f} square meters per person.".format(indicator_val))
print("")
print("In other words, on average, according to this analysis, every new person is consuming {:.2f} square meters of land in total.".format(indicator_val))
Explanation: <a id="indicator"></a>SDG Indicator 11.3.1 ▴
End of explanation |
7,946 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting Examples
In this notebook, we demonstrate how to write a simple Model, run an SMC updater for several experiments, then plot the resulting posterior distribution.
Preamble
Before anything else, it's helpful to take care of some boiler plate. First, we want to enable pylab inline mode so that the plots will be associated with this notebook.
Step1: Next, it's a good idea in any Python 2.x program to turn on the division feature. This ensures that the / operator always returns a float if its arguments are numeric.
Step2: Having set things up, we can now import the parts of QInfer that we will be using in this example.
Step3: Model Definition
For this example, we'll be using a very simple likelihood function,
$$
\Pr(0 | \omega_1, \omega_2; t_1, t_2) = \cos^2(\omega_1 t_1) \cos^2(\omega_2 t_2).
$$
The model parameters for this function are $\vec{x} = (\omega_1, \omega_2)$, and the experimental
parameters are $\vec{e} = (t_1, t_2)$.
This likelihood function demonstrates many of the core concepts we want to explore here, but is simple enough to implement quickly.
Step4: Now that we've defined a model, we can make an instance.
Step5: The prior we take to be $\pi(\omega_1, \omega_2) = 1$ for all $\omega_i \in [0, 1]$.
Step6: Finally, we can pass the model and the prior to the updater. We will use 2500 particles.
Step7: Let's run a few experiments.
Step8: Using the plot_posterior_contour method of SMCUpdater, we can quickly produce a contour plot of the current posterior distribution.
Step9: Using posterior_mesh, we can also get to the raw mesh of kernel density estimated points and feed it to other plotting functions, such as imshow. | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
try: plt.style.use('ggplot')
except: pass
Explanation: Plotting Examples
In this notebook, we demonstrate how to write a simple Model, run an SMC updater for several experiments, then plot the resulting posterior distribution.
Preamble
Before anything else, it's helpful to take care of some boiler plate. First, we want to enable pylab inline mode so that the plots will be associated with this notebook.
End of explanation
from __future__ import division, print_function
Explanation: Next, it's a good idea in any Python 2.x program to turn on the division feature. This ensures that the / operator always returns a float if its arguments are numeric.
End of explanation
import qinfer as qi
import scipy.stats
Explanation: Having set things up, we can now import the parts of QInfer that we will be using in this example.
End of explanation
# We start off by making a new class that inherits from Model.
class MultiCosModel(qi.FiniteOutcomeModel):
# We need to specify how many model parameters this model has.
@property
def n_modelparams(self):
return 2
# The number of outcomes is always 2, so we indicate that it's constant
# and define the n_outcomes method to return that constant.
@property
def is_n_outcomes_constant(self):
return True
def n_outcomes(self, expparams):
return 2
# Next, we denote that the experiment parameters are represented by a
# single field of two floats.
@property
def expparams_dtype(self):
return [('ts', '2float')]
# Valid models are defined to lie in the range [0, 1].
def are_models_valid(self, modelparams):
return np.all(np.logical_and(modelparams > 0, modelparams <= 1), axis=1)
# Finally, the likelihood function itself.
def likelihood(self, outcomes, modelparams, expparams):
# We first call the superclass method, which basically
# just makes sure that call count diagnostics are properly
# logged.
super(MultiCosModel, self).likelihood(outcomes, modelparams, expparams)
# Next, since we have a two-outcome model, everything is defined by
# Pr(0 | modelparams; expparams), so we find the probability of 0
# for each model and each experiment.
#
# We do so by taking a product along the modelparam index (len 2,
# indicating omega_1 or omega_2), then squaring the result.
pr0 = np.prod(
np.cos(
# shape (n_models, 1, 2)
modelparams[:, np.newaxis, :] *
# shape (n_experiments, 2)
expparams['ts']
), # <- broadcasts to shape (n_models, n_experiments, 2).
axis=2 # <- product over the final index (len 2)
) ** 2 # square each element
# Now we use pr0_to_likelihood_array to turn this two index array
# above into the form expected by SMCUpdater and other consumers
# of likelihood().
return qi.FiniteOutcomeModel.pr0_to_likelihood_array(outcomes, pr0)
Explanation: Model Definition
For this example, we'll be using a very simple likelihood function,
$$
\Pr(0 | \omega_1, \omega_2; t_1, t_2) = \cos^2(\omega_1 t_1) \cos^2(\omega_2 t_2).
$$
The model parameters for this function are $\vec{x} = (\omega_1, \omega_2)$, and the experimental
parameters are $\vec{e} = (t_1, t_2)$.
This likelihood function demonstrates many of the core concepts we want to explore here, but is simple enough to implement quickly.
End of explanation
m = MultiCosModel()
Explanation: Now that we've defined a model, we can make an instance.
End of explanation
prior = qi.UniformDistribution([[0, 1], [0, 1]])
Explanation: The prior we take to be $\pi(\omega_1, \omega_2) = 1$ for all $\omega_i \in [0, 1]$.
End of explanation
updater = qi.SMCUpdater(m, 2500, prior)
Explanation: Finally, we can pass the model and the prior to the updater. We will use 2500 particles.
End of explanation
true = prior.sample()
for idx_exp in range(50):
# Use the variance in the posterior to set the time we evolve for.
# Note that this is a slight generalization of the
# particle guess heuristic introduced in [].
#
# We slow it down by 30% to ensure unimodality, since we
# don't have an inversion argument here.
expparams = np.array([
# We want one element...
(
# ...containing an array.
0.7 / (2 * np.pi * np.diag(scipy.linalg.sqrtm(updater.est_covariance_mtx()))),
)
], dtype=m.expparams_dtype)
o = m.simulate_experiment(true, expparams)
updater.update(o, expparams)
Explanation: Let's run a few experiments.
End of explanation
updater.plot_posterior_contour(res1=60, res2=60)
plt.plot(true[0, 0], true[0, 1], 'r.', markersize=12)
Explanation: Using the plot_posterior_contour method of SMCUpdater, we can quickly produce a contour plot of the current posterior distribution.
End of explanation
w1s, w2s, Z = updater.posterior_mesh(res1=60, res2=60)
plt.imshow(Z, origin='lower', extent=[np.min(w1s), np.max(w1s), np.min(w2s), np.max(w2s)])
plt.colorbar()
plt.plot(true[0, 0], true[0, 1], 'r.', markersize=12)
Explanation: Using posterior_mesh, we can also get to the raw mesh of kernel density estimated points and feed it to other plotting functions, such as imshow.
End of explanation |
7,947 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1-D
Series
Step1: x-D
Dataframes
The most important feature pandas gives us access to is the DataFrame. Dataframes are two-dimensional stucutres that you can think of very much like a spreadsheet with named columns and rows. In fact, it supports reading in CSV and Excel files.
First, let's read a CSV containing population information of the States of the USA.
Step2: To see what our data looks like, we can use df.head(n) to see the first n rows, with n=5 the default
Step3: We see that for each state we have two IDs and then 6 columns of years - in this case each column is the population of that state during the given year.
We can acess columns by referencing the column name just like a python dictionary
Step4: We can get multiple columns at once by passing a list of column names
Step5: And then we can access groups of rows using a range of row IDs
Step6: Accessing individual rows is different. You can't just use df[i]. Instead you need to use df.loc
Step7: Pandas gives us an easy way to get summary statistics of our data
Step8: One thing you might notice is that describe only lists the numeric columns, but Id2 is included in that even though it would be better to treat it as a string. pandas tries to guess the datatype of each column and in this case, all of the values in Id2 are integers, so it gets treated as an integer.
We can see the datatype details
Step9: We can cast Id2 to a string using astype and then override the original column
Step10: Or we could have specified the data type when we originally read the CSV
Step11: Operations and Filtering
Each column of data behaves very much like a normal numpy array and thus can be used for mathematical operations. For example, to get the population change from 2014 to 2015 for each state
Step12: Rather than continually computing that value, we can save it to a new column in the DataFrame. Let's make a new column called 'change'
Step13: Just like numpy, we can also do element-wise comparisons. For example, to find out whether a state's population decreased over that year
Step14: The True values are the states with negative population change (decrease). But that boolean array by itself isn't very useful. We can use that array as an index to filter our DataFrame
Step15: Now we have a subset of the DataFrame with only the decreasing populations.
Statistical Operations
Step16: Merging DataFrames
If you have data across multiple files, as long as there is a common column they can be joined. To start with, let's read in a CSV which contains the number of housing units in the state for each year from 2010-2015.
Step17: Since the Id column is shared, it can easily be merged with our original DataFrame
Step18: Since the column names are all shared, pandas appends '_x' and '_y' to columns from the left and right dataframes, respectively.
This isn't very user-friendly, so we can use the parameter suffixes to specify custom labels to append. Furthermore, we can also specify Id2 and Geography in on so we don't duplicate those columns.
Step19: We can also notice that when we did the merge, we lost one row. That is because the housing dataset didn't contain data for Puerto Rico.
Step20: Now we can do something involving both datasets. For example, finding the ratio of people to houses
Step21: Now let's use sort_values to view the states with the lowest ratio of people to houses and view just the state name and ratio columns
Step22: And now to view the top 5 use ascending=False
Step23: Grouping Rows by Value
Sometimes you'd like to aggregate groups of similar rows. For instance, let's compare the change in housing stock between the states with decreasing population to those with increasing population.
First let's make a column for the housing change and make a column with either True or False for whether the population is increasing.
Step24: Then use groupby to group our rows by whether they had an increasing or decreasing population change from 2014-2015
Step25: Then we can run aggeregate functions on our groups or describe to run the same summary statistics we did before
Step26: We can see that the average housing increase for states with decreasing population is lower. But the change in housing for all those states is still positive.
Statistical Operations | Python Code:
s = pd.Series([4, 7, -5, 3])
s
s.index
s.values
s[1:3]
s2 = s**2
s2
s2+s
print(np.sum(s))
print(np.mean(s))
print(np.std(s))
s3 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
s3
# !!!
s2+s3
s4 = pd.Series({'d':10, 'b':12, 'a':3, 'c':9})
s4
s3+s4
Explanation: 1-D
Series
End of explanation
# Create a DataFrame, `df`, from the csv located in `data/population.csv`
df = pd.read_csv('../../data/population.csv')
Explanation: x-D
Dataframes
The most important feature pandas gives us access to is the DataFrame. Dataframes are two-dimensional stucutres that you can think of very much like a spreadsheet with named columns and rows. In fact, it supports reading in CSV and Excel files.
First, let's read a CSV containing population information of the States of the USA.
End of explanation
df.head()
Explanation: To see what our data looks like, we can use df.head(n) to see the first n rows, with n=5 the default:
End of explanation
df['2010'].head()
Explanation: We see that for each state we have two IDs and then 6 columns of years - in this case each column is the population of that state during the given year.
We can acess columns by referencing the column name just like a python dictionary:
End of explanation
df[['2010', '2011']].head()
Explanation: We can get multiple columns at once by passing a list of column names:
End of explanation
df[5:10]
Explanation: And then we can access groups of rows using a range of row IDs:
End of explanation
df.loc[20]
type(df.loc[20])
Explanation: Accessing individual rows is different. You can't just use df[i]. Instead you need to use df.loc:
End of explanation
df.describe()
Explanation: Pandas gives us an easy way to get summary statistics of our data:
End of explanation
df.dtypes
Explanation: One thing you might notice is that describe only lists the numeric columns, but Id2 is included in that even though it would be better to treat it as a string. pandas tries to guess the datatype of each column and in this case, all of the values in Id2 are integers, so it gets treated as an integer.
We can see the datatype details:
End of explanation
df['Id2'] = df['Id2'].astype(str)
df.dtypes
Explanation: We can cast Id2 to a string using astype and then override the original column:
End of explanation
# Pass a dictionary to the dtype parameter with `'column': dtype`
df = pd.read_csv('../../data/population.csv', dtype={'Id2': str})
df.dtypes
Explanation: Or we could have specified the data type when we originally read the CSV:
End of explanation
df['2015'] - df['2014']
Explanation: Operations and Filtering
Each column of data behaves very much like a normal numpy array and thus can be used for mathematical operations. For example, to get the population change from 2014 to 2015 for each state:
End of explanation
df['pop_change'] = df['2015'] - df['2014']
df.head()
Explanation: Rather than continually computing that value, we can save it to a new column in the DataFrame. Let's make a new column called 'change':
End of explanation
df['pop_change'] < 0
Explanation: Just like numpy, we can also do element-wise comparisons. For example, to find out whether a state's population decreased over that year:
End of explanation
df[df['pop_change'] < 0]
Explanation: The True values are the states with negative population change (decrease). But that boolean array by itself isn't very useful. We can use that array as an index to filter our DataFrame:
End of explanation
print(df.mean())
print(df.std())
print(df.max())
print(df.sum())
# or over single columns
print(df[['2010','2011']].mean())
Explanation: Now we have a subset of the DataFrame with only the decreasing populations.
Statistical Operations
End of explanation
housing = pd.read_csv('../../data/housing.csv', dtype={'Id2': str})
housing.head()
Explanation: Merging DataFrames
If you have data across multiple files, as long as there is a common column they can be joined. To start with, let's read in a CSV which contains the number of housing units in the state for each year from 2010-2015.
End of explanation
merged = df.merge(housing, on='Id')
merged.head()
Explanation: Since the Id column is shared, it can easily be merged with our original DataFrame:
End of explanation
merged = df.merge(housing, on=['Id', 'Id2', 'Geography'], suffixes=('_population', '_housing'))
merged.head()
Explanation: Since the column names are all shared, pandas appends '_x' and '_y' to columns from the left and right dataframes, respectively.
This isn't very user-friendly, so we can use the parameter suffixes to specify custom labels to append. Furthermore, we can also specify Id2 and Geography in on so we don't duplicate those columns.
End of explanation
print('Population:', len(df), 'Merged:', len(merged))
Explanation: We can also notice that when we did the merge, we lost one row. That is because the housing dataset didn't contain data for Puerto Rico.
End of explanation
merged['ratio'] = merged['2015_population']/merged['2015_housing']
merged['ratio'].head()
Explanation: Now we can do something involving both datasets. For example, finding the ratio of people to houses:
End of explanation
# Sort the data by ratio
merged_sorted = merged.sort_values(by=['ratio'])
# Just get the `Geography` and `ratio` columns
merged_subset = merged_sorted[['Geography', 'ratio']]
# View the first 5
merged_subset.head()
Explanation: Now let's use sort_values to view the states with the lowest ratio of people to houses and view just the state name and ratio columns:
End of explanation
merged.sort_values(by=['ratio'], ascending=False)[['Geography', 'ratio']].head()
Explanation: And now to view the top 5 use ascending=False:
End of explanation
merged['housing_change'] = merged['2015_housing'] - merged['2014_housing']
merged['pop_change_increasing'] = merged['pop_change'] > 0
Explanation: Grouping Rows by Value
Sometimes you'd like to aggregate groups of similar rows. For instance, let's compare the change in housing stock between the states with decreasing population to those with increasing population.
First let's make a column for the housing change and make a column with either True or False for whether the population is increasing.
End of explanation
grouped = merged.groupby('pop_change_increasing')
Explanation: Then use groupby to group our rows by whether they had an increasing or decreasing population change from 2014-2015:
End of explanation
grouped.describe()['housing_change']
Explanation: Then we can run aggeregate functions on our groups or describe to run the same summary statistics we did before:
End of explanation
grouped.mean()
grouped.mean()['housing_change']
Explanation: We can see that the average housing increase for states with decreasing population is lower. But the change in housing for all those states is still positive.
Statistical Operations
End of explanation |
7,948 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Double clik to put your name(s) here
Instructions
Run the code in each cell by holding down the shift key and pushing Return (Enter)
DOWNLOAD A COPY OF THIS NOTEBOOK when you are done!
Step1: The cell below defines the potential
Step2: Double click here to edit, and describe this potential in words
Step4: YOU NEED TO ADD THE CODE BELOW TO CALCULATE PSI
Step5: The cell below calculates $\psi$ and graphs it
Change the upper and lower energies until you get a valid solution. | Python Code:
from __future__ import division, print_function
import numpy as np
from ipywidgets import interact
import matplotlib.pyplot as plt
%matplotlib nbagg
Explanation: Double clik to put your name(s) here
Instructions
Run the code in each cell by holding down the shift key and pushing Return (Enter)
DOWNLOAD A COPY OF THIS NOTEBOOK when you are done!
End of explanation
def potential(x, V0=20.0):
if x < 0 or x > 1:
return V0
else:
return 0
Explanation: The cell below defines the potential
End of explanation
# Smallest position for which we will calculate psi
x_min = -1
# Largest position for which we will calculate psi
x_max = 2
# Number of points
n_points = 1000
# Create a list of all points at which we will calculate psi, and the spacing
# between those points.
all_x, delta_x = np.linspace(x_min, x_max, num=n_points, retstep=True)
Explanation: Double click here to edit, and describe this potential in words
End of explanation
def wave_function(E, all_x, delta_x, psi_0=0.0001, dpsi_dx_0=0):
Calculate the wave function at the positions all_x.
Parameters
----------
E : float
Energy to use in calculating psi. Most Energies do *not* lead to physical
solutions.
all_x : numpy array
Positions at which psi should be calculated.
delta_x: float
Spacing between those positions.
psi_0: float, optional
Value of the wave function at the first position.
dpsi_dx_0: float, optional
Value of the derivative of psi at the first position.
Returns
-------
psi: numpy array
Wave function at all positions.
## FILL THIS IN WITH REAL CODE (which will include a loop)
return np.array(psi)
Explanation: YOU NEED TO ADD THE CODE BELOW TO CALCULATE PSI
End of explanation
plt.figure(figsize=(12,10))
E_min = 2.0
E_max = 10.0
for E in np.linspace(E_min, E_max, num=7):
plt.plot(all_x, wave_function(E, all_x), label=str(E))
plt.legend(loc='lower left')
Explanation: The cell below calculates $\psi$ and graphs it
Change the upper and lower energies until you get a valid solution.
End of explanation |
7,949 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pythonic Syntactic Sugar
The Image Basics Notebook was straight forward and closely follows ITK's C++ interface.
Sugar is great it gives your energy to get things done faster! SimpleITK has applied a generous about of syntactic sugar to help get things done faster too.
Step1: Let us begin by developing a convenient method for displaying images in our notebooks.
Step2: Multi-dimension slice indexing
If you are familiar with numpy, sliced index then this should be cake for the SimpleITK image. The Python standard slice interface for 1-D object
Step3: Cropping
Step4: Flipping
Step5: Slice Extraction
A 2D image can be extracted from a 3D one.
Step6: Super Sampling
Step7: Mathematical Operators
Most python mathematical operators are overloaded to call the SimpleITK filter which does that same operation on a per-pixel basis. They can operate on a two images or an image and a scalar.
If two images are used then both must have the same pixel type. The output image type is ussually the same.
As these operators basically call ITK filter, which just use raw C++ operators, care must be taked to prevent overflow, and divide by zero etc.
<table>
<tr><td>Operators</td></tr>
<tr><td>+</td></tr>
<tr><td>-</td></tr>
<tr><td>\*</td></tr>
<tr><td>/</td></tr>
<tr><td>//</td></tr>
<tr><td>**</td></tr>
<table>
Step8: Division Operators
All three Python division operators are implemented __floordiv__, __truediv__, and __div__.
The true division's output is a double pixle type.
See PEP 238 to see why Python changed the division operator in Python 3.
Bitwise Logic Operators
<table>
<tr><td>Operators</td></tr>
<tr><td>&</td></tr>
<tr><td>|</td></tr>
<tr><td>^</td></tr>
<tr><td>~</td></tr>
<table>
Step9: Comparative Operators
<table>
<tr><td>Operators</td></tr>
<tr><td>\></td></tr>
<tr><td>\>=</td></tr>
<tr><td><</td></tr>
<tr><td><=</td></tr>
<tr><td>==</td></tr>
<table>
These comparative operators follow the same convention as the reset of SimpleITK for binary images. They have the pixel type of ``sitkUInt8`` with values of 0 and 1.
Step10: Amazingly make common trivial tasks really trivial | Python Code:
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rc('image', aspect='equal')
%matplotlib inline
import SimpleITK as sitk
# Download data to work on
from downloaddata import fetch_data as fdata
Explanation: Pythonic Syntactic Sugar
The Image Basics Notebook was straight forward and closely follows ITK's C++ interface.
Sugar is great it gives your energy to get things done faster! SimpleITK has applied a generous about of syntactic sugar to help get things done faster too.
End of explanation
img = sitk.GaussianSource(size=[64]*2)
plt.imshow(sitk.GetArrayFromImage(img))
img = sitk.GaborSource(size=[64]*2, frequency=.03)
plt.imshow(sitk.GetArrayFromImage(img))
def myshow(img):
nda = sitk.GetArrayFromImage(img)
plt.imshow(nda)
myshow(img)
Explanation: Let us begin by developing a convenient method for displaying images in our notebooks.
End of explanation
img[24,24]
Explanation: Multi-dimension slice indexing
If you are familiar with numpy, sliced index then this should be cake for the SimpleITK image. The Python standard slice interface for 1-D object:
<table>
<tr><td>Operation</td> <td>Result</td></tr>
<tr><td>d[i]</td> <td>ith item of d, starting index 0</td></tr>
<tr><td>d[i:j]</td> <td>slice of d from i to j</td></tr>
<tr><td>d[i:j:k]</td> <td>slice of d from i to j with step k</td></tr>
</table>
With this convient syntax many basic tasks can be easily done.
End of explanation
myshow(img[16:48,:])
myshow(img[:,16:-16])
myshow(img[:32,:32])
Explanation: Cropping
End of explanation
img_corner = img[:32,:32]
myshow(img_corner)
myshow(img_corner[::-1,:])
myshow(sitk.Tile(img_corner, img_corner[::-1,::],img_corner[::,::-1],img_corner[::-1,::-1], [2,2]))
Explanation: Flipping
End of explanation
img = sitk.GaborSource(size=[64]*3, frequency=0.05)
# Why does this produce an error?
myshow(img)
myshow(img[:,:,32])
myshow(img[16,:,:])
Explanation: Slice Extraction
A 2D image can be extracted from a 3D one.
End of explanation
myshow(img[:,::3,32])
Explanation: Super Sampling
End of explanation
img = sitk.ReadImage(fdata("cthead1.png"))
img = sitk.Cast(img,sitk.sitkFloat32)
myshow(img)
img[150,150]
timg = img**2
myshow(timg)
timg[150,150]
Explanation: Mathematical Operators
Most python mathematical operators are overloaded to call the SimpleITK filter which does that same operation on a per-pixel basis. They can operate on a two images or an image and a scalar.
If two images are used then both must have the same pixel type. The output image type is ussually the same.
As these operators basically call ITK filter, which just use raw C++ operators, care must be taked to prevent overflow, and divide by zero etc.
<table>
<tr><td>Operators</td></tr>
<tr><td>+</td></tr>
<tr><td>-</td></tr>
<tr><td>\*</td></tr>
<tr><td>/</td></tr>
<tr><td>//</td></tr>
<tr><td>**</td></tr>
<table>
End of explanation
img = sitk.ReadImage(fdata("cthead1.png"))
myshow(img)
Explanation: Division Operators
All three Python division operators are implemented __floordiv__, __truediv__, and __div__.
The true division's output is a double pixle type.
See PEP 238 to see why Python changed the division operator in Python 3.
Bitwise Logic Operators
<table>
<tr><td>Operators</td></tr>
<tr><td>&</td></tr>
<tr><td>|</td></tr>
<tr><td>^</td></tr>
<tr><td>~</td></tr>
<table>
End of explanation
img = sitk.ReadImage(fdata("cthead1.png"))
myshow(img)
Explanation: Comparative Operators
<table>
<tr><td>Operators</td></tr>
<tr><td>\></td></tr>
<tr><td>\>=</td></tr>
<tr><td><</td></tr>
<tr><td><=</td></tr>
<tr><td>==</td></tr>
<table>
These comparative operators follow the same convention as the reset of SimpleITK for binary images. They have the pixel type of ``sitkUInt8`` with values of 0 and 1.
End of explanation
myshow(img>90)
myshow(img>150)
myshow((img>90)+(img>150))
Explanation: Amazingly make common trivial tasks really trivial
End of explanation |
7,950 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiple Inheritance
In multiple inheritance, a class can be derived from more than one base classes. The syntax for multiple inheritance is similar to single inheritance except we list all the base classes in sequence instead of one base class in single inheritance.
python
class ChildClass(<base_class_1>, <base_class_2>, ...)
Step1: Lets create the class MultiDerived child class using Base1 & Base2.
Step2: The above object is a blank object with contains no custom defined attributes. Lets explore it in more details.
Step3: In the above example, we have created two child classes C1 and C2 with P1, P2 and P2, P1 as parents respectively. You will note that when we created child c1 of class C1, as C1 do not have any __init__ function, Python searched it on parent classes, and executed & returned after finding its first definition, which it found in P1 class, thus it did not ran the __init__ of P2. Similarly c2 ran the __init__ of P2 class. We will explain the algo which is used to find the required functions on parents later in the chapter.
Lets create a child class TechLead which is derived from Lead and Tech classes.
Step4: Lets try the same using super function
Step5: Few things of importance you will find are as follows
- By adding super().__init__(**kwds) in all the parents __init__ functions, and adding super().__init__(**kwds) in child __init__ function, we can make sure that init of every parent is called automatically.
We can use similar to def __init__(self, count_reportee, **kwds) as __init__ function signature, where count_reportee is the needed parameter for that class.
Step6: Note in the above example, when we created c1 an object of C1 and as C1 class do not have initializing function __init__ thus Python searched its parent
Multilevel Inheritance
we can inherit to from a derived class also. This is called as multilevel inheritance. Multilevel inheritance can be of any depth in Python. An example with corresponding visualization is given below.
Step7: In the multiple inheritance scenario, any specified attribute is searched first in the current class. If not found, the search continues into parent classes in depth-first, left-right fashion without searching same class twice
Step8: consistent method resolution
CMR is explained by Guido at http
Step9: C3 Linearization Algorithm
C3 super-class linearization follow the following rules
Step10: Problem
```python
class First(object)
Step11: Finding subclasses
Step12: thus, we can create the following code the get the sub-classes name
Step13: Lets create a small function based on the above code sample | Python Code:
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
Explanation: Multiple Inheritance
In multiple inheritance, a class can be derived from more than one base classes. The syntax for multiple inheritance is similar to single inheritance except we list all the base classes in sequence instead of one base class in single inheritance.
python
class ChildClass(<base_class_1>, <base_class_2>, ...):
.... Child Class code
Lets create few classes and expore the features of Multiple Inheritance.
End of explanation
md = MultiDerived()
print(md)
Explanation: Lets create the class MultiDerived child class using Base1 & Base2.
End of explanation
class P1():
def __init__(self):
print("P-1 init")
class P2():
def __init__(self):
print("P_2 init")
class C1(P1, P2):
pass
class C2(P2, P1):
pass
c1 = C1()
print("*"*20)
c2 = C2()
Explanation: The above object is a blank object with contains no custom defined attributes. Lets explore it in more details.
End of explanation
class Tech(object):
def __init__(self, tech):
self._tech_name = tech
@property
def tech_name(self):
return self._tech_name
@tech_name.setter
def tech_name(self, name):
self._tech_name = name
class Lead(object):
def __init__(self, reportee_count):
self._reportee_count = reportee_count
@property
def reportee(self):
return self._reportee_count
@reportee.setter
def reportee(self, count):
self._reportee_count = count
class TechLead(Tech, Lead):
def __init__(self, tech, count):
Lead.__init__(self, count)
Tech.__init__(self, tech)
vivek = TechLead("Java", 2)
print(vivek)
print(vivek.__dict__)
Explanation: In the above example, we have created two child classes C1 and C2 with P1, P2 and P2, P1 as parents respectively. You will note that when we created child c1 of class C1, as C1 do not have any __init__ function, Python searched it on parent classes, and executed & returned after finding its first definition, which it found in P1 class, thus it did not ran the __init__ of P2. Similarly c2 ran the __init__ of P2 class. We will explain the algo which is used to find the required functions on parents later in the chapter.
Lets create a child class TechLead which is derived from Lead and Tech classes.
End of explanation
class Tech(object):
def __init__(self, tech, **kwds):
print("Inside Tech")
self._tech_name = tech
super().__init__(**kwds)
@property
def tech_name(self):
return self._tech_name
@tech_name.setter
def tech_name(self, name):
self._tech_name = name
class Lead(object):
def __init__(self, count_reportee, **kwds):
print("Inside Lead")
self._reportee_count = count_reportee
super().__init__(**kwds)
@property
def reportee(self):
return self._reportee_count
@reportee.setter
def reportee(self, count):
self._reportee_count = count
class TechLead(Tech, Lead):
def __init__(self, name, **kwds):
print("Inside TechLead")
self._name = name
super().__init__(**kwds)
abhi = TechLead(name="Abhishek Kumar", tech="macOS", count_reportee= 10)
print(abhi)
print(abhi.__dict__)
class Tech(object):
def __init__(self, tech, **kwds):
print("Inside Tech")
self._tech_name = tech
# super().__init__(**kwds)
@property
def tech_name(self):
return self._tech_name
@tech_name.setter
def tech_name(self, name):
self._tech_name = name
class Lead(object):
def __init__(self, count_reportee, **kwds):
print("Inside Lead")
self._reportee_count = count_reportee
super().__init__(**kwds)
@property
def reportee(self):
return self._reportee_count
@reportee.setter
def reportee(self, count):
self._reportee_count = count
class TechLead(Tech, Lead
):
def __init__(self, name, **kwds):
print("Inside TechLead")
self._name = name
super().__init__(**kwds)
abhi = TechLead(name="Abhishek Kumar", count_reportee= 10, tech="macOS")
print(abhi)
print(abhi.__dict__)
Explanation: Lets try the same using super function
End of explanation
class Base1:
def test(self):
print("in Base1 -> test")
class Base2:
def test(self):
print("in Base2 -> test")
class MultiDerived(Base1, Base2):
def test2(self):
super().test()
Base2.test(Base2)
class MultiDerived2(Base2, Base1):
def test2(self):
super().test()
Base2.test(Base2)
print("Please check the result of test()")
md = MultiDerived()
md.test2()
md.test()
print("*"*10)
md2 = MultiDerived2()
md2.test2()
md2.test()
Explanation: Few things of importance you will find are as follows
- By adding super().__init__(**kwds) in all the parents __init__ functions, and adding super().__init__(**kwds) in child __init__ function, we can make sure that init of every parent is called automatically.
We can use similar to def __init__(self, count_reportee, **kwds) as __init__ function signature, where count_reportee is the needed parameter for that class.
End of explanation
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass
Explanation: Note in the above example, when we created c1 an object of C1 and as C1 class do not have initializing function __init__ thus Python searched its parent
Multilevel Inheritance
we can inherit to from a derived class also. This is called as multilevel inheritance. Multilevel inheritance can be of any depth in Python. An example with corresponding visualization is given below.
End of explanation
class Base:
def test(self):
print("In Base test")
def test_alone(self):
print("In Base test: test_alone")
class Derived1(Base):
def test(self):
print("In Derived1 test")
super().test()
def test_alone(self, val):
print("In Derived1 test: test_alone ", val)
def test_alone(self):
print("In Base test: test_alone")
class Derived2(Derived1):
def test2(self):
print("in Derived2 test2")
obj = Derived2()
obj.test()
obj.test2()
obj.test_alone()
Base.test(Base)
class Base:
def test(self):
print("In Base test")
def test_base(self):
print("test_base")
def test_alone(self):
print("In Base test: test_alone")
class Derived1(Base):
def test(self):
print("In Derived1 test")
super().test()
self.test_base()
def test_alone(self, val):
print("In Derived1 test: test_alone ", val)
self.test()
obj = Derived1()
obj.test()
obj.test_alone("test")
Base.test(Base)
class Base:
def test(self):
print("In Base test")
def test_base(self):
print("test_base")
def test_alone(self):
print("In Base test: test_alone")
class Derived1(Base):
def test(self):
print("In Derived1 test")
super().test()
Base.test_base(Base)
def test_alone(self, val):
print("In Derived1 test: test_alone ", val)
self.test()
obj = Derived1()
obj.test()
obj.test_alone("test")
Base.test(Base)
class Base:
def test(self):
print("In Base test")
def test_alone(self):
print("In Base test: test_alone")
class Derived1(Base):
def test(self):
print("In Derived1 test")
super().test()
def test_alone(self, val):
print("In Derived1 test: test_alone ", val)
def test_alone(self):
print("In Base test: test_alone")
class Derived2(Derived1):
def test2(self):
print("in Derived2 test2")
obj = Derived2()
obj.test()
obj.test2()
obj.test_alone()
Base.test(Base)
class Base():
def test1(self):
print("In Base test")
class Derived1(Base):
def test(self):
print("In Derived1 test")
class Derived3(Derived1):
pass
d = Derived3()
d.test()
d.test1()
class Base():
def test(self):
print("In Base test")
class Derived1(Base):
def test(self):
print("In Derived1 test", end=", ")
return "Golu"
class Derived3(Derived1):
pass
d = Derived3()
print(d.test())
#### Explicitly calling function
class Base:
def test(self):
print("In Base test")
class Derived1(Base):
def test(self):
print("In Derived1 test")
class Derived2(Derived1):
pass
obj = Derived2
obj.test(obj)
Derived2.test(Derived2)
#### Explicitly calling function
class Base:
def test(self):
print("In Base test")
class Derived1(Base):
def test(self):
print("In Derived1 test")
print(type(self))
class Derived2(Derived1):
pass
obj = Derived2
obj.test(obj)
Derived2.test(Derived2)
#### Explicitly calling function
class Base:
def test(self):
print("In Base test")
class Derived1(Base):
def test(self):
print("In Derived1 test")
print(type(self))
class Derived2(Derived1):
pass
obj = Derived2()
obj.test()
Derived2.test(Derived2)
## TODO : Need to find a way to call init of both the parents
class CL1(object):
def __init__(self):
# super(CL1, self).__init__()
print ("class 1")
class CL2(object):
def __init__(self):
# super(CL2, self).__init__()
print ("class 2")
class CL3(CL1, CL2):
def __init__(self):
super(CL3, self).__init__()
print ("class 3")
instance = CL3()
Explanation: In the multiple inheritance scenario, any specified attribute is searched first in the current class. If not found, the search continues into parent classes in depth-first, left-right fashion without searching same class twice
End of explanation
class A:
def whereiam(self):
print("I am in A")
class B:
def whoiam(self):
print("I am a method")
class C(A, B):
pass
c = C()
print(dir(c))
c.whoiam()
class A:
def whoiam(self):
print("I am in A")
class B:
def whoiam(self):
print("I am a method")
class C(A, B):
pass
c = C()
print(dir(c))
c.whoiam()
class A:
def whereiam(self):
print("I am in A")
class B(A):
def whereiam(self):
print("I am in B")
class C(A):
def whereiam(self):
print("I am in C")
class D(B, C):
def whereiam(self):
print("I am in D")
d = D()
d.whereiam()
class A:
def whereiam(self):
print("I am in A")
class B(A):
def whereiam(self):
print("I am in B")
class C(A):
def whereiam(self):
print("I am in C")
class D(B, C):
pass
d = D()
d.whereiam()
class A:
def whereiam(self):
print("I am in A")
class B(A):
pass
class C(A):
def whereiam(self):
print("I am in C")
class D(B, C):
pass
d = D()
d.whereiam()
class A:
def whereiam(self):
print("I am in A")
class D:
def whereiam(self):
print("I am in D")
class B(A):
pass
class C(D):
pass
class E(B, C):
pass
e = E()
e.whereiam()
Explanation: consistent method resolution
CMR is explained by Guido at http://python-history.blogspot.com/2010/06/method-resolution-order.html.
We will try to summerize it here.
End of explanation
class Type(type):
def __repr__(cls):
return cls.__name__
class O(object, metaclass=Type): pass
class A(O): pass
class B(O): pass
class C(O): pass
class D(O): pass
class E(O): pass
class K1(A, B, C): pass
class K2(D, B, E): pass
class K3(D, A): pass
class Z(K1, K2, K3): pass
Z.mro()
Explanation: C3 Linearization Algorithm
C3 super-class linearization follow the following rules:
Children precede their parents
If a class inherits from multiple classes, they are kept in the order specified in the tuple of the base class.
Consistent extended precedence graph, which in short means how base class is extended from the super class. Inheritance graph determines the structure of method resolution order.
Preserving local precedence ordering, i.e., visiting the super class only after the method of the local classes are visited.
Monotonicity
End of explanation
class First(object):
def __init__(self):
print("first")
class Second(First):
def __init__(self):
print("second")
class Third(Second):
def __init__(self):
print("third")
Third.mro()
class O(object): pass
class A(O): pass
class B(O): pass
class C(O): pass
class D(O): pass
class E(O): pass
class K1(A, B, C): pass
class K2(D, B, E): pass
class K3(D, A): pass
class Z(K1, K2, K3): pass
print(Z.mro())
Explanation: Problem
```python
class First(object):
def init(self):
print("first")
class Second(First):
def init(self):
print("second")
class Third(First, Second):
def init(self):
print("third")
```
```python
TypeError Traceback (most recent call last)
<ipython-input-37-a1afb9897f3d> in <module>()
7 print("second")
8
----> 9 class Third(First, Second):
10 def init(self):
11 print("third")
TypeError: Cannot create a consistent method resolution
order (MRO) for bases First, Second
```
Solution
End of explanation
class O(object): pass
class A(O): pass
class B(O): pass
class C(O): pass
class D(O): pass
class E(O): pass
class K1(A, B, C): pass
class K2(D, B, E): pass
O.__subclasses__()
Explanation: Finding subclasses
End of explanation
print([cls.__name__ for cls in O.__subclasses__()])
Explanation: thus, we can create the following code the get the sub-classes name
End of explanation
def get_subclasses(cls):
lst = []
for a in cls.__subclasses__():
lst.append(a)
lst.extend(get_subclasses(a))
return set(lst)
get_subclasses(O)
Explanation: Lets create a small function based on the above code sample
End of explanation |
7,951 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ttHbb variables preparation
Step1: variables
ATL-COM-PHYS-2017-079 (table 8, page 46)
|variable |type |n-tuple name |description |region >= 6j|region 5j|
|-------------------------------------------------|-------------------------|----------------------------------|---------------------------------------------------------------------------------------------------------------|--------------|-----------|
|${\Delta R^{\text{avg}}{bb}}$ |general kinematic |dRbb_avg_Sort4 |average ${\Delta R}$ for all ${b}$-tagged jet pairs |yes |yes |
|${\Delta R^{\text{max} p{T}}{bb}}$ |general kinematic |dRbb_MaxPt_Sort4 |${\Delta R}$ between the two ${b}$-tagged jets with the largest vector sum ${p{T}}$ |yes |- |
|${\Delta \eta^{\textrm{max}\Delta\eta}{jj}}$ |general kinematic |dEtajj_MaxdEta |maximum ${\Delta\eta}$ between any two jets |yes |yes |
|${m^{\text{min} \Delta R}{bb}}$ |general kinematic |Mbb_MindR_Sort4 |mass of the combination of the two ${b}$-tagged jets with the smallest ${\Delta R}$ |yes |- |
|${m^{\text{min} \Delta R}{jj}}$ |general kinematic |Mjj_MindR |mass of the combination of any two jets with the smallest ${\Delta R}$ |- |yes |
|${N^{\text{Higgs}}{30}}$ |general kinematic |nHiggsbb30_Sort4 |number of ${b}$-jet pairs with invariant mass within 30 GeV of the Higgs boson mass |yes |yes |
|${H^{\text{had}}{T}}$ |general kinematic |HT_jets? |scalar sum of jet ${p{T}}$ |- |yes |
|${\Delta R^{\text{min}\Delta R}{\text{lep}-bb}}$|general kinematic |dRlepbb_MindR_Sort4 |${\Delta R}$ between the lepton and the combination of the two ${b}$-tagged jets with the smallest ${\Delta R}$|- |yes |
|aplanarity |general kinematic |Aplanarity_jets |${1.5\lambda{2}}$, where ${\lambda_{2}}$ is the second eigenvalue of the momentum tensor built with all jets |yes |yes |
|${H1}$ |general kinematic |H1_all |second Fox-Wolfram moment computed using all jets and the lepton |yes |yes |
|BDT |reconstruction BDT output|TTHReco_best_TTHReco |BDT output |yes |yes |
|${m_{H}}$ |reconstruction BDT output|TTHReco_best_Higgs_mass |Higgs boson mass |yes |yes |
|${m_{H,b_{\text{lep top}}}}$ |reconstruction BDT output|TTHReco_best_Higgsbleptop_mass |Higgs boson mass and ${b}$-jet from leptonic ${t}$ |yes |- |
|${\Delta R_{\text{Higgs }bb}}$ |reconstruction BDT output|TTHReco_best_bbHiggs_dR |${\Delta R}$ between ${b}$-jets from Higgs boson |yes |yes |
|${\Delta R_{H,t\bar{t}}}$ |reconstruction BDT output|TTHReco_withH_best_Higgsttbar_dR|${\Delta R}$ between Higgs boson and ${t\bar{t}}$ system |yes |yes |
|${\Delta R_{H,\text{lep top}}}$ |reconstruction BDT output|TTHReco_best_Higgsleptop_dR |${\Delta R}$ between Higgs boson and leptonic ${t}$ |yes |- |
|${\Delta R_{H,b_{\text{had top}}}}$ |reconstruction BDT output|TTHReco_best_b1Higgsbhadtop_dR |${\Delta R}$ between Higgs boson and ${b}$-jet from hadronic ${t}$ |- |yes* |
|D |likelihood calculation |LHD_Discriminant |likelihood discriminant |yes |yes |
|${\text{MEM}{D1}}$ |matrix method | |matrix method |yes |- |
|${w^{H}{b}}$ |${b}$-tagging |? |sum of binned ${b}$-tagging weights of jets from best Higgs candidate |yes |yes |
|${B_{j^{3}}}$ |${b}$-tagging |? |third jet binned ${b}$-tagging weight (sorted by weight) |yes |yes |
|${B_{j^{4}}}$ |${b}$-tagging |? |fourth jet binned ${b}$-tagging weight (sorted by weight) |yes |yes |
|${B_{j^{5}}}$ |${b}$-tagging |? |fifth jet binned ${b}$-tagging weight (sorted by weight) |yes |yes |
Step2: read
Step3: selection
Step4: characteristics
Step5: imputation
Step6: histograms
Step7: correlations
correlations ${t\bar{t}H}$
Step8: correlations ${t\bar{t}b\bar{b}}$
Step9: ratio of correlations of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$
Step10: ## clustered correlations
Step11: strongest correlations and anticorrelations for discrimination of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$
Step12: strongest absolute correlations for discrimination of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$
Step13: clustered correlations of 10 strongest absolute correlations
Step14: rescale
Step15: save | Python Code:
import datetime
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
plt.rcParams["figure.figsize"] = (13, 6)
import pandas as pd
import seaborn as sns
sns.set(context = "paper", font = "monospace")
from sklearn.preprocessing import MinMaxScaler
import sqlite3
import warnings
warnings.filterwarnings("ignore")
pd.set_option("display.max_rows", 500)
pd.set_option("display.max_columns", 500)
import root_pandas
Explanation: ttHbb variables preparation
End of explanation
variables = [
"nElectrons",
"nMuons",
"nJets",
"nBTags_70",
"dRbb_avg_Sort4",
"dRbb_MaxPt_Sort4",
"dEtajj_MaxdEta",
"Mbb_MindR_Sort4",
"Mjj_MindR",
"nHiggsbb30_Sort4",
"HT_jets",
"dRlepbb_MindR_Sort4",
"Aplanarity_jets",
"H1_all",
"TTHReco_best_TTHReco",
"TTHReco_best_Higgs_mass",
"TTHReco_best_Higgsbleptop_mass",
"TTHReco_best_bbHiggs_dR",
"TTHReco_withH_best_Higgsttbar_dR",
"TTHReco_best_Higgsleptop_dR",
"TTHReco_best_b1Higgsbhadtop_dR",
"LHD_Discriminant"
]
Explanation: variables
ATL-COM-PHYS-2017-079 (table 8, page 46)
|variable |type |n-tuple name |description |region >= 6j|region 5j|
|-------------------------------------------------|-------------------------|----------------------------------|---------------------------------------------------------------------------------------------------------------|--------------|-----------|
|${\Delta R^{\text{avg}}{bb}}$ |general kinematic |dRbb_avg_Sort4 |average ${\Delta R}$ for all ${b}$-tagged jet pairs |yes |yes |
|${\Delta R^{\text{max} p{T}}{bb}}$ |general kinematic |dRbb_MaxPt_Sort4 |${\Delta R}$ between the two ${b}$-tagged jets with the largest vector sum ${p{T}}$ |yes |- |
|${\Delta \eta^{\textrm{max}\Delta\eta}{jj}}$ |general kinematic |dEtajj_MaxdEta |maximum ${\Delta\eta}$ between any two jets |yes |yes |
|${m^{\text{min} \Delta R}{bb}}$ |general kinematic |Mbb_MindR_Sort4 |mass of the combination of the two ${b}$-tagged jets with the smallest ${\Delta R}$ |yes |- |
|${m^{\text{min} \Delta R}{jj}}$ |general kinematic |Mjj_MindR |mass of the combination of any two jets with the smallest ${\Delta R}$ |- |yes |
|${N^{\text{Higgs}}{30}}$ |general kinematic |nHiggsbb30_Sort4 |number of ${b}$-jet pairs with invariant mass within 30 GeV of the Higgs boson mass |yes |yes |
|${H^{\text{had}}{T}}$ |general kinematic |HT_jets? |scalar sum of jet ${p{T}}$ |- |yes |
|${\Delta R^{\text{min}\Delta R}{\text{lep}-bb}}$|general kinematic |dRlepbb_MindR_Sort4 |${\Delta R}$ between the lepton and the combination of the two ${b}$-tagged jets with the smallest ${\Delta R}$|- |yes |
|aplanarity |general kinematic |Aplanarity_jets |${1.5\lambda{2}}$, where ${\lambda_{2}}$ is the second eigenvalue of the momentum tensor built with all jets |yes |yes |
|${H1}$ |general kinematic |H1_all |second Fox-Wolfram moment computed using all jets and the lepton |yes |yes |
|BDT |reconstruction BDT output|TTHReco_best_TTHReco |BDT output |yes |yes |
|${m_{H}}$ |reconstruction BDT output|TTHReco_best_Higgs_mass |Higgs boson mass |yes |yes |
|${m_{H,b_{\text{lep top}}}}$ |reconstruction BDT output|TTHReco_best_Higgsbleptop_mass |Higgs boson mass and ${b}$-jet from leptonic ${t}$ |yes |- |
|${\Delta R_{\text{Higgs }bb}}$ |reconstruction BDT output|TTHReco_best_bbHiggs_dR |${\Delta R}$ between ${b}$-jets from Higgs boson |yes |yes |
|${\Delta R_{H,t\bar{t}}}$ |reconstruction BDT output|TTHReco_withH_best_Higgsttbar_dR|${\Delta R}$ between Higgs boson and ${t\bar{t}}$ system |yes |yes |
|${\Delta R_{H,\text{lep top}}}$ |reconstruction BDT output|TTHReco_best_Higgsleptop_dR |${\Delta R}$ between Higgs boson and leptonic ${t}$ |yes |- |
|${\Delta R_{H,b_{\text{had top}}}}$ |reconstruction BDT output|TTHReco_best_b1Higgsbhadtop_dR |${\Delta R}$ between Higgs boson and ${b}$-jet from hadronic ${t}$ |- |yes* |
|D |likelihood calculation |LHD_Discriminant |likelihood discriminant |yes |yes |
|${\text{MEM}{D1}}$ |matrix method | |matrix method |yes |- |
|${w^{H}{b}}$ |${b}$-tagging |? |sum of binned ${b}$-tagging weights of jets from best Higgs candidate |yes |yes |
|${B_{j^{3}}}$ |${b}$-tagging |? |third jet binned ${b}$-tagging weight (sorted by weight) |yes |yes |
|${B_{j^{4}}}$ |${b}$-tagging |? |fourth jet binned ${b}$-tagging weight (sorted by weight) |yes |yes |
|${B_{j^{5}}}$ |${b}$-tagging |? |fifth jet binned ${b}$-tagging weight (sorted by weight) |yes |yes |
End of explanation
filenames_ttH = ["ttH_group.phys-higgs.11468583._000005.out.root"]
filenames_ttbb = ["ttbb_group.phys-higgs.11468624._000005.out.root"]
ttH = root_pandas.read_root(filenames_ttH, "nominal_Loose", columns = variables)
ttH["target"] = 1
ttH.head()
ttbb = root_pandas.read_root(filenames_ttbb, "nominal_Loose", columns = variables)
ttbb["target"] = 0
ttbb.head()
df = pd.concat([ttH, ttbb])
df.head()
Explanation: read
End of explanation
selection_ejets = "(nElectrons == 1) & (nJets >= 4)"
selection_mujets = "(nMuons == 1) & (nJets >= 4)"
selection_ejets_5JE4BI = "(nElectrons == 1) & (nJets == 4) & (nBTags_70 >= 4)"
selection_ejets_6JI4BI = "(nElectrons == 1) & (nJets == 6) & (nBTags_70 >= 4)"
df = df.query(selection_ejets)
df.drop(["nElectrons", "nMuons", "nJets", "nBTags_70"], axis = 1, inplace = True)
df.head()
Explanation: selection
End of explanation
rows = []
for variable in df.columns.values:
rows.append({
"name": variable,
"maximum": df[variable].max(),
"minimum": df[variable].min(),
"mean": df[variable].mean(),
"median": df[variable].median(),
"std": df[variable].std()
})
_df = pd.DataFrame(rows)[["name", "maximum", "minimum", "mean", "std", "median"]]
_df
Explanation: characteristics
End of explanation
df["TTHReco_best_TTHReco"].replace( -9, -1, inplace = True)
df["TTHReco_best_Higgs_mass"].replace( -9, -1, inplace = True)
df["TTHReco_best_Higgsbleptop_mass"].replace( -9, -1, inplace = True)
df["TTHReco_best_bbHiggs_dR"].replace( -9, -1, inplace = True)
df["TTHReco_withH_best_Higgsttbar_dR"].replace(-9, -1, inplace = True)
df["TTHReco_best_Higgsleptop_dR"].replace( -9, -1, inplace = True)
df["TTHReco_best_b1Higgsbhadtop_dR"].replace( -9, -1, inplace = True)
df["LHD_Discriminant"].replace( -9, -1, inplace = True)
Explanation: imputation
End of explanation
plt.rcParams["figure.figsize"] = (17, 14)
df.hist();
Explanation: histograms
End of explanation
sns.heatmap(df.query("target == 1").drop("target", axis = 1).corr());
Explanation: correlations
correlations ${t\bar{t}H}$
End of explanation
sns.heatmap(df.query("target == 0").drop("target", axis = 1).corr());
Explanation: correlations ${t\bar{t}b\bar{b}}$
End of explanation
_df = df.query("target == 1").drop("target", axis = 1).corr() / df.query("target == 0").drop("target", axis = 1).corr()
sns.heatmap(_df);
Explanation: ratio of correlations of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$
End of explanation
plot = sns.clustermap(df.corr())
plt.setp(plot.ax_heatmap.get_yticklabels(), rotation = 0);
Explanation: ## clustered correlations
End of explanation
df.corr()["target"].sort_values(ascending = False).to_frame()[1:]
Explanation: strongest correlations and anticorrelations for discrimination of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$
End of explanation
df.corr()["target"].abs().sort_values(ascending = False).to_frame()[1:]
_df = df.corr()["target"].abs().sort_values(ascending = False).to_frame()[1:]
_df.plot(kind = "barh", legend = "False");
Explanation: strongest absolute correlations for discrimination of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$
End of explanation
names = df.corr()["target"].abs().sort_values(ascending = False)[1:11].index.values
plot = sns.clustermap(df[names].corr())
plt.setp(plot.ax_heatmap.get_yticklabels(), rotation = 0);
Explanation: clustered correlations of 10 strongest absolute correlations
End of explanation
variables_rescale = [variable for variable in list(df.columns) if variable != "target"]
scaler = MinMaxScaler()
df[variables_rescale] = scaler.fit_transform(df[variables_rescale])
df.head()
Explanation: rescale
End of explanation
df.to_csv("ttHbb_data.csv", index = False)
Explanation: save
End of explanation |
7,952 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <a href="http
Step2: The figure below illustrates the terminology
Step3: We can call the function
Step4: If we call the function with a new input we get a new result
Step5: We can create different functions. For example, we can create a function that multiplies two numbers. The numbers will be represented by the variables a and b
Step6: The same function can be used for different data types. For example, we can multiply two integers
Step7: Two Floats
Step8: We can even replicate a string by multiplying with an integer
Step9: Come up with a function that divides the first input by the second input
Step11: <div align="right">
<a href="#q1" class="btn btn-default" data-toggle="collapse">Click here for the solution</a>
</div>
<div id="q1" class="collapse">
```
def div(a,b)
Step12: The labels are displayed in the figure
Step13: We can call the function with an input of 2 in a different manner
Step14: If there is no return statement, the function returns None. The following two functions are equivalent
Step15: Printing the function after a call reveals a None is the default return statement
Step16: Create a function con that concatenates two strings using the addition operation
Step17: <div align="right">
<a href="#q2" class="btn btn-default" data-toggle="collapse">Click here for the solution</a>
</div>
<div id="q2" class="collapse">
```
def div(a,b)
Step18: <div align="right">
<a href="#q3" class="btn btn-default" data-toggle="collapse">Click here for the solution</a>
</div>
<div id="q3" class="collapse">
```
yes,for example
Step19: <div align="right">
<a href="#q4" class="btn btn-default" data-toggle="collapse">Click here for the solution</a>
</div>
<div id="q4" class="collapse">
```
yes,for example
Step20: The sum() function adds all the elements in a list or tuple
Step21: The length function returns the length of a list or tuple
Step22: <div class="alert alert-success alertsuccess" style="margin-top
Step23: Block 2
Step24: We can replace the lines of code with a function. A function combines many instructions into a single line of code. Once a function is defined, it can be used repeatedly. You can invoke the same function many times in your program. You can save your function and use it in another program or use someone else’s function. The lines of code in code block 1 and code block 2 can be replaced by the following function
Step25: This function takes two inputs, a and b, then applies several operations to return c.
We simply define the function, replace the instructions with the function, and input the new values of a1,b1 and a2,b2 as inputs. The entire process is demonstrated in the figure
Step26: Block 4
Step27: <hr>
<a id='ref3'></a>
<center><h2>Using if/else statements and loops in functions</h2></center>
The return() function is particularly useful if you have any IF statements in the function, when you want your output to be dependent on some condition
Step28: We can use a loop in a function. For example, we can print out each element in a list
Step29: <hr>
<a id='ref4'></a>
<center><h2>Setting default argument values in your custom functions</h2></center>
You can set a default value for arguments in your function. For example, in the isGoodRating() function, what if we wanted to create a threshold for what we consider to be a good rating? Perhaps by default, we should have a default rating of 4
Step30: <hr>
Step31: <a id='ref6'></a>
<center><h2>Global variables</h2></center>
<br>
So far, we've been creating variables within functions, but we have not discussed variables outside the function. These are called global variables.
<br>
Let's try to see what printer1 returns
Step32: If we print internal_var we get an error.
We got a Name Error
Step33: <a id='ref7'></a>
<center><h2>Scope of a Variable</h2></center>
<hr>
The scope of a variable is the part of that program where that variable is accessible. Variables that are declared outside of all function definitions, such as the myFavouriteBand variable in the code shown here, are accessible from anywhere within the program. As a result, such variables are said to have global scope, and are known as global variables.
myFavouriteBand is a global variable, so it is accessible from within the getBandRating function, and we can use it to determine a band's rating. We can also use it outside of the function, such as when we pass it to the print function to display it
Step34: Take a look at this modified version of our code. Now the myFavouriteBand variable is defined within the getBandRating function. A variable that is defined within a function is said to be a local variable of that function. That means that it is only accessible from within the function in which it is defined. Our getBandRating function will still work, because myFavouriteBand is still defined within the function. However, we can no longer print myFavouriteBand outside our function, because it is a local variable of our getBandRating function; it is only defined within the getBandRating function
Step35: Finally, take a look at this example. We now have two myFavouriteBand variable definitions. The first one of these has a global scope, and the second of them is a local variable within the getBandRating function. Within the getBandRating function, the local variable takes precedence. Deep Purple will receive a rating of 10.0 when passed to the getBandRating function. However, outside of the getBandRating function, the getBandRating s local variable is not defined, so the myFavouriteBand variable we print is the global variable, which has a value of AC/DC | Python Code:
def add(a):
add 1 to a
b=a+1;
print(a, "if you add one" ,b)
return(b)
Explanation: <a href="http://cocl.us/topNotebooksPython101Coursera"><img src = "https://ibm.box.com/shared/static/yfe6h4az47ktg2mm9h05wby2n7e8kei3.png" width = 750, align = "center"></a>
<a href="https://www.bigdatauniversity.com"><img src = "https://ibm.box.com/shared/static/ugcqz6ohbvff804xp84y4kqnvvk3bq1g.png" width = 300, align = "center"></a>
<h1 align=center><font size = 5>WRITING YOUR OWN FUNCTIONS IN PYTHON</font></h1>
Table of Contents
<div class="alert alert-block alert-info" style="margin-top: 20px">
<ol>
<li><a href="#ref1">What is a Function?</a></li>
<li><a href="#ref3">Using if/else statements in functions</a></li>
<li><a href="#ref4">Setting default argument values in your custom functions</a></li>
<li><a href="#ref6">Global and local variables</a></li>
<li><a href="#ref7">Scope of a Variable </a></li>
</ol>
<br>
<p></p>
Estimated Time Needed: <strong>40 min</strong>
</div>
<hr>
<hr>
<a id='ref1'></a>
<center><h2>Defining a Function</h2></center>
A function is a reusable block of code which performs operations specified in the function. They let you break down tasks and allow you to reuse your code in different programs.
There are two types of functions :
Pre-defined functions
User defined functions
<h3>What is a Function?</h3>
You can define functions to provide the required functionality. Here are simple rules to define a function in Python:
- Functions blocks begin def followed by the function name and parentheses ().
- There are input parameters or arguments that should be placed within these parentheses.
- You can also define parameters inside these parentheses.
- There is a body within every function that starts with a colon (:) and is indented.
- You can also place documentation before the body
- The statement return exits a function, optionally passing back a value
An example of a function that adds on to the parameter a prints and returns the output as b:
End of explanation
help(add)
Explanation: The figure below illustrates the terminology:
<a ><img src = "https://ibm.box.com/shared/static/wsl6jcfld2c3171ob19vjr5chw9gyxrc.png" width = 500, align = "center"></a>
<h4 align=center>
A labeled function
</h4>
We can obtain help about a function :
End of explanation
add(1)
Explanation: We can call the function:
End of explanation
add(2)
Explanation: If we call the function with a new input we get a new result:
End of explanation
def Mult(a,b):
c=a*b
return(c)
Explanation: We can create different functions. For example, we can create a function that multiplies two numbers. The numbers will be represented by the variables a and b:
End of explanation
Mult(2,3)
Explanation: The same function can be used for different data types. For example, we can multiply two integers:
End of explanation
Mult(10,3.14)
Explanation: Two Floats:
End of explanation
Mult(2,"Michael Jackson ")
Explanation: We can even replicate a string by multiplying with an integer:
End of explanation
def divide_values(a, b):
return a / b
Explanation: Come up with a function that divides the first input by the second input:
End of explanation
#Function Definition
def square(a):
Square the input and add one
#Local variable
b=1
c=a*a+b;
print(a, "if you square +1 ",c)
return(c)
Explanation: <div align="right">
<a href="#q1" class="btn btn-default" data-toggle="collapse">Click here for the solution</a>
</div>
<div id="q1" class="collapse">
```
def div(a,b):
return(a/b)
```
</div>
<h3>Variables </h3>
The input to a function is called a formal parameter.
A variable that is declared inside a function is called a local variable. The parameter only exists within the function (i.e. the point where the function starts and stops).
A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout the program. We will discuss more about global variables at the end of the lab.
End of explanation
#Initializes Global variable
x=3
#Makes function call and return function a y
z=square(x)
z
Explanation: The labels are displayed in the figure:
<a ><img src = "https://ibm.box.com/shared/static/gpfa525nnfwxt5rhrvd3o6i8rp2iwsai.png" width = 500, align = "center"></a>
<h4 align=center>
Figure 2: A function with labeled variables
</h4>
We can call the function with an input of 3:
End of explanation
square(2)
Explanation: We can call the function with an input of 2 in a different manner:
End of explanation
def MJ():
print('Michael Jackson')
def MJ1():
print('Michael Jackson')
return(None)
MJ()
MJ1()
Explanation: If there is no return statement, the function returns None. The following two functions are equivalent:
End of explanation
print(MJ())
print(MJ1())
Explanation: Printing the function after a call reveals a None is the default return statement:
End of explanation
def con(a,b):
return(a+b)
Explanation: Create a function con that concatenates two strings using the addition operation:
:
End of explanation
print(con(1, 2))
print(con('1', '2'))
Explanation: <div align="right">
<a href="#q2" class="btn btn-default" data-toggle="collapse">Click here for the solution</a>
</div>
<div id="q2" class="collapse">
```
def div(a,b):
return(a+b)
```
</div>
Can the same function be used to add to integers or strings?
End of explanation
print(con([1], [2]))
Explanation: <div align="right">
<a href="#q3" class="btn btn-default" data-toggle="collapse">Click here for the solution</a>
</div>
<div id="q3" class="collapse">
```
yes,for example:
con(2,2)
```
</div>
Can the same function be used to concentrate a list or tuple?
End of explanation
album_ratings = [10.0,8.5,9.5,7.0,7.0,9.5,9.0,9.5]
print(album_ratings)
Explanation: <div align="right">
<a href="#q4" class="btn btn-default" data-toggle="collapse">Click here for the solution</a>
</div>
<div id="q4" class="collapse">
```
yes,for example:
con(['a',1],['b',1])
```
</div>
<h3><b>Pre-defined functions</b></h3>
There are many pre-defined functions in Python, so let's start with the simple ones.
The print() function:
End of explanation
sum(album_ratings)
Explanation: The sum() function adds all the elements in a list or tuple:
End of explanation
len(album_ratings)
Explanation: The length function returns the length of a list or tuple:
End of explanation
a1=4;
b1=5;
c1=a1+b1+2*a1*b1-1
if(c1<0):
c1=0;
else:
c1=5;
c1
Explanation: <div class="alert alert-success alertsuccess" style="margin-top: 20px">
<h4> [Tip] How do I learn more about the pre-defined functions in Python? </h4>
<p></p>
We will be introducing a variety of **pre-defined functions** to you as you learn more about Python. There are just too many functions, so there's no way we can teach them all in one sitting. But if you'd like to take a quick peek, here's a short reference card for some of the commonly-used pre-defined functions:
http://www.astro.up.pt/~sousasag/Python_For_Astronomers/Python_qr.pdf
</div>
<h3>Functions Makes Things Simple </h3>
Consider the two lines of code in Block 1 and Block 2: the procedure for each block is identical. The only thing that is different is the variable names and values.
Block 1:
End of explanation
a2=0;
b2=0;
c2=a2+b2+2*a2*b2-1
if(c2<0):
c2=0;
else:
c2=5;
c2
Explanation: Block 2:
End of explanation
def Equation(a,b):
c=a+b+2*a*b-1
if(c<0):
c=0
else:
c=5
return(c)
Explanation: We can replace the lines of code with a function. A function combines many instructions into a single line of code. Once a function is defined, it can be used repeatedly. You can invoke the same function many times in your program. You can save your function and use it in another program or use someone else’s function. The lines of code in code block 1 and code block 2 can be replaced by the following function:
End of explanation
a1=4;
b1=5;
c1=Equation(a1,b1)
c1
Explanation: This function takes two inputs, a and b, then applies several operations to return c.
We simply define the function, replace the instructions with the function, and input the new values of a1,b1 and a2,b2 as inputs. The entire process is demonstrated in the figure:
<a ><img src = "https://ibm.box.com/shared/static/efn4rii75bgytjdb5c8ek6uezch7yaxq.gif" width = 1100, align = "center"></a>
<h4 align=center>
Example of a function used to replace redundant lines of code
</h4>
Code Blocks 1 and Block 2 can now be replaced with code Block 3 and code Block 4.
Block 3:
End of explanation
a2=0;
b2=0;
c2=Equation(a2,b2)
c2
Explanation: Block 4:
End of explanation
def type_of_album(artist,album,year_released):
if year_released > 1980:
print(artist,album,year_released)
return "Modern"
else:
print(artist,album,year_released)
return "Oldie"
x = type_of_album("Michael Jackson","Thriller",1980)
print(x)
Explanation: <hr>
<a id='ref3'></a>
<center><h2>Using if/else statements and loops in functions</h2></center>
The return() function is particularly useful if you have any IF statements in the function, when you want your output to be dependent on some condition:
End of explanation
def PrintList(the_list):
for element in the_list:
print(element)
PrintList(['1',1,'the man',"abc"])
Explanation: We can use a loop in a function. For example, we can print out each element in a list:
End of explanation
def isGoodRating(rating=4):
if(rating < 7):
print("this album sucks it's rating is",rating)
else:
print("this album is good its rating is",rating)
Explanation: <hr>
<a id='ref4'></a>
<center><h2>Setting default argument values in your custom functions</h2></center>
You can set a default value for arguments in your function. For example, in the isGoodRating() function, what if we wanted to create a threshold for what we consider to be a good rating? Perhaps by default, we should have a default rating of 4:
End of explanation
isGoodRating()
isGoodRating(10)
Explanation: <hr>
End of explanation
artist = "Michael Jackson"
def printer1(artist):
internal_var = artist
print(artist,"is an artist")
printer1(artist)
Explanation: <a id='ref6'></a>
<center><h2>Global variables</h2></center>
<br>
So far, we've been creating variables within functions, but we have not discussed variables outside the function. These are called global variables.
<br>
Let's try to see what printer1 returns:
End of explanation
artist = "Michael Jackson"
def printer(artist):
global internal_var
internal_var= "Whitney Houston"
print(artist,"is an artist")
printer(artist)
printer(internal_var)
Explanation: If we print internal_var we get an error.
We got a Name Error: name 'internal_var' is not defined. Why?
It's because all the variables we create in the function is a local variable, meaning that the variable assignment does not persist outside the function.
But there is a way to create global variables from within a function as follows:
End of explanation
myFavouriteBand = "AC/DC"
def getBandRating(bandname):
if bandname == myFavouriteBand:
return 10.0
else:
return 0.0
print("AC/DC's rating is:", getBandRating("AC/DC"))
print("Deep Purple's rating is:",getBandRating("Deep Purple"))
print("My favourite band is:", myFavouriteBand)
Explanation: <a id='ref7'></a>
<center><h2>Scope of a Variable</h2></center>
<hr>
The scope of a variable is the part of that program where that variable is accessible. Variables that are declared outside of all function definitions, such as the myFavouriteBand variable in the code shown here, are accessible from anywhere within the program. As a result, such variables are said to have global scope, and are known as global variables.
myFavouriteBand is a global variable, so it is accessible from within the getBandRating function, and we can use it to determine a band's rating. We can also use it outside of the function, such as when we pass it to the print function to display it:
End of explanation
def getBandRating(bandname):
myFavouriteBand = "AC/DC"
if bandname == myFavouriteBand:
return 10.0
else:
return 0.0
print("AC/DC's rating is: ", getBandRating("AC/DC"))
print("Deep Purple's rating is: ", getBandRating("Deep Purple"))
print("My favourite band is", myFavouriteBand)
Explanation: Take a look at this modified version of our code. Now the myFavouriteBand variable is defined within the getBandRating function. A variable that is defined within a function is said to be a local variable of that function. That means that it is only accessible from within the function in which it is defined. Our getBandRating function will still work, because myFavouriteBand is still defined within the function. However, we can no longer print myFavouriteBand outside our function, because it is a local variable of our getBandRating function; it is only defined within the getBandRating function:
End of explanation
myFavouriteBand = "AC/DC"
def getBandRating(bandname):
myFavouriteBand = "Deep Purple"
if bandname == myFavouriteBand:
return 10.0
else:
return 0.0
print("AC/DC's rating is:",getBandRating("AC/DC"))
print("Deep Purple's rating is: ",getBandRating("Deep Purple"))
print("My favourite band is:",myFavouriteBand)
Explanation: Finally, take a look at this example. We now have two myFavouriteBand variable definitions. The first one of these has a global scope, and the second of them is a local variable within the getBandRating function. Within the getBandRating function, the local variable takes precedence. Deep Purple will receive a rating of 10.0 when passed to the getBandRating function. However, outside of the getBandRating function, the getBandRating s local variable is not defined, so the myFavouriteBand variable we print is the global variable, which has a value of AC/DC:
End of explanation |
7,953 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
House Prices Estimator
Note
Step1: First problem
The training and test datasets have almost the same size so it's going to be difficult to get good predictions. Worst if we want to take a part of the training set as the validation dataset. It would be desirable to have more training samples.
Selecting only numeric columns (by now)
Probably the non numeric features have a lot of useful information, but for our study purposes we are only going to get the numeric features and see what happens and if we are able to get a good model predictor.
Step2: Find if there's null values
Step3: NaN values will be filled with the mean of the feature they belong. It's a good way to replace NaN values in order to avoid modifying the distribution of the feature but it could cheat the predicted results. We'll assume that.
Step4: Normalizing
This process is useful when we are dealing with neural networs. At this moment we don't know what kind of model we are going to implement, so the data will be normalized.
Also the normalization bring us the possibility of managing smaller numbers which improves the speed in the calculations.
Step5: The 'SalePrice' has a skewed graph. We can stabilize it applying a logarithmic operation because we know that all the values are positive.
Step6: Selecting good features...
There are a lot of features in this dataset so we are going to select only the most correlated features with the 'SalePrice'.
With the following query we can see that the ten first features have a good correlation.
Step7: Showing relationships
Step8: Splitting dataset in train and test
Now we have to recover the datasets for training and test from our current preprocessed dataset. We'll use the 'train_samples' variable that we saved in advance to split it in these two.
The KFold object is also defined and instanced.
KFold
Step9: Anomaly Detection
Besides it's important to take into account the possible anomalies we can found in the training dataset. For this reason it's going to be calculated a small number of them to be removed.
Step10: Polynomial Features
It could be interesting to extract more information between the current features. Actually we are only working with a small number of the original so we can afford to get polynomial features from them. Obviously that will increase the number of final features.
Step11: Models
*__Note__
Step12: Stacked Model
In order to improve the previous predictions it's going to create a simple stacked model with the following architecture
Step13: Averaged Model
Same as before, the averaged model tries to improve the predictions results. In this case the architecture is indeed much simpler. The final prediction is averaged with the outcomes of the LinearRegressor, GradientBoostingRegressor and AdaBoostRegressor.
Step14: Evaluation
Step15: Get Predictions | Python Code:
import numpy as np
import pandas as pd
#load the files
train = pd.read_csv('input/train.csv')
test = pd.read_csv('input/test.csv')
data = pd.concat([train, test])
#size of training dataset
train_samples = train.shape[0]
#print some of them
data.head()
# remove the Id feature, because is not useful for price predictions
data.drop(['Id'],1, inplace=True);
data.info()
print("Size training: {}".format(train.shape[0]))
print("Size testing: {}".format(test.shape[0]))
Explanation: House Prices Estimator
Note: It's a competition from Kaggle.com and the input data was retrieved from there.
Data Analysis
First off we're going to load the training and test dataset. A 'data' variable is created from both datasets and the number of training samples are saved it for future uses.
End of explanation
datanum = data.select_dtypes([np.number])
Explanation: First problem
The training and test datasets have almost the same size so it's going to be difficult to get good predictions. Worst if we want to take a part of the training set as the validation dataset. It would be desirable to have more training samples.
Selecting only numeric columns (by now)
Probably the non numeric features have a lot of useful information, but for our study purposes we are only going to get the numeric features and see what happens and if we are able to get a good model predictor.
End of explanation
datanum.columns[datanum.isnull().any()].tolist()
#number of row without NaN
print(datanum.shape[0] - datanum.dropna().shape[0])
#list of columns with NaN
datanum.columns[datanum.isnull().any()].tolist()
Explanation: Find if there's null values
End of explanation
#Filling with the mean
datanum_no_nan = datanum.fillna(datanum.dropna().mean())
#check
datanum_no_nan.columns[datanum_no_nan.isnull().any()].tolist()
Explanation: NaN values will be filled with the mean of the feature they belong. It's a good way to replace NaN values in order to avoid modifying the distribution of the feature but it could cheat the predicted results. We'll assume that.
End of explanation
import matplotlib.pyplot as plt
%matplotlib inline
# All numeric features except the 'SalePrice'
datanum_no_nan.drop(['SalePrice'], axis=1).head(30).plot(legend=False);
# SalePrice
datanum_no_nan['SalePrice'].head(30).plot(legend=False);
# Showing SalePrice distribution
data.SalePrice.hist(bins=50)
Explanation: Normalizing
This process is useful when we are dealing with neural networs. At this moment we don't know what kind of model we are going to implement, so the data will be normalized.
Also the normalization bring us the possibility of managing smaller numbers which improves the speed in the calculations.
End of explanation
# Transforming to non-skewed SalePrice
data.SalePrice = data.SalePrice.apply(np.log)
data.SalePrice.hist(bins=50)
#Squeeze the data using standard scaler: z = (x - mean)/ std
from sklearn import preprocessing
scaler = preprocessing.StandardScaler()
columns = datanum_no_nan.columns.drop('SalePrice')
print("Features: {}".format(columns))
#make a copy
data_norm = datanum_no_nan
data_norm[columns] = scaler.fit_transform(datanum_no_nan[columns])
print("Train shape: {}".format(data_norm.shape))
data_norm.drop(['SalePrice'], axis=1).head(30).plot(legend=False);
Explanation: The 'SalePrice' has a skewed graph. We can stabilize it applying a logarithmic operation because we know that all the values are positive.
End of explanation
# Correlation features
data_norm.corr()['SalePrice'].sort_values(ascending=False).head(10)
high_corr_feat_names = data_norm.corr()['SalePrice'].sort_values(ascending=False).head(10).axes[0].tolist()
high_corr_feat_names.remove('SalePrice')
data_norm_high_corr = data_norm[high_corr_feat_names]
Explanation: Selecting good features...
There are a lot of features in this dataset so we are going to select only the most correlated features with the 'SalePrice'.
With the following query we can see that the ten first features have a good correlation.
End of explanation
#heatmap between the most correlated features
import seaborn as sns
fig = plt.figure(figsize=(7, 5))
sns.heatmap(data_norm_high_corr.corr());
#plotting distributions of numeric features
data_norm_high_corr.hist(bins=50, figsize=(22,16));
#Relationships between correlated features
for feature in high_corr_feat_names:
data.plot.scatter(feature, 'SalePrice');
Explanation: Showing relationships
End of explanation
from sklearn.model_selection import KFold
y = np.array(data['SalePrice'])
X = np.array(data_norm_high_corr)
#split by idx
idx = train_samples
X_train, X_test = X[:idx], X[idx:]
y_train, y_test = y[:idx], y[idx:]
print("Shape X train: {}".format(X_train.shape))
print("Shape y train: {}".format(y_train.shape))
print("Shape X test: {}".format(X_test.shape))
print("Shape y test: {}".format(y_test.shape))
kf = KFold(n_splits=3, random_state=9, shuffle=True)
print(kf)
Explanation: Splitting dataset in train and test
Now we have to recover the datasets for training and test from our current preprocessed dataset. We'll use the 'train_samples' variable that we saved in advance to split it in these two.
The KFold object is also defined and instanced.
KFold
End of explanation
#plotting PCA
from sklearn.decomposition import PCA
def getX_PCA(X):
pca = PCA(n_components=1)
return pca.fit(X).transform(X)
def plotPCA(X, y):
pca = PCA(n_components=1)
X_r = pca.fit(X).transform(X)
plt.plot(X_r, y, 'x')
from sklearn.covariance import EllipticEnvelope
# fit the model
ee = EllipticEnvelope(contamination=0.1,
assume_centered=True,
random_state=9)
ee.fit(X_train)
pred = ee.predict(X_train)
X_train_orig = X_train
y_train_orig = y_train
X_bad = X_train[pred != 1]
y_bad = y_train[pred != 1]
X_train = X_train[pred == 1]
y_train = y_train[pred == 1]
print("Number samples: {}".format(X_train.shape[0]))
#after removing anomalies
plt.scatter(getX_PCA(X_train), y_train)
plt.scatter(getX_PCA(X_bad), y_bad)
Explanation: Anomaly Detection
Besides it's important to take into account the possible anomalies we can found in the training dataset. For this reason it's going to be calculated a small number of them to be removed.
End of explanation
# Get polynomial features
from sklearn.preprocessing import PolynomialFeatures
poly = preprocessing.PolynomialFeatures(degree=2)
X_train_orig = poly.fit_transform(X_train_orig)
X_train = poly.fit_transform(X_train)
X_test = poly.fit_transform(X_test)
Explanation: Polynomial Features
It could be interesting to extract more information between the current features. Actually we are only working with a small number of the original so we can afford to get polynomial features from them. Obviously that will increase the number of final features.
End of explanation
# Linear regression
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
lr = LinearRegression()
#
batch = 0
for train_idx, val_idx in kf.split(X_train, y_train):
X_t, X_v = X_train[train_idx], X_train[val_idx]
y_t, y_v = y_train[train_idx], y_train[val_idx]
#training
lr.fit(X_t, y_t)
#calculate costs
t_error = mean_squared_error(y_t, lr.predict(X_t))**0.5
v_error = mean_squared_error(y_v, lr.predict(X_v))**0.5
print("{}) Training error: {:.2f} Validation error: {:.2f} Score: {:.2f}"
.format(batch, t_error, v_error, lr.score(X_v, y_v)))
batch += 1
#Scores
print("Training score: {:.4f}".format(lr.score(X_train_orig, y_train_orig)))
#RMSLE
rmsle = mean_squared_error(y_train_orig, lr.predict(X_train_orig))**0.5
print("RMSLE: {:.4f}".format(rmsle))
# Plotting the results
plt.scatter(lr.predict(X_train_orig), y_train_orig)
# Gradient boosting
from sklearn import ensemble
params = {'n_estimators': 100, 'max_depth': X_train.shape[1], 'min_samples_split': 5,
'learning_rate': 0.1, 'loss': 'ls', 'random_state':9, 'warm_start':True}
gbr = ensemble.GradientBoostingRegressor(**params)
batch = 0
for train_idx, val_idx in kf.split(X_train, y_train):
X_t, X_v = X_train[train_idx], X_train[val_idx]
y_t, y_v = y_train[train_idx], y_train[val_idx]
#training
gbr.fit(X_t, y_t)
#calculate costs
t_error = mean_squared_error(y_t, gbr.predict(X_t))**0.5
v_error = mean_squared_error(y_v, gbr.predict(X_v))**0.5
print("{}) Training error: {:.2f} Validation error: {:.2f} Score: {:.2f}"
.format(batch, t_error, v_error, gbr.score(X_v, y_v)))
batch += 1
#Scores
print("Training score: {:.4f}".format(gbr.score(X_train_orig, y_train_orig)))
#RMSLE
rmsle = mean_squared_error(y_train_orig, gbr.predict(X_train_orig))**0.5
print("RMSLE: {:.4f}".format(rmsle))
# Plotting the results
plt.scatter(gbr.predict(X_train_orig), y_train_orig)
# AdaBoost
from sklearn.ensemble import AdaBoostRegressor
from sklearn.tree import DecisionTreeRegressor
abr = AdaBoostRegressor(DecisionTreeRegressor(max_depth=X_train.shape[1]),
n_estimators=100, random_state=9)
batch = 0
for train_idx, val_idx in kf.split(X_train, y_train):
X_t, X_v = X_train[train_idx], X_train[val_idx]
y_t, y_v = y_train[train_idx], y_train[val_idx]
#training
abr.fit(X_t, y_t)
#calculate costs
t_error = mean_squared_error(y_t, abr.predict(X_t))**0.5
v_error = mean_squared_error(y_v, abr.predict(X_v))**0.5
print("{}) Training error: {:.2f} Validation error: {:.2f} Score: {:.2f}"
.format(batch, t_error, v_error, abr.score(X_v, y_v)))
batch += 1
#Scores
print("Training score: {:.4f}".format(abr.score(X_train_orig, y_train_orig)))
#RMSLE
rmsle = mean_squared_error(y_train_orig, abr.predict(X_train_orig))**0.5
print("RMSLE: {:.4f}".format(rmsle))
# Plotting the results
plt.scatter(abr.predict(X_train_orig), y_train_orig)
Explanation: Models
*__Note__: a logarithmic function has been applied to 'SalePrice' so using the mean squared error directly we will obtain the RMSLE.
End of explanation
from sklearn.linear_model import LinearRegression
slr = LinearRegression()
sclr = preprocessing.StandardScaler()
def features_level1(X):
X0 = lr.predict(X)
X1 = gbr.predict(X)
X2 = abr.predict(X)
Xt = np.array([X0, X1, X2]).T
return sclr.fit_transform(Xt)
def stack_training(X, y):
slr.fit(features_level1(X), y)
def stack_predict(X):
return slr.predict(features_level1(X))
def stack_score(X, y):
return slr.score(features_level1(X), y)
#
batch = 0
kf = KFold(n_splits=3, random_state=9)
for train_idx, val_idx in kf.split(X_train, y_train):
X_t, X_v = X_train[train_idx], X_train[val_idx]
y_t, y_v = y_train[train_idx], y_train[val_idx]
#training
stack_training(X_t, y_t)
#calculate costs
t_error = mean_squared_error(y_t, stack_predict(X_t))**0.5
v_error = mean_squared_error(y_v, stack_predict(X_v))**0.5
print("{}) Training error: {:.2f} Validation error: {:.2f} Score: {:.2f}"
.format(batch, t_error, v_error, stack_score(X_v, y_v)))
batch += 1
rmsle = mean_squared_error(y_train_orig, stack_predict(X_train_orig))**0.5
print("RMSLE: {:.4f}".format(rmsle))
# Plotting the results
plt.scatter(stack_predict(X_train_orig), y_train_orig)
Explanation: Stacked Model
In order to improve the previous predictions it's going to create a simple stacked model with the following architecture:
Level1 is composed of previous trained LinearRegressor, GradiendBoostingRegressor and AdaBoostRegressor
The outcome of this level1 layer is passed to a LinearRegressor.
End of explanation
def avg_predict(X):
return (lr.predict(X) + gbr.predict(X) + abr.predict(X))/3
predictions = avg_predict(X_train_orig)
RMSLE = mean_squared_error(y_train_orig, predictions)**0.5
print("RMSLE: {:.3f}".format(RMSLE))
# Plotting the results
plt.scatter(avg_predict(X_train_orig), y_train_orig)
Explanation: Averaged Model
Same as before, the averaged model tries to improve the predictions results. In this case the architecture is indeed much simpler. The final prediction is averaged with the outcomes of the LinearRegressor, GradientBoostingRegressor and AdaBoostRegressor.
End of explanation
from sklearn.metrics import mean_squared_error
import random
RMSLE_lr = mean_squared_error(y_train, lr.predict(X_train))**0.5
RMSLE_gbr = mean_squared_error(y_train, gbr.predict(X_train))**0.5
RMSLE_abr = mean_squared_error(y_train, abr.predict(X_train))**0.5
RMSLE_avg = mean_squared_error(y_train, stack_predict(X_train))**0.5
RMSLE_stack = mean_squared_error(y_train, avg_predict(X_train))**0.5
print("RMSLE lr: {:.3f}".format(RMSLE_lr))
print("RMSLE gbr: {:.3f}".format(RMSLE_gbr))
print("RMSLE abr: {:.3f}".format(RMSLE_abr))
print("RMSLE average: {:.3f}".format(RMSLE_avg))
print("RMSLE stacked: {:.3f}".format(RMSLE_stack))
Explanation: Evaluation
End of explanation
import os
predict = avg_predict(X_test)
#predict = stack_predict(X_test)
#predict = lr.predict(X_test)
#predictions are logs, return to the value
predict = np.exp(predict)
file = "Id,SalePrice" + os.linesep
startId = 1461
for i in range(len(X_test)):
file += "{},{}".format(startId, (int)(predict[i])) + os.linesep
startId += 1
#print(file)
# Save to file
with open('attempt.txt', 'w') as f:
f.write(file)
Explanation: Get Predictions
End of explanation |
7,954 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Tensors and Variables
Learning Objectives
Understand Basic and Advanced Tensor Concepts
Understand Single-Axis and Multi-Axis Indexing
Create Tensors and Variables
Introduction
In this notebook, we look at tensors, which are multi-dimensional arrays with a uniform type (called a dtype). You can see all supported dtypes at tf.dtypes.DType. If you're familiar with NumPy, tensors are (kind of) like np.arrays. All tensors are immutable like python numbers and strings
Step1: Lab Task 1
Step2: A "vector" or "rank-1" tensor is like a list of values. A vector has 1-axis
Step3: A "matrix" or "rank-2" tensor has 2-axes
Step4: <table>
<tr>
<th>A scalar, shape
Step5: There are many ways you might visualize a tensor with more than 2-axes.
<table>
<tr>
<th colspan=3>A 3-axis tensor, shape
Step6: Tensors often contain floats and ints, but have many other types, including
Step7: Tensors are used in all kinds of operations (ops).
Step8: About shapes
Tensors have shapes. Some vocabulary
Step9: <table>
<tr>
<th colspan=2>A rank-4 tensor, shape
Step10: While axes are often referred to by their indices, you should always keep track of the meaning of each. Often axes are ordered from global to local
Step11: Indexing with a scalar removes the dimension
Step12: Indexing with a
Step13: Multi-axis indexing
Higher rank tensors are indexed by passing multiple indices.
The single-axis exact same rules as in the single-axis case apply to each axis independently.
Step14: Passing an integer for each index the result is a scalar.
Step15: You can index using any combination integers and slices
Step16: Here is an example with a 3-axis tensor
Step17: <table>
<tr>
<th colspan=2>Selecting the last feature across all locations in each example in the batch </th>
</tr>
<tr>
<td>
<img src="../images/tensor/index1.png" alt="A 3x2x5 tensor with all the values at the index-4 of the last axis selected.">
</td>
<td>
<img src="../images/tensor/index2.png" alt="The selected values packed into a 2-axis tensor.">
</td>
</tr>
</table>
Manipulating Shapes
Reshaping a tensor is of great utility.
The tf.reshape operation is fast and cheap as the underlying data does not need to be duplicated.
Step18: You can reshape a tensor into a new shape. Reshaping is fast and cheap as the underlying data does not need to be duplicated.
Step19: The data maintains it's layout in memory and a new tensor is created, with the requested shape, pointing to the same data. TensorFlow uses C-style "row-major" memory ordering, where incrementing the right-most index corresponds to a single step in memory.
Step20: If you flatten a tensor you can see what order it is laid out in memory.
Step21: Typically the only reasonable uses of tf.reshape are to combine or split adjacent axes (or add/remove 1s).
For this 3x2x5 tensor, reshaping to (3x2)x5 or 3x(2x5) are both reasonable things to do, as the slices do not mix
Step22: <table>
<th colspan=3>
Some good reshapes.
</th>
<tr>
<td>
<img src="../images/tensor/reshape-before.png" alt="A 3x2x5 tensor">
</td>
<td>
<img src="../images/tensor/reshape-good1.png" alt="The same data reshaped to (3x2)x5">
</td>
<td>
<img src="../images/tensor/reshape-good2.png" alt="The same data reshaped to 3x(2x5)">
</td>
</tr>
</table>
Reshaping will "work" for any new shape with the same total number of elements, but it will not do anything useful if you do not respect the order of the axes.
Swapping axes in tf.reshape does not work, you need tf.transpose for that.
Step23: <table>
<th colspan=3>
Some bad reshapes.
</th>
<tr>
<td>
<img src="../images/tensor/reshape-bad.png" alt="You can't reorder axes, use tf.transpose for that">
</td>
<td>
<img src="../images/tensor/reshape-bad4.png" alt="Anything that mixes the slices of data together is probably wrong.">
</td>
<td>
<img src="../images/tensor/reshape-bad2.png" alt="The new shape must fit exactly.">
</td>
</tr>
</table>
You may run across not-fully-specified shapes. Either the shape contains a None (a dimension's length is unknown) or the shape is None (the rank of the tensor is unknown).
Except for tf.RaggedTensor, this will only occur in the context of TensorFlow's, symbolic, graph-building APIs
Step24: Broadcasting
Broadcasting is a concept borrowed from the equivalent feature in NumPy. In short, under certain conditions, smaller tensors are "stretched" automatically to fit larger tensors when running combined operations on them.
The simplest and most common case is when you attempt to multiply or add a tensor to a scalar. In that case, the scalar is broadcast to be the same shape as the other argument.
Step25: Likewise, 1-sized dimensions can be stretched out to match the other arguments. Both arguments can be stretched in the same computation.
In this case a 3x1 matrix is element-wise multiplied by a 1x4 matrix to produce a 3x4 matrix. Note how the leading 1 is optional
Step26: <table>
<tr>
<th>A broadcasted add
Step27: Most of the time, broadcasting is both time and space efficient, as the broadcast operation never materializes the expanded tensors in memory.
You see what broadcasting looks like using tf.broadcast_to.
Step28: Unlike a mathematical op, for example, broadcast_to does nothing special to save memory. Here, you are materializing the tensor.
It can get even more complicated. This section of Jake VanderPlas's book Python Data Science Handbook shows more broadcasting tricks (again in NumPy).
tf.convert_to_tensor
Most ops, like tf.matmul and tf.reshape take arguments of class tf.Tensor. However, you'll notice in the above case, we frequently pass Python objects shaped like tensors.
Most, but not all, ops call convert_to_tensor on non-tensor arguments. There is a registry of conversions, and most object classes like NumPy's ndarray, TensorShape, Python lists, and tf.Variable will all convert automatically.
See tf.register_tensor_conversion_function for more details, and if you have your own type you'd like to automatically convert to a tensor.
Ragged Tensors
A tensor with variable numbers of elements along some axis is called "ragged". Use tf.ragged.RaggedTensor for ragged data.
For example, This cannot be represented as a regular tensor
Step29: Instead create a tf.RaggedTensor using tf.ragged.constant
Step30: The shape of a tf.RaggedTensor contains unknown dimensions
Step31: String tensors
tf.string is a dtype, which is to say we can represent data as strings (variable-length byte arrays) in tensors.
The strings are atomic and cannot be indexed the way Python strings are. The length of the string is not one of the dimensions of the tensor. See tf.strings for functions to manipulate them.
Here is a scalar string tensor
Step32: And a vector of strings
Step33: In the above printout the b prefix indicates that tf.string dtype is not a unicode string, but a byte-string. See the Unicode Tutorial for more about working with unicode text in TensorFlow.
If you pass unicode characters they are utf-8 encoded.
Step34: Some basic functions with strings can be found in tf.strings, including tf.strings.split.
Step35: <table>
<tr>
<th>Three strings split, shape
Step36: Although you can't use tf.cast to turn a string tensor into numbers, you can convert it into bytes, and then into numbers.
Step37: The tf.string dtype is used for all raw bytes data in TensorFlow. The tf.io module contains functions for converting data to and from bytes, including decoding images and parsing csv.
Sparse tensors
Sometimes, your data is sparse, like a very wide embedding space. TensorFlow supports tf.sparse.SparseTensor and related operations to store sparse data efficiently.
<table>
<tr>
<th>A `tf.SparseTensor`, shape
Step38: Lab Task 3
Step39: Create a variable
To create a variable, provide an initial value. The tf.Variable will have the same dtype as the initialization value.
Step40: A variable looks and acts like a tensor, and, in fact, is a data structure backed by a tf.Tensor. Like tensors, they have a dtype and a shape, and can be exported to NumPy.
Step41: Most tensor operations work on variables as expected, although variables cannot be reshaped.
Step42: As noted above, variables are backed by tensors. You can reassign the tensor using tf.Variable.assign. Calling assign does not (usually) allocate a new tensor; instead, the existing tensor's memory is reused.
Step43: If you use a variable like a tensor in operations, you will usually operate on the backing tensor.
Creating new variables from existing variables duplicates the backing tensors. Two variables will not share the same memory.
Step44: Lifecycles, naming, and watching
In Python-based TensorFlow, tf.Variable instance have the same lifecycle as other Python objects. When there are no references to a variable it is automatically deallocated.
Variables can also be named which can help you track and debug them. You can give two variables the same name.
Step45: Variable names are preserved when saving and loading models. By default, variables in models will acquire unique variable names automatically, so you don't need to assign them yourself unless you want to.
Although variables are important for differentiation, some variables will not need to be differentiated. You can turn off gradients for a variable by setting trainable to false at creation. An example of a variable that would not need gradients is a training step counter.
Step46: Placing variables and tensors
For better performance, TensorFlow will attempt to place tensors and variables on the fastest device compatible with its dtype. This means most variables are placed on a GPU if one is available.
However, we can override this. In this snippet, we can place a float tensor and a variable on the CPU, even if a GPU is available. By turning on device placement logging (see Setup), we can see where the variable is placed.
Note
Step47: It's possible to set the location of a variable or tensor on one device and do the computation on another device. This will introduce delay, as data needs to be copied between the devices.
You might do this, however, if you had multiple GPU workers but only want one copy of the variables. | Python Code:
import tensorflow as tf
import numpy as np
print("TensorFlow version: ",tf.version.VERSION)
Explanation: Introduction to Tensors and Variables
Learning Objectives
Understand Basic and Advanced Tensor Concepts
Understand Single-Axis and Multi-Axis Indexing
Create Tensors and Variables
Introduction
In this notebook, we look at tensors, which are multi-dimensional arrays with a uniform type (called a dtype). You can see all supported dtypes at tf.dtypes.DType. If you're familiar with NumPy, tensors are (kind of) like np.arrays. All tensors are immutable like python numbers and strings: you can never update the contents of a tensor, only create a new one.
We also look at variables, a tf.Variable represents a tensor whose value can be changed by running operations (ops) on it. Specific ops allow you to read and modify the values of this tensor. Higher level libraries like tf.keras use tf.Variable to store model parameters.
Each learning objective will correspond to a #TODO in the notebook where you will complete the notebook cell's code before running. Refer to the solution for reference.
Load necessary libraries
We will start by importing the necessary libraries for this lab.
End of explanation
# This will be an int32 tensor by default; see "dtypes" below.
rank_0_tensor = tf.constant(4)
print(rank_0_tensor)
Explanation: Lab Task 1: Understand Basic and Advanced Tensor Concepts
Basics
Let's create some basic tensors.
Here is a "scalar" or "rank-0" tensor . A scalar contains a single value, and no "axes".
End of explanation
# Let's make this a float tensor.
rank_1_tensor = tf.constant([2.0, 3.0, 4.0])
print(rank_1_tensor)
Explanation: A "vector" or "rank-1" tensor is like a list of values. A vector has 1-axis:
End of explanation
# If we want to be specific, we can set the dtype (see below) at creation time
rank_2_tensor = tf.constant([[1, 2],
[3, 4],
[5, 6]], dtype= # TODO 1a
# TODO: Your code goes here.
print(rank_2_tensor)
Explanation: A "matrix" or "rank-2" tensor has 2-axes:
End of explanation
# There can be an arbitrary number of
# axes (sometimes called "dimensions")
rank_3_tensor = tf.constant([
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]],
[[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]],])
print(rank_3_tensor)
Explanation: <table>
<tr>
<th>A scalar, shape: <code>[]</code></th>
<th>A vector, shape: <code>[3]</code></th>
<th>A matrix, shape: <code>[3, 2]</code></th>
</tr>
<tr>
<td>
<img src="../images/tensor/scalar.png" alt="A scalar, the number 4" />
</td>
<td>
<img src="../images/tensor/vector.png" alt="The line with 3 sections, each one containing a number."/>
</td>
<td>
<img src="../images/tensor/matrix.png" alt="A 3x2 grid, with each cell containing a number.">
</td>
</tr>
</table>
Tensors may have more axes, here is a tensor with 3-axes:
End of explanation
# Convert a tensor to a NumPy array using `np.array` method
# TODO 1b
# TODO -- Your code here.
# Convert a tensor to a NumPy array using `tensor.numpy` method
# TODO 1c
# TODO -- Your code here.
Explanation: There are many ways you might visualize a tensor with more than 2-axes.
<table>
<tr>
<th colspan=3>A 3-axis tensor, shape: <code>[3, 2, 5]</code></th>
<tr>
<tr>
<td>
<img src="../images/tensor/3-axis_numpy.png"/>
</td>
<td>
<img src="../images/tensor/3-axis_front.png"/>
</td>
<td>
<img src="../images/tensor/3-axis_block.png"/>
</td>
</tr>
</table>
You can convert a tensor to a NumPy array either using np.array or the tensor.numpy method:
End of explanation
a = tf.constant([[1, 2],
[3, 4]])
b = tf.constant([[1, 1],
[1, 1]]) # Could have also said `tf.ones([2,2])`
print(tf.add(a, b), "\n")
print(tf.multiply(a, b), "\n")
print(tf.matmul(a, b), "\n")
print(a + b, "\n") # element-wise addition
print(a * b, "\n") # element-wise multiplication
print(a @ b, "\n") # matrix multiplication
Explanation: Tensors often contain floats and ints, but have many other types, including:
complex numbers
strings
The base tf.Tensor class requires tensors to be "rectangular"---that is, along each axis, every element is the same size. However, there are specialized types of Tensors that can handle different shapes:
ragged (see RaggedTensor below)
sparse (see SparseTensor below)
We can do basic math on tensors, including addition, element-wise multiplication, and matrix multiplication.
End of explanation
c = tf.constant([[4.0, 5.0], [10.0, 1.0]])
# Find the largest value
print(tf.reduce_max(c))
# TODO 1d
# Find the index of the largest value
# TODO -- Your code here.
# Compute the softmax
# TODO -- Your code here.
Explanation: Tensors are used in all kinds of operations (ops).
End of explanation
rank_4_tensor = tf.zeros([3, 2, 4, 5])
Explanation: About shapes
Tensors have shapes. Some vocabulary:
Shape: The length (number of elements) of each of the dimensions of a tensor.
Rank: Number of tensor dimensions. A scalar has rank 0, a vector has rank 1, a matrix is rank 2.
Axis or Dimension: A particular dimension of a tensor.
Size: The total number of items in the tensor, the product shape vector
Note: Although you may see reference to a "tensor of two dimensions", a rank-2 tensor does not usually describe a 2D space.
Tensors and tf.TensorShape objects have convenient properties for accessing these:
End of explanation
print("Type of every element:", rank_4_tensor.dtype)
print("Number of dimensions:", rank_4_tensor.ndim)
print("Shape of tensor:", rank_4_tensor.shape)
print("Elements along axis 0 of tensor:", rank_4_tensor.shape[0])
print("Elements along the last axis of tensor:", rank_4_tensor.shape[-1])
print("Total number of elements (3*2*4*5): ", tf.size(rank_4_tensor).numpy())
Explanation: <table>
<tr>
<th colspan=2>A rank-4 tensor, shape: <code>[3, 2, 4, 5]</code></th>
</tr>
<tr>
<td>
<img src="../images/tensor/shape.png" alt="A tensor shape is like a vector.">
<td>
<img src="../images/tensor/4-axis_block.png" alt="A 4-axis tensor">
</td>
</tr>
</table>
End of explanation
rank_1_tensor = tf.constant([0, 1, 1, 2, 3, 5, 8, 13, 21, 34])
print(rank_1_tensor.numpy())
Explanation: While axes are often referred to by their indices, you should always keep track of the meaning of each. Often axes are ordered from global to local: The batch axis first, followed by spatial dimensions, and features for each location last. This way feature vectors are contiguous regions of memory.
<table>
<tr>
<th>Typical axis order</th>
</tr>
<tr>
<td>
<img src="../images/tensor/shape2.png" alt="Keep track of what each axis is. A 4-axis tensor might be: Batch, Width, Height, Freatures">
</td>
</tr>
</table>
Lab Task 2: Understand Single-Axis and Multi-Axis Indexing
Single-axis indexing
TensorFlow follow standard python indexing rules, similar to indexing a list or a string in python, and the bacic rules for numpy indexing.
indexes start at 0
negative indices count backwards from the end
colons, :, are used for slices start:stop:step
End of explanation
print("First:", rank_1_tensor[0].numpy())
print("Second:", rank_1_tensor[1].numpy())
print("Last:", rank_1_tensor[-1].numpy())
Explanation: Indexing with a scalar removes the dimension:
End of explanation
print("Everything:", rank_1_tensor[:].numpy())
print("Before 4:", rank_1_tensor[:4].numpy())
print("From 4 to the end:", rank_1_tensor[4:].numpy())
print("From 2, before 7:", rank_1_tensor[2:7].numpy())
print("Every other item:", rank_1_tensor[::2].numpy())
print("Reversed:", rank_1_tensor[::-1].numpy())
Explanation: Indexing with a : slice keeps the dimension:
End of explanation
print(rank_2_tensor.numpy())
Explanation: Multi-axis indexing
Higher rank tensors are indexed by passing multiple indices.
The single-axis exact same rules as in the single-axis case apply to each axis independently.
End of explanation
# Pull out a single value from a 2-rank tensor
print(rank_2_tensor[1, 1].numpy())
Explanation: Passing an integer for each index the result is a scalar.
End of explanation
# Get row and column tensors
print("Second row:", rank_2_tensor[1, :].numpy())
print("Second column:", rank_2_tensor[:, 1].numpy())
print("Last row:", rank_2_tensor[-1, :].numpy())
print("First item in last column:", rank_2_tensor[0, -1].numpy())
print("Skip the first row:")
print(rank_2_tensor[1:, :].numpy(), "\n")
Explanation: You can index using any combination integers and slices:
End of explanation
print(rank_3_tensor[:, :, 4])
Explanation: Here is an example with a 3-axis tensor:
End of explanation
# Shape returns a `TensorShape` object that shows the size on each dimension
var_x = tf.Variable(tf.constant([[1], [2], [3]]))
print(var_x.shape)
# You can convert this object into a Python list, too
print(var_x.shape.as_list())
Explanation: <table>
<tr>
<th colspan=2>Selecting the last feature across all locations in each example in the batch </th>
</tr>
<tr>
<td>
<img src="../images/tensor/index1.png" alt="A 3x2x5 tensor with all the values at the index-4 of the last axis selected.">
</td>
<td>
<img src="../images/tensor/index2.png" alt="The selected values packed into a 2-axis tensor.">
</td>
</tr>
</table>
Manipulating Shapes
Reshaping a tensor is of great utility.
The tf.reshape operation is fast and cheap as the underlying data does not need to be duplicated.
End of explanation
# We can reshape a tensor to a new shape.
# Note that we're passing in a list
# TODO 2a
# TODO -- Your code here.
print(var_x.shape)
print(reshaped.shape)
Explanation: You can reshape a tensor into a new shape. Reshaping is fast and cheap as the underlying data does not need to be duplicated.
End of explanation
print(rank_3_tensor)
Explanation: The data maintains it's layout in memory and a new tensor is created, with the requested shape, pointing to the same data. TensorFlow uses C-style "row-major" memory ordering, where incrementing the right-most index corresponds to a single step in memory.
End of explanation
# A `-1` passed in the `shape` argument says "Whatever fits".
print(tf.reshape(rank_3_tensor, [-1]))
Explanation: If you flatten a tensor you can see what order it is laid out in memory.
End of explanation
print(tf.reshape(rank_3_tensor, [3*2, 5]), "\n")
print(tf.reshape(rank_3_tensor, [3, -1]))
Explanation: Typically the only reasonable uses of tf.reshape are to combine or split adjacent axes (or add/remove 1s).
For this 3x2x5 tensor, reshaping to (3x2)x5 or 3x(2x5) are both reasonable things to do, as the slices do not mix:
End of explanation
# Bad examples: don't do this
# You can't reorder axes with reshape.
print(tf.reshape(rank_3_tensor, [2, 3, 5]), "\n")
# This is a mess
print(tf.reshape(rank_3_tensor, [5, 6]), "\n")
# This doesn't work at all
try:
tf.reshape(rank_3_tensor, [7, -1])
except Exception as e: print(e)
Explanation: <table>
<th colspan=3>
Some good reshapes.
</th>
<tr>
<td>
<img src="../images/tensor/reshape-before.png" alt="A 3x2x5 tensor">
</td>
<td>
<img src="../images/tensor/reshape-good1.png" alt="The same data reshaped to (3x2)x5">
</td>
<td>
<img src="../images/tensor/reshape-good2.png" alt="The same data reshaped to 3x(2x5)">
</td>
</tr>
</table>
Reshaping will "work" for any new shape with the same total number of elements, but it will not do anything useful if you do not respect the order of the axes.
Swapping axes in tf.reshape does not work, you need tf.transpose for that.
End of explanation
# Use the `Tensor.dtype` property
# You can cast from type to type
# TODO 2b
the_f64_tensor = # TODO -- Your code here.
the_f16_tensor = # TODO -- Your code here.
# Now, let's cast to an uint8 and lose the decimal precision
the_u8_tensor = # TODO -- Your code here.
print(the_u8_tensor)
Explanation: <table>
<th colspan=3>
Some bad reshapes.
</th>
<tr>
<td>
<img src="../images/tensor/reshape-bad.png" alt="You can't reorder axes, use tf.transpose for that">
</td>
<td>
<img src="../images/tensor/reshape-bad4.png" alt="Anything that mixes the slices of data together is probably wrong.">
</td>
<td>
<img src="../images/tensor/reshape-bad2.png" alt="The new shape must fit exactly.">
</td>
</tr>
</table>
You may run across not-fully-specified shapes. Either the shape contains a None (a dimension's length is unknown) or the shape is None (the rank of the tensor is unknown).
Except for tf.RaggedTensor, this will only occur in the context of TensorFlow's, symbolic, graph-building APIs:
tf.function
The keras functional API.
More on DTypes
To inspect a tf.Tensor's data type use the Tensor.dtype property.
When creating a tf.Tensor from a Python object you may optionally specify the datatype.
If you don't, TensorFlow chooses a datatype that can represent your data. TensorFlow converts Python integers to tf.int32 and python floating point numbers to tf.float32. Otherwise TensorFlow uses the same rules NumPy uses when converting to arrays.
You can cast from type to type.
End of explanation
x = tf.constant([1, 2, 3])
y = tf.constant(2)
z = tf.constant([2, 2, 2])
# All of these are the same computation
print(tf.multiply(x, 2))
print(x * y)
print(x * z)
Explanation: Broadcasting
Broadcasting is a concept borrowed from the equivalent feature in NumPy. In short, under certain conditions, smaller tensors are "stretched" automatically to fit larger tensors when running combined operations on them.
The simplest and most common case is when you attempt to multiply or add a tensor to a scalar. In that case, the scalar is broadcast to be the same shape as the other argument.
End of explanation
# These are the same computations
x = tf.reshape(x,[3,1])
y = tf.range(1, 5)
print(x, "\n")
print(y, "\n")
print(tf.multiply(x, y))
Explanation: Likewise, 1-sized dimensions can be stretched out to match the other arguments. Both arguments can be stretched in the same computation.
In this case a 3x1 matrix is element-wise multiplied by a 1x4 matrix to produce a 3x4 matrix. Note how the leading 1 is optional: The shape of y is [4].
End of explanation
x_stretch = tf.constant([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
y_stretch = tf.constant([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
print(x_stretch * y_stretch) # Again, operator overloading
Explanation: <table>
<tr>
<th>A broadcasted add: a <code>[3, 1]</code> times a <code>[1, 4]</code> gives a <code>[3,4]</code> </th>
</tr>
<tr>
<td>
<img src="../images/tensor/broadcasting.png" alt="Adding a 3x1 matrix to a 4x1 matrix results in a 3x4 matrix">
</td>
</tr>
</table>
Here is the same operation without broadcasting:
End of explanation
print(tf.broadcast_to(tf.constant([1, 2, 3]), [3, 3]))
Explanation: Most of the time, broadcasting is both time and space efficient, as the broadcast operation never materializes the expanded tensors in memory.
You see what broadcasting looks like using tf.broadcast_to.
End of explanation
ragged_list = [
[0, 1, 2, 3],
[4, 5],
[6, 7, 8],
[9]]
try:
tensor = tf.constant(ragged_list)
except Exception as e: print(e)
Explanation: Unlike a mathematical op, for example, broadcast_to does nothing special to save memory. Here, you are materializing the tensor.
It can get even more complicated. This section of Jake VanderPlas's book Python Data Science Handbook shows more broadcasting tricks (again in NumPy).
tf.convert_to_tensor
Most ops, like tf.matmul and tf.reshape take arguments of class tf.Tensor. However, you'll notice in the above case, we frequently pass Python objects shaped like tensors.
Most, but not all, ops call convert_to_tensor on non-tensor arguments. There is a registry of conversions, and most object classes like NumPy's ndarray, TensorShape, Python lists, and tf.Variable will all convert automatically.
See tf.register_tensor_conversion_function for more details, and if you have your own type you'd like to automatically convert to a tensor.
Ragged Tensors
A tensor with variable numbers of elements along some axis is called "ragged". Use tf.ragged.RaggedTensor for ragged data.
For example, This cannot be represented as a regular tensor:
<table>
<tr>
<th>A `tf.RaggedTensor`, shape: <code>[4, None]</code></th>
</tr>
<tr>
<td>
<img src="../images/tensor/ragged.png" alt="A 2-axis ragged tensor, each row can have a different length.">
</td>
</tr>
</table>
End of explanation
# TODO 2c
ragged_tensor = # TODO -- Your code here.
print(ragged_tensor)
Explanation: Instead create a tf.RaggedTensor using tf.ragged.constant:
End of explanation
print(ragged_tensor.shape)
Explanation: The shape of a tf.RaggedTensor contains unknown dimensions:
End of explanation
# Tensors can be strings, too here is a scalar string.
scalar_string_tensor = tf.constant("Gray wolf")
print(scalar_string_tensor)
Explanation: String tensors
tf.string is a dtype, which is to say we can represent data as strings (variable-length byte arrays) in tensors.
The strings are atomic and cannot be indexed the way Python strings are. The length of the string is not one of the dimensions of the tensor. See tf.strings for functions to manipulate them.
Here is a scalar string tensor:
End of explanation
# If we have two string tensors of different lengths, this is OK.
tensor_of_strings = tf.constant(["Gray wolf",
"Quick brown fox",
"Lazy dog"])
# Note that the shape is (2,), indicating that it is 2 x unknown.
print(tensor_of_strings)
Explanation: And a vector of strings:
<table>
<tr>
<th>A vector of strings, shape: <code>[3,]</code></th>
</tr>
<tr>
<td>
<img src="../images/tensor/strings.png" alt="The string length is not one of the tensor's axes.">
</td>
</tr>
</table>
End of explanation
tf.constant("🥳👍")
Explanation: In the above printout the b prefix indicates that tf.string dtype is not a unicode string, but a byte-string. See the Unicode Tutorial for more about working with unicode text in TensorFlow.
If you pass unicode characters they are utf-8 encoded.
End of explanation
# We can use split to split a string into a set of tensors
print(tf.strings.split(scalar_string_tensor, sep=" "))
# ...but it turns into a `RaggedTensor` if we split up a tensor of strings,
# as each string might be split into a different number of parts.
print(tf.strings.split(tensor_of_strings))
Explanation: Some basic functions with strings can be found in tf.strings, including tf.strings.split.
End of explanation
text = tf.constant("1 10 100")
print(tf.strings.to_number(tf.strings.split(text, " ")))
Explanation: <table>
<tr>
<th>Three strings split, shape: <code>[3, None]</code></th>
</tr>
<tr>
<td>
<img src="../images/tensor/string-split.png" alt="Splitting multiple strings returns a tf.RaggedTensor">
</td>
</tr>
</table>
And tf.string.to_number:
End of explanation
byte_strings = tf.strings.bytes_split(tf.constant("Duck"))
byte_ints = tf.io.decode_raw(tf.constant("Duck"), tf.uint8)
print("Byte strings:", byte_strings)
print("Bytes:", byte_ints)
# Or split it up as unicode and then decode it
unicode_bytes = tf.constant("アヒル 🦆")
unicode_char_bytes = tf.strings.unicode_split(unicode_bytes, "UTF-8")
unicode_values = tf.strings.unicode_decode(unicode_bytes, "UTF-8")
print("\nUnicode bytes:", unicode_bytes)
print("\nUnicode chars:", unicode_char_bytes)
print("\nUnicode values:", unicode_values)
Explanation: Although you can't use tf.cast to turn a string tensor into numbers, you can convert it into bytes, and then into numbers.
End of explanation
# Sparse tensors store values by index in a memory-efficient manner
# TODO 2d
sparse_tensor = # TODO -- Your code here.
print(sparse_tensor, "\n")
# We can convert sparse tensors to dense
print(tf.sparse.to_dense(sparse_tensor))
Explanation: The tf.string dtype is used for all raw bytes data in TensorFlow. The tf.io module contains functions for converting data to and from bytes, including decoding images and parsing csv.
Sparse tensors
Sometimes, your data is sparse, like a very wide embedding space. TensorFlow supports tf.sparse.SparseTensor and related operations to store sparse data efficiently.
<table>
<tr>
<th>A `tf.SparseTensor`, shape: <code>[3, 4]</code></th>
</tr>
<tr>
<td>
<img src="../images/tensor/sparse.png" alt="An 3x4 grid, with values in only two of the cells.">
</td>
</tr>
</table>
End of explanation
import tensorflow as tf
# Uncomment to see where your variables get placed (see below)
# tf.debugging.set_log_device_placement(True)
Explanation: Lab Task 3: Introduction to Variables
A TensorFlow variable is the recommended way to represent shared, persistent state your program manipulates. This guide covers how to create, update, and manage instances of tf.Variable in TensorFlow.
Variables are created and tracked via the tf.Variable class. A tf.Variable represents a tensor whose value can be changed by running ops on it. Specific ops allow you to read and modify the values of this tensor. Higher level libraries like tf.keras use tf.Variable to store model parameters.
Setup
This notebook discusses variable placement. If you want to see on what device your variables are placed, uncomment this line.
End of explanation
# TODO 3a
my_tensor = # TODO -- Your code here.
my_variable = # TODO -- Your code here.
# Variables can be all kinds of types, just like tensors
bool_variable = tf.Variable([False, False, False, True])
complex_variable = tf.Variable([5 + 4j, 6 + 1j])
Explanation: Create a variable
To create a variable, provide an initial value. The tf.Variable will have the same dtype as the initialization value.
End of explanation
print("Shape: ",my_variable.shape)
print("DType: ",my_variable.dtype)
print("As NumPy: ", my_variable.numpy)
Explanation: A variable looks and acts like a tensor, and, in fact, is a data structure backed by a tf.Tensor. Like tensors, they have a dtype and a shape, and can be exported to NumPy.
End of explanation
print("A variable:",my_variable)
print("\nViewed as a tensor:", tf.convert_to_tensor(my_variable))
print("\nIndex of highest value:", tf.argmax(my_variable))
# This creates a new tensor; it does not reshape the variable.
print("\nCopying and reshaping: ", tf.reshape(my_variable, ([1,4])))
Explanation: Most tensor operations work on variables as expected, although variables cannot be reshaped.
End of explanation
a = tf.Variable([2.0, 3.0])
# This will keep the same dtype, float32
a.assign([1, 2])
# Not allowed as it resizes the variable:
try:
a.assign([1.0, 2.0, 3.0])
except Exception as e: print(e)
Explanation: As noted above, variables are backed by tensors. You can reassign the tensor using tf.Variable.assign. Calling assign does not (usually) allocate a new tensor; instead, the existing tensor's memory is reused.
End of explanation
a = tf.Variable([2.0, 3.0])
# Create b based on the value of a
b = tf.Variable(a)
a.assign([5, 6])
# a and b are different
print(a.numpy())
print(b.numpy())
# There are other versions of assign
print(a.assign_add([2,3]).numpy()) # [7. 9.]
print(a.assign_sub([7,9]).numpy()) # [0. 0.]
Explanation: If you use a variable like a tensor in operations, you will usually operate on the backing tensor.
Creating new variables from existing variables duplicates the backing tensors. Two variables will not share the same memory.
End of explanation
# Create a and b; they have the same value but are backed by different tensors.
a = tf.Variable(my_tensor, name="Mark")
# A new variable with the same name, but different value
# Note that the scalar add is broadcast
b = tf.Variable(my_tensor + 1, name="Mark")
# These are elementwise-unequal, despite having the same name
print(a == b)
Explanation: Lifecycles, naming, and watching
In Python-based TensorFlow, tf.Variable instance have the same lifecycle as other Python objects. When there are no references to a variable it is automatically deallocated.
Variables can also be named which can help you track and debug them. You can give two variables the same name.
End of explanation
step_counter = tf.Variable(1, trainable=False)
Explanation: Variable names are preserved when saving and loading models. By default, variables in models will acquire unique variable names automatically, so you don't need to assign them yourself unless you want to.
Although variables are important for differentiation, some variables will not need to be differentiated. You can turn off gradients for a variable by setting trainable to false at creation. An example of a variable that would not need gradients is a training step counter.
End of explanation
with tf.device('CPU:0'):
# Create some tensors
a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
Explanation: Placing variables and tensors
For better performance, TensorFlow will attempt to place tensors and variables on the fastest device compatible with its dtype. This means most variables are placed on a GPU if one is available.
However, we can override this. In this snippet, we can place a float tensor and a variable on the CPU, even if a GPU is available. By turning on device placement logging (see Setup), we can see where the variable is placed.
Note: Although manual placement works, using distribution strategies can be a more convenient and scalable way to optimize your computation.
If you run this notebook on different backends with and without a GPU you will see different logging. Note that logging device placement must be turned on at the start of the session.
End of explanation
with tf.device('CPU:0'):
a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.Variable([[1.0, 2.0, 3.0]])
with tf.device('GPU:0'):
# Element-wise multiply
k = a * b
print(k)
Explanation: It's possible to set the location of a variable or tensor on one device and do the computation on another device. This will introduce delay, as data needs to be copied between the devices.
You might do this, however, if you had multiple GPU workers but only want one copy of the variables.
End of explanation |
7,955 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 4 - Tensorflow ANN for regression
In this lab we will use Tensorflow to build an Artificial Neuron Network (ANN) for a regression task.
As opposed to the low-level implementation from the previous week, here we will use Tensorflow to automate many of the computation tasks in the neural network. Tensorflow is a higher-level open-source machine learning library released by Google last year which is made specifically to optimize and speed up the development and training of neural networks.
At its core, Tensorflow is very similar to numpy and other numerical computation libraries. Like numpy, it's main function is to do very fast computation on multi-dimensional datasets (such as computing the dot product between a vector of input values and a matrix of values representing the weights in a fully connected network). While numpy refers to such multi-dimensional data sets as 'arrays', Tensorflow calls them 'tensors', but fundamentally they are the same thing. The two main advantages of Tensorflow over custom low-level solutions are
Step1: Next, let's import the Boston housing prices dataset. This is included with the scikit-learn library, so we can import it directly from there. The data will come in as two numpy arrays, one with all the features, and one with the target (price). We will use pandas to convert this data to a DataFrame so we can visualize it. We will then print the first 5 entries of the dataset to see the kind of data we will be working with.
Step2: You can see that the dataset contains only continuous features, which we can feed directly into the neural network for training. The target is also a continuous variable, so we can use regression to try to predict the exact value of the target. You can see more information about this dataset by printing the 'DESCR' object stored in the data set.
Step3: Next, we will do some exploratory data visualization to get a general sense of the data and how the different features are related to each other and to the target we will try to predict. First, let's plot the correlations between each feature. Larger positive or negative correlation values indicate that the two features are related (large positive or negative correlation), while values closer to zero indicate that the features are not related (no correlation).
Step4: We can get a more detailed picture of the relationship between any two variables in the dataset by using seaborn's jointplot function and passing it two features of our data. This will show a single-dimension histogram distribution for each feature, as well as a two-dimension density scatter plot for how the two features are related. From the correlation matrix above, we can see that the RM feature has a strong positive correlation to the target, while the LSTAT feature has a strong negative correlation to the target. Let's create jointplots for both sets of features to see how they relate in more detail
Step5: As expected, the plots show a positive relationship between the RM feature and the target, and a negative relationship between the LSTAT feature and the target.
This type of exploratory visualization is not strictly necessary for using machine learning, but it does help to formulate your solution, and to troubleshoot your implementation incase you are not getting the results you want. For example, if you find that two features have a strong correlation with each other, you might want to include only one of them to speed up the training process. Similarly, you may want to exclude features that show little correlation to the target, since they have little influence over its value.
Now that we know a little bit about the data, let's prepare it for training with our neural network. We will follow a process similar to the previous lab
Step6: Next, we set up some variables that we will use to define our model. The first group are helper variables taken from the dataset which specify the number of samples in our training set, the number of features, and the number of outputs. The second group are the actual hyper-parameters which define how the model is structured and how it performs. In this case we will be building a neural network with two hidden layers, and the size of each hidden layer is controlled by a hyper-parameter. The other hyper-parameters include
Step7: Next, we define a few helper functions which will dictate how error will be measured for our model, and how the weights and biases should be defined.
The accuracy() function defines how we want to measure error in a regression problem. The function will take in two lists of values - predictions which represent predicted values, and targets which represent actual target values. In this case we simply compute the absolute difference between the two (the error) and return the average error using numpy's mean() fucntion.
The weight_variable() and bias_variable() functions help create parameter variables for our neural network model, formatted in the proper type for Tensorflow. Both functions take in a shape parameter and return a variable of that shape using the specified initialization. In this case we are using a 'truncated normal' distribution for the weights, and a constant value for the bias. For more information about various ways to initialize parameters in Tensorflow you can consult the documentation
Step8: Now we are ready to build our neural network model in Tensorflow.
Tensorflow operates in a slightly different way than the procedural logic we have been using in Python so far. Instead of telling Tensorflow the exact operations to run line by line, we build the entire neural network within a structure called a Graph. The Graph does several things
Step9: Now that we have specified our model, we are ready to train it. We do this by iteratively calling the model, with each call representing one training step. At each step, we
Step10: Now that the model is trained, let's visualize the training process by plotting the error we achieved in the small training batch, the full training set, and the test set at each epoch. We will also print out the minimum loss we were able to achieve in the test set over all the training steps. | Python Code:
%matplotlib inline
import math
import random
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import load_boston
import numpy as np
import tensorflow as tf
sns.set(style="ticks", color_codes=True)
Explanation: Lab 4 - Tensorflow ANN for regression
In this lab we will use Tensorflow to build an Artificial Neuron Network (ANN) for a regression task.
As opposed to the low-level implementation from the previous week, here we will use Tensorflow to automate many of the computation tasks in the neural network. Tensorflow is a higher-level open-source machine learning library released by Google last year which is made specifically to optimize and speed up the development and training of neural networks.
At its core, Tensorflow is very similar to numpy and other numerical computation libraries. Like numpy, it's main function is to do very fast computation on multi-dimensional datasets (such as computing the dot product between a vector of input values and a matrix of values representing the weights in a fully connected network). While numpy refers to such multi-dimensional data sets as 'arrays', Tensorflow calls them 'tensors', but fundamentally they are the same thing. The two main advantages of Tensorflow over custom low-level solutions are:
While it has a Python interface, much of the low-level computation is implemented in C/C++, making it run much faster than a native Python solution.
Many common aspects of neural networks such as computation of various losses and a variety of modern optimization techniques are implemented as built in methods, reducing their implementation to a single line of code. This also helps in development and testing of various solutions, as you can easily swap in and try various solutions without having to write all the code by hand.
You can get more details about various popular machine learning libraries in this comparison.
To test our basic network, we will use the Boston Housing Dataset, which represents data on 506 houses in Boston across 14 different features. One of the features is the median value of the house in $1000’s. This is a common data set for testing regression performance of machine learning algorithms. All 14 features are continuous values, making them easy to plug directly into a neural network (after normalizing ofcourse!). The common goal is to predict the median house value using the other columns as features.
This lab will conclude with two assignments:
Assignment 1 (at bottom of this notebook) asks you to experiment with various regularization parameters to reduce overfitting and improve the results of the model.
Assignment 2 (in the next notebook) asks you to take our regression problem and convert it to a classification problem.
Let's start by importing some of the libraries we will use for this tutorial:
End of explanation
#load data from scikit-learn library
dataset = load_boston()
#load data as DataFrame
houses = pd.DataFrame(dataset.data, columns=dataset.feature_names)
#add target data to DataFrame
houses['target'] = dataset.target
#print first 5 entries of data
print houses.head()
Explanation: Next, let's import the Boston housing prices dataset. This is included with the scikit-learn library, so we can import it directly from there. The data will come in as two numpy arrays, one with all the features, and one with the target (price). We will use pandas to convert this data to a DataFrame so we can visualize it. We will then print the first 5 entries of the dataset to see the kind of data we will be working with.
End of explanation
print dataset['DESCR']
Explanation: You can see that the dataset contains only continuous features, which we can feed directly into the neural network for training. The target is also a continuous variable, so we can use regression to try to predict the exact value of the target. You can see more information about this dataset by printing the 'DESCR' object stored in the data set.
End of explanation
# Create a datset of correlations between house features
corrmat = houses.corr()
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(9, 6))
# Draw the heatmap using seaborn
sns.set_context("notebook", font_scale=0.7, rc={"lines.linewidth": 1.5})
sns.heatmap(corrmat, annot=True, square=True)
f.tight_layout()
Explanation: Next, we will do some exploratory data visualization to get a general sense of the data and how the different features are related to each other and to the target we will try to predict. First, let's plot the correlations between each feature. Larger positive or negative correlation values indicate that the two features are related (large positive or negative correlation), while values closer to zero indicate that the features are not related (no correlation).
End of explanation
sns.jointplot(houses['target'], houses['RM'], kind='hex')
sns.jointplot(houses['target'], houses['LSTAT'], kind='hex')
Explanation: We can get a more detailed picture of the relationship between any two variables in the dataset by using seaborn's jointplot function and passing it two features of our data. This will show a single-dimension histogram distribution for each feature, as well as a two-dimension density scatter plot for how the two features are related. From the correlation matrix above, we can see that the RM feature has a strong positive correlation to the target, while the LSTAT feature has a strong negative correlation to the target. Let's create jointplots for both sets of features to see how they relate in more detail:
End of explanation
# convert housing data to numpy format
houses_array = houses.as_matrix().astype(float)
# split data into feature and target sets
X = houses_array[:, :-1]
y = houses_array[:, -1]
# normalize the data per feature by dividing by the maximum value in each column
X = X / X.max(axis=0)
# split data into training and test sets
trainingSplit = int(.7 * houses_array.shape[0])
X_train = X[:trainingSplit]
y_train = y[:trainingSplit]
X_test = X[trainingSplit:]
y_test = y[trainingSplit:]
print('Training set', X_train.shape, y_train.shape)
print('Test set', X_test.shape, y_test.shape)
Explanation: As expected, the plots show a positive relationship between the RM feature and the target, and a negative relationship between the LSTAT feature and the target.
This type of exploratory visualization is not strictly necessary for using machine learning, but it does help to formulate your solution, and to troubleshoot your implementation incase you are not getting the results you want. For example, if you find that two features have a strong correlation with each other, you might want to include only one of them to speed up the training process. Similarly, you may want to exclude features that show little correlation to the target, since they have little influence over its value.
Now that we know a little bit about the data, let's prepare it for training with our neural network. We will follow a process similar to the previous lab:
We will first re-split the data into a feature set (X) and a target set (y)
Then we will normalize the feature set so that the values range from 0 to 1
Finally, we will split both data sets into a training and test set.
End of explanation
# helper variables
num_samples = X_train.shape[0]
num_features = X_train.shape[1]
num_outputs = 1
# Hyper-parameters
batch_size = 50
num_hidden_1 = 10
num_hidden_2 = 5
learning_rate = 0.0001
training_epochs = 900
dropout_keep_prob = 0.4# set to no dropout by default
# variable to control the resolution at which the training results are stored
display_step = 1
Explanation: Next, we set up some variables that we will use to define our model. The first group are helper variables taken from the dataset which specify the number of samples in our training set, the number of features, and the number of outputs. The second group are the actual hyper-parameters which define how the model is structured and how it performs. In this case we will be building a neural network with two hidden layers, and the size of each hidden layer is controlled by a hyper-parameter. The other hyper-parameters include:
batch size, which sets how many training samples are used at a time
learning rate which controls how quickly the gradient descent algorithm works
training epochs which sets how many rounds of training occurs
dropout keep probability, a regularization technique which controls how many neurons are 'dropped' randomly during each training step (note in Tensorflow this is specified as the 'keep probability' from 0 to 1, with 0 representing all neurons dropped, and 1 representing all neurons kept). You can read more about dropout here.
End of explanation
def accuracy(predictions, targets):
error = np.absolute(predictions.reshape(-1) - targets)
return np.mean(error)
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
Explanation: Next, we define a few helper functions which will dictate how error will be measured for our model, and how the weights and biases should be defined.
The accuracy() function defines how we want to measure error in a regression problem. The function will take in two lists of values - predictions which represent predicted values, and targets which represent actual target values. In this case we simply compute the absolute difference between the two (the error) and return the average error using numpy's mean() fucntion.
The weight_variable() and bias_variable() functions help create parameter variables for our neural network model, formatted in the proper type for Tensorflow. Both functions take in a shape parameter and return a variable of that shape using the specified initialization. In this case we are using a 'truncated normal' distribution for the weights, and a constant value for the bias. For more information about various ways to initialize parameters in Tensorflow you can consult the documentation
End of explanation
'''First we create a variable to store our graph'''
graph = tf.Graph()
'''Next we build our neural network within this graph variable'''
with graph.as_default():
'''Our training data will come in as x feature data and
y target data. We need to create tensorflow placeholders
to capture this data as it comes in'''
x = tf.placeholder(tf.float32, shape=(None, num_features))
_y = tf.placeholder(tf.float32, shape=(None))
'''Another placeholder stores the hyperparameter
that controls dropout'''
keep_prob = tf.placeholder(tf.float32)
'''Finally, we convert the test and train feature data sets
to tensorflow constants so we can use them to generate
predictions on both data sets'''
tf_X_test = tf.constant(X_test, dtype=tf.float32)
tf_X_train = tf.constant(X_train, dtype=tf.float32)
'''Next we create the parameter variables for the model.
Each layer of the neural network needs it's own weight
and bias variables which will be tuned during training.
The sizes of the parameter variables are determined by
the number of neurons in each layer.'''
W_fc1 = weight_variable([num_features, num_hidden_1])
b_fc1 = bias_variable([num_hidden_1])
W_fc2 = weight_variable([num_hidden_1, num_hidden_2])
b_fc2 = bias_variable([num_hidden_2])
W_fc3 = weight_variable([num_hidden_2, num_outputs])
b_fc3 = bias_variable([num_outputs])
'''Next, we define the forward computation of the model.
We do this by defining a function model() which takes in
a set of input data, and performs computations through
the network until it generates the output.'''
def model(data, keep):
# computing first hidden layer from input, using relu activation function
fc1 = tf.nn.sigmoid(tf.matmul(data, W_fc1) + b_fc1)
# adding dropout to first hidden layer
fc1_drop = tf.nn.dropout(fc1, keep)
# computing second hidden layer from first hidden layer, using relu activation function
fc2 = tf.nn.sigmoid(tf.matmul(fc1_drop, W_fc2) + b_fc2)
# adding dropout to second hidden layer
fc2_drop = tf.nn.dropout(fc2, keep)
# computing output layer from second hidden layer
# the output is a single neuron which is directly interpreted as the prediction of the target value
fc3 = tf.matmul(fc2_drop, W_fc3) + b_fc3
# the output is returned from the function
return fc3
'''Next we define a few calls to the model() function which
will return predictions for the current batch input data (x),
as well as the entire test and train feature set'''
prediction = model(x, keep_prob)
test_prediction = model(tf_X_test, 1.0)
train_prediction = model(tf_X_train, 1.0)
'''Finally, we define the loss and optimization functions
which control how the model is trained.
For the loss we will use the basic mean square error (MSE) function,
which tries to minimize the MSE between the predicted values and the
real values (_y) of the input dataset.
For the optimization function we will use basic Gradient Descent (SGD)
which will minimize the loss using the specified learning rate.'''
loss = tf.reduce_mean(tf.square(tf.sub(prediction, _y)))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
'''We also create a saver variable which will allow us to
save our trained model for later use'''
saver = tf.train.Saver()
Explanation: Now we are ready to build our neural network model in Tensorflow.
Tensorflow operates in a slightly different way than the procedural logic we have been using in Python so far. Instead of telling Tensorflow the exact operations to run line by line, we build the entire neural network within a structure called a Graph. The Graph does several things:
describes the architecture of the network, including how many layers it has and how many neurons are in each layer
initializes all the parameters of the network
describes the 'forward' calculation of the network, or how input data is passed through the network layer by layer until it reaches the result
defines the loss function which describes how well the model is performing
specifies the optimization function which dictates how the parameters are tuned in order to minimize the loss
Once this graph is defined, we can work with it by 'executing' it on sets of training data and 'calling' different parts of the graph to get back results. Every time the graph is executed, Tensorflow will only do the minimum calculations necessary to generate the requested results. This makes Tensorflow very efficient, and allows us to structure very complex models while only testing and using certain portions at a time. In programming language theory, this type of programming is called 'lazy evaluation'.
End of explanation
# create an array to store the results of the optimization at each epoch
results = []
'''First we open a session of Tensorflow using our graph as the base.
While this session is active all the parameter values will be stored,
and each step of training will be using the same model.'''
with tf.Session(graph=graph) as session:
'''After we start a new session we first need to
initialize the values of all the variables.'''
tf.initialize_all_variables().run()
print('Initialized')
'''Now we iterate through each training epoch based on the hyper-parameter set above.
Each epoch represents a single pass through all the training data.
The total number of training steps is determined by the number of epochs and
the size of mini-batches relative to the size of the entire training set.'''
for epoch in range(training_epochs):
'''At the beginning of each epoch, we create a set of shuffled indexes
so that we are using the training data in a different order each time'''
indexes = range(num_samples)
random.shuffle(indexes)
'''Next we step through each mini-batch in the training set'''
for step in range(int(math.floor(num_samples/float(batch_size)))):
offset = step * batch_size
'''We subset the feature and target training sets to create each mini-batch'''
batch_data = X_train[indexes[offset:(offset + batch_size)]]
batch_labels = y_train[indexes[offset:(offset + batch_size)]]
'''Then, we create a 'feed dictionary' that will feed this data,
along with any other hyper-parameters such as the dropout probability,
to the model'''
feed_dict = {x : batch_data, _y : batch_labels, keep_prob: dropout_keep_prob}
'''Finally, we call the session's run() function, which will feed in
the current training data, and execute portions of the graph as necessary
to return the data we ask for.
The first argument of the run() function is a list specifying the
model variables we want it to compute and return from the function.
The most important is 'optimizer' which triggers all calculations necessary
to perform one training step. We also include 'loss' and 'prediction'
because we want these as ouputs from the function so we can keep
track of the training process.
The second argument specifies the feed dictionary that contains
all the data we want to pass into the model at each training step.'''
_, l, p = session.run([optimizer, loss, prediction], feed_dict=feed_dict)
'''At the end of each epoch, we will calcule the error of predictions
on the full training and test data set. We will then store the epoch number,
along with the mini-batch, training, and test accuracies to the 'results' array
so we can visualize the training process later. How often we save the data to
this array is specified by the display_step variable created above'''
if (epoch % display_step == 0):
batch_acc = accuracy(p, batch_labels)
train_acc = accuracy(train_prediction.eval(session=session), y_train)
test_acc = accuracy(test_prediction.eval(session=session), y_test)
results.append([epoch, batch_acc, train_acc, test_acc])
'''Once training is complete, we will save the trained model so that we can use it later'''
save_path = saver.save(session, "model_houses.ckpt")
print("Model saved in file: %s" % save_path)
Explanation: Now that we have specified our model, we are ready to train it. We do this by iteratively calling the model, with each call representing one training step. At each step, we:
Feed in a new set of training data. Remember that with SGD we only have to feed in a small set of data at a time. The size of each batch of training data is determined by the 'batch_size' hyper-parameter specified above.
Call the optimizer function by asking tensorflow to return the model's 'optimizer' variable. This starts a chain reaction in Tensorflow that executes all the computation necessary to train the model. The optimizer function itself will compute the gradients in the model and modify the weight and bias parameters in a way that minimizes the overall loss. Because it needs this loss to compute the gradients, it will also trigger the loss function, which will in turn trigger the model to compute predictions based on the input data. This sort of chain reaction is at the root of the 'lazy evaluation' model used by Tensorflow.
End of explanation
df = pd.DataFrame(data=results, columns = ["epoch", "batch_acc", "train_acc", "test_acc"])
df.set_index("epoch", drop=True, inplace=True)
fig, ax = plt.subplots(1, 1, figsize=(10, 4))
ax.plot(df)
ax.set(xlabel='Epoch',
ylabel='Error',
title='Training result')
ax.legend(df.columns, loc=1)
print "Minimum test loss:", np.min(df["test_acc"])
Explanation: Now that the model is trained, let's visualize the training process by plotting the error we achieved in the small training batch, the full training set, and the test set at each epoch. We will also print out the minimum loss we were able to achieve in the test set over all the training steps.
End of explanation |
7,956 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading necessary library
Step1: Loading data
deleting irrelevant features
Step2: encoding catagorical features
Step3: splitting data into test and train
Step4: seperating features and class in both test and train sets
Step5: getting best parameters
do not run this section as the best set of parameters is already found
Step6: creating model with best parameter combination and reporting metrics
Step7: creating a test file with predicted results to visualize | Python Code:
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn import metrics
from sklearn.metrics import accuracy_score
from sklearn.ensemble import AdaBoostClassifier
from sklearn.neighbors import KNeighborsClassifier
import xgboost as xgb
import numpy as np
Explanation: Loading necessary library
End of explanation
kobe = pd.read_csv('data.csv', sep=',')
kobe= kobe[np.isfinite(kobe['shot_made_flag'])]
del kobe['lat']
del kobe['lon']
del kobe['game_id']
del kobe['team_id']
del kobe['team_name']
kobe_2 = pd.read_csv('data.csv', sep=',')
kobe_2= kobe_2[np.isfinite(kobe_2['shot_made_flag'])]
del kobe_2['lat']
del kobe_2['lon']
del kobe_2['game_id']
del kobe_2['team_id']
del kobe_2['team_name']
Explanation: Loading data
deleting irrelevant features
End of explanation
mt_up = preprocessing.LabelEncoder()
kobe.matchup = mt_up.fit_transform(kobe.matchup )
#kobe_2.matchup = mt_up.fit_transform(kobe.matchup )
opp = preprocessing.LabelEncoder()
kobe.opponent = opp.fit_transform(kobe.opponent )
#kobe_2.opponent = opp.fit_transform(kobe.opponent )
dt = preprocessing.LabelEncoder()
kobe.game_date = dt.fit_transform(kobe.game_date )
#kobe_2.game_date = dt.fit_transform(kobe.game_date )
at = preprocessing.LabelEncoder()
kobe.action_type = at.fit_transform(kobe.action_type )
#kobe_2.action_type = at.fit_transform(kobe.action_type )
cst = preprocessing.LabelEncoder()
kobe.combined_shot_type = cst.fit_transform(kobe.combined_shot_type )
#kobe_2.combined_shot_type = cst.fit_transform(kobe.combined_shot_type )
seson = preprocessing.LabelEncoder()
kobe.season = seson.fit_transform(kobe.season )
#kobe_2.season = seson.fit_transform(kobe.season )
st = preprocessing.LabelEncoder()
kobe.shot_type = st.fit_transform(kobe.shot_type )
#kobe_2.shot_type = st.fit_transform(kobe.shot_type )
sza = preprocessing.LabelEncoder()
kobe.shot_zone_area = sza.fit_transform(kobe.shot_zone_area )
#kobe_2.shot_zone_area = sza.fit_transform(kobe.shot_zone_area )
szb = preprocessing.LabelEncoder()
kobe.shot_zone_basic = szb.fit_transform(kobe.shot_zone_basic )
#kobe_2.shot_zone_basic = szb.fit_transform(kobe.shot_zone_basic )
szr = preprocessing.LabelEncoder()
kobe.shot_zone_range = szr.fit_transform(kobe.shot_zone_range )
#kobe_2.shot_zone_range = szr.fit_transform(kobe.shot_zone_range )
Explanation: encoding catagorical features
End of explanation
from sklearn.cross_validation import train_test_split
# Generate the training set. Set random_state to be able to replicate results.
train = kobe.sample(frac=0.6, random_state=1)
train_2 = kobe_2.sample(frac=0.6, random_state=1)
# Select anything not in the training set and put it in the testing set.
test = kobe.loc[~kobe.index.isin(train.index)]
test_2 = kobe_2.loc[~kobe_2.index.isin(train_2.index)]
Explanation: splitting data into test and train
End of explanation
columns = kobe.columns.tolist()
columns = [c for c in columns if c not in ["shot_made_flag","team_id","team_name"]]
kobe_train_x =train[columns]
kobe_test_x =test[columns]
kobe_train_y=train['shot_made_flag']
kobe_test_y=test['shot_made_flag']
print(kobe_train_x.shape)
print(kobe_test_x.shape)
print(kobe_train_y.shape)
print(kobe_test_y.shape)
Explanation: seperating features and class in both test and train sets
End of explanation
def optimization(depth, n_est,l_r):
maxacc=0
best_depth=0
best_n_est=0
best_l_r=0
for i in range(1,depth):
for j in n_est:
for k in l_r:
gbm = xgb.XGBClassifier(max_depth=i, n_estimators=j, learning_rate=k).fit(kobe_train_x, kobe_train_y)
predicted = gbm.predict(kobe_test_x)
key=str(i)+"_"+str(j)+"_"+str(k)
accu=accuracy_score(kobe_test_y, predicted)
if(accu>maxacc):
maxacc=accu
best_depth=i
best_n_est=j
best_l_r=k
print(maxkey+" "+str(maxacc))
return(best_depth,best_n_est,best_l_r)
n_est=[5,10,20,50,100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000]
depth=10
l_r = [0.0001, 0.001, 0.01,0.05, 0.1, 0.2, 0.3]
best_depth,best_n_est,best_l_r=optimization(depth,n_est,l_r)
Explanation: getting best parameters
do not run this section as the best set of parameters is already found
End of explanation
#hard coded the best features
gbm = xgb.XGBClassifier(max_depth=4, n_estimators=600, learning_rate=0.01).fit(kobe_train_x, kobe_train_y)
predicted = gbm.predict(kobe_test_x)
# summarize the fit of the model
print(metrics.classification_report(kobe_test_y, predicted))
print("Confusion Matrix")
print(metrics.confusion_matrix(kobe_test_y, predicted))
accuracy=accuracy_score(kobe_test_y, predicted)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
Explanation: creating model with best parameter combination and reporting metrics
End of explanation
test_2['predicted']=predicted
test_2.to_csv(path_or_buf='test_with_predictions.csv', sep=',')
test_2.head(10)
Explanation: creating a test file with predicted results to visualize
End of explanation |
7,957 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prediction Model
Course
Step1: Step 1
Step2: Step 2
Step3: Step 3
Step4: Our output/classification label is diagnosis(M(1)/B(0)), which is nominal categorical data.
The ratios between Benign and Malignant outputs in train and test
are pretty similar to what we had in the full data.
Step 4
Step5: Step 5
Step6: Step 6. Model Predictions on Training Dataset
Apply your model to input (scaled) columns of Training dataset to obtain the predicted output for Training dataset. If your model is regression then plot actual output versus predicted output column of Training dataset. If your model is classification then generate confusion matrix on actual and predicted columns of Training dataset.
Hint
Step7: Step 7. Model Predictions on Test Dataset
Apply your model to input (scaled) columns of Test dataset to obtain the predicted output for Test dataset. If your model is regression then plot actual output versus predicted output column of Test dataset. If your model is classification then generate confusion matrix on actual and predicted columns of Test dataset.
Hint
Step8: Step 8. Model Performance
Using one of the error (evaluation) metrics (classification or regression), calculate the performance of the model on Training set and Test set. Compare the performance of the model on Training and Test set. Which one (Training or Testing performance) is better, is there an overfitting case, why ?. Would you deploy (Productionize) this model for using in actual usage in your business system? why ?
Classification Metrics
Step9: As it seems clear in the plot we created, the Test data is better than the Train data. Which is not expected. I do not see the traces of overfitting since the test data is also performing well.
But there is also another chance that Test data is also overfitting... ??
Naive bayes on this particular data set works really good. It might be good for fast prototyping and usage.
Step 9. Update the Model
Go back to Step5, and choose different values of the model parameters and re-train the model. Repeat Steps
Step10: Extra calibration which add one more layer above the GaussianNB() works better than no calibration. Isotonic and Sigmoid calibrations are performed better than the initial no calibration version.
Step 10. Change the Error Metric
Choose another error metric other than you used in Step 8 and evaluate the performance of the model on Training and Test dataset by generating the accuracy of the model based on the new metric. Compare the results and explain which error metric is better for your modeling and why? | Python Code:
import pandas as pd
# Read CSV data into df
df = pd.read_csv('./theAwesome_PredModel.csv')
# delete id column no need
df.drop('id',axis=1,inplace=True)
# delete unnamed colum at the end
df.drop('Unnamed: 32',axis=1,inplace=True)
df.head()
# Learn the unique values in diagnosis column
df.diagnosis.unique()
# M: Malign (Yes Cancer)
# B: Benign (No Cancer)
# I can also map M and B as 1 and 0 for more numerical
# approach
df['diagnosis'] = df['diagnosis'].map({'M':1,'B':0})
Explanation: Prediction Model
Course: Data Mining
Name: Enes Kemal Ergin
Dataset from Breast Cancer UCI Machine Learning Repo
Attribute Information:
ID number
Diagnosis (M = malignant, B = benign)
3-32: Ten real-valued features are computed for each cell nucleus:
radius (mean of distances from center to points on the perimeter)
texture (standard deviation of gray-scale values)
perimeter
area
smoothness (local variation in radius lengths)
compactness (perimeter^2 / area - 1.0)
concavity (severity of concave portions of the contour)
concave points (number of concave portions of the contour)
symmetry
fractal dimension ("coastline approximation" - 1)
The mean, standard error and "worst" or largest (mean of the three
largest values) of these features were computed for each image,
resulting in 30 features. For instance, field 3 is Mean Radius, field
13 is Radius SE, field 23 is Worst Radius.
All feature values are recoded with four significant digits.
Missing attribute values: none
Class distribution: 357 benign, 212 malignant
Step 0: Data Preparation and Cleaning
End of explanation
df.info()
df.describe()
Explanation: Step 1: Data Information and Descriptive Statistics
Generate the information about your dataset: number of columns and rows, names and data types of the columns, memory usage of the dataset.
Hint: Pandas data frame info() function.
Generate descriptive statistics of all columns (input and output) of your dataset. Descriptive statistics for numerical columns include: count, mean, std, min, 25 percentile (Q1), 50 percentile (Q2, median), 75 percentile (Q3), max values of the columns. For categorical columns, determine distinct values and their frequency in each categorical column.
Hint: Pandas, data frame describe() function.
End of explanation
df["diagnosis"].value_counts(df["diagnosis"].unique()[0])
# Splitting train and test data
# .7 and .3
import numpy as np # Linear algebra and numerical apps
msk = np.random.rand(len(df)) < 0.7
train_df = df[msk]
test_df = df[~msk]
train_df.describe()
Explanation: Step 2: Train Test Split
Split your data into Training and Test data set by randomly selecting; use 70% for training and 30 % for testing. Generate descriptive statistics of all columns (input and output) of Training and Test datasets. Review the descriptive statistics of input output columns in Train, Test and original Full (before the splitting operation) datasets and compare them to each other. Are they similar or not? Do you think Train and Test dataset are representative of the Full datasets ? why ?
Hint: Scikit learn, data train_test_split(), stratified function.
End of explanation
print(train_df["diagnosis"].value_counts(train_df["diagnosis"].unique()[0]))
print(len(train_df))
train_df.describe()
print(test_df["diagnosis"].value_counts(test_df["diagnosis"].unique()[0]))
print(len(test_df))
test_df.describe()
Explanation: Step 3: Analysis of the Output Column
Analyze the output columns in Train and Test dataset. If the output column is numerical then calculate the IQR (inter quartile range, Q3-Q1) and Range (difference between max and min value). If your output column is categorical then determine if the column is nominal or ordinal, why?. Is there a class imbalance problem? (check if there is big difference between the number of distinct values in your categorical output column)
End of explanation
# I am going to apply min-max scaling for my data.
from sklearn import preprocessing
# Fitting the minmax scaled version for training data
minmax_scale = preprocessing.MinMaxScaler().fit(train_df.iloc[:, 1:])
# Now actually scale train and test data
train_df.iloc[:, 1:] = minmax_scale.transform(train_df.iloc[:, 1:])
test_df.iloc[:, 1:] = minmax_scale.transform(test_df.iloc[:, 1:])
train_df.head()
test_df.head()
Explanation: Our output/classification label is diagnosis(M(1)/B(0)), which is nominal categorical data.
The ratios between Benign and Malignant outputs in train and test
are pretty similar to what we had in the full data.
Step 4: Scale Training and Test Dataset
Using one of the scaling method (max, min-max, standard or robust), create a scaler object and scale the numerical input columns of the Training dataset. Using the same scaler object, scale the numerical input columns of the Test set. Generate the descriptive statistics of the scaled input columns of Training and Test set.
If some of the input columns are categorical then convert them to binary columns using one-hotencoder() function (scikit learn) or dummy() function (Pandas data frame).
Hint: http://scikit-learn.org/stable/modules/preprocessing.html#preprocessing
End of explanation
# Input and Output
inp_train = train_df.iloc[:, 1:]
out_train = train_df["diagnosis"]
inp_test = test_df.iloc[:, 1:]
out_test = test_df["diagnosis"]
# Naive Bayes:
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import cross_val_score
nb_model = GaussianNB()
nb_model.fit(inp_train, out_train)
# Cross validation score of my model
nb_model_scores = cross_val_score(nb_model, inp_train, out_train, cv=10, scoring='accuracy')
print(nb_model_scores)
Explanation: Step 5: Build Predictive Model
Using one of the methods (K-Nearest Neighbor, Naïve Bayes, Neural Network, Support Vector Machines, Decision Tree), build your predictive model using the scaled input columns of Training set. You can use any value for the model parameters, or use the default values. In building your model, use k-fold crossvalidation.
Hint:
- http://scikit-learn.org/stable/supervised_learning.html#supervised-learning ,
- http://scikit-learn.org/stable/modules/cross_validation.html
End of explanation
# importing libraries for plotting
# Importing library for confusion matrix
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='darkgrid')
# train prediction for train data
out_train_pred = nb_model.predict(inp_train)
# Compute confusion matrix for prediction of train
cm = confusion_matrix(out_train, out_train_pred)
print(cm)
# Show confusion matrix in a separate window
sns.heatmap(cm)
plt.title('Confusion matrix')
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
Explanation: Step 6. Model Predictions on Training Dataset
Apply your model to input (scaled) columns of Training dataset to obtain the predicted output for Training dataset. If your model is regression then plot actual output versus predicted output column of Training dataset. If your model is classification then generate confusion matrix on actual and predicted columns of Training dataset.
Hint: Matplotlip, Seaborn, Bokeh scatter(), plot() functions
- http://scikit-learn.org/0.15/auto_examples/plot_confusion_matrix.html
- http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
End of explanation
# train prediction for train data
out_test_pred = nb_model.predict(inp_test)
# Compute confusion matrix for prediction of train
cm = confusion_matrix(out_test, out_test_pred)
print(cm)
# Show confusion matrix in a separate window
sns.heatmap(cm)
plt.title('Confusion matrix')
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
Explanation: Step 7. Model Predictions on Test Dataset
Apply your model to input (scaled) columns of Test dataset to obtain the predicted output for Test dataset. If your model is regression then plot actual output versus predicted output column of Test dataset. If your model is classification then generate confusion matrix on actual and predicted columns of Test dataset.
Hint: Matplotlip, Seaborn, Bokeh scatter(), plot() functions
- http://scikit-learn.org/0.15/auto_examples/plot_confusion_matrix.html
- http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
End of explanation
# I would like to use ROC
# Area under ROC Curve (or AUC for short) is
# a performance metric for binary classification problems.
from sklearn.metrics import roc_curve
# ROC curve for train data
fpr,tpr,thresholds = roc_curve(out_train, out_train_pred)
# plot the curve
plt.plot(fpr, tpr, label="Train Data")
# ROC curve for test data
fpr, tpr, thresholds = roc_curve(out_test, out_test_pred)
# Plotting the curves
plt.plot(fpr, tpr, label="Test Data")
plt.xlim([0.0,1.0])
plt.ylim([0.0,1.0])
plt.title('ROC curve for Cancer classifer')
plt.xlabel('False positive rate (1-specificity)')
plt.ylabel('True positive rate (sensitivity)')
plt.legend(loc=4,)
plt.show()
Explanation: Step 8. Model Performance
Using one of the error (evaluation) metrics (classification or regression), calculate the performance of the model on Training set and Test set. Compare the performance of the model on Training and Test set. Which one (Training or Testing performance) is better, is there an overfitting case, why ?. Would you deploy (Productionize) this model for using in actual usage in your business system? why ?
Classification Metrics: Accuracy, Precision, Recall, F-score, Recall, AUC, ROC etc Regression Metrics: RMSE, MSE, MAE, R2 etc
http://scikit-learn.org/stable/model_selection.html#model-selection
http://scikit-learn.org/stable/modules/model_evaluation.html#classification-report
End of explanation
# For Training Data:
# Let's remember we have GaussianNB model with
# no calibration called out_train_pred
from sklearn.calibration import CalibratedClassifierCV
# Gaussian Naive-Bayes with isotonic calibration
nb_model_isotonic = CalibratedClassifierCV(nb_model, cv=2, method='isotonic')
nb_model_isotonic.fit(inp_train, out_train)
out_train_isotonic = nb_model_isotonic.predict_proba(inp_train)[:, 1]
out_test_isotonic = nb_model_isotonic.predict_proba(inp_test)[:, 1]
# Gaussian Naive-Bayes with sigmoid calibration
nb_model_sigmoid = CalibratedClassifierCV(nb_model, cv=2, method='sigmoid')
nb_model_sigmoid.fit(inp_train, out_train)
out_train_sigmoid = nb_model_sigmoid.predict_proba(inp_train)[:, 1]
out_test_sigmoid = nb_model_sigmoid.predict_proba(inp_test)[:, 1]
## Plotting the comparison of train Data roc_curves
# ROC curve for train data no calibration
fpr,tpr,thresholds = roc_curve(out_train, out_train_pred)
# plot the curve
plt.plot(fpr, tpr, label="No Cal - Train Data")
# ROC curve for train data isotonic calibration
fpr,tpr,thresholds = roc_curve(out_train, out_train_isotonic)
# plot the curve
plt.plot(fpr, tpr, label="Isotonic - Train Data")
# ROC curve for train data sigmoid calibration
fpr,tpr,thresholds = roc_curve(out_train, out_train_sigmoid)
# plot the curve
plt.plot(fpr, tpr, label="Sigmoid - Train Data")
plt.xlim([-0.05,1.05])
plt.ylim([-0.05,1.05])
plt.title('ROC curve of Train Data with Calibrations')
plt.xlabel('False positive rate (1-specificity)')
plt.ylabel('True positive rate (sensitivity)')
plt.legend(loc=4,)
plt.show()
# ROC curve for test data no calibration
fpr, tpr, thresholds = roc_curve(out_test, out_test_pred)
# Plotting the curves
plt.plot(fpr, tpr, label="No Cal - Test Data")
# ROC curve for test data isotonic calibration
fpr,tpr,thresholds = roc_curve(out_test, out_test_isotonic)
# plot the curve
plt.plot(fpr, tpr, label="Isotonic - Test Data")
# ROC curve for test data sigmoid calibration
fpr,tpr,thresholds = roc_curve(out_test, out_test_sigmoid)
# plot the curve
plt.plot(fpr, tpr, label="Sigmoid - Test Data")
plt.xlim([-0.05,1.05])
plt.ylim([-0.05,1.05])
plt.title('ROC curve of Test Data with Calibrations')
plt.xlabel('False positive rate (1-specificity)')
plt.ylabel('True positive rate (sensitivity)')
plt.legend(loc=4,)
plt.show()
Explanation: As it seems clear in the plot we created, the Test data is better than the Train data. Which is not expected. I do not see the traces of overfitting since the test data is also performing well.
But there is also another chance that Test data is also overfitting... ??
Naive bayes on this particular data set works really good. It might be good for fast prototyping and usage.
Step 9. Update the Model
Go back to Step5, and choose different values of the model parameters and re-train the model. Repeat Steps: 6 and 7. Using the same error metric, generate the accuracy of the model on Training and Test dataset. Did you get a better performance on Training or Test set? Explain why the new model performs better or worse than the former model.
Let's try to calibrate the GaussianNB(); I will be using isotonic, sigmoid calibration for Gaussian Naive Bayes:
End of explanation
# Checking the error metric to Brier scores
from sklearn.metrics import brier_score_loss
# Checking for only test data predictions
print("Brier scores: (the smaller the better)")
mdl_score = brier_score_loss(out_test, out_test_pred)
print("No calibration: %1.3f" % mdl_score)
mdl_isotonic_score = brier_score_loss(out_test, out_test_isotonic)
print("With isotonic calibration: %1.3f" % mdl_isotonic_score)
mdl_sigmoid_score = brier_score_loss(out_test, out_test_sigmoid)
print("With sigmoid calibration: %1.3f" % mdl_sigmoid_score)
# Applying other metrics
from sklearn import metrics
print("Printing the different metric results for Not calibrated test data")
print("-"*60)
print("Precision score: %1.3f" %
metrics.precision_score(out_test, out_test_pred))
print("Recall score on: %1.3f" %
metrics.recall_score(out_test, out_test_pred))
print("F1 score on: %1.3f" %
metrics.f1_score(out_test, out_test_pred) )
print("Fbeta score with b=0.5 on: %1.3f" %
metrics.fbeta_score(out_test, out_test_pred, beta=0.5))
print("Fbeta score with b=1.0 on: %1.3f" %
metrics.fbeta_score(out_test, out_test_pred, beta=1))
print("Fbeta score with b=2.0 on: %1.3f" %
metrics.fbeta_score(out_test, out_test_pred, beta=2))
Explanation: Extra calibration which add one more layer above the GaussianNB() works better than no calibration. Isotonic and Sigmoid calibrations are performed better than the initial no calibration version.
Step 10. Change the Error Metric
Choose another error metric other than you used in Step 8 and evaluate the performance of the model on Training and Test dataset by generating the accuracy of the model based on the new metric. Compare the results and explain which error metric is better for your modeling and why?
End of explanation |
7,958 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overview of Subdomains
Subdomains are a key feature of OpenPNM, but the can be a source of confusion. First, let's understand what subdomains are and why they are useful. The simplest scenario is a porous materials with 2 distince layers, each with their own pore size distribution. In OpenPNM you can handle this by creating two separate Geometry objects, with each assigned to one of the layers. Each Geometry object can then compute pore size distributions independently from their own different statistical distributions, and store the values corresponding the pores in its layer. A subdomain is thus a selection of pores (and/or throats) that are related to each other but distinct from the rest of the network. Geometry objects thus define subdomains by the pores and/or throats to which they are applied or assigned.
One of the repercussion of supporing subdomains at the deepest possible layer in OpenPNM is that all users must deal with them, regardelss of whether they are actually using the feature. In other words, even materials with one domain must also define Geometry that defines a single subdomain.
This notebook explores how subdomains work in OpenPNM.
Step1: Create a simple 2D cubic network for easy visualization
Step2: Label the pores on the left and right to indicate that the Network has two subdomains
Step3: The Preferred Way to Work with Subdomains
Create two Geometry objects, with one assigned to each set of pores (i.e. 'layer1' and 'layer2'). Let's also assign all the throats to geo1.
Step4: The "preferred" way to create Physics objects is to assign them to a specific Phase AND Geometry upon instantiation
Step5: The project has a useful feature for studying the associations between Geometry, Phase, and Physics objects called the grid.
Step6: When creating Physics objects as done above, all the associations between which pores and throats belong to each Physics is taken care of automatically. Essentially, all the pores/throats of geo1 are assigned to phys1 and simlarly all the pores/throats of geo2 are assigned to phys2. However, it is possible to make these assigments manually post-instantiation as will be demonstrated below, but first let's talk about how these associations are tracked by OpenPNM. When a Geometry object is created, two label arrays are added to the Network with True indicating the locations where that Geometry applies. Let's see this by printing the Network
Step7: As can be seen, there is a label array called 'pore.geo_01' that is True in 8 locations. We can see which locations using np.where
Step8: And similarly, for geo2
Step9: These values are the locations in each array where True was found. Note that they correspond to the pore locations used when creating geo1 and geo2.
NOTE
Step10: Next, create two Physics objects, but don't assign them to a Phase or a Geometry object. Note that a warning is issued that the instantiation was not able to assign the Physics to any pores or throats. We'll add these associations manually below
Step11: Physics objects have a phase attribute that points to the Phase with which it is currently associated. Because we did not provide one when initializing phys1 and phys2 this will raise an exception
Step12: We can assign a air to phys1 as follows, after which we can retrieve it using the phase attribute
Step13: Physics objects also have geometry attribute which acts just like phase. We have not yet associated phys1 with any locations so it will raise an error
Step14: We can assign a Geometry in the same manner as we did for Phase above. This will connect phys1 with the locations corresponding to geo1
Step15: This shows that phys_02 resides in the ? column indicating that it is not associated with a phase, and it resides in the ? row indicating it is not associated with a geometry either. Let's fix this below.
Step16: Now we can see that phys_02 is associated with geo_02 and air. We can also see there are some locations, either pores or throats, that are not yet associated with a geometry object, as indicated by --- in the first column. This is because we did not assign any throats to a Geometry yet. Let's fix this below
Step17: Note that we only assigned 12 throats to geo3, but there were 24 throats in the network. We can either create yet another Geometry, or we can use the set_locations method
Step18: Now we can see that all locations are assigned to a Geometry, indicated by the lack of any rows in the first column containing ---. We still need to create a Physics object for these throats.
Again, let's not assign it to the throats during instantiation and do it manually afterward. But we will include a Phase
Step19: Because we included a Phase, this new Physics is in the appropriate column, but is in a ? row since it is not yet associated with a Geometry. Instead of using the geometry attribute as we did above, let's use the set_geometry method, which is actually called behind the scenes when using the geometry attribute
Step20: Now we can print the project's grid and see that everything is looking good | Python Code:
import openpnm as op
import numpy as np
import matplotlib.pyplot as plt
Explanation: Overview of Subdomains
Subdomains are a key feature of OpenPNM, but the can be a source of confusion. First, let's understand what subdomains are and why they are useful. The simplest scenario is a porous materials with 2 distince layers, each with their own pore size distribution. In OpenPNM you can handle this by creating two separate Geometry objects, with each assigned to one of the layers. Each Geometry object can then compute pore size distributions independently from their own different statistical distributions, and store the values corresponding the pores in its layer. A subdomain is thus a selection of pores (and/or throats) that are related to each other but distinct from the rest of the network. Geometry objects thus define subdomains by the pores and/or throats to which they are applied or assigned.
One of the repercussion of supporing subdomains at the deepest possible layer in OpenPNM is that all users must deal with them, regardelss of whether they are actually using the feature. In other words, even materials with one domain must also define Geometry that defines a single subdomain.
This notebook explores how subdomains work in OpenPNM.
End of explanation
pn = op.network.Cubic([4, 4, 1])
fig, ax = plt.subplots(1, 1)
ax = op.topotools.plot_connections(network=pn, c='k', ax=ax)
plt.axis(False);
Explanation: Create a simple 2D cubic network for easy visualization:
End of explanation
pn.set_label(label='layer1', pores=range(8))
pn.set_label(label='layer2', pores=range(8, 16))
op.topotools.plot_coordinates(network=pn, pores=pn.pores('layer1'), c='r', markersize=100, ax=ax)
op.topotools.plot_coordinates(network=pn, pores=pn.pores('layer2'), c='c', markersize=100, ax=ax)
fig # Re-show figure
Explanation: Label the pores on the left and right to indicate that the Network has two subdomains:
End of explanation
geo1 = op.geometry.GenericGeometry(network=pn, pores=pn.pores('layer1'), throats=pn.Ts)
geo2 = op.geometry.GenericGeometry(network=pn, pores=pn.pores('layer2'))
air = op.phases.Air(network=pn, name='air')
Explanation: The Preferred Way to Work with Subdomains
Create two Geometry objects, with one assigned to each set of pores (i.e. 'layer1' and 'layer2'). Let's also assign all the throats to geo1.
End of explanation
phys1 = op.physics.GenericPhysics(network=pn, phase=air, geometry=geo1)
phys2 = op.physics.GenericPhysics(network=pn, phase=air, geometry=geo2)
Explanation: The "preferred" way to create Physics objects is to assign them to a specific Phase AND Geometry upon instantiation:
End of explanation
proj = pn.project
print(pn.project.grid)
Explanation: The project has a useful feature for studying the associations between Geometry, Phase, and Physics objects called the grid.
End of explanation
print(pn)
Explanation: When creating Physics objects as done above, all the associations between which pores and throats belong to each Physics is taken care of automatically. Essentially, all the pores/throats of geo1 are assigned to phys1 and simlarly all the pores/throats of geo2 are assigned to phys2. However, it is possible to make these assigments manually post-instantiation as will be demonstrated below, but first let's talk about how these associations are tracked by OpenPNM. When a Geometry object is created, two label arrays are added to the Network with True indicating the locations where that Geometry applies. Let's see this by printing the Network:
End of explanation
print(np.where(pn['pore.geo_01'])[0])
Explanation: As can be seen, there is a label array called 'pore.geo_01' that is True in 8 locations. We can see which locations using np.where:
End of explanation
print(np.where(pn['pore.geo_02'])[0])
Explanation: And similarly, for geo2:
End of explanation
pn = op.network.Cubic([4, 4, 1])
pn.set_label(label='layer1', pores=range(8))
pn.set_label(label='layer2', pores=range(8, 16))
geo1 = op.geometry.GenericGeometry(network=pn, pores=pn.pores('layer1'))
geo2 = op.geometry.GenericGeometry(network=pn, pores=pn.pores('layer2'))
air = op.phases.Air(network=pn, name='air')
Explanation: These values are the locations in each array where True was found. Note that they correspond to the pore locations used when creating geo1 and geo2.
NOTE: We cannot just change the values in these arrays to change the locations where geo1 and geo2 are applied. There are several things that need to go on behind the scenes. For instance, if we want to transfer half the throats from geo1 to geo2, OpenPNM must also move any numerical data on geo1, which requires resizes the arrays on both objects. Instead we must use the set_locations method.
Working with Subdomains Manually
Let's recreate the above multidomain network to illustrate how to manually set locations and associations.
End of explanation
phys1 = op.physics.GenericPhysics(network=pn)
phys2 = op.physics.GenericPhysics(network=pn)
Explanation: Next, create two Physics objects, but don't assign them to a Phase or a Geometry object. Note that a warning is issued that the instantiation was not able to assign the Physics to any pores or throats. We'll add these associations manually below:
End of explanation
try:
phys1.phase
except Exception as e:
print(e)
Explanation: Physics objects have a phase attribute that points to the Phase with which it is currently associated. Because we did not provide one when initializing phys1 and phys2 this will raise an exception:
End of explanation
phys1.phase = air
print(phys1.phase.name)
Explanation: We can assign a air to phys1 as follows, after which we can retrieve it using the phase attribute:
End of explanation
try:
phys1.geometry
except Exception as e:
print(e)
Explanation: Physics objects also have geometry attribute which acts just like phase. We have not yet associated phys1 with any locations so it will raise an error:
End of explanation
phys1.geometry = geo1
print(phys1.geometry.name)
print(phys1.pores())
phys1.Np
try:
phys2.geometry = geo2
except Exception as e:
print(e)
proj = pn.project
print(proj.grid)
Explanation: We can assign a Geometry in the same manner as we did for Phase above. This will connect phys1 with the locations corresponding to geo1:
End of explanation
phys2.phase = air
phys2.geometry = geo2
print(pn.project.grid)
Explanation: This shows that phys_02 resides in the ? column indicating that it is not associated with a phase, and it resides in the ? row indicating it is not associated with a geometry either. Let's fix this below.
End of explanation
geo3 = op.geometry.GenericGeometry(network=pn, throats=range(12))
print(pn.project.grid)
Explanation: Now we can see that phys_02 is associated with geo_02 and air. We can also see there are some locations, either pores or throats, that are not yet associated with a geometry object, as indicated by --- in the first column. This is because we did not assign any throats to a Geometry yet. Let's fix this below:
End of explanation
geo3.set_locations(throats=range(12, 24))
print(pn.project.grid)
Explanation: Note that we only assigned 12 throats to geo3, but there were 24 throats in the network. We can either create yet another Geometry, or we can use the set_locations method:
End of explanation
phys3 = op.physics.GenericPhysics(network=pn, phase=air)
print(pn.project.grid)
Explanation: Now we can see that all locations are assigned to a Geometry, indicated by the lack of any rows in the first column containing ---. We still need to create a Physics object for these throats.
Again, let's not assign it to the throats during instantiation and do it manually afterward. But we will include a Phase:
End of explanation
phys3.set_geometry(geo3)
Explanation: Because we included a Phase, this new Physics is in the appropriate column, but is in a ? row since it is not yet associated with a Geometry. Instead of using the geometry attribute as we did above, let's use the set_geometry method, which is actually called behind the scenes when using the geometry attribute:
End of explanation
print(pn.project.grid)
Explanation: Now we can print the project's grid and see that everything is looking good:
End of explanation |
7,959 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Query the database system catalog to retrieve table metadata
You can verify that the table creation was successful by retrieving the list of all tables in your schema and checking whether the SCHOOLS table was created
Step2: Double-click here for a hint
<!--
In Db2 the system catalog table called SYSCAT.TABLES contains the table metadata
-->
Double-click here for the solution.
<!-- Solution
Step3: Double-click here for a hint
<!--
In Db2 the system catalog table called SYSCAT.COLUMNS contains the column metadata
-->
Double-click here for the solution.
<!-- Solution | Python Code:
%load_ext sql
# Enter the connection string for your Db2 on Cloud database instance below
# %sql ibm_db_sa://my-username:my-password@my-hostname:my-port/my-db-name
%sql ibm_db_sa://
Explanation: <a href="https://cognitiveclass.ai"><img src = "https://ibm.box.com/shared/static/ugcqz6ohbvff804xp84y4kqnvvk3bq1g.png" width = 300, align = "center"></a>
<h1 align=center><font size = 5>Lab: Working with a real world data-set using SQL and Python</font></h1>
Introduction
This notebook shows how to work with a real world dataset using SQL and Python. In this lab you will:
1. Understand the dataset for Chicago Public School level performance
1. Store the dataset in an Db2 database on IBM Cloud instance
1. Retrieve metadata about tables and columns and query data from mixed case columns
1. Solve example problems to practice your SQL skills including using built-in database functions
Chicago Public Schools - Progress Report Cards (2011-2012)
The city of Chicago released a dataset showing all school level performance data used to create School Report Cards for the 2011-2012 school year. The dataset is available from the Chicago Data Portal: https://data.cityofchicago.org/Education/Chicago-Public-Schools-Progress-Report-Cards-2011-/9xs2-f89t
This dataset includes a large number of metrics. Start by familiarizing yourself with the types of metrics in the database: https://data.cityofchicago.org/api/assets/AAD41A13-BE8A-4E67-B1F5-86E711E09D5F?download=true
NOTE: Do not download the dataset directly from City of Chicago portal. Instead download a more database friendly version from the link below.
Now download a static copy of this database and review some of its contents:
https://ibm.box.com/shared/static/0g7kbanvn5l2gt2qu38ukooatnjqyuys.csv
Store the dataset in a Table
In many cases the dataset to be analyzed is available as a .CSV (comma separated values) file, perhaps on the internet. To analyze the data using SQL, it first needs to be stored in the database.
While it is easier to read the dataset into a Pandas dataframe and then PERSIST it into the database as we saw in the previous lab, it results in mapping to default datatypes which may not be optimal for SQL querying. For example a long textual field may map to a CLOB instead of a VARCHAR.
Therefore, it is highly recommended to manually load the table using the database console LOAD tool, as indicated in Week 2 Lab 1 Part II. The only difference with that lab is that in Step 5 of the instructions you will need to click on create "(+) New Table" and specify the name of the table you want to create and then click "Next".
Now open the Db2 console, open the LOAD tool, Select / Drag the .CSV file for the CHICAGO PUBLIC SCHOOLS dataset and load the dataset into a new table called SCHOOLS.
<a href="https://cognitiveclass.ai"><img src = "https://ibm.box.com/shared/static/uc4xjh1uxcc78ks1i18v668simioz4es.jpg"></a>
Connect to the database
Let us now load the ipython-sql extension and establish a connection with the database
End of explanation
# type in your query to retrieve list of all tables in the database for your db2 schema (username)
Explanation: Query the database system catalog to retrieve table metadata
You can verify that the table creation was successful by retrieving the list of all tables in your schema and checking whether the SCHOOLS table was created
End of explanation
# type in your query to retrieve the number of columns in the SCHOOLS table
Explanation: Double-click here for a hint
<!--
In Db2 the system catalog table called SYSCAT.TABLES contains the table metadata
-->
Double-click here for the solution.
<!-- Solution:
%sql select TABSCHEMA, TABNAME, CREATE_TIME from SYSCAT.TABLES where TABSCHEMA='YOUR-DB2-USERNAME'
or, you can retrieve list of all tables where the schema name is not one of the system created ones:
%sql select TABSCHEMA, TABNAME, CREATE_TIME from SYSCAT.TABLES \
where TABSCHEMA not in ('SYSIBM', 'SYSCAT', 'SYSSTAT', 'SYSIBMADM', 'SYSTOOLS', 'SYSPUBLIC')
or, just query for a specifc table that you want to verify exists in the database
%sql select * from SYSCAT.TABLES where TABNAME = 'SCHOOLS'
-->
Query the database system catalog to retrieve column metadata
The SCHOOLS table contains a large number of columns. How many columns does this table have?
End of explanation
# type in your query to retrieve all column names in the SCHOOLS table along with their datatypes and length
Explanation: Double-click here for a hint
<!--
In Db2 the system catalog table called SYSCAT.COLUMNS contains the column metadata
-->
Double-click here for the solution.
<!-- Solution:
%sql select count(*) from SYSCAT.COLUMNS where TABNAME = 'SCHOOLS'
-->
Now retrieve the the list of columns in SCHOOLS table and their column type (datatype) and length.
End of explanation |
7,960 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute ICA on MEG data and remove artifacts
ICA is fit to MEG raw data.
The sources matching the ECG and EOG are automatically found and displayed.
Subsequently, artifact detection and rejection quality are assessed.
Step1: Setup paths and prepare raw data.
Step2: 1) Fit ICA model using the FastICA algorithm.
Step3: 2) identify bad components by analyzing latent sources.
Step4: 3) Assess component selection and unmixing quality. | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.preprocessing import ICA
from mne.preprocessing import create_ecg_epochs, create_eog_epochs
from mne.datasets import sample
Explanation: Compute ICA on MEG data and remove artifacts
ICA is fit to MEG raw data.
The sources matching the ECG and EOG are automatically found and displayed.
Subsequently, artifact detection and rejection quality are assessed.
End of explanation
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 45, n_jobs=1, l_trans_bandwidth=0.5, h_trans_bandwidth=0.5,
filter_length='10s', phase='zero-double', fir_design='firwin2')
raw.annotations = mne.Annotations([1], [10], 'BAD')
raw.plot(block=True)
# For the sake of example we annotate first 10 seconds of the recording as
# 'BAD'. This part of data is excluded from the ICA decomposition by default.
# To turn this behavior off, pass ``reject_by_annotation=False`` to
# :meth:`mne.preprocessing.ICA.fit`.
raw.annotations = mne.Annotations([0], [10], 'BAD')
Explanation: Setup paths and prepare raw data.
End of explanation
# Other available choices are `infomax` or `extended-infomax`
# We pass a float value between 0 and 1 to select n_components based on the
# percentage of variance explained by the PCA components.
ica = ICA(n_components=0.95, method='fastica')
picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=False,
stim=False, exclude='bads')
ica.fit(raw, picks=picks, decim=3, reject=dict(mag=4e-12, grad=4000e-13))
# maximum number of components to reject
n_max_ecg, n_max_eog = 3, 1 # here we don't expect horizontal EOG components
Explanation: 1) Fit ICA model using the FastICA algorithm.
End of explanation
title = 'Sources related to %s artifacts (red)'
# generate ECG epochs use detection via phase statistics
ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5, picks=picks)
ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, method='ctps')
ica.plot_scores(scores, exclude=ecg_inds, title=title % 'ecg', labels='ecg')
show_picks = np.abs(scores).argsort()[::-1][:5]
ica.plot_sources(raw, show_picks, exclude=ecg_inds, title=title % 'ecg')
ica.plot_components(ecg_inds, title=title % 'ecg', colorbar=True)
ecg_inds = ecg_inds[:n_max_ecg]
ica.exclude += ecg_inds
# detect EOG by correlation
eog_inds, scores = ica.find_bads_eog(raw)
ica.plot_scores(scores, exclude=eog_inds, title=title % 'eog', labels='eog')
show_picks = np.abs(scores).argsort()[::-1][:5]
ica.plot_sources(raw, show_picks, exclude=eog_inds, title=title % 'eog')
ica.plot_components(eog_inds, title=title % 'eog', colorbar=True)
eog_inds = eog_inds[:n_max_eog]
ica.exclude += eog_inds
Explanation: 2) identify bad components by analyzing latent sources.
End of explanation
# estimate average artifact
ecg_evoked = ecg_epochs.average()
ica.plot_sources(ecg_evoked, exclude=ecg_inds) # plot ECG sources + selection
ica.plot_overlay(ecg_evoked, exclude=ecg_inds) # plot ECG cleaning
eog_evoked = create_eog_epochs(raw, tmin=-.5, tmax=.5, picks=picks).average()
ica.plot_sources(eog_evoked, exclude=eog_inds) # plot EOG sources + selection
ica.plot_overlay(eog_evoked, exclude=eog_inds) # plot EOG cleaning
# check the amplitudes do not change
ica.plot_overlay(raw) # EOG artifacts remain
# To save an ICA solution you can say:
# ica.save('my_ica.fif')
# You can later load the solution by saying:
# from mne.preprocessing import read_ica
# read_ica('my_ica.fif')
# Apply the solution to Raw, Epochs or Evoked like this:
# ica.apply(epochs)
Explanation: 3) Assess component selection and unmixing quality.
End of explanation |
7,961 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Importance of known positives versus known negatives
In this notebook we will show how to compute performance curves (ROC and PR curves to be specific) based on a data set with known positives, known negatives and unlabeled data. We will show how to use our approach starting from known negatives instead of known positives, which is useful of the number of known negatives is much larger.
This notebook is intended to enable you to easily change the configuration of experiments, so feel free to make modifications where you see fit to see their effect.
Step1: Create or load data set
Generate simulated data. Feel free to configure the code below as you please.
Step2: Data set characteristics
Known parameters
Step3: Unknown parameters
Step4: Estimate beta
As this notebook is intended to show the effect of known positives vs known negatives, we will continue with the true value of beta. Change this parameter to see its effect in the figures later on.
Step5: 1. Compute cumulative rank distribution of known positives
We start by computing the rank CDF of known positives, and then determine a confidence interval for it. We will use a standard bootstrap approach.
Step6: Next, we determine a confidence interval on the rank CDF of known positives. We can do this in several ways, our code provides a bootstrap approach and a method based on the Dvoretzky–Kiefer–Wolfowitz (DKW) inequality. Feel free to experiment.
Step7: For reference, we will also compute the rank ECDF of latent positives. In practical applications this is impossible, as the latent positives are by definition not known.
Step8: Plot the rank CDFs of known and latent positives. It may occur that the rank CDF of latent positives is not within the confidence interval of known positives, in which case the corresponding bounds on performance will not be strict.
Step9: 2. Compute cumulative rank distribution of known negatives
The code below is analogous to what we did earlier for known positives, but now for known negatives. We will first flip known class labels, as described in the text.
Step10: Plot rank CDFs of known positives and known negatives along with their CIs.
Step11: 3. Compute contingency tables for each rank
We will compute contingency tables based on the rank distribution of known positives and based on the rank distribution of known negatives.
Applying our approach to known negatives requires a few modifications
Step12: 4. Compute and plot performance estimates based on the contingency tables
4.1 ROC curves
Start off with the easy stuff
Step13: Compute bounds based on the proposed method.
Step14: Plot the resulting curves
Step15: The resulting curves show clearly that in this case computing bounds based on known negatives is better, because we have far more known negatives.
4.2 PR curves | Python Code:
import random
import operator as op
import optunity.metrics
import semisup_metrics as ss
import numpy as np
from matplotlib import pyplot as plt
import pickle
import csv
import util
%matplotlib inline
Explanation: Importance of known positives versus known negatives
In this notebook we will show how to compute performance curves (ROC and PR curves to be specific) based on a data set with known positives, known negatives and unlabeled data. We will show how to use our approach starting from known negatives instead of known positives, which is useful of the number of known negatives is much larger.
This notebook is intended to enable you to easily change the configuration of experiments, so feel free to make modifications where you see fit to see their effect.
End of explanation
# fraction of positives/negatives that are known
# known_neg_frac == 0 implies PU learning
known_pos_frac = 0.05
known_neg_frac = 0.5
# if you simulate a smaller data set you can see some effects better
# but estimated bounds will be much wider
# because the ECDF confidence interval becomes large
num_pos = 10000
num_neg = 10000
distid = 2 # can be 1, 2 or 3, these correspond to certain curves in ROC space
# generate rankings and label vectors and compute corresponding beta
# beta is based on known_pos_frac, known_neg_frac and the number of pos and negs
# labels is a list of {True, False, None}, where None indicates unlabeled
# true_labels is a list of {True, False}
labels, true_labels, decision_values, beta = util.simulate_data(distid, num_pos, num_neg,
known_pos_frac,
known_neg_frac)
Explanation: Create or load data set
Generate simulated data. Feel free to configure the code below as you please.
End of explanation
print('total number of instances: \t %d' % len(labels))
print('number of known positives: \t %d' % len(list(filter(lambda x: x == True, labels))))
print('number of known negatives: \t %d' % len(list(filter(lambda x: x == False, labels))))
print('number of unlabeled instances: \t %d' % len(list(filter(lambda x: x == None, labels))))
Explanation: Data set characteristics
Known parameters:
End of explanation
print('number of latent positives: \t %d' % len(list(filter(lambda x: x[0] == None and x[1] == True, zip(labels, true_labels)))))
print('number of latent negatives: \t %d' % len(list(filter(lambda x: x[0] == None and x[1] == False, zip(labels, true_labels)))))
print('beta: \t %1.4f' % beta)
Explanation: Unknown parameters:
End of explanation
betahat = beta
print('true value of beta\t%1.4f' % beta)
print('point estimate of beta\t%1.4f' % betahat)
Explanation: Estimate beta
As this notebook is intended to show the effect of known positives vs known negatives, we will continue with the true value of beta. Change this parameter to see its effect in the figures later on.
End of explanation
# sort the labels in descending order of corresponding decision values
sort_labels, sort_dv, sort_true_labels = zip(*sorted(zip(labels, decision_values, true_labels),
key=op.itemgetter(1), reverse=True))
# ranks of the known positives
known_pos_ranks = [idx for idx, lab in enumerate(sort_labels) if lab]
# compute rank ECDF of known positives
known_pos_ecdf = ss.compute_ecdf_curve(known_pos_ranks)
Explanation: 1. Compute cumulative rank distribution of known positives
We start by computing the rank CDF of known positives, and then determine a confidence interval for it. We will use a standard bootstrap approach.
End of explanation
ci_width = 0.95 # width of the confidence band on ECDF to be used
use_bootstrap = True # use bootstrap to compute confidence band
nboot = 2000 # number of bootstrap iterations to use, not used if use_bootstrap = False
if use_bootstrap:
pos_cdf_bounds = ss.bootstrap_ecdf_bounds(labels, decision_values, nboot=nboot, ci_width=ci_width)
else:
pos_cdf_bounds = ss.dkw_bounds(labels, decision_values, ci_width=ci_width)
Explanation: Next, we determine a confidence interval on the rank CDF of known positives. We can do this in several ways, our code provides a bootstrap approach and a method based on the Dvoretzky–Kiefer–Wolfowitz (DKW) inequality. Feel free to experiment.
End of explanation
latent_positives = map(lambda x, y: x == True and y == None, true_labels, labels)
sort_lps, _ = zip(*sorted(zip(latent_positives, decision_values),
key=op.itemgetter(1), reverse=True))
latent_pos_ranks = [idx for idx, lab in enumerate(sort_lps) if lab]
latent_pos_ecdf = ss.compute_ecdf_curve(latent_pos_ranks)
Explanation: For reference, we will also compute the rank ECDF of latent positives. In practical applications this is impossible, as the latent positives are by definition not known.
End of explanation
# convenience plot functions
def plot_proxy(color, alpha):
p = plt.Rectangle((0, 0), 0, 0, color=color, alpha=alpha)
ax = plt.gca()
ax.add_patch(p)
return p
def fix_plot_shape(fig):
ax = fig.add_subplot(111, aspect='equal')
axes = fig.gca()
axes.set_xlim([0,1])
axes.set_ylim([0,1])
xs = list(range(len(labels)))
plt.figure(1)
plt.fill_between(xs, list(map(pos_cdf_bounds.lower, xs)), list(map(pos_cdf_bounds.upper, xs)),
color='blue', alpha=0.4)
plt.plot(*zip(*known_pos_ecdf), color='black', linestyle='dashed', linewidth=2)
plt.plot(*zip(*latent_pos_ecdf), color='black', linewidth=2)
plot_proxy('blue', 0.4)
plt.xlabel('rank')
plt.ylabel('TPR')
plt.legend(['known positives', 'latent positives', 'expected region'], loc=4)
plt.title('Rank CDF')
plt.show()
Explanation: Plot the rank CDFs of known and latent positives. It may occur that the rank CDF of latent positives is not within the confidence interval of known positives, in which case the corresponding bounds on performance will not be strict.
End of explanation
# ranks of the known positives
known_neg_ranks = [idx for idx, lab in enumerate(sort_labels) if lab == False]
# compute rank ECDF of known positives
known_neg_ecdf = ss.compute_ecdf_curve(sorted(known_neg_ranks))
# flip class labels
labels_flipped = [not label if label is not None else None for label in labels]
sort_labels_flipped = [not label if label is not None else None for label in sort_labels]
# compute confidence interval in the same way as we did for known positives
if use_bootstrap:
neg_cdf_bounds = ss.bootstrap_ecdf_bounds(labels_flipped, decision_values, nboot=nboot, ci_width=ci_width)
else:
neg_cdf_bounds = ss.dkw_bounds(labels_flipped, decision_values, ci_width=ci_width)
# for reference, rank CDF of latent negatives
latent_negatives = map(lambda x, y: x == False and y == None, true_labels, labels)
sort_lns, _ = zip(*sorted(zip(latent_negatives, decision_values),
key=op.itemgetter(1), reverse=True))
latent_neg_ranks = [idx for idx, lab in enumerate(sort_lns) if lab]
latent_neg_ecdf = ss.compute_ecdf_curve(latent_neg_ranks)
Explanation: 2. Compute cumulative rank distribution of known negatives
The code below is analogous to what we did earlier for known positives, but now for known negatives. We will first flip known class labels, as described in the text.
End of explanation
xs = list(range(len(labels)))
plt.figure(1)
plt.fill_between(xs, list(map(pos_cdf_bounds.lower, xs)), list(map(pos_cdf_bounds.upper, xs)),
color='blue', alpha=0.4)
plt.plot(*zip(*known_pos_ecdf), color='blue', linestyle='dashed', linewidth=2)
plt.plot(*zip(*latent_pos_ecdf), color='blue', linewidth=2)
plot_proxy('blue', 0.4)
plt.fill_between(xs, list(map(neg_cdf_bounds.lower, xs)), list(map(neg_cdf_bounds.upper, xs)),
color='red', alpha=0.4)
plt.plot(*zip(*known_neg_ecdf), color='red', linestyle='dashed', linewidth=2)
plt.plot(*zip(*latent_neg_ecdf), color='red', linewidth=2)
plot_proxy('red', 0.4)
plt.xlabel('rank')
plt.ylabel('TPR')
plt.legend(['known positives', 'latent positives', 'known negatives', 'latent negatives', 'CI for pos', 'CI for neg'],
loc="upper left", bbox_to_anchor=(1,1))
plt.title('Rank CDF')
plt.show()
Explanation: Plot rank CDFs of known positives and known negatives along with their CIs.
End of explanation
# compute contingency tables based on CI of rank CDF of known positives
tables_pos = ss.compute_contingency_tables(labels=sort_labels, decision_values=sort_dv,
reference_lb=pos_cdf_bounds.lower,
reference_ub=pos_cdf_bounds.upper,
beta=betahat, presorted=True)
# compute contingency tables based on CI of rank CDF of known negatives
# this requires flipping labels, changing beta and post-processing the resulting contingency tables
betahat_flipped = 1.0 - betahat
tables_neg = ss.compute_contingency_tables(labels=sort_labels_flipped, decision_values=sort_dv,
reference_lb=neg_cdf_bounds.lower,
reference_ub=neg_cdf_bounds.upper,
beta=betahat_flipped, presorted=True)
postprocess_ct = lambda ct: ss.ContingencyTable(TP=ct.FP,
FP=ct.TP,
TN=ct.FN,
FN=ct.TN)
tables_neg_post = ss._lb_ub(lower=list(map(postprocess_ct, tables_neg.upper)),
upper=list(map(postprocess_ct, tables_neg.lower)))
Explanation: 3. Compute contingency tables for each rank
We will compute contingency tables based on the rank distribution of known positives and based on the rank distribution of known negatives.
Applying our approach to known negatives requires a few modifications:
1. Flip known class labels, so negatives become positives
2. Modify beta (new beta = 1 - beta)
3. Run our approach
4. Adjust resulting contingency tables (i.e., flip class labels back). Note also that the optimistic contingency table becomes the pessimistic table when flipping labels and vice versa.
End of explanation
# compute the true ROC curve (we use Optunity's ROC function)
_, roc_true = optunity.metrics.roc_auc(true_labels, decision_values, return_curve=True)
Explanation: 4. Compute and plot performance estimates based on the contingency tables
4.1 ROC curves
Start off with the easy stuff: the true ROC curve (unknown in practice), and the curve we obtain by assuming beta=0.
End of explanation
# we can directly use the contingency tables we already computed anyways
roc_bounds = lambda tables: ss._lb_ub(lower=ss.roc_from_cts(tables.lower),
upper=ss.roc_from_cts(tables.upper))
# bounds starting from known positives
roc_bounds_pos = roc_bounds(tables_pos)
# bounds starting from known negatives
roc_bounds_neg = roc_bounds(tables_neg_post)
Explanation: Compute bounds based on the proposed method.
End of explanation
xs = [float(x) / 100 for x in range(101)]
roc_pos_up = ss.zoh(*zip(*roc_bounds_pos.upper))
roc_pos_lo = ss.zoh(*zip(*roc_bounds_pos.lower))
roc_neg_up = ss.zoh(*zip(*roc_bounds_neg.upper))
roc_neg_lo = ss.zoh(*zip(*roc_bounds_neg.lower))
fig = plt.figure(2)
fix_plot_shape(fig)
plt.plot(*zip(*roc_true), color='black', linewidth=2)
plt.fill_between(xs, list(map(roc_pos_lo, xs)), list(map(roc_pos_up, xs)), color='blue', alpha=0.3)
plt.fill_between(xs, list(map(roc_neg_lo, xs)), list(map(roc_neg_up, xs)), color='red', alpha=0.7)
plot_proxy('blue', 0.3)
plot_proxy('red', 0.7)
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.legend(['true curve', 'expected region via known pos', 'expected region via known neg'],
loc="upper left", bbox_to_anchor=(1,1))
plt.title('Receiver Operating Characteristic curve')
plt.show()
Explanation: Plot the resulting curves
End of explanation
# we can directly use the contingency tables we already computed anyways
pr_bounds = lambda tables: ss._lb_ub(lower=ss.pr_from_cts(tables.lower),
upper=ss.pr_from_cts(tables.upper))
pr_bounds_pos = pr_bounds(tables_pos)
pr_bounds_neg = pr_bounds(tables_neg_post)
# an alternative without all these intermediate steps would be:
# roc_bounds_point = ss.roc_bounds(labels, decision_values, beta=betahat)
# compute the true ROC curve (we use Optunity's ROC function)
_, pr_true = optunity.metrics.pr_auc(true_labels, decision_values, return_curve=True)
pr_pos_up = ss.zoh(*zip(*pr_bounds_pos.upper))
pr_pos_lo = ss.zoh(*zip(*pr_bounds_pos.lower))
pr_neg_up = ss.zoh(*zip(*pr_bounds_neg.upper))
pr_neg_lo = ss.zoh(*zip(*pr_bounds_neg.lower))
fig = plt.figure(3)
fix_plot_shape(fig)
plt.plot(*zip(*pr_true), color='black', linewidth=2)
plt.fill_between(xs, list(map(pr_pos_lo, xs)), list(map(pr_pos_up, xs)), color='blue', alpha=0.3)
plt.fill_between(xs, list(map(pr_neg_lo, xs)), list(map(pr_neg_up, xs)), color='red', alpha=0.7)
plot_proxy('blue', 0.3)
plot_proxy('red', 0.7)
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.legend(['true curve', 'expected region via known pos', 'expected region via known neg'],
loc="upper left", bbox_to_anchor=(1,1))
plt.title('Precision-Recall curve')
plt.show()
Explanation: The resulting curves show clearly that in this case computing bounds based on known negatives is better, because we have far more known negatives.
4.2 PR curves
End of explanation |
7,962 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We'll try to desribe our loci of interest procedure with details and illustrations here.
Let's start with some modules
Step1: Then import the Codon Table for standard genetic code, with the slight modification - add STOP codon * as a fully-fledged member of the table
Step2: Kyte-Doolittle hydrophobicity scale is needed for us as well. We add the STOP codon there as well, and assign it artificially large KD value, simply to make all the mutations to/from the STOP codon distinguishable.
Step3: Reference flu as object and pH1N1 alignment
We would also need our custom Flu-module, located outside the current path to perform all flu-genome related manipulations.
Step4: Reference flu-genome sequence is a consensus of the pandemic H1N1
Step5: Our segment-wide alignments are stored in files with particular names
Step6: Let's load all of the alignments using these file names and store them as a dictionary
Step7: Let's output some characteristics of the alignment
Step9: in ORF or not in ORF? where exactly?
Next we define a funtion that would provide all ORFs associated with a given genome locus, along with the description of the hosting codon, and a codon-shift of a given locus (first, second, third position).
Step10: Then we perform the analysis, exploring observed mutations and their basic features | Python Code:
%matplotlib inline
import os
import sys
from Bio import SeqRecord
from Bio import AlignIO
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: We'll try to desribe our loci of interest procedure with details and illustrations here.
Let's start with some modules:
End of explanation
from Bio.Data import CodonTable
genetic_code = CodonTable.standard_dna_table.forward_table
stop_codons = dict([ (codon,'*') for codon in CodonTable.standard_dna_table.stop_codons ])
genetic_code.update(stop_codons)
Explanation: Then import the Codon Table for standard genetic code, with the slight modification - add STOP codon * as a fully-fledged member of the table:
End of explanation
from Bio.SeqUtils import ProtParamData
KD = ProtParamData.kd
KD['*'] = 25.0
Explanation: Kyte-Doolittle hydrophobicity scale is needed for us as well. We add the STOP codon there as well, and assign it artificially large KD value, simply to make all the mutations to/from the STOP codon distinguishable.
End of explanation
sys.path.append("../RNA_SNP_association")
import flu_module as flu
Explanation: Reference flu as object and pH1N1 alignment
We would also need our custom Flu-module, located outside the current path to perform all flu-genome related manipulations.
End of explanation
ref_fname = "./pH1N1_coding_dat/pH1N1.fa"
orf_fname = "./pH1N1_coding_dat/pH1N1_noPB1F.orf"
ph1n1 = flu.influenza(ref_fname, orf_fname)
Explanation: Reference flu-genome sequence is a consensus of the pandemic H1N1: pH1N1. Let's load the reference with the description of ORF location.
End of explanation
aligned_seg_fname = lambda number: "seg%d.afa"%number
Explanation: Our segment-wide alignments are stored in files with particular names:
End of explanation
segment_aln = {}
for seg_idx in range(1, ph1n1.segnum+1):
fname = aligned_seg_fname(seg_idx)
segment_aln['seg%d'%seg_idx] = AlignIO.read(fname,'fasta')
Explanation: Let's load all of the alignments using these file names and store them as a dictionary:
End of explanation
for seg in sorted(segment_aln):
print "%s of len %d has %d sequences aligned"%(seg,segment_aln[seg].get_alignment_length(),len(segment_aln[seg]))
Explanation: Let's output some characteristics of the alignment:
End of explanation
def get_loci_orf_assoc(orf,loci):
checks if a given position is in any of the ORFs. Returns
a list of the hosting ORFs with corresponding coords. of codons.
which_orf = []
for orf_id in orf:
orf_bounds = orf[orf_id]
orf_positions = sum([range(start,stop+1) for start,stop in orf_bounds], [])
# pos residence in ORF or not in ORF?
if loci in orf_positions:
# relative loci, simply an index in the list of orf_positions ...
relative_pos = orf_positions.index(loci)
# the index of the codon it belongs to ...
codon_idx = relative_pos//3
# relative codon coordinates (indexes within CDS):
relative_codon_coord = [codon_idx*3+i for i in range(3)]
# loci is 1st,2nd or 3rd position in the codon?
codon_shift = relative_pos - relative_codon_coord[0]
# absolute codon coordinates (indexes in the genome):
codon_coord = [orf_positions[_] for _ in relative_codon_coord]
which_orf.append( (orf_id, (codon_idx,codon_shift,codon_coord) ) )
return dict(which_orf)
Explanation: in ORF or not in ORF? where exactly?
Next we define a funtion that would provide all ORFs associated with a given genome locus, along with the description of the hosting codon, and a codon-shift of a given locus (first, second, third position).
End of explanation
# lists to store some info ...
codon_position_mutated = []
codon_position_mutated_weight = []
dKD = []
dKD_weight = []
#
segment_var_info = {}
#
# analysis for each segment ...
for seg in sorted(segment_aln):
# turn aln to an array and describe aln ...
aln = np.array([list(rec) for rec in segment_aln[seg]], np.character)
aln = pd.DataFrame(aln)
aln = aln.where(aln!='-',None) # gaps to Nones
descr = aln.describe().transpose() #built-in
descr['freq_ratio'] = descr['freq']/descr['count'] # freq_ratio ignores gaps ...
descr['gaps'] = aln.isnull().sum()
descr['variation'] = descr['freq']<descr['count'] # variable positions ...
# ORF of this segment ...
seg_orf = ph1n1.orf[seg+'_pH1N1']
seg_seq = ph1n1.genome[seg+'_pH1N1']
# we would like to store some averaged statisticsfor each var position:
codon_position_avg = []
codon_position_mutated_weight = []
dKD = []
dKD_weight = []
# go over all variable positions ...
for pos in descr[descr['variation']].index:
# unpack codon information ...
prod_codon = get_loci_orf_assoc(seg_orf,pos)
for product in prod_codon:
codon_idx, codon_shift, codon_coords = prod_codon[product]
# the consensus codon, AA and KD ...
codon_itself = ''.join(seg_seq[i] for i in codon_coords)
aa_itself = genetic_code[codon_itself]
KD_itself = KD[aa_itself]
# SNPs at this position ...
nts_present = aln.loc[:,pos].value_counts().to_dict()
# CODON SHIFT STATISTICS GATHERING ...
codon_position_mutated.append(codon_shift)
# variation frequency, non-consensus % aka mutation 'weight'
weight = 1.0 - descr['freq_ratio'][pos]
codon_position_mutated_weight.append(weight)
# hence, possible codons are:
possible_codons = []
for snp in nts_present:
mut_codon = list(codon_itself)
mut_codon[codon_shift] = snp
possible_codons.append(mut_codon)
# STATISTICS GATHERING ...
the_alt_codon = ''.join(mut_codon)
if the_alt_codon != codon_itself:
the_alt_aa = genetic_code[the_alt_codon]
the_alt_KD = KD[the_alt_aa]
weight = nts_present[snp]*1.0/sum(nts_present.values())
#################################
dKD.append(the_alt_KD - KD_itself)
dKD_weight.append(weight)
# # amino acids ...
# print "Product %s, position %d in protein (codon %s, aa %s)"%(product, codon_shift+1, codon_itself, genetic_code[codon_itself])
# other_possible_codons = [''.join(codon) for codon in possible_codons if ''.join(codon)!=codon_itself]
# print "outcome AAs are: %s"%str([genetic_code[ccc] for ccc in other_possible_codons]).strip('[]').replace('\'','')
# # print str([genetic_code[ccc] for ccc in other_possible_codons]).strip('[]').replace('\'','')
# print "dKD for AA subs: %s"%str([ KD[genetic_code[ccc]]-KD[genetic_code[codon_itself]] for ccc in other_possible_codons]).strip('[]')
print descr.head(15)
print seg
f,ax = plt.subplots(1,1,figsize=(20,4))
ax.plot(descr[descr['variation']].index,descr[descr['variation']]['freq_ratio'],'ro')
# ax = plt.gca()
# ax.set_yscale('log')
# ax.set_ylim(0.99,1)
plt.show()
plt.hist(codon_position_mutated,bins=3)
ax = plt.gca()
ax.set_xlabel("codon position: 1,2,3")
plt.show()
plt.hist(codon_position_mutated,bins=3,weights=codon_position_mutated_weight)
ax = plt.gca()
ax.set_xlabel("codon position: 1,2,3")
plt.show()
Explanation: Then we perform the analysis, exploring observed mutations and their basic features:
End of explanation |
7,963 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Autoencoders
What are Autoencoders?
Step1: "Autoencoding" is a data compression algorithm where the compression and decompression functions are 1) data-specific, 2) lossy, and 3) learned automatically from examples rather than engineered by a human. Additionally, in almost all contexts where the term "autoencoder" is used, the compression and decompression functions are implemented with neural networks.
1) Autoencoders are data-specific, which means that they will only be able to compress data similar to what they have been trained on. This is different from, say, the MPEG-2 Audio Layer III (MP3) compression algorithm, which only holds assumptions about "sound" in general, but not about specific types of sounds. An autoencoder trained on pictures of faces would do a rather poor job of compressing pictures of trees, because the features it would learn would be face-specific.
2) Autoencoders are lossy, which means that the decompressed outputs will be degraded compared to the original inputs (similar to MP3 or JPEG compression). This differs from lossless arithmetic compression.
3) Autoencoders are learned automatically from data examples, which is a useful property
Step2: Let's also create a separate encoder model
Step3: As well as the decoder model
Step4: Now let's train our autoencoder to reconstruct MNIST digits.
First, we'll configure our model to use a per-pixel categorical crossentropy loss, and the Adagrad optimizer
Step5: Let's prepare our input data. We're using MNIST digits, and we're discarding the labels (since we're only interested in encoding/decoding the input images).
Step6: We will normalize all values between 0 and 1 and we will flatten the 28x28 images into vectors of size 784.
Step7: Now let's train our autoencoder for 100 epochs
Step8: After 100 epochs, the autoencoder seems to reach a stable train/test loss value of about 0.0932. We can try to visualize the reconstructed inputs and the encoded representations. We will use Matplotlib.
Step9: Here's what we get. The top row is the original digits, and the bottom row is the reconstructed digits. We are losing quite a bit of detail with this basic approach.
Adding a sparsity constraint on the encoded representations
In the previous example, the representations were only constrained by the size of the hidden layer (32). In such a situation, what typically happens is that the hidden layer is learning an approximation of PCA (principal component analysis). But another way to constrain the representations to be compact is to add a sparsity contraint on the activity of the hidden representations, so fewer units would "fire" at a given time. In Keras, this can be done by adding an activity_regularizer to our Dense layer
Step10: Let's train this model for 100 epochs (with the added regularization the model is less likely to overfit and can be trained longer).
Step11: The models ends with a train loss of 0.1887 and test loss of 0.876. The difference between the two is mostly due to the regularization term being added to the loss during training (worth about 0.01).
Here's a visualization of our new results
Step12: Deep autoencoder
We do not have to limit ourselves to a single layer as encoder or decoder, we could instead use a stack of layers, such as
Step13: Let's try this | Python Code:
PATH = "/Users/raghu/Downloads/"
Image(filename = PATH + "autoencoder_schema.jpg", width=500, height=500)
Explanation: Autoencoders
What are Autoencoders?
End of explanation
from keras.layers import Input, Dense
from keras.models import Model
# this is the size of our encoded representations
encoding_dim = 32 # 32 floats -> compression of factor 24.5, assuming the input is 784 floats
# this is our input placeholder
input_img = Input(shape=(784,))
# "encoded" is the encoded representation of the input
encoded = Dense(encoding_dim, activation='relu')(input_img)
# "decoded" is the lossy reconstruction of the input
decoded = Dense(784, activation='sigmoid')(encoded)
# this model maps an input to its reconstruction
autoencoder = Model(input_img, decoded)
Explanation: "Autoencoding" is a data compression algorithm where the compression and decompression functions are 1) data-specific, 2) lossy, and 3) learned automatically from examples rather than engineered by a human. Additionally, in almost all contexts where the term "autoencoder" is used, the compression and decompression functions are implemented with neural networks.
1) Autoencoders are data-specific, which means that they will only be able to compress data similar to what they have been trained on. This is different from, say, the MPEG-2 Audio Layer III (MP3) compression algorithm, which only holds assumptions about "sound" in general, but not about specific types of sounds. An autoencoder trained on pictures of faces would do a rather poor job of compressing pictures of trees, because the features it would learn would be face-specific.
2) Autoencoders are lossy, which means that the decompressed outputs will be degraded compared to the original inputs (similar to MP3 or JPEG compression). This differs from lossless arithmetic compression.
3) Autoencoders are learned automatically from data examples, which is a useful property: it means that it is easy to train specialized instances of the algorithm that will perform well on a specific type of input. It doesn't require any new engineering, just appropriate training data.
To build an autoencoder, you need three things: an encoding function, a decoding function, and a distance function between the amount of information loss between the compressed representation of your data and the decompressed representation (i.e. a "loss" function). The encoder and decoder will be chosen to be parametric functions (typically neural networks), and to be differentiable with respect to the distance function, so the parameters of the encoding/decoding functions can be optimize to minimize the reconstruction loss, using Stochastic Gradient Descent. It's simple! And you don't even need to understand any of these words to start using autoencoders in practice.
Are they good at data compression?
Usually, not really. In picture compression for instance, it is pretty difficult to train an autoencoder that does a better job than a basic algorithm like JPEG, and typically the only way it can be achieved is by restricting yourself to a very specific type of picture (e.g. one for which JPEG does not do a good job). The fact that autoencoders are data-specific makes them generally impractical for real-world data compression problems: you can only use them on data that is similar to what they were trained on, and making them more general thus requires lots of training data.
What are applications of autoencoders?
They are rarely used in practical applications. In 2012 they briefly found an application in greedy layer-wise pretraining for deep convolutional neural networks, but this quickly fell out of fashion as we started realizing that better random weight initialization schemes were sufficient for training deep networks from scratch. In 2014, batch normalization started allowing for even deeper networks, and from late 2015 we could train arbitrarily deep networks from scratch using residual learning.
Today two interesting practical applications of autoencoders are data denoising (which we feature later in this post), and dimensionality reduction for data visualization. With appropriate dimensionality and sparsity constraints, autoencoders can learn data projections that are more interesting than PCA or other basic techniques.
For 2D visualization specifically, t-SNE (pronounced "tee-snee") is probably the best algorithm around, but it typically requires relatively low-dimensional data. So a good strategy for visualizing similarity relationships in high-dimensional data is to start by using an autoencoder to compress your data into a low-dimensional space (e.g. 32 dimensional), then use t-SNE for mapping the compressed data to a 2D plane.
Lets build simplest Autoencoder
End of explanation
# this model maps an input to its encoded representation
encoder = Model(input_img, encoded)
Explanation: Let's also create a separate encoder model:
End of explanation
# create a placeholder for an encoded (32-dimensional) input
encoded_input = Input(shape=(encoding_dim,))
# retrieve the last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]
# create the decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))
Explanation: As well as the decoder model:
End of explanation
autoencoder.compile(optimizer='adagrad', loss='binary_crossentropy')
Explanation: Now let's train our autoencoder to reconstruct MNIST digits.
First, we'll configure our model to use a per-pixel categorical crossentropy loss, and the Adagrad optimizer:
End of explanation
from keras.datasets import mnist
import numpy as np
(x_train, _), (x_test, _) = mnist.load_data()
Explanation: Let's prepare our input data. We're using MNIST digits, and we're discarding the labels (since we're only interested in encoding/decoding the input images).
End of explanation
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
print(x_train.shape)
print(x_test.shape)
Explanation: We will normalize all values between 0 and 1 and we will flatten the 28x28 images into vectors of size 784.
End of explanation
autoencoder.fit(x_train, x_train,
epochs=100,
batch_size=32,
shuffle=True,
validation_data=(x_test, x_test))
Explanation: Now let's train our autoencoder for 100 epochs:
End of explanation
# encode and decode some digits
# note that we take them from the *test* set
encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)
# use Matplotlib
import matplotlib.pyplot as plt
n = 10 # how many digits we will display
plt.figure(figsize=(20, 4))
for i in range(n):
# display original
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstruction
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow(decoded_imgs[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
Explanation: After 100 epochs, the autoencoder seems to reach a stable train/test loss value of about 0.0932. We can try to visualize the reconstructed inputs and the encoded representations. We will use Matplotlib.
End of explanation
from keras import regularizers
encoding_dim = 32
input_img = Input(shape=(784,))
# add a Dense layer with a L1 activity regularizer
encoded = Dense(encoding_dim, activation='relu',
activity_regularizer=regularizers.l1(10e-5))(input_img)
decoded = Dense(784, activation='sigmoid')(encoded)
autoencoder = Model(input_img, decoded)
Explanation: Here's what we get. The top row is the original digits, and the bottom row is the reconstructed digits. We are losing quite a bit of detail with this basic approach.
Adding a sparsity constraint on the encoded representations
In the previous example, the representations were only constrained by the size of the hidden layer (32). In such a situation, what typically happens is that the hidden layer is learning an approximation of PCA (principal component analysis). But another way to constrain the representations to be compact is to add a sparsity contraint on the activity of the hidden representations, so fewer units would "fire" at a given time. In Keras, this can be done by adding an activity_regularizer to our Dense layer:
End of explanation
autoencoder.compile(optimizer='adagrad', loss='binary_crossentropy')
autoencoder.fit(x_train, x_train,
epochs=250,
batch_size=25,
shuffle=True,
validation_data=(x_test, x_test))
Explanation: Let's train this model for 100 epochs (with the added regularization the model is less likely to overfit and can be trained longer).
End of explanation
# encode and decode some digits
# note that we take them from the *test* set
encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)
# use Matplotlib
import matplotlib.pyplot as plt
n = 10 # how many digits we will display
plt.figure(figsize=(20, 4))
for i in range(n):
# display original
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstruction
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow(decoded_imgs[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
Explanation: The models ends with a train loss of 0.1887 and test loss of 0.876. The difference between the two is mostly due to the regularization term being added to the loss during training (worth about 0.01).
Here's a visualization of our new results:
End of explanation
input_img = Input(shape=(784,))
encoded = Dense(128, activation='relu')(input_img)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(32, activation='relu')(encoded)
decoded = Dense(64, activation='relu')(encoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(784, activation='sigmoid')(decoded)
Explanation: Deep autoencoder
We do not have to limit ourselves to a single layer as encoder or decoder, we could instead use a stack of layers, such as:
End of explanation
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
autoencoder.fit(x_train, x_train,
epochs=100,
batch_size=100,
shuffle=True,
validation_data=(x_test, x_test))
Explanation: Let's try this:
End of explanation |
7,964 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
# Chapter 3
Step2: We present here the figure 3.2 in its original form in the book
Step3: Now we repeat the plot with seaborn
Step4: ## Monty Hall problem
We will simulate the Monty Hall problem where you pick one out of three boxes, the host eliminates one of the boxes (knowing the one that has the prize) and we want to see what is the probability of winning by keeping the first choice or by changing the choice
Step5: ## Plots with Bokeh
Step6: We are going to take advantage of the interactivity of Bokeh to plot several distributions presented along the chapter 3
Step7: An example of better estimators than the mean for distributions with heavy tails.
Step8: Here is an example of computing the components of a bivariate gaussian using a sample of 1000 data values with two levels of contamination. Figure 3.23.
The robust method implemented in astroML uses the robust estimator of the variance $\sigma_{G}$ and takes into account the correlation between parameters.
Step9: Correlation Coefficients
This section discusses the strengths and weaknesses of three techniques to measure to the sample correlation coefficient.
Pearson
Measurement errors are not used
Sensitive to outliers
Measures linear relationship
Spearman
Based on ranks (exactly Pearsons but on the ranks instead of the actual data).
Measures any kind of monotonic dependency
Kendall
Based on ranks (takes different between concordant and discordant pairs)
harder to compute than Spearman.
approaches normality faster than spearman
The nonparametric methods don't require knowledge of the distribution of the data to determine the distribution of the sample.
Ranks limit outliers to the value of their ranks.
Step10: 1-D Random Number generation
generate a uniform random number and apply the inverse CDF of the distribution of the type of random variable you would like to simulate.
This example shows how to clone a disribution and compute the inverse cdf with interpolation. | Python Code:
%pylab inline
import astroML
Explanation: # Chapter 3
End of explanation
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)
def banana_distribution(N=10000):
This generates random points in a banana shape
# create a truncated normal distribution
theta = np.random.normal(0, np.pi / 8, 10000)
theta[theta >= np.pi / 4] /= 2
theta[theta <= -np.pi / 4] /= 2
# define the curve parametrically
r = np.sqrt(1. / abs(np.cos(theta) ** 2 - np.sin(theta) ** 2))
r += np.random.normal(0, 0.08, size=10000)
x = r * np.cos(theta + np.pi / 4)
y = r * np.sin(theta + np.pi / 4)
return (x, y)
#------------------------------------------------------------
# Generate the data and compute the normalized 2D histogram
np.random.seed(1)
x, y = banana_distribution(10000)
Ngrid = 41
grid = np.linspace(0, 2, Ngrid + 1)
H, xbins, ybins = np.histogram2d(x, y, grid)
H /= np.sum(H)
#------------------------------------------------------------
# plot the result
fig = plt.figure(figsize=(15, 7.5)) ## We multiplied times 3 the size in both x and y axes to make it look bigger
# define axes
ax_Pxy = plt.axes((0.2, 0.34, 0.27, 0.52))
ax_Px = plt.axes((0.2, 0.14, 0.27, 0.2))
ax_Py = plt.axes((0.1, 0.34, 0.1, 0.52))
ax_cb = plt.axes((0.48, 0.34, 0.01, 0.52))
ax_Px_y = [plt.axes((0.65, 0.62, 0.32, 0.23)),
plt.axes((0.65, 0.38, 0.32, 0.23)),
plt.axes((0.65, 0.14, 0.32, 0.23))]
# set axis label formatters
ax_Px_y[0].xaxis.set_major_formatter(NullFormatter())
ax_Px_y[1].xaxis.set_major_formatter(NullFormatter())
ax_Pxy.xaxis.set_major_formatter(NullFormatter())
ax_Pxy.yaxis.set_major_formatter(NullFormatter())
ax_Px.yaxis.set_major_formatter(NullFormatter())
ax_Py.xaxis.set_major_formatter(NullFormatter())
# draw the joint probability
plt.axes(ax_Pxy)
H *= 1000
plt.imshow(H, interpolation='nearest', origin='lower', aspect='auto',
extent=[0, 2, 0, 2], cmap=plt.cm.binary)
cb = plt.colorbar(cax=ax_cb)
cb.set_label('$p(x, y)$')
plt.text(0, 1.02, r'$\times 10^{-3}$',
transform=ax_cb.transAxes)
# draw p(x) distribution
ax_Px.plot(xbins[1:], H.sum(0), '-k', drawstyle='steps')
# draw p(y) distribution
ax_Py.plot(H.sum(1), ybins[1:], '-k', drawstyle='steps')
# define axis limits
ax_Pxy.set_xlim(0, 2)
ax_Pxy.set_ylim(0, 2)
ax_Px.set_xlim(0, 2)
ax_Py.set_ylim(0, 2)
# label axes
ax_Pxy.set_xlabel('$x$')
ax_Pxy.set_ylabel('$y$')
ax_Px.set_xlabel('$x$')
ax_Px.set_ylabel('$p(x)$')
ax_Px.yaxis.set_label_position('right')
ax_Py.set_ylabel('$y$')
ax_Py.set_xlabel('$p(y)$')
ax_Py.xaxis.set_label_position('top')
# draw marginal probabilities
iy = [3 * Ngrid / 4, Ngrid / 2, Ngrid / 4]
colors = 'rgc'
axis = ax_Pxy.axis()
for i in range(3):
# overplot range on joint probability
ax_Pxy.plot([0, 2, 2, 0],
[ybins[iy[i] + 1], ybins[iy[i] + 1],
ybins[iy[i]], ybins[iy[i]]], c=colors[i], lw=1)
Px_y = H[iy[i]] / H[iy[i]].sum()
ax_Px_y[i].plot(xbins[1:], Px_y, drawstyle='steps', c=colors[i])
ax_Px_y[i].yaxis.set_major_formatter(NullFormatter())
ax_Px_y[i].set_ylabel('$p(x | %.1f)$' % ybins[iy[i]])
ax_Pxy.axis(axis)
ax_Px_y[2].set_xlabel('$x$')
ax_Pxy.set_title('Joint Probability')
ax_Px_y[0].set_title('Conditional Probability')
plt.show()
Explanation: We present here the figure 3.2 in its original form in the book
End of explanation
import seaborn as sns
import pandas as pd
data = (x,y)
data = np.array(data)
data = data.T
df = pd.DataFrame(data, columns=["x", "y"])
g = sns.jointplot(x="x", y="y",data=df, kind="hex", marginal_kws={"bins":41*41/2}, gridsize=41*41/2, xlim=(0,2), ylim=(0,2))
cond1 = (y>=0.5-2./41.) & (y<=0.5+2./41.)
cond2 = (y>=1.0-2./41.) & (y<=1.0+2./41.)
cond3 = (y>=1.5-2./41.) & (y<=1.5+2./41.)
sns.__version__
weights = np.ones(10000)*1./10000.
g1 = sns.distplot(x[cond1],hist=True, color='cyan', kde=False, hist_kws={'weights':weights[cond1]})
g2 = sns.distplot(x[cond2],hist=True, color='green', kde=False, hist_kws={'weights':weights[cond2]})
g3 = sns.distplot(x[cond3],hist=True, color='red', kde=False, hist_kws={'weights':weights[cond3]})
Explanation: Now we repeat the plot with seaborn
End of explanation
orig_choice = np.random.random_integers(1,3,size=10000)
correct_choice = np.random.random_integers(1,3,size=10000)
change_mind = np.zeros(10000)
host_choice = np.zeros(10000)
choice = [1,2,3]
for i in range(0,10000):
if(orig_choice[i]==correct_choice[i]):
host_choice[i]=choice[correct_choice[i]-2]
else:
host_choice[i]=6-correct_choice[i]-orig_choice[i]
change_mind[i]=6-orig_choice[i]-host_choice[i]
[x]=np.where(change_mind==correct_choice)
[y]=np.where(orig_choice==correct_choice)
print len(x)/10000., len(y)/10000.
Explanation: ## Monty Hall problem
We will simulate the Monty Hall problem where you pick one out of three boxes, the host eliminates one of the boxes (knowing the one that has the prize) and we want to see what is the probability of winning by keeping the first choice or by changing the choice
End of explanation
from ipywidgets import interact
from bokeh.io import push_notebook
from bokeh.plotting import figure, output_file, show
from bokeh.plotting import output_notebook
output_notebook()
Explanation: ## Plots with Bokeh
End of explanation
from scipy import stats
xd = np.linspace(0,10,100)
dist = stats.norm(0,1)
yd=dist.pdf(xd)
pp = figure(title="Probability distribution plot", plot_height=300, plot_width=600, y_range=(0.05,1.05))
rr = pp.line(xd,yd,color="red",line_width=3)
def pdist(f,par1=0,par2=1):
if f=="Gaussian": dist = stats.norm(par1,par2); rr.data_source.data['y']=dist.pdf(xd)
if f=="Uniform": dist = stats.uniform(par1,par2); rr.data_source.data['y']=dist.pdf(xd)
if f=="Binomial": dist = stats.binom(par1,par2); rr.data_source.data['y']=dist.pmf(xd)
if f=="Poisson": dist = stats.poisson(par1); rr.data_source.data['y']=dist.pmf(xd)
if f=="Cauchy": dist = stats.cauchy(par1,par2); rr.data_source.data['y']=dist.pdf(xd)
if f=="Laplace": dist = stats.laplace(par1,par2); rr.data_source.data['y']=dist.pdf(xd)
if f=="Chi2": dist = stats.chi2(par1); rr.data_source.data['y']=dist.pdf(xd)
if f=="Student t": dist = stats.t(par1); rr.data_source.data['y']=dist.pdf(xd)
if f=="Fisher f": dist = stats.f(par1,par2); rr.data_source.data['y']=dist.pdf(xd)
if f=="Beta": dist = stats.beta(par1,par2); rr.data_source.data['y']=dist.pdf(xd)
if f=="Gamma": dist = stats.gamma(par1,par2); rr.data_source.data['y']=dist.pdf(xd)
if f=="Weibull": dist = stats.dweibull(par1,0,par2); rr.data_source.data['y']=dist.pdf(xd)
push_notebook()
show(pp)
interact(pdist,f=["Gaussian","Uniform","Binomial","Poisson","Cauchy","Chi2","Laplace","Student t","Fisher f","Beta","Gamma","Weibull"],par1=(0,10),par2=(0,10))
nsamples = 10
x = np.random.uniform(size=nsamples)
xp = np.zeros(nsamples)
for i in range(0,nsamples):
xp[i]=np.mean(x[0:i])-0.5
hist, edges = np.histogram(xp,bins=100, range=(-1,1))
p = figure(title="Central Limit Theorem interactive demo", plot_height=300, plot_width=600)
r = p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
fill_color="#036564", line_color="#033649")
def update(nsamples=1):
np.random.seed(123)
x = np.random.uniform(size=nsamples)
xp = np.zeros(nsamples)
for i in range(0,nsamples):
xp[i]=np.mean(x[0:i])-0.5
hist, edges = np.histogram(xp,bins=100, range=(-1,1))
r.data_source.data['top']=hist
push_notebook()
show(p)
interact(update,nsamples=(1,500))
Explanation: We are going to take advantage of the interactivity of Bokeh to plot several distributions presented along the chapter 3
End of explanation
from scipy.stats import uniform
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)
#------------------------------------------------------------
# Generate the random distribution
N = (10 ** np.linspace(2, 4, 1000)).astype(int)
mu = 0
W = 2
rng = uniform(mu - 0.5 * W, W) # uniform distribution between mu-W and mu+W
#------------------------------------------------------------
# Compute the cumulative mean and min/max estimator of the sample
mu_estimate_mean = np.zeros(N.shape)
mu_estimate_minmax = np.zeros(N.shape)
for i in xrange(len(N)):
x = rng.rvs(N[i]) # generate N[i] uniformly distributed values
mu_estimate_mean[i] = np.mean(x)
mu_estimate_minmax[i] = 0.5 * (np.min(x) + np.max(x))
# compute the expected scalings of the estimator uncertainties
N_scaling = 2. * W / N / np.sqrt(12)
root_N_scaling = W / np.sqrt(N * 12)
#------------------------------------------------------------
# Plot the results
fig = plt.figure(figsize=(10, 7))
fig.subplots_adjust(hspace=0, bottom=0.15, left=0.15)
# upper plot: mean statistic
ax = fig.add_subplot(211, xscale='log')
ax.scatter(N, mu_estimate_mean, c='b', lw=0, s=4)
# draw shaded sigma contours
for nsig in (1, 2, 3):
ax.fill(np.hstack((N, N[::-1])),
np.hstack((nsig * root_N_scaling,
-nsig * root_N_scaling[::-1])), 'b', alpha=0.2)
ax.set_xlim(N[0], N[-1])
ax.set_ylim(-0.199, 0.199)
ax.set_ylabel(r'$\bar{\mu}$')
ax.xaxis.set_major_formatter(plt.NullFormatter())
ax.text(0.99, 0.95,
r'$\bar\mu = \mathrm{mean}(x)$',
ha='right', va='top', transform=ax.transAxes)
ax.text(0.99, 0.02,
r'$\sigma = \frac{1}{\sqrt{12}}\cdot\frac{W}{\sqrt{N}}$',
ha='right', va='bottom', transform=ax.transAxes)
# lower plot: min/max statistic
ax = fig.add_subplot(212, xscale='log')
ax.scatter(N, mu_estimate_minmax, c='g', lw=0, s=4)
# draw shaded sigma contours
for nsig in (1, 2, 3):
ax.fill(np.hstack((N, N[::-1])),
np.hstack((nsig * N_scaling,
-nsig * N_scaling[::-1])), 'g', alpha=0.2)
ax.set_xlim(N[0], N[-1])
ax.set_ylim(-0.0399, 0.0399)
ax.set_xlabel('$N$')
ax.set_ylabel(r'$\bar{\mu}$')
ax.text(0.99, 0.95,
r'$\bar\mu = \frac{1}{2}[\mathrm{max}(x) + \mathrm{min}(x)]$',
ha='right', va='top', transform=ax.transAxes)
ax.text(0.99, 0.02,
r'$\sigma = \frac{1}{\sqrt{12}}\cdot\frac{2W}{N}$',
ha='right', va='bottom', transform=ax.transAxes)
plt.show()
Explanation: An example of better estimators than the mean for distributions with heavy tails.
End of explanation
import numpy as np
from scipy import stats
from matplotlib import pyplot as plt
from matplotlib.patches import Ellipse
from astroML.stats import fit_bivariate_normal
from astroML.stats.random import bivariate_normal
# percent sign needs to be escaped if usetex is activated
import matplotlib
if matplotlib.rcParams.get('text.usetex'):
pct = r'\%'
else:
pct = r'%'
#----------------------------------------------------------------------
# This function adjusts matplotlib settings for a uniform feel in the textbook.
# Note that with usetex=True, fonts are rendered with LaTeX. This may
# result in an error if LaTeX is not installed on your system. In that case,
# you can set usetex to False.
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)
N = 1000
sigma1 = 2.0
sigma2 = 1.0
mu = [10, 10]
alpha_deg = 45.0
alpha = alpha_deg * np.pi / 180
#------------------------------------------------------------
# Draw N points from a multivariate normal distribution
#
# we use the bivariate_normal function from astroML. A more
# general function for this is numpy.random.multivariate_normal(),
# which requires the user to specify the full covariance matrix.
# bivariate_normal() generates this covariance matrix for the
# given inputs
np.random.seed(0)
X = bivariate_normal(mu, sigma1, sigma2, alpha, N)
#------------------------------------------------------------
# Create the figure showing the fits
fig = plt.figure(figsize=(15, 7.5)) ##3 times the original size
fig.subplots_adjust(left=0.1, right=0.95, wspace=0.05,
bottom=0.15, top=0.95)
# We'll create two figures, with two levels of contamination
for i, f in enumerate([0.05, 0.15]):
ax = fig.add_subplot(1, 2, i + 1)
# add outliers distributed using a bivariate normal.
X[:int(f * N)] = bivariate_normal((10, 10), 2, 4,
45 * np.pi / 180., int(f * N))
x, y = X.T
# compute the non-robust statistics
(mu_nr, sigma1_nr,
sigma2_nr, alpha_nr) = fit_bivariate_normal(x, y, robust=False)
# compute the robust statistics
(mu_r, sigma1_r,
sigma2_r, alpha_r) = fit_bivariate_normal(x, y, robust=True)
# scatter the points
ax.scatter(x, y, s=2, lw=0, c='k', alpha=0.5)
# Draw elipses showing the fits
for Nsig in [1, 3]:
# True fit
E = Ellipse((10, 10), sigma1 * Nsig, sigma2 * Nsig, alpha_deg,
ec='k', fc='none')
ax.add_patch(E)
# Non-robust fit
E = Ellipse(mu_nr, sigma1_nr * Nsig, sigma2_nr * Nsig,
(alpha_nr * 180. / np.pi),
ec='k', fc='none', linestyle='dotted')
ax.add_patch(E)
# Robust fit
E = Ellipse(mu_r, sigma1_r * Nsig, sigma2_r * Nsig,
(alpha_r * 180. / np.pi),
ec='k', fc='none', linestyle='dashed')
ax.add_patch(E)
ax.text(0.04, 0.96, '%i%s outliers' % (f * 100, pct),
ha='left', va='top', transform=ax.transAxes)
ax.set_xlim(5.5, 14.5)
ax.set_ylim(5.5, 14.5)
ax.set_xlabel('$x$')
# This is a bit of a hack:
# We'll draw some lines off the picture to make our legend look better
ax.plot([0], [0], '-k', label='Input')
ax.plot([0], [0], ':k', label='Fit')
ax.plot([0], [0], '--k', label='Robust Fit')
ax.legend(loc='lower right')
if i == 0:
ax.set_ylabel('$y$')
else:
ax.yaxis.set_major_formatter(plt.NullFormatter())
plt.show()
Explanation: Here is an example of computing the components of a bivariate gaussian using a sample of 1000 data values with two levels of contamination. Figure 3.23.
The robust method implemented in astroML uses the robust estimator of the variance $\sigma_{G}$ and takes into account the correlation between parameters.
End of explanation
from astroML.stats.random import bivariate_normal
from astroML.decorators import pickle_results
# percent sign must be escaped if usetex=True
import matplotlib
if matplotlib.rcParams.get('text.usetex'):
pct = '\%'
else:
pct = '%'
#----------------------------------------------------------------------
# This function adjusts matplotlib settings for a uniform feel in the textbook.
# Note that with usetex=True, fonts are rendered with LaTeX. This may
# result in an error if LaTeX is not installed on your system. In that case,
# you can set usetex to False.
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)
#------------------------------------------------------------
# Set parameters for the distributions
Nbootstraps = 5000
N = 1000
sigma1 = 2.0
sigma2 = 1.0
mu = (10.0, 10.0)
alpha_deg = 45.0
alpha = alpha_deg * np.pi / 180
f = 0.01
#------------------------------------------------------------
# sample the distribution
# without outliers and with outliers
np.random.seed(0)
X = bivariate_normal(mu, sigma1, sigma2, alpha, N)
X_out = X.copy()
X_out[:int(f * N)] = bivariate_normal(mu, 2, 5,
45 * np.pi / 180., int(f * N))
# true values of rho (pearson/spearman r) and tau
# tau value comes from Eq. 41 of arXiv:1011.2009
rho_true = 0.6
tau_true = 2 / np.pi * np.arcsin(rho_true)
#------------------------------------------------------------
# Create a function to compute the statistics. Since this
# takes a while, we'll use the "pickle_results" decorator
# to save the results of the computation to disk
@pickle_results('fig_correlations_dump.pkl')
def compute_results(N, Nbootstraps):
results = np.zeros((3, 2, Nbootstraps))
for k in range(Nbootstraps):
ind = np.random.randint(N, size=N)
for j, data in enumerate([X, X_out]):
x = data[ind, 0]
y = data[ind, 1]
for i, statistic in enumerate([stats.pearsonr,
stats.spearmanr,
stats.kendalltau]):
results[i, j, k] = statistic(x, y)[0]
return results
results = compute_results(N, Nbootstraps)
#------------------------------------------------------------
# Plot the results in a three-panel plot
fig = plt.figure(figsize=(10, 10))
fig.subplots_adjust(bottom=0.1, top=0.95, hspace=0.25)
histargs = (dict(alpha=0.5, label='No Outliers'),
dict(alpha=0.8, label='%i%s Outliers' % (int(f * 100), pct)))
distributions = ['Pearson-r', 'Spearman-r', r'Kendall-$\tau$']
xlabels = ['r_p', 'r_s', r'\tau']\
for i in range(3):
ax = fig.add_subplot(311 + i)
for j in range(2):
ax.hist(results[i, j], 40, histtype='stepfilled', fc='gray',
normed=True, **histargs[j])
if i == 0:
ax.legend(loc=2)
ylim = ax.get_ylim()
if i < 2:
ax.plot([rho_true, rho_true], ylim, '--k', lw=1)
ax.set_xlim(0.34, 0.701)
else:
ax.plot([tau_true, tau_true], ylim, '--k', lw=1)
ax.set_xlim(0.31, 0.48)
ax.set_ylim(ylim)
ax.text(0.98, 0.95, distributions[i], ha='right', va='top',
transform=ax.transAxes, bbox=dict(fc='w', ec='w'))
ax.set_xlabel('$%s$' % xlabels[i])
ax.set_ylabel('$N(%s)$' % xlabels[i])
plt.show()
Explanation: Correlation Coefficients
This section discusses the strengths and weaknesses of three techniques to measure to the sample correlation coefficient.
Pearson
Measurement errors are not used
Sensitive to outliers
Measures linear relationship
Spearman
Based on ranks (exactly Pearsons but on the ranks instead of the actual data).
Measures any kind of monotonic dependency
Kendall
Based on ranks (takes different between concordant and discordant pairs)
harder to compute than Spearman.
approaches normality faster than spearman
The nonparametric methods don't require knowledge of the distribution of the data to determine the distribution of the sample.
Ranks limit outliers to the value of their ranks.
End of explanation
from scipy import stats, interpolate
from astroML.plotting import hist
from astroML.density_estimation import EmpiricalDistribution
#----------------------------------------------------------------------
# This function adjusts matplotlib settings for a uniform feel in the textbook.
# Note that with usetex=True, fonts are rendered with LaTeX. This may
# result in an error if LaTeX is not installed on your system. In that case,
# you can set usetex to False.
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)
#------------------------------------------------------------å
# Create a distribution and clone it
Ndata = 1000
Nclone = 100000
np.random.seed(0)
# generate an 'observed' bimodal distribution with 10000 values
dists = (stats.norm(-1.3, 0.5), stats.norm(1.3, 0.5))
fracs = (0.6, 0.4)
x = np.hstack((d.rvs(f * Ndata) for d, f in zip(dists, fracs)))
# We can clone the distribution easily with this function
x_cloned = EmpiricalDistribution(x).rvs(Nclone)
# compute the KS test to check if they're the same
D, p = stats.ks_2samp(x, x_cloned)
print "KS test: D = %.2g; p = %.2g" % (D, p)
#------------------------------------------------------------
# For the sake of this example, we need to calculate some
# of the partial steps used by EmpiricalDistribution
# create a cumulative distribution
x.sort()
Px_cuml = np.linspace(0, 1, Ndata)
# set up an interpolation of the inverse cumulative distribution
tck = interpolate.splrep(Px_cuml, x)
# sample evenly along the cumulative distribution, and interpolate
Px_cuml_sample = np.linspace(0, 1, 10 * Ndata)
x_sample = interpolate.splev(Px_cuml_sample, tck)
#------------------------------------------------------------
# Plot the cloned distribution and the procedure for obtaining it
fig = plt.figure(figsize=(10, 10))
fig.subplots_adjust(hspace=0.3, left=0.1, right=0.95,
bottom=0.08, top=0.92)
indices = np.linspace(0, Ndata - 1, 20).astype(int)
# plot a histogram of the input
ax = fig.add_subplot(221)
hist(x, bins='knuth', ax=ax,
histtype='stepfilled', ec='k', fc='#AAAAAA')
ax.set_ylim(0, 300)
ax.set_title('Input data distribution')
ax.set_xlabel('$x$')
ax.set_ylabel('$N(x)$')
# plot the cumulative distribution
ax = fig.add_subplot(222)
ax.scatter(x[indices], Px_cuml[indices], lw=0, c='k', s=9)
ax.plot(x, Px_cuml, '-k')
ax.set_xlim(-3, 3)
ax.set_ylim(-0.05, 1.05)
ax.set_title('Cumulative Distribution')
ax.set_xlabel('$x$')
ax.set_ylabel('$p(<x)$')
# plot the inverse cumulative distribution and spline fit
ax = fig.add_subplot(223)
ax.scatter(Px_cuml[indices], x[indices], lw=0, c='k', s=9)
ax.plot(Px_cuml_sample, x_sample, '-k')
ax.arrow(0.7, -3, 0, 3.5, width=0.015, fc='gray', ec='gray',
head_width=0.05, head_length=0.4)
ax.arrow(0.7, 0.9, -0.69, 0, width=0.1, fc='gray', ec='gray',
head_width=0.3, head_length=0.06)
ax.set_xlim(-0.05, 1.05)
ax.set_ylim(-3, 3)
ax.set_title('Inverse Cuml. Distribution')
ax.set_xlabel('$p(<x)$')
ax.set_ylabel('$x$')
# plot the resulting cloned distribution
ax = fig.add_subplot(224)
hist(x, bins='knuth', ax=ax,
histtype='stepfilled', normed=True,
ec='#AAAAAA', fc='#DDDDDD',
label='input data')
hist(x_cloned, bins='knuth', ax=ax,
histtype='step', normed=True,
color='k', label='cloned data')
ax.set_title('Cloned Distribution')
ax.set_xlabel('$x$')
ax.set_ylabel('$p(x)dx$')
ax.text(0.75, 0.95, "KS test:\nD = %.2f\np = %.2f" % (D, p),
ha='left', va='top', transform=ax.transAxes)
plt.show()
Explanation: 1-D Random Number generation
generate a uniform random number and apply the inverse CDF of the distribution of the type of random variable you would like to simulate.
This example shows how to clone a disribution and compute the inverse cdf with interpolation.
End of explanation |
7,965 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Titanic Data Science Solutions
This notebook is companion to the book Data Science Solutions. The notebook walks us through a typical workflow for solving data science competitions at sites like Kaggle.
There are several excellent notebooks to study data science competition entries. However many will skip some of the explanation on how the solution is developed as these notebooks are developed by experts for experts. The objective of this notebook is to follow a step-by-step workflow, explaining each step and rationale for every decision we take during solution development.
Workflow stages
The competition solution workflow goes through seven stages described in the Data Science Solutions book.
Question or problem definition.
Acquire training and testing data.
Wrangle, prepare, cleanse the data.
Analyze, identify patterns, and explore the data.
Model, predict and solve the problem.
Visualize, report, and present the problem solving steps and final solution.
Supply or submit the results.
The workflow indicates general sequence of how each stage may follow the other. However there are use cases with exceptions.
We may combine mulitple workflow stages. We may analyze by visualizing data.
Perform a stage earlier than indicated. We may analyze data before and after wrangling.
Perform a stage multiple times in our workflow. Visualize stage may be used multiple times.
Drop a stage altogether. We may not need supply stage to productize or service enable our dataset for a competition.
Question and problem definition
Competition sites like Kaggle define the problem to solve or questions to ask while providing the datasets for training your data science model and testing the model results against a test dataset. The question or problem definition for Titanic Survival competition is described here at Kaggle.
Knowing from a training set of samples listing passengers who survived or did not survive the Titanic disaster, can our model determine based on a given test dataset not containing the survival information, if these passengers in the test dataset survived or not.
We may also want to develop some early understanding about the domain of our problem. This is described on the Kaggle competition description page here. Here are the highlights to note.
On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. Translated 32% survival rate.
One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew.
Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class.
Workflow goals
The data science solutions workflow solves for seven major goals.
Classifying. We may want to classify or categorize our samples. We may also want to understand the implications or correlation of different classes with our solution goal.
Correlating. One can approach the problem based on available features within the training dataset. Which features within the dataset contribute significantly to our solution goal? Statistically speaking is there a correlation among a feature and solution goal? As the feature values change does the solution state change as well, and visa-versa? This can be tested both for numerical and categorical features in the given dataset. We may also want to determine correlation among features other than survival for subsequent goals and workflow stages. Correlating certain features may help in creating, completing, or correcting features.
Converting. For modeling stage, one needs to prepare the data. Depending on the choice of model algorithm one may require all features to be converted to numerical equivalent values. So for instance converting text categorical values to numeric values.
Completing. Data preparation may also require us to estimate any missing values within a feature. Model algorithms may work best when there are no missing values.
Correcting. We may also analyze the given training dataset for errors or possibly innacurate values within features and try to corrent these values or exclude the samples containing the errors. One way to do this is to detect any outliers among our samples or features. We may also completely discard a feature if it is not contribting to the analysis or may significantly skew the results.
Creating. Can we create new features based on an existing feature or a set of features, such that the new feature follows the correlation, conversion, completeness goals.
Charting. How to select the right visualization plots and charts depending on nature of the data and the solution goals. A good start is to read the Tableau paper on Which chart or graph is right for you?.
Refactor Release 2017-Jan-29
We are significantly refactoring the notebook based on (a) comments received by readers, (b) issues in porting notebook from Jupyter kernel (2.7) to Kaggle kernel (3.5), and (c) review of few more best practice kernels.
User comments
Combine training and test data for certain operations like converting titles across dataset to numerical values. (thanks @Sharan Naribole)
Correct observation - nearly 30% of the passengers had siblings and/or spouses aboard. (thanks @Reinhard)
Correctly interpreting logistic regresssion coefficients. (thanks @Reinhard)
Porting issues
Specify plot dimensions, bring legend into plot.
Best practices
Performing feature correlation analysis early in the project.
Using multiple plots instead of overlays for readability.
Step1: Acquire data
The Python Pandas packages helps us work with our datasets. We start by acquiring the training and testing datasets into Pandas DataFrames. We also combine these datasets to run certain operations on both datasets together.
Step2: Analyze by describing data
Pandas also helps describe the datasets answering following questions early in our project.
Which features are available in the dataset?
Noting the feature names for directly manipulating or analyzing these. These feature names are described on the Kaggle data page here.
Step3: Which features are categorical?
These values classify the samples into sets of similar samples. Within categorical features are the values nominal, ordinal, ratio, or interval based? Among other things this helps us select the appropriate plots for visualization.
Categorical
Step4: Which features are mixed data types?
Numerical, alphanumeric data within same feature. These are candidates for correcting goal.
Ticket is a mix of numeric and alphanumeric data types. Cabin is alphanumeric.
Which features may contain errors or typos?
This is harder to review for a large dataset, however reviewing a few samples from a smaller dataset may just tell us outright, which features may require correcting.
Name feature may contain errors or typos as there are several ways used to describe a name including titles, round brackets, and quotes used for alternative or short names.
Step5: Which features contain blank, null or empty values?
These will require correcting.
Cabin > Age > Embarked features contain a number of null values in that order for the training dataset.
Cabin > Age are incomplete in case of test dataset.
What are the data types for various features?
Helping us during converting goal.
Seven features are integer or floats. Six in case of test dataset.
Five features are strings (object).
Step6: What is the distribution of numerical feature values across the samples?
This helps us determine, among other early insights, how representative is the training dataset of the actual problem domain.
Total samples are 891 or 40% of the actual number of passengers on board the Titanic (2,224).
Survived is a categorical feature with 0 or 1 values.
Around 38% samples survived representative of the actual survival rate at 32%.
Most passengers (> 75%) did not travel with parents or children.
Nearly 30% of the passengers had siblings and/or spouse aboard.
Fares varied significantly with few passengers (<1%) paying as high as $512.
Few elderly passengers (<1%) within age range 65-80.
Step7: What is the distribution of categorical features?
Names are unique across the dataset (count=unique=891)
Sex variable as two possible values with 65% male (top=male, freq=577/count=891).
Cabin values have several dupicates across samples. Alternatively several passengers shared a cabin.
Embarked takes three possible values. S port used by most passengers (top=S)
Ticket feature has high ratio (22%) of duplicate values (unique=681).
Step8: Assumtions based on data analysis
We arrive at following assumptions based on data analysis done so far. We may validate these assumptions further before taking appropriate actions.
Correlating.
We want to know how well does each feature correlate with Survival. We want to do this early in our project and match these quick correlations with modelled correlations later in the project.
Completing.
We may want to complete Age feature as it is definitely correlated to survival.
We may want to complete the Embarked feature as it may also correlate with survival or another important feature.
Correcting.
Ticket feature may be dropped from our analysis as it contains high ratio of duplicates (22%) and there may not be a correlation between Ticket and survival.
Cabin feature may be dropped as it is highly incomplete or contains many null values both in training and test dataset.
PassengerId may be dropped from training dataset as it does not contribute to survival.
Name feature is relatively non-standard, may not contribute directly to survival, so maybe dropped.
Creating.
We may want to create a new feature called Family based on Parch and SibSp to get total count of family members on board.
We may want to engineer the Name feature to extract Title as a new feature.
We may want to create new feature for Age bands. This turns a continous numerical feature into an ordinal categorical feature.
We may also want to create a Fare range feature if it helps our analysis.
Classifying.
We may also add to our assumptions based on the problem description noted earlier.
Women (Sex=female) were more likely to have survived.
Children (Age<?) were more likely to have survived.
The upper-class passengers (Pclass=1) were more likely to have survived.
Analyze by pivoting features
To confirm some of our observations and assumptions, we can quickly analyze our feature correlations by pivoting features against each other. We can only do so at this stage for features which do not have any empty values. It also makes sense doing so only for features which are categorical (Sex), ordinal (Pclass) or discrete (SibSp, Parch) type.
Pclass We observe significant correlation (>0.5) among Pclass=1 and Survived (classifying #3). We decide to include this feature in our model.
Sex We confirm the observation during problem definition that Sex=female had very high survival rate at 74% (classifying #1).
SibSp and Parch These features have zero correlation for certain values. It may be best to derive a feature or a set of features from these individual features (creating #1).
Step9: Analyze by visualizing data
Now we can continue confirming some of our assumptions using visualizations for analyzing the data.
Correlating numerical features
Let us start by understanding correlations between numerical features and our solution goal (Survived).
A histogram chart is useful for analyzing continous numerical variables like Age where banding or ranges will help identify useful patterns. The histogram can indicate distribution of samples using automatically defined bins or equally ranged bands. This helps us answer questions relating to specific bands (Did infants have better survival rate?)
Note that x-axis in historgram visualizations represents the count of samples or passengers.
Observations.
Infants (Age <=4) had high survival rate.
Oldest passengers (Age = 80) survived.
Large number of 15-25 year olds did not survive.
Most passengers are in 15-35 age range.
Decisions.
This simple analysis confirms our assumptions as decisions for subsequent workflow stages.
We should consider Age (our assumption classifying #2) in our model training.
Complete the Age feature for null values (completing #1).
We should band age groups (creating #3).
Step10: Correlating numerical and ordinal features
We can combine multiple features for identifying correlations using a single plot. This can be done with numerical and categorical features which have numeric values.
Observations.
Pclass=3 had most passengers, however most did not survive. Confirms our classifying assumption #2.
Infant passengers in Pclass=2 and Pclass=3 mostly survived. Further qualifies our classifying assumption #2.
Most passengers in Pclass=1 survived. Confirms our classifying assumption #3.
Pclass varies in terms of Age distribution of passengers.
Decisions.
Consider Pclass for model training.
Step11: Correlating categorical features
Now we can correlate categorical features with our solution goal.
Observations.
Female passengers had much better survival rate than males. Confirms classifying (#1).
Exception in Embarked=C where males had higher survival rate. This could be a correlation between Pclass and Embarked and in turn Pclass and Survived, not necessarily direct correlation between Embarked and Survived.
Males had better survival rate in Pclass=3 when compared with Pclass=2 for C and Q ports. Completing (#2).
Ports of embarkation have varying survival rates for Pclass=3 and among male passengers. Correlating (#1).
Decisions.
Add Sex feature to model training.
Complete and add Embarked feature to model training.
Step12: Correlating categorical and numerical features
We may also want to correlate categorical features (with non-numeric values) and numeric features. We can consider correlating Embarked (Categorical non-numeric), Sex (Categorical non-numeric), Fare (Numeric continuous), with Survived (Categorical numeric).
Observations.
Higher fare paying passengers had better survival. Confirms our assumption for creating (#4) fare ranges.
Port of embarkation correlates with survival rates. Confirms correlating (#1) and completing (#2).
Decisions.
Consider banding Fare feature.
Step13: Wrangle data
We have collected several assumptions and decisions regarding our datasets and solution requirements. So far we did not have to change a single feature or value to arrive at these. Let us now execute our decisions and assumptions for correcting, creating, and completing goals.
Correcting by dropping features
This is a good starting goal to execute. By dropping features we are dealing with fewer data points. Speeds up our notebook and eases the analysis.
Based on our assumptions and decisions we want to drop the Cabin (correcting #2) and Ticket (correcting #1) features.
Note that where applicable we perform operations on both training and testing datasets together to stay consistent.
Step14: Creating new feature extracting from existing
We want to analyze if Name feature can be engineered to extract titles and test correlation between titles and survival, before dropping Name and PassengerId features.
In the following code we extract Title feature using regular expressions. The RegEx pattern (\w+\.) matches the first word which ends with a dot character within Name feature. The expand=False flag returns a DataFrame.
Observations.
When we plot Title, Age, and Survived, we note the following observations.
Most titles band Age groups accurately. For example
Step15: We can replace many titles with a more common name or classify them as Rare.
Step16: We can convert the categorical titles to ordinal.
Step17: Now we can safely drop the Name feature from training and testing datasets. We also do not need the PassengerId feature in the training dataset.
Step18: Converting a categorical feature
Now we can convert features which contain strings to numerical values. This is required by most model algorithms. Doing so will also help us in achieving the feature completing goal.
Let us start by converting Sex feature to a new feature called Gender where female=1 and male=0.
Step19: Completing a numerical continuous feature
Now we should start estimating and completing features with missing or null values. We will first do this for the Age feature.
We can consider three methods to complete a numerical continuous feature.
A simple way is to generate random numbers between mean and standard deviation.
More accurate way of guessing missing values is to use other correlated features. In our case we note correlation among Age, Gender, and Pclass. Guess Age values using median values for Age across sets of Pclass and Gender feature combinations. So, median Age for Pclass=1 and Gender=0, Pclass=1 and Gender=1, and so on...
Combine methods 1 and 2. So instead of guessing age values based on median, use random numbers between mean and standard deviation, based on sets of Pclass and Gender combinations.
Method 1 and 3 will introduce random noise into our models. The results from multiple executions might vary. We will prefer method 2.
Step20: Let us start by preparing an empty array to contain guessed Age values based on Pclass x Gender combinations.
Step21: Now we iterate over Sex (0 or 1) and Pclass (1, 2, 3) to calculate guessed values of Age for the six combinations.
Step22: Let us create Age bands and determine correlations with Survived.
Step23: Let us replace Age with ordinals based on these bands.
Step24: We can not remove the AgeBand feature.
Step25: Create new feature combining existing features
We can create a new feature for FamilySize which combines Parch and SibSp. This will enable us to drop Parch and SibSp from our datasets.
Step26: We can create another feature called IsAlone.
Step27: Let us drop Parch, SibSp, and FamilySize features in favor of IsAlone.
Step28: We can also create an artificial feature combining Pclass and Age.
Step29: Completing a categorical feature
Embarked feature takes S, Q, C values based on port of embarkation. Our training dataset has two missing values. We simply fill these with the most common occurance.
Step30: Converting categorical feature to numeric
We can now convert the EmbarkedFill feature by creating a new numeric Port feature.
Step31: Quick completing and converting a numeric feature
We can now complete the Fare feature for single missing value in test dataset using mode to get the value that occurs most frequently for this feature. We do this in a single line of code.
Note that we are not creating an intermediate new feature or doing any further analysis for correlation to guess missing feature as we are replacing only a single value. The completion goal achieves desired requirement for model algorithm to operate on non-null values.
We may also want round off the fare to two decimals as it represents currency.
Step32: We can not create FareBand.
Step33: Convert the Fare feature to ordinal values based on the FareBand.
Step34: And the test dataset.
Step35: Model, predict and solve
Now we are ready to train a model and predict the required solution. There are 60+ predictive modelling algorithms to choose from. We must understand the type of problem and solution requirement to narrow down to a select few models which we can evaluate. Our problem is a classification and regression problem. We want to identify relationship between output (Survived or not) with other variables or features (Gender, Age, Port...). We are also perfoming a category of machine learning which is called supervised learning as we are training our model with a given dataset. With these two criteria - Supervised Learning plus Classification and Regression, we can narrow down our choice of models to a few. These include
Step36: Logistic Regression is a useful model to run early in the workflow. Logistic regression measures the relationship between the categorical dependent variable (feature) and one or more independent variables (features) by estimating probabilities using a logistic function, which is the cumulative logistic distribution. Reference Wikipedia.
Note the confidence score generated by the model based on our training dataset.
Step37: We can use Logistic Regression to validate our assumptions and decisions for feature creating and completing goals. This can be done by calculating the coefficient of the features in the decision function.
Positive coefficients increase the log-odds of the response (and thus increase the probability), and negative coefficients decrease the log-odds of the response (and thus decrease the probability).
Sex is highest positivie coefficient, implying as the Sex value increases (male
Step38: Next we model using Support Vector Machines which are supervised learning models with associated learning algorithms that analyze data used for classification and regression analysis. Given a set of training samples, each marked as belonging to one or the other of two categories, an SVM training algorithm builds a model that assigns new test samples to one category or the other, making it a non-probabilistic binary linear classifier. Reference Wikipedia.
Note that the model generates a confidence score which is higher than Logistics Regression model.
Step39: In pattern recognition, the k-Nearest Neighbors algorithm (or k-NN for short) is a non-parametric method used for classification and regression. A sample is classified by a majority vote of its neighbors, with the sample being assigned to the class most common among its k nearest neighbors (k is a positive integer, typically small). If k = 1, then the object is simply assigned to the class of that single nearest neighbor. Reference Wikipedia.
KNN confidence score is better than Logistics Regression but worse than SVM.
Step40: In machine learning, naive Bayes classifiers are a family of simple probabilistic classifiers based on applying Bayes' theorem with strong (naive) independence assumptions between the features. Naive Bayes classifiers are highly scalable, requiring a number of parameters linear in the number of variables (features) in a learning problem. Reference Wikipedia.
The model generated confidence score is the lowest among the models evaluated so far.
Step41: The perceptron is an algorithm for supervised learning of binary classifiers (functions that can decide whether an input, represented by a vector of numbers, belongs to some specific class or not). It is a type of linear classifier, i.e. a classification algorithm that makes its predictions based on a linear predictor function combining a set of weights with the feature vector. The algorithm allows for online learning, in that it processes elements in the training set one at a time. Reference Wikipedia.
Step42: This model uses a decision tree as a predictive model which maps features (tree branches) to conclusions about the target value (tree leaves). Tree models where the target variable can take a finite set of values are called classification trees; in these tree structures, leaves represent class labels and branches represent conjunctions of features that lead to those class labels. Decision trees where the target variable can take continuous values (typically real numbers) are called regression trees. Reference Wikipedia.
The model confidence score is the highest among models evaluated so far.
Step43: The next model Random Forests is one of the most popular. Random forests or random decision forests are an ensemble learning method for classification, regression and other tasks, that operate by constructing a multitude of decision trees (n_estimators=100) at training time and outputting the class that is the mode of the classes (classification) or mean prediction (regression) of the individual trees. Reference Wikipedia.
The model confidence score is the highest among models evaluated so far. We decide to use this model's output (Y_pred) for creating our competition submission of results.
Step44: Model evaluation
We can now rank our evaluation of all the models to choose the best one for our problem. While both Decision Tree and Random Forest score the same, we choose to use Random Forest as they correct for decision trees' habit of overfitting to their training set. | Python Code:
# data analysis and wrangling
import pandas as pd
import numpy as np
import random as rnd
# visualization
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
# machine learning
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import Perceptron
from sklearn.linear_model import SGDClassifier
from sklearn.tree import DecisionTreeClassifier
Explanation: Titanic Data Science Solutions
This notebook is companion to the book Data Science Solutions. The notebook walks us through a typical workflow for solving data science competitions at sites like Kaggle.
There are several excellent notebooks to study data science competition entries. However many will skip some of the explanation on how the solution is developed as these notebooks are developed by experts for experts. The objective of this notebook is to follow a step-by-step workflow, explaining each step and rationale for every decision we take during solution development.
Workflow stages
The competition solution workflow goes through seven stages described in the Data Science Solutions book.
Question or problem definition.
Acquire training and testing data.
Wrangle, prepare, cleanse the data.
Analyze, identify patterns, and explore the data.
Model, predict and solve the problem.
Visualize, report, and present the problem solving steps and final solution.
Supply or submit the results.
The workflow indicates general sequence of how each stage may follow the other. However there are use cases with exceptions.
We may combine mulitple workflow stages. We may analyze by visualizing data.
Perform a stage earlier than indicated. We may analyze data before and after wrangling.
Perform a stage multiple times in our workflow. Visualize stage may be used multiple times.
Drop a stage altogether. We may not need supply stage to productize or service enable our dataset for a competition.
Question and problem definition
Competition sites like Kaggle define the problem to solve or questions to ask while providing the datasets for training your data science model and testing the model results against a test dataset. The question or problem definition for Titanic Survival competition is described here at Kaggle.
Knowing from a training set of samples listing passengers who survived or did not survive the Titanic disaster, can our model determine based on a given test dataset not containing the survival information, if these passengers in the test dataset survived or not.
We may also want to develop some early understanding about the domain of our problem. This is described on the Kaggle competition description page here. Here are the highlights to note.
On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. Translated 32% survival rate.
One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew.
Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class.
Workflow goals
The data science solutions workflow solves for seven major goals.
Classifying. We may want to classify or categorize our samples. We may also want to understand the implications or correlation of different classes with our solution goal.
Correlating. One can approach the problem based on available features within the training dataset. Which features within the dataset contribute significantly to our solution goal? Statistically speaking is there a correlation among a feature and solution goal? As the feature values change does the solution state change as well, and visa-versa? This can be tested both for numerical and categorical features in the given dataset. We may also want to determine correlation among features other than survival for subsequent goals and workflow stages. Correlating certain features may help in creating, completing, or correcting features.
Converting. For modeling stage, one needs to prepare the data. Depending on the choice of model algorithm one may require all features to be converted to numerical equivalent values. So for instance converting text categorical values to numeric values.
Completing. Data preparation may also require us to estimate any missing values within a feature. Model algorithms may work best when there are no missing values.
Correcting. We may also analyze the given training dataset for errors or possibly innacurate values within features and try to corrent these values or exclude the samples containing the errors. One way to do this is to detect any outliers among our samples or features. We may also completely discard a feature if it is not contribting to the analysis or may significantly skew the results.
Creating. Can we create new features based on an existing feature or a set of features, such that the new feature follows the correlation, conversion, completeness goals.
Charting. How to select the right visualization plots and charts depending on nature of the data and the solution goals. A good start is to read the Tableau paper on Which chart or graph is right for you?.
Refactor Release 2017-Jan-29
We are significantly refactoring the notebook based on (a) comments received by readers, (b) issues in porting notebook from Jupyter kernel (2.7) to Kaggle kernel (3.5), and (c) review of few more best practice kernels.
User comments
Combine training and test data for certain operations like converting titles across dataset to numerical values. (thanks @Sharan Naribole)
Correct observation - nearly 30% of the passengers had siblings and/or spouses aboard. (thanks @Reinhard)
Correctly interpreting logistic regresssion coefficients. (thanks @Reinhard)
Porting issues
Specify plot dimensions, bring legend into plot.
Best practices
Performing feature correlation analysis early in the project.
Using multiple plots instead of overlays for readability.
End of explanation
train_df = pd.read_csv('../input/train.csv')
test_df = pd.read_csv('../input/test.csv')
combine = [train_df, test_df]
Explanation: Acquire data
The Python Pandas packages helps us work with our datasets. We start by acquiring the training and testing datasets into Pandas DataFrames. We also combine these datasets to run certain operations on both datasets together.
End of explanation
print(train_df.columns.values)
Explanation: Analyze by describing data
Pandas also helps describe the datasets answering following questions early in our project.
Which features are available in the dataset?
Noting the feature names for directly manipulating or analyzing these. These feature names are described on the Kaggle data page here.
End of explanation
# preview the data
train_df.head()
Explanation: Which features are categorical?
These values classify the samples into sets of similar samples. Within categorical features are the values nominal, ordinal, ratio, or interval based? Among other things this helps us select the appropriate plots for visualization.
Categorical: Survived, Sex, and Embarked. Ordinal: Pclass.
Which features are numerical?
Which features are numerical? These values change from sample to sample. Within numerical features are the values discrete, continuous, or timeseries based? Among other things this helps us select the appropriate plots for visualization.
Continous: Age, Fare. Discrete: SibSp, Parch.
End of explanation
train_df.tail()
Explanation: Which features are mixed data types?
Numerical, alphanumeric data within same feature. These are candidates for correcting goal.
Ticket is a mix of numeric and alphanumeric data types. Cabin is alphanumeric.
Which features may contain errors or typos?
This is harder to review for a large dataset, however reviewing a few samples from a smaller dataset may just tell us outright, which features may require correcting.
Name feature may contain errors or typos as there are several ways used to describe a name including titles, round brackets, and quotes used for alternative or short names.
End of explanation
train_df.info()
print('_'*40)
test_df.info()
Explanation: Which features contain blank, null or empty values?
These will require correcting.
Cabin > Age > Embarked features contain a number of null values in that order for the training dataset.
Cabin > Age are incomplete in case of test dataset.
What are the data types for various features?
Helping us during converting goal.
Seven features are integer or floats. Six in case of test dataset.
Five features are strings (object).
End of explanation
train_df.describe()
# Review survived rate using `percentiles=[.61, .62]` knowing our problem description mentions 38% survival rate.
# Review Parch distribution using `percentiles=[.75, .8]`
# SibSp distribution `[.68, .69]`
# Age and Fare `[.1, .2, .3, .4, .5, .6, .7, .8, .9, .99]`
Explanation: What is the distribution of numerical feature values across the samples?
This helps us determine, among other early insights, how representative is the training dataset of the actual problem domain.
Total samples are 891 or 40% of the actual number of passengers on board the Titanic (2,224).
Survived is a categorical feature with 0 or 1 values.
Around 38% samples survived representative of the actual survival rate at 32%.
Most passengers (> 75%) did not travel with parents or children.
Nearly 30% of the passengers had siblings and/or spouse aboard.
Fares varied significantly with few passengers (<1%) paying as high as $512.
Few elderly passengers (<1%) within age range 65-80.
End of explanation
train_df.describe(include=['O'])
Explanation: What is the distribution of categorical features?
Names are unique across the dataset (count=unique=891)
Sex variable as two possible values with 65% male (top=male, freq=577/count=891).
Cabin values have several dupicates across samples. Alternatively several passengers shared a cabin.
Embarked takes three possible values. S port used by most passengers (top=S)
Ticket feature has high ratio (22%) of duplicate values (unique=681).
End of explanation
train_df[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False).mean().sort_values(by='Survived', ascending=False)
train_df[["Sex", "Survived"]].groupby(['Sex'], as_index=False).mean().sort_values(by='Survived', ascending=False)
train_df[["SibSp", "Survived"]].groupby(['SibSp'], as_index=False).mean().sort_values(by='Survived', ascending=False)
train_df[["Parch", "Survived"]].groupby(['Parch'], as_index=False).mean().sort_values(by='Survived', ascending=False)
Explanation: Assumtions based on data analysis
We arrive at following assumptions based on data analysis done so far. We may validate these assumptions further before taking appropriate actions.
Correlating.
We want to know how well does each feature correlate with Survival. We want to do this early in our project and match these quick correlations with modelled correlations later in the project.
Completing.
We may want to complete Age feature as it is definitely correlated to survival.
We may want to complete the Embarked feature as it may also correlate with survival or another important feature.
Correcting.
Ticket feature may be dropped from our analysis as it contains high ratio of duplicates (22%) and there may not be a correlation between Ticket and survival.
Cabin feature may be dropped as it is highly incomplete or contains many null values both in training and test dataset.
PassengerId may be dropped from training dataset as it does not contribute to survival.
Name feature is relatively non-standard, may not contribute directly to survival, so maybe dropped.
Creating.
We may want to create a new feature called Family based on Parch and SibSp to get total count of family members on board.
We may want to engineer the Name feature to extract Title as a new feature.
We may want to create new feature for Age bands. This turns a continous numerical feature into an ordinal categorical feature.
We may also want to create a Fare range feature if it helps our analysis.
Classifying.
We may also add to our assumptions based on the problem description noted earlier.
Women (Sex=female) were more likely to have survived.
Children (Age<?) were more likely to have survived.
The upper-class passengers (Pclass=1) were more likely to have survived.
Analyze by pivoting features
To confirm some of our observations and assumptions, we can quickly analyze our feature correlations by pivoting features against each other. We can only do so at this stage for features which do not have any empty values. It also makes sense doing so only for features which are categorical (Sex), ordinal (Pclass) or discrete (SibSp, Parch) type.
Pclass We observe significant correlation (>0.5) among Pclass=1 and Survived (classifying #3). We decide to include this feature in our model.
Sex We confirm the observation during problem definition that Sex=female had very high survival rate at 74% (classifying #1).
SibSp and Parch These features have zero correlation for certain values. It may be best to derive a feature or a set of features from these individual features (creating #1).
End of explanation
g = sns.FacetGrid(train_df, col='Survived')
g.map(plt.hist, 'Age', bins=20)
Explanation: Analyze by visualizing data
Now we can continue confirming some of our assumptions using visualizations for analyzing the data.
Correlating numerical features
Let us start by understanding correlations between numerical features and our solution goal (Survived).
A histogram chart is useful for analyzing continous numerical variables like Age where banding or ranges will help identify useful patterns. The histogram can indicate distribution of samples using automatically defined bins or equally ranged bands. This helps us answer questions relating to specific bands (Did infants have better survival rate?)
Note that x-axis in historgram visualizations represents the count of samples or passengers.
Observations.
Infants (Age <=4) had high survival rate.
Oldest passengers (Age = 80) survived.
Large number of 15-25 year olds did not survive.
Most passengers are in 15-35 age range.
Decisions.
This simple analysis confirms our assumptions as decisions for subsequent workflow stages.
We should consider Age (our assumption classifying #2) in our model training.
Complete the Age feature for null values (completing #1).
We should band age groups (creating #3).
End of explanation
# grid = sns.FacetGrid(train_df, col='Pclass', hue='Survived')
grid = sns.FacetGrid(train_df, col='Survived', row='Pclass', size=2.2, aspect=1.6)
grid.map(plt.hist, 'Age', alpha=.5, bins=20)
grid.add_legend();
Explanation: Correlating numerical and ordinal features
We can combine multiple features for identifying correlations using a single plot. This can be done with numerical and categorical features which have numeric values.
Observations.
Pclass=3 had most passengers, however most did not survive. Confirms our classifying assumption #2.
Infant passengers in Pclass=2 and Pclass=3 mostly survived. Further qualifies our classifying assumption #2.
Most passengers in Pclass=1 survived. Confirms our classifying assumption #3.
Pclass varies in terms of Age distribution of passengers.
Decisions.
Consider Pclass for model training.
End of explanation
# grid = sns.FacetGrid(train_df, col='Embarked')
grid = sns.FacetGrid(train_df, row='Embarked', size=2.2, aspect=1.6)
grid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette='deep')
grid.add_legend()
Explanation: Correlating categorical features
Now we can correlate categorical features with our solution goal.
Observations.
Female passengers had much better survival rate than males. Confirms classifying (#1).
Exception in Embarked=C where males had higher survival rate. This could be a correlation between Pclass and Embarked and in turn Pclass and Survived, not necessarily direct correlation between Embarked and Survived.
Males had better survival rate in Pclass=3 when compared with Pclass=2 for C and Q ports. Completing (#2).
Ports of embarkation have varying survival rates for Pclass=3 and among male passengers. Correlating (#1).
Decisions.
Add Sex feature to model training.
Complete and add Embarked feature to model training.
End of explanation
# grid = sns.FacetGrid(train_df, col='Embarked', hue='Survived', palette={0: 'k', 1: 'w'})
grid = sns.FacetGrid(train_df, row='Embarked', col='Survived', size=2.2, aspect=1.6)
grid.map(sns.barplot, 'Sex', 'Fare', alpha=.5, ci=None)
grid.add_legend()
Explanation: Correlating categorical and numerical features
We may also want to correlate categorical features (with non-numeric values) and numeric features. We can consider correlating Embarked (Categorical non-numeric), Sex (Categorical non-numeric), Fare (Numeric continuous), with Survived (Categorical numeric).
Observations.
Higher fare paying passengers had better survival. Confirms our assumption for creating (#4) fare ranges.
Port of embarkation correlates with survival rates. Confirms correlating (#1) and completing (#2).
Decisions.
Consider banding Fare feature.
End of explanation
print("Before", train_df.shape, test_df.shape, combine[0].shape, combine[1].shape)
train_df = train_df.drop(['Ticket', 'Cabin'], axis=1)
test_df = test_df.drop(['Ticket', 'Cabin'], axis=1)
combine = [train_df, test_df]
"After", train_df.shape, test_df.shape, combine[0].shape, combine[1].shape
Explanation: Wrangle data
We have collected several assumptions and decisions regarding our datasets and solution requirements. So far we did not have to change a single feature or value to arrive at these. Let us now execute our decisions and assumptions for correcting, creating, and completing goals.
Correcting by dropping features
This is a good starting goal to execute. By dropping features we are dealing with fewer data points. Speeds up our notebook and eases the analysis.
Based on our assumptions and decisions we want to drop the Cabin (correcting #2) and Ticket (correcting #1) features.
Note that where applicable we perform operations on both training and testing datasets together to stay consistent.
End of explanation
for dataset in combine:
dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.', expand=False)
pd.crosstab(train_df['Title'], train_df['Sex'])
Explanation: Creating new feature extracting from existing
We want to analyze if Name feature can be engineered to extract titles and test correlation between titles and survival, before dropping Name and PassengerId features.
In the following code we extract Title feature using regular expressions. The RegEx pattern (\w+\.) matches the first word which ends with a dot character within Name feature. The expand=False flag returns a DataFrame.
Observations.
When we plot Title, Age, and Survived, we note the following observations.
Most titles band Age groups accurately. For example: Master title has Age mean of 5 years.
Survival among Title Age bands varies slightly.
Certain titles mostly survived (Mme, Lady, Sir) or did not (Don, Rev, Jonkheer).
Decision.
We decide to retain the new Title feature for model training.
End of explanation
for dataset in combine:
dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col',\
'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')
dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')
dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')
train_df[['Title', 'Survived']].groupby(['Title'], as_index=False).mean()
Explanation: We can replace many titles with a more common name or classify them as Rare.
End of explanation
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5}
for dataset in combine:
dataset['Title'] = dataset['Title'].map(title_mapping)
dataset['Title'] = dataset['Title'].fillna(0)
train_df.head()
Explanation: We can convert the categorical titles to ordinal.
End of explanation
train_df = train_df.drop(['Name', 'PassengerId'], axis=1)
test_df = test_df.drop(['Name'], axis=1)
combine = [train_df, test_df]
train_df.shape, test_df.shape
Explanation: Now we can safely drop the Name feature from training and testing datasets. We also do not need the PassengerId feature in the training dataset.
End of explanation
for dataset in combine:
dataset['Sex'] = dataset['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
train_df.head()
Explanation: Converting a categorical feature
Now we can convert features which contain strings to numerical values. This is required by most model algorithms. Doing so will also help us in achieving the feature completing goal.
Let us start by converting Sex feature to a new feature called Gender where female=1 and male=0.
End of explanation
# grid = sns.FacetGrid(train_df, col='Pclass', hue='Gender')
grid = sns.FacetGrid(train_df, row='Pclass', col='Sex', size=2.2, aspect=1.6)
grid.map(plt.hist, 'Age', alpha=.5, bins=20)
grid.add_legend()
Explanation: Completing a numerical continuous feature
Now we should start estimating and completing features with missing or null values. We will first do this for the Age feature.
We can consider three methods to complete a numerical continuous feature.
A simple way is to generate random numbers between mean and standard deviation.
More accurate way of guessing missing values is to use other correlated features. In our case we note correlation among Age, Gender, and Pclass. Guess Age values using median values for Age across sets of Pclass and Gender feature combinations. So, median Age for Pclass=1 and Gender=0, Pclass=1 and Gender=1, and so on...
Combine methods 1 and 2. So instead of guessing age values based on median, use random numbers between mean and standard deviation, based on sets of Pclass and Gender combinations.
Method 1 and 3 will introduce random noise into our models. The results from multiple executions might vary. We will prefer method 2.
End of explanation
guess_ages = np.zeros((2,3))
guess_ages
Explanation: Let us start by preparing an empty array to contain guessed Age values based on Pclass x Gender combinations.
End of explanation
for dataset in combine:
for i in range(0, 2):
for j in range(0, 3):
guess_df = dataset[(dataset['Sex'] == i) & \
(dataset['Pclass'] == j+1)]['Age'].dropna()
# age_mean = guess_df.mean()
# age_std = guess_df.std()
# age_guess = rnd.uniform(age_mean - age_std, age_mean + age_std)
age_guess = guess_df.median()
# Convert random age float to nearest .5 age
guess_ages[i,j] = int( age_guess/0.5 + 0.5 ) * 0.5
for i in range(0, 2):
for j in range(0, 3):
dataset.loc[ (dataset.Age.isnull()) & (dataset.Sex == i) & (dataset.Pclass == j+1),\
'Age'] = guess_ages[i,j]
dataset['Age'] = dataset['Age'].astype(int)
train_df.head()
Explanation: Now we iterate over Sex (0 or 1) and Pclass (1, 2, 3) to calculate guessed values of Age for the six combinations.
End of explanation
train_df['AgeBand'] = pd.cut(train_df['Age'], 5)
train_df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False).mean().sort_values(by='AgeBand', ascending=True)
Explanation: Let us create Age bands and determine correlations with Survived.
End of explanation
for dataset in combine:
dataset.loc[ dataset['Age'] <= 16, 'Age'] = 0
dataset.loc[(dataset['Age'] > 16) & (dataset['Age'] <= 32), 'Age'] = 1
dataset.loc[(dataset['Age'] > 32) & (dataset['Age'] <= 48), 'Age'] = 2
dataset.loc[(dataset['Age'] > 48) & (dataset['Age'] <= 64), 'Age'] = 3
dataset.loc[ dataset['Age'] > 64, 'Age']
train_df.head()
Explanation: Let us replace Age with ordinals based on these bands.
End of explanation
train_df = train_df.drop(['AgeBand'], axis=1)
combine = [train_df, test_df]
train_df.head()
Explanation: We can not remove the AgeBand feature.
End of explanation
for dataset in combine:
dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1
train_df[['FamilySize', 'Survived']].groupby(['FamilySize'], as_index=False).mean().sort_values(by='Survived', ascending=False)
Explanation: Create new feature combining existing features
We can create a new feature for FamilySize which combines Parch and SibSp. This will enable us to drop Parch and SibSp from our datasets.
End of explanation
for dataset in combine:
dataset['IsAlone'] = 0
dataset.loc[dataset['FamilySize'] == 1, 'IsAlone'] = 1
train_df[['IsAlone', 'Survived']].groupby(['IsAlone'], as_index=False).mean()
Explanation: We can create another feature called IsAlone.
End of explanation
train_df = train_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1)
test_df = test_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1)
combine = [train_df, test_df]
train_df.head()
Explanation: Let us drop Parch, SibSp, and FamilySize features in favor of IsAlone.
End of explanation
for dataset in combine:
dataset['Age*Class'] = dataset.Age * dataset.Pclass
train_df.loc[:, ['Age*Class', 'Age', 'Pclass']].head(10)
Explanation: We can also create an artificial feature combining Pclass and Age.
End of explanation
freq_port = train_df.Embarked.dropna().mode()[0]
freq_port
for dataset in combine:
dataset['Embarked'] = dataset['Embarked'].fillna(freq_port)
train_df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False).mean().sort_values(by='Survived', ascending=False)
Explanation: Completing a categorical feature
Embarked feature takes S, Q, C values based on port of embarkation. Our training dataset has two missing values. We simply fill these with the most common occurance.
End of explanation
for dataset in combine:
dataset['Embarked'] = dataset['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int)
train_df.head()
Explanation: Converting categorical feature to numeric
We can now convert the EmbarkedFill feature by creating a new numeric Port feature.
End of explanation
test_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True)
test_df.head()
Explanation: Quick completing and converting a numeric feature
We can now complete the Fare feature for single missing value in test dataset using mode to get the value that occurs most frequently for this feature. We do this in a single line of code.
Note that we are not creating an intermediate new feature or doing any further analysis for correlation to guess missing feature as we are replacing only a single value. The completion goal achieves desired requirement for model algorithm to operate on non-null values.
We may also want round off the fare to two decimals as it represents currency.
End of explanation
train_df['FareBand'] = pd.qcut(train_df['Fare'], 4)
train_df[['FareBand', 'Survived']].groupby(['FareBand'], as_index=False).mean().sort_values(by='FareBand', ascending=True)
Explanation: We can not create FareBand.
End of explanation
for dataset in combine:
dataset.loc[ dataset['Fare'] <= 7.91, 'Fare'] = 0
dataset.loc[(dataset['Fare'] > 7.91) & (dataset['Fare'] <= 14.454), 'Fare'] = 1
dataset.loc[(dataset['Fare'] > 14.454) & (dataset['Fare'] <= 31), 'Fare'] = 2
dataset.loc[ dataset['Fare'] > 31, 'Fare'] = 3
dataset['Fare'] = dataset['Fare'].astype(int)
train_df = train_df.drop(['FareBand'], axis=1)
combine = [train_df, test_df]
train_df.head(10)
Explanation: Convert the Fare feature to ordinal values based on the FareBand.
End of explanation
test_df.head(10)
Explanation: And the test dataset.
End of explanation
X_train = train_df.drop("Survived", axis=1)
Y_train = train_df["Survived"]
X_test = test_df.drop("PassengerId", axis=1).copy()
X_train.shape, Y_train.shape, X_test.shape
Explanation: Model, predict and solve
Now we are ready to train a model and predict the required solution. There are 60+ predictive modelling algorithms to choose from. We must understand the type of problem and solution requirement to narrow down to a select few models which we can evaluate. Our problem is a classification and regression problem. We want to identify relationship between output (Survived or not) with other variables or features (Gender, Age, Port...). We are also perfoming a category of machine learning which is called supervised learning as we are training our model with a given dataset. With these two criteria - Supervised Learning plus Classification and Regression, we can narrow down our choice of models to a few. These include:
Logistic Regression
KNN or k-Nearest Neighbors
Support Vector Machines
Naive Bayes classifier
Decision Tree
Random Forrest
Perceptron
Artificial neural network
RVM or Relevance Vector Machine
End of explanation
# Logistic Regression
logreg = LogisticRegression()
logreg.fit(X_train, Y_train)
Y_pred = logreg.predict(X_test)
acc_log = round(logreg.score(X_train, Y_train) * 100, 2)
acc_log
Explanation: Logistic Regression is a useful model to run early in the workflow. Logistic regression measures the relationship between the categorical dependent variable (feature) and one or more independent variables (features) by estimating probabilities using a logistic function, which is the cumulative logistic distribution. Reference Wikipedia.
Note the confidence score generated by the model based on our training dataset.
End of explanation
coeff_df = pd.DataFrame(train_df.columns.delete(0))
coeff_df.columns = ['Feature']
coeff_df["Correlation"] = pd.Series(logreg.coef_[0])
coeff_df.sort_values(by='Correlation', ascending=False)
Explanation: We can use Logistic Regression to validate our assumptions and decisions for feature creating and completing goals. This can be done by calculating the coefficient of the features in the decision function.
Positive coefficients increase the log-odds of the response (and thus increase the probability), and negative coefficients decrease the log-odds of the response (and thus decrease the probability).
Sex is highest positivie coefficient, implying as the Sex value increases (male: 0 to female: 1), the probability of Survived=1 increases the most.
Inversely as Pclass increases, probability of Survived=1 decreases the most.
This way Age*Class is a good artificial feature to model as it has second highest negative correlation with Survived.
So is Title as second highest positive correlation.
End of explanation
# Support Vector Machines
svc = SVC()
svc.fit(X_train, Y_train)
Y_pred = svc.predict(X_test)
acc_svc = round(svc.score(X_train, Y_train) * 100, 2)
acc_svc
Explanation: Next we model using Support Vector Machines which are supervised learning models with associated learning algorithms that analyze data used for classification and regression analysis. Given a set of training samples, each marked as belonging to one or the other of two categories, an SVM training algorithm builds a model that assigns new test samples to one category or the other, making it a non-probabilistic binary linear classifier. Reference Wikipedia.
Note that the model generates a confidence score which is higher than Logistics Regression model.
End of explanation
knn = KNeighborsClassifier(n_neighbors = 3)
knn.fit(X_train, Y_train)
Y_pred = knn.predict(X_test)
acc_knn = round(knn.score(X_train, Y_train) * 100, 2)
acc_knn
Explanation: In pattern recognition, the k-Nearest Neighbors algorithm (or k-NN for short) is a non-parametric method used for classification and regression. A sample is classified by a majority vote of its neighbors, with the sample being assigned to the class most common among its k nearest neighbors (k is a positive integer, typically small). If k = 1, then the object is simply assigned to the class of that single nearest neighbor. Reference Wikipedia.
KNN confidence score is better than Logistics Regression but worse than SVM.
End of explanation
# Gaussian Naive Bayes
gaussian = GaussianNB()
gaussian.fit(X_train, Y_train)
Y_pred = gaussian.predict(X_test)
acc_gaussian = round(gaussian.score(X_train, Y_train) * 100, 2)
acc_gaussian
Explanation: In machine learning, naive Bayes classifiers are a family of simple probabilistic classifiers based on applying Bayes' theorem with strong (naive) independence assumptions between the features. Naive Bayes classifiers are highly scalable, requiring a number of parameters linear in the number of variables (features) in a learning problem. Reference Wikipedia.
The model generated confidence score is the lowest among the models evaluated so far.
End of explanation
# Perceptron
perceptron = Perceptron()
perceptron.fit(X_train, Y_train)
Y_pred = perceptron.predict(X_test)
acc_perceptron = round(perceptron.score(X_train, Y_train) * 100, 2)
acc_perceptron
# Linear SVC
linear_svc = LinearSVC()
linear_svc.fit(X_train, Y_train)
Y_pred = linear_svc.predict(X_test)
acc_linear_svc = round(linear_svc.score(X_train, Y_train) * 100, 2)
acc_linear_svc
# Stochastic Gradient Descent
sgd = SGDClassifier()
sgd.fit(X_train, Y_train)
Y_pred = sgd.predict(X_test)
acc_sgd = round(sgd.score(X_train, Y_train) * 100, 2)
acc_sgd
Explanation: The perceptron is an algorithm for supervised learning of binary classifiers (functions that can decide whether an input, represented by a vector of numbers, belongs to some specific class or not). It is a type of linear classifier, i.e. a classification algorithm that makes its predictions based on a linear predictor function combining a set of weights with the feature vector. The algorithm allows for online learning, in that it processes elements in the training set one at a time. Reference Wikipedia.
End of explanation
# Decision Tree
decision_tree = DecisionTreeClassifier()
decision_tree.fit(X_train, Y_train)
Y_pred = decision_tree.predict(X_test)
acc_decision_tree = round(decision_tree.score(X_train, Y_train) * 100, 2)
acc_decision_tree
Explanation: This model uses a decision tree as a predictive model which maps features (tree branches) to conclusions about the target value (tree leaves). Tree models where the target variable can take a finite set of values are called classification trees; in these tree structures, leaves represent class labels and branches represent conjunctions of features that lead to those class labels. Decision trees where the target variable can take continuous values (typically real numbers) are called regression trees. Reference Wikipedia.
The model confidence score is the highest among models evaluated so far.
End of explanation
# Random Forest
random_forest = RandomForestClassifier(n_estimators=100)
random_forest.fit(X_train, Y_train)
Y_pred = random_forest.predict(X_test)
random_forest.score(X_train, Y_train)
acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)
acc_random_forest
Explanation: The next model Random Forests is one of the most popular. Random forests or random decision forests are an ensemble learning method for classification, regression and other tasks, that operate by constructing a multitude of decision trees (n_estimators=100) at training time and outputting the class that is the mode of the classes (classification) or mean prediction (regression) of the individual trees. Reference Wikipedia.
The model confidence score is the highest among models evaluated so far. We decide to use this model's output (Y_pred) for creating our competition submission of results.
End of explanation
models = pd.DataFrame({
'Model': ['Support Vector Machines', 'KNN', 'Logistic Regression',
'Random Forest', 'Naive Bayes', 'Perceptron',
'Stochastic Gradient Decent', 'Linear SVC',
'Decision Tree'],
'Score': [acc_svc, acc_knn, acc_log,
acc_random_forest, acc_gaussian, acc_perceptron,
acc_sgd, acc_linear_svc, acc_decision_tree]})
models.sort_values(by='Score', ascending=False)
submission = pd.DataFrame({
"PassengerId": test_df["PassengerId"],
"Survived": Y_pred
})
# submission.to_csv('../output/submission.csv', index=False)
Explanation: Model evaluation
We can now rank our evaluation of all the models to choose the best one for our problem. While both Decision Tree and Random Forest score the same, we choose to use Random Forest as they correct for decision trees' habit of overfitting to their training set.
End of explanation |
7,966 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Reformer
Step2: Setting up data and model
In this notebook, we'll be pushing the limits of just how many tokens we can fit on a single TPU device. The TPUs available in Colab have 8GB of memory per core, and 8 cores. We will set up a Reformer model that can fit a copy of "Crime and Punishment" on each of the 8 TPU cores (over 500,000 tokens per 8GB of memory).
Step4: As we see above, "Crime and Punishment" has just over half a million tokens with the BPE vocabulary we have selected.
Normally we would have a dataset with many examples, but for this demonstration we fit a language model on the single novel only. We don't want the model to just memorize the dataset by encoding the words in its position embeddings, so at each training iteration we will randomly select how much padding to put before the text vs. after it.
We have 8 TPU cores, so we will separately randomize the amount of padding for each core.
Step7: Sample from the model | Python Code:
# 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 the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Explanation: <a href="https://colab.research.google.com/github/JENkt4k/pynotes-general/blob/master/Reformer_Text_Generation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Copyright 2020 Google LLC.
End of explanation
# Grab newest JAX version.
!pip install --upgrade -q jax==0.1.57 jaxlib==0.1.37
# Make sure the Colab Runtime is set to Accelerator: TPU.
import requests
import os
if 'TPU_DRIVER_MODE' not in globals():
url = 'http://' + os.environ['COLAB_TPU_ADDR'].split(':')[0] + ':8475/requestversion/tpu_driver0.1-dev20191206'
resp = requests.post(url)
TPU_DRIVER_MODE = 1
# The following is required to use TPU Driver as JAX's backend.
from jax.config import config
config.FLAGS.jax_xla_backend = "tpu_driver"
config.FLAGS.jax_backend_target = "grpc://" + os.environ['COLAB_TPU_ADDR']
print(config.FLAGS.jax_backend_target)
!pip install --upgrade -q sentencepiece
!pip install --upgrade -q gin git+https://github.com/google/trax.git@v1.2.0
from tensorflow.compat.v1.io.gfile import GFile
import gin
import os
import jax
import trax
from trax.supervised import inputs
import numpy as onp
import jax.numpy as np
from scipy.special import softmax
from sentencepiece import SentencePieceProcessor
Explanation: Reformer: Text Generation
This notebook was designed to run on TPU.
To use TPUs in Colab, click "Runtime" on the main menu bar and select Change runtime type. Set "TPU" as the hardware accelerator.
End of explanation
# Import a copy of "Crime and Punishment", by Fyodor Dostoevsky
with GFile('gs://trax-ml/reformer/crime-and-punishment-2554.txt') as f:
text = f.read()
# The file read above includes metadata and licensing information.
# For training our language model, we will only use the actual novel text.
start = text.find('CRIME AND PUNISHMENT') # skip header
start = text.find('CRIME AND PUNISHMENT', start + 1) # skip header
start = text.find('CRIME AND PUNISHMENT', start + 1) # skip translator preface
end = text.rfind('End of Project') # skip extra text at the end
text = text[start:end].strip()
# Load a BPE vocabulaary with 320 types. This mostly consists of single letters
# and pairs of letters, but it has some common words and word pieces, too.
!gsutil cp gs://trax-ml/reformer/cp.320.* .
TOKENIZER = SentencePieceProcessor()
TOKENIZER.load('cp.320.model')
# Tokenize
IDS = TOKENIZER.EncodeAsIds(text)
IDS = onp.asarray(IDS, dtype=onp.int32)
PAD_AMOUNT = 512 * 1024 - len(IDS)
print("Number of tokens:", IDS.shape[0])
Explanation: Setting up data and model
In this notebook, we'll be pushing the limits of just how many tokens we can fit on a single TPU device. The TPUs available in Colab have 8GB of memory per core, and 8 cores. We will set up a Reformer model that can fit a copy of "Crime and Punishment" on each of the 8 TPU cores (over 500,000 tokens per 8GB of memory).
End of explanation
# Set up the data pipeline.
def my_inputs(n_devices):
while True:
inputs = []
mask = []
pad_amounts = onp.random.choice(PAD_AMOUNT, n_devices)
for i in range(n_devices):
inputs.append(onp.pad(IDS, (pad_amounts[i], PAD_AMOUNT - pad_amounts[i]),
mode='constant'))
mask.append(onp.pad(onp.ones_like(IDS, dtype=onp.float32),
(pad_amounts[i], PAD_AMOUNT - pad_amounts[i]),
mode='constant'))
inputs = onp.stack(inputs)
mask = onp.stack(mask)
yield (inputs, inputs, mask)
print("(device count, tokens per device) = ",
next(my_inputs(trax.math.device_count()))[0].shape)
# Configure hyperparameters.
gin.parse_config(
import trax.layers
import trax.models
import trax.optimizers
import trax.supervised.inputs
import trax.supervised.trainer_lib
# Parameters that will vary between experiments:
# ==============================================================================
train.model = @trax.models.ReformerLM
# Our model will have 6 layers, alternating between the LSH attention proposed
# in the Reformer paper and local attention within a certain context window.
n_layers = 6
attn_type = [
@TimeBinCausalAttention,
@LSHCausalAttention,
@TimeBinCausalAttention,
@LSHCausalAttention,
@TimeBinCausalAttention,
@LSHCausalAttention,
]
share_qk = False # LSHCausalAttention ignores this flag and always shares q & k
n_heads = 2
attn_kv = 64
dropout = 0.05
n_tokens = 524288
# Parameters for MultifactorSchedule:
# ==============================================================================
MultifactorSchedule.constant = 0.01
MultifactorSchedule.factors = 'constant * linear_warmup * cosine_decay'
MultifactorSchedule.warmup_steps = 100
MultifactorSchedule.steps_per_cycle = 900
# Parameters for Adam:
# ==============================================================================
Adam.weight_decay_rate=0.0
Adam.b1 = 0.86
Adam.b2 = 0.92
Adam.eps = 1e-9
# Parameters for TimeBinCausalAttention:
# ==============================================================================
TimeBinCausalAttention.bin_length = 64
TimeBinCausalAttention.dropout = 0.05
TimeBinCausalAttention.n_bins = None
TimeBinCausalAttention.share_qk = %share_qk
# Parameters for LSHCausalAttention:
# ==============================================================================
LSHCausalAttention.allow_duplicate_attention = False
LSHCausalAttention.attend_across_buckets = True
LSHCausalAttention.rehash_each_round = True
LSHCausalAttention.data_rotation = False
LSHCausalAttention.n_bins = 4096
LSHCausalAttention.n_buckets = 8192
LSHCausalAttention.factorize_hash = [64, 128]
LSHCausalAttention.n_hashes = 1
LSHCausalAttention.one_rng = False
LSHCausalAttention.hard_k = 0
LSHCausalAttention.dropout = 0.0
LSHCausalAttention.drop_for_hash_rate = 0.0
LSHCausalAttention.max_len_for_inference = 2048
LSHCausalAttention.bucket_capacity_for_inference = 64
# Parameters for ReformerLM:
# ==============================================================================
ReformerLM.attention_type = %attn_type
ReformerLM.d_attention_key = %attn_kv
ReformerLM.d_attention_value = %attn_kv
ReformerLM.d_model = 256
ReformerLM.d_ff = 512
ReformerLM.dropout = %dropout
ReformerLM.ff_activation = @trax.layers.Relu
ReformerLM.max_len = %n_tokens
ReformerLM.mode = 'train'
ReformerLM.n_heads = %n_heads
ReformerLM.n_layers = %n_layers
ReformerLM.vocab_size = 320
ReformerLM.share_qk = %share_qk
ReformerLM.axial_pos_shape = (512, 1024)
ReformerLM.d_axial_pos_embs= (64, 192)
)
# Set up a Trainer.
output_dir = os.path.expanduser('~/train_dir/')
!rm -f ~/train_dir/model.pkl # Remove old model
trainer = trax.supervised.Trainer(
model=trax.models.ReformerLM,
loss_fn=trax.layers.CrossEntropyLoss,
optimizer=trax.optimizers.Adam,
lr_schedule=trax.lr.MultifactorSchedule,
inputs=trax.supervised.inputs.Inputs(my_inputs),
output_dir=output_dir,
has_weights=True)
# Run one training step, to make sure the model fits in memory.
# The first time trainer.train_epoch is called, it will JIT the entire network
# architecture, which takes around 2 minutes. The JIT-compiled model is saved
# so subsequent runs will be much faster than the first.
trainer.train_epoch(n_steps=1, n_eval_steps=1)
# Train for 600 steps total
# The first ~20 steps are slow to run, but after that it reaches steady-state
# speed. This will take at least 30 minutes to run to completion, but can safely
# be interrupted by selecting "Runtime > Interrupt Execution" from the menu.
# The language model won't be exceptionally good when trained for just a few
# steps and with minimal regularization. However, we can still sample from it to
# see what it learns.
trainer.train_epoch(n_steps=9, n_eval_steps=1)
for _ in range(59):
trainer.train_epoch(n_steps=10, n_eval_steps=1)
Explanation: As we see above, "Crime and Punishment" has just over half a million tokens with the BPE vocabulary we have selected.
Normally we would have a dataset with many examples, but for this demonstration we fit a language model on the single novel only. We don't want the model to just memorize the dataset by encoding the words in its position embeddings, so at each training iteration we will randomly select how much padding to put before the text vs. after it.
We have 8 TPU cores, so we will separately randomize the amount of padding for each core.
End of explanation
# As we report in the Reformer paper, increasing the number of hashing rounds
# helps with quality. We can even increase the number of hashing rounds at
# evaluation time only.
gin.parse_config(LSHCausalAttention.n_hashes = 4)
model_infer = trax.models.ReformerLM(mode='predict')
# Prepare a jitted copy of the model.
jit_model_infer = trax.layers.base._accelerate(
model_infer._forward_internal, trax.math.device_count())
# Set up the initial state for sampling.
infer_state = model_infer.new_weights_and_state(
trax.supervised.trainer_lib.ShapeDtype((1,1), dtype=np.int32))[1]
infer_state = trainer._for_n_devices(infer_state)
def sample(length=2048, prompt=None):
Sample from the ReformerLM model
model_weights = trainer._opt_state[0][0]
# Token id 0 is the equivalent of a "start" token
cur_inputs = np.zeros((trax.math.device_count(), 1, 1), dtype=np.int32)
cur_state = infer_state
rngs = trax.math.random.split(trax.math.random.get_prng(0), trax.math.device_count())
all_samples = []
if prompt is not None:
prompt = np.asarray(
[TOKENIZER.EncodeAsIds(prompt)] * trax.math.device_count())
for iteration in range(length):
logits, cur_state = jit_model_infer(
cur_inputs,
model_weights,
cur_state,
rngs)
if prompt is not None and iteration < prompt.shape[1]:
cur_samples = onp.array(prompt[:, iteration], dtype=int)
else:
logits = onp.array(logits)[:,0,0,:]
probs = onp.exp(logits)
cur_samples = [onp.random.choice(probs.shape[-1], p=probs[i,:])
for i in range(probs.shape[0])]
cur_samples = onp.array(cur_samples, dtype=int)
all_samples.append(cur_samples)
cur_inputs = np.array(cur_samples[:,None,None])
all_samples = onp.stack(all_samples, -1)
return all_samples
# Sample from the Reformer language model, given a prefix.
samples = sample(length=128, prompt="There was a time when")
for ids in samples:
print(TOKENIZER.DecodeIds(ids.tolist()))
Explanation: Sample from the model
End of explanation |
7,967 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implement CNN network with TensorFlow
Brief
Load a CNN implemented in TensorFlow trained before and test it's performance on MNIST dataset.
Notice
Saving checkpoints of this model demands sufficient disk memory.
Import necessary libraries
Step1: Load MNIST dataset
Step3: Create Graph
Step4: Reload Parameters and test performance | Python Code:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
Explanation: Implement CNN network with TensorFlow
Brief
Load a CNN implemented in TensorFlow trained before and test it's performance on MNIST dataset.
Notice
Saving checkpoints of this model demands sufficient disk memory.
Import necessary libraries
End of explanation
from tensorflow.examples.tutorials.mnist import input_data
MNIST=input_data.read_data_sets(r"..\DataSet\mnist",one_hot=True)
print("Number of training samples: {}\nNumber of test samples: {}".format(MNIST.train.num_examples,MNIST.test.num_examples))
Explanation: Load MNIST dataset
End of explanation
def filter2Gray(weight):
Convert filters in CNN into a batch of not yet normalized (e.g ranged from 0 to 255)gray images
:type weight: A Tensor of shape [filter_height, filter_width, in_channels, out_channels]
:type name: str
:rtype: A Tensor of shape [number_of_filters, height, width, 1]
trans=tf.transpose(a=weight,perm=[2,3,0,1])
ret=tf.reshape(tensor=trans,shape=[-1,int(trans.shape[2]),int(trans.shape[3]),1])
return ret
with tf.name_scope("CNN"):
with tf.name_scope("Input"):
X=tf.placeholder(dtype=tf.float32,shape=[None,784],name="X")
Y=tf.placeholder(dtype=tf.float32,shape=[None,10],name="Y")
NetIn=tf.reshape(tensor=X,shape=[-1,28,28,1],name="NetIn")
with tf.name_scope("Conv1"):
W1=tf.Variable(tf.truncated_normal([5,5,1,32]),name="Weight")
b1=tf.Variable(tf.truncated_normal([32]),name="bias")
L1Out=tf.nn.conv2d(input=NetIn,filter=W1,strides=[1,1,1,1],padding="SAME",name="conv")
L1Out=tf.nn.relu(L1Out+b1,name="ReLu")
L1Out=tf.nn.max_pool(value=L1Out,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME",name="L1Out")
#Need to check out what the param#0 and param#3 means in ksize.
with tf.name_scope("Conv2"):
W2=tf.Variable(tf.truncated_normal([5,5,32,64]),name="Weight")
b2=tf.Variable(tf.truncated_normal([64]),name="bias")
L2Out=tf.nn.conv2d(input=L1Out,filter=W2,strides=[1,1,1,1],padding="SAME",name="conv")
L2Out=tf.nn.relu(L2Out+b2,name="ReLu")
L2Out=tf.nn.max_pool(value=L2Out,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME",name="L2Out")
#Need to check out what the param#0 and param#3 means in ksize.
with tf.name_scope("FullConnect"):
flatten=tf.reshape(tensor=L2Out,shape=[-1,7*7*64],name="flatten")
W3=tf.Variable(tf.truncated_normal(dtype=tf.float32,shape=[7*7*64,1024]),name="Weight")
b3=tf.Variable(tf.truncated_normal(dtype=tf.float32,shape=[1024]),name="bias")
L3Out=tf.nn.relu(tf.matmul(flatten,W3)+b3,name="L3Out")
with tf.name_scope("Output"):
W4=tf.Variable(tf.truncated_normal(dtype=tf.float32,shape=[1024,10]),name="Weight")
b4=tf.Variable(tf.truncated_normal(dtype=tf.float32,shape=[10]))
L4Out=tf.matmul(L3Out,W4)+b4
with tf.name_scope("Loss"):
entropy=tf.nn.softmax_cross_entropy_with_logits(logits=L4Out,labels=Y,name="crossEntropy")
loss=tf.reduce_mean(input_tensor=entropy,name="loss")
with tf.name_scope("Train") as scope:
optimizer=tf.train.AdamOptimizer(learning_rate=0.01,name="optimizer").minimize(loss)
#Need to make reference to the summary objects to prevent the garbage collection.
#Do I really have to?
with tf.name_scope("epochSummary") as epochSummary:
sumLoss=tf.summary.scalar(name="lossSummary",tensor=loss)
summary_op_epoch=tf.summary.merge(inputs=tf.get_collection(key=tf.GraphKeys.SUMMARIES,scope=epochSummary),name="epochSummaryOp")
with tf.name_scope("finalSummary") as finalSummary:
sumW1=filter2Gray(weight=W1)
#sumW1=tf.summary.image(tensor=sumW1,name="Conv1Weight",max_outputs=int(sumW1.shape[0]))
sumW1=tf.summary.image(tensor=sumW1,name="Conv1Weight",max_outputs=20)
sumW2=filter2Gray(weight=W2)
#sumW2=tf.summary.image(tensor=sumW2,name="Conv2Weight",max_outputs=int(sumW2.shape[0]))
sumW2=tf.summary.image(tensor=sumW2,name="Conv2Weight",max_outputs=20)
summary_op_final=tf.summary.merge(inputs=tf.get_collection(key=tf.GraphKeys.SUMMARIES,scope=finalSummary),name="finalSummaryOp")
Explanation: Create Graph
End of explanation
batchSize=20
with tf.Session() as sess:
saver=tf.train.Saver()
saver.restore(sess=sess,save_path=r".\model_checkpoints\MNIST_CNN-"+str(3000))
acc=0
for batch_i in range(int(MNIST.test.num_examples/batchSize)):
x_batch,y_batch=MNIST.test.next_batch(batch_size=batchSize)
pred=sess.run(L4Out,feed_dict={X:x_batch})
acc+=sess.run(tf.reduce_sum(tf.cast(x=tf.equal(tf.argmax(input=pred,axis=1),tf.argmax(input=y_batch,axis=1)),dtype=tf.float32)))
print("Accuracy: {}".format(acc/MNIST.test.num_examples))
Explanation: Reload Parameters and test performance
End of explanation |
7,968 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Which morphology indicators did I settle on?
Perfect correlation with table3 above
Step1: Selecting samples for Clean Image examples
Estimated the source density for every cutout I made by counting the number of objects in the resulting SExtractor catalog (bright run). Took this value and divided by the area of the image in arcsec (which itself was estimated as ($4\times(2\times r_{\mathrm{Petro}}))^2$)
Step2: Measured morphologies on how many galaxies? | Python Code:
print table1.columns
print table4.columns
print len(table1), len(table4)
test = pd.merge(table1, table4, on=['OBJID'])
# What we started with - what we have after the merge
# The twelve are likely those S82 objects that snuck into the main sample :(
282350-282338
test.columns
plt.scatter(test.C_x, test.C_y)
plt.scatter(test.M20_x, test.M20_y)
plt.scatter(test.A_x, test.A_y)
plt.scatter(test.G_x, test.G_y)
Explanation: Which morphology indicators did I settle on?
Perfect correlation with table3 above: SDSSmorphology_full_catalog_92415.fits morphology indicators measured with elliptical apertures.
End of explanation
#plt.hist(table4.cat,bins=np.arange(0,9,1))
table2['source_density'] = table2['bright_count']/(4*2*table2['PETROR90_R'].values)**2
h, bins, _ = plt.hist(table2['source_density'].values, range=(0,0.0035))
for i in range(len(bins)-1):
objects = table2[(table2['source_density']>bins[i]) &
(table2['source_density']<bins[i+1])]
idx = np.random.choice(objects['Unnamed: 0'], size=10, replace=False, p=None)
sample = objects.loc[idx]
print sample[ 'OBJID']
Explanation: Selecting samples for Clean Image examples
Estimated the source density for every cutout I made by counting the number of objects in the resulting SExtractor catalog (bright run). Took this value and divided by the area of the image in arcsec (which itself was estimated as ($4\times(2\times r_{\mathrm{Petro}}))^2$)
End of explanation
print "What Morphologies was I able to Measure?"
print "All GZ2:", len(table)
#print "All GZ2 (published):", len(table[''])
print "Petrosian radius:", len(table['Rp'].dropna())
print "Concentration:", len(table['C'].dropna())
print "M20:", len(table['M20'].dropna())
print "A:", len(table['A'].dropna())
print "Gini:", len(table['G'].dropna())
print "elipt:", len(table['elipt'].dropna())
table[['OBJID','A']]
print np.min(table['REDSHIFT']), np.max(table['REDSHIFT'])
plt.hist(table['REDSHIFT_SIMPLE_BIN'], range=(0, 20))
zbins = np.unique(table['REDSHIFT_SIMPLE_BIN'])[2:-1]
print zbins
sample = [np.random.choice(table["OBJID"][table['REDSHIFT_SIMPLE_BIN'] == n]) for n in zbins]
sample
Explanation: Measured morphologies on how many galaxies?
End of explanation |
7,969 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Orienting Yourself
Image
Step1: If you use Python for any amount of time, you'll quickly find that there are some things it is not so good at.
In particular, performing repeated operations via loops is one of its weaknesses.
For example, in pure Python
Step2: Using numpy we would do
Step3: Why is pure Python so slow?
Image
Step4: Aside
Step5: Some interesting properties of numpy functions
Functions that operate element-wise on arrays are known as universal functions ("UFuncs").
UFuncs have some methods built-in, which allow for some very interesting, flexible, and fast operations
Step6: All operators (like +) actuall call an underlying numpy function
Step7: These ufuncs have some interesting and useful properties
Step8: numpy aggregates
Aggregates are functions that take an array and return a smaller-dimension array.
Step9: Indexing
Slice indexing
Step10: This sort of indexing does not make a copy
Step11: Indexing with indicies
Step12: Indexing with booleans
Step13: How do you remember which type of indexing creates a copy?
NumPy arrays are stored as a chunk of data and a set of strides in each dimension.
Boolean and arbitrary indicies cannot be represented this way, so numpy must make a copy.
More on masking
All indexing operations also work in assigning to an array. Here we demonstrate assignment with booleans.
For example, imagine you have an array of data where negative values indicate some kind of error.
Step14: How might you clean this array, setting all negative values to, say, zero?
Step15: And the mask can be used directly to set the value you desire
Step16: Often you'll see this done in a separate step
Step17: Broadcasting
Step18:
Step19:
Step20: Broadcasting rules
Step21: What else is in NumPy?
numpy.random
Step22: SciPy
Interestingly, scipy predates numpy by more than half a decade (circa 1999), even though it is built on top of numpy.
Originally "scipack", a collection of wrappers for Fortran NetLib libraries.
Step23: Note the overlap | Python Code:
from __future__ import print_function
import math
import numpy as np
Explanation: Orienting Yourself
Image: @jakevdp
How to install packages using conda
If you're using anaconda, you probably already have most (if not all) of these installed. If you installed miniconda:
conda install numpy
Conda also has channels which allows anybody to distribute their own conda packages. There is an "astropy" channel for AstroPy affiliated packages. You can do:
conda install -c astropy astroml
To check if a package is available on conda:
conda search numpy
How to install packages using pip
Many smaller packages are not available via the conda package manager. For these, use pip:
pip install --no-deps corner
Why prefer conda?
conda is an actual package manager that will take care of resolving dependencies optimally.
NumPy
End of explanation
def add_one(x):
return [xi + 1 for xi in x]
x = list(range(1000000))
%timeit add_one(x)
Explanation: If you use Python for any amount of time, you'll quickly find that there are some things it is not so good at.
In particular, performing repeated operations via loops is one of its weaknesses.
For example, in pure Python:
End of explanation
x = np.arange(1000000)
%timeit np.add(x, 1)
Explanation: Using numpy we would do:
End of explanation
# Point coordinates
x = np.random.rand(100000)
y = np.random.rand(100000)
# calculate distance from origin
%%timeit
dist = np.empty(len(x))
for i in range(len(x)):
dist[i] = math.sqrt(x[i]**2 + y[i]**2)
%%timeit
dist = np.sqrt(x**2 + y**2)
Explanation: Why is pure Python so slow?
Image: @jakevdp
Operations in NumPy are faster than Python functions involving loops, because
The data type can be checked just once
The looping then happens in compiled code
Using NumPy efficiently
The name of the game is moving all array-oriented code into vectorized NumPy operations.
End of explanation
x = np.arange(10)**2
x
# difference between adjacent elements
x[1:] - x[:-1]
# by the way, this is basically the implementation of `np.ediff1d`
np.ediff1d??
Explanation: Aside: How many arrays are created in the above cell?
Sometimes you have to get a little creative to "vectorize" things:
End of explanation
x = np.arange(5)
y = np.arange(1, 6)
x + y
Explanation: Some interesting properties of numpy functions
Functions that operate element-wise on arrays are known as universal functions ("UFuncs").
UFuncs have some methods built-in, which allow for some very interesting, flexible, and fast operations:
End of explanation
np.add(x, y)
Explanation: All operators (like +) actuall call an underlying numpy function: in this case np.add:
End of explanation
np.add.accumulate(x)
np.multiply.accumulate(x)
np.multiply.accumulate(y)
np.add.identity
np.multiply.identity
np.add.outer(x, x)
np.multiply.outer(x, x)
Explanation: These ufuncs have some interesting and useful properties:
End of explanation
z = np.arange(10, dtype=np.float64).reshape((2, 5))
z
np.sum(z)
# alternate spelling:
z.sum()
np.mean(z)
np.min(z), np.max(z)
# could also use ufunc
np.add.reduce(z, axis=0)
np.add.reduce(x)
# equivalent to sum:
np.sum(z, axis=0)
Explanation: numpy aggregates
Aggregates are functions that take an array and return a smaller-dimension array.
End of explanation
x = np.arange(15)
x
x[0:5]
x[0:10:2] # with a stride
x[10:0:-2] # reversed
Explanation: Indexing
Slice indexing
End of explanation
y = x[0:10:2]
y[0] = 100. # modify y
y
# x is modified:
x
Explanation: This sort of indexing does not make a copy:
End of explanation
x = np.arange(15)
y = x[[1, 2, 4]]
y
y[0] = 100
y
# x is not modified
x
Explanation: Indexing with indicies
End of explanation
x = np.arange(5)
x
mask = np.array([True, True, False, True, False])
x[mask]
# creates a copy
y = x[mask]
y[0] = 100.
print(y)
print(x)
Explanation: Indexing with booleans
End of explanation
x = np.array([1, 2, 3, -999, 2, 4, -999])
Explanation: How do you remember which type of indexing creates a copy?
NumPy arrays are stored as a chunk of data and a set of strides in each dimension.
Boolean and arbitrary indicies cannot be represented this way, so numpy must make a copy.
More on masking
All indexing operations also work in assigning to an array. Here we demonstrate assignment with booleans.
For example, imagine you have an array of data where negative values indicate some kind of error.
End of explanation
for i in range(len(x)):
if x[i] < 0:
x[i] = 0
x
x = np.array([1, 2, 3, -999, 2, 4, -999])
mask = (x < 0)
mask
Explanation: How might you clean this array, setting all negative values to, say, zero?
End of explanation
x[mask] = 0
x
Explanation: And the mask can be used directly to set the value you desire:
End of explanation
x = np.array([1, 2, 3, -999, 2, 4, -999])
x[x < 0] = 0
x
# additional boolean operations: invert
x = np.array([1, 2, 3, -999, 2, 4, -999])
x[~(x < 0)] = 0
x
x = np.array([1, 2, 3, -999, 2, 4, -999])
x[(x < 0) | (x > 3)] = 0
x
Explanation: Often you'll see this done in a separate step:
End of explanation
x = np.arange(4)
x
x + 3
Explanation: Broadcasting
End of explanation
x = np.array([[0, 0, 0],
[10, 10, 10],
[20, 20, 20],
[30, 30, 30]])
y = np.array([0, 1, 2])
print("x shape:", x.shape)
print("y shape: ", y.shape)
# If x and y are different dimensions, shape is padded on left with 1s
# before broadcasting.
x + y
Explanation:
End of explanation
x = np.array([[0],
[10],
[20],
[30]])
y = np.array([0, 1, 2])
print("x shape:", x.shape)
print("y shape: ", y.shape)
x + y
Explanation:
End of explanation
np.random.seed(0)
X = np.random.rand(5000)
X[np.random.randint(0, 5000, size=500)] = np.nan # 10% missing
X = X.reshape((1000, 5)) # 1000 points in 5 dimensions
# 1. Compute the number of points (rows) with no missing values, using `np.any` or `np.all`.
# 2. Clean the array, leaving only rows with no missing values
# 3. Compute the whitened version of the array using np.mean and np.std.
Explanation: Broadcasting rules:
If the two arrays differ in their number of dimensions, the shape of the array with fewer dimensions is padded with ones on its leading (left) side.
If the shape of the two arrays does not match in any dimension, the array with shape equal to 1 in that dimension is stretched to match the other shape.
If in any dimension the sizes disagree and neither is equal to 1, an error is raised.
Mini exercises
Assume you have $N$ points in $D$ dimensions, represented by an array of shape (N, D), where there are some mising values scattered throughout the points.
Count the number of points (rows) with no missing values, using np.any or np.all.
Clean the array of the points with missing values.
Construct the matrix M, the centered and normalized version of the X array: $$ M_{ij} = (X_{ij} - \mu_j) / \sigma_j $$ using np.mean and np.std. This is one version of whitening the array.
End of explanation
print(np.random.__doc__)
Explanation: What else is in NumPy?
numpy.random: Random number generation
numpy.linalg: Some linear algebra routines
numpy.fft: Fast Fourier Transform
End of explanation
# contents of scipy:
import scipy
print(scipy.__doc__)
Explanation: SciPy
Interestingly, scipy predates numpy by more than half a decade (circa 1999), even though it is built on top of numpy.
Originally "scipack", a collection of wrappers for Fortran NetLib libraries.
End of explanation
from astropy import coordinates as coords
from astropy import units as u
ra = 360. * np.random.rand(100)
dec = -90. + 180. * np.random.rand(100)
print("RA:", ra[:5], "...")
print("Dec:", dec[:5], "...")
c = coords.SkyCoord(ra, dec, unit=(u.deg, u.deg))
c
# convert to galactic
g = c.galactic
g
# access longitude or latitude
g.l
type(g.l)
# get underlying numpy array
g.l.degree
Explanation: Note the overlap:
numpy.fft / scipy.fft
numpy.linalg / scipy.linalg
Why the duplication? The scipy routines are based on Fortran libraries, whereas numpy is C-only.
AstroPy
Project started in 2011, in response to increasing duplication in Python astronomy ecosystem.
Initially brought together several existing Python packages:
astropy.io.fits (formerly pyfits)
astropy.io.ascii (formerly asciitable)
astropy.wcs (formerly pywcs)
astropy.cosmology (formerly cosmolopy)
Now also contains:
astropy.table (Table class and table operations)
astropy.units (Quantity: arrays with units)
astropy.coordinates (astronomical coordinate systems)
astropy.time (UTC, UT, MJD, etc)
astropy.stats (additional stats not in scipy)
astropy.modeling (simple model fitting)
astropy.vo (virtual observatory)
astropy.io.votable
astropy.analytic_functions
Example: Coordinates
End of explanation |
7,970 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sample Data Wrangling Project
OpenStreetMap Sample Project - Data Wrangling with MongoDB
Step1: 1 - Data Preparation
Map Area
Step2: 1.1 - Auditing Data
1.1.1 - node and way xml tags
A quick look at the different 'tag' available in our data set
Step3: Few tags are to be ignored for the rest of cleansing process as tag names contains problematic characters.
The auditing will focus on the following tags (to illustrate the different checks that could be put in place for cleansing) from the remaining tags
Step4: From the auditing, the following problems have been identified
Step5: 2.2 - MongoDB Import
Step6: 2.3 - Data Overview
Step7: Just peek the previously selected sample example from our python cleansing code
Step8: Check that we have the same count as the result of our python cleansing code
Step9: Count the number of "xml node" imported
Step10: How many different users have contributed to this database?
Step11: When did the contribution take place?
Step12: We have quite recent contributions for this dataset, let's identify the top 10 contributors?
Step13: We can consider having 1 top contributor followed by 5 high contributors... let see the distribution of the contribution for all users
Step14: The above ouput clearly show that we have outliers in term of user contribution... just see if mongodb can provide us the distribution of the all users contribution with a predefined bins.
Step15: The result confirm that most user are below 100 contributions and the main contributors are composed of 5 high contributors and TOP contributor
3 - How MongoDb will ease the data cleansing process...?
First focus on all document with type='node' and having a subdocument 'address'
Step16: There is some missing data for all selected attributes (with one Nan for postcode)
3.1 - City
Let see if we can identify any problems with city attribute... Can we recover the missing data for the city?
note
Step17: One remaining issue
Step18: The above code addressed most remaining issues not handled during the initial cleansing step, for the City and PostCode fields, what about street? What are the remaining issues?
Step19: Let's load updated file...and apply the mapping
note
Step20: We have identify some rules to (partially) update the addresses, why not updating the mongo database...
Postal Code and City | Python Code:
import pprint
import pandas as pd
import numpy as np
import csv
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
from IPython.display import Image, display
Explanation: Sample Data Wrangling Project
OpenStreetMap Sample Project - Data Wrangling with MongoDB
End of explanation
Image(filename='LaReunion.png', width=300, height=300)
from openstreetmap import audit, shape
from openstreetmap.data_gouv_fr import postalcode, fantoir
OSM_FILE = "data/Saint-Joseph.La-Reunion.osm"
Explanation: 1 - Data Preparation
Map Area: Saint-Joseph - Île de La Réunion
- http://www.openstreetmap.org/relation/1282272#map=12/-21.2918/55.6440
- http://overpass-api.de/api/map?bbox=55.4871,-21.4039,55.8009,-21.1796
End of explanation
!openstreetmap/tags.py -o data/Saint-Joseph.La-Reunion.osm
Explanation: 1.1 - Auditing Data
1.1.1 - node and way xml tags
A quick look at the different 'tag' available in our data set
End of explanation
# Official databases are filtered to limit the data for the area of interest aka 974**
# All tag values not compliants with the rules defined are listed in associated files under audit folder
# The diffirents files will be manually checked and updated for the next step in cleansing process
!openstreetmap/audit.py -i -o data/Saint-Joseph.La-Reunion.osm -f data/FANTOIR1016 -a 974 -u audit
Explanation: Few tags are to be ignored for the rest of cleansing process as tag names contains problematic characters.
The auditing will focus on the following tags (to illustrate the different checks that could be put in place for cleansing) from the remaining tags:
- population, capacity, elevation, direction, phone, postal_code
- addr:city, addr:postcode, addr:housenumber, addr:street
other tags will be included "as-is".
note: City, Post Code, Street name and type will be checked against official data sources (see references in audit.py)
End of explanation
!openstreetmap/shape.py -o data/Saint-Joseph.La-Reunion.osm -u update
Explanation: From the auditing, the following problems have been identified:
1. Some street types are wrongly spelled or abbreviated
2. No street type information for some street (all street listed under one single entry 'None' in our audit results)
3. Street name case not consistent (Full upercase, lowercase or mix)
4. House number contain more than one number (grouping of several houses is not considered as an issue for the auditing process and the validation rule has been updated to take it into account)
5. Same issue for the phone (e.g.: "0692407639;0692407637")
6. Some city are wrongly spelled or case not consistent (Full upercase, lowercase or mix)
7. An extra space inside postcode value + an unknown postcode value: 97447 to be replaced by 97442 according to the city name
2 - From XML to JSON to MongoDB
2.1 - Create JSON file
Based on the cleansing identified in previous section, Some values are partially or fully updated during the JSON file generation from the data recovered from associated files under update folder
End of explanation
# Drop previous database if any
!mongo OpenStreetMap --eval "db.dropDatabase()"
!mongoimport -d OpenStreetMap -c LaReunion --file data/Saint-Joseph.La-Reunion.osm.json
Explanation: 2.2 - MongoDB Import
End of explanation
from pymongo import MongoClient
from bson.son import SON
client = MongoClient()
def pretty(documents):
for document in documents:
pprint.pprint(document)
db = client.OpenStreetMap
Explanation: 2.3 - Data Overview
End of explanation
pretty(db.LaReunion.find({"id": "3480487005"}))
Explanation: Just peek the previously selected sample example from our python cleansing code
End of explanation
db.LaReunion.count() == 801017
Explanation: Check that we have the same count as the result of our python cleansing code
End of explanation
pipeline = [
{"$unwind": "$type"},
{"$group": {"_id": "$type", "count": {"$sum": 1}}},
{"$sort": SON([("count", -1), ("_id", -1)])}
]
nodes = pd.DataFrame(list(db.LaReunion.aggregate(pipeline)))
nodes.columns = ["node", "count"]
nodes.head()
Explanation: Count the number of "xml node" imported
End of explanation
len(db.LaReunion.find().distinct("created.user"))
Explanation: How many different users have contributed to this database?
End of explanation
pipeline = [
{"$project": {"_id": False, "timestamp": "$created.timestamp", "user": "$created.user" } },
{"$group": {"_id": "$timestamp", "users": { "$sum": 1 }}}
]
contributions = pd.DataFrame(list(db.LaReunion.aggregate(pipeline)))
contributions["_id"] = pd.to_datetime(contributions._id)
contributions.columns = ["date", "users"]
axes = contributions.set_index(['date']).plot(figsize=(12,6), title="Number of users contribution by date")
Explanation: When did the contribution take place?
End of explanation
pipeline = [
{ "$project": { "_id": False, "user": "$created.user" } },
{ "$group": { "_id": "$user", "count": { "$sum": 1 } } },
{ "$sort": SON([("count", -1), ("_id", -1)]) },
{ "$limit": 10 }
]
pretty(list(db.LaReunion.aggregate(pipeline)))
Explanation: We have quite recent contributions for this dataset, let's identify the top 10 contributors?
End of explanation
pipeline = [
{ "$project": { "_id": False, "user": "$created.user" } },
{ "$group": { "_id": "$user", "count": { "$sum": 1 } } },
{ "$sort": SON([("count", -1), ("_id", -1)]) },
{ "$project": { "_id": "$count"} }
]
contributions = pd.DataFrame(list(db.LaReunion.aggregate(pipeline)))
contributions.describe().T
Explanation: We can consider having 1 top contributor followed by 5 high contributors... let see the distribution of the contribution for all users
End of explanation
pipeline = [
{ "$project": { "_id": False, "user": "$created.user" } },
{ "$group": { "_id": "$user", "count": { "$sum": 1 } } },
{
"$bucket": {
"groupBy": "$count",
"boundaries": [ 1, 100, 10000, 25000, 100000 ],
"default": "TOP",
"output": {
"count": { "$sum": 1 },
"users": { "$push": "$_id" }
}
}
}
]
contributions = pd.DataFrame(list(db.LaReunion.aggregate(pipeline)))
contributions
Explanation: The above ouput clearly show that we have outliers in term of user contribution... just see if mongodb can provide us the distribution of the all users contribution with a predefined bins.
End of explanation
pipeline = [
{ "$match": { "type": "node", "address": { "$exists": True } } },
{ "$project": { "_id": False,
"city": "$address.city",
"housenumber": "$address.housenumber",
"postcode": "$address.postcode",
"street": "$address.street" } },
#{ "$limit": 10 }
]
addresses = pd.DataFrame(list(db.LaReunion.aggregate(pipeline)))
addresses.shape
addresses.describe()
Explanation: The result confirm that most user are below 100 contributions and the main contributors are composed of 5 high contributors and TOP contributor
3 - How MongoDb will ease the data cleansing process...?
First focus on all document with type='node' and having a subdocument 'address'
End of explanation
from openstreetmap.data_gouv_fr import postalcode
codes = postalcode.PostalCode("data/laposte_hexasmal.csv").localityByPostcode()
addresses.loc[:, "city"] = addresses.postcode.dropna().apply(lambda x: codes[int(x)].title())
addresses[(addresses.city.isnull() == True) & (addresses.postcode.isnull() == False)].city.count()
addresses.city.unique()
Explanation: There is some missing data for all selected attributes (with one Nan for postcode)
3.1 - City
Let see if we can identify any problems with city attribute... Can we recover the missing data for the city?
note: This will be possible if the postcode is not null... to crosscheck with the official postcal code database
End of explanation
addresses.set_index("postcode")["city"].dropna().to_dict()
Explanation: One remaining issue: a 'nan' value that could not be updated without extra information
End of explanation
# To compare with the official database, some french characters have to be translated to their corresponding ASCII
# what a pity for a french official database
xtd = {ord(u'’'): u"'", ord(u'é'): u'e', ord(u'è'): u'e', ord(u'É'): u'E',}
def tr(x):
return x.translate(xtd).upper()
ways_referential = fantoir.FANTOIR().ways("data/FANTOIR1016", "974")
addresses["CHECKED"] = addresses.street.dropna().apply(lambda x: tr(x) in ways_referential["FULL_NAME"].values)
# Generate a step 2 mapping file for manual street name update ... updated file to be moved to update folder
mapping = addresses[addresses.CHECKED == False]["street"].unique()
df = pd.DataFrame.from_dict({ "OLD": mapping, "NEW": mapping })
df.to_csv("audit/street_clean_step2.csv",
encoding='utf-8',
index=False,
quoting=csv.QUOTE_ALL)
Explanation: The above code addressed most remaining issues not handled during the initial cleansing step, for the City and PostCode fields, what about street? What are the remaining issues?
End of explanation
updated_mapping = pd.read_csv("update/street_clean_step2.csv", encoding='utf-8').set_index("NEW")["OLD"].to_dict()
addresses.loc[:, "street"] = addresses.street.apply(lambda x: x if x not in updated_mapping.keys()
else updated_mapping[x])
Explanation: Let's load updated file...and apply the mapping
note: not all street will be updated (limited to illustration purpose only)
End of explanation
for n in db.LaReunion.find({ "type": "node",
"address": { "$exists": True },
"address.postcode": { "$exists": True } }):
postcode = n["address"]["postcode"].replace(' ', '')
db.LaReunion.update_one({ "_id": n["_id"] }, { "$set": { "address.postcode": postcode } }, upsert=False)
for n in db.LaReunion.find({ "type": "node",
"address": { "$exists": True },
"address.postcode": { "$exists": True } }):
city = codes[int(n["address"]["postcode"])]
db.LaReunion.update_one({ "_id": n["_id"] }, { "$set": { "address.city": city } }, upsert=False)
pipeline = [
{ "$match": { "type": "node", "address": { "$exists": True }, "address.postcode": { "$exists": True } } },
{ "$project": { "_id": False,
"city": "$address.city",
"housenumber": "$address.housenumber",
"postcode": "$address.postcode",
"street": "$address.street" } },
{ "$limit": 10 }
]
pd.DataFrame(list(db.LaReunion.aggregate(pipeline)))
pretty(list(db.LaReunion.find({
"type": "node",
"address": { "$exists": True },
"address.city": { "$exists": False },
"address.postcode": { "$exists": False }}).limit(1)))
Explanation: We have identify some rules to (partially) update the addresses, why not updating the mongo database...
Postal Code and City
End of explanation |
7,971 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dropping PassengerId, Name and Ticket because they are unique.
Dropping Cabin because of too many null values.
Step1: Now need to take care of the missing data for Age variable. Need to approximate- one way, to take mean age for all the missing values.
Or, find if age is related to Pclass, and assign respective means.
Step2: If Passenger belongs to Pclass 3, age assigned is 24, if 2, age is assigned 29, if 1 then 37.
Step3: There are two null values in Embarked, we can just drop them.
Step4: Getting dummy variables from categorical ones.
Step5: The train test split is done for parameter tuning.
We now deploy the models.
Step6: Now taking in Competition Data.
Step7: There are 86 null values in Age, so we approximate them like we did earlier.
There are 327 null values in Cabin, so we drop it altogether.
There is 1 null value in Fare, so we approximate it according to the median of each class of the null position.
Step8: Cleaning up the test data
Step9: Prediction for Competition Data | Python Code:
titanic_data = titanic.drop(['PassengerId','Name','Ticket'],1)
titanic_data.head()
Explanation: Dropping PassengerId, Name and Ticket because they are unique.
Dropping Cabin because of too many null values.
End of explanation
sb.boxplot(x='Pclass',y='Age',data=titanic_data)
Explanation: Now need to take care of the missing data for Age variable. Need to approximate- one way, to take mean age for all the missing values.
Or, find if age is related to Pclass, and assign respective means.
End of explanation
def age_approx(cols):
age = cols[0]
pclass = cols[1]
if pd.isnull(age):
if pclass == 1:
return 37
elif pclass == 2:
return 29
else:
return 24
else:
return age
titanic_data['Age'] = titanic_data[['Age', 'Pclass']].apply(age_approx, axis=1)
titanic_data.isnull().sum()
def cabin_approx(cols):
cabin = cols[0]
pclass = cols[1]
if pd.isnull(cabin):
return 0
elif cabin[0] == ('C' or 'B'):
return 3
elif cabin[0] == ('A' or 'D' or 'E' or 'T'):
return 2
elif cabin[0] == ('F' or 'G'):
return 1
else:
return 0
titanic_data['Cabin'] = titanic_data[['Cabin', 'Pclass']].apply(cabin_approx, axis=1)
#titanic_data.isnull().sum()
sb.boxplot(x='Cabin',y='Fare',data=titanic_data)
Explanation: If Passenger belongs to Pclass 3, age assigned is 24, if 2, age is assigned 29, if 1 then 37.
End of explanation
titanic_data.dropna(inplace=True)
titanic_data.isnull().sum()
Explanation: There are two null values in Embarked, we can just drop them.
End of explanation
gender = pd.get_dummies(titanic_data['Sex'],drop_first=True)
gender.head()
embark_location = pd.get_dummies(titanic_data['Embarked'],drop_first=True)
embark_location.head()
titanic_data.drop(['Sex','Embarked'],axis=1,inplace=True)
titanic_data.head()
titanic_dmy = pd.concat([titanic_data, gender, embark_location],axis=1)
titanic_dmy.tail()
#Checking for correlation between variables.
sb.heatmap(titanic_dmy.corr(),square=True)
#print(titanic_dmy.corr())
X = titanic_dmy.ix[:,(1,2,3,4,5,6,7,8,9)].values
y = titanic_dmy.ix[:,0].values
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.1, random_state=2)
Explanation: Getting dummy variables from categorical ones.
End of explanation
!pip install xgboost
from sklearn.ensemble import RandomForestClassifier
#from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from xgboost import XGBClassifier
from sklearn.metrics import confusion_matrix
from sklearn.ensemble import VotingClassifier
clf1 = SVC(kernel='linear',C=1.0,random_state=3)
clf2 = XGBClassifier(random_state=3)
clf3 = RandomForestClassifier(n_estimators=30, max_depth=10, random_state=300)
eclf = VotingClassifier(estimators=[('clf1', clf1), ('clf2', clf2),('clf3',clf3)], voting='hard')
eclf.fit(X_train, y_train)
y_pred = eclf.predict(X_test)
print(confusion_matrix(y_test, y_pred))
print(eclf.score(X_test, y_test))
Explanation: The train test split is done for parameter tuning.
We now deploy the models.
End of explanation
url = 'C:\\Users\\ajaohri\\Desktop\\all/test.csv'
test = pd.read_csv(url)
test.head()
test.isnull().sum()
Explanation: Now taking in Competition Data.
End of explanation
test.describe()
sb.set(rc={'figure.figsize':(11.7,8.27)})
ax = sb.boxplot(x='Pclass',y='Fare',data=test,width=0.9)
def fare_approx(cols):
fare = cols[0]
pclass = cols[1]
if pd.isnull(fare):
if pclass == 1:
return 55
elif pclass == 2:
return 20
else:
return 10
else:
return fare
Explanation: There are 86 null values in Age, so we approximate them like we did earlier.
There are 327 null values in Cabin, so we drop it altogether.
There is 1 null value in Fare, so we approximate it according to the median of each class of the null position.
End of explanation
test_data = test.drop(['Name','Ticket'],1)
test_data['Age'] = test_data[['Age', 'Pclass']].apply(age_approx, axis=1)
test_data['Fare'] = test_data[['Fare','Pclass']].apply(fare_approx, axis=1)
test_data['Cabin'] = test_data[['Cabin','Pclass']].apply(cabin_approx, axis=1)
#
gender_test = pd.get_dummies(test_data['Sex'],drop_first=True)
embark_location_test = pd.get_dummies(test_data['Embarked'],drop_first=True)
test_data.drop(['Sex','Embarked'],axis=1,inplace=True)
test_dmy = pd.concat([test_data, gender_test, embark_location_test],axis=1)
#test_dmy.describe()
test_data.dropna(inplace=True)
test_dmy.isnull().sum()
test_dmy.head()
X_competition = test_dmy.ix[:,(1,2,3,4,5,6,7,8,9)].values
Explanation: Cleaning up the test data:
Dropping variables, approximating age and fare, dummy variables.
End of explanation
y_comp = eclf.predict(X_competition)
submission = pd.DataFrame({'PassengerId':test_data['PassengerId'],'Survived':y_comp})
submission.head()
filename = 'Titanic Predictions 1.csv'
submission.to_csv(filename,index=False)
print('Saved file: ' + filename)
os.getcwd()
Explanation: Prediction for Competition Data
End of explanation |
7,972 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Neural Machine Translation with Attention
<table class="tfo-notebook-buttons" align="left"><td>
<a target="_blank" href="https
Step1: Download and prepare the dataset
We'll use a language dataset provided by http
Step2: Limit the size of the dataset to experiment faster (optional)
Training on the complete dataset of >100,000 sentences will take a long time. To train faster, we can limit the size of the dataset to 30,000 sentences (of course, translation quality degrades with less data)
Step3: Create a tf.data dataset
Step4: Write the encoder and decoder model
Here, we'll implement an encoder-decoder model with attention which you can read about in the TensorFlow Neural Machine Translation (seq2seq) tutorial. This example uses a more recent set of APIs. This notebook implements the attention equations from the seq2seq tutorial. The following diagram shows that each input words is assigned a weight by the attention mechanism which is then used by the decoder to predict the next word in the sentence.
<img src="https
Step5: Define the optimizer and the loss function
Step6: Checkpoints (Object-based saving)
Step7: Training
Pass the input through the encoder which return encoder output and the encoder hidden state.
The encoder output, encoder hidden state and the decoder input (which is the start token) is passed to the decoder.
The decoder returns the predictions and the decoder hidden state.
The decoder hidden state is then passed back into the model and the predictions are used to calculate the loss.
Use teacher forcing to decide the next input to the decoder.
Teacher forcing is the technique where the target word is passed as the next input to the decoder.
The final step is to calculate the gradients and apply it to the optimizer and backpropagate.
Step8: Translate
The evaluate function is similar to the training loop, except we don't use teacher forcing here. The input to the decoder at each time step is its previous predictions along with the hidden state and the encoder output.
Stop predicting when the model predicts the end token.
And store the attention weights for every time step.
Note
Step9: Restore the latest checkpoint and test | Python Code:
from __future__ import absolute_import, division, print_function
# Import TensorFlow >= 1.10 and enable eager execution
import tensorflow as tf
tf.enable_eager_execution()
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import unicodedata
import re
import numpy as np
import os
import time
print(tf.__version__)
Explanation: Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Neural Machine Translation with Attention
<table class="tfo-notebook-buttons" align="left"><td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb">
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td><td>
<a target="_blank" href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a></td></table>
This notebook trains a sequence to sequence (seq2seq) model for Spanish to English translation using tf.keras and eager execution. This is an advanced example that assumes some knowledge of sequence to sequence models.
After training the model in this notebook, you will be able to input a Spanish sentence, such as "¿todavia estan en casa?", and return the English translation: "are you still at home?"
The translation quality is reasonable for a toy example, but the generated attention plot is perhaps more interesting. This shows which parts of the input sentence has the model's attention while translating:
<img src="https://tensorflow.org/images/spanish-english.png" alt="spanish-english attention plot">
Note: This example takes approximately 10 mintues to run on a single P100 GPU.
End of explanation
# Download the file
path_to_zip = tf.keras.utils.get_file(
'spa-eng.zip', origin='http://download.tensorflow.org/data/spa-eng.zip',
extract=True)
path_to_file = os.path.dirname(path_to_zip)+"/spa-eng/spa.txt"
# Converts the unicode file to ascii
def unicode_to_ascii(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
def preprocess_sentence(w):
w = unicode_to_ascii(w.lower().strip())
# creating a space between a word and the punctuation following it
# eg: "he is a boy." => "he is a boy ."
# Reference:- https://stackoverflow.com/questions/3645931/python-padding-punctuation-with-white-spaces-keeping-punctuation
w = re.sub(r"([?.!,¿])", r" \1 ", w)
w = re.sub(r'[" "]+', " ", w)
# replacing everything with space except (a-z, A-Z, ".", "?", "!", ",")
w = re.sub(r"[^a-zA-Z?.!,¿]+", " ", w)
w = w.rstrip().strip()
# adding a start and an end token to the sentence
# so that the model know when to start and stop predicting.
w = '<start> ' + w + ' <end>'
return w
# 1. Remove the accents
# 2. Clean the sentences
# 3. Return word pairs in the format: [ENGLISH, SPANISH]
def create_dataset(path, num_examples):
lines = open(path, encoding='UTF-8').read().strip().split('\n')
word_pairs = [[preprocess_sentence(w) for w in l.split('\t')] for l in lines[:num_examples]]
return word_pairs
# This class creates a word -> index mapping (e.g,. "dad" -> 5) and vice-versa
# (e.g., 5 -> "dad") for each language,
class LanguageIndex():
def __init__(self, lang):
self.lang = lang
self.word2idx = {}
self.idx2word = {}
self.vocab = set()
self.create_index()
def create_index(self):
for phrase in self.lang:
self.vocab.update(phrase.split(' '))
self.vocab = sorted(self.vocab)
self.word2idx['<pad>'] = 0
for index, word in enumerate(self.vocab):
self.word2idx[word] = index + 1
for word, index in self.word2idx.items():
self.idx2word[index] = word
def max_length(tensor):
return max(len(t) for t in tensor)
def load_dataset(path, num_examples):
# creating cleaned input, output pairs
pairs = create_dataset(path, num_examples)
# index language using the class defined above
inp_lang = LanguageIndex(sp for en, sp in pairs)
targ_lang = LanguageIndex(en for en, sp in pairs)
# Vectorize the input and target languages
# Spanish sentences
input_tensor = [[inp_lang.word2idx[s] for s in sp.split(' ')] for en, sp in pairs]
# English sentences
target_tensor = [[targ_lang.word2idx[s] for s in en.split(' ')] for en, sp in pairs]
# Calculate max_length of input and output tensor
# Here, we'll set those to the longest sentence in the dataset
max_length_inp, max_length_tar = max_length(input_tensor), max_length(target_tensor)
# Padding the input and output tensor to the maximum length
input_tensor = tf.keras.preprocessing.sequence.pad_sequences(input_tensor,
maxlen=max_length_inp,
padding='post')
target_tensor = tf.keras.preprocessing.sequence.pad_sequences(target_tensor,
maxlen=max_length_tar,
padding='post')
return input_tensor, target_tensor, inp_lang, targ_lang, max_length_inp, max_length_tar
Explanation: Download and prepare the dataset
We'll use a language dataset provided by http://www.manythings.org/anki/. This dataset contains language translation pairs in the format:
May I borrow this book? ¿Puedo tomar prestado este libro?
There are a variety of languages available, but we'll use the English-Spanish dataset. For convenience, we've hosted a copy of this dataset on Google Cloud, but you can also download your own copy. After downloading the dataset, here are the steps we'll take to prepare the data:
Add a start and end token to each sentence.
Clean the sentences by removing special characters.
Create a word index and reverse word index (dictionaries mapping from word → id and id → word).
Pad each sentence to a maximum length.
End of explanation
# Try experimenting with the size of that dataset
num_examples = 30000
input_tensor, target_tensor, inp_lang, targ_lang, max_length_inp, max_length_targ = load_dataset(path_to_file, num_examples)
# Creating training and validation sets using an 80-20 split
input_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2)
# Show length
len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val)
Explanation: Limit the size of the dataset to experiment faster (optional)
Training on the complete dataset of >100,000 sentences will take a long time. To train faster, we can limit the size of the dataset to 30,000 sentences (of course, translation quality degrades with less data):
End of explanation
BUFFER_SIZE = len(input_tensor_train)
BATCH_SIZE = 64
N_BATCH = BUFFER_SIZE//BATCH_SIZE
embedding_dim = 256
units = 1024
vocab_inp_size = len(inp_lang.word2idx)
vocab_tar_size = len(targ_lang.word2idx)
dataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE)
dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)
Explanation: Create a tf.data dataset
End of explanation
def gru(units):
# If you have a GPU, we recommend using CuDNNGRU(provides a 3x speedup than GRU)
# the code automatically does that.
if tf.test.is_gpu_available():
return tf.keras.layers.CuDNNGRU(units,
return_sequences=True,
return_state=True,
recurrent_initializer='glorot_uniform')
else:
return tf.keras.layers.GRU(units,
return_sequences=True,
return_state=True,
recurrent_activation='sigmoid',
recurrent_initializer='glorot_uniform')
class Encoder(tf.keras.Model):
def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):
super(Encoder, self).__init__()
self.batch_sz = batch_sz
self.enc_units = enc_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru = gru(self.enc_units)
def call(self, x, hidden):
x = self.embedding(x)
output, state = self.gru(x, initial_state = hidden)
return output, state
def initialize_hidden_state(self):
return tf.zeros((self.batch_sz, self.enc_units))
class Decoder(tf.keras.Model):
def __init__(self, vocab_size, embedding_dim, dec_units, batch_sz):
super(Decoder, self).__init__()
self.batch_sz = batch_sz
self.dec_units = dec_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru = gru(self.dec_units)
self.fc = tf.keras.layers.Dense(vocab_size)
# used for attention
self.W1 = tf.keras.layers.Dense(self.dec_units)
self.W2 = tf.keras.layers.Dense(self.dec_units)
self.V = tf.keras.layers.Dense(1)
def call(self, x, hidden, enc_output):
# enc_output shape == (batch_size, max_length, hidden_size)
# hidden shape == (batch_size, hidden size)
# hidden_with_time_axis shape == (batch_size, 1, hidden size)
# we are doing this to perform addition to calculate the score
hidden_with_time_axis = tf.expand_dims(hidden, 1)
# score shape == (batch_size, max_length, 1)
# we get 1 at the last axis because we are applying tanh(FC(EO) + FC(H)) to self.V
score = self.V(tf.nn.tanh(self.W1(enc_output) + self.W2(hidden_with_time_axis)))
# attention_weights shape == (batch_size, max_length, 1)
attention_weights = tf.nn.softmax(score, axis=1)
# context_vector shape after sum == (batch_size, hidden_size)
context_vector = attention_weights * enc_output
context_vector = tf.reduce_sum(context_vector, axis=1)
# x shape after passing through embedding == (batch_size, 1, embedding_dim)
x = self.embedding(x)
# x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size)
x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)
# passing the concatenated vector to the GRU
output, state = self.gru(x)
# output shape == (batch_size * 1, hidden_size)
output = tf.reshape(output, (-1, output.shape[2]))
# output shape == (batch_size * 1, vocab)
x = self.fc(output)
return x, state, attention_weights
def initialize_hidden_state(self):
return tf.zeros((self.batch_sz, self.dec_units))
encoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)
decoder = Decoder(vocab_tar_size, embedding_dim, units, BATCH_SIZE)
Explanation: Write the encoder and decoder model
Here, we'll implement an encoder-decoder model with attention which you can read about in the TensorFlow Neural Machine Translation (seq2seq) tutorial. This example uses a more recent set of APIs. This notebook implements the attention equations from the seq2seq tutorial. The following diagram shows that each input words is assigned a weight by the attention mechanism which is then used by the decoder to predict the next word in the sentence.
<img src="https://www.tensorflow.org/images/seq2seq/attention_mechanism.jpg" width="500" alt="attention mechanism">
The input is put through an encoder model which gives us the encoder output of shape (batch_size, max_length, hidden_size) and the encoder hidden state of shape (batch_size, hidden_size).
Here are the equations that are implemented:
<img src="https://www.tensorflow.org/images/seq2seq/attention_equation_0.jpg" alt="attention equation 0" width="800">
<img src="https://www.tensorflow.org/images/seq2seq/attention_equation_1.jpg" alt="attention equation 1" width="800">
We're using Bahdanau attention. Lets decide on notation before writing the simplified form:
FC = Fully connected (dense) layer
EO = Encoder output
H = hidden state
X = input to the decoder
And the pseudo-code:
score = FC(tanh(FC(EO) + FC(H)))
attention weights = softmax(score, axis = 1). Softmax by default is applied on the last axis but here we want to apply it on the 1st axis, since the shape of score is (batch_size, max_length, 1). Max_length is the length of our input. Since we are trying to assign a weight to each input, softmax should be applied on that axis.
context vector = sum(attention weights * EO, axis = 1). Same reason as above for choosing axis as 1.
embedding output = The input to the decoder X is passed through an embedding layer.
merged vector = concat(embedding output, context vector)
This merged vector is then given to the GRU
The shapes of all the vectors at each step have been specified in the comments in the code:
End of explanation
optimizer = tf.train.AdamOptimizer()
def loss_function(real, pred):
mask = 1 - np.equal(real, 0)
loss_ = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=real, logits=pred) * mask
return tf.reduce_mean(loss_)
Explanation: Define the optimizer and the loss function
End of explanation
checkpoint_dir = './training_checkpoints'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint = tf.train.Checkpoint(optimizer=optimizer,
encoder=encoder,
decoder=decoder)
Explanation: Checkpoints (Object-based saving)
End of explanation
EPOCHS = 10
for epoch in range(EPOCHS):
start = time.time()
hidden = encoder.initialize_hidden_state()
total_loss = 0
for (batch, (inp, targ)) in enumerate(dataset):
loss = 0
with tf.GradientTape() as tape:
enc_output, enc_hidden = encoder(inp, hidden)
dec_hidden = enc_hidden
dec_input = tf.expand_dims([targ_lang.word2idx['<start>']] * BATCH_SIZE, 1)
# Teacher forcing - feeding the target as the next input
for t in range(1, targ.shape[1]):
# passing enc_output to the decoder
predictions, dec_hidden, _ = decoder(dec_input, dec_hidden, enc_output)
loss += loss_function(targ[:, t], predictions)
# using teacher forcing
dec_input = tf.expand_dims(targ[:, t], 1)
batch_loss = (loss / int(targ.shape[1]))
total_loss += batch_loss
variables = encoder.variables + decoder.variables
gradients = tape.gradient(loss, variables)
optimizer.apply_gradients(zip(gradients, variables))
if batch % 100 == 0:
print('Epoch {} Batch {} Loss {:.4f}'.format(epoch + 1,
batch,
batch_loss.numpy()))
# saving (checkpoint) the model every 2 epochs
if (epoch + 1) % 2 == 0:
checkpoint.save(file_prefix = checkpoint_prefix)
print('Epoch {} Loss {:.4f}'.format(epoch + 1,
total_loss / N_BATCH))
print('Time taken for 1 epoch {} sec\n'.format(time.time() - start))
Explanation: Training
Pass the input through the encoder which return encoder output and the encoder hidden state.
The encoder output, encoder hidden state and the decoder input (which is the start token) is passed to the decoder.
The decoder returns the predictions and the decoder hidden state.
The decoder hidden state is then passed back into the model and the predictions are used to calculate the loss.
Use teacher forcing to decide the next input to the decoder.
Teacher forcing is the technique where the target word is passed as the next input to the decoder.
The final step is to calculate the gradients and apply it to the optimizer and backpropagate.
End of explanation
def evaluate(sentence, encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ):
attention_plot = np.zeros((max_length_targ, max_length_inp))
sentence = preprocess_sentence(sentence)
inputs = [inp_lang.word2idx[i] for i in sentence.split(' ')]
inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs], maxlen=max_length_inp, padding='post')
inputs = tf.convert_to_tensor(inputs)
result = ''
hidden = [tf.zeros((1, units))]
enc_out, enc_hidden = encoder(inputs, hidden)
dec_hidden = enc_hidden
dec_input = tf.expand_dims([targ_lang.word2idx['<start>']], 0)
for t in range(max_length_targ):
predictions, dec_hidden, attention_weights = decoder(dec_input, dec_hidden, enc_out)
# storing the attention weigths to plot later on
attention_weights = tf.reshape(attention_weights, (-1, ))
attention_plot[t] = attention_weights.numpy()
predicted_id = tf.argmax(predictions[0]).numpy()
result += targ_lang.idx2word[predicted_id] + ' '
if targ_lang.idx2word[predicted_id] == '<end>':
return result, sentence, attention_plot
# the predicted ID is fed back into the model
dec_input = tf.expand_dims([predicted_id], 0)
return result, sentence, attention_plot
# function for plotting the attention weights
def plot_attention(attention, sentence, predicted_sentence):
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(1, 1, 1)
ax.matshow(attention, cmap='viridis')
fontdict = {'fontsize': 14}
ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90)
ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict)
plt.show()
def translate(sentence, encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ):
result, sentence, attention_plot = evaluate(sentence, encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)
print('Input: {}'.format(sentence))
print('Predicted translation: {}'.format(result))
attention_plot = attention_plot[:len(result.split(' ')), :len(sentence.split(' '))]
plot_attention(attention_plot, sentence.split(' '), result.split(' '))
Explanation: Translate
The evaluate function is similar to the training loop, except we don't use teacher forcing here. The input to the decoder at each time step is its previous predictions along with the hidden state and the encoder output.
Stop predicting when the model predicts the end token.
And store the attention weights for every time step.
Note: The encoder output is calculated only once for one input.
End of explanation
# restoring the latest checkpoint in checkpoint_dir
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
translate(u'hace mucho frio aqui.', encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)
translate(u'esta es mi vida.', encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)
translate(u'todavia estan en casa?', encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)
# wrong translation
translate(u'trata de averiguarlo.', encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)
Explanation: Restore the latest checkpoint and test
End of explanation |
7,973 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating and Manipulating Tensors
Learning Objectives
Step1: Vector Addition
You can perform many typical mathematical operations on tensors (TF API). The following code
creates and manipulates two vectors (1-D tensors), each having exactly six elements
Step2: Tensor Shapes
Shapes are used to characterize the size and number of dimensions of a tensor. The shape of a tensor is expressed as list, with the ith element representing the size along dimension i. The length of the list then indicates the rank of the tensor (i.e., the number of dimensions).
For more information, see the TensorFlow documentation.
A few basic examples
Step3: Broadcasting
In mathematics, you can only perform element-wise operations (e.g. add and equals) on tensors of the same shape. In TensorFlow, however, you may perform operations on tensors that would traditionally have been incompatible. TensorFlow supports broadcasting (a concept borrowed from numpy), where the smaller array in an element-wise operation is enlarged to have the same shape as the larger array. For example, via broadcasting
Step4: Matrix Multiplication
In linear algebra, when multiplying two matrices, the number of columns of the first matrix must
equal the number of rows in the second matrix.
It is valid to multiply a 3x4 matrix by a 4x2 matrix. This will result in a 3x2 matrix.
It is invalid to multiply a 4x2 matrix by a 3x4 matrix.
Step5: Tensor Reshaping
With tensor addition and matrix multiplication each imposing constraints
on operands, TensorFlow programmers must frequently reshape tensors.
You can use the tf.reshape method to reshape a tensor.
For example, you can reshape a 8x2 tensor into a 2x8 tensor or a 4x4 tensor
Step6: You can also use tf.reshape to change the number of dimensions (the "rank") of the tensor.
For example, you could reshape that 8x2 tensor into a 3-D 2x2x4 tensor or a 1-D 16-element tensor.
Step7: Exercise #1
Step8: Variables, Initialization and Assignment
So far, all the operations we performed were on static values (tf.constant); calling eval() always returned the same result. TensorFlow allows you to define Variable objects, whose values can be changed.
When creating a variable, you can set an initial value explicitly, or you can use an initializer (like a distribution)
Step9: One peculiarity of TensorFlow is that variable initialization is not automatic. For example, the following block will cause an error
Step10: The easiest way to initialize a variable is to call global_variables_initializer. Note the use of Session.run(), which is roughly equivalent to eval().
Step11: Once initialized, variables will maintain their value within the same session (however, when starting a new session, you will need to re-initialize them)
Step12: To change the value of a variable, use the assign op. Note that simply creating the assign op will not have any effect. As with initialization, you have to run the assignment op to update the variable value
Step13: Exercise #2 | Python Code:
import tensorflow as tf
Explanation: Creating and Manipulating Tensors
Learning Objectives:
- Initialize and assing TensorFlow Variables
- Create and manipulate tensors
- Refresh your memory about addition and multiplication in linear algebra (consult an introduction to matrix addition and multiplication if these topics are new to you)
- Familiarize yourself with basic TensorFlow math and array operations
End of explanation
with tf.Graph().as_default():
# Create a six-element vector (1-D tensor).
primes = tf.constant([2, 3, 5, 7, 11, 13], dtype=tf.int32)
# Create another six-element vector. Each element in the vector will be
# initialized to 1. The first argument is the shape of the tensor (more on shapes below).
ones = tf.ones([6], dtype=tf.int32)
# Add the two vectors. The resulting tensor is a six-element vector.
primes_plus_one = tf.add(primes, ones)
# Create a session to run the default graph.
with tf.Session() as sess:
print(primes_plus_one.eval())
Explanation: Vector Addition
You can perform many typical mathematical operations on tensors (TF API). The following code
creates and manipulates two vectors (1-D tensors), each having exactly six elements:
End of explanation
with tf.Graph().as_default():
# A scalar (0-D tensor).
scalar = tf.zeros([])
# A vector with 3 elements.
vector = tf.zeros([3])
# A matrix with 2 rows and 3 columns
matrix = tf.zeros([2, 3])
with tf.Session() as sess:
print("Scalar shape: {0} and the value:\n {1}".format(scalar.get_shape(), scalar.eval()))
print("Vector shape: {0} and the value:\n {1}".format(vector.get_shape(), vector.eval()))
print("Matrix shape: {0} and the value:\n {1}".format(matrix.get_shape(), matrix.eval()))
Explanation: Tensor Shapes
Shapes are used to characterize the size and number of dimensions of a tensor. The shape of a tensor is expressed as list, with the ith element representing the size along dimension i. The length of the list then indicates the rank of the tensor (i.e., the number of dimensions).
For more information, see the TensorFlow documentation.
A few basic examples:
End of explanation
with tf.Graph().as_default():
# Create a six-element vector (1-D tensor).
primes = tf.constant([2, 3, 5, 7, 11, 13], dtype=tf.int32)
# Create a constant scalar with value 1.
ones = tf.constant(1, dtype=tf.int32)
# Add the two tensors. The resulting tensor is a six-element vector.
primes_plus_one = tf.add(primes, ones)
with tf.Session() as sess:
print(primes_plus_one.eval())
Explanation: Broadcasting
In mathematics, you can only perform element-wise operations (e.g. add and equals) on tensors of the same shape. In TensorFlow, however, you may perform operations on tensors that would traditionally have been incompatible. TensorFlow supports broadcasting (a concept borrowed from numpy), where the smaller array in an element-wise operation is enlarged to have the same shape as the larger array. For example, via broadcasting:
If an operand requires a size [6] tensor, a size [1] or a size [] tensor can serve as an operand.
If an operation requires a size [4, 6] tensor, any of the following sizes can serve as an operand:
[1, 6]
[6]
[]
If an operation requires a size [3, 5, 6] tensor, any of the following sizes can serve as an operand:
[1, 5, 6]
[3, 1, 6]
[3, 5, 1]
[1, 1, 1]
[5, 6]
[1, 6]
[6]
[1]
[]
NOTE: When a tensor is broadcast, its entries are conceptually copied. (They are not actually copied for performance reasons. Broadcasting was invented as a performance optimization.)
The full broadcasting ruleset is well described in the easy-to-read numpy broadcasting documentation.
The following code performs the same tensor addition as before, but using broadcasting:
End of explanation
with tf.Graph().as_default():
# Create a matrix (2-d tensor) with 3 rows and 4 columns.
# | 5, 2, 4, 3 |
# | 5, 1, 6, -2 |
# | -1, 3, -1, -2 |
x = tf.constant([[5, 2, 4, 3], [5, 1, 6, -2], [-1, 3, -1, -2]], dtype=tf.int32)
# Create a matrix with 4 rows and 2 columns.
# | -2, 3 |
# | 2, 6 |
# | -1, 1 |
# | 0, 8 |
y = tf.constant([[-2, 3], [2, 6], [-1, 1], [0, 8]], dtype=tf.int32)
# Multiply `x` by `y`. The resulting matrix will have 3 rows and 2 columns.
matrix_mul_result = tf.matmul(x, y)
with tf.Session() as sess:
print(matrix_mul_result.eval())
Explanation: Matrix Multiplication
In linear algebra, when multiplying two matrices, the number of columns of the first matrix must
equal the number of rows in the second matrix.
It is valid to multiply a 3x4 matrix by a 4x2 matrix. This will result in a 3x2 matrix.
It is invalid to multiply a 4x2 matrix by a 3x4 matrix.
End of explanation
with tf.Graph().as_default():
# Create an 8x2 matrix (2-D tensor).
x = tf.constant([[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13, 14], [15,16]], dtype=tf.int32)
# Reshape the 8x2 matrix to 2x8 matrix.
x_reshaped_2x8 = tf.reshape(x, [2, 8])
# Reshape the 8x2 matrix to 4x4 matrix.
x_reshaped_4x4 = tf.reshape(x, [4, 4])
with tf.Session() as sess:
print("Original matrix (8x2):\n{0}".format(x.eval()))
print("Reshaped matrix (2x8):\n{0}".format(x_reshaped_2x8.eval()))
print("Reshaped matrix (4x4):\n{0}".format(x_reshaped_4x4.eval()))
Explanation: Tensor Reshaping
With tensor addition and matrix multiplication each imposing constraints
on operands, TensorFlow programmers must frequently reshape tensors.
You can use the tf.reshape method to reshape a tensor.
For example, you can reshape a 8x2 tensor into a 2x8 tensor or a 4x4 tensor:
End of explanation
with tf.Graph().as_default():
# Create an 8x2 matrix (2-D tensor).
x = tf.constant([[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13, 14], [15,16]], dtype=tf.int32)
# Reshape the 8x2 matrix to 2x2x4 (3-D tensor).
x_reshaped_2x2x4 = tf.reshape(x, [2, 2, 4])
# Reshape the 8x2 matrix to 16-element (1-D tensor).
x_reshaped_16 = tf.reshape(x, [16])
with tf.Session() as sess:
print("Original matrix (8x2):\n{0}".format(x.eval()))
print("Reshaped 3-D tensor (2x2x4):\n{0}".format(x_reshaped_2x2x4.eval()))
print("Reshaped 1-D vector (16):\n{0}".format(x_reshaped_16.eval()))
Explanation: You can also use tf.reshape to change the number of dimensions (the "rank") of the tensor.
For example, you could reshape that 8x2 tensor into a 3-D 2x2x4 tensor or a 1-D 16-element tensor.
End of explanation
with tf.Graph().as_default():
# initialize given matrices
a = tf.constant([5, 3, 2, 7, 1, 4])
b = tf.constant([4, 6, 3])
# reshape a to 2x3 and b to 3x1
reshaped_a = tf.reshape(a, [2, 3])
reshaped_b = tf.reshape(b, [3, 1])
# result of multiplication of 2x3 and 3x1 matrices will be a 2x1 matrix
mul_a_b = tf.matmul(reshaped_a, reshaped_b)
with tf.Session() as sess:
print("Multiplication of a and b:\n{0}".format(mul_a_b.eval()))
Explanation: Exercise #1: Reshape two tensors in order to multiply them.
The following two vectors are incompatible for matrix multiplication:
a = tf.constant([5, 3, 2, 7, 1, 4])
b = tf.constant([4, 6, 3])
Reshape these vectors into compatible operands for matrix multiplication.
Then, invoke a matrix multiplication operation on the reshaped tensors.
End of explanation
g = tf.Graph()
with g.as_default():
# Create a variable with the initial value of 3
v = tf.Variable([3])
# Create a variable of shape [1], with a random initial value,
# sampled from a normal distribution with mean 1 and standard deviation 0.35.
w = tf.Variable(tf.random_normal([1], mean=1, stddev=0.35))
Explanation: Variables, Initialization and Assignment
So far, all the operations we performed were on static values (tf.constant); calling eval() always returned the same result. TensorFlow allows you to define Variable objects, whose values can be changed.
When creating a variable, you can set an initial value explicitly, or you can use an initializer (like a distribution):
End of explanation
with g.as_default():
with tf.Session() as sess:
try:
v.eval()
except tf.errors.FailedPreconditionError as e:
print("Caught expected error: {0}".format(e))
Explanation: One peculiarity of TensorFlow is that variable initialization is not automatic. For example, the following block will cause an error:
End of explanation
with g.as_default():
with tf.Session() as sess:
initialization = tf.global_variables_initializer()
sess.run(initialization)
# Now, variables can be accessed normally, and have values assigned to them.
print(v.eval())
print(w.eval())
Explanation: The easiest way to initialize a variable is to call global_variables_initializer. Note the use of Session.run(), which is roughly equivalent to eval().
End of explanation
with g.as_default():
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# These three prints will print the same value.
print(w.eval())
print(w.eval())
print(w.eval())
Explanation: Once initialized, variables will maintain their value within the same session (however, when starting a new session, you will need to re-initialize them):
End of explanation
with g.as_default():
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# Print the current value of v
print(v.eval())
assignment = tf.assign(v, [7])
# The variable has not changed yet!
print(v.eval())
# Execute the assignment op.
sess.run(assignment)
# Now the variable is updated.
print(v.eval())
Explanation: To change the value of a variable, use the assign op. Note that simply creating the assign op will not have any effect. As with initialization, you have to run the assignment op to update the variable value:
End of explanation
with tf.Graph().as_default():
# Creating a 10x2 dices matrix with min value of 1 and max value of 6
dices = tf.Variable(tf.random_uniform([10, 2], minval=1, maxval=7, dtype=tf.int32))
# Calculating the sum of rows in dices matrix
dices_sum = tf.reduce_sum(dices, 1)
# Reshaping the sum matrix to 10x1 from 1x10 concat with dices matrix
dices_sum = tf.reshape(dices_sum, [10, 1])
# Concat two matrices
dices = tf.concat([dices, dices_sum], 1)
with tf.Session() as sess:
initialization = tf.global_variables_initializer()
sess.run(initialization)
print(dices.eval())
Explanation: Exercise #2: Simulate 10 rolls of two dice.
Create a dice simulation, which generates a 10x3 2-D tensor in which:
Columns 1 and 2 each hold one throw of one die.
Column 3 holds the sum of Columns 1 and 2 on the same row.
For example, the first row might have the following values:
Column 1 holds 4
Column 2 holds 3
Column 3 holds 7
You'll need to explore the TensorFlow documentation to solve this task.
End of explanation |
7,974 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LBYL versus EAFP
In some other languages,
one can not recover from an error,
or it is difficult to recover from an error,
so one tests input before doing something that could provoke the error.
This technique is called Look Before You Leap (LBYL)
For example, one must avoid dividing by zero.
Below is code that divides by numbers. When it gets the zero, it crashes.
Step1: So one checks before dividing as shown below.
Checking before doing something is called "Look Before You Leap" (LBYL).
Step2: Another technique is to just try stuff,
and if it blows up, do something else.
This technique is called Easier to Ask Forgiveness than Permission (EAFP).
Python makes it very easy to do something else
when something blows up.
Step3: For that simple example,
EAFP does not have much if any benefit over LBYL.
For that simple example,
there is not much benefit in the size or readability of the code.
However, for more complicated problems,
EAFP lets one write much simpler and readable code.
We will use the example of determining if a string is a valid float for Python.
See
2.4.6. Floating point literals
for what constitutes a valid float.
floatnumber
Step4: Now we try EAFP technique below.
Step5: The EAFP code is much much simpler.
The LBYL version was very complicated.
If there was a bug in the LBYL version, how would you find it?
If you fixed it, how much confidence would you have that your fix is correct?
How hard would it be to have test cases that covered all the edge cases?
How much confidence would you have that the test cases were comprehensive?
EAFP makes code easier to read, simpler, and more reliable.
This is what makes try/except one of Python's superpowers!!!
try/except best practices
Should | Python Code:
numbers = (3, 1, 0, -1, -2)
def foo(x):
return 10 // x
for x in numbers:
y = foo(x)
print(f'foo({x}) --> {y}')
Explanation: LBYL versus EAFP
In some other languages,
one can not recover from an error,
or it is difficult to recover from an error,
so one tests input before doing something that could provoke the error.
This technique is called Look Before You Leap (LBYL)
For example, one must avoid dividing by zero.
Below is code that divides by numbers. When it gets the zero, it crashes.
End of explanation
def foo(x):
if x == 0:
y = 0
else:
y = 10 // x
return y
for x in numbers:
y = foo(x)
print(f'foo({x}) --> {y}')
Explanation: So one checks before dividing as shown below.
Checking before doing something is called "Look Before You Leap" (LBYL).
End of explanation
def foo(x):
try:
y = 10 // x
except ZeroDivisionError:
y = 0
return y
for x in numbers:
y = foo(x)
print(f'foo({x}) --> {y}')
Explanation: Another technique is to just try stuff,
and if it blows up, do something else.
This technique is called Easier to Ask Forgiveness than Permission (EAFP).
Python makes it very easy to do something else
when something blows up.
End of explanation
import re
def is_float(s, debug=False):
digit = f'([0-9])'
digitpart = f'({digit}(_?{digit})*)' # digit (["_"] digit)*
fraction = f'([.]{digitpart})' # "." digitpart
pointfloat = f'(({digitpart}?{fraction}) | ({digitpart}[.]))' # [digitpart] fraction | digitpart "."
exponent = f'([eE][-+]?{digitpart})' # ("e" | "E") ["+" | "-"] digitpart
exponentfloat = f'(({digitpart} | {pointfloat}) {exponent})' # (digitpart | pointfloat) exponent
floatnumber = f'^({pointfloat} | {exponentfloat})$' # pointfloat | exponentfloat
floatnumber = f'^[-+]?({pointfloat} | {exponentfloat} | {digitpart})$' # allow signs and ints
if debug:
regular_expressions = (
digit,
digitpart,
fraction,
pointfloat,
exponent,
exponentfloat,
floatnumber,
)
for s in regular_expressions:
print(repr(s))
# print(str(s))
float_pattern = re.compile(floatnumber, re.VERBOSE)
return re.match(float_pattern, s)
floats = '''
2
0
-1
+17.
.
-.17
17e-3
-19.e-3
hello
'''.split()
floats
is_float('', debug=True)
for s in floats:
print(f'{s!r} -> {bool(is_float(s))}')
import re
def is_float(s):
digit = f'([0-9])'
digitpart = f'({digit}(_?{digit})*)' # digit (["_"] digit)*
fraction = f'([.]{digitpart})' # "." digitpart
pointfloat = f'(({digitpart}?{fraction}) | ({digitpart}[.]))' # [digitpart] fraction | digitpart "."
exponent = f'([eE][-+]?{digitpart})' # ("e" | "E") ["+" | "-"] digitpart
exponentfloat = f'(({digitpart} | {pointfloat}) {exponent})' # (digitpart | pointfloat) exponent
floatnumber = f'^({pointfloat} | {exponentfloat})$' # pointfloat | exponentfloat
floatnumber = f'^[-+]?({pointfloat} | {exponentfloat} | {digitpart})$' # allow signs and ints
float_pattern = re.compile(floatnumber, re.VERBOSE)
return re.match(float_pattern, s)
def safe_float(s, default=0.):
if is_float(s):
x = float(s)
else:
x = default
return x
def main(lines):
total = sum(safe_float(line) for line in lines)
print(f'total is {total}')
main(floats)
Explanation: For that simple example,
EAFP does not have much if any benefit over LBYL.
For that simple example,
there is not much benefit in the size or readability of the code.
However, for more complicated problems,
EAFP lets one write much simpler and readable code.
We will use the example of determining if a string is a valid float for Python.
See
2.4.6. Floating point literals
for what constitutes a valid float.
floatnumber ::= pointfloat | exponentfloat
pointfloat ::= [digitpart] fraction | digitpart "."
exponentfloat ::= (digitpart | pointfloat) exponent
digitpart ::= digit (["_"] digit)*
fraction ::= "." digitpart
exponent ::= ("e" | "E") ["+" | "-"] digitpart
Some code for that follows.
End of explanation
def safe_float(s, default=0.):
try:
x = float(s)
except ValueError:
x = default
return x
def main(lines):
total = sum(safe_float(line) for line in lines)
print(f'total is {total}')
main(floats)
Explanation: Now we try EAFP technique below.
End of explanation
from glob import glob
import os
for filename in sorted(glob('20170424-cohpy-except-*.py')):
print(79 * '#')
print(filename)
print()
with open(filename) as f:
print(f.read())
print()
Explanation: The EAFP code is much much simpler.
The LBYL version was very complicated.
If there was a bug in the LBYL version, how would you find it?
If you fixed it, how much confidence would you have that your fix is correct?
How hard would it be to have test cases that covered all the edge cases?
How much confidence would you have that the test cases were comprehensive?
EAFP makes code easier to read, simpler, and more reliable.
This is what makes try/except one of Python's superpowers!!!
try/except best practices
Should:
always specify at least one exception
put as little as possible in the try clause
Because the 20170424-except-*.py programs can lock up Jupyter notebook,
run them outside of the notebook.
The cell below shows what they look like,
but does not run them.
End of explanation |
7,975 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
https
Step1: Step 0 - hyperparams
vocab_size is all the potential words you could have (classification for translation case)
and max sequence length are the SAME thing
decoder RNN hidden units are usually same size as encoder RNN hidden units in translation but for our case it does not seem really to be a relationship there but we can experiment and find out later, not a priority thing right now
Step2: Once generate data
Step3: Step 1 - collect data
Step4: Step 2 - Build model
Step5: Step 3 training the network
RECALL
Step6: Recall that without batch normalization within 10 epochs with num units 400 and batch_size 64 we reached at 4.940
and with having the decoder inputs NOT filled from the outputs | Python Code:
from __future__ import division
import tensorflow as tf
from os import path, remove
import numpy as np
import pandas as pd
import csv
from sklearn.model_selection import StratifiedShuffleSplit
from time import time
from matplotlib import pyplot as plt
import seaborn as sns
from mylibs.jupyter_notebook_helper import show_graph, renderStatsList, renderStatsCollection, \
renderStatsListWithLabels, renderStatsCollectionOfCrossValids
from tensorflow.contrib import rnn
from tensorflow.contrib import learn
import shutil
from tensorflow.contrib.learn.python.learn import learn_runner
from mylibs.tf_helper import getDefaultGPUconfig
from sklearn.metrics import r2_score
from mylibs.py_helper import factors
from fastdtw import fastdtw
from collections import OrderedDict
from scipy.spatial.distance import euclidean
from statsmodels.tsa.stattools import coint
from common import get_or_run_nn
from data_providers.price_history_seq2seq_data_provider import PriceHistorySeq2SeqDataProvider
from data_providers.price_history_dataset_generator import PriceHistoryDatasetGenerator
from skopt.space.space import Integer, Real
from skopt import gp_minimize
from skopt.plots import plot_convergence
import pickle
import inspect
import dill
import sys
from models.price_history_19_seq2seq_raw_dropout import PriceHistorySeq2SeqRawDropout
dtype = tf.float32
seed = 16011984
random_state = np.random.RandomState(seed=seed)
config = getDefaultGPUconfig()
n_jobs = 1
%matplotlib inline
Explanation: https://www.youtube.com/watch?v=ElmBrKyMXxs
https://github.com/hans/ipython-notebooks/blob/master/tf/TF%20tutorial.ipynb
https://github.com/ematvey/tensorflow-seq2seq-tutorials
End of explanation
epochs = 10
num_features = 1
num_units = 400 #state size
input_len = 60
target_len = 30
batch_size = 50 #47
#trunc_backprop_len = ??
with_EOS = False
total_train_size = 57994
train_size = 6400
test_size = 1282
Explanation: Step 0 - hyperparams
vocab_size is all the potential words you could have (classification for translation case)
and max sequence length are the SAME thing
decoder RNN hidden units are usually same size as encoder RNN hidden units in translation but for our case it does not seem really to be a relationship there but we can experiment and find out later, not a priority thing right now
End of explanation
data_path = '../data/price_history'
#npz_full_train = data_path + '/price_history_03_dp_60to30_train.npz'
#npz_full_train = data_path + '/price_history_60to30_targets_normed_train.npz'
#npz_train = data_path + '/price_history_03_dp_60to30_57980_train.npz'
#npz_train = data_path + '/price_history_03_dp_60to30_6400_train.npz'
npz_train = data_path + '/price_history_60to30_6400_targets_normed_train.npz'
#npz_test = data_path + '/price_history_03_dp_60to30_test.npz'
npz_test = data_path + '/price_history_60to30_targets_normed_test.npz'
Explanation: Once generate data
End of explanation
dp = PriceHistorySeq2SeqDataProvider(npz_path=npz_train, batch_size=batch_size, with_EOS=with_EOS)
dp.inputs.shape, dp.targets.shape
aa, bb = dp.next()
aa.shape, bb.shape
Explanation: Step 1 - collect data
End of explanation
model = PriceHistorySeq2SeqRawDropout(rng=random_state, dtype=dtype, config=config, with_EOS=with_EOS)
graph = model.getGraph(batch_size=batch_size,
num_units=num_units,
input_len=input_len,
target_len=target_len)
#show_graph(graph)
Explanation: Step 2 - Build model
End of explanation
#rnn_cell = PriceHistorySeq2SeqCV.RNN_CELLS.GRU
#cross_val_n_splits = 5
epochs, num_units, batch_size
#set(factors(train_size)).intersection(factors(train_size/5))
best_learning_rate = 1e-3 #0.0026945952539362472
keep_prob_input = 0.7
def experiment():
return model.run(npz_path=npz_train,
epochs=epochs,
batch_size = batch_size,
num_units = num_units,
input_len=input_len,
target_len=target_len,
learning_rate = best_learning_rate,
preds_gather_enabled=True,
keep_prob_input = keep_prob_input,
)
Explanation: Step 3 training the network
RECALL: baseline is around 4 for huber loss for current problem, anything above 4 should be considered as major errors
End of explanation
%%time
dyn_stats, preds_dict = get_or_run_nn(
experiment,
filename='019_seq2seq_60to30_epochs{}_learning_rate_{:.4f}_prob_input{}'.format(
epochs, best_learning_rate, keep_prob_input
))
dyn_stats.plotStats()
plt.show()
r2_scores = [r2_score(y_true=dp.targets[ind], y_pred=preds_dict[ind])
for ind in range(len(dp.targets))]
ind = np.argmin(r2_scores)
ind
reals = dp.targets[ind]
preds = preds_dict[ind]
r2_score(y_true=reals, y_pred=preds)
sns.tsplot(data=dp.inputs[ind].flatten())
fig = plt.figure(figsize=(15,6))
plt.plot(reals, 'b')
plt.plot(preds, 'g')
plt.legend(['reals','preds'])
plt.show()
%%time
dtw_scores = [fastdtw(dp.targets[ind], preds_dict[ind])[0]
for ind in range(len(dp.targets))]
np.mean(dtw_scores)
coint(preds, reals)
cur_ind = np.random.randint(len(dp.targets))
reals = dp.targets[cur_ind]
preds = preds_dict[cur_ind]
fig = plt.figure(figsize=(15,6))
plt.plot(reals, 'b')
plt.plot(preds, 'g')
plt.legend(['reals','preds'])
plt.show()
Explanation: Recall that without batch normalization within 10 epochs with num units 400 and batch_size 64 we reached at 4.940
and with having the decoder inputs NOT filled from the outputs
End of explanation |
7,976 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify document publication status
Step4: Document Table of Contents
1. Key Properties --> Overview
2. Key Properties --> Resolution
3. Key Properties --> Timestepping
4. Key Properties --> Orography
5. Grid --> Discretisation
6. Grid --> Discretisation --> Horizontal
7. Grid --> Discretisation --> Vertical
8. Dynamical Core
9. Dynamical Core --> Top Boundary
10. Dynamical Core --> Lateral Boundary
11. Dynamical Core --> Diffusion Horizontal
12. Dynamical Core --> Advection Tracers
13. Dynamical Core --> Advection Momentum
14. Radiation
15. Radiation --> Shortwave Radiation
16. Radiation --> Shortwave GHG
17. Radiation --> Shortwave Cloud Ice
18. Radiation --> Shortwave Cloud Liquid
19. Radiation --> Shortwave Cloud Inhomogeneity
20. Radiation --> Shortwave Aerosols
21. Radiation --> Shortwave Gases
22. Radiation --> Longwave Radiation
23. Radiation --> Longwave GHG
24. Radiation --> Longwave Cloud Ice
25. Radiation --> Longwave Cloud Liquid
26. Radiation --> Longwave Cloud Inhomogeneity
27. Radiation --> Longwave Aerosols
28. Radiation --> Longwave Gases
29. Turbulence Convection
30. Turbulence Convection --> Boundary Layer Turbulence
31. Turbulence Convection --> Deep Convection
32. Turbulence Convection --> Shallow Convection
33. Microphysics Precipitation
34. Microphysics Precipitation --> Large Scale Precipitation
35. Microphysics Precipitation --> Large Scale Cloud Microphysics
36. Cloud Scheme
37. Cloud Scheme --> Optical Cloud Properties
38. Cloud Scheme --> Sub Grid Scale Water Distribution
39. Cloud Scheme --> Sub Grid Scale Ice Distribution
40. Observation Simulation
41. Observation Simulation --> Isscp Attributes
42. Observation Simulation --> Cosp Attributes
43. Observation Simulation --> Radar Inputs
44. Observation Simulation --> Lidar Inputs
45. Gravity Waves
46. Gravity Waves --> Orographic Gravity Waves
47. Gravity Waves --> Non Orographic Gravity Waves
48. Solar
49. Solar --> Solar Pathways
50. Solar --> Solar Constant
51. Solar --> Orbital Parameters
52. Solar --> Insolation Ozone
53. Volcanos
54. Volcanos --> Volcanoes Treatment
1. Key Properties --> Overview
Top level key properties
1.1. Model Overview
Is Required
Step5: 1.2. Model Name
Is Required
Step6: 1.3. Model Family
Is Required
Step7: 1.4. Basic Approximations
Is Required
Step8: 2. Key Properties --> Resolution
Characteristics of the model resolution
2.1. Horizontal Resolution Name
Is Required
Step9: 2.2. Canonical Horizontal Resolution
Is Required
Step10: 2.3. Range Horizontal Resolution
Is Required
Step11: 2.4. Number Of Vertical Levels
Is Required
Step12: 2.5. High Top
Is Required
Step13: 3. Key Properties --> Timestepping
Characteristics of the atmosphere model time stepping
3.1. Timestep Dynamics
Is Required
Step14: 3.2. Timestep Shortwave Radiative Transfer
Is Required
Step15: 3.3. Timestep Longwave Radiative Transfer
Is Required
Step16: 4. Key Properties --> Orography
Characteristics of the model orography
4.1. Type
Is Required
Step17: 4.2. Changes
Is Required
Step18: 5. Grid --> Discretisation
Atmosphere grid discretisation
5.1. Overview
Is Required
Step19: 6. Grid --> Discretisation --> Horizontal
Atmosphere discretisation in the horizontal
6.1. Scheme Type
Is Required
Step20: 6.2. Scheme Method
Is Required
Step21: 6.3. Scheme Order
Is Required
Step22: 6.4. Horizontal Pole
Is Required
Step23: 6.5. Grid Type
Is Required
Step24: 7. Grid --> Discretisation --> Vertical
Atmosphere discretisation in the vertical
7.1. Coordinate Type
Is Required
Step25: 8. Dynamical Core
Characteristics of the dynamical core
8.1. Overview
Is Required
Step26: 8.2. Name
Is Required
Step27: 8.3. Timestepping Type
Is Required
Step28: 8.4. Prognostic Variables
Is Required
Step29: 9. Dynamical Core --> Top Boundary
Type of boundary layer at the top of the model
9.1. Top Boundary Condition
Is Required
Step30: 9.2. Top Heat
Is Required
Step31: 9.3. Top Wind
Is Required
Step32: 10. Dynamical Core --> Lateral Boundary
Type of lateral boundary condition (if the model is a regional model)
10.1. Condition
Is Required
Step33: 11. Dynamical Core --> Diffusion Horizontal
Horizontal diffusion scheme
11.1. Scheme Name
Is Required
Step34: 11.2. Scheme Method
Is Required
Step35: 12. Dynamical Core --> Advection Tracers
Tracer advection scheme
12.1. Scheme Name
Is Required
Step36: 12.2. Scheme Characteristics
Is Required
Step37: 12.3. Conserved Quantities
Is Required
Step38: 12.4. Conservation Method
Is Required
Step39: 13. Dynamical Core --> Advection Momentum
Momentum advection scheme
13.1. Scheme Name
Is Required
Step40: 13.2. Scheme Characteristics
Is Required
Step41: 13.3. Scheme Staggering Type
Is Required
Step42: 13.4. Conserved Quantities
Is Required
Step43: 13.5. Conservation Method
Is Required
Step44: 14. Radiation
Characteristics of the atmosphere radiation process
14.1. Aerosols
Is Required
Step45: 15. Radiation --> Shortwave Radiation
Properties of the shortwave radiation scheme
15.1. Overview
Is Required
Step46: 15.2. Name
Is Required
Step47: 15.3. Spectral Integration
Is Required
Step48: 15.4. Transport Calculation
Is Required
Step49: 15.5. Spectral Intervals
Is Required
Step50: 16. Radiation --> Shortwave GHG
Representation of greenhouse gases in the shortwave radiation scheme
16.1. Greenhouse Gas Complexity
Is Required
Step51: 16.2. ODS
Is Required
Step52: 16.3. Other Flourinated Gases
Is Required
Step53: 17. Radiation --> Shortwave Cloud Ice
Shortwave radiative properties of ice crystals in clouds
17.1. General Interactions
Is Required
Step54: 17.2. Physical Representation
Is Required
Step55: 17.3. Optical Methods
Is Required
Step56: 18. Radiation --> Shortwave Cloud Liquid
Shortwave radiative properties of liquid droplets in clouds
18.1. General Interactions
Is Required
Step57: 18.2. Physical Representation
Is Required
Step58: 18.3. Optical Methods
Is Required
Step59: 19. Radiation --> Shortwave Cloud Inhomogeneity
Cloud inhomogeneity in the shortwave radiation scheme
19.1. Cloud Inhomogeneity
Is Required
Step60: 20. Radiation --> Shortwave Aerosols
Shortwave radiative properties of aerosols
20.1. General Interactions
Is Required
Step61: 20.2. Physical Representation
Is Required
Step62: 20.3. Optical Methods
Is Required
Step63: 21. Radiation --> Shortwave Gases
Shortwave radiative properties of gases
21.1. General Interactions
Is Required
Step64: 22. Radiation --> Longwave Radiation
Properties of the longwave radiation scheme
22.1. Overview
Is Required
Step65: 22.2. Name
Is Required
Step66: 22.3. Spectral Integration
Is Required
Step67: 22.4. Transport Calculation
Is Required
Step68: 22.5. Spectral Intervals
Is Required
Step69: 23. Radiation --> Longwave GHG
Representation of greenhouse gases in the longwave radiation scheme
23.1. Greenhouse Gas Complexity
Is Required
Step70: 23.2. ODS
Is Required
Step71: 23.3. Other Flourinated Gases
Is Required
Step72: 24. Radiation --> Longwave Cloud Ice
Longwave radiative properties of ice crystals in clouds
24.1. General Interactions
Is Required
Step73: 24.2. Physical Reprenstation
Is Required
Step74: 24.3. Optical Methods
Is Required
Step75: 25. Radiation --> Longwave Cloud Liquid
Longwave radiative properties of liquid droplets in clouds
25.1. General Interactions
Is Required
Step76: 25.2. Physical Representation
Is Required
Step77: 25.3. Optical Methods
Is Required
Step78: 26. Radiation --> Longwave Cloud Inhomogeneity
Cloud inhomogeneity in the longwave radiation scheme
26.1. Cloud Inhomogeneity
Is Required
Step79: 27. Radiation --> Longwave Aerosols
Longwave radiative properties of aerosols
27.1. General Interactions
Is Required
Step80: 27.2. Physical Representation
Is Required
Step81: 27.3. Optical Methods
Is Required
Step82: 28. Radiation --> Longwave Gases
Longwave radiative properties of gases
28.1. General Interactions
Is Required
Step83: 29. Turbulence Convection
Atmosphere Convective Turbulence and Clouds
29.1. Overview
Is Required
Step84: 30. Turbulence Convection --> Boundary Layer Turbulence
Properties of the boundary layer turbulence scheme
30.1. Scheme Name
Is Required
Step85: 30.2. Scheme Type
Is Required
Step86: 30.3. Closure Order
Is Required
Step87: 30.4. Counter Gradient
Is Required
Step88: 31. Turbulence Convection --> Deep Convection
Properties of the deep convection scheme
31.1. Scheme Name
Is Required
Step89: 31.2. Scheme Type
Is Required
Step90: 31.3. Scheme Method
Is Required
Step91: 31.4. Processes
Is Required
Step92: 31.5. Microphysics
Is Required
Step93: 32. Turbulence Convection --> Shallow Convection
Properties of the shallow convection scheme
32.1. Scheme Name
Is Required
Step94: 32.2. Scheme Type
Is Required
Step95: 32.3. Scheme Method
Is Required
Step96: 32.4. Processes
Is Required
Step97: 32.5. Microphysics
Is Required
Step98: 33. Microphysics Precipitation
Large Scale Cloud Microphysics and Precipitation
33.1. Overview
Is Required
Step99: 34. Microphysics Precipitation --> Large Scale Precipitation
Properties of the large scale precipitation scheme
34.1. Scheme Name
Is Required
Step100: 34.2. Hydrometeors
Is Required
Step101: 35. Microphysics Precipitation --> Large Scale Cloud Microphysics
Properties of the large scale cloud microphysics scheme
35.1. Scheme Name
Is Required
Step102: 35.2. Processes
Is Required
Step103: 36. Cloud Scheme
Characteristics of the cloud scheme
36.1. Overview
Is Required
Step104: 36.2. Name
Is Required
Step105: 36.3. Atmos Coupling
Is Required
Step106: 36.4. Uses Separate Treatment
Is Required
Step107: 36.5. Processes
Is Required
Step108: 36.6. Prognostic Scheme
Is Required
Step109: 36.7. Diagnostic Scheme
Is Required
Step110: 36.8. Prognostic Variables
Is Required
Step111: 37. Cloud Scheme --> Optical Cloud Properties
Optical cloud properties
37.1. Cloud Overlap Method
Is Required
Step112: 37.2. Cloud Inhomogeneity
Is Required
Step113: 38. Cloud Scheme --> Sub Grid Scale Water Distribution
Sub-grid scale water distribution
38.1. Type
Is Required
Step114: 38.2. Function Name
Is Required
Step115: 38.3. Function Order
Is Required
Step116: 38.4. Convection Coupling
Is Required
Step117: 39. Cloud Scheme --> Sub Grid Scale Ice Distribution
Sub-grid scale ice distribution
39.1. Type
Is Required
Step118: 39.2. Function Name
Is Required
Step119: 39.3. Function Order
Is Required
Step120: 39.4. Convection Coupling
Is Required
Step121: 40. Observation Simulation
Characteristics of observation simulation
40.1. Overview
Is Required
Step122: 41. Observation Simulation --> Isscp Attributes
ISSCP Characteristics
41.1. Top Height Estimation Method
Is Required
Step123: 41.2. Top Height Direction
Is Required
Step124: 42. Observation Simulation --> Cosp Attributes
CFMIP Observational Simulator Package attributes
42.1. Run Configuration
Is Required
Step125: 42.2. Number Of Grid Points
Is Required
Step126: 42.3. Number Of Sub Columns
Is Required
Step127: 42.4. Number Of Levels
Is Required
Step128: 43. Observation Simulation --> Radar Inputs
Characteristics of the cloud radar simulator
43.1. Frequency
Is Required
Step129: 43.2. Type
Is Required
Step130: 43.3. Gas Absorption
Is Required
Step131: 43.4. Effective Radius
Is Required
Step132: 44. Observation Simulation --> Lidar Inputs
Characteristics of the cloud lidar simulator
44.1. Ice Types
Is Required
Step133: 44.2. Overlap
Is Required
Step134: 45. Gravity Waves
Characteristics of the parameterised gravity waves in the atmosphere, whether from orography or other sources.
45.1. Overview
Is Required
Step135: 45.2. Sponge Layer
Is Required
Step136: 45.3. Background
Is Required
Step137: 45.4. Subgrid Scale Orography
Is Required
Step138: 46. Gravity Waves --> Orographic Gravity Waves
Gravity waves generated due to the presence of orography
46.1. Name
Is Required
Step139: 46.2. Source Mechanisms
Is Required
Step140: 46.3. Calculation Method
Is Required
Step141: 46.4. Propagation Scheme
Is Required
Step142: 46.5. Dissipation Scheme
Is Required
Step143: 47. Gravity Waves --> Non Orographic Gravity Waves
Gravity waves generated by non-orographic processes.
47.1. Name
Is Required
Step144: 47.2. Source Mechanisms
Is Required
Step145: 47.3. Calculation Method
Is Required
Step146: 47.4. Propagation Scheme
Is Required
Step147: 47.5. Dissipation Scheme
Is Required
Step148: 48. Solar
Top of atmosphere solar insolation characteristics
48.1. Overview
Is Required
Step149: 49. Solar --> Solar Pathways
Pathways for solar forcing of the atmosphere
49.1. Pathways
Is Required
Step150: 50. Solar --> Solar Constant
Solar constant and top of atmosphere insolation characteristics
50.1. Type
Is Required
Step151: 50.2. Fixed Value
Is Required
Step152: 50.3. Transient Characteristics
Is Required
Step153: 51. Solar --> Orbital Parameters
Orbital parameters and top of atmosphere insolation characteristics
51.1. Type
Is Required
Step154: 51.2. Fixed Reference Date
Is Required
Step155: 51.3. Transient Method
Is Required
Step156: 51.4. Computation Method
Is Required
Step157: 52. Solar --> Insolation Ozone
Impact of solar insolation on stratospheric ozone
52.1. Solar Ozone Impact
Is Required
Step158: 53. Volcanos
Characteristics of the implementation of volcanoes
53.1. Overview
Is Required
Step159: 54. Volcanos --> Volcanoes Treatment
Treatment of volcanoes in the atmosphere
54.1. Volcanoes Implementation
Is Required | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'miroc', 'nicam16-8s', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: MIROC
Source ID: NICAM16-8S
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation, Turbulence Convection, Microphysics Precipitation, Cloud Scheme, Observation Simulation, Gravity Waves, Solar, Volcanos.
Properties: 156 (127 required)
Model descriptions: Model description details
Initialized From: --
Notebook Help: Goto notebook help page
Notebook Initialised: 2018-02-20 15:02:40
Document Setup
IMPORTANT: to be executed each time you run the notebook
End of explanation
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
Explanation: Document Authors
Set document authors
End of explanation
# Set as follows: DOC.set_contributor("name", "email")
# TODO - please enter value(s)
Explanation: Document Contributors
Specify document contributors
End of explanation
# Set publication status:
# 0=do not publish, 1=publish.
DOC.set_publication_status(0)
Explanation: Document Publication
Specify document publication status
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.overview.model_overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: Document Table of Contents
1. Key Properties --> Overview
2. Key Properties --> Resolution
3. Key Properties --> Timestepping
4. Key Properties --> Orography
5. Grid --> Discretisation
6. Grid --> Discretisation --> Horizontal
7. Grid --> Discretisation --> Vertical
8. Dynamical Core
9. Dynamical Core --> Top Boundary
10. Dynamical Core --> Lateral Boundary
11. Dynamical Core --> Diffusion Horizontal
12. Dynamical Core --> Advection Tracers
13. Dynamical Core --> Advection Momentum
14. Radiation
15. Radiation --> Shortwave Radiation
16. Radiation --> Shortwave GHG
17. Radiation --> Shortwave Cloud Ice
18. Radiation --> Shortwave Cloud Liquid
19. Radiation --> Shortwave Cloud Inhomogeneity
20. Radiation --> Shortwave Aerosols
21. Radiation --> Shortwave Gases
22. Radiation --> Longwave Radiation
23. Radiation --> Longwave GHG
24. Radiation --> Longwave Cloud Ice
25. Radiation --> Longwave Cloud Liquid
26. Radiation --> Longwave Cloud Inhomogeneity
27. Radiation --> Longwave Aerosols
28. Radiation --> Longwave Gases
29. Turbulence Convection
30. Turbulence Convection --> Boundary Layer Turbulence
31. Turbulence Convection --> Deep Convection
32. Turbulence Convection --> Shallow Convection
33. Microphysics Precipitation
34. Microphysics Precipitation --> Large Scale Precipitation
35. Microphysics Precipitation --> Large Scale Cloud Microphysics
36. Cloud Scheme
37. Cloud Scheme --> Optical Cloud Properties
38. Cloud Scheme --> Sub Grid Scale Water Distribution
39. Cloud Scheme --> Sub Grid Scale Ice Distribution
40. Observation Simulation
41. Observation Simulation --> Isscp Attributes
42. Observation Simulation --> Cosp Attributes
43. Observation Simulation --> Radar Inputs
44. Observation Simulation --> Lidar Inputs
45. Gravity Waves
46. Gravity Waves --> Orographic Gravity Waves
47. Gravity Waves --> Non Orographic Gravity Waves
48. Solar
49. Solar --> Solar Pathways
50. Solar --> Solar Constant
51. Solar --> Orbital Parameters
52. Solar --> Insolation Ozone
53. Volcanos
54. Volcanos --> Volcanoes Treatment
1. Key Properties --> Overview
Top level key properties
1.1. Model Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of atmosphere model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.overview.model_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 1.2. Model Name
Is Required: TRUE Type: STRING Cardinality: 1.1
Name of atmosphere model code (CAM 4.0, ARPEGE 3.2,...)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.overview.model_family')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "AGCM"
# "ARCM"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 1.3. Model Family
Is Required: TRUE Type: ENUM Cardinality: 1.1
Type of atmospheric model.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.overview.basic_approximations')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "primitive equations"
# "non-hydrostatic"
# "anelastic"
# "Boussinesq"
# "hydrostatic"
# "quasi-hydrostatic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 1.4. Basic Approximations
Is Required: TRUE Type: ENUM Cardinality: 1.N
Basic approximations made in the atmosphere.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.resolution.horizontal_resolution_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 2. Key Properties --> Resolution
Characteristics of the model resolution
2.1. Horizontal Resolution Name
Is Required: TRUE Type: STRING Cardinality: 1.1
This is a string usually used by the modelling group to describe the resolution of the model grid, e.g. T42, N48.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.resolution.canonical_horizontal_resolution')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 2.2. Canonical Horizontal Resolution
Is Required: TRUE Type: STRING Cardinality: 1.1
Expression quoted for gross comparisons of resolution, e.g. 2.5 x 3.75 degrees lat-lon.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.resolution.range_horizontal_resolution')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 2.3. Range Horizontal Resolution
Is Required: TRUE Type: STRING Cardinality: 1.1
Range of horizontal resolution with spatial details, eg. 1 deg (Equator) - 0.5 deg
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.resolution.number_of_vertical_levels')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 2.4. Number Of Vertical Levels
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Number of vertical levels resolved on the computational grid.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.resolution.high_top')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 2.5. High Top
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Does the atmosphere have a high-top? High-Top atmospheres have a fully resolved stratosphere with a model top above the stratopause.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_dynamics')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 3. Key Properties --> Timestepping
Characteristics of the atmosphere model time stepping
3.1. Timestep Dynamics
Is Required: TRUE Type: STRING Cardinality: 1.1
Timestep for the dynamics, e.g. 30 min.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_shortwave_radiative_transfer')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 3.2. Timestep Shortwave Radiative Transfer
Is Required: FALSE Type: STRING Cardinality: 0.1
Timestep for the shortwave radiative transfer, e.g. 1.5 hours.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_longwave_radiative_transfer')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 3.3. Timestep Longwave Radiative Transfer
Is Required: FALSE Type: STRING Cardinality: 0.1
Timestep for the longwave radiative transfer, e.g. 3 hours.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.orography.type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "present day"
# "modified"
# TODO - please enter value(s)
Explanation: 4. Key Properties --> Orography
Characteristics of the model orography
4.1. Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Time adaptation of the orography.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.key_properties.orography.changes')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "related to ice sheets"
# "related to tectonics"
# "modified mean"
# "modified variance if taken into account in model (cf gravity waves)"
# TODO - please enter value(s)
Explanation: 4.2. Changes
Is Required: TRUE Type: ENUM Cardinality: 1.N
If the orography type is modified describe the time adaptation changes.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.grid.discretisation.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 5. Grid --> Discretisation
Atmosphere grid discretisation
5.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of grid discretisation in the atmosphere
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "spectral"
# "fixed grid"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 6. Grid --> Discretisation --> Horizontal
Atmosphere discretisation in the horizontal
6.1. Scheme Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Horizontal discretisation type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "finite elements"
# "finite volumes"
# "finite difference"
# "centered finite difference"
# TODO - please enter value(s)
Explanation: 6.2. Scheme Method
Is Required: TRUE Type: ENUM Cardinality: 1.1
Horizontal discretisation method
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_order')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "second"
# "third"
# "fourth"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 6.3. Scheme Order
Is Required: TRUE Type: ENUM Cardinality: 1.1
Horizontal discretisation function order
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.horizontal_pole')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "filter"
# "pole rotation"
# "artificial island"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 6.4. Horizontal Pole
Is Required: FALSE Type: ENUM Cardinality: 0.1
Horizontal discretisation pole singularity treatment
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.grid_type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Gaussian"
# "Latitude-Longitude"
# "Cubed-Sphere"
# "Icosahedral"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 6.5. Grid Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Horizontal grid type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.grid.discretisation.vertical.coordinate_type')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "isobaric"
# "sigma"
# "hybrid sigma-pressure"
# "hybrid pressure"
# "vertically lagrangian"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 7. Grid --> Discretisation --> Vertical
Atmosphere discretisation in the vertical
7.1. Coordinate Type
Is Required: TRUE Type: ENUM Cardinality: 1.N
Type of vertical coordinate system
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8. Dynamical Core
Characteristics of the dynamical core
8.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of atmosphere dynamical core
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8.2. Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Commonly used name for the dynamical core of the model.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.timestepping_type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Adams-Bashforth"
# "explicit"
# "implicit"
# "semi-implicit"
# "leap frog"
# "multi-step"
# "Runge Kutta fifth order"
# "Runge Kutta second order"
# "Runge Kutta third order"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 8.3. Timestepping Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Timestepping framework type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.prognostic_variables')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "surface pressure"
# "wind components"
# "divergence/curl"
# "temperature"
# "potential temperature"
# "total water"
# "water vapour"
# "water liquid"
# "water ice"
# "total water moments"
# "clouds"
# "radiation"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 8.4. Prognostic Variables
Is Required: TRUE Type: ENUM Cardinality: 1.N
List of the model prognostic variables
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_boundary_condition')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "sponge layer"
# "radiation boundary condition"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 9. Dynamical Core --> Top Boundary
Type of boundary layer at the top of the model
9.1. Top Boundary Condition
Is Required: TRUE Type: ENUM Cardinality: 1.1
Top boundary condition
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_heat')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.2. Top Heat
Is Required: TRUE Type: STRING Cardinality: 1.1
Top boundary heat treatment
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_wind')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.3. Top Wind
Is Required: TRUE Type: STRING Cardinality: 1.1
Top boundary wind treatment
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.lateral_boundary.condition')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "sponge layer"
# "radiation boundary condition"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 10. Dynamical Core --> Lateral Boundary
Type of lateral boundary condition (if the model is a regional model)
10.1. Condition
Is Required: FALSE Type: ENUM Cardinality: 0.1
Type of lateral boundary condition
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.diffusion_horizontal.scheme_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 11. Dynamical Core --> Diffusion Horizontal
Horizontal diffusion scheme
11.1. Scheme Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Horizontal diffusion scheme name
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.diffusion_horizontal.scheme_method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "iterated Laplacian"
# "bi-harmonic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 11.2. Scheme Method
Is Required: TRUE Type: ENUM Cardinality: 1.1
Horizontal diffusion scheme method
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.scheme_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Heun"
# "Roe and VanLeer"
# "Roe and Superbee"
# "Prather"
# "UTOPIA"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 12. Dynamical Core --> Advection Tracers
Tracer advection scheme
12.1. Scheme Name
Is Required: FALSE Type: ENUM Cardinality: 0.1
Tracer advection scheme name
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.scheme_characteristics')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Eulerian"
# "modified Euler"
# "Lagrangian"
# "semi-Lagrangian"
# "cubic semi-Lagrangian"
# "quintic semi-Lagrangian"
# "mass-conserving"
# "finite volume"
# "flux-corrected"
# "linear"
# "quadratic"
# "quartic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 12.2. Scheme Characteristics
Is Required: TRUE Type: ENUM Cardinality: 1.N
Tracer advection scheme characteristics
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.conserved_quantities')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "dry mass"
# "tracer mass"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 12.3. Conserved Quantities
Is Required: TRUE Type: ENUM Cardinality: 1.N
Tracer advection scheme conserved quantities
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.conservation_method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "conservation fixer"
# "Priestley algorithm"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 12.4. Conservation Method
Is Required: TRUE Type: ENUM Cardinality: 1.1
Tracer advection scheme conservation method
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "VanLeer"
# "Janjic"
# "SUPG (Streamline Upwind Petrov-Galerkin)"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 13. Dynamical Core --> Advection Momentum
Momentum advection scheme
13.1. Scheme Name
Is Required: FALSE Type: ENUM Cardinality: 0.1
Momentum advection schemes name
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_characteristics')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "2nd order"
# "4th order"
# "cell-centred"
# "staggered grid"
# "semi-staggered grid"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 13.2. Scheme Characteristics
Is Required: TRUE Type: ENUM Cardinality: 1.N
Momentum advection scheme characteristics
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_staggering_type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Arakawa B-grid"
# "Arakawa C-grid"
# "Arakawa D-grid"
# "Arakawa E-grid"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 13.3. Scheme Staggering Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Momentum advection scheme staggering type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.conserved_quantities')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Angular momentum"
# "Horizontal momentum"
# "Enstrophy"
# "Mass"
# "Total energy"
# "Vorticity"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 13.4. Conserved Quantities
Is Required: TRUE Type: ENUM Cardinality: 1.N
Momentum advection scheme conserved quantities
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.conservation_method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "conservation fixer"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 13.5. Conservation Method
Is Required: TRUE Type: ENUM Cardinality: 1.1
Momentum advection scheme conservation method
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.aerosols')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "sulphate"
# "nitrate"
# "sea salt"
# "dust"
# "ice"
# "organic"
# "BC (black carbon / soot)"
# "SOA (secondary organic aerosols)"
# "POM (particulate organic matter)"
# "polar stratospheric ice"
# "NAT (nitric acid trihydrate)"
# "NAD (nitric acid dihydrate)"
# "STS (supercooled ternary solution aerosol particle)"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 14. Radiation
Characteristics of the atmosphere radiation process
14.1. Aerosols
Is Required: TRUE Type: ENUM Cardinality: 1.N
Aerosols whose radiative effect is taken into account in the atmosphere model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 15. Radiation --> Shortwave Radiation
Properties of the shortwave radiation scheme
15.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of shortwave radiation in the atmosphere
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 15.2. Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Commonly used name for the shortwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.spectral_integration')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "wide-band model"
# "correlated-k"
# "exponential sum fitting"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 15.3. Spectral Integration
Is Required: TRUE Type: ENUM Cardinality: 1.1
Shortwave radiation scheme spectral integration
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.transport_calculation')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "two-stream"
# "layer interaction"
# "bulk"
# "adaptive"
# "multi-stream"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 15.4. Transport Calculation
Is Required: TRUE Type: ENUM Cardinality: 1.N
Shortwave radiation transport calculation methods
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.spectral_intervals')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 15.5. Spectral Intervals
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Shortwave radiation scheme number of spectral intervals
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.greenhouse_gas_complexity')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "CO2"
# "CH4"
# "N2O"
# "CFC-11 eq"
# "CFC-12 eq"
# "HFC-134a eq"
# "Explicit ODSs"
# "Explicit other fluorinated gases"
# "O3"
# "H2O"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 16. Radiation --> Shortwave GHG
Representation of greenhouse gases in the shortwave radiation scheme
16.1. Greenhouse Gas Complexity
Is Required: TRUE Type: ENUM Cardinality: 1.N
Complexity of greenhouse gases whose shortwave radiative effects are taken into account in the atmosphere model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.ODS')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "CFC-12"
# "CFC-11"
# "CFC-113"
# "CFC-114"
# "CFC-115"
# "HCFC-22"
# "HCFC-141b"
# "HCFC-142b"
# "Halon-1211"
# "Halon-1301"
# "Halon-2402"
# "methyl chloroform"
# "carbon tetrachloride"
# "methyl chloride"
# "methylene chloride"
# "chloroform"
# "methyl bromide"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 16.2. ODS
Is Required: FALSE Type: ENUM Cardinality: 0.N
Ozone depleting substances whose shortwave radiative effects are explicitly taken into account in the atmosphere model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.other_flourinated_gases')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "HFC-134a"
# "HFC-23"
# "HFC-32"
# "HFC-125"
# "HFC-143a"
# "HFC-152a"
# "HFC-227ea"
# "HFC-236fa"
# "HFC-245fa"
# "HFC-365mfc"
# "HFC-43-10mee"
# "CF4"
# "C2F6"
# "C3F8"
# "C4F10"
# "C5F12"
# "C6F14"
# "C7F16"
# "C8F18"
# "c-C4F8"
# "NF3"
# "SF6"
# "SO2F2"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 16.3. Other Flourinated Gases
Is Required: FALSE Type: ENUM Cardinality: 0.N
Other flourinated gases whose shortwave radiative effects are explicitly taken into account in the atmosphere model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.general_interactions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "scattering"
# "emission/absorption"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17. Radiation --> Shortwave Cloud Ice
Shortwave radiative properties of ice crystals in clouds
17.1. General Interactions
Is Required: TRUE Type: ENUM Cardinality: 1.N
General shortwave radiative interactions with cloud ice crystals
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.physical_representation')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "bi-modal size distribution"
# "ensemble of ice crystals"
# "mean projected area"
# "ice water path"
# "crystal asymmetry"
# "crystal aspect ratio"
# "effective crystal radius"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.2. Physical Representation
Is Required: TRUE Type: ENUM Cardinality: 1.N
Physical representation of cloud ice crystals in the shortwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.optical_methods')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "T-matrix"
# "geometric optics"
# "finite difference time domain (FDTD)"
# "Mie theory"
# "anomalous diffraction approximation"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.3. Optical Methods
Is Required: TRUE Type: ENUM Cardinality: 1.N
Optical methods applicable to cloud ice crystals in the shortwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.general_interactions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "scattering"
# "emission/absorption"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 18. Radiation --> Shortwave Cloud Liquid
Shortwave radiative properties of liquid droplets in clouds
18.1. General Interactions
Is Required: TRUE Type: ENUM Cardinality: 1.N
General shortwave radiative interactions with cloud liquid droplets
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.physical_representation')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "cloud droplet number concentration"
# "effective cloud droplet radii"
# "droplet size distribution"
# "liquid water path"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 18.2. Physical Representation
Is Required: TRUE Type: ENUM Cardinality: 1.N
Physical representation of cloud liquid droplets in the shortwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.optical_methods')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "geometric optics"
# "Mie theory"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 18.3. Optical Methods
Is Required: TRUE Type: ENUM Cardinality: 1.N
Optical methods applicable to cloud liquid droplets in the shortwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_inhomogeneity.cloud_inhomogeneity')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Monte Carlo Independent Column Approximation"
# "Triplecloud"
# "analytic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 19. Radiation --> Shortwave Cloud Inhomogeneity
Cloud inhomogeneity in the shortwave radiation scheme
19.1. Cloud Inhomogeneity
Is Required: TRUE Type: ENUM Cardinality: 1.1
Method for taking into account horizontal cloud inhomogeneity
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.general_interactions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "scattering"
# "emission/absorption"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 20. Radiation --> Shortwave Aerosols
Shortwave radiative properties of aerosols
20.1. General Interactions
Is Required: TRUE Type: ENUM Cardinality: 1.N
General shortwave radiative interactions with aerosols
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.physical_representation')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "number concentration"
# "effective radii"
# "size distribution"
# "asymmetry"
# "aspect ratio"
# "mixing state"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 20.2. Physical Representation
Is Required: TRUE Type: ENUM Cardinality: 1.N
Physical representation of aerosols in the shortwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.optical_methods')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "T-matrix"
# "geometric optics"
# "finite difference time domain (FDTD)"
# "Mie theory"
# "anomalous diffraction approximation"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 20.3. Optical Methods
Is Required: TRUE Type: ENUM Cardinality: 1.N
Optical methods applicable to aerosols in the shortwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.shortwave_gases.general_interactions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "scattering"
# "emission/absorption"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 21. Radiation --> Shortwave Gases
Shortwave radiative properties of gases
21.1. General Interactions
Is Required: TRUE Type: ENUM Cardinality: 1.N
General shortwave radiative interactions with gases
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_radiation.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 22. Radiation --> Longwave Radiation
Properties of the longwave radiation scheme
22.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of longwave radiation in the atmosphere
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_radiation.name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 22.2. Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Commonly used name for the longwave radiation scheme.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_radiation.spectral_integration')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "wide-band model"
# "correlated-k"
# "exponential sum fitting"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 22.3. Spectral Integration
Is Required: TRUE Type: ENUM Cardinality: 1.1
Longwave radiation scheme spectral integration
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_radiation.transport_calculation')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "two-stream"
# "layer interaction"
# "bulk"
# "adaptive"
# "multi-stream"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 22.4. Transport Calculation
Is Required: TRUE Type: ENUM Cardinality: 1.N
Longwave radiation transport calculation methods
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_radiation.spectral_intervals')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 22.5. Spectral Intervals
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Longwave radiation scheme number of spectral intervals
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_GHG.greenhouse_gas_complexity')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "CO2"
# "CH4"
# "N2O"
# "CFC-11 eq"
# "CFC-12 eq"
# "HFC-134a eq"
# "Explicit ODSs"
# "Explicit other fluorinated gases"
# "O3"
# "H2O"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 23. Radiation --> Longwave GHG
Representation of greenhouse gases in the longwave radiation scheme
23.1. Greenhouse Gas Complexity
Is Required: TRUE Type: ENUM Cardinality: 1.N
Complexity of greenhouse gases whose longwave radiative effects are taken into account in the atmosphere model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_GHG.ODS')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "CFC-12"
# "CFC-11"
# "CFC-113"
# "CFC-114"
# "CFC-115"
# "HCFC-22"
# "HCFC-141b"
# "HCFC-142b"
# "Halon-1211"
# "Halon-1301"
# "Halon-2402"
# "methyl chloroform"
# "carbon tetrachloride"
# "methyl chloride"
# "methylene chloride"
# "chloroform"
# "methyl bromide"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 23.2. ODS
Is Required: FALSE Type: ENUM Cardinality: 0.N
Ozone depleting substances whose longwave radiative effects are explicitly taken into account in the atmosphere model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_GHG.other_flourinated_gases')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "HFC-134a"
# "HFC-23"
# "HFC-32"
# "HFC-125"
# "HFC-143a"
# "HFC-152a"
# "HFC-227ea"
# "HFC-236fa"
# "HFC-245fa"
# "HFC-365mfc"
# "HFC-43-10mee"
# "CF4"
# "C2F6"
# "C3F8"
# "C4F10"
# "C5F12"
# "C6F14"
# "C7F16"
# "C8F18"
# "c-C4F8"
# "NF3"
# "SF6"
# "SO2F2"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 23.3. Other Flourinated Gases
Is Required: FALSE Type: ENUM Cardinality: 0.N
Other flourinated gases whose longwave radiative effects are explicitly taken into account in the atmosphere model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.general_interactions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "scattering"
# "emission/absorption"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 24. Radiation --> Longwave Cloud Ice
Longwave radiative properties of ice crystals in clouds
24.1. General Interactions
Is Required: TRUE Type: ENUM Cardinality: 1.N
General longwave radiative interactions with cloud ice crystals
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.physical_reprenstation')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "bi-modal size distribution"
# "ensemble of ice crystals"
# "mean projected area"
# "ice water path"
# "crystal asymmetry"
# "crystal aspect ratio"
# "effective crystal radius"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 24.2. Physical Reprenstation
Is Required: TRUE Type: ENUM Cardinality: 1.N
Physical representation of cloud ice crystals in the longwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.optical_methods')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "T-matrix"
# "geometric optics"
# "finite difference time domain (FDTD)"
# "Mie theory"
# "anomalous diffraction approximation"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 24.3. Optical Methods
Is Required: TRUE Type: ENUM Cardinality: 1.N
Optical methods applicable to cloud ice crystals in the longwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.general_interactions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "scattering"
# "emission/absorption"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 25. Radiation --> Longwave Cloud Liquid
Longwave radiative properties of liquid droplets in clouds
25.1. General Interactions
Is Required: TRUE Type: ENUM Cardinality: 1.N
General longwave radiative interactions with cloud liquid droplets
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.physical_representation')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "cloud droplet number concentration"
# "effective cloud droplet radii"
# "droplet size distribution"
# "liquid water path"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 25.2. Physical Representation
Is Required: TRUE Type: ENUM Cardinality: 1.N
Physical representation of cloud liquid droplets in the longwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.optical_methods')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "geometric optics"
# "Mie theory"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 25.3. Optical Methods
Is Required: TRUE Type: ENUM Cardinality: 1.N
Optical methods applicable to cloud liquid droplets in the longwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_cloud_inhomogeneity.cloud_inhomogeneity')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Monte Carlo Independent Column Approximation"
# "Triplecloud"
# "analytic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 26. Radiation --> Longwave Cloud Inhomogeneity
Cloud inhomogeneity in the longwave radiation scheme
26.1. Cloud Inhomogeneity
Is Required: TRUE Type: ENUM Cardinality: 1.1
Method for taking into account horizontal cloud inhomogeneity
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.general_interactions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "scattering"
# "emission/absorption"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 27. Radiation --> Longwave Aerosols
Longwave radiative properties of aerosols
27.1. General Interactions
Is Required: TRUE Type: ENUM Cardinality: 1.N
General longwave radiative interactions with aerosols
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.physical_representation')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "number concentration"
# "effective radii"
# "size distribution"
# "asymmetry"
# "aspect ratio"
# "mixing state"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 27.2. Physical Representation
Is Required: TRUE Type: ENUM Cardinality: 1.N
Physical representation of aerosols in the longwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.optical_methods')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "T-matrix"
# "geometric optics"
# "finite difference time domain (FDTD)"
# "Mie theory"
# "anomalous diffraction approximation"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 27.3. Optical Methods
Is Required: TRUE Type: ENUM Cardinality: 1.N
Optical methods applicable to aerosols in the longwave radiation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.radiation.longwave_gases.general_interactions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "scattering"
# "emission/absorption"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 28. Radiation --> Longwave Gases
Longwave radiative properties of gases
28.1. General Interactions
Is Required: TRUE Type: ENUM Cardinality: 1.N
General longwave radiative interactions with gases
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 29. Turbulence Convection
Atmosphere Convective Turbulence and Clouds
29.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of atmosphere convection and turbulence
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.scheme_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Mellor-Yamada"
# "Holtslag-Boville"
# "EDMF"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 30. Turbulence Convection --> Boundary Layer Turbulence
Properties of the boundary layer turbulence scheme
30.1. Scheme Name
Is Required: FALSE Type: ENUM Cardinality: 0.1
Boundary layer turbulence scheme name
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.scheme_type')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "TKE prognostic"
# "TKE diagnostic"
# "TKE coupled with water"
# "vertical profile of Kz"
# "non-local diffusion"
# "Monin-Obukhov similarity"
# "Coastal Buddy Scheme"
# "Coupled with convection"
# "Coupled with gravity waves"
# "Depth capped at cloud base"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 30.2. Scheme Type
Is Required: TRUE Type: ENUM Cardinality: 1.N
Boundary layer turbulence scheme type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.closure_order')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 30.3. Closure Order
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Boundary layer turbulence scheme closure order
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.counter_gradient')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 30.4. Counter Gradient
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Uses boundary layer turbulence scheme counter gradient
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 31. Turbulence Convection --> Deep Convection
Properties of the deep convection scheme
31.1. Scheme Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Deep convection scheme name
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_type')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "mass-flux"
# "adjustment"
# "plume ensemble"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 31.2. Scheme Type
Is Required: TRUE Type: ENUM Cardinality: 1.N
Deep convection scheme type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_method')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "CAPE"
# "bulk"
# "ensemble"
# "CAPE/WFN based"
# "TKE/CIN based"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 31.3. Scheme Method
Is Required: TRUE Type: ENUM Cardinality: 1.N
Deep convection scheme method
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.processes')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "vertical momentum transport"
# "convective momentum transport"
# "entrainment"
# "detrainment"
# "penetrative convection"
# "updrafts"
# "downdrafts"
# "radiative effect of anvils"
# "re-evaporation of convective precipitation"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 31.4. Processes
Is Required: TRUE Type: ENUM Cardinality: 1.N
Physical processes taken into account in the parameterisation of deep convection
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.microphysics')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "tuning parameter based"
# "single moment"
# "two moment"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 31.5. Microphysics
Is Required: FALSE Type: ENUM Cardinality: 0.N
Microphysics scheme for deep convection. Microphysical processes directly control the amount of detrainment of cloud hydrometeor and water vapor from updrafts
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 32. Turbulence Convection --> Shallow Convection
Properties of the shallow convection scheme
32.1. Scheme Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Shallow convection scheme name
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_type')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "mass-flux"
# "cumulus-capped boundary layer"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 32.2. Scheme Type
Is Required: TRUE Type: ENUM Cardinality: 1.N
shallow convection scheme type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "same as deep (unified)"
# "included in boundary layer turbulence"
# "separate diagnosis"
# TODO - please enter value(s)
Explanation: 32.3. Scheme Method
Is Required: TRUE Type: ENUM Cardinality: 1.1
shallow convection scheme method
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.processes')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "convective momentum transport"
# "entrainment"
# "detrainment"
# "penetrative convection"
# "re-evaporation of convective precipitation"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 32.4. Processes
Is Required: TRUE Type: ENUM Cardinality: 1.N
Physical processes taken into account in the parameterisation of shallow convection
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.microphysics')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "tuning parameter based"
# "single moment"
# "two moment"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 32.5. Microphysics
Is Required: FALSE Type: ENUM Cardinality: 0.N
Microphysics scheme for shallow convection
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.microphysics_precipitation.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 33. Microphysics Precipitation
Large Scale Cloud Microphysics and Precipitation
33.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of large scale cloud microphysics and precipitation
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_precipitation.scheme_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 34. Microphysics Precipitation --> Large Scale Precipitation
Properties of the large scale precipitation scheme
34.1. Scheme Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Commonly used name of the large scale precipitation parameterisation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_precipitation.hydrometeors')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "liquid rain"
# "snow"
# "hail"
# "graupel"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 34.2. Hydrometeors
Is Required: TRUE Type: ENUM Cardinality: 1.N
Precipitating hydrometeors taken into account in the large scale precipitation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_cloud_microphysics.scheme_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 35. Microphysics Precipitation --> Large Scale Cloud Microphysics
Properties of the large scale cloud microphysics scheme
35.1. Scheme Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Commonly used name of the microphysics parameterisation scheme used for large scale clouds.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_cloud_microphysics.processes')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "mixed phase"
# "cloud droplets"
# "cloud ice"
# "ice nucleation"
# "water vapour deposition"
# "effect of raindrops"
# "effect of snow"
# "effect of graupel"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 35.2. Processes
Is Required: TRUE Type: ENUM Cardinality: 1.N
Large scale cloud microphysics processes
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 36. Cloud Scheme
Characteristics of the cloud scheme
36.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of the atmosphere cloud scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 36.2. Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Commonly used name for the cloud scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.atmos_coupling')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "atmosphere_radiation"
# "atmosphere_microphysics_precipitation"
# "atmosphere_turbulence_convection"
# "atmosphere_gravity_waves"
# "atmosphere_solar"
# "atmosphere_volcano"
# "atmosphere_cloud_simulator"
# TODO - please enter value(s)
Explanation: 36.3. Atmos Coupling
Is Required: FALSE Type: ENUM Cardinality: 0.N
Atmosphere components that are linked to the cloud scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.uses_separate_treatment')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 36.4. Uses Separate Treatment
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Different cloud schemes for the different types of clouds (convective, stratiform and boundary layer)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.processes')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "entrainment"
# "detrainment"
# "bulk cloud"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 36.5. Processes
Is Required: TRUE Type: ENUM Cardinality: 1.N
Processes included in the cloud scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.prognostic_scheme')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 36.6. Prognostic Scheme
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is the cloud scheme a prognostic scheme?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.diagnostic_scheme')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 36.7. Diagnostic Scheme
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is the cloud scheme a diagnostic scheme?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.prognostic_variables')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "cloud amount"
# "liquid"
# "ice"
# "rain"
# "snow"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 36.8. Prognostic Variables
Is Required: FALSE Type: ENUM Cardinality: 0.N
List the prognostic variables used by the cloud scheme, if applicable.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.optical_cloud_properties.cloud_overlap_method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "random"
# "maximum"
# "maximum-random"
# "exponential"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 37. Cloud Scheme --> Optical Cloud Properties
Optical cloud properties
37.1. Cloud Overlap Method
Is Required: FALSE Type: ENUM Cardinality: 0.1
Method for taking into account overlapping of cloud layers
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.optical_cloud_properties.cloud_inhomogeneity')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 37.2. Cloud Inhomogeneity
Is Required: FALSE Type: STRING Cardinality: 0.1
Method for taking into account cloud inhomogeneity
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "diagnostic"
# TODO - please enter value(s)
Explanation: 38. Cloud Scheme --> Sub Grid Scale Water Distribution
Sub-grid scale water distribution
38.1. Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Sub-grid scale water distribution type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.function_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 38.2. Function Name
Is Required: TRUE Type: STRING Cardinality: 1.1
Sub-grid scale water distribution function name
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.function_order')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 38.3. Function Order
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Sub-grid scale water distribution function type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.convection_coupling')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "coupled with deep"
# "coupled with shallow"
# "not coupled with convection"
# TODO - please enter value(s)
Explanation: 38.4. Convection Coupling
Is Required: TRUE Type: ENUM Cardinality: 1.N
Sub-grid scale water distribution coupling with convection
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "diagnostic"
# TODO - please enter value(s)
Explanation: 39. Cloud Scheme --> Sub Grid Scale Ice Distribution
Sub-grid scale ice distribution
39.1. Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Sub-grid scale ice distribution type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.function_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 39.2. Function Name
Is Required: TRUE Type: STRING Cardinality: 1.1
Sub-grid scale ice distribution function name
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.function_order')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 39.3. Function Order
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Sub-grid scale ice distribution function type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.convection_coupling')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "coupled with deep"
# "coupled with shallow"
# "not coupled with convection"
# TODO - please enter value(s)
Explanation: 39.4. Convection Coupling
Is Required: TRUE Type: ENUM Cardinality: 1.N
Sub-grid scale ice distribution coupling with convection
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 40. Observation Simulation
Characteristics of observation simulation
40.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of observation simulator characteristics
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.isscp_attributes.top_height_estimation_method')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "no adjustment"
# "IR brightness"
# "visible optical depth"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 41. Observation Simulation --> Isscp Attributes
ISSCP Characteristics
41.1. Top Height Estimation Method
Is Required: TRUE Type: ENUM Cardinality: 1.N
Cloud simulator ISSCP top height estimation methodUo
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.isscp_attributes.top_height_direction')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "lowest altitude level"
# "highest altitude level"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 41.2. Top Height Direction
Is Required: TRUE Type: ENUM Cardinality: 1.1
Cloud simulator ISSCP top height direction
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.run_configuration')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Inline"
# "Offline"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 42. Observation Simulation --> Cosp Attributes
CFMIP Observational Simulator Package attributes
42.1. Run Configuration
Is Required: TRUE Type: ENUM Cardinality: 1.1
Cloud simulator COSP run configuration
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_grid_points')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 42.2. Number Of Grid Points
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Cloud simulator COSP number of grid points
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_sub_columns')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 42.3. Number Of Sub Columns
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Cloud simulator COSP number of sub-cloumns used to simulate sub-grid variability
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_levels')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 42.4. Number Of Levels
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Cloud simulator COSP number of levels
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.frequency')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 43. Observation Simulation --> Radar Inputs
Characteristics of the cloud radar simulator
43.1. Frequency
Is Required: TRUE Type: FLOAT Cardinality: 1.1
Cloud simulator radar frequency (Hz)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "surface"
# "space borne"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 43.2. Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Cloud simulator radar type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.gas_absorption')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 43.3. Gas Absorption
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Cloud simulator radar uses gas absorption
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.effective_radius')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 43.4. Effective Radius
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Cloud simulator radar uses effective radius
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.lidar_inputs.ice_types')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "ice spheres"
# "ice non-spherical"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 44. Observation Simulation --> Lidar Inputs
Characteristics of the cloud lidar simulator
44.1. Ice Types
Is Required: TRUE Type: ENUM Cardinality: 1.1
Cloud simulator lidar ice type
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.observation_simulation.lidar_inputs.overlap')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "max"
# "random"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 44.2. Overlap
Is Required: TRUE Type: ENUM Cardinality: 1.N
Cloud simulator lidar overlap
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 45. Gravity Waves
Characteristics of the parameterised gravity waves in the atmosphere, whether from orography or other sources.
45.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of gravity wave parameterisation in the atmosphere
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.sponge_layer')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Rayleigh friction"
# "Diffusive sponge layer"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 45.2. Sponge Layer
Is Required: TRUE Type: ENUM Cardinality: 1.1
Sponge layer in the upper levels in order to avoid gravity wave reflection at the top.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.background')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "continuous spectrum"
# "discrete spectrum"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 45.3. Background
Is Required: TRUE Type: ENUM Cardinality: 1.1
Background wave distribution
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.subgrid_scale_orography')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "effect on drag"
# "effect on lifting"
# "enhanced topography"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 45.4. Subgrid Scale Orography
Is Required: TRUE Type: ENUM Cardinality: 1.N
Subgrid scale orography effects taken into account.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 46. Gravity Waves --> Orographic Gravity Waves
Gravity waves generated due to the presence of orography
46.1. Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Commonly used name for the orographic gravity wave scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.source_mechanisms')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "linear mountain waves"
# "hydraulic jump"
# "envelope orography"
# "low level flow blocking"
# "statistical sub-grid scale variance"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 46.2. Source Mechanisms
Is Required: TRUE Type: ENUM Cardinality: 1.N
Orographic gravity wave source mechanisms
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.calculation_method')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "non-linear calculation"
# "more than two cardinal directions"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 46.3. Calculation Method
Is Required: TRUE Type: ENUM Cardinality: 1.N
Orographic gravity wave calculation method
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.propagation_scheme')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "linear theory"
# "non-linear theory"
# "includes boundary layer ducting"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 46.4. Propagation Scheme
Is Required: TRUE Type: ENUM Cardinality: 1.1
Orographic gravity wave propogation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.dissipation_scheme')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "total wave"
# "single wave"
# "spectral"
# "linear"
# "wave saturation vs Richardson number"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 46.5. Dissipation Scheme
Is Required: TRUE Type: ENUM Cardinality: 1.1
Orographic gravity wave dissipation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 47. Gravity Waves --> Non Orographic Gravity Waves
Gravity waves generated by non-orographic processes.
47.1. Name
Is Required: FALSE Type: STRING Cardinality: 0.1
Commonly used name for the non-orographic gravity wave scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.source_mechanisms')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "convection"
# "precipitation"
# "background spectrum"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 47.2. Source Mechanisms
Is Required: TRUE Type: ENUM Cardinality: 1.N
Non-orographic gravity wave source mechanisms
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.calculation_method')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "spatially dependent"
# "temporally dependent"
# TODO - please enter value(s)
Explanation: 47.3. Calculation Method
Is Required: TRUE Type: ENUM Cardinality: 1.N
Non-orographic gravity wave calculation method
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.propagation_scheme')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "linear theory"
# "non-linear theory"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 47.4. Propagation Scheme
Is Required: TRUE Type: ENUM Cardinality: 1.1
Non-orographic gravity wave propogation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.dissipation_scheme')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "total wave"
# "single wave"
# "spectral"
# "linear"
# "wave saturation vs Richardson number"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 47.5. Dissipation Scheme
Is Required: TRUE Type: ENUM Cardinality: 1.1
Non-orographic gravity wave dissipation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.solar.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 48. Solar
Top of atmosphere solar insolation characteristics
48.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of solar insolation of the atmosphere
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.solar.solar_pathways.pathways')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "SW radiation"
# "precipitating energetic particles"
# "cosmic rays"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 49. Solar --> Solar Pathways
Pathways for solar forcing of the atmosphere
49.1. Pathways
Is Required: TRUE Type: ENUM Cardinality: 1.N
Pathways for the solar forcing of the atmosphere model domain
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.solar.solar_constant.type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "fixed"
# "transient"
# TODO - please enter value(s)
Explanation: 50. Solar --> Solar Constant
Solar constant and top of atmosphere insolation characteristics
50.1. Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Time adaptation of the solar constant.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.solar.solar_constant.fixed_value')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 50.2. Fixed Value
Is Required: FALSE Type: FLOAT Cardinality: 0.1
If the solar constant is fixed, enter the value of the solar constant (W m-2).
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.solar.solar_constant.transient_characteristics')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 50.3. Transient Characteristics
Is Required: TRUE Type: STRING Cardinality: 1.1
solar constant transient characteristics (W m-2)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.solar.orbital_parameters.type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "fixed"
# "transient"
# TODO - please enter value(s)
Explanation: 51. Solar --> Orbital Parameters
Orbital parameters and top of atmosphere insolation characteristics
51.1. Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Time adaptation of orbital parameters
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.solar.orbital_parameters.fixed_reference_date')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 51.2. Fixed Reference Date
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Reference date for fixed orbital parameters (yyyy)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.solar.orbital_parameters.transient_method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 51.3. Transient Method
Is Required: TRUE Type: STRING Cardinality: 1.1
Description of transient orbital parameters
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.solar.orbital_parameters.computation_method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Berger 1978"
# "Laskar 2004"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 51.4. Computation Method
Is Required: TRUE Type: ENUM Cardinality: 1.1
Method used for computing orbital parameters.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.solar.insolation_ozone.solar_ozone_impact')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 52. Solar --> Insolation Ozone
Impact of solar insolation on stratospheric ozone
52.1. Solar Ozone Impact
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Does top of atmosphere insolation impact on stratospheric ozone?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.volcanos.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 53. Volcanos
Characteristics of the implementation of volcanoes
53.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview description of the implementation of volcanic effects in the atmosphere
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.atmos.volcanos.volcanoes_treatment.volcanoes_implementation')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "high frequency solar constant anomaly"
# "stratospheric aerosols optical thickness"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 54. Volcanos --> Volcanoes Treatment
Treatment of volcanoes in the atmosphere
54.1. Volcanoes Implementation
Is Required: TRUE Type: ENUM Cardinality: 1.1
How volcanic effects are modeled in the atmosphere.
End of explanation |
7,977 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 3 - noise removal
The figure in this notebook illustrates
Step1: variable definitions
figure directory
Step2: example recording 1
Step3: example recording 2
Step4: formating
Step5: remove noise
remove noise from example recordings 1 and 2 using the adaptive level equalization algorithm
Step6: plot
Step7: save figure | Python Code:
from matplotlib import pyplot
%matplotlib inline
from matplotlib.patches import Rectangle
from matplotlib.lines import Line2D
import numpy
from scipy.io import wavfile
from os import path
from datetime import timedelta
from django.db import connection
from database.models import Sound
from database.models import Site
from nacoustik import Wave
from nacoustik.spectrum import psd
from nacoustik.noise import remove_background_noise, remove_anthrophony
from figutils import query, style
Explanation: Figure 3 - noise removal
The figure in this notebook illustrates: <br />
a) an example of a spectrogram from a section of an original recording <br />
b) Spectrogram of biophony after we applied the modified-ALE technique to the original spectrogram <br />
c) Spectrogram from a section of an original recording <br />
d) Spectrogram of biophony after we applied the modified-ALE technique to the original spectrogram <br />
import statements
End of explanation
figure_directory = ""
Explanation: variable definitions
figure directory
End of explanation
site1 = Site.objects.get(name='Höttinger Rain')
sound_db1 = Sound.objects.get(id=147)
Explanation: example recording 1
End of explanation
site2 = Site.objects.get(name='Pfaffensteig')
sound_db2 = Sound.objects.get(id=158)
Explanation: example recording 2
End of explanation
style.set_font()
Explanation: formating
End of explanation
# example recording 1
wave1 = Wave(sound_db1.get_filepath())
wave1.read()
wave1.normalize()
samples1 = wave1.samples[(100 * wave1.rate):(160 * wave1.rate)]
duration = 60
f, t, a_pass = psd(samples1, rate=wave1.rate, window_length=512)
ale_pass = remove_background_noise(a_pass, N=0.18, iterations=3)
b_pass = remove_anthrophony(ale_pass, time_delta=t[1]-t[0], freq_delta=f[1]-f[0])
b_pass = numpy.ma.masked_equal(b_pass, value=0)
# example recording 2
wave2 = Wave(sound_db2.get_filepath())
wave2.read()
wave2.normalize()
samples2 = wave2.samples[(0 * wave2.rate):(60 * wave2.rate)]
duration = 60
f, t, a_fail = psd(samples2, rate=wave2.rate, window_length=512)
ale_fail = remove_background_noise(a_fail, N=0.18, iterations=3)
b_fail = remove_anthrophony(ale_fail, time_delta=t[1]-t[0], freq_delta=f[1]-f[0])
b_fail = numpy.ma.masked_equal(b_fail, value=0)
Explanation: remove noise
remove noise from example recordings 1 and 2 using the adaptive level equalization algorithm
End of explanation
# create figure
figure3 = pyplot.figure()
#figure3.subplots_adjust(left=0.04, bottom=0.12, right=0.96, top=0.97, wspace=0, hspace=0)
figure3.subplots_adjust(left=0.04, bottom=0.04, right=0.96, top=0.99, wspace=0, hspace=0)
figure3.set_figwidth(6.85)
figure3.set_figheight(9.21)
# specify frequency bins (width of 1 kiloherz)
bins = numpy.arange(0, (wave1.rate / 2), 1000)
# axes
ax_a = pyplot.subplot2grid((21, 1), (0, 0), rowspan=5, colspan=1)
ax_b = pyplot.subplot2grid((21, 1), (5, 0), rowspan=5, colspan=1, sharex=ax_a, sharey=ax_a)
ax_c = pyplot.subplot2grid((21, 1), (11, 0), rowspan=5, colspan=1, sharey=ax_a)
ax_d = pyplot.subplot2grid((21, 1), (16, 0), rowspan=5, colspan=1, sharex=ax_c, sharey=ax_a)
# compute xlabels
start_time = sound_db1.get_datetime() + timedelta(seconds=100)
time_delta = 10
n = int((duration / time_delta) + 1)
xlabels_pass = [(start_time + timedelta(seconds=i*time_delta)).strftime("%H:%M:%S") for i in range(n)]
start_time = sound_db1.get_datetime()
xlabels_fail = [(start_time + timedelta(seconds=i*time_delta)).strftime("%H:%M:%S") for i in range(n)]
ylabels = ["", "2", "", "4", "", "6", "", "8", "", "10", "", ""]
# original - example 1
spec_1 = ax_a.pcolormesh(t, f, a_pass[0], cmap='Greys', vmin=-150, vmax=-80)
ax_a.set(ylim=([0, wave1.rate / 2]),
yticks = bins.astype(numpy.int) + 1000)
ax_a.set_yticklabels(ylabels)
ax_a.set_ylabel("frequency (kilohertz)")
ax_a.tick_params(length=6, color='black', direction='in',
bottom=True, labelbottom=False,
top=False, labeltop=False,
left=True, labelleft=False,
right=True, labelright=True)
ax_a.set_frame_on(False)
# after adaptive level equalization - example 1
spec_2 = ax_b.pcolormesh(t, f, b_pass[0], cmap='Greys', vmin=-150, vmax=-80)
ax_b.set(ylim=([0, wave1.rate / 2]),
yticks = bins.astype(numpy.int) + 1000)
ax_b.set_xticklabels(xlabels_pass)
ax_b.set_ylabel("frequency (kilohertz)")
ax_b.tick_params(length=6, color='black', direction='in',
bottom=True, labelbottom=True,
top=False, labeltop=False,
left=True, labelleft=False,
right=True, labelright=True)
ax_b.set_frame_on(False)
# original - example 2
spec_3 = ax_c.pcolormesh(t, f, a_fail[1], cmap='Greys', vmin=-150, vmax=-80)
ax_c.set(ylim=([0, wave2.rate / 2]),
yticks = bins.astype(numpy.int) + 1000)
ax_c.set_ylabel("frequency (kilohertz)")
ax_c.tick_params(length=6, color='black', direction='in',
bottom=True, labelbottom=False,
top=False, labeltop=False,
left=True, labelleft=False,
right=True, labelright=True)
ax_c.set_frame_on(False)
# after adaptive level equalization - example 2
spec_4 = ax_d.pcolormesh(t, f, b_fail[1], cmap='Greys', vmin=-150, vmax=-80)
ax_d.set(ylim=([0, wave2.rate / 2]),
yticks = bins.astype(numpy.int) + 1000)
ax_d.set_xticklabels(xlabels_fail)
ax_d.set_ylabel("frequency (kilohertz)")
ax_d.tick_params(length=6, color='black', direction='in',
bottom=True, labelbottom=True,
top=False, labeltop=False,
left=True, labelleft=False,
right=True, labelright=True)
ax_d.set_frame_on(False)
ax_d.set_xlabel("time of day (hours:minutes:seconds)")
# axes borders
ax_a.add_line(Line2D([t[0], t[-1:]], [1, 1], color='black', linewidth=1))
ax_a.add_line(Line2D([t[0], t[0]], [0, 12000], color='black', linewidth=1))
ax_a.add_line(Line2D([t[-1:], t[-1:]], [0, 12000], color='black', linewidth=1))
ax_b.add_line(Line2D([t[0], t[-1:]], [1, 1], color='black', linewidth=1))
ax_b.add_line(Line2D([t[0], t[0]], [0, 12000], color='black', linewidth=1))
ax_b.add_line(Line2D([t[-1:], t[-1:]], [0, 12000], color='black', linewidth=1))
ax_c.add_line(Line2D([t[0], t[-1:]], [1, 1], color='black', linewidth=1))
ax_c.add_line(Line2D([t[0], t[0]], [0, 12000], color='black', linewidth=1))
ax_c.add_line(Line2D([t[-1:], t[-1:]], [0, 12000], color='black', linewidth=1))
ax_d.add_line(Line2D([t[0], t[-1:]], [1, 1], color='black', linewidth=1))
ax_d.add_line(Line2D([t[0], t[0]], [0, 12000], color='black', linewidth=1))
ax_d.add_line(Line2D([t[-1:], t[-1:]], [0, 12000], color='black', linewidth=1))
# annotation
ax_a.add_line(Line2D([t[0], t[-1:]], [2000, 2000], color='black', linewidth=1, linestyle='--'))
t1 = ax_a.text(14, 2100, '2 kilohertz', color='black', ha='left', va='bottom')
b1 = ax_a.add_patch(Rectangle((23, 0), 9, 6100, facecolor='none', edgecolor='black', linestyle='--'))
b2 = ax_a.add_patch(Rectangle((30, 0), 9, 11500, facecolor='none', edgecolor='black', linestyle='--'))
ap = dict(arrowstyle='-',
connectionstyle='arc3,rad=0.2')
a1 = ax_a.annotate('plane landing', (23, 4000), xytext=(21, 6000), ha='right', va='center', arrowprops=ap)
a2 = ax_a.annotate('car passing', (39, 9000), xytext=(42, 10000), ha='left', va='center', arrowprops=ap)
style.multi_annotate(ax_a, 'birds calling', xy_list=[(53.5, 8500), (45.5, 4000)], xytext=(50, 6300),
ha='center', va='center',
arrowprops=dict(arrowstyle='->',
connectionstyle='arc3,rad=0.2'))
# title formatting
title_font = {
'size': 12.0,
'weight': 'bold'
}
ax_a2 = pyplot.axes([0.005, 0, 1, 0.99], facecolor=(1, 1, 1, 0), frameon=False)
ax_a2.tick_params(bottom=False, labelbottom=False,
top=False, labeltop=False,
left=False, labelleft=False,
right=False, labelright=False)
ax_b2 = pyplot.axes([0.005, 0, 1, 0.76], facecolor=(1, 1, 1, 0), frameon=False)
ax_b2.tick_params(bottom=False, labelbottom=False,
top=False, labeltop=False,
left=False, labelleft=False,
right=False, labelright=False)
ax_c2 = pyplot.axes([0.005, 0, 1, 0.49], facecolor=(1, 1, 1, 0), frameon=False)
ax_c2.tick_params(bottom=False, labelbottom=False,
top=False, labeltop=False,
left=False, labelleft=False,
right=False, labelright=False)
ax_d2 = pyplot.axes([0.005, 0, 1, 0.26], facecolor=(1, 1, 1, 0), frameon=False)
ax_d2.tick_params(bottom=False, labelbottom=False,
top=False, labeltop=False,
left=False, labelleft=False,
right=False, labelright=False)
t1 = ax_a2.text(0, 1, 'a', horizontalalignment='left', verticalalignment='top',
fontdict=title_font)
t2 = ax_b2.text(0, 1, 'b', horizontalalignment='left', verticalalignment='top',
fontdict=title_font)
t3 = ax_c2.text(0, 1, 'c', horizontalalignment='left', verticalalignment='top',
fontdict=title_font)
t4 = ax_d2.text(0, 1, 'd', horizontalalignment='left', verticalalignment='top',
fontdict=title_font)
Explanation: plot
End of explanation
#figure3.savefig(path.join(figure_directory, "figure3.png"), dpi=300)
Explanation: save figure
End of explanation |
7,978 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RNA example
We take a fasta file in input and write utility functions to build a graph representation based on the structure computed by RNAfold. Finally we use the EDeN vectorizer to perform clustering or build a predictive model.
Step1: set an interface for data acquisition, either from file or from remote
Step2: write a parser for FASTA format
Step3: write a converter that takes a parsed fasta file in input, calls RNAfold, parses the output and builds a graph
Step4: display the graphs
Step5: Setup the vectorizer object
Step6: process the fasta, build the graphs, transform them with the vectorizer into sparse vectors
Step7: create a custom fasta parser that shuffles the sequences; these will be used as negative examples
Step8: build a data matrix by stacking the data matrix for positive and for negative instances, build a target vector with +1 for positive ids and -1 for negative ids
Step9: fit a binary classifier from the scikit ML library
Step10: evaluate the quality of the classifier using the cross-validation technique
Step11: use the decision_function of the classifier to get an indication on its confidence for each instance | Python Code:
%matplotlib inline
Explanation: RNA example
We take a fasta file in input and write utility functions to build a graph representation based on the structure computed by RNAfold. Finally we use the EDeN vectorizer to perform clustering or build a predictive model.
End of explanation
def rfam_uri(family_id):
return 'http://rfam.xfam.org/family/%s/alignment?acc=%s&format=fastau&download=0'%(family_id,family_id)
def rfam_uri(family_id):
return '%s.fa'%(family_id)
rfam_id = 'RF00005' #tRNA
rfam_id = 'RF00871' #microRNA mir-689
rfam_id = 'RF02275' #Hammerhead_HH9
Explanation: set an interface for data acquisition, either from file or from remote
End of explanation
import re
from eden import util
def fasta_to_fasta( input ):
for m in re.finditer(r"^(>[^\n]+)\n+([^>]+)",'\n'.join(util.read( input )), re.MULTILINE):
if m:
header, seq = m.groups()
seq = re.sub('\n','',seq)
yield header
yield seq
iterable = fasta_to_fasta(rfam_uri(rfam_id))
[line for line in iterable]
Explanation: write a parser for FASTA format
End of explanation
import networkx as nx
def sequence_dotbracket_to_graph(seq_info, seq_struct):
G = nx.Graph()
lifo = list()
for i,(c,b) in enumerate( zip(seq_info, seq_struct) ):
G.add_node(i, label = c)
if i > 0:
#add backbone edges
G.add_edge(i,i-1, label='-')
if b == '(':
lifo.append(i)
if b == ')':
#when a closing bracket is found, add a basepair edge with the corresponding opening bracket
j = lifo.pop()
G.add_edge(i,j, label='=')
return G
import subprocess as sp
def pre_process(input):
lines = fasta_to_fasta(input)
for line in lines:
#get a header+sequence
header = line
seq = lines.next()
#invoke RNAfold
cmd = 'echo "%s" | RNAfold --noPS' % seq
out = sp.check_output(cmd, shell = True)
#parse the output
text = out.strip().split('\n')
seq_info = text[0]
seq_struct = text[1].split()[0]
#make a graph
G = sequence_dotbracket_to_graph(seq_info, seq_struct)
G.graph['id'] = header
yield G
Explanation: write a converter that takes a parsed fasta file in input, calls RNAfold, parses the output and builds a graph
End of explanation
from eden.util.display import draw_graph
import itertools
graphs = pre_process(rfam_uri(rfam_id))
for graph in itertools.islice(graphs,2):
draw_graph(graph, size=11, node_size=200, node_border=False)
Explanation: display the graphs
End of explanation
from eden.graph import Vectorizer
vectorizer = Vectorizer( complexity=2 )
def describe(X):
print 'Instances: %d ; Features: %d with an avg of %d features per instance' % (X.shape[0], X.shape[1], X.getnnz()/X.shape[0])
Explanation: Setup the vectorizer object
End of explanation
graphs = pre_process(rfam_uri(rfam_id))
Xp = vectorizer.transform( graphs )
describe(Xp)
Explanation: process the fasta, build the graphs, transform them with the vectorizer into sparse vectors
End of explanation
import random
def shuffle_fasta( input , times=1, order=1):
iterable = fasta_to_fasta(input)
for line in iterable:
#get pairs of header-sequence
header = line
seq = iterable.next()
#shuffle
for i in range(times):
#split the seqeunce in substrings of length 'order'
kmers = [ seq[i:i+order] for i in range(0,len(seq),order) ]
#shuffle and join
random.shuffle(kmers)
seq_out = ''.join(kmers)
yield header
yield seq_out
iterable = shuffle_fasta( rfam_uri(rfam_id), times=2, order=2)
graphs = pre_process( iterable )
Xn = vectorizer.transform( graphs )
describe(Xn)
Explanation: create a custom fasta parser that shuffles the sequences; these will be used as negative examples
End of explanation
import numpy as np
from scipy.sparse import vstack
yp = [1] * Xp.shape[0]
yn = [-1] * Xn.shape[0]
y = np.array(yp + yn)
X = vstack( [Xp,Xn] , format = "csr")
Explanation: build a data matrix by stacking the data matrix for positive and for negative instances, build a target vector with +1 for positive ids and -1 for negative ids
End of explanation
from sklearn.linear_model import SGDClassifier
estimator = SGDClassifier(class_weight='auto', shuffle = True )
estimator.fit(X,y)
Explanation: fit a binary classifier from the scikit ML library
End of explanation
from sklearn import cross_validation
print 'Predictive performance:'
#assess the generalization capacity of the model via a k-fold cross validation
for scoring in ['accuracy','precision', 'recall', 'f1', 'average_precision', 'roc_auc']:
scores = cross_validation.cross_val_score( estimator, X, y, cv = 3, scoring = scoring )
print( '%20s: %.3f +- %.3f' % ( scoring, np.mean( scores ), np.std( scores ) ) )
Explanation: evaluate the quality of the classifier using the cross-validation technique
End of explanation
graphs = pre_process(rfam_uri(rfam_id))
Xp = vectorizer.transform( graphs )
predictions = estimator.decision_function(Xp)
iterable = fasta_to_fasta(rfam_uri(rfam_id))
headers = [line for line in itertools.islice(iterable, 0, None, 2)]
for prediction,header in sorted(zip(predictions, headers), reverse=True):
print "Score: %0.3f %s " % (prediction, header)
%%time
from sklearn.cluster import KMeans
kmeans = KMeans( n_clusters=4 )
predictions = kmeans.fit_predict(Xp)
#get the headers of the FASTA files
iterable = fasta_to_fasta(rfam_uri(rfam_id))
headers = [line for line in itertools.islice(iterable, 0, None, 2)]
for prediction,header in sorted(zip(predictions, headers)):
print "cluster: %d %s " % (prediction, header)
graphs = itertools.islice( pre_process( rfam_uri( rfam_id ) ), 50 )
from eden.util.display import dendrogram
dendrogram( graphs, vectorizer )
%%time
graphs = itertools.islice( pre_process( rfam_uri( rfam_id ) ), 450 )
from eden.util.display import embed2D
embed2D( graphs, vectorizer )
Explanation: use the decision_function of the classifier to get an indication on its confidence for each instance
End of explanation |
7,979 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Guide to Building End-to-End Reinforcement Learning Application Pipelines using Vertex AI
<table align="left">
<td>
<a href="https
Step1: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
Step2: Before you begin
Select a GPU runtime
Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select "Runtime --> Change runtime type > GPU"
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the Vertex AI API, BigQuery API, Cloud Build, Cloud Functions, Cloud Scheduler, Cloud Storage, and Pub/Sub API.
If you are running this notebook locally, you will need to install the Cloud SDK.
Enter your project ID in the cell below. Then run the cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.
Note
Step3: Otherwise, set your project ID here.
Step4: Timestamp
If 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 it onto the name of resources you create in this tutorial.
Step5: Authenticate your Google Cloud account
If you are using Google Cloud Notebooks, your environment is already
authenticated. Skip this step.
If you are using Colab, run the cell below and follow the instructions
when prompted to authenticate your account via oAuth.
Otherwise, follow these steps
Step6: Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
In this tutorial, a Cloud Storage bucket holds the MovieLens dataset files to be used for model training. Vertex AI also saves the trained model that results from your training job in the same bucket. Using this model artifact, you can then create Vertex AI model and endpoint resources in order to serve online predictions.
Set the name of your Cloud Storage bucket below. It must be unique across all
Cloud Storage buckets.
You may also change the REGION variable, which is used for operations
throughout the rest of this notebook. Make sure to choose a region where Vertex AI services are
available. You may
not use a Multi-Regional Storage bucket for training with Vertex AI. Also note that Vertex
Pipelines is currently only supported in select regions such as "us-central1" (reference).
Step7: Only if your bucket doesn't already exist
Step8: Finally, validate access to your Cloud Storage bucket by examining its contents
Step9: Import libraries and define constants
Step10: Fill out the following configurations
Step11: Set additional configurations
You may use the default values below as is.
Step12: Create the RL pipeline components
This section consists of the following steps
Step13: Create the Ingester to ingest data
Create the Ingester component to ingest data from BigQuery, package them as tf.train.Example objects, and output TFRecord files.
Read more about tf.train.Example and TFRecord here.
The Ingester component source code is in src/ingester/ingester_component.py.
Run unit tests on the Ingester component
Step14: Create the Trainer to train the RL policy
Create the Trainer component to train a RL policy on the training dataset, and then submit a remote custom training job to Vertex AI. This component trains a policy using the TF-Agents LinUCB agent on the MovieLens simulation dataset, and saves the trained policy as a SavedModel.
The Trainer component source code is in src/trainer/trainer_component.py. You use additional Vertex AI platform code in pipeline construction to submit the training code defined in Trainer as a custom training job to Vertex AI. (The additional code is similar to what kfp.v2.google.experimental.run_as_aiplatform_custom_job does. You can find an example notebook here for how to use that first-party Trainer component.)
The Trainer performs off-policy training, where you train a policy on a static set of pre-collected data records containing information including observation, action and reward. For a data record, the policy in training might not output the same action given the observation in that data record.
If you're interested in pipeline metrics, read about KFP Pipeline Metrics here.
Step15: Run unit tests on the Trainer component
Step16: Create the Deployer to deploy the trained policy to a Vertex AI endpoint
Use google_cloud_pipeline_components.aiplatform components during pipeline construction to
Step17: Create a custom prediction container using Cloud Build
Before setting up the Deployer, define and build a custom prediction container that serves predictions using the trained policy. The source code, Cloud Build YAML configuration file and Dockerfile are in src/prediction_container.
This prediction container is the serving container for the deployed, trained policy. See a more detailed guide on building prediction custom containers here.
Step19: Create a Cloud Build YAML file using Kaniko build
Note
Step20: Run unit tests on the prediction code
Step21: Build custom prediction container
Step23: Author and run the RL pipeline
You author the pipeline using custom KFP components built from the previous section, and create a pipeline run using Vertex Pipelines. You can read more about whether to enable execution caching here. You can also specifically configure the worker pool spec for training if for instance you want to train at scale and/or at a higher speed; you can adjust the replica count, machine type, accelerator type and count, and many other specifications.
Here, you build a "startup" pipeline that generates randomly sampled training data (with the Generator) as the first step. This pipeline runs only once.
Step24: Create the Simulator to send simulated MovieLens prediction requests
Create the Simulator to obtain observations from the MovieLens simulation environment, formats them, and sends prediction requests to the Vertex AI endpoint.
The workflow is
Step25: Run unit tests on the Simulator
Step26: Create a Pub/Sub topic
Read more about creating Pub/Sub topics here
Step27: Set up a recurrent Cloud Scheduler job for the Pub/Sub topic
Read more about possible ways to create cron jobs here.
Read about the cron job schedule format here.
Step28: Define the Simulator logic in a Cloud Function to be triggered periodically, and deploy this Function
Specify dependencies of the Function in src/simulator/requirements.txt.
Read more about the available configurable arguments for deploying a Function here. For instance, based on the complexity of your Function, you may want to adjust its memory and timeout.
Note that the environment variables in ENV_VARS should be comma-separated; there should not be additional spaces, or other characters in between. Read more about setting/updating/deleting environment variables here.
Read more about sending predictions to Vertex endpoints here.
Step29: Create the Logger to asynchronously log prediction inputs and results
Create the Logger to get environment feedback as rewards from the MovieLens simulation environment based on prediction observations and predicted actions, formulate trajectory data, and store said data back to BigQuery. The Logger closes the RL feedback loop from prediction to training data, and allows re-training of the policy on new training data.
The Logger is triggered by a hook in the prediction code. At each prediction request, the prediction code messages a Pub/Sub topic, which triggers the Logger code.
The workflow is
Step30: Create a Pub/Sub topic
Read more about creating Pub/Sub topics here
Step31: Define the Logger logic in a Cloud Function to be triggered by a Pub/Sub topic, which is triggered by the prediction code at each prediction request.
Specify dependencies of the Function in src/logger/requirements.txt.
Read more about the available configurable arguments for deploying a Function here. For instance, based on the complexity of your Function, you may want to adjust its memory and timeout.
Note that the environment variables in ENV_VARS should be comma-separated; there should not be additional spaces, or other characters in between. Read more about setting/updating/deleting environment variables here.
Step33: Create the Trigger to trigger re-training
Create the Trigger to recurrently re-run the pipeline to re-train the policy on new training data, using kfp.v2.google.client.AIPlatformClient.create_schedule_from_job_spec. You create a pipeline for orchestration on Vertex Pipelines, and a Cloud Scheduler job that recurrently triggers the pipeline. The method also automatically creates a Cloud Function that acts as an intermediary between the Scheduler and Pipelines. You can find the source code here.
When the Simulator sends prediction requests to the endpoint, the Logger is triggered by the hook in the prediction code to log prediction results to BigQuery, as new training data. As this pipeline has a recurrent schedule, it utlizes the new training data in training a new policy, therefore closing the feedback loop. Theoretically speaking, if you set the pipeline scheduler to be infinitely frequent, then you would be approaching real-time, continuous training.
Step34: Cleaning up
To clean up all Google Cloud resources used in this project, you can delete the Google Cloud
project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial (you also need to clean up other resources that are difficult to delete here, such as the all/partial of data in BigQuery, the recurring pipeline and its Scheduler job, the uploaded policy/model, etc.) | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
! pip3 install {USER_FLAG} google-cloud-aiplatform
! pip3 install {USER_FLAG} google-cloud-pipeline-components
! pip3 install {USER_FLAG} --upgrade kfp
! pip3 install {USER_FLAG} numpy
! pip3 install {USER_FLAG} --upgrade tensorflow
! pip3 install {USER_FLAG} --upgrade pillow
! pip3 install {USER_FLAG} --upgrade tf-agents
! pip3 install {USER_FLAG} --upgrade fastapi
Explanation: Guide to Building End-to-End Reinforcement Learning Application Pipelines using Vertex AI
<table align="left">
<td>
<a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/tree/master/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb">
<img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab
</a>
</td>
<td>
<a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/master/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/mlops_pipeline_tf_agents_bandits_movie_recommendation.ipynb">
<img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">
View on GitHub
</a>
</td>
</table>
Overview
This demo showcases the use of TF-Agents, Kubeflow Pipelines (KFP) and Vertex AI, particularly Vertex Pipelines, in building an end-to-end reinforcement learning (RL) pipeline of a movie recommendation system. The demo is intended for developers who want to create RL applications using TensorFlow, TF-Agents and Vertex AI services, and those who want to build end-to-end production pipelines using KFP and Vertex Pipelines. It is recommended for developers to have familiarity with RL and the contextual bandits formulation, and the TF-Agents interface.
Dataset
This demo uses the MovieLens 100K dataset to simulate an environment with users and their respective preferences. It is available at gs://cloud-samples-data/vertex-ai/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/u.data.
Objective
In this notebook, you will learn how to build an end-to-end RL pipeline for a TF-Agents (particularly the bandits module) based movie recommendation system, using KFP, Vertex AI and particularly Vertex Pipelines which is fully managed and highly scalable.
This Vertex Pipeline includes the following components:
1. Generator to generate MovieLens simulation data
2. Ingester to ingest data
3. Trainer to train the RL policy
4. Deployer to deploy the trained policy to a Vertex AI endpoint
After pipeline construction, you (1) create the Simulator (which utilizes Cloud Functions, Cloud Scheduler and Pub/Sub) to send simulated MovieLens prediction requests, (2) create the Logger to asynchronously log prediction inputs and results (which utilizes Cloud Functions, Pub/Sub and a hook in the prediction code), and (3) create the Trigger to trigger recurrent re-training.
A more general ML pipeline is demonstrated in MLOps on Vertex AI.
Costs
This tutorial uses billable components of Google Cloud:
Vertex AI
BigQuery
Cloud Build
Cloud Functions
Cloud Scheduler
Cloud Storage
Pub/Sub
Learn about Vertex AI
pricing, BigQuery pricing, Cloud Build, Cloud Functions, Cloud Scheduler, Cloud Storage
pricing, and Pub/Sub pricing, and use the Pricing
Calculator
to generate a cost estimate based on your projected usage.
Set up your local development environment
If you are using Colab or Google Cloud Notebooks, your environment already meets
all the requirements to run this notebook. You can skip this step.
Otherwise, make sure your environment meets this notebook's requirements.
You need the following:
The Google Cloud SDK
Git
Python 3
virtualenv
Jupyter notebook running in a virtual environment with Python 3
The Google Cloud guide to Setting up a Python development
environment and the Jupyter
installation guide provide detailed instructions
for meeting these requirements. The following steps provide a condensed set of
instructions:
Install and initialize the Cloud SDK.
Install Python 3.
Install
virtualenv
and create a virtual environment that uses Python 3. Activate the virtual environment.
To install Jupyter, run pip3 install jupyter on the
command-line in a terminal shell.
To launch Jupyter, run jupyter notebook on the command-line in a terminal shell.
Open this notebook in the Jupyter Notebook Dashboard.
Install additional packages
Install additional package dependencies not installed in your notebook environment, such as the Kubeflow Pipelines (KFP) SDK.
End of explanation
# Automatically restart kernel after installs
import os
if not os.getenv("IS_TESTING"):
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
Explanation: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
End of explanation
import os
PROJECT_ID = ""
# Get your Google Cloud project ID from gcloud
if not os.getenv("IS_TESTING"):
shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
print("Project ID: ", PROJECT_ID)
Explanation: Before you begin
Select a GPU runtime
Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select "Runtime --> Change runtime type > GPU"
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the Vertex AI API, BigQuery API, Cloud Build, Cloud Functions, Cloud Scheduler, Cloud Storage, and Pub/Sub API.
If you are running this notebook locally, you will need to install the Cloud SDK.
Enter your project ID in the cell below. Then run the cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.
Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $ into these commands.
Set your project ID
If you don't know your project ID, you may be able to get your project ID using gcloud.
End of explanation
if PROJECT_ID == "" or PROJECT_ID is None:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
Explanation: Otherwise, set your project ID here.
End of explanation
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
Explanation: Timestamp
If 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 it onto the name of resources you create in this tutorial.
End of explanation
import os
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# If on Google Cloud Notebooks, then don't execute this code
if not IS_GOOGLE_CLOUD_NOTEBOOK:
if "google.colab" in sys.modules:
from google.colab import auth as google_auth
google_auth.authenticate_user()
# If you are running this notebook locally, replace the string below with the
# path to your service account key and run this cell to authenticate your GCP
# account.
elif not os.getenv("IS_TESTING"):
%env GOOGLE_APPLICATION_CREDENTIALS ''
Explanation: Authenticate your Google Cloud account
If you are using Google Cloud Notebooks, your environment is already
authenticated. Skip this step.
If you are using Colab, run the cell below and follow the instructions
when prompted to authenticate your account via oAuth.
Otherwise, follow these steps:
In the Cloud Console, go to the Create service account key
page.
Click Create service account.
In the Service account name field, enter a name, and
click Create.
In the Grant this service account access to project section, click the Role drop-down list. Type "Vertex AI"
into the filter box, and select
Vertex AI Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin.
Click Create. A JSON file that contains your key downloads to your
local environment.
Enter the path to your service account key as the
GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell.
End of explanation
BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"}
REGION = "[your-region]" # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP
Explanation: Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
In this tutorial, a Cloud Storage bucket holds the MovieLens dataset files to be used for model training. Vertex AI also saves the trained model that results from your training job in the same bucket. Using this model artifact, you can then create Vertex AI model and endpoint resources in order to serve online predictions.
Set the name of your Cloud Storage bucket below. It must be unique across all
Cloud Storage buckets.
You may also change the REGION variable, which is used for operations
throughout the rest of this notebook. Make sure to choose a region where Vertex AI services are
available. You may
not use a Multi-Regional Storage bucket for training with Vertex AI. Also note that Vertex
Pipelines is currently only supported in select regions such as "us-central1" (reference).
End of explanation
! gsutil mb -l $REGION $BUCKET_NAME
Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket.
End of explanation
! gsutil ls -al $BUCKET_NAME
Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents:
End of explanation
import os
import sys
from google.cloud import aiplatform
from google_cloud_pipeline_components import aiplatform as gcc_aip
from kfp.v2 import compiler, dsl
from kfp.v2.google.client import AIPlatformClient
Explanation: Import libraries and define constants
End of explanation
# BigQuery parameters (used for the Generator, Ingester, Logger)
BIGQUERY_DATASET_ID = f"{PROJECT_ID}.movielens_dataset" # @param {type:"string"} BigQuery dataset ID as `project_id.dataset_id`.
BIGQUERY_LOCATION = "us" # @param {type:"string"} BigQuery dataset region.
BIGQUERY_TABLE_ID = f"{BIGQUERY_DATASET_ID}.training_dataset" # @param {type:"string"} BigQuery table ID as `project_id.dataset_id.table_id`.
Explanation: Fill out the following configurations
End of explanation
# Dataset parameters
RAW_DATA_PATH = "gs://[your-bucket-name]/raw_data/u.data" # @param {type:"string"}
# Download the sample data into your RAW_DATA_PATH
! gsutil cp "gs://cloud-samples-data/vertex-ai/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/u.data" $RAW_DATA_PATH
# Pipeline parameters
PIPELINE_NAME = "movielens-pipeline" # Pipeline display name.
ENABLE_CACHING = False # Whether to enable execution caching for the pipeline.
PIPELINE_ROOT = f"{BUCKET_NAME}/pipeline" # Root directory for pipeline artifacts.
PIPELINE_SPEC_PATH = "metadata_pipeline.json" # Path to pipeline specification file.
OUTPUT_COMPONENT_SPEC = "output-component.yaml" # Output component specification file.
# BigQuery parameters (used for the Generator, Ingester, Logger)
BIGQUERY_TMP_FILE = (
"tmp.json" # Temporary file for storing data to be loaded into BigQuery.
)
BIGQUERY_MAX_ROWS = 5 # Maximum number of rows of data in BigQuery to ingest.
# Dataset parameters
TFRECORD_FILE = (
f"{BUCKET_NAME}/trainer_input_path/*" # TFRecord file to be used for training.
)
# Logger parameters (also used for the Logger hook in the prediction container)
LOGGER_PUBSUB_TOPIC = "logger-pubsub-topic" # Pub/Sub topic name for the Logger.
LOGGER_CLOUD_FUNCTION = "logger-cloud-function" # Cloud Functions name for the Logger.
Explanation: Set additional configurations
You may use the default values below as is.
End of explanation
! python3 -m unittest src.generator.test_generator_component
Explanation: Create the RL pipeline components
This section consists of the following steps:
1. Create the Generator to generate MovieLens simulation data
2. Create the Ingester to ingest data
3. Create the Trainer to train the RL policy
4. Create the Deployer to deploy the trained policy to a Vertex AI endpoint
After pipeline construction, create the Simulator to send simulated MovieLens prediction requests, create the Logger to asynchronously log prediction inputs and results, and create the Trigger to trigger re-training.
Here's the entire workflow:
1. The startup pipeline has the following components: Generator --> Ingester --> Trainer --> Deployer. This pipeline only runs once.
2. Then, the Simulator generates prediction requests (e.g. every 5 mins), and the Logger gets invoked immediately at each prediction request and logs each prediction request asynchronously into BigQuery. The Trigger runs the re-training pipeline (e.g. every 30 mins) with the following components: Ingester --> Trainer --> Deploy.
You can find the KFP SDK documentation here.
Create the Generator to generate MovieLens simulation data
Create the Generator component to generate the initial set of training data using a MovieLens simulation environment and a random data-collecting policy. Store the generated data in BigQuery.
The Generator source code is src/generator/generator_component.py.
Run unit tests on the Generator component
Before running the command, you should update the RAW_DATA_PATH in src/generator/test_generator_component.py.
End of explanation
! python3 -m unittest src.ingester.test_ingester_component
Explanation: Create the Ingester to ingest data
Create the Ingester component to ingest data from BigQuery, package them as tf.train.Example objects, and output TFRecord files.
Read more about tf.train.Example and TFRecord here.
The Ingester component source code is in src/ingester/ingester_component.py.
Run unit tests on the Ingester component
End of explanation
# Trainer parameters
TRAINING_ARTIFACTS_DIR = (
f"{BUCKET_NAME}/artifacts" # Root directory for training artifacts.
)
TRAINING_REPLICA_COUNT = 1 # Number of replica to run the custom training job.
TRAINING_MACHINE_TYPE = (
"n1-standard-4" # Type of machine to run the custom training job.
)
TRAINING_ACCELERATOR_TYPE = "ACCELERATOR_TYPE_UNSPECIFIED" # Type of accelerators to run the custom training job.
TRAINING_ACCELERATOR_COUNT = 0 # Number of accelerators for the custom training job.
Explanation: Create the Trainer to train the RL policy
Create the Trainer component to train a RL policy on the training dataset, and then submit a remote custom training job to Vertex AI. This component trains a policy using the TF-Agents LinUCB agent on the MovieLens simulation dataset, and saves the trained policy as a SavedModel.
The Trainer component source code is in src/trainer/trainer_component.py. You use additional Vertex AI platform code in pipeline construction to submit the training code defined in Trainer as a custom training job to Vertex AI. (The additional code is similar to what kfp.v2.google.experimental.run_as_aiplatform_custom_job does. You can find an example notebook here for how to use that first-party Trainer component.)
The Trainer performs off-policy training, where you train a policy on a static set of pre-collected data records containing information including observation, action and reward. For a data record, the policy in training might not output the same action given the observation in that data record.
If you're interested in pipeline metrics, read about KFP Pipeline Metrics here.
End of explanation
! python3 -m unittest src.trainer.test_trainer_component
Explanation: Run unit tests on the Trainer component
End of explanation
# Deployer parameters
TRAINED_POLICY_DISPLAY_NAME = (
"movielens-trained-policy" # Display name of the uploaded and deployed policy.
)
TRAFFIC_SPLIT = {"0": 100}
ENDPOINT_DISPLAY_NAME = "movielens-endpoint" # Display name of the prediction endpoint.
ENDPOINT_MACHINE_TYPE = "n1-standard-4" # Type of machine of the prediction endpoint.
ENDPOINT_REPLICA_COUNT = 1 # Number of replicas of the prediction endpoint.
ENDPOINT_ACCELERATOR_TYPE = "ACCELERATOR_TYPE_UNSPECIFIED" # Type of accelerators to run the custom training job.
ENDPOINT_ACCELERATOR_COUNT = 0 # Number of accelerators for the custom training job.
Explanation: Create the Deployer to deploy the trained policy to a Vertex AI endpoint
Use google_cloud_pipeline_components.aiplatform components during pipeline construction to:
1. Upload the trained policy
2. Create a Vertex AI endpoint
3. Deploy the uploaded trained policy to the endpoint
These 3 components formulate the Deployer. They support flexible configurations; for instance, if you want to set up traffic splitting for the endpoint to run A/B testing, you may pass in your configurations to google_cloud_pipeline_components.aiplatform.ModelDeployOp.
End of explanation
# Prediction container parameters
PREDICTION_CONTAINER = "prediction-container" # Name of the container image.
PREDICTION_CONTAINER_DIR = "src/prediction_container"
Explanation: Create a custom prediction container using Cloud Build
Before setting up the Deployer, define and build a custom prediction container that serves predictions using the trained policy. The source code, Cloud Build YAML configuration file and Dockerfile are in src/prediction_container.
This prediction container is the serving container for the deployed, trained policy. See a more detailed guide on building prediction custom containers here.
End of explanation
cloudbuild_yaml = steps:
- name: "gcr.io/kaniko-project/executor:latest"
args: ["--destination=gcr.io/{PROJECT_ID}/{PREDICTION_CONTAINER}:latest",
"--cache=true",
"--cache-ttl=99h"]
env: ["AIP_STORAGE_URI={ARTIFACTS_DIR}",
"PROJECT_ID={PROJECT_ID}",
"LOGGER_PUBSUB_TOPIC={LOGGER_PUBSUB_TOPIC}"]
options:
machineType: "E2_HIGHCPU_8"
.format(
PROJECT_ID=PROJECT_ID,
PREDICTION_CONTAINER=PREDICTION_CONTAINER,
ARTIFACTS_DIR=TRAINING_ARTIFACTS_DIR,
LOGGER_PUBSUB_TOPIC=LOGGER_PUBSUB_TOPIC,
)
with open(f"{PREDICTION_CONTAINER_DIR}/cloudbuild.yaml", "w") as fp:
fp.write(cloudbuild_yaml)
Explanation: Create a Cloud Build YAML file using Kaniko build
Note: For this application, you are recommended to use E2_HIGHCPU_8 or other high resouce machine configurations instead of the standard machine type listed here to prevent out-of-memory errors.
End of explanation
! python3 -m unittest src.prediction_container.test_main
Explanation: Run unit tests on the prediction code
End of explanation
! gcloud builds submit --config $PREDICTION_CONTAINER_DIR/cloudbuild.yaml $PREDICTION_CONTAINER_DIR
Explanation: Build custom prediction container
End of explanation
from google_cloud_pipeline_components.experimental.custom_job import utils
from kfp.components import load_component_from_url
generate_op = load_component_from_url(
"https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/62a2a7611499490b4b04d731d48a7ba87c2d636f/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/src/generator/component.yaml"
)
ingest_op = load_component_from_url(
"https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/62a2a7611499490b4b04d731d48a7ba87c2d636f/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/src/ingester/component.yaml"
)
train_op = load_component_from_url(
"https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/62a2a7611499490b4b04d731d48a7ba87c2d636f/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/src/trainer/component.yaml"
)
@dsl.pipeline(pipeline_root=PIPELINE_ROOT, name=f"{PIPELINE_NAME}-startup")
def pipeline(
# Pipeline configs
project_id: str,
raw_data_path: str,
training_artifacts_dir: str,
# BigQuery configs
bigquery_dataset_id: str,
bigquery_location: str,
bigquery_table_id: str,
bigquery_max_rows: int = 10000,
# TF-Agents RL configs
batch_size: int = 8,
rank_k: int = 20,
num_actions: int = 20,
driver_steps: int = 3,
num_epochs: int = 5,
tikhonov_weight: float = 0.01,
agent_alpha: float = 10,
) -> None:
Authors a RL pipeline for MovieLens movie recommendation system.
Integrates the Generator, Ingester, Trainer and Deployer components. This
pipeline generates initial training data with a random policy and runs once
as the initiation of the system.
Args:
project_id: GCP project ID. This is required because otherwise the BigQuery
client will use the ID of the tenant GCP project created as a result of
KFP, which doesn't have proper access to BigQuery.
raw_data_path: Path to MovieLens 100K's "u.data" file.
training_artifacts_dir: Path to store the Trainer artifacts (trained policy).
bigquery_dataset: A string of the BigQuery dataset ID in the format of
"project.dataset".
bigquery_location: A string of the BigQuery dataset location.
bigquery_table_id: A string of the BigQuery table ID in the format of
"project.dataset.table".
bigquery_max_rows: Optional; maximum number of rows to ingest.
batch_size: Optional; batch size of environment generated quantities eg.
rewards.
rank_k: Optional; rank for matrix factorization in the MovieLens environment;
also the observation dimension.
num_actions: Optional; number of actions (movie items) to choose from.
driver_steps: Optional; number of steps to run per batch.
num_epochs: Optional; number of training epochs.
tikhonov_weight: Optional; LinUCB Tikhonov regularization weight of the
Trainer.
agent_alpha: Optional; LinUCB exploration parameter that multiplies the
confidence intervals of the Trainer.
# Run the Generator component.
generate_task = generate_op(
project_id=project_id,
raw_data_path=raw_data_path,
batch_size=batch_size,
rank_k=rank_k,
num_actions=num_actions,
driver_steps=driver_steps,
bigquery_tmp_file=BIGQUERY_TMP_FILE,
bigquery_dataset_id=bigquery_dataset_id,
bigquery_location=bigquery_location,
bigquery_table_id=bigquery_table_id,
)
# Run the Ingester component.
ingest_task = ingest_op(
project_id=project_id,
bigquery_table_id=generate_task.outputs["bigquery_table_id"],
bigquery_max_rows=bigquery_max_rows,
tfrecord_file=TFRECORD_FILE,
)
# Run the Trainer component and submit custom job to Vertex AI.
# Convert the train_op component into a Vertex AI Custom Job pre-built component
custom_job_training_op = utils.create_custom_training_job_op_from_component(
component_spec=train_op,
replica_count=TRAINING_REPLICA_COUNT,
machine_type=TRAINING_MACHINE_TYPE,
accelerator_type=TRAINING_ACCELERATOR_TYPE,
accelerator_count=TRAINING_ACCELERATOR_COUNT,
)
train_task = custom_job_training_op(
training_artifacts_dir=training_artifacts_dir,
tfrecord_file=ingest_task.outputs["tfrecord_file"],
num_epochs=num_epochs,
rank_k=rank_k,
num_actions=num_actions,
tikhonov_weight=tikhonov_weight,
agent_alpha=agent_alpha,
project=PROJECT_ID,
location=REGION,
)
# Run the Deployer components.
# Upload the trained policy as a model.
model_upload_op = gcc_aip.ModelUploadOp(
project=project_id,
display_name=TRAINED_POLICY_DISPLAY_NAME,
artifact_uri=train_task.outputs["training_artifacts_dir"],
serving_container_image_uri=f"gcr.io/{PROJECT_ID}/{PREDICTION_CONTAINER}:latest",
)
# Create a Vertex AI endpoint. (This operation can occur in parallel with
# the Generator, Ingester, Trainer components.)
endpoint_create_op = gcc_aip.EndpointCreateOp(
project=project_id, display_name=ENDPOINT_DISPLAY_NAME
)
# Deploy the uploaded, trained policy to the created endpoint. (This operation
# has to occur after both model uploading and endpoint creation complete.)
gcc_aip.ModelDeployOp(
endpoint=endpoint_create_op.outputs["endpoint"],
model=model_upload_op.outputs["model"],
deployed_model_display_name=TRAINED_POLICY_DISPLAY_NAME,
traffic_split=TRAFFIC_SPLIT,
dedicated_resources_machine_type=ENDPOINT_MACHINE_TYPE,
dedicated_resources_accelerator_type=ENDPOINT_ACCELERATOR_TYPE,
dedicated_resources_accelerator_count=ENDPOINT_ACCELERATOR_COUNT,
dedicated_resources_min_replica_count=ENDPOINT_REPLICA_COUNT,
)
# Compile the authored pipeline.
compiler.Compiler().compile(pipeline_func=pipeline, package_path=PIPELINE_SPEC_PATH)
# Create a pipeline run job.
job = aiplatform.PipelineJob(
display_name=f"{PIPELINE_NAME}-startup",
template_path=PIPELINE_SPEC_PATH,
pipeline_root=PIPELINE_ROOT,
parameter_values={
# Pipeline configs
"project_id": PROJECT_ID,
"raw_data_path": RAW_DATA_PATH,
"training_artifacts_dir": TRAINING_ARTIFACTS_DIR,
# BigQuery configs
"bigquery_dataset_id": BIGQUERY_DATASET_ID,
"bigquery_location": BIGQUERY_LOCATION,
"bigquery_table_id": BIGQUERY_TABLE_ID,
},
enable_caching=ENABLE_CACHING,
)
job.run()
Explanation: Author and run the RL pipeline
You author the pipeline using custom KFP components built from the previous section, and create a pipeline run using Vertex Pipelines. You can read more about whether to enable execution caching here. You can also specifically configure the worker pool spec for training if for instance you want to train at scale and/or at a higher speed; you can adjust the replica count, machine type, accelerator type and count, and many other specifications.
Here, you build a "startup" pipeline that generates randomly sampled training data (with the Generator) as the first step. This pipeline runs only once.
End of explanation
# Simulator parameters
SIMULATOR_PUBSUB_TOPIC = (
"simulator-pubsub-topic" # Pub/Sub topic name for the Simulator.
)
SIMULATOR_CLOUD_FUNCTION = (
"simulator-cloud-function" # Cloud Functions name for the Simulator.
)
SIMULATOR_SCHEDULER_JOB = (
"simulator-scheduler-job" # Cloud Scheduler cron job name for the Simulator.
)
SIMULATOR_SCHEDULE = "*/5 * * * *" # Cloud Scheduler cron job schedule for the Simulator. Eg. "*/5 * * * *" means every 5 mins.
SIMULATOR_SCHEDULER_MESSAGE = (
"simulator-message" # Cloud Scheduler message for the Simulator.
)
# TF-Agents RL configs
BATCH_SIZE = 8
RANK_K = 20
NUM_ACTIONS = 20
Explanation: Create the Simulator to send simulated MovieLens prediction requests
Create the Simulator to obtain observations from the MovieLens simulation environment, formats them, and sends prediction requests to the Vertex AI endpoint.
The workflow is: Cloud Scheduler --> Pub/Sub --> Cloud Functions --> Endpoint
In production, this Simulator logic can be modified to that of gathering real-world input features as observations, getting prediction results from the endpoint and communicating those results to real-world users.
The Simulator source code is src/simulator/main.py.
End of explanation
! python3 -m unittest src.simulator.test_main
Explanation: Run unit tests on the Simulator
End of explanation
! gcloud pubsub topics create $SIMULATOR_PUBSUB_TOPIC
Explanation: Create a Pub/Sub topic
Read more about creating Pub/Sub topics here
End of explanation
scheduler_job_args = " ".join(
[
SIMULATOR_SCHEDULER_JOB,
f"--schedule='{SIMULATOR_SCHEDULE}'",
f"--topic={SIMULATOR_PUBSUB_TOPIC}",
f"--message-body={SIMULATOR_SCHEDULER_MESSAGE}",
]
)
! echo $scheduler_job_args
! gcloud scheduler jobs create pubsub $scheduler_job_args
Explanation: Set up a recurrent Cloud Scheduler job for the Pub/Sub topic
Read more about possible ways to create cron jobs here.
Read about the cron job schedule format here.
End of explanation
endpoints = ! gcloud ai endpoints list \
--region=$REGION \
--filter=display_name=$ENDPOINT_DISPLAY_NAME
print("\n".join(endpoints), "\n")
ENDPOINT_ID = endpoints[2].split(" ")[0]
print(f"ENDPOINT_ID={ENDPOINT_ID}")
ENV_VARS = ",".join(
[
f"PROJECT_ID={PROJECT_ID}",
f"REGION={REGION}",
f"ENDPOINT_ID={ENDPOINT_ID}",
f"RAW_DATA_PATH={RAW_DATA_PATH}",
f"BATCH_SIZE={BATCH_SIZE}",
f"RANK_K={RANK_K}",
f"NUM_ACTIONS={NUM_ACTIONS}",
]
)
! echo $ENV_VARS
! gcloud functions deploy $SIMULATOR_CLOUD_FUNCTION \
--region=$REGION \
--trigger-topic=$SIMULATOR_PUBSUB_TOPIC \
--runtime=python37 \
--memory=512MB \
--timeout=200s \
--source=src/simulator \
--entry-point=simulate \
--stage-bucket=$BUCKET_NAME \
--update-env-vars=$ENV_VARS
Explanation: Define the Simulator logic in a Cloud Function to be triggered periodically, and deploy this Function
Specify dependencies of the Function in src/simulator/requirements.txt.
Read more about the available configurable arguments for deploying a Function here. For instance, based on the complexity of your Function, you may want to adjust its memory and timeout.
Note that the environment variables in ENV_VARS should be comma-separated; there should not be additional spaces, or other characters in between. Read more about setting/updating/deleting environment variables here.
Read more about sending predictions to Vertex endpoints here.
End of explanation
! python3 -m unittest src.logger.test_main
Explanation: Create the Logger to asynchronously log prediction inputs and results
Create the Logger to get environment feedback as rewards from the MovieLens simulation environment based on prediction observations and predicted actions, formulate trajectory data, and store said data back to BigQuery. The Logger closes the RL feedback loop from prediction to training data, and allows re-training of the policy on new training data.
The Logger is triggered by a hook in the prediction code. At each prediction request, the prediction code messages a Pub/Sub topic, which triggers the Logger code.
The workflow is: prediction container code (at prediction request) --> Pub/Sub --> Cloud Functions (logging predictions back to BigQuery)
In production, this Logger logic can be modified to that of gathering real-world feedback (rewards) based on observations and predicted actions.
The Logger source code is src/logger/main.py.
Run unit tests on the Logger
End of explanation
! gcloud pubsub topics create $LOGGER_PUBSUB_TOPIC
Explanation: Create a Pub/Sub topic
Read more about creating Pub/Sub topics here
End of explanation
ENV_VARS = ",".join(
[
f"PROJECT_ID={PROJECT_ID}",
f"RAW_DATA_PATH={RAW_DATA_PATH}",
f"BATCH_SIZE={BATCH_SIZE}",
f"RANK_K={RANK_K}",
f"NUM_ACTIONS={NUM_ACTIONS}",
f"BIGQUERY_TMP_FILE={BIGQUERY_TMP_FILE}",
f"BIGQUERY_DATASET_ID={BIGQUERY_DATASET_ID}",
f"BIGQUERY_LOCATION={BIGQUERY_LOCATION}",
f"BIGQUERY_TABLE_ID={BIGQUERY_TABLE_ID}",
]
)
! echo $ENV_VARS
! gcloud functions deploy $LOGGER_CLOUD_FUNCTION \
--region=$REGION \
--trigger-topic=$LOGGER_PUBSUB_TOPIC \
--runtime=python37 \
--memory=512MB \
--timeout=200s \
--source=src/logger \
--entry-point=log \
--stage-bucket=$BUCKET_NAME \
--update-env-vars=$ENV_VARS
Explanation: Define the Logger logic in a Cloud Function to be triggered by a Pub/Sub topic, which is triggered by the prediction code at each prediction request.
Specify dependencies of the Function in src/logger/requirements.txt.
Read more about the available configurable arguments for deploying a Function here. For instance, based on the complexity of your Function, you may want to adjust its memory and timeout.
Note that the environment variables in ENV_VARS should be comma-separated; there should not be additional spaces, or other characters in between. Read more about setting/updating/deleting environment variables here.
End of explanation
TRIGGER_SCHEDULE = "*/30 * * * *" # Schedule to trigger the pipeline. Eg. "*/30 * * * *" means every 30 mins.
ingest_op = load_component_from_url(
"https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/62a2a7611499490b4b04d731d48a7ba87c2d636f/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/src/ingester/component.yaml"
)
train_op = load_component_from_url(
"https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/62a2a7611499490b4b04d731d48a7ba87c2d636f/community-content/tf_agents_bandits_movie_recommendation_with_kfp_and_vertex_sdk/mlops_pipeline_tf_agents_bandits_movie_recommendation/src/trainer/component.yaml"
)
@dsl.pipeline(pipeline_root=PIPELINE_ROOT, name=f"{PIPELINE_NAME}-retraining")
def pipeline(
# Pipeline configs
project_id: str,
training_artifacts_dir: str,
# BigQuery configs
bigquery_table_id: str,
bigquery_max_rows: int = 10000,
# TF-Agents RL configs
rank_k: int = 20,
num_actions: int = 20,
num_epochs: int = 5,
tikhonov_weight: float = 0.01,
agent_alpha: float = 10,
) -> None:
Authors a re-training pipeline for MovieLens movie recommendation system.
Integrates the Ingester, Trainer and Deployer components.
Args:
project_id: GCP project ID. This is required because otherwise the BigQuery
client will use the ID of the tenant GCP project created as a result of
KFP, which doesn't have proper access to BigQuery.
training_artifacts_dir: Path to store the Trainer artifacts (trained policy).
bigquery_table_id: A string of the BigQuery table ID in the format of
"project.dataset.table".
bigquery_max_rows: Optional; maximum number of rows to ingest.
rank_k: Optional; rank for matrix factorization in the MovieLens environment;
also the observation dimension.
num_actions: Optional; number of actions (movie items) to choose from.
num_epochs: Optional; number of training epochs.
tikhonov_weight: Optional; LinUCB Tikhonov regularization weight of the
Trainer.
agent_alpha: Optional; LinUCB exploration parameter that multiplies the
confidence intervals of the Trainer.
# Run the Ingester component.
ingest_task = ingest_op(
project_id=project_id,
bigquery_table_id=bigquery_table_id,
bigquery_max_rows=bigquery_max_rows,
tfrecord_file=TFRECORD_FILE,
)
# Run the Trainer component and submit custom job to Vertex AI.
# Convert the train_op component into a Vertex AI Custom Job pre-built component
custom_job_training_op = utils.create_custom_training_job_op_from_component(
component_spec=train_op,
replica_count=TRAINING_REPLICA_COUNT,
machine_type=TRAINING_MACHINE_TYPE,
accelerator_type=TRAINING_ACCELERATOR_TYPE,
accelerator_count=TRAINING_ACCELERATOR_COUNT,
)
train_task = custom_job_training_op(
training_artifacts_dir=training_artifacts_dir,
tfrecord_file=ingest_task.outputs["tfrecord_file"],
num_epochs=num_epochs,
rank_k=rank_k,
num_actions=num_actions,
tikhonov_weight=tikhonov_weight,
agent_alpha=agent_alpha,
project=PROJECT_ID,
location=REGION,
)
# Run the Deployer components.
# Upload the trained policy as a model.
model_upload_op = gcc_aip.ModelUploadOp(
project=project_id,
display_name=TRAINED_POLICY_DISPLAY_NAME,
artifact_uri=train_task.outputs["training_artifacts_dir"],
serving_container_image_uri=f"gcr.io/{PROJECT_ID}/{PREDICTION_CONTAINER}:latest",
)
# Create a Vertex AI endpoint. (This operation can occur in parallel with
# the Generator, Ingester, Trainer components.)
endpoint_create_op = gcc_aip.EndpointCreateOp(
project=project_id, display_name=ENDPOINT_DISPLAY_NAME
)
# Deploy the uploaded, trained policy to the created endpoint. (This operation
# has to occur after both model uploading and endpoint creation complete.)
gcc_aip.ModelDeployOp(
endpoint=endpoint_create_op.outputs["endpoint"],
model=model_upload_op.outputs["model"],
deployed_model_display_name=TRAINED_POLICY_DISPLAY_NAME,
dedicated_resources_machine_type=ENDPOINT_MACHINE_TYPE,
dedicated_resources_accelerator_type=ENDPOINT_ACCELERATOR_TYPE,
dedicated_resources_accelerator_count=ENDPOINT_ACCELERATOR_COUNT,
dedicated_resources_min_replica_count=ENDPOINT_REPLICA_COUNT,
)
# Compile the authored pipeline.
compiler.Compiler().compile(pipeline_func=pipeline, package_path=PIPELINE_SPEC_PATH)
# Createa Vertex AI client.
api_client = AIPlatformClient(project_id=PROJECT_ID, region=REGION)
# Schedule a recurring pipeline.
response = api_client.create_schedule_from_job_spec(
job_spec_path=PIPELINE_SPEC_PATH,
schedule=TRIGGER_SCHEDULE,
parameter_values={
# Pipeline configs
"project_id": PROJECT_ID,
"training_artifacts_dir": TRAINING_ARTIFACTS_DIR,
# BigQuery config
"bigquery_table_id": BIGQUERY_TABLE_ID,
},
)
response["name"]
Explanation: Create the Trigger to trigger re-training
Create the Trigger to recurrently re-run the pipeline to re-train the policy on new training data, using kfp.v2.google.client.AIPlatformClient.create_schedule_from_job_spec. You create a pipeline for orchestration on Vertex Pipelines, and a Cloud Scheduler job that recurrently triggers the pipeline. The method also automatically creates a Cloud Function that acts as an intermediary between the Scheduler and Pipelines. You can find the source code here.
When the Simulator sends prediction requests to the endpoint, the Logger is triggered by the hook in the prediction code to log prediction results to BigQuery, as new training data. As this pipeline has a recurrent schedule, it utlizes the new training data in training a new policy, therefore closing the feedback loop. Theoretically speaking, if you set the pipeline scheduler to be infinitely frequent, then you would be approaching real-time, continuous training.
End of explanation
# Delete endpoint resource.
! gcloud ai endpoints delete $ENDPOINT_ID --quiet --region $REGION
# Delete Pub/Sub topics.
! gcloud pubsub topics delete $SIMULATOR_PUBSUB_TOPIC --quiet
! gcloud pubsub topics delete $LOGGER_PUBSUB_TOPIC --quiet
# Delete Cloud Functions.
! gcloud functions delete $SIMULATOR_CLOUD_FUNCTION --quiet
! gcloud functions delete $LOGGER_CLOUD_FUNCTION --quiet
# Delete Scheduler job.
! gcloud scheduler jobs delete $SIMULATOR_SCHEDULER_JOB --quiet
# Delete Cloud Storage objects that were created.
! gsutil -m rm -r $PIPELINE_ROOT
! gsutil -m rm -r $TRAINING_ARTIFACTS_DIR
Explanation: Cleaning up
To clean up all Google Cloud resources used in this project, you can delete the Google Cloud
project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial (you also need to clean up other resources that are difficult to delete here, such as the all/partial of data in BigQuery, the recurring pipeline and its Scheduler job, the uploaded policy/model, etc.):
End of explanation |
7,980 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HMTK Geological Tools Demonstration
This notepad demonstrates the use of the HMTK geological tools for preparing fault source models for input into OpenQuake
Construction of the Geological Input File
An active fault model input file contains two sections
Step1: The following examples refer to a fault with the following properties
Step2: Anderson & Luco (Arbitrary)
This describes a set of distributons where the maximum magnitude is assumed to rupture the whole fault surface
Step3: Anderson & Luco (Area - MMax)
This describes a set of distributons where the maximum rupture extent is limited to only part of the fault surface
Step4: Characteristic Earthquake
The following example illustrates a "Characteristic" Model, represented by a Truncated Gaussian Distribution
Step5: Youngs & Coppersmith (1985) Models
The following describes the recurrence from two distributions presented by Youngs & Coppersmith (1985)
Step7: Epistemic Uncertainty Examples
This example considers the fault defined at the top of the page. This fault defines two values of slip rate and two different magnitude frequency distributions
Step8: Example 1 - Full Enumeration
In this example each individual MFD for each branch is determined. In the resulting file the fault is duplicated n_branches number of times, with the
corresponding MFD multiplied by the end-branch weight
Step9: Example 2 | Python Code:
#Import tools
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from hmtk.plotting.faults.geology_mfd_plot import plot_recurrence_models
from openquake.hazardlib.scalerel.wc1994 import WC1994 # In all the following examples the Wells & Coppersmith (1994) Scaling Relation is Used
Explanation: HMTK Geological Tools Demonstration
This notepad demonstrates the use of the HMTK geological tools for preparing fault source models for input into OpenQuake
Construction of the Geological Input File
An active fault model input file contains two sections:
1) A tectonic regionalisation - this can provide a container for a set of properties that may be assigned to multiple faults by virtue of a common tectonic region
2) A set of active faults
Tectonic Regionalisation Representation in the Fault Source File
In the tectonic regionalisation information each of the three properties can be represented according to a set of weighted values.
For example, in the case below faults in an arbitrarily named tectonic region (called here "GEM Region 1") will share the same set
of magnitude scaling relations and shear moduli, unless over-written by the specific fault. Those faults assigned to "GEM Region 2"
will have the magnitude scaling relation fixed as WC1994 and the shear modulus of 30 GPa
Active Fault Model
A set of active faults will be defined with a common ID and name.
An active fault set containing a single fault is shown below:
Fault Geometry Representations - Example 1: Simple Fault
Fault Geometry Representations - Example 2: Complex Fault
Rupture Properties
The rupture requires characterisation of the rake (using the Aki & Richards 2002 convention), the slip-type, the slip completeness factor
(an integer constraining the quality of the slip information with 1 being the hights quality), the range of slip values and their
corresponding weights, and the aseismic slip coefficient (the proportion of slip released aseismically, 1.0 - coupling coefficient)
The Magnitude Frequency Distributions
End of explanation
# Set up fault parameters
slip = 10.0 # Slip rate in mm/yr
# Area = along-strike length (km) * down-dip with (km)
area = 100.0 * 20.0
# Rake = 0.
rake = 0.
# Magnitude Scaling Relation
msr = WC1994()
Explanation: The following examples refer to a fault with the following properties:
Length (Along-strike) = 100 km,
Width (Down-Dip) = 20 km,
Slip = 10.0 mm/yr,
Rake = 0. (Strike Slip),
Magnitude Scaling Relation = Wells & Coppersmith (1994),
Shear Modulus = 30.0 GPa
End of explanation
#Magnitude Frequency Distribution Example
anderson_luco_config1 = {'Model_Name': 'AndersonLucoArbitrary',
'Model_Type': 'First',
'Model_Weight': 1.0, # Weight is a required key - normally weights should sum to 1.0 - current example is simply illustrative!
'MFD_spacing': 0.1,
'Maximum_Magnitude': None,
'Minimum_Magnitude': 4.5,
'b_value': [0.8, 0.05]}
anderson_luco_config2 = {'Model_Name': 'AndersonLucoArbitrary',
'Model_Type': 'Second',
'Model_Weight': 1.0,
'MFD_spacing': 0.1,
'Maximum_Magnitude': None,
'Minimum_Magnitude': 4.5,
'b_value': [0.8, 0.05]}
anderson_luco_config3 = {'Model_Name': 'AndersonLucoArbitrary',
'Model_Type': 'Third',
'Model_Weight': 1.0,
'MFD_spacing': 0.1,
'Maximum_Magnitude': None,
'Minimum_Magnitude': 4.5,
'b_value': [0.8, 0.05]}
# Create a list of the configurations
anderson_luco_arb = [anderson_luco_config1, anderson_luco_config2, anderson_luco_config3]
# View the corresponding magnitude recurrence model
plot_recurrence_models(anderson_luco_arb, area, slip, msr, rake, msr_sigma=0.0)
Explanation: Anderson & Luco (Arbitrary)
This describes a set of distributons where the maximum magnitude is assumed to rupture the whole fault surface
End of explanation
anderson_luco_config1 = {'Model_Name': 'AndersonLucoAreaMmax',
'Model_Type': 'First',
'Model_Weight': 1.0, # Weight is a required key - normally weights should sum to 1.0 - current example is simply illustrative!
'MFD_spacing': 0.1,
'Maximum_Magnitude': None,
'Minimum_Magnitude': 4.5,
'b_value': [0.8, 0.05]}
anderson_luco_config2 = {'Model_Name': 'AndersonLucoAreaMmax',
'Model_Type': 'Second',
'Model_Weight': 1.0,
'MFD_spacing': 0.1,
'Maximum_Magnitude': None,
'Minimum_Magnitude': 4.5,
'b_value': [0.8, 0.05]}
anderson_luco_config3 = {'Model_Name': 'AndersonLucoAreaMmax',
'Model_Type': 'Third',
'Model_Weight': 1.0,
'MFD_spacing': 0.1,
'Maximum_Magnitude': None,
'Minimum_Magnitude': 4.5,
'b_value': [0.8, 0.05]}
# For these models a displacement to length ratio is needed
disp_length_ratio = 1.25E-5
# Create a list of the configurations
anderson_luco_area_mmax = [anderson_luco_config1, anderson_luco_config2, anderson_luco_config3]
# View the corresponding magnitude recurrence model
plot_recurrence_models(anderson_luco_area_mmax, area, slip, msr, rake, msr_sigma=0.0)
Explanation: Anderson & Luco (Area - MMax)
This describes a set of distributons where the maximum rupture extent is limited to only part of the fault surface
End of explanation
characteristic = [{'Model_Name': 'Characteristic',
'MFD_spacing': 0.05,
'Model_Weight': 1.0,
'Maximum_Magnitude': None,
'Sigma': 0.15, # Standard Deviation of Distribution (in Magnitude Units) - omit for fixed value
'Lower_Bound': -3.0, # Bounds of the distribution correspond to the number of sigma for truncation
'Upper_Bound': 3.0}]
# View the corresponding magnitude recurrence model
plot_recurrence_models(characteristic, area, slip, msr, rake, msr_sigma=0.0)
Explanation: Characteristic Earthquake
The following example illustrates a "Characteristic" Model, represented by a Truncated Gaussian Distribution
End of explanation
exponential = {'Model_Name': 'YoungsCoppersmithExponential',
'MFD_spacing': 0.1,
'Maximum_Magnitude': None,
'Maximum_Magnitude_Uncertainty': None,
'Minimum_Magnitude': 5.0,
'Model_Weight': 1.0,
'b_value': [0.8, 0.1]}
hybrid = {'Model_Name': 'YoungsCoppersmithCharacteristic',
'MFD_spacing': 0.1,
'Maximum_Magnitude': None,
'Maximum_Magnitude_Uncertainty': None,
'Minimum_Magnitude': 5.0,
'Model_Weight': 1.0,
'b_value': [0.8, 0.1],
'delta_m': None}
youngs_coppersmith = [exponential, hybrid]
# View the corresponding magnitude recurrence model
plot_recurrence_models(youngs_coppersmith, area, slip, msr, rake, msr_sigma=0.0)
Explanation: Youngs & Coppersmith (1985) Models
The following describes the recurrence from two distributions presented by Youngs & Coppersmith (1985): 1) Exponential Distribution, 2) Hybrid Exponential-Characteristic Distribution
End of explanation
def show_file_contents(filename):
Shows the file contents
fid = open(filename, 'r')
for row in fid.readlines():
print row
fid.close()
input_file = 'input_data/simple_fault_example_4branch.yml'
show_file_contents(input_file)
Explanation: Epistemic Uncertainty Examples
This example considers the fault defined at the top of the page. This fault defines two values of slip rate and two different magnitude frequency distributions
End of explanation
# Import the Parser
from hmtk.parsers.faults.fault_yaml_parser import FaultYmltoSource
# Fault mesh discretization step
mesh_spacing = 1.0 # (km)
# Read in the fault model
reader = FaultYmltoSource(input_file)
fault_model, tectonic_region = reader.read_file(mesh_spacing)
# Construct the fault source model (this is really running the MFD calculation code)
fault_model.build_fault_model()
# Write to an output NRML file
output_file_1 = 'output_data/fault_example_enumerated.xml'
fault_model.source_model.serialise_to_nrml(output_file_1)
show_file_contents(output_file_1)
Explanation: Example 1 - Full Enumeration
In this example each individual MFD for each branch is determined. In the resulting file the fault is duplicated n_branches number of times, with the
corresponding MFD multiplied by the end-branch weight
End of explanation
# Read in the fault model
reader = FaultYmltoSource(input_file)
fault_model, tectonic_region = reader.read_file(mesh_spacing)
# Scaling relation for export
output_msr = WC1994()
# Construct the fault source model - collapsing the branches
fault_model.build_fault_model(collapse=True, rendered_msr=output_msr)
# Write to an output NRML file
output_file_2 = 'output_data/fault_example_collapsed.xml'
fault_model.source_model.serialise_to_nrml(output_file_2)
show_file_contents(output_file_2)
Explanation: Example 2: Collapsed Branches
In the following example we implement the same model, this time collapsing the branched. This means that the MFD is discretised and the incremental rate
in each magnitude bin is the weighted sum of the rates in that bin from all the end branches of the logic tree.
When collapsing the branches, however, it is necessary to define a single Magnitude Scaling Relation that will need to be assigned to the fault for
use in OpenQuake.
End of explanation |
7,981 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Sprachübergreifende-Textalignierung" data-toc-modified-id="Sprachübergreifende-Textalignierung-1"><span class="toc-item-num">1 </span>Sprachübergreifende Textalignierung</a></div><div class="lev1 toc-item"><a href="#Manuales-(sprachübergreifende-Alignierung)" data-toc-modified-id="Manuales-(sprachübergreifende-Alignierung)-2"><span class="toc-item-num">2 </span>Manuales (sprachübergreifende Alignierung)</a></div><div class="lev2 toc-item"><a href="#LXML" data-toc-modified-id="LXML-21"><span class="toc-item-num">2.1 </span>LXML</a></div>
# Sprachübergreifende Textalignierung
Blockseminar Studiengang "Digitale Methodik in den Geistes- und Kulturwissenschaften" (18.1.2020, 8.2.2020, 15.2.2020)
Step1: Manuales (sprachübergreifende Alignierung)
Step2: LXML
Step3: Save sentences as plaintext files. | Python Code:
import os
in_dir = "./data/constitutions/"
# we create a dictionary with our constitutions:
sources = {}
for file in sorted(os.listdir(in_dir)):
key = os.path.basename(file).split(os.extsep)[0]
with open(in_dir + '/' + file, encoding="utf-8") as f:
sources[key] = f.read()
# and a list of available constitutions for quick lookup:
constitutions = list(sources.keys())
print ("{} files read:".format(len(constitutions)))
print (constitutions)
from nltk import tokenize
# nltk.download('punkt')
sentences = {}
nos = {}
for c in constitutions:
t = tokenize.sent_tokenize(sources[c])
nos[c] = len(t)
for i, s in enumerate(t):
sentences[c + '_' + str(i)] = s
boundary = len(sentences) - nos['1948_-_BU_-_Burma_-_constitution_of_burma']
print("Corpus has {} sentences.".format(len(sentences)))
print("1948_-_BU_-_Burma_-_constitution_of_burma has {}.\n".format(nos['1948_-_BU_-_Burma_-_constitution_of_burma']))
print("Its first 3 sentences are:\n{}".format([sentences['1948_-_BU_-_Burma_-_constitution_of_burma_0'],\
sentences['1948_-_BU_-_Burma_-_constitution_of_burma_1'],\
sentences['1948_-_BU_-_Burma_-_constitution_of_burma_2']]))
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(analyzer='word', strip_accents='unicode', stop_words=["the", "of", "and"])
dfm = vectorizer.fit_transform(sentences.values())
print(dfm.shape)
print(type(dfm))
print(dfm.toarray())
from sklearn.metrics.pairwise import cosine_similarity
target = dfm[boundary:]
sources = dfm[:boundary,]
print(target.shape)
print(sources.shape)
simils = cosine_similarity(target, sources)
print(simils.shape)
import numpy as np
np.argmax(simils, axis=1)
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Sprachübergreifende-Textalignierung" data-toc-modified-id="Sprachübergreifende-Textalignierung-1"><span class="toc-item-num">1 </span>Sprachübergreifende Textalignierung</a></div><div class="lev1 toc-item"><a href="#Manuales-(sprachübergreifende-Alignierung)" data-toc-modified-id="Manuales-(sprachübergreifende-Alignierung)-2"><span class="toc-item-num">2 </span>Manuales (sprachübergreifende Alignierung)</a></div><div class="lev2 toc-item"><a href="#LXML" data-toc-modified-id="LXML-21"><span class="toc-item-num">2.1 </span>LXML</a></div>
# Sprachübergreifende Textalignierung
Blockseminar Studiengang "Digitale Methodik in den Geistes- und Kulturwissenschaften" (18.1.2020, 8.2.2020, 15.2.2020)
End of explanation
import os
in_dir = "./data/manual/"
# we create a dictionary with our manuales:
sources = {}
for file in sorted(os.listdir(in_dir)):
key = os.path.basename(file).split(os.extsep)[0]
with open(in_dir + '/' + file, encoding="utf-8") as f:
sources[key] = f.read()
# and a list of available constitutions for quick lookup:
manuales = list(sources.keys())
print ("{} files read:".format(len(manuales)))
print (manuales)
from nltk import tokenize
# nltk.download('punkt')
sentences = {}
nos = {}
for c in manuales:
t = tokenize.sent_tokenize(sources[c])
nos[c] = len(t)
for i, s in enumerate(t):
sentences[c + '_' + str(i)] = s
print("Corpus has {} sentences.".format(len(sentences)))
print("azp1552_ch17 {}.\n".format(nos['azp1552_ch17']))
print("Its first 3 sentences are:\n{}".format([sentences['azp1552_ch17_2'],\
sentences['azp1552_ch17_3'],\
sentences['azp1552_ch17_4']]))
Explanation: Manuales (sprachübergreifende Alignierung)
End of explanation
import lxml
from lxml import etree
import glob
import re
import os
in_dir = "./data/manual/"
sources = glob.glob(in_dir + '*.xml')
parsed = { os.path.basename(file).split(os.extsep)[0] :
(etree.parse(file))
for file in sorted(sources)
}
manuales = list(parsed.keys())
print (manuales)
nsmap = {"tei": "http://www.tei-c.org/ns/1.0"}
def flatten(element):
t = ""
# Dagger milestones
if element.get("rendition")=="#dagger":
t += "†"
if element.tail:
t += str.replace(element.tail, "\n", " ")
# asterisk milestones (additions in the 1556 ed.) - create temporary marker
elif element.get("rendition")=="#asterisk":
t += "*"
if element.tail:
t += str.replace(element.tail, "\n", " ")
# Unanchored milestones - create temporary marker
elif element.get("rendition")=="#unanchored":
t += "‡"
if element.tail:
t += str.replace(element.tail, "\n", " ")
else:
for c in element.iter("expan"):
flatten(c)
if element.tail:
t += str.replace(element.tail, "\n", " ")
for c in element.iter("corr"):
flatten(c)
if element.tail:
t += str.replace(element.tail, "\n", " ")
if element.text:
t += str.replace(element.text, "\n", " ")
if element.getchildren():
t += " ".join((flatten(child)) for child in element.getchildren())
if element.tail:
t += str.replace(element.tail, "\n", " ")
return t
xp_divs = etree.XPath("(//tei:body/tei:div[@type = 'chapter'][not(@n = '0')])", namespaces = nsmap)
divs = {}
text = {}
for ed in manuales:
t1 = ""
divs[ed] = xp_divs(parsed[ed])
t1 = "".join("++div--" + re.sub('\s+', ' ', '<p>' + flatten(div)) for div in divs[ed])
t2 = re.sub(r'¶', '++break--¶', t1) # where pilcrow signs are
t3 = re.sub(r'([:\.\?\]])\s+([A-Z])(?!([CIJLVX]+|.)?\.)(?![^†‡*]{0,80}[:\.\?\]][^a-z]*[A-Z])(?=.{0,80}[†‡*])',
r'\1 ++break-- \2', t2) # sentences beginning
# with punctuation, whitespace, and a
# capital letter (not immediately followed by
# an abbreviation period)
# and a milestone follows within 80 characters
# (that do not contain a punctuation character)
t4 = re.sub(r'\b([A-Z]{2}\s*[a-z])', r'++break-- \1', t3) # two capital letters
t5 = t4[::-1] # reverse the string
t6 = re.sub(r'([†‡*])(?!.{0,100}--kaerb)', r'\1--kaerb++', t5) # daggers without sentence boundaries, i.e. not covered above
t7 = t6[::-1] # reverse the string
t8 = re.sub(r'‡', '', t7) # Eliminate temporary markers: unanchored milestones
# Concat everything and do a final removal of redundant breaks.
t9 = re.sub(r'\+\+break--\s*\+\+break--', '++break--', " ".join(t8.strip().split()))
t10 = re.sub(r'\+\+break--', r'<milestone type="lera-segment"/>', t9)
t11 = re.sub(r'\+\+div--', r'</div><div type="chapter">', t10)
text[ed] = '<root>' + re.sub(r'&', '&', t11)[6:] + '</div></root>'
print("text['azp1552_ch17'] is:\n{}...".format(text['azp1552_ch17'][:400]))
sentences = {}
nos = {}
for ed in manuales:
sentences[ed] = {}
segments = text[ed].split('<milestone type="lera-segment"/>')
nos[ed] = len(segments)
for i, s in enumerate(segments):
sentences[ed][ed + '_' + str(i)] = s.strip()
print("Corpus has {} sentences.".format(len(sentences)))
print("azp1552_ch17 has {}.\n".format(nos['azp1552_ch17']))
print("Its first 5 sentences are:\n{}".format([sentences['azp1552_ch17']['azp1552_ch17_0'],\
sentences['azp1552_ch17']['azp1552_ch17_1'],\
sentences['azp1552_ch17']['azp1552_ch17_2'],\
sentences['azp1552_ch17']['azp1552_ch17_3'],\
sentences['azp1552_ch17']['azp1552_ch17_4']]))
Explanation: LXML
End of explanation
import csv
for ed in manuales:
with open('./data/manual/' + ed + '_seg.csv', 'w', encoding='utf-8') as csv_file:
writer = csv.writer(csv_file, lineterminator="\n")
for key, value in sentences[ed].items():
writer.writerow([key, value])
Explanation: Save sentences as plaintext files.
End of explanation |
7,982 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to Efficiently Read BigQuery Data from TensorFlow 2.3
Learning Objectives
Build a benchmark model.
Find the breakoff point for Keras.
Training a TensorFlow/Keras model that reads from BigQuery.
Load TensorFlow model into BigQuery.
Introduction
In this notebook, you learn
"How to efficiently read BigQuery data from TensorFlow 2.x"
The example problem is to find credit card fraud from the dataset published in
Step1: Find the breakoff point for Keras
When we do the training in Keras & TensorFlow, we need to find the place to split the dataset and how to weight the imbalanced data.
(BigQuery ML did that for us because we specified 'seq' as the split method and auto_class_weights to be True).
Step2: The time cutoff is 144803 and the Keras model's output bias needs to be set at -6.36
The class weights need to be 289.4 and 0.5
Training a TensorFlow/Keras model that reads from BigQuery
Create the dataset from BigQuery
Step3: Create Keras model
Step4: Load TensorFlow model into BigQuery
Now that we have trained a TensorFlow model off BigQuery data ...
let's load the model into BigQuery and use it for batch prediction!
Step5: Now predict with this model (the reason it's called 'd4' is because the output node of my Keras model was called 'd4').
To get probabilities, etc. we'd have to add the corresponding outputs to the Keras model. | Python Code:
%%bash
# create output dataset
bq mk advdata
%%bigquery
CREATE OR REPLACE MODEL advdata.ulb_fraud_detection
TRANSFORM(
* EXCEPT(Amount),
SAFE.LOG(Amount) AS log_amount
)
OPTIONS(
INPUT_LABEL_COLS=['class'],
AUTO_CLASS_WEIGHTS = TRUE,
DATA_SPLIT_METHOD='seq',
DATA_SPLIT_COL='Time',
MODEL_TYPE='logistic_reg'
) AS
SELECT
*
FROM `bigquery-public-data.ml_datasets.ulb_fraud_detection`
%%bigquery
# TODO
# Use the ML.EVALUATE function to evaluate model metrics.
SELECT * FROM ML.EVALUATE(MODEL advdata.ulb_fraud_detection)
%%bigquery
SELECT predicted_class_probs, Class
# TODO
# The ML.PREDICT function is used to predict outcomes using the model
FROM ML.PREDICT( MODEL advdata.ulb_fraud_detection,
(SELECT * FROM `bigquery-public-data.ml_datasets.ulb_fraud_detection` WHERE Time = 85285.0)
)
Explanation: How to Efficiently Read BigQuery Data from TensorFlow 2.3
Learning Objectives
Build a benchmark model.
Find the breakoff point for Keras.
Training a TensorFlow/Keras model that reads from BigQuery.
Load TensorFlow model into BigQuery.
Introduction
In this notebook, you learn
"How to efficiently read BigQuery data from TensorFlow 2.x"
The example problem is to find credit card fraud from the dataset published in:
<i>
Andrea Dal Pozzolo, Olivier Caelen, Reid A. Johnson and Gianluca Bontempi. Calibrating Probability with Undersampling for Unbalanced Classification. In Symposium on Computational Intelligence and Data Mining (CIDM), IEEE, 2015
</i>
and available in BigQuery at <pre>bigquery-public-data.ml_datasets.ulb_fraud_detection</pre>
Each learning objective will correspond to a #TODO in the student lab notebook -- try to complete that notebook first before reviewing this solution notebook.
Build a benchmark model
In order to compare things, we will do a simple logistic regression in BigQuery ML.
Note that we are using all the columns in the dataset as predictors (except for the Time and Class columns).
The Time column is used to split the dataset 80:20 with the first 80% used for training and the last 20% used for evaluation.
We will also have BigQuery ML automatically balance the weights.
Because the Amount column has a huge range, we take the log of it in preprocessing.
End of explanation
%%bigquery
WITH counts AS (
SELECT
APPROX_QUANTILES(Time, 5)[OFFSET(4)] AS train_cutoff
, COUNTIF(CLASS > 0) AS pos
, COUNTIF(CLASS = 0) AS neg
FROM `bigquery-public-data`.ml_datasets.ulb_fraud_detection
)
SELECT
train_cutoff
, SAFE.LOG(SAFE_DIVIDE(pos,neg)) AS output_bias
, 0.5*SAFE_DIVIDE(pos + neg, pos) AS weight_pos
, 0.5*SAFE_DIVIDE(pos + neg, neg) AS weight_neg
FROM counts # TODO
Explanation: Find the breakoff point for Keras
When we do the training in Keras & TensorFlow, we need to find the place to split the dataset and how to weight the imbalanced data.
(BigQuery ML did that for us because we specified 'seq' as the split method and auto_class_weights to be True).
End of explanation
# import necessary libraries
import tensorflow as tf
from tensorflow.python.framework import dtypes
from tensorflow_io.bigquery import BigQueryClient
from tensorflow_io.bigquery import BigQueryReadSession
def features_and_labels(features):
label = features.pop('Class') # this is what we will train for
return features, label
def read_dataset(client, row_restriction, batch_size=2048):
GCP_PROJECT_ID='qwiklabs-gcp-03-5b2f0816822f' # CHANGE
COL_NAMES = ['Time', 'Amount', 'Class'] + ['V{}'.format(i) for i in range(1,29)]
COL_TYPES = [dtypes.float64, dtypes.float64, dtypes.int64] + [dtypes.float64 for i in range(1,29)]
DATASET_GCP_PROJECT_ID, DATASET_ID, TABLE_ID, = 'bigquery-public-data.ml_datasets.ulb_fraud_detection'.split('.')
bqsession = client.read_session(
"projects/" + GCP_PROJECT_ID,
DATASET_GCP_PROJECT_ID, TABLE_ID, DATASET_ID,
COL_NAMES, COL_TYPES,
requested_streams=2,
row_restriction=row_restriction)
dataset = bqsession.parallel_read_rows()
return dataset.prefetch(1).map(features_and_labels).shuffle(batch_size*10).batch(batch_size)
client = BigQueryClient()
# TODO
temp_df = read_dataset(client, 'Time <= 144803', 2)
for row in temp_df:
print(row)
break
train_df = read_dataset(client, 'Time <= 144803', 2048)
eval_df = read_dataset(client, 'Time > 144803', 2048)
Explanation: The time cutoff is 144803 and the Keras model's output bias needs to be set at -6.36
The class weights need to be 289.4 and 0.5
Training a TensorFlow/Keras model that reads from BigQuery
Create the dataset from BigQuery
End of explanation
metrics = [
tf.keras.metrics.BinaryAccuracy(name='accuracy'),
tf.keras.metrics.Precision(name='precision'),
tf.keras.metrics.Recall(name='recall'),
tf.keras.metrics.AUC(name='roc_auc'),
]
# create inputs, and pass them into appropriate types of feature columns (here, everything is numeric)
inputs = {
'V{}'.format(i) : tf.keras.layers.Input(name='V{}'.format(i), shape=(), dtype='float64') for i in range(1, 29)
}
inputs['Amount'] = tf.keras.layers.Input(name='Amount', shape=(), dtype='float64')
input_fc = [tf.feature_column.numeric_column(colname) for colname in inputs.keys()]
# transformations. only the Amount is transformed
transformed = inputs.copy()
transformed['Amount'] = tf.keras.layers.Lambda(
lambda x: tf.math.log(tf.math.maximum(x, 0.01)), name='log_amount')(inputs['Amount'])
input_layer = tf.keras.layers.DenseFeatures(input_fc, name='inputs')(transformed)
# Deep learning model
d1 = tf.keras.layers.Dense(16, activation='relu', name='d1')(input_layer)
d2 = tf.keras.layers.Dropout(0.25, name='d2')(d1)
d3 = tf.keras.layers.Dense(16, activation='relu', name='d3')(d2)
output = tf.keras.layers.Dense(1, activation='sigmoid', name='d4', bias_initializer=tf.keras.initializers.Constant())(d3)
model = tf.keras.Model(inputs, output)
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=metrics)
tf.keras.utils.plot_model(model, rankdir='LR')
class_weight = {0: 0.5, 1: 289.4}
# TODO
# Trains the model for a fixed number of epochs
history = model.fit(train_df, validation_data=eval_df, epochs=20, class_weight=class_weight)
import matplotlib.pyplot as plt
plt.plot(history.history['val_roc_auc']);
plt.xlabel('Epoch');
plt.ylabel('AUC');
Explanation: Create Keras model
End of explanation
BUCKET='<your-bucket>' # CHANGE TO SOMETHING THAT YOU OWN
model.save('gs://{}/bqexample/export'.format(BUCKET))
%%bigquery
CREATE OR REPLACE MODEL advdata.keras_fraud_detection
OPTIONS(model_type='tensorflow', model_path='gs://qwiklabs-gcp-03-5b2f0816822f/bqexample/export/*')
Explanation: Load TensorFlow model into BigQuery
Now that we have trained a TensorFlow model off BigQuery data ...
let's load the model into BigQuery and use it for batch prediction!
End of explanation
%%bigquery
SELECT d4, Class
FROM ML.PREDICT( MODEL advdata.keras_fraud_detection,
(SELECT * FROM `bigquery-public-data.ml_datasets.ulb_fraud_detection` WHERE Time = 85285.0)
)
Explanation: Now predict with this model (the reason it's called 'd4' is because the output node of my Keras model was called 'd4').
To get probabilities, etc. we'd have to add the corresponding outputs to the Keras model.
End of explanation |
7,983 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
JupyterWorkflow3
From exploratory analysis to reproducible research
Mehmetcan Budak
Step1: SECOND PART
To make a python package so we and other people can use it for analysis.
Go to the directory
mkdir jupyterworkflow create a directory
touch jupyterworkflow/init.py initialize a python package
create a data.py in this directory.
import os
from urllib.request import urlretrieve
import pandas as pd
FREMONT_URL = "https | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use("seaborn")
from jupyterworkflow.data import get_fremont_data
data = get_fremont_data()
data.head()
data.resample("W").sum().plot()
data.groupby(data.index.time).mean().plot()
pivoted = data.pivot_table("Total", index=data.index.time, columns=data.index.date)
pivoted.iloc[:5, :5]
pivoted.plot(legend=False, alpha=0.01)
Explanation: JupyterWorkflow3
From exploratory analysis to reproducible research
Mehmetcan Budak
End of explanation
#get_fremont_data?
Explanation: SECOND PART
To make a python package so we and other people can use it for analysis.
Go to the directory
mkdir jupyterworkflow create a directory
touch jupyterworkflow/init.py initialize a python package
create a data.py in this directory.
import os
from urllib.request import urlretrieve
import pandas as pd
FREMONT_URL = "https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD"
/# create a function to only dowload this data if we need to download it, first run..
def get_fremont_data(filename="Fremont.csv", url=FREMONT_URL, force_download=False):
Download and cache the fremont data
Parameters
----------
filename :string (optional)
loation to save the data
url: string (optional)
web location of the data
force_download: bool (optional)
if True, force redownload of data
Returns
-------
data: pandas.DataFrame
The fremont bridge data
if force_download or not os.path.exists(filename):
urlretrieve(url, filename)
data = pd.read_csv("Fremont.csv", index_col="Date", parse_dates=True)
data.columns = ["West", "East"]
data["Total"] = data["West"] + data["East"]
return data
End of explanation |
7,984 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multimodality and Resampling
This notebook tests the robustness of modified Liu-West (MLW) resampling to multimodality in the posterior distribution. We use as a test the familiar model
$$
\Pr(0 | \omega, t) = \cos^2(\omega t),
$$
exploiting that the likelihood function is even in $\omega$ to produce posteriors that always have exactly two modes. Because this structure is not explicitly added to the resampling, but is easy to reason about analytically, it serves as a nice test case.
Preamble
As usual, we start by configuring division and enabling plotting support.
Step1: In order to view the incredibly verbose output from resampler debugging, it is helpful to point Python's logging functionality at a file instead of printing it inside the notebook. We use tempfile to pick a directory in a cross-platform way.
Step2: Next, we import all the functionality from QInfer that we will need.
Step3: Model and Prior Definition
We want the simple precession model $\cos^2(\omega t)$ to now extend over $\omega \in [-1, 1]$, so we redefine the are_models_valid method to allow for negative $\omega$.
Step4: Having done so, we now set a prior that explicitly includes the degeneracy in the likelihood.
Step5: WIP | Python Code:
from __future__ import division, print_function
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
try: plt.style.use('ggplot')
except: pass
Explanation: Multimodality and Resampling
This notebook tests the robustness of modified Liu-West (MLW) resampling to multimodality in the posterior distribution. We use as a test the familiar model
$$
\Pr(0 | \omega, t) = \cos^2(\omega t),
$$
exploiting that the likelihood function is even in $\omega$ to produce posteriors that always have exactly two modes. Because this structure is not explicitly added to the resampling, but is easy to reason about analytically, it serves as a nice test case.
Preamble
As usual, we start by configuring division and enabling plotting support.
End of explanation
import os, tempfile
logfile = os.path.join(tempfile.gettempdir(), 'multimodal_testing.log')
print("Logging to {}.".format(logfile))
import logging
logging.basicConfig(level=logging.DEBUG, filename=logfile)
Explanation: In order to view the incredibly verbose output from resampler debugging, it is helpful to point Python's logging functionality at a file instead of printing it inside the notebook. We use tempfile to pick a directory in a cross-platform way.
End of explanation
import qinfer as qi
Explanation: Next, we import all the functionality from QInfer that we will need.
End of explanation
class NotQuiteSoSimplePrecessionModel(qi.SimplePrecessionModel):
@staticmethod
def are_models_valid(modelparams):
return (np.abs(modelparams) <= 1)[:, 0]
Explanation: Model and Prior Definition
We want the simple precession model $\cos^2(\omega t)$ to now extend over $\omega \in [-1, 1]$, so we redefine the are_models_valid method to allow for negative $\omega$.
End of explanation
model = NotQuiteSoSimplePrecessionModel()
prior = qi.UniformDistribution([-1, 1])
def trial(a=0.98, h=None, track=True):
true_params = prior.sample()
updater = qi.SMCUpdater(model, 1000, prior, resampler=qi.LiuWestResampler(a=a, h=h, debug=True), track_resampling_divergence=track, debug_resampling=True)
for idx_exp in range(100):
exp = np.array([(9/8)**idx_exp], dtype=model.expparams_dtype)
datum = model.simulate_experiment(true_params, exp)
updater.update(datum, exp)
# Since this model is always degenerate about the origin, take the mean
# not of the original particles, but of the absolute value of the particles.
updater.particle_locations = np.abs(updater.particle_locations)
if track:
return [true_params, updater.est_mean()], np.mean(updater.resampling_divergences)
else:
return [true_params, updater.est_mean()]
def corr(a=0.98, h=None, track=True, n_trials=100):
trues = np.zeros((n_trials,))
ests = np.zeros((n_trials,))
if track:
divs = np.zeros((n_trials, ))
for idx_trial in range(n_trials):
if track:
print(idx_trial, end=' ')
(true, est), div = trial(a, h, track)
else:
true, est = trial(a, h, track)
trues[idx_trial] = true
ests[idx_trial] = est
if track:
divs[idx_trial] = div
if track:
return trues, ests, divs
else:
return trues, ests
trues, ests = corr(1, 0.02, False, 100)
bias = np.mean(np.abs(trues) - np.abs(ests))
risk = np.mean(np.abs(np.abs(trues) - np.abs(ests)))
print(bias, risk)
plt.plot(np.abs(trues), ests, 'k.')
plt.xlabel('true')
plt.ylabel('estimated')
plt.xlim((0, 1))
plt.ylim((0, 1))
trues, ests = corr(0.98, None, False, 100)
bias = np.mean(np.abs(trues) - np.abs(ests))
print(bias)
plt.plot(np.abs(trues), ests, 'k.')
plt.xlabel('true')
plt.ylabel('estimated')
plt.xlim((0, 1))
plt.ylim((0, 1))
Explanation: Having done so, we now set a prior that explicitly includes the degeneracy in the likelihood.
End of explanation
class MultiCosModel(qi.FiniteOutcomeModel):
def __init__(self, n_terms=2):
self._n_terms = n_terms
super(MultiCosModel, self).__init__()
@property
def n_modelparams(self):
return self._n_terms
@property
def is_n_outcomes_constant(self):
return True
def n_outcomes(self, expparams):
return 2
def are_models_valid(self, modelparams):
return np.all(np.logical_and(modelparams > 0, modelparams <= 1), axis=1)
@property
def expparams_dtype(self):
return [('ts', '{}float'.format(self._n_terms))]
def likelihood(self, outcomes, modelparams, expparams):
# We first call the superclass method, which basically
# just makes sure that call count diagnostics are properly
# logged.
super(MultiCosModel, self).likelihood(outcomes, modelparams, expparams)
# Next, since we have a two-outcome model, everything is defined by
# Pr(0 | modelparams; expparams), so we find the probability of 0
# for each model and each experiment.
#
# We do so by taking a product along the modelparam index (len 2,
# indicating omega_1 or omega_2), then squaring the result.
pr0 = np.prod(
np.cos(
# shape (n_models, 1, 2)
modelparams[:, np.newaxis, :] *
# shape (n_experiments, 2)
expparams['ts']
), # <- broadcasts to shape (n_models, n_experiments, 2).
axis=2 # <- product over the final index (len 2)
) ** 2 # square each element
# Now we use pr0_to_likelihood_array to turn this two index array
# above into the form expected by SMCUpdater and other consumers
# of likelihood().
return qi.FiniteOutcomeModel.pr0_to_likelihood_array(outcomes, pr0)
mp_model = qi.BinomialModel(MultiCosModel(3))
mp_prior = qi.UniformDistribution([[0, 1]]*3)
def multicos_trial(a, h, n_exps=200):
true = mp_prior.sample()
mp_updater = qi.SMCUpdater(mp_model, 2000, mp_prior,
resampler=qi.LiuWestResampler(a=a, h=h, debug=True),
debug_resampling=True
)
while True:
exp = np.array([(20 * np.pi * np.random.random(3), 40)], dtype=mp_model.expparams_dtype)
# To test the resampler, we take data according to one experiment design until it has to resample, then switch.
# Since the MLW resampler works quite well, we need to set an upper limit.
for idx in range(500):
datum = mp_model.simulate_experiment(true, exp)
mp_updater.update(datum, exp)
if len(mp_updater.data_record) >= n_exps:
return true, mp_updater.est_mean()
if mp_updater.just_resampled and idx >= 100:
break
def nanmean(arr):
return np.nansum(arr) / np.sum(np.isfinite(arr))
def mp_risk(a, h, n_trials=10, n_exps=200):
mp_errors = np.empty((n_trials,))
for idx_trial in range(n_trials):
true, est = multicos_trial(a, h, n_exps)
mp_errors[idx_trial] = np.sum((true - est)**2)
n_nan = np.sum(np.isnan(mp_errors))
if n_nan > 0:
print("{} NaNs observed.".format(n_nan))
return nanmean(mp_errors)
Explanation: WIP: Mutliparameter Models
We also want to try with a multicos model, since that model admits a degeneracy between parameters that is broken by experimental variety. To arrive at a good estimate, then, a resampler must preserve unusual posterior structures that arise in the approach to a unimodal final posterior.
It's worth noting here that the traditional LW parameters work quite well for a better experimental protocol (choosing lots of varied experiments), but that this protocol may not always be available. Thus, MLW is a resource here to compensate for experimental restrictions.
End of explanation |
7,985 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source alignment and coordinate frames
The aim of this tutorial is to show how to visually assess that the data are
well aligned in space for computing the forward solution, and understand
the different coordinate frames involved in this process.
Step1: Understanding coordinate frames
For M/EEG source imaging, there are three coordinate frames that we must
bring into alignment using two 3D
transformation matrices <trans_matrices_>_
that define how to rotate and translate points in one coordinate frame
to their equivalent locations in another.
Step2: Coordinate frame definitions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. raw
Step3: It is quite clear that the MRI surfaces (head, brain) are not well aligned
to the head digitization points (dots).
A good example
Here is the same plot, this time with the trans properly defined
(using a precomputed matrix).
Step4: Defining the head↔MRI trans using the GUI
You can try creating the head↔MRI transform yourself using
Step5: Alignment without MRI
The surface alignments above are possible if you have the surfaces available
from Freesurfer. | Python Code:
import os.path as op
import numpy as np
from mayavi import mlab
import mne
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
trans_fname = op.join(data_path, 'MEG', 'sample',
'sample_audvis_raw-trans.fif')
raw = mne.io.read_raw_fif(raw_fname)
trans = mne.read_trans(trans_fname)
src = mne.read_source_spaces(op.join(subjects_dir, 'sample', 'bem',
'sample-oct-6-src.fif'))
Explanation: Source alignment and coordinate frames
The aim of this tutorial is to show how to visually assess that the data are
well aligned in space for computing the forward solution, and understand
the different coordinate frames involved in this process.
:depth: 2
Let's start out by loading some data.
End of explanation
mne.viz.plot_alignment(raw.info, trans=trans, subject='sample',
subjects_dir=subjects_dir, surfaces='head-dense',
show_axes=True, dig=True, eeg=[], meg='sensors',
coord_frame='meg')
mlab.view(45, 90, distance=0.6, focalpoint=(0., 0., 0.))
print('Distance from head origin to MEG origin: %0.1f mm'
% (1000 * np.linalg.norm(raw.info['dev_head_t']['trans'][:3, 3])))
print('Distance from head origin to MRI origin: %0.1f mm'
% (1000 * np.linalg.norm(trans['trans'][:3, 3])))
Explanation: Understanding coordinate frames
For M/EEG source imaging, there are three coordinate frames that we must
bring into alignment using two 3D
transformation matrices <trans_matrices_>_
that define how to rotate and translate points in one coordinate frame
to their equivalent locations in another.
:func:mne.viz.plot_alignment is a very useful function for inspecting
these transformations, and the resulting alignment of EEG sensors, MEG
sensors, brain sources, and conductor models. If the subjects_dir and
subject parameters are provided, the function automatically looks for the
Freesurfer MRI surfaces to show from the subject's folder.
We can use the show_axes argument to see the various coordinate frames
given our transformation matrices. These are shown by axis arrows for each
coordinate frame:
shortest arrow is (R)ight/X
medium is forward/(A)nterior/Y
longest is up/(S)uperior/Z
i.e., a RAS coordinate system in each case. We can also set
the coord_frame argument to choose which coordinate
frame the camera should initially be aligned with.
Let's take a look:
End of explanation
mne.viz.plot_alignment(raw.info, trans=None, subject='sample', src=src,
subjects_dir=subjects_dir, dig=True,
surfaces=['head-dense', 'white'], coord_frame='meg')
Explanation: Coordinate frame definitions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. raw:: html
<style>
.pink {color:DarkSalmon; font-weight:bold}
.blue {color:DeepSkyBlue; font-weight:bold}
.gray {color:Gray; font-weight:bold}
.magenta {color:Magenta; font-weight:bold}
.purple {color:Indigo; font-weight:bold}
.green {color:LimeGreen; font-weight:bold}
.red {color:Red; font-weight:bold}
</style>
.. role:: pink
.. role:: blue
.. role:: gray
.. role:: magenta
.. role:: purple
.. role:: green
.. role:: red
Neuromag head coordinate frame ("head", :pink:pink axes)
Defined by the intersection of 1) the line between the LPA
(:red:red sphere) and RPA (:purple:purple sphere), and
2) the line perpendicular to this LPA-RPA line one that goes through
the Nasion (:green:green sphere).
The axes are oriented as X origin→RPA, Y origin→Nasion,
Z origin→upward (orthogonal to X and Y).
.. note:: This gets defined during the head digitization stage during
acquisition, often by use of a Polhemus or other digitizer.
MEG device coordinate frame ("meg", :blue:blue axes)
This is defined by the MEG manufacturers. From the Elekta user manual:
The origin of the device coordinate system is located at the center
of the posterior spherical section of the helmet with axis going
from left to right and axis pointing front. The axis is, again
normal to the plane with positive direction up.
.. note:: The device is coregistered with the head coordinate frame
during acquisition via emission of sinusoidal currents in
head position indicator (HPI) coils
(:magenta:magenta spheres) at the beginning of the
recording. This is stored in raw.info['dev_head_t'].
MRI coordinate frame ("mri", :gray:gray axes)
Defined by Freesurfer, the MRI (surface RAS) origin is at the
center of a 256×256×256 1mm anisotropic volume (may not be in the center
of the head).
.. note:: This is aligned to the head coordinate frame that we
typically refer to in MNE as trans.
A bad example
Let's try using trans=None, which (incorrectly!) equates the MRI
and head coordinate frames.
End of explanation
mne.viz.plot_alignment(raw.info, trans=trans, subject='sample',
src=src, subjects_dir=subjects_dir, dig=True,
surfaces=['head-dense', 'white'], coord_frame='meg')
Explanation: It is quite clear that the MRI surfaces (head, brain) are not well aligned
to the head digitization points (dots).
A good example
Here is the same plot, this time with the trans properly defined
(using a precomputed matrix).
End of explanation
# mne.gui.coregistration(subject='sample', subjects_dir=subjects_dir)
Explanation: Defining the head↔MRI trans using the GUI
You can try creating the head↔MRI transform yourself using
:func:mne.gui.coregistration.
First you must load the digitization data from the raw file
(Head Shape Source). The MRI data is already loaded if you provide the
subject and subjects_dir. Toggle Always Show Head Points to see
the digitization points.
To set the landmarks, toggle Edit radio button in MRI Fiducials.
Set the landmarks by clicking the radio button (LPA, Nasion, RPA) and then
clicking the corresponding point in the image.
After doing this for all the landmarks, toggle Lock radio button. You
can omit outlier points, so that they don't interfere with the finetuning.
.. note:: You can save the fiducials to a file and pass
mri_fiducials=True to plot them in
:func:mne.viz.plot_alignment. The fiducials are saved to the
subject's bem folder by default.
* Click Fit Head Shape. This will align the digitization points to the
head surface. Sometimes the fitting algorithm doesn't find the correct
alignment immediately. You can try first fitting using LPA/RPA or fiducials
and then align according to the digitization. You can also finetune
manually with the controls on the right side of the panel.
* Click Save As... (lower right corner of the panel), set the filename
and read it with :func:mne.read_trans.
For more information, see step by step instructions
in these slides
<https://www.slideshare.net/mne-python/mnepython-coregistration>_.
Uncomment the following line to align the data yourself.
End of explanation
sphere = mne.make_sphere_model(info=raw.info, r0='auto', head_radius='auto')
src = mne.setup_volume_source_space(sphere=sphere, pos=10.)
mne.viz.plot_alignment(
raw.info, eeg='projected', bem=sphere, src=src, dig=True,
surfaces=['brain', 'outer_skin'], coord_frame='meg', show_axes=True)
Explanation: Alignment without MRI
The surface alignments above are possible if you have the surfaces available
from Freesurfer. :func:mne.viz.plot_alignment automatically searches for
the correct surfaces from the provided subjects_dir. Another option is
to use a spherical conductor model <ch_forward_spherical_model>. It is
passed through bem parameter.
End of explanation |
7,986 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Executed
Step1: Notebook arguments
sigma (float)
Step2: Fitting models
Models used to fit the data.
1. Simple Exponential
In this model, we define the model function as an exponential transient
Step3: 2. Integrated Exponential
A more realistic model needs to take into account that each data point
is the result of an integration over a time window $w$
Step4: Generative model
These are the models used to generate the simulates (noisy) data.
1. Simple Exponential + Noise
In this simple model, we simulate random data $Y$ as an exponential decay plus
additive Gaussian noise
Step5: An ideal transient (no noise, no integration)
Step6: A simulated transient (including noise + integration)
Step7: Plot the computed curves
Step8: Fit data
Fit the "Integrated Exponential" model
Step9: Fit the "Simple Exponential" model
Step10: Print and plot fit results
Step11: Monte-Carlo Simulation
Here, fixed the model paramenters, we generate and fit several noisy datasets. Then, by plotting the distribution of the fitted parameters, we assess the stability and accuracy of the fit.
Parameters
The number simulation cycles is defined by num_sim_cycles. Current value is
Step12: The fixed kinetic curve parameters are
Step13: While tau is varied, taking the following values
Step14: <div class="alert alert-info">
**NOTE**
Step15: Run Monte-Carlo simulation
Run the Monte-Carlo fit for a set of different time-constants (taus)
and save results in two DataFrames, one for each model.
Step16: <div class="alert alert-danger">
**WARNING**
Step17: Results2 - Integrated Exponential | Python Code:
sigma = 0.016
time_window = 30
time_step = 5
time_start = -900
time_stop = 900
decimation = 20
t0_vary = True
true_params = dict(
tau = 60, # time constant
init_value = 0.3, # initial value (for t < t0)
final_value = 0.8, # final value (for t -> +inf)
t0 = 0) # time origin
num_sim_cycles = 1000
taus = (30, 60)
# Cell inserted during automated execution.
time_start = -900
num_sim_cycles = 1000
t0_vary = False
time_window = 180
taus = (30, 60, 120, 240)
decimation = 20
time_stop = 900
time_step = 10
true_params = {'init_value': 0.3, 't0': 0, 'tau': 60, 'final_value': 0.8}
sigma = 0.053
Explanation: Executed: Tue Oct 11 12:24:31 2016
Duration: 613 seconds.
End of explanation
%matplotlib inline
import numpy as np
import lmfit
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import models # custom module
Explanation: Notebook arguments
sigma (float): standard deviation of additive Gaussian noise to be simulated
time_window (float): seconds, integration window duration
time_step (float): seconds, time step for the moving integration window
time_start (float): seconds, start of time axis (kinetics starts at t = t0).
time_stop (float): seconds, stop of time axis (kinetics starts at t = t0).
t0_vary (bool): whether models should vary the curve origin (t0) during the fit
true_params (dict): parameters used to generate simulated kinetic curves
num_sim_cycles (int): number of times fit is repeated (Monte-Carlo)
taus (tuple): list of values for time-costant tau simulated during repeated fits (Monte-Carlo).
Simulated Kinetic Curve Fit
<p class=lead>This notebook fits simulated exponential transients with additive Gaissian noise in order to study time-constant fitting accuracy.
In particular we compare a simple exponential model with a more realistic model
with integration window, checking the effect on the fit results.
<p>
You can either run this notebook directly, or run it through the [master notebook](Simulated Kinetic Curve Fit - Run-All.ipynb) for batch processing.
## Imports
End of explanation
labels = ('tau', 'init_value', 'final_value')
model = models.factory_model_exp(t0_vary=True)
Explanation: Fitting models
Models used to fit the data.
1. Simple Exponential
In this model, we define the model function as an exponential transient:
$$ y = f(t) = A \cdot e^{-t/\tau} + K$$
The python function implementing it is:
models.exp_func().
Next cell defines and initializes the fitting model (lmfit.model.Model) including parameters' constrains:
End of explanation
modelw = models.factory_model_expwin(t_window=time_window, decimation=decimation, t0_vary=t0_vary)
Explanation: 2. Integrated Exponential
A more realistic model needs to take into account that each data point
is the result of an integration over a time window $w$:
$$f(t) = A \cdot e^{-t/\tau} + K$$
$$y(t) = \int_{t}^{t+w} f(t')\;dt'$$
In other words, when we process a measurement in time chunks, we are integrating
a non-stationary signal $f(t)$ over a time window $w$. This integration causes
a smoothing of $f(t)$, regardless of the fact that time is binned or
is swiped-through with a moving windows (overlapping chunks).
Numerically, $t$ is discretized with step equal to (time_step / decimation).
The python function implementing this model function is:
models.expwindec_func().
And, finally, we define and initialize the fitting model parameters' constrains:
End of explanation
t = np.arange(time_start, time_stop-time_window, time_step).astype(float)
t.size
Explanation: Generative model
These are the models used to generate the simulates (noisy) data.
1. Simple Exponential + Noise
In this simple model, we simulate random data $Y$ as an exponential decay plus
additive Gaussian noise:
$$ Y(t_k) = f(t_k) + N_k $$
$$ {N_k} \sim {\rm Normal}{\mu=0; \sigma}$$
$$ \Delta t = t_k - t_{k-1} = \texttt{time_step}$$
2. Integrated Exponential + Noise
For the "integrating window" model, we first define a finer time axis $\theta_i$
which oversamples $t_k$ by a factor $n$. Then we define the function $Y_f$
adding Gaussian noise $\sqrt{n}\,N_i$, with $n$ times larger variance:
$$ Y_f(\theta_i) = f(\theta_i) + \sqrt{n}\,N_i $$
$$ \Delta \theta = \theta_i - \theta_{i-1} = \texttt{time_step} \;/\; n$$
Finally, by averaging each time window, we compute the data on the coarse time axis $t_k$:
$$ Y_w(t_k) = \frac{1}{m}\sum_{i} Y_f(\theta_i)$$
Here, for each $t_k$, we compute the mean of $m$ consecutive $Y_f$ values. The number $m$
is chosen so that $m\, \Delta \theta$ is equal to the time window.
Noise amplitude
The amplitude of the additive noise ($\sigma$) is estimated from the experimental kinetic curves.
In particular we take the variance from the POST period (i.e. the steady state period after the transient).
The POST period has been chosen because it exhibits higher variance than the PRE period (i.e. the steady state period
before the transient). These values have been calculated in 8-spot bubble-bubble kinetics - Summary.
In both models we define the noise amplitude as sigma (see first cell):
sigma = 0.016
Time axis
We also define the parameters for the time axis $t$:
time_start = -900 # seconds
time_stop = 900 # seconds
time_step = 5 # seconds
Kinetic curve paramenters
The simulated kinetic curve has the following parameters:
true_params = dict(
tau = 60, # time constant
init_value = 0.3, # initial value (for t < t0)
final_value = 0.8, # final value (for t -> +inf)
t0 = 0) # time origin
<div class="alert alert-info">
**NOTE**: All previous parameters are defined in the first notebook cell.
</div>
Single kinetic curve fit
Here we simulate one kinetic curve and fit it with the two models (simple exponential and integrated exponential).
Draw simulated data
Time axis for simulated data:
End of explanation
y = models.expwindec_func(t, t_window=time_window, **true_params)
y.shape
Explanation: An ideal transient (no noise, no integration):
End of explanation
time_window, time_step
yr = models.expwindec_func(t, t_window=time_window, sigma=sigma, **true_params)
yr.shape
Explanation: A simulated transient (including noise + integration):
End of explanation
plt.plot(t, y, '-', label='model')
plt.plot(t, yr, 'o', label='model + noise')
Explanation: Plot the computed curves:
End of explanation
#%%timeit
resw = modelw.fit(yr, t=t, tau=10, init_value=0.1, final_value=0.9, verbose=False)
Explanation: Fit data
Fit the "Integrated Exponential" model:
End of explanation
#%%timeit
res = model.fit(yr, t=t + 0.5*time_window, tau=10, init_value=0.1, final_value=0.9, verbose=False)
Explanation: Fit the "Simple Exponential" model:
End of explanation
fig = plt.figure(figsize=(14, 8))
res.plot(fig=fig)
ci = lmfit.conf_interval(res, res)
lmfit.report_fit(res)
print(lmfit.ci_report(ci, with_offset=False))
#plt.xlim(-300, 300)
fig = plt.figure(figsize=(14, 8))
resw.plot(fig=fig)
ci = lmfit.conf_interval(resw, resw)
lmfit.report_fit(resw)
print(lmfit.ci_report(ci, with_offset=False))
#plt.xlim(-300, 300)
Explanation: Print and plot fit results:
End of explanation
num_sim_cycles
Explanation: Monte-Carlo Simulation
Here, fixed the model paramenters, we generate and fit several noisy datasets. Then, by plotting the distribution of the fitted parameters, we assess the stability and accuracy of the fit.
Parameters
The number simulation cycles is defined by num_sim_cycles. Current value is:
End of explanation
{k: v for k, v in true_params.items() if k is not "tau"}
Explanation: The fixed kinetic curve parameters are:
End of explanation
taus
t0_vary
Explanation: While tau is varied, taking the following values:
End of explanation
def draw_samples_and_fit(true_params):
# Create the data
t = np.arange(time_start, time_stop-time_window, time_step).astype(float)
yr = models.expwindec_func(t, t_window=time_window, sigma=sigma, decimation=100, **true_params)
# Fit the model
tc = t + 0.5*time_window
kws = dict(fit_kws=dict(nan_policy='omit'), verbose=False)
res = model.fit(yr, t=tc, tau=90, method='nelder', **kws)
res = model.fit(yr, t=tc, **kws)
resw = modelw.fit(yr, t=t, tau=400, decimation=decimation, method='nelder', **kws)
resw = modelw.fit(yr, t=t, decimation=decimation, **kws)
return res, resw
def monte_carlo_sim(true_params, N):
df1 = pd.DataFrame(index=range(N), columns=labels)
df2 = df1.copy()
for i in range(N):
res1, res2 = draw_samples_and_fit(true_params)
for var in labels:
df1.loc[i, var] = res1.values[var]
df2.loc[i, var] = res2.values[var]
return df1, df2
Explanation: <div class="alert alert-info">
**NOTE**: All previous parameters are defined in the first notebook cell.
</div>
Functions
Here we define two functions:
draw_samples_and_fit() draws a set of data and fits it with both models
monte_carlo_sim() run the Monte-Carlo simulation: calls draw_samples_and_fit() many times.
NOTE: Global variables are used by previous functions.
End of explanation
mc_results1, mc_results2 = [], []
%%timeit -n1 -r1 # <-- prints execution time
for tau in taus:
true_params['tau'] = tau
df1, df2 = monte_carlo_sim(true_params, num_sim_cycles)
mc_results1.append(df1)
mc_results2.append(df2)
Explanation: Run Monte-Carlo simulation
Run the Monte-Carlo fit for a set of different time-constants (taus)
and save results in two DataFrames, one for each model.
End of explanation
for tau, df in zip(taus, mc_results1):
true_params['tau'] = tau
fig, ax = plt.subplots(1, 3, figsize=(16, 4))
for i, var in enumerate(labels):
std = df[var].std()
df[var].hist(bins=30, ax=ax[i])
ax[i].set_title("%s = %.1f (%.3f)" % (var, true_params[var], std), fontsize=18)
ax[i].axvline(true_params[var], color='r', ls='--')
#print('True parameters: %s' % true_params)
Explanation: <div class="alert alert-danger">
**WARNING**: The previous cell can take a long to execute. Execution time scales with **`num_sim_cycles * len(taus)`**.
</div>
Results1 - Simple Exponential
End of explanation
for tau, df in zip(taus, mc_results2):
true_params['tau'] = tau
fig, ax = plt.subplots(1, 3, figsize=(16, 4))
for i, var in enumerate(labels):
std = df[var].std()
df[var].hist(bins=30, ax=ax[i])
ax[i].set_title("%s = %.1f (%.3f)" % (var, true_params[var], std), fontsize=18)
ax[i].axvline(true_params[var], color='r', ls='--')
#print('True parameters: %s' % true_params)
Explanation: Results2 - Integrated Exponential
End of explanation |
7,987 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
\title{Counters in myHDL}
\author{Steven K Armour}
\maketitle
Counters play a vital role in Digital Hardware, ranging from Clock Dividers; (see below) to event triggers by recording the number of events that have occurred or will still need to occur (all the counters here in use a clock as the counting event but this is easily changed). Presented below are some basic HDL counters (Up, Down, Hybridized Up-Down) in myHDL.
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Refrances" data-toc-modified-id="Refrances-1"><span class="toc-item-num">1 </span>Refrances</a></span></li><li><span><a href="#Libraries-and-Helper-functions" data-toc-modified-id="Libraries-and-Helper-functions-2"><span class="toc-item-num">2 </span>Libraries and Helper functions</a></span></li><li><span><a href="#Counter-Specs" data-toc-modified-id="Counter-Specs-3"><span class="toc-item-num">3 </span>Counter Specs</a></span></li><li><span><a href="#myHDL-modules-bitvector-type-behavior" data-toc-modified-id="myHDL-modules-bitvector-type-behavior-4"><span class="toc-item-num">4 </span>myHDL modules bitvector type behavior</a></span><ul class="toc-item"><li><span><a href="#up-counting-behavior" data-toc-modified-id="up-counting-behavior-4.1"><span class="toc-item-num">4.1 </span>up counting behavior</a></span></li><li><span><a href="#down-counting-behavior" data-toc-modified-id="down-counting-behavior-4.2"><span class="toc-item-num">4.2 </span>down counting behavior</a></span></li></ul></li><li><span><a href="#Up-Counter" data-toc-modified-id="Up-Counter-5"><span class="toc-item-num">5 </span>Up-Counter</a></span><ul class="toc-item"><li><span><a href="#myHDL-testing" data-toc-modified-id="myHDL-testing-5.1"><span class="toc-item-num">5.1 </span>myHDL testing</a></span></li><li><span><a href="#Verilog-Code" data-toc-modified-id="Verilog-Code-5.2"><span class="toc-item-num">5.2 </span>Verilog Code</a></span></li><li><span><a href="#Verilog-Testbench" data-toc-modified-id="Verilog-Testbench-5.3"><span class="toc-item-num">5.3 </span>Verilog Testbench</a></span></li></ul></li><li><span><a href="#Down-Counter" data-toc-modified-id="Down-Counter-6"><span class="toc-item-num">6 </span>Down Counter</a></span><ul class="toc-item"><li><span><a href="#myHDL-Testing" data-toc-modified-id="myHDL-Testing-6.1"><span class="toc-item-num">6.1 </span>myHDL Testing</a></span></li><li><span><a href="#Verilog-Code" data-toc-modified-id="Verilog-Code-6.2"><span class="toc-item-num">6.2 </span>Verilog Code</a></span></li><li><span><a href="#Verilog-Testbench" data-toc-modified-id="Verilog-Testbench-6.3"><span class="toc-item-num">6.3 </span>Verilog Testbench</a></span></li></ul></li><li><span><a href="#Up/Down-Counter" data-toc-modified-id="Up/Down-Counter-7"><span class="toc-item-num">7 </span>Up/Down Counter</a></span><ul class="toc-item"><li><span><a href="#myHDL-Testing" data-toc-modified-id="myHDL-Testing-7.1"><span class="toc-item-num">7.1 </span>myHDL Testing</a></span></li><li><span><a href="#Verilog-Code" data-toc-modified-id="Verilog-Code-7.2"><span class="toc-item-num">7.2 </span>Verilog Code</a></span></li><li><span><a href="#Verilog-Testbench" data-toc-modified-id="Verilog-Testbench-7.3"><span class="toc-item-num">7.3 </span>Verilog Testbench</a></span></li></ul></li><li><span><a href="#Application
Step1: Counter Specs
Step2: myHDL modules bitvector type behavior
up counting behavior
Step3: down counting behavior
Step5: Up-Counter
up counters are counters that count up to a target value from a lower starting value. The following counter is a simple one that uses the clock as incrementer (think one clock cycle as one swing of an old grandfather clock pendulum). But more complicated counters can use any signal as an incrementer. This Counter also has a signal the indicates that the counter has been triggered before the modulus values for the internal counter is reset. This is because this counter tries to reproduce the behavior of timers found on common apps that show how much time has elapsed since the counter has run up
\begin{figure}
\centerline{\includegraphics[width=10cm]{Up_Counter.png}}
\caption{\label{fig
Step7: myHDL testing
Step8: Verilog Code
Step10: \begin{figure}
\centerline{\includegraphics[width=10cm]{Up_CounterRTL.png}}
\caption{\label{fig
Step12: Down Counter
Down Counters Count Down from a set upper value to a set target lower value. The following Down Counter is a simple revamp of the previous Up Counter. Thus it starts from the CountVal and counts down to zero to trigger the trigger signal that it has completed one countdown cycle before the internal counter resets to restart the countdown.
\begin{figure}
\centerline{\includegraphics[width=10cm]{}}
\caption{\label{fig
Step14: myHDL Testing
Step15: Verilog Code
Step17: \begin{figure}
\centerline{\includegraphics[width=10cm]{Down_CounterRTL.png}}
\caption{\label{fig
Step19: Up/Down Counter
This Counter incorporates both an Up Counter and Down Counter via hybridizing between the two via a direction control state machine
\begin{figure}
\centerline{\includegraphics[width=10cm]{}}
\caption{\label{fig
Step21: myHDL Testing
Step22: Verilog Code
Step24: \begin{figure}
\centerline{\includegraphics[width=10cm]{UpDown_CounterRTL.png}}
\caption{\label{fig
Step26: Application
Step28: myHDL Testing
Step30: Verilog Code
\begin{figure}
\centerline{\includegraphics[width=10cm]{ClockDividerRTL.png}}
\caption{\label{fig | Python Code:
from myhdl import *
from myhdlpeek import Peeker
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sympy import *
init_printing()
import random
#https://github.com/jrjohansson/version_information
%load_ext version_information
%version_information myhdl, myhdlpeek, numpy, pandas, matplotlib, sympy, random
#helper functions to read in the .v and .vhd generated files into python
def VerilogTextReader(loc, printresult=True):
with open(f'{loc}.v', 'r') as vText:
VerilogText=vText.read()
if printresult:
print(f'***Verilog modual from {loc}.v***\n\n', VerilogText)
return VerilogText
def VHDLTextReader(loc, printresult=True):
with open(f'{loc}.vhd', 'r') as vText:
VerilogText=vText.read()
if printresult:
print(f'***VHDL modual from {loc}.vhd***\n\n', VerilogText)
return VerilogText
Explanation: \title{Counters in myHDL}
\author{Steven K Armour}
\maketitle
Counters play a vital role in Digital Hardware, ranging from Clock Dividers; (see below) to event triggers by recording the number of events that have occurred or will still need to occur (all the counters here in use a clock as the counting event but this is easily changed). Presented below are some basic HDL counters (Up, Down, Hybridized Up-Down) in myHDL.
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Refrances" data-toc-modified-id="Refrances-1"><span class="toc-item-num">1 </span>Refrances</a></span></li><li><span><a href="#Libraries-and-Helper-functions" data-toc-modified-id="Libraries-and-Helper-functions-2"><span class="toc-item-num">2 </span>Libraries and Helper functions</a></span></li><li><span><a href="#Counter-Specs" data-toc-modified-id="Counter-Specs-3"><span class="toc-item-num">3 </span>Counter Specs</a></span></li><li><span><a href="#myHDL-modules-bitvector-type-behavior" data-toc-modified-id="myHDL-modules-bitvector-type-behavior-4"><span class="toc-item-num">4 </span>myHDL modules bitvector type behavior</a></span><ul class="toc-item"><li><span><a href="#up-counting-behavior" data-toc-modified-id="up-counting-behavior-4.1"><span class="toc-item-num">4.1 </span>up counting behavior</a></span></li><li><span><a href="#down-counting-behavior" data-toc-modified-id="down-counting-behavior-4.2"><span class="toc-item-num">4.2 </span>down counting behavior</a></span></li></ul></li><li><span><a href="#Up-Counter" data-toc-modified-id="Up-Counter-5"><span class="toc-item-num">5 </span>Up-Counter</a></span><ul class="toc-item"><li><span><a href="#myHDL-testing" data-toc-modified-id="myHDL-testing-5.1"><span class="toc-item-num">5.1 </span>myHDL testing</a></span></li><li><span><a href="#Verilog-Code" data-toc-modified-id="Verilog-Code-5.2"><span class="toc-item-num">5.2 </span>Verilog Code</a></span></li><li><span><a href="#Verilog-Testbench" data-toc-modified-id="Verilog-Testbench-5.3"><span class="toc-item-num">5.3 </span>Verilog Testbench</a></span></li></ul></li><li><span><a href="#Down-Counter" data-toc-modified-id="Down-Counter-6"><span class="toc-item-num">6 </span>Down Counter</a></span><ul class="toc-item"><li><span><a href="#myHDL-Testing" data-toc-modified-id="myHDL-Testing-6.1"><span class="toc-item-num">6.1 </span>myHDL Testing</a></span></li><li><span><a href="#Verilog-Code" data-toc-modified-id="Verilog-Code-6.2"><span class="toc-item-num">6.2 </span>Verilog Code</a></span></li><li><span><a href="#Verilog-Testbench" data-toc-modified-id="Verilog-Testbench-6.3"><span class="toc-item-num">6.3 </span>Verilog Testbench</a></span></li></ul></li><li><span><a href="#Up/Down-Counter" data-toc-modified-id="Up/Down-Counter-7"><span class="toc-item-num">7 </span>Up/Down Counter</a></span><ul class="toc-item"><li><span><a href="#myHDL-Testing" data-toc-modified-id="myHDL-Testing-7.1"><span class="toc-item-num">7.1 </span>myHDL Testing</a></span></li><li><span><a href="#Verilog-Code" data-toc-modified-id="Verilog-Code-7.2"><span class="toc-item-num">7.2 </span>Verilog Code</a></span></li><li><span><a href="#Verilog-Testbench" data-toc-modified-id="Verilog-Testbench-7.3"><span class="toc-item-num">7.3 </span>Verilog Testbench</a></span></li></ul></li><li><span><a href="#Application:-Clock-Divider" data-toc-modified-id="Application:-Clock-Divider-8"><span class="toc-item-num">8 </span>Application: Clock Divider</a></span><ul class="toc-item"><li><span><a href="#myHDL-Testing" data-toc-modified-id="myHDL-Testing-8.1"><span class="toc-item-num">8.1 </span>myHDL Testing</a></span></li><li><span><a href="#Verilog-Code" data-toc-modified-id="Verilog-Code-8.2"><span class="toc-item-num">8.2 </span>Verilog Code</a></span></li><li><span><a href="#Verilog-Testbench" data-toc-modified-id="Verilog-Testbench-8.3"><span class="toc-item-num">8.3 </span>Verilog Testbench</a></span></li></ul></li></ul></div>
Refrances
@misc{loi le_2017,
title={Verilog code for counter with testbench},
url={http://www.fpga4student.com/2017/03/verilog-code-for-counter-with-testbench.html},
journal={Fpga4student.com},
author={Loi Le, Van},
year={2017}
}
@misc{digilent_2018,
title={Learn.Digilentinc | Counter and Clock Divider},
url={https://learn.digilentinc.com/Documents/262},
journal={Learn.digilentinc.com},
author={Digilent},
year={2018}
}
Libraries and Helper functions
End of explanation
CountVal=17
BitSize=int(np.log2(CountVal))+1; BitSize
Explanation: Counter Specs
End of explanation
ModBV=modbv(0)[BitSize:]
IntBV=intbv(0)[BitSize:]
print(f"`ModBV` max is {ModBV.max}; min is {ModBV.min}")
print(f"`IntBV` max is {IntBV.max}; min is {IntBV.min}")
for _ in range(ModBV.max*2):
try:
ModBV+=1; IntBV+=1
print(f"`ModBV` value is {ModBV}; `IntBV` value is {IntBV}")
except ValueError:
ModBV+=1
print(f"`ModBV` value is {ModBV}; `IntBV` value is {IntBV} and INVALID")
Explanation: myHDL modules bitvector type behavior
up counting behavior
End of explanation
ModBV=modbv(2**BitSize -1)[BitSize:]
IntBV=intbv(2**BitSize -1)[BitSize:]
print(f"`ModBV` max is {ModBV.max}; min is {ModBV.min}")
print(f"`IntBV` max is {IntBV.max}; min is {IntBV.min}")
for _ in range(ModBV.max*2):
try:
ModBV-=1; IntBV-=1
print(f"`ModBV` value is {ModBV}; `IntBV` value is {IntBV}")
except ValueError:
ModBV-=0
print(f"`ModBV` value is {ModBV}; `IntBV` value is {IntBV} and INVALID")
Explanation: down counting behavior
End of explanation
@block
def Up_Counter(count, Trig, clk, rst, CountVal, BitSize):
UpCounter
Input:
clk(bool): system clock feed
rst(bool): clock reset signal
Ouput:
count (bit vector): current count value; count
Trig(bool)
Parmeter(Python Only):
CountVal(int): value to count to
BitSize (int): Bitvalue size is log_2(CountVal)+1
#internals
count_i=Signal(modbv(0)[BitSize:])
Trig_i=Signal(bool(0))
@always(clk.posedge, rst.negedge)
def logic():
if rst:
count_i.next=0
Trig_i.next=0
elif count_i%CountVal==0 and count_i!=0:
Trig_i.next=1
count_i.next=0
else:
count_i.next=count_i+1
@always_comb
def OuputBuffer():
count.next=count_i
Trig.next=Trig_i
return instances()
Explanation: Up-Counter
up counters are counters that count up to a target value from a lower starting value. The following counter is a simple one that uses the clock as incrementer (think one clock cycle as one swing of an old grandfather clock pendulum). But more complicated counters can use any signal as an incrementer. This Counter also has a signal the indicates that the counter has been triggered before the modulus values for the internal counter is reset. This is because this counter tries to reproduce the behavior of timers found on common apps that show how much time has elapsed since the counter has run up
\begin{figure}
\centerline{\includegraphics[width=10cm]{Up_Counter.png}}
\caption{\label{fig:RP} Up_Counter Functianl Digram }
\end{figure}
End of explanation
Peeker.clear()
clk=Signal(bool(0)); Peeker(clk, 'clk')
rst=Signal(bool(0)); Peeker(rst, 'rst')
Trig=Signal(bool(0)); Peeker(Trig, 'Trig')
count=Signal(modbv(0)[BitSize:]); Peeker(count, 'count')
DUT=Up_Counter(count, Trig, clk, rst, CountVal, BitSize)
def Up_CounterTB():
myHDL only Testbench for `Up_Counter` module
@always(delay(1))
def ClkGen():
clk.next=not clk
@instance
def stimules():
i=0
while True:
if i==int(CountVal*1.5):
rst.next=1
elif i==int(CountVal*1.5)+1:
rst.next=0
if i==int(CountVal*2.5):
raise StopSimulation()
i+=1
yield clk.posedge
return instances()
sim=Simulation(DUT, Up_CounterTB(), *Peeker.instances()).run()
Peeker.to_wavedrom()
Up_CounterData=Peeker.to_dataframe()
Up_CounterData=Up_CounterData[Up_CounterData['clk']==1]
Up_CounterData.drop('clk', axis=1, inplace=True)
Up_CounterData.reset_index(drop=True, inplace=True)
Up_CounterData
Explanation: myHDL testing
End of explanation
DUT.convert()
VerilogTextReader('Up_Counter');
Explanation: Verilog Code
End of explanation
ResetAt=int(CountVal*1.5)+1
StopAt=int(CountVal*2.5)
@block
def Up_CounterTBV():
myHDL -> Verilog Testbench for `Up_Counter` module
clk=Signal(bool(0))
rst=Signal(bool(0))
Trig=Signal(bool(0))
count=Signal(modbv(0)[BitSize:])
@always_comb
def print_data():
print(clk, rst, Trig, count)
DUT=Up_Counter(count, Trig, clk, rst, CountVal, BitSize)
@instance
def clk_signal():
while True:
clk.next = not clk
yield delay(1)
@instance
def stimules():
i=0
while True:
if i==ResetAt:
rst.next=1
elif i==(ResetAt+1):
rst.next=0
else:
pass
if i==StopAt:
raise StopSimulation()
i+=1
yield clk.posedge
return instances()
TB=Up_CounterTBV()
TB.convert(hdl="Verilog", initial_values=True)
VerilogTextReader('Up_CounterTBV');
Explanation: \begin{figure}
\centerline{\includegraphics[width=10cm]{Up_CounterRTL.png}}
\caption{\label{fig:UCRTL} Up_Counter RTL Schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{Up_CounterSYN.png}}
\caption{\label{fig:UCSYN} Up_Counter Synthesized Schematic; Xilinx Vivado 2017.4}
\end{figure}
Verilog Testbench
End of explanation
@block
def Down_Counter(count, Trig, clk, rst, StartVal, BitSize):
DownCounter
Input:
clk(bool): system clock feed
rst(bool): clock reset signal
Ouput:
count (bit vector): current count value; count
Trig(bool)
Parmeter(Python Only):
StartVal(int): value to count from
BitSize (int): Bitvalue size is log_2(CountVal)+1
CatButt
#internal counter value
count_i=Signal(modbv(StartVal)[BitSize:])
@always(clk.posedge, rst.negedge)
def logic():
if rst:
count_i.next=StartVal
Trig.next=0
elif count_i==0:
Trig.next=1
count_i.next=StartVal
else:
count_i.next=count_i-1
@always_comb
def OuputBuffer():
count.next=count_i
return instances()
Explanation: Down Counter
Down Counters Count Down from a set upper value to a set target lower value. The following Down Counter is a simple revamp of the previous Up Counter. Thus it starts from the CountVal and counts down to zero to trigger the trigger signal that it has completed one countdown cycle before the internal counter resets to restart the countdown.
\begin{figure}
\centerline{\includegraphics[width=10cm]{}}
\caption{\label{fig:RP} Down_Counter Functianl Digram (ToDo) }
\end{figure}
End of explanation
Peeker.clear()
clk=Signal(bool(0)); Peeker(clk, 'clk')
rst=Signal(bool(0)); Peeker(rst, 'rst')
Trig=Signal(bool(0)); Peeker(Trig, 'Trig')
count=Signal(modbv(0)[BitSize:]); Peeker(count, 'count')
DUT=Down_Counter(count, Trig, clk, rst, CountVal, BitSize)
def Down_CounterTB():
myHDL only Testbench for `Down_Counter` module
@always(delay(1))
def ClkGen():
clk.next=not clk
@instance
def stimules():
i=0
while True:
if i==int(CountVal*1.5):
rst.next=1
elif i==int(CountVal*1.5)+1:
rst.next=0
if i==int(CountVal*2.5):
raise StopSimulation()
i+=1
yield clk.posedge
return instances()
sim=Simulation(DUT, Down_CounterTB(), *Peeker.instances()).run()
Peeker.to_wavedrom()
Down_CounterData=Peeker.to_dataframe()
Down_CounterData=Down_CounterData[Down_CounterData['clk']==1]
Down_CounterData.drop('clk', axis=1, inplace=True)
Down_CounterData.reset_index(drop=True, inplace=True)
Down_CounterData
Explanation: myHDL Testing
End of explanation
DUT.convert()
VerilogTextReader('Down_Counter');
Explanation: Verilog Code
End of explanation
ResetAt=int(CountVal*1.5)
StopAt=int(CountVal*2.5)
@block
def Down_CounterTBV():
myHDL -> Verilog Testbench for `Down_Counter` module
clk=Signal(bool(0))
rst=Signal(bool(0))
Trig=Signal(bool(0))
count=Signal(modbv(0)[BitSize:])
@always_comb
def print_data():
print(clk, rst, Trig, count)
DUT=Down_Counter(count, Trig, clk, rst, CountVal, BitSize)
@instance
def clk_signal():
while True:
clk.next = not clk
yield delay(1)
@instance
def stimules():
i=0
while True:
if i==ResetAt:
rst.next=1
elif i==(ResetAt+1):
rst.next=0
else:
pass
if i==StopAt:
raise StopSimulation()
i+=1
yield clk.posedge
return instances()
TB=Down_CounterTBV()
TB.convert(hdl="Verilog", initial_values=True)
VerilogTextReader('Down_CounterTBV');
Explanation: \begin{figure}
\centerline{\includegraphics[width=10cm]{Down_CounterRTL.png}}
\caption{\label{fig:DCRTL} Down_Counter RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{Down_CounterSYN.png}}
\caption{\label{fig:DCSYN} Down_Counter Synthesized Schematic; Xilinx Vivado 2017.4}
\end{figure}
Verilog Testbench
End of explanation
#Create the Direction States for UpDown Counter
DirStates=enum('Up', 'Down')
print(f"`Up` state repersentation is {bin(DirStates.Up)}")
print(f"`Down` state repersentation is {bin(DirStates.Down)}")
@block
def UpDown_Counter(Dir, count, Trig, clk, rst,
CountVal, StartVal, BitSize):
UpDownCounter, hybrid of a simple Up Counter and
a simple Down Counter using `Dir` to control Up/Down
count Direction
Input:
Dir():
clk(bool): system clock feed
rst(bool): clock reset signal
Ouput:
count (bit vector): current count value; count
Trig(bool)
Parmeter(Python Only):
CountVal(int): Highest Value for counter
StartVal(int): starting value for internal counter
BitSize (int): Bitvalue size is log_2(CountVal)+1
#internal counter value
count_i=Signal(modbv(StartVal)[BitSize:])
@always(clk.posedge, rst.negedge)
def logic():
if rst:
count_i.next=StartVal
Trig.next=0
#counter contanment
elif count_i//CountVal==1 and rst==0:
count_i.next=StartVal
#up behavior
elif Dir==DirStates.Up:
count_i.next=count_i+1
#simple Triger at ends
if count_i%CountVal==0:
Trig.next=1
#down behavior
elif Dir==DirStates.Down:
count_i.next=count_i-1
#simple Triger at ends
if count_i%CountVal==0:
Trig.next=1
@always_comb
def OuputBuffer():
count.next=count_i
return instances()
Explanation: Up/Down Counter
This Counter incorporates both an Up Counter and Down Counter via hybridizing between the two via a direction control state machine
\begin{figure}
\centerline{\includegraphics[width=10cm]{}}
\caption{\label{fig:RP} UpDown_Counter Functianl Digram (ToDo) }
\end{figure}
End of explanation
Peeker.clear()
clk=Signal(bool(0)); Peeker(clk, 'clk')
rst=Signal(bool(0)); Peeker(rst, 'rst')
Trig=Signal(bool(0)); Peeker(Trig, 'Trig')
count=Signal(modbv(0)[BitSize:]); Peeker(count, 'count')
Dir=Signal(DirStates.Up); Peeker(Dir, 'Dir')
DUT=UpDown_Counter(Dir, count, Trig, clk, rst,
CountVal, StartVal=CountVal//2, BitSize=BitSize)
def UpDown_CounterTB():
myHDL only Testbench for `UpDown_Counter` module
@always(delay(1))
def ClkGen():
clk.next=not clk
@instance
def stimules():
i=0
while True:
if i==int(CountVal*1.5):
Dir.next=DirStates.Down
elif i==int(CountVal*2.5):
rst.next=1
elif i==int(CountVal*2.5)+1:
rst.next=0
if i==int(CountVal*3.5):
raise StopSimulation()
i+=1
yield clk.posedge
return instances()
sim=Simulation(DUT, UpDown_CounterTB(), *Peeker.instances()).run()
Peeker.to_wavedrom()
UpDown_CounterData=Peeker.to_dataframe()
UpDown_CounterData=UpDown_CounterData[UpDown_CounterData['clk']==1]
UpDown_CounterData.drop('clk', axis=1, inplace=True)
UpDown_CounterData.reset_index(drop=True, inplace=True)
UpDown_CounterData
Explanation: myHDL Testing
End of explanation
DUT.convert()
VerilogTextReader('UpDown_Counter');
Explanation: Verilog Code
End of explanation
StateChangeAt=int(CountVal*1.5)
ResetAt=int(CountVal*2.5)
StopAt=int(CountVal*3.5)
@block
def UpDown_CounterTBV():
myHDL -> Verilog Testbench for `Down_Counter` module
clk=Signal(bool(0))
rst=Signal(bool(0))
Trig=Signal(bool(0))
count=Signal(modbv(0)[BitSize:])
Dir=Signal(DirStates.Up)
DUT=UpDown_Counter(Dir, count, Trig, clk, rst,
CountVal, StartVal=CountVal//2, BitSize=BitSize)
@always_comb
def print_data():
print(clk, rst, Trig, count)
DUT=Down_Counter(count, Trig, clk, rst, CountVal, BitSize)
@instance
def clk_signal():
while True:
clk.next = not clk
yield delay(1)
@instance
def stimules():
i=0
while True:
if i==StateChangeAt:
Dir.next=DirStates.Down
elif i==ResetAt:
rst.next=1
elif i==ResetAt+1:
rst.next=0
else:
pass
if i==StopAt:
raise StopSimulation()
i+=1
yield clk.posedge
return instances()
TB=UpDown_CounterTBV()
TB.convert(hdl="Verilog", initial_values=True)
VerilogTextReader('UpDown_CounterTBV');
Explanation: \begin{figure}
\centerline{\includegraphics[width=10cm]{UpDown_CounterRTL.png}}
\caption{\label{fig:UDCRTL} UpDown_Counter RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{UpDown_CounterSYN.png}}
\caption{\label{fig:UDCSYN} UpDown_Counter Synthesized schematic; Xilinx Vivado 2017.4}
\end{figure}
Verilog Testbench
End of explanation
@block
def ClockDivider(Divisor, clkOut, count, clk,rst):
Simple Clock Divider based on the Digilint Clock Divider
https://learn.digilentinc.com/Documents/262
Input:
Divisor(32 bit): the clock frequncy divide by value
clk(bool): The input clock
rst(bool): clockDivider Reset
Ouput:
clkOut(bool): the divided clock ouput
count(32bit): the value of the internal counter
count_i=Signal(modbv(0)[32:])
@always(clk.posedge, rst.posedge)
def counter():
if rst:
count_i.next=0
elif count_i==(Divisor-1):
count_i.next=0
else:
count_i.next=count_i+1
clkOut_i=Signal(bool(0))
@always(clk.posedge, rst.posedge)
def clockTick():
if rst:
clkOut_i.next=0
elif count_i==(Divisor-1):
clkOut_i.next=not clkOut_i
else:
clkOut_i.next=clkOut_i
@always_comb
def OuputBuffer():
count.next=count_i
clkOut.next=clkOut_i
return instances()
Explanation: Application: Clock Divider
On common application in HDL for counters in build clock dividers. And while there are more specialized and advanced means to perform up or down frequency generation from a reference clock (see for example digital Phase Lock Loops). A simple clock divider is very useful HDL code to drive other HDL IPs that should/need a slower event rate than the Megahertz+ speeds of today's FPGAs
\begin{figure}
\centerline{\includegraphics[width=10cm]{}}
\caption{\label{fig:RP} ClockDivider Functianl Digram (ToDo) }
\end{figure}
End of explanation
Peeker.clear()
clk=Signal(bool(0)); Peeker(clk, 'clk')
Divisor=Signal(intbv(0)[32:]); Peeker(Divisor, 'Divisor')
count=Signal(intbv(0)[32:]); Peeker(count, 'count')
clkOut=Signal(bool(0)); Peeker(clkOut, 'clkOut')
rst=Signal(bool(0)); Peeker(rst, 'rst')
DUT=ClockDivider(Divisor, clkOut, count, clk,rst)
def ClockDividerTB():
myHDL only Testbench for `ClockDivider` module
@always(delay(1))
def ClkGen():
clk.next=not clk
@instance
def stimules():
for i in range(2,6+1):
Divisor.next=i
rst.next=0
#run clock time
for _ in range(4*2**(i-1)):
yield clk.posedge
for j in range(1):
if j==0:
rst.next=1
yield clk.posedge
raise StopSimulation()
return instances()
sim=Simulation(DUT, ClockDividerTB(), *Peeker.instances()).run()
Peeker.to_wavedrom()
ClockDividerData=Peeker.to_dataframe()
ClockDividerData
ClockDividerData_2=ClockDividerData[ClockDividerData['Divisor']==2]
ClockDividerData_2.reset_index(drop=True, inplace=True)
ClockDividerData_2.plot(y=['clk', 'clkOut']);
ClockDividerData_3=ClockDividerData[ClockDividerData['Divisor']==3]
ClockDividerData_3.reset_index(drop=True, inplace=True)
ClockDividerData_3.plot(y=['clk', 'clkOut']);
ClockDividerData_4=ClockDividerData[ClockDividerData['Divisor']==4]
ClockDividerData_4.reset_index(drop=True, inplace=True)
ClockDividerData_4.plot(y=['clk', 'clkOut']);
ClockDividerData_5=ClockDividerData[ClockDividerData['Divisor']==5]
ClockDividerData_5.reset_index(drop=True, inplace=True)
ClockDividerData_5.plot(y=['clk', 'clkOut']);
ClockDividerData_6=ClockDividerData[ClockDividerData['Divisor']==6]
ClockDividerData_6.reset_index(drop=True, inplace=True)
ClockDividerData_6.plot(y=['clk', 'clkOut']);
DUT.convert()
VerilogTextReader('ClockDivider');
Explanation: myHDL Testing
End of explanation
@block
def ClockDividerTBV():
myHDL -> Verilog Testbench for `ClockDivider` module
clk=Signal(bool(0));
Divisor=Signal(intbv(0)[32:])
count=Signal(intbv(0)[32:])
clkOut=Signal(bool(0))
rst=Signal(bool(0))
@always_comb
def print_data():
print(clk, Divisor, count, clkOut, rst)
DUT=ClockDivider(Divisor, clkOut, count, clk,rst)
@instance
def clk_signal():
while True:
clk.next = not clk
yield delay(1)
@instance
def stimules():
for i in range(2,6+1):
Divisor.next=i
rst.next=0
#run clock time
for _ in range(4*2**(i-1)):
yield clk.posedge
for j in range(1):
if j==0:
rst.next=1
else:
pass
yield clk.posedge
raise StopSimulation()
return instances()
TB=ClockDividerTBV()
TB.convert(hdl="Verilog", initial_values=True)
VerilogTextReader('ClockDividerTBV');
Explanation: Verilog Code
\begin{figure}
\centerline{\includegraphics[width=10cm]{ClockDividerRTL.png}}
\caption{\label{fig:clkDivRTL} ClockDivider RTL schematic; Xilinx Vivado 2017.4}
\end{figure}
\begin{figure}
\centerline{\includegraphics[width=10cm]{ClockDividerSYN.png}}
\caption{\label{fig:clkDivRTL} ClockDivider synthesized schematic; Xilinx Vivado 2017.4}
\end{figure}
Verilog Testbench
End of explanation |
7,988 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transfer Learning
Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instead, most people use a pretrained network either as a fixed feature extractor, or as an initial network to fine tune. In this notebook, you'll be using VGGNet trained on the ImageNet dataset as a feature extractor. Below is a diagram of the VGGNet architecture.
<img src="assets/cnnarchitecture.jpg" width=700px>
VGGNet is great because it's simple and has great performance, coming in second in the ImageNet competition. The idea here is that we keep all the convolutional layers, but replace the final fully connected layers with our own classifier. This way we can use VGGNet as a feature extractor for our images then easily train a simple classifier on top of that. What we'll do is take the first fully connected layer with 4096 units, including thresholding with ReLUs. We can use those values as a code for each image, then build a classifier on top of those codes.
You can read more about transfer learning from the CS231n course notes.
Pretrained VGGNet
We'll be using a pretrained network from https
Step1: Flower power
Here we'll be using VGGNet to classify images of flowers. To get the flower dataset, run the cell below. This dataset comes from the TensorFlow inception tutorial.
Step2: ConvNet Codes
Below, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier.
Here we're using the vgg16 module from tensorflow_vgg. The network takes images of size $224 \times 224 \times 3$ as input. Then it has 5 sets of convolutional layers. The network implemented here has this structure (copied from the source code)
Step3: Below I'm running images through the VGG network in batches.
Exercise
Step4: Building the Classifier
Now that we have codes for all the images, we can build a simple classifier on top of them. The codes behave just like normal input into a simple neural network. Below I'm going to have you do most of the work.
Step5: Data prep
As usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels!
Exercise
Step6: Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typically, you'll also want to make sure that each smaller set has the same the distribution of classes as it is for the whole data set. The easiest way to accomplish both these goals is to use StratifiedShuffleSplit from scikit-learn.
You can create the splitter like so
Step7: If you did it right, you should see these sizes for the training sets
Step9: Batches!
Here is just a simple way to do batches. I've written it so that it includes all the data. Sometimes you'll throw out some data at the end to make sure you have full batches. Here I just extend the last batch to include the remaining data.
Step10: Training
Here, we'll train the network.
Exercise
Step11: Testing
Below you see the test accuracy. You can also see the predictions returned for images.
Step12: Below, feel free to choose images and see how the trained classifier predicts the flowers in them. | Python Code:
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
vgg_dir = 'tensorflow_vgg/'
# Make sure vgg exists
if not isdir(vgg_dir):
raise Exception("VGG directory doesn't exist!")
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_size=None):
self.total = total_size
self.update((block_num - self.last_block) * block_size)
self.last_block = block_num
if not isfile(vgg_dir + "vgg16.npy"):
with DLProgress(unit='B', unit_scale=True, miniters=1, desc='VGG16 Parameters') as pbar:
urlretrieve(
'https://s3.amazonaws.com/content.udacity-data.com/nd101/vgg16.npy',
vgg_dir + 'vgg16.npy',
pbar.hook)
else:
print("Parameter file already exists!")
Explanation: Transfer Learning
Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instead, most people use a pretrained network either as a fixed feature extractor, or as an initial network to fine tune. In this notebook, you'll be using VGGNet trained on the ImageNet dataset as a feature extractor. Below is a diagram of the VGGNet architecture.
<img src="assets/cnnarchitecture.jpg" width=700px>
VGGNet is great because it's simple and has great performance, coming in second in the ImageNet competition. The idea here is that we keep all the convolutional layers, but replace the final fully connected layers with our own classifier. This way we can use VGGNet as a feature extractor for our images then easily train a simple classifier on top of that. What we'll do is take the first fully connected layer with 4096 units, including thresholding with ReLUs. We can use those values as a code for each image, then build a classifier on top of those codes.
You can read more about transfer learning from the CS231n course notes.
Pretrained VGGNet
We'll be using a pretrained network from https://github.com/machrisaa/tensorflow-vgg. Make sure to clone this repository to the directory you're working from. You'll also want to rename it so it has an underscore instead of a dash.
git clone https://github.com/machrisaa/tensorflow-vgg.git tensorflow_vgg
This is a really nice implementation of VGGNet, quite easy to work with. The network has already been trained and the parameters are available from this link. You'll need to clone the repo into the folder containing this notebook. Then download the parameter file using the next cell.
End of explanation
import tarfile
dataset_folder_path = 'flower_photos'
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_size=None):
self.total = total_size
self.update((block_num - self.last_block) * block_size)
self.last_block = block_num
if not isfile('flower_photos.tar.gz'):
with DLProgress(unit='B', unit_scale=True, miniters=1, desc='Flowers Dataset') as pbar:
urlretrieve(
'http://download.tensorflow.org/example_images/flower_photos.tgz',
'flower_photos.tar.gz',
pbar.hook)
if not isdir(dataset_folder_path):
with tarfile.open('flower_photos.tar.gz') as tar:
tar.extractall()
tar.close()
Explanation: Flower power
Here we'll be using VGGNet to classify images of flowers. To get the flower dataset, run the cell below. This dataset comes from the TensorFlow inception tutorial.
End of explanation
import os
import numpy as np
import tensorflow as tf
from tensorflow_vgg import vgg16
from tensorflow_vgg import utils
data_dir = 'flower_photos/'
contents = os.listdir(data_dir)
classes = [each for each in contents if os.path.isdir(data_dir + each)]
Explanation: ConvNet Codes
Below, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier.
Here we're using the vgg16 module from tensorflow_vgg. The network takes images of size $224 \times 224 \times 3$ as input. Then it has 5 sets of convolutional layers. The network implemented here has this structure (copied from the source code):
```
self.conv1_1 = self.conv_layer(bgr, "conv1_1")
self.conv1_2 = self.conv_layer(self.conv1_1, "conv1_2")
self.pool1 = self.max_pool(self.conv1_2, 'pool1')
self.conv2_1 = self.conv_layer(self.pool1, "conv2_1")
self.conv2_2 = self.conv_layer(self.conv2_1, "conv2_2")
self.pool2 = self.max_pool(self.conv2_2, 'pool2')
self.conv3_1 = self.conv_layer(self.pool2, "conv3_1")
self.conv3_2 = self.conv_layer(self.conv3_1, "conv3_2")
self.conv3_3 = self.conv_layer(self.conv3_2, "conv3_3")
self.pool3 = self.max_pool(self.conv3_3, 'pool3')
self.conv4_1 = self.conv_layer(self.pool3, "conv4_1")
self.conv4_2 = self.conv_layer(self.conv4_1, "conv4_2")
self.conv4_3 = self.conv_layer(self.conv4_2, "conv4_3")
self.pool4 = self.max_pool(self.conv4_3, 'pool4')
self.conv5_1 = self.conv_layer(self.pool4, "conv5_1")
self.conv5_2 = self.conv_layer(self.conv5_1, "conv5_2")
self.conv5_3 = self.conv_layer(self.conv5_2, "conv5_3")
self.pool5 = self.max_pool(self.conv5_3, 'pool5')
self.fc6 = self.fc_layer(self.pool5, "fc6")
self.relu6 = tf.nn.relu(self.fc6)
```
So what we want are the values of the first fully connected layer, after being ReLUd (self.relu6). To build the network, we use
with tf.Session() as sess:
vgg = vgg16.Vgg16()
input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])
with tf.name_scope("content_vgg"):
vgg.build(input_)
This creates the vgg object, then builds the graph with vgg.build(input_). Then to get the values from the layer,
feed_dict = {input_: images}
codes = sess.run(vgg.relu6, feed_dict=feed_dict)
End of explanation
# Set the batch size higher if you can fit in in your GPU memory
batch_size = 10
codes_list = []
labels = []
batch = []
codes = None
with tf.Session() as sess:
# TODO: Build the vgg network here
vgg = vgg16.Vgg16()
input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])
with tf.name_scope("content_vgg"):
vgg.build(input_)
for each in classes:
print("Starting {} images".format(each))
class_path = data_dir + each
files = os.listdir(class_path)
for ii, file in enumerate(files, 1):
# Add images to the current batch
# utils.load_image crops the input images for us, from the center
img = utils.load_image(os.path.join(class_path, file))
batch.append(img.reshape((1, 224, 224, 3)))
labels.append(each)
# Running the batch through the network to get the codes
if ii % batch_size == 0 or ii == len(files):
# Image batch to pass to VGG network
images = np.concatenate(batch)
# TODO: Get the values from the relu6 layer of the VGG network
feed_dict = {input_: images}
codes_batch = sess.run(vgg.relu6, feed_dict=feed_dict)
# Here I'm building an array of the codes
if codes is None:
codes = codes_batch
else:
codes = np.concatenate((codes, codes_batch))
# Reset to start building the next batch
batch = []
print('{} images processed'.format(ii))
# write codes to file
with open('codes', 'w') as f:
codes.tofile(f)
# write labels to file
import csv
with open('labels', 'w') as f:
writer = csv.writer(f, delimiter='\n')
writer.writerow(labels)
Explanation: Below I'm running images through the VGG network in batches.
Exercise: Below, build the VGG network. Also get the codes from the first fully connected layer (make sure you get the ReLUd values).
End of explanation
# read codes and labels from file
import csv
with open('labels') as f:
reader = csv.reader(f, delimiter='\n')
labels = np.array([each for each in reader if len(each) > 0]).squeeze()
with open('codes') as f:
codes = np.fromfile(f, dtype=np.float32)
codes = codes.reshape((len(labels), -1))
Explanation: Building the Classifier
Now that we have codes for all the images, we can build a simple classifier on top of them. The codes behave just like normal input into a simple neural network. Below I'm going to have you do most of the work.
End of explanation
from sklearn import preprocessing
lb = preprocessing.LabelBinarizer()
# lb.fit(labels)
labels_vecs = lb.fit_transform(labels) # Your one-hot encoded labels array here
Explanation: Data prep
As usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels!
Exercise: From scikit-learn, use LabelBinarizer to create one-hot encoded vectors from the labels.
End of explanation
from sklearn.model_selection import StratifiedShuffleSplit
ss = StratifiedShuffleSplit(n_splits=1, test_size=0.2)
for train_index, test_index in ss.split(codes, labels_vecs):
# print("TRAIN:", train_index, "TEST:", test_index)
train_x, test_x_full = codes[train_index], codes[test_index]
train_y, test_y_full = labels_vecs[train_index], labels_vecs[test_index]
# train_x, train_y =
splitting_idx = int(len(test_x_full)/2)
val_x, val_y = test_x_full[:splitting_idx],test_y_full[:splitting_idx]
test_x, test_y = test_x_full[splitting_idx:],test_y_full[splitting_idx:]
print("Train shapes (x, y):", train_x.shape, train_y.shape)
print("Validation shapes (x, y):", val_x.shape, val_y.shape)
print("Test shapes (x, y):", test_x.shape, test_y.shape)
Explanation: Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typically, you'll also want to make sure that each smaller set has the same the distribution of classes as it is for the whole data set. The easiest way to accomplish both these goals is to use StratifiedShuffleSplit from scikit-learn.
You can create the splitter like so:
ss = StratifiedShuffleSplit(n_splits=1, test_size=0.2)
Then split the data with
splitter = ss.split(x, y)
ss.split returns a generator of indices. You can pass the indices into the arrays to get the split sets. The fact that it's a generator means you either need to iterate over it, or use next(splitter) to get the indices. Be sure to read the documentation and the user guide.
Exercise: Use StratifiedShuffleSplit to split the codes and labels into training, validation, and test sets.
End of explanation
inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]])
labels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]])
# TODO: Classifier layers and operations
nn = tf.contrib.layers.fully_connected(inputs_, 512)
logits =tf.contrib.layers.fully_connected(nn, labels_vecs.shape[1] , activation_fn = None)# output layer logits
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels_)) # cross entropy loss
optimizer = tf.train.AdamOptimizer().minimize(cost) # training optimizer
# Operations for validation/test accuracy
predicted = tf.nn.softmax(logits)
correct_pred = tf.equal(tf.argmax(predicted, 1), tf.argmax(labels_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
Explanation: If you did it right, you should see these sizes for the training sets:
Train shapes (x, y): (2936, 4096) (2936, 5)
Validation shapes (x, y): (367, 4096) (367, 5)
Test shapes (x, y): (367, 4096) (367, 5)
Classifier layers
Once you have the convolutional codes, you just need to build a classfier from some fully connected layers. You use the codes as the inputs and the image labels as targets. Otherwise the classifier is a typical neural network.
Exercise: With the codes and labels loaded, build the classifier. Consider the codes as your inputs, each of them are 4096D vectors. You'll want to use a hidden layer and an output layer as your classifier. Remember that the output layer needs to have one unit for each class and a softmax activation function. Use the cross entropy to calculate the cost.
End of explanation
def get_batches(x, y, n_batches=10):
Return a generator that yields batches from arrays x and y.
batch_size = len(x)//n_batches
for ii in range(0, n_batches*batch_size, batch_size):
# If we're not on the last batch, grab data with size batch_size
if ii != (n_batches-1)*batch_size:
X, Y = x[ii: ii+batch_size], y[ii: ii+batch_size]
# On the last batch, grab the rest of the data
else:
X, Y = x[ii:], y[ii:]
# I love generators
yield X, Y
Explanation: Batches!
Here is just a simple way to do batches. I've written it so that it includes all the data. Sometimes you'll throw out some data at the end to make sure you have full batches. Here I just extend the last batch to include the remaining data.
End of explanation
saver = tf.train.Saver()
epochs = 50
batch_size = 10
iteration=0
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(epochs):
for batch_features, batch_labels in get_batches(train_x, train_y, batch_size):
sess.run(optimizer, feed_dict={
inputs_: batch_features,
labels_: batch_labels})
loss= sess.run(cost, feed_dict={
inputs_: batch_features,
labels_: batch_labels})
print("Epoch: {}/{}".format(epoch+1, epochs),
"Iteration: {}".format(iteration),
"Training loss: {:.5f}".format(loss))
iteration += 1
if iteration % 5 == 0:
feed = {inputs_: val_x,
labels_: val_y}
val_acc = sess.run(accuracy, feed_dict=feed)
print("Epoch: {}/{}".format(epoch, epochs),
"Iteration: {}".format(iteration),
"Validation Acc: {:.4f}".format(val_acc))
# TODO: Your training code here
saver.save(sess, "checkpoints/flowers.ckpt")
Explanation: Training
Here, we'll train the network.
Exercise: So far we've been providing the training code for you. Here, I'm going to give you a bit more of a challenge and have you write the code to train the network. Of course, you'll be able to see my solution if you need help. Use the get_batches function I wrote before to get your batches like for x, y in get_batches(train_x, train_y). Or write your own!
End of explanation
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
feed = {inputs_: test_x,
labels_: test_y}
test_acc = sess.run(accuracy, feed_dict=feed)
print("Test accuracy: {:.4f}".format(test_acc))
%matplotlib inline
import matplotlib.pyplot as plt
from scipy.ndimage import imread
Explanation: Testing
Below you see the test accuracy. You can also see the predictions returned for images.
End of explanation
test_img_path = 'flower_photos/roses/10894627425_ec76bbc757_n.jpg'
test_img = imread(test_img_path)
plt.imshow(test_img)
# Run this cell if you don't have a vgg graph built
if 'vgg' in globals():
print('"vgg" object already exists. Will not create again.')
else:
#create vgg
with tf.Session() as sess:
input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])
vgg = vgg16.Vgg16()
vgg.build(input_)
with tf.Session() as sess:
img = utils.load_image(test_img_path)
img = img.reshape((1, 224, 224, 3))
feed_dict = {input_: img}
code = sess.run(vgg.relu6, feed_dict=feed_dict)
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
feed = {inputs_: code}
prediction = sess.run(predicted, feed_dict=feed).squeeze()
plt.imshow(test_img)
plt.barh(np.arange(5), prediction)
_ = plt.yticks(np.arange(5), lb.classes_)
Explanation: Below, feel free to choose images and see how the trained classifier predicts the flowers in them.
End of explanation |
7,989 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Template for test
Step1: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using S, T, and Y Phosphorylation.
Included is N Phosphorylation however no benchmarks are available, yet.
Training data is from phospho.elm and benchmarks are from dbptm.
Note
Step2: Y Phosphorylation
Step3: T Phosphorylation | Python Code:
from pred import Predictor
from pred import sequence_vector
from pred import chemical_vector
Explanation: Template for test
End of explanation
par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
for i in par:
print("y", i)
y = Predictor()
y.load_data(file="Data/Training/clean_s_filtered.csv")
y.process_data(vector_function="sequence", amino_acid="S", imbalance_function=i, random_data=0)
y.supervised_training("bagging")
y.benchmark("Data/Benchmarks/phos.csv", "S")
del y
print("x", i)
x = Predictor()
x.load_data(file="Data/Training/clean_s_filtered.csv")
x.process_data(vector_function="sequence", amino_acid="S", imbalance_function=i, random_data=1)
x.supervised_training("bagging")
x.benchmark("Data/Benchmarks/phos.csv", "S")
del x
Explanation: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using S, T, and Y Phosphorylation.
Included is N Phosphorylation however no benchmarks are available, yet.
Training data is from phospho.elm and benchmarks are from dbptm.
Note: SMOTEEN seems to preform best
End of explanation
par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
for i in par:
print("y", i)
y = Predictor()
y.load_data(file="Data/Training/clean_Y_filtered.csv")
y.process_data(vector_function="sequence", amino_acid="Y", imbalance_function=i, random_data=0)
y.supervised_training("bagging")
y.benchmark("Data/Benchmarks/phos.csv", "Y")
del y
print("x", i)
x = Predictor()
x.load_data(file="Data/Training/clean_Y_filtered.csv")
x.process_data(vector_function="sequence", amino_acid="Y", imbalance_function=i, random_data=1)
x.supervised_training("bagging")
x.benchmark("Data/Benchmarks/phos.csv", "Y")
del x
Explanation: Y Phosphorylation
End of explanation
par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
for i in par:
print("y", i)
y = Predictor()
y.load_data(file="Data/Training/clean_t_filtered.csv")
y.process_data(vector_function="sequence", amino_acid="T", imbalance_function=i, random_data=0)
y.supervised_training("bagging")
y.benchmark("Data/Benchmarks/phos.csv", "T")
del y
print("x", i)
x = Predictor()
x.load_data(file="Data/Training/clean_t_filtered.csv")
x.process_data(vector_function="sequence", amino_acid="T", imbalance_function=i, random_data=1)
x.supervised_training("bagging")
x.benchmark("Data/Benchmarks/phos.csv", "T")
del x
Explanation: T Phosphorylation
End of explanation |
7,990 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Selecting variants by number of unique barcodes
This notebook gets scores for the variants in an Experiment that are linked to multiple barcodes, and plots the relationship between each variant's score and number of unique barcodes.
Step1: Modify the results_path variable in the next cell to match the output directory of your Enrich2-Example dataset.
Step2: Open the Experiment HDF5 file.
Step3: The pd.HDFStore.keys() method returns a list of all the tables in this HDF5 file.
Step4: First we will work with the barcode-variant map for this analysis, stored in the "/main/barcodemap" table. The index is the barcode and it has a single column for the variant HGVS string.
Step5: To find out how many unique barcodes are linked to each variant, we'll count the number of times each variant appears in the barcode-variant map using a Counter data structure. We'll then output the top ten variants by number of unique barcodes.
Step6: Next we'll turn the Counter into a data frame.
Step7: The data frame has the information we want, but it will be easier to use later if it's indexed by variant rather than row number.
Step8: We'll use a cutoff to choose variants with a minimum number of unique barcodes, and store this subset in a new index. We'll also exclude the wild type by dropping the first entry of the index.
Step9: We can use this index to get condition-level scores for these variants by querying the "/main/variants/scores" table. Since we are working with an Experiment HDF5 file, the data frame column names are a MultiIndex with two levels, one for experimental conditions and one for data values (see the pandas documentation for more information).
Step10: There are fewer rows in multi_bc_scores than in multi_bc_variants because some of the variants were not scored in all replicate selections, and therefore do not have a condition-level score.
Now that we're finished getting data out of the HDF5 file, we'll close it.
Step11: We'll add a column to the bc_counts data frame that contains scores from the multi_bc_scores data frame. To reference a column in a data frame with a MultiIndex, we need to specify all column levels.
Step12: Many rows in bc_counts are missing scores (displayed as NaN) because those variants were not in multi_bc_scores. We'll drop them before continuing.
Step13: Now that we have a data frame containing the subset of variants we're interested in, we can make a plot of score vs. number of unique barcodes. This example uses functions and colors from the Enrich2 plotting library. | Python Code:
% matplotlib inline
from __future__ import print_function
import os.path
from collections import Counter
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from enrich2.variant import WILD_TYPE_VARIANT
import enrich2.plots as enrich_plot
pd.set_option("display.max_rows", 10) # rows shown when pretty-printing
Explanation: Selecting variants by number of unique barcodes
This notebook gets scores for the variants in an Experiment that are linked to multiple barcodes, and plots the relationship between each variant's score and number of unique barcodes.
End of explanation
results_path = "/path/to/Enrich2-Example/Results/"
Explanation: Modify the results_path variable in the next cell to match the output directory of your Enrich2-Example dataset.
End of explanation
my_store = pd.HDFStore(os.path.join(results_path, "BRCA1_Example_exp.h5"))
Explanation: Open the Experiment HDF5 file.
End of explanation
my_store.keys()
Explanation: The pd.HDFStore.keys() method returns a list of all the tables in this HDF5 file.
End of explanation
bcm = my_store['/main/barcodemap']
bcm
Explanation: First we will work with the barcode-variant map for this analysis, stored in the "/main/barcodemap" table. The index is the barcode and it has a single column for the variant HGVS string.
End of explanation
variant_bcs = Counter(bcm['value'])
variant_bcs.most_common(10)
Explanation: To find out how many unique barcodes are linked to each variant, we'll count the number of times each variant appears in the barcode-variant map using a Counter data structure. We'll then output the top ten variants by number of unique barcodes.
End of explanation
bc_counts = pd.DataFrame(variant_bcs.most_common(), columns=['variant', 'barcodes'])
bc_counts
Explanation: Next we'll turn the Counter into a data frame.
End of explanation
bc_counts.index = bc_counts['variant']
bc_counts.index.name = None
del bc_counts['variant']
bc_counts
Explanation: The data frame has the information we want, but it will be easier to use later if it's indexed by variant rather than row number.
End of explanation
bc_cutoff = 10
multi_bc_variants = bc_counts.loc[bc_counts['barcodes'] >= bc_cutoff].index[1:]
multi_bc_variants
Explanation: We'll use a cutoff to choose variants with a minimum number of unique barcodes, and store this subset in a new index. We'll also exclude the wild type by dropping the first entry of the index.
End of explanation
multi_bc_scores = my_store.select('/main/variants/scores', where='index in multi_bc_variants')
multi_bc_scores
Explanation: We can use this index to get condition-level scores for these variants by querying the "/main/variants/scores" table. Since we are working with an Experiment HDF5 file, the data frame column names are a MultiIndex with two levels, one for experimental conditions and one for data values (see the pandas documentation for more information).
End of explanation
my_store.close()
Explanation: There are fewer rows in multi_bc_scores than in multi_bc_variants because some of the variants were not scored in all replicate selections, and therefore do not have a condition-level score.
Now that we're finished getting data out of the HDF5 file, we'll close it.
End of explanation
bc_counts['score'] = multi_bc_scores['E3', 'score']
bc_counts
Explanation: We'll add a column to the bc_counts data frame that contains scores from the multi_bc_scores data frame. To reference a column in a data frame with a MultiIndex, we need to specify all column levels.
End of explanation
bc_counts.dropna(inplace=True)
bc_counts
Explanation: Many rows in bc_counts are missing scores (displayed as NaN) because those variants were not in multi_bc_scores. We'll drop them before continuing.
End of explanation
fig, ax = plt.subplots()
enrich_plot.configure_axes(ax, xgrid=True)
ax.plot(bc_counts['barcodes'],
bc_counts['score'],
linestyle='none', marker='.', alpha=0.6,
color=enrich_plot.plot_colors['bright5'])
ax.set_xlabel("Unique Barcodes")
ax.set_ylabel("Variant Score")
Explanation: Now that we have a data frame containing the subset of variants we're interested in, we can make a plot of score vs. number of unique barcodes. This example uses functions and colors from the Enrich2 plotting library.
End of explanation |
7,991 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LSTM Time Series Example
Before we get into the example, let's talk about old fashioned computer memory. Mercury delay lines are an early form of computer memory. They basically recycled electrical signals until they where needed. They also could replace or reshape the signal with new information (i.e. forgeting the old information).
Image Source
Step1: Load Data
Unlike part 1, this example includes additional training features. These include the US unemployment rate and weather data for a yellowstone weather station.
Step2: Convert to Stationary Data
Like the visitors, the weather contains seasonal trends. We'll convert all the values to the changes over the last month. The differences remove the season trends from the dataset. This conversion from non-stationary to stationary helps model longer term changes.
Step3: Label Data
The label is the proceeding month's change in visitors. This makes the training set a supervised training set.
Step4: Split Training & Test Datasets
This step also scales the values between -1 and 1.
Step5: Define the Model
This network defines the following layers (excluding dropouts)
Step6: Optimizer
Unlike the first example, this model predicts a scalar value and not a class probability. Thus the loss function minimizes the mean square error.
Step7: Train the Model
Note
Step8: Create Predictions
To get the monthly visitors, We'll need to invert the scaling plus convert to absoult values.
Step9: Let's plot the results...
Step10: Did the LSTM work any better than the simple monthly average? | Python Code:
from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas import read_csv
from pandas import datetime
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.layers import GRU
from math import sqrt
from matplotlib import pyplot
import numpy
Explanation: LSTM Time Series Example
Before we get into the example, let's talk about old fashioned computer memory. Mercury delay lines are an early form of computer memory. They basically recycled electrical signals until they where needed. They also could replace or reshape the signal with new information (i.e. forgeting the old information).
Image Source: Delay Line Memory
Note: This tutorial is based on Time Series Forecasting with the Long Short-Term Memory Network in Python by Jason Brownlee.
Part 2 - Train LSTM
End of explanation
def parser(x):
return datetime.strptime(x, '%Y-%m-%d')
dataset = read_csv('../data/yellowstone-visitors-ur-weather.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
dataset.head()
Explanation: Load Data
Unlike part 1, this example includes additional training features. These include the US unemployment rate and weather data for a yellowstone weather station.
End of explanation
def difference(dataset, interval=1):
diff = list()
for i in range(interval, len(dataset)):
value = dataset[i] - dataset[i - interval]
diff.append(value)
return diff
diff_values = difference(dataset.values)
diff_df = DataFrame(diff_values, columns=dataset.columns.values)
diff_df.head()
Explanation: Convert to Stationary Data
Like the visitors, the weather contains seasonal trends. We'll convert all the values to the changes over the last month. The differences remove the season trends from the dataset. This conversion from non-stationary to stationary helps model longer term changes.
End of explanation
labels = diff_df['visitors'].rename(index='label')
shifted = diff_df.shift(1)
supervised = concat([shifted, labels], axis=1)
supervised.fillna(0, inplace=True)
supervised.head()
Explanation: Label Data
The label is the proceeding month's change in visitors. This makes the training set a supervised training set.
End of explanation
supervised_values = supervised.values
train, test = supervised_values[0:-12], supervised_values[-12:]
scaler = MinMaxScaler(feature_range=(-1, 1))
scaler = scaler.fit(train)
train = train.reshape(train.shape[0], train.shape[1])
train_scaled = scaler.transform(train)
test = test.reshape(test.shape[0], test.shape[1])
test_scaled = scaler.transform(test)
print('training set shape: {}'.format(train_scaled.shape))
print(train_scaled[0])
Explanation: Split Training & Test Datasets
This step also scales the values between -1 and 1.
End of explanation
batch_size = 1 # required for stateful LSTM
neurons = 20
features = 6
labels = 1
model = Sequential()
model.add(LSTM(neurons, batch_input_shape=(batch_size, 1, features), stateful=True))
model.add(Dense(features))
model.add(Dropout(0.5))
model.add(Dense(1))
Explanation: Define the Model
This network defines the following layers (excluding dropouts):
Stateful Long Short Term Memory (LSTM)
Hidden Dense Layer
Output Dense Layer
Long Short Term Memory
The north remebers and so do LSTMs... Until they forget on purpose.
LSTM maintain state over sequences. Unlike simple RNNs, LSTM can forget...
Image Source: Christopher Olah, Understanding LSTMs
Stateful vs Stateless LSTMs
Stateless LSTMs reinitialize the state after each batch. By default, Keras uses stateless LSTMs.
Stateful LSTMs retain memory across batches. model.reset_states() will clear out the state.
If the model uses a larger batch than this example, the Stateless LSTM could update the gradients more efficiently because the state is only maintained over one batch.
This example only uses a batch size of one, so a stateless LSTM will only remember one month. Not very helpful.
Dense Layers
The model adds a hidden layer because why not? The model also uses a single neuron for the layer output to predict next months visitors.
End of explanation
model.compile(loss='mean_squared_error', optimizer='adam')
Explanation: Optimizer
Unlike the first example, this model predicts a scalar value and not a class probability. Thus the loss function minimizes the mean square error.
End of explanation
nb_epoch = 300
X, y = train_scaled[:, 0:-1], train_scaled[:, -1]
X = X.reshape(X.shape[0], 1, X.shape[1])
for i in range(nb_epoch):
if(i % 50 == 0):
print(i)
model.fit(X, y, epochs=1, batch_size=batch_size, verbose=0, shuffle=False)
model.reset_states()
Explanation: Train the Model
Note: Stateful models update gradients for previous batches. Get a cup of coffee...
End of explanation
# inverse scaling for a forecasted value
def invert_scale(scaler, X, value):
new_row = [x for x in X] + [value]
array = numpy.array(new_row)
array = array.reshape(1, len(array))
inverted = scaler.inverse_transform(array)
return inverted[0, -1]
visitor_history = dataset['visitors'].values
predictions = list()
for i in range(len(test_scaled)):
X, y = test_scaled[i, 0:-1], test_scaled[i, -1]
X = X.reshape(1, 1, len(X))
scaled_pred = model.predict(X, batch_size=batch_size)
visitor_delta = invert_scale(scaler, X[0,0], scaled_pred[0,0])
prev_mon_vistitor = visitor_history[-len(test_scaled)+1-i]
pred = prev_mon_vistitor + visitor_delta
expected = visitor_history[len(test_scaled) + i + 1]
print('Month=%d, Predicted=%f, Expected=%f' % (i+1, pred, expected))
predictions.append(pred)
Explanation: Create Predictions
To get the monthly visitors, We'll need to invert the scaling plus convert to absoult values.
End of explanation
pyplot.plot(visitor_history[-12:])
pyplot.plot(predictions)
pyplot.show()
Explanation: Let's plot the results...
End of explanation
rmse = sqrt(mean_squared_error(visitor_history[-12:], predictions))
print('Test RMSE: %.3f' % rmse)
Explanation: Did the LSTM work any better than the simple monthly average?
End of explanation |
7,992 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VARMAX models
This is a brief introduction notebook to VARMAX models in Statsmodels. The VARMAX model is generically specified as
Step1: Model specification
The VARMAX class in Statsmodels allows estimation of VAR, VMA, and VARMA models (through the order argument), optionally with a constant term (via the trend argument). Exogenous regressors may also be included (as usual in Statsmodels, by the exog argument), and in this way a time trend may be added. Finally, the class allows measurement error (via the measurement_error argument) and allows specifying either a diagonal or unstructured innovation covariance matrix (via the error_cov_type argument).
Example 1
Step2: From the estimated VAR model, we can plot the impulse response functions of the endogenous variables.
Step3: Example 2
Step4: Caution | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
dta = sm.datasets.webuse('lutkepohl2', 'http://www.stata-press.com/data/r12/')
dta.index = dta.qtr
endog = dta.ix['1960-04-01':'1978-10-01', ['dln_inv', 'dln_inc', 'dln_consump']]
Explanation: VARMAX models
This is a brief introduction notebook to VARMAX models in Statsmodels. The VARMAX model is generically specified as:
$$
y_t = \nu + A_1 y_{t-1} + \dots + A_p y_{t-p} + B x_t + \epsilon_t +
M_1 \epsilon_{t-1} + \dots M_q \epsilon_{t-q}
$$
where $y_t$ is a $\text{k_endog} \times 1$ vector.
End of explanation
exog = endog['dln_consump']
mod = sm.tsa.VARMAX(endog[['dln_inv', 'dln_inc']], order=(2,0), trend='nc', exog=exog)
res = mod.fit(maxiter=1000, disp=False)
print(res.summary())
Explanation: Model specification
The VARMAX class in Statsmodels allows estimation of VAR, VMA, and VARMA models (through the order argument), optionally with a constant term (via the trend argument). Exogenous regressors may also be included (as usual in Statsmodels, by the exog argument), and in this way a time trend may be added. Finally, the class allows measurement error (via the measurement_error argument) and allows specifying either a diagonal or unstructured innovation covariance matrix (via the error_cov_type argument).
Example 1: VAR
Below is a simple VARX(2) model in two endogenous variables and an exogenous series, but no constant term. Notice that we needed to allow for more iterations than the default (which is maxiter=50) in order for the likelihood estimation to converge. This is not unusual in VAR models which have to estimate a large number of parameters, often on a relatively small number of time series: this model, for example, estimates 27 parameters off of 75 observations of 3 variables.
End of explanation
ax = res.impulse_responses(10, orthogonalized=True).plot(figsize=(13,3))
ax.set(xlabel='t', title='Responses to a shock to `dln_inv`');
Explanation: From the estimated VAR model, we can plot the impulse response functions of the endogenous variables.
End of explanation
mod = sm.tsa.VARMAX(endog[['dln_inv', 'dln_inc']], order=(0,2), error_cov_type='diagonal')
res = mod.fit(maxiter=1000, disp=False)
print(res.summary())
Explanation: Example 2: VMA
A vector moving average model can also be formulated. Below we show a VMA(2) on the same data, but where the innovations to the process are uncorrelated. In this example we leave out the exogenous regressor but now include the constant term.
End of explanation
mod = sm.tsa.VARMAX(endog[['dln_inv', 'dln_inc']], order=(1,1))
res = mod.fit(maxiter=1000, disp=False)
print(res.summary())
Explanation: Caution: VARMA(p,q) specifications
Although the model allows estimating VARMA(p,q) specifications, these models are not identified without additional restrictions on the representation matrices, which are not built-in. For this reason, it is recommended that the user proceed with error (and indeed a warning is issued when these models are specified). Nonetheless, they may in some circumstances provide useful information.
End of explanation |
7,993 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <div style="background
Step2: <div style="background
Step3: <div style="background
Step4: <div style="background
Step5: <div style="background
Step6: <div style="background
Step7: <div style="background
Step8: <div style="background
Step9: <div style="background
Step10: <div style="background
Step11: <div style="background | Python Code:
from IPython.display import Javascript,display
from corticalmapping.ipython_lizard.html_widgets import raw_code_toggle
raw_code_toggle()
display(Javascript(var nb = IPython.notebook;
//var is_code_cell = (nb.get_selected_cell().cell_type == 'code')
//var curr_idx = (nb.get_selected_index() == 3);
nb.select(3);
nb.execute_cell();
))
from IPython.display import Javascript
from corticalmapping.ipython_lizard.ipython_filedialog import IPythonTkinterFileDialog
initial_dir = r"C:"
tkinter_file_dialog = IPythonTkinterFileDialog(initial_dir)
tkinter_file_dialog.execute_below = True
tkinter_file_dialog.show()
import os
from PyQt4 import QtGui,QtCore
import matplotlib.pyplot as plt
import matplotlib as mpl
from warnings import warn
#mpl.rcParams['figure.figsize'] = 10, 10
from corticalmapping import ipython_lizard
from corticalmapping.ipython_lizard.wrapped_retinotopic_mapping import WrappedRetinotopicMapping
from corticalmapping.ipython_lizard.patchplot_ipywidgets import PatchPlotWidgets
from corticalmapping.ipython_lizard.html_widgets import getSignMapWidget,getRawPatchMapWidget,getRawPatchesWidget, \
splitPatchesWidget,mergePatchesWidget,getEccentricityMapWidget, \
saveFinalResultWidget,submitAndRunBelowButton
%matplotlib inline
#%load_ext autoreload
#%autoreload 2
pkl_path = tkinter_file_dialog.file_path
TEST_PKL_IDX = 0
TEST_PATH = ipython_lizard.TEST_PKLS[TEST_PKL_IDX] #there are like 6 different test pkls in this iterable
current_dir = os.getcwd()
adj_pkl_paths = [os.path.join(current_dir,f) for f in os.listdir(current_dir) if f.endswith("pkl")]
if adj_pkl_paths:
adj_pkl_path = adj_pkl_paths[0]
else:
adj_pkl_path = None
pkls = zip(["MANUAL","ADJACENT","TEST"],[pkl_path,adj_pkl_path,TEST_PATH])
for p_type,pkl in pkls:
try:
trial = WrappedRetinotopicMapping.load_from_pkl(pkl)
print "Successfully loaded from: {0}, {1}".format(p_type,pkl)
__pkl_path = pkl
break
except Exception as e:
#warn(str(e))
warn("Failed to load from: {0}, {1}".format(p_type,pkl))
Explanation: <div style="background:red;color:white;border:2px solid black;border-radius:5px;">
<br>
<b><i><font size=3> Standard usage:</font></i></b>
<ul>
<li>Requires Jupyter 3.0 and ipywidgets (type "pip install ipywidgets" in windows command line.)</li>
<li>Copy this notebook to your desired location.</li>
<li>Do not modify the first 4 cells in this notebook.</li>
<li>Run the raw code toggle cell (code cell #1)</li>
<li>Select a pkl with the "Get File Path" button. <b>It is recommended to have only one pkl file in a given folder!</b></li>
<li>Once the pkl file has been chosen, the notebook will run all the cells automatically.</li>
<li>Adjust the parameters with the sliding bar to get desired results. <b>Make sure to hit the "submit changes and rerun below cells" button after each change.</b></li>
<li>Make sure to hit "save all" button when you are done. Standardized the results will be saved into the same folder containing the pkl file.</li>
</ul>
<br>
</div>
<div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Raw code toggle</font></i></b>
<hr>
<ul>
<li>If code is hidden and you don't see a button, click the hidden cell right below this cell and run it</li>
<ul>
<li>It's very thin and between this cell and the "Get File Path" cell, sorry for the inconvenience</li>
</ul>
</ul>
<br>
</div>
End of explanation
phaseMapFilterSigma = 1.0
signMapFilterSigma = 9.0
getSignMapWidget(trial,
phaseMapFilterSigmaDefault=phaseMapFilterSigma,
signMapFilterSigmaDefault=signMapFilterSigma,
)
submitAndRunBelowButton()
Explanation: <div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Calculate sign map</font></i></b>
<hr>
<b><i><font size=3> phaseMapFilterSigma:</font></i></b>
<ul>
<li>The sigma value of Gaussian filter for altitude and azimuth maps</li>
<li>FLOAT, default = 1.0, recommended range: [0.0, 2.0]</li>
<li>Large "phaseMapFilterSigma" gives you more patches</li>
<li>Small "phaseMapFilterSigma" gives you less patches</li>
</ul>
<br>
<b><i><font size=3> signMapFilterSigma:</font></i></b>
<ul>
<li>The sigma value of Gaussian filter for visual sign maps</li>
<li>FLOAT, default = 9.0, recommended range: [0.6, 10.0]</li>
<li>Large "signMapFilterSigma" gives you less patches</li>
<li>Small "signMapFilterSigma" gives you more patches</li>
</ul>
<br>
</div>
End of explanation
signMapThr = 0.35
openIter = 3
closeIter = 3
getRawPatchMapWidget(trial,
signMapThrDefault=signMapThr,
openIterDefault=openIter,
closeIterDefault=closeIter,
)
submitAndRunBelowButton()
Explanation: <div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Get raw patch map</font></i></b>
<hr>
<b><i><font size=3> signMapThr:</font></i></b>
<ul>
<li>Threshold to binarize visual signmap</li>
<li>FLOAT, default = 0.35, recommended range: [0.2, 0.5]</li>
<li>Large signMapThr gives you fewer patches</li>
<li>Smaller signMapThr gives you more patches</li>
</ul>
<br>
<b><i><font size=3> closeIter:</font></i></b>
<ul>
<li>Binary close iteration for each raw patches</li>
<li>INT, default = 3</li>
<li>You do not want to change this parameter very often</li>
</ul>
<br>
<b><i><font size=3> openIter:</font></i></b>
<ul>
<li>Binary open iteration for each raw patches</li>
<li>INT, default = 3</li>
<li>You do not want to change this parameter very often</li>
</ul>
<br>
</div>
End of explanation
dilationIter = 15
borderWidth = 1
smallPatchThr = 100
getRawPatchesWidget(trial,
dilationIterDefault=dilationIter,
borderWidthDefault=borderWidth,
smallPatchThrDefault=smallPatchThr,
)
submitAndRunBelowButton()
Explanation: <div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Get dictionary for raw patches</font></i></b>
<hr>
<b><i><font size=3> dilationIter:</font></i></b>
<ul>
<li>Binary dilation iteration for each raw patches</li>
<li>INT, default = 15</li>
<li>You do not want to change this parameter very often</li>
</ul>
<br>
<b><i><font size=3> borderWidth:</font></i></b>
<ul>
<li>Pixel number between adjcent patches</li>
<li>INT, default = 1</li>
<li>You do not want to change this parameter very often</li>
</ul>
<br>
<b><i><font size=3> smallPatchThr:</font></i></b>
<ul>
<li>The patches with pixel number below this number will be discarded</li>
<li>INT, default = 100</li>
<li>You do not want to change this parameter very often</li>
</ul>
<br>
</div>
End of explanation
trial.getDeterminantMap()
Explanation: <div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Calculate determinant map</font></i></b>
<hr>
<br>
</div>
End of explanation
eccMapFilterSigma = 10.0
getEccentricityMapWidget(trial,eccMapFilterSigmaDefault=eccMapFilterSigma)
submitAndRunBelowButton()
Explanation: <div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Calculate eccentricity map</font></i></b>
<hr>
<b><i><font size=3> eccMapFilterSigma:</font></i></b>
<ul>
<li>The sigma value of Gaussian filter for eccentricity maps</li>
<li>FLOAT, default = 10.0</li>
<li>You do not want to change this parameter very often, and it may take some time to run</li>
</ul>
<br>
</div>
End of explanation
visualSpacePixelSize = 0.5
visualSpaceCloseIter = 15
splitLocalMinCutStep = 5.0
splitOverlapThr = 1.2
splitPatchesWidget(trial,
visualSpacePixelSizeDefault=visualSpacePixelSize,
visualSpaceCloseIterDefault=visualSpaceCloseIter,
splitLocalMinCutStepDefault=splitLocalMinCutStep,
splitOverlapThrDefault=splitOverlapThr
)
submitAndRunBelowButton()
Explanation: <div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Split overlapping patches</font></i></b>
<hr>
<b><i><font size=3> visualSpacePixelSize:</font></i></b>
<ul>
<li>The pixel size for patch to visual space mapping</li>
<li>FLOAT, default = 0.5</li>
<li>You do not want to change this parameter very often</li>
</ul>
<br>
<b><i><font size=3> visualSpaceCloseIter:</font></i></b>
<ul>
<li>The binary iteration for visual space coverage for each patch</li>
<li>INT, default = 15</li>
<li>You do not want to change this parameter very often</li>
</ul>
<br>
<b><i><font size=3> splitLocalMinCutStep:</font></i></b>
<ul>
<li>The step width for detecting number of local minimums during spliting</li>
<li>FLOAT, default = 5.0, recommend range: [0.5, 15.0]</li>
<li>Small "splitLocalMinCutStep" will make it more likely to split but into less sub patches</li>
<li>Large "splitLocalMinCutStep" will make it less likely to split but into more sub patches</li>
</ul>
<br>
<b><i><font size=3> splitOverlapThr:</font></i></b>
<ul>
<li>Patches with overlap ration larger than this value will go through the split procedure</li>
<li>FLOAT, default = 1.1, recommend range: [1.0, 1.2], should be larger than 1.0</li>
<li>Small "splitOverlapThr" will split more patches</li>
<li>Large "splitOverlapThr" will split less patches</li>
</ul>
<br>
</div>
End of explanation
mergeOverlapThr = 0.1
mergePatchesWidget(trial,mergeOverlapThrDefault=mergeOverlapThr)
submitAndRunBelowButton()
Explanation: <div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Merge non-overlapping patches</font></i></b>
<hr>
<b><i><font size=3> mergeOverlapThr:</font></i></b>
<ul>
<li>Considering a patch pair (A and B) with same sign, A has visual coverage a deg<sup>2</sup> and B has visual coverage b deg<sup>2</sup></li>
<li>The overlaping visual coverage between this pair is c deg<sup>2</sup></li>
<li>Then if (c/a < "mergeOverlapThr") and (c/b < "mergeOverlapThr"), these two patches will be merged</li>
<li>FLOAT, default = 0.1, recommend range: [0.0, 0.2], should be smaller than 1.0</li>
<li>Small "mergeOverlapThr" will merge less patches</li>
<li>Large "mergeOverlapThr" will merge more patches</li>
</ul>
<br>
</div>
End of explanation
patchplot_widgets = PatchPlotWidgets(trial,{},[],figsize=(5,5))
patchplot_widgets.plot_reference_img()
rename_patches_dict = dict(trial.finalPatches)
DESIRED_PATCH_NAMES = ['A','AL','AM','LI','LLA','LM','M','MMA','MMP','P','PM','POR','RL','RLL','RS','S1','V1']
for patch in rename_patches_dict.keys(): #replace 'patch01' with 01, etc
rename_patches_dict[patch.replace("patch","")] = rename_patches_dict.pop(patch)
patchplot_widgets = PatchPlotWidgets(trial,rename_patches_dict,DESIRED_PATCH_NAMES,figsize=(12,6))
patchplot_widgets.show()
submitAndRunBelowButton()
Explanation: <div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Rename patches</font></i></b>
<hr>
<ul>
<li>Click the patches and type their desired names according to the reference map below</li>
<li>Established visual area names:</li>
<ul>
<li>A, AL, AM, LI, LLA, LM, M, MMA, MMP, P, PM, POR, RL, RLL, RS, S1, V1</li>
</ul>
<li>The name you typed within this list will show in green, others will show in orange</li>
</ul>
<br>
</div>
End of explanation
rename_patches_dict = patchplot_widgets.patches_dict
finalPatchBorder_figure = trial.plotFinalPatchBorders(rename_patches_dict,borderWidth=4)
Explanation: <div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Plot final borders</font></i></b>
<hr>
<br>
</div>
End of explanation
pkl_save_path = None
#saveTrialDictPkl(trial,pkl_save_path)
saveFinalResultWidget(trial,finalPatchBorder_figure,__pkl_path,pkl_save_path)
Explanation: <div style="background:#6699FF;color:#FFDDBB;border:1px solid #87868A;border-radius:5px;">
<br>
<b><i><font size=3> Save</font></i></b>
<hr>
<ul>
<li>Saves the following to the directory containing the original pkl file:</li>
<ul>
<li>final borders plot (.png & .pdf)</li>
<li>updated pkl file</li>
<li>the current notebook (.ipynb & .html)</li>
</ul>
</ul>
<br>
</div>
End of explanation |
7,994 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transfer Learning and Fine Tuning
Train a simple convnet on the MNIST dataset the first 5 digits [0..4].
Freeze convolutional layers and fine-tune dense layers for the classification of digits [5..9].
Using GPU (highly recommended)
-> If using theano backend
Step1: Settings
Step2: Dataset Preparation
Step3: Your Turn
Try to Fine Tune a VGG16 Network | Python Code:
import numpy as np
import datetime
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
from numpy import nan
now = datetime.datetime.now
Explanation: Transfer Learning and Fine Tuning
Train a simple convnet on the MNIST dataset the first 5 digits [0..4].
Freeze convolutional layers and fine-tune dense layers for the classification of digits [5..9].
Using GPU (highly recommended)
-> If using theano backend:
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32
End of explanation
now = datetime.datetime.now
batch_size = 128
nb_classes = 5
nb_epoch = 5
# input image dimensions
img_rows, img_cols = 28, 28
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = 2
# convolution kernel size
kernel_size = 3
if K.image_data_format() == 'channels_first':
input_shape = (1, img_rows, img_cols)
else:
input_shape = (img_rows, img_cols, 1)
def train_model(model, train, test, nb_classes):
X_train = train[0].reshape((train[0].shape[0],) + input_shape)
X_test = test[0].reshape((test[0].shape[0],) + input_shape)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(train[1], nb_classes)
Y_test = np_utils.to_categorical(test[1], nb_classes)
model.compile(loss='categorical_crossentropy',
optimizer='adadelta',
metrics=['accuracy'])
t = now()
model.fit(X_train, Y_train,
batch_size=batch_size, nb_epoch=nb_epoch,
verbose=1,
validation_data=(X_test, Y_test))
print('Training time: %s' % (now() - t))
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])
Explanation: Settings
End of explanation
# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# create two datasets one with digits below 5 and one with 5 and above
X_train_lt5 = X_train[y_train < 5]
y_train_lt5 = y_train[y_train < 5]
X_test_lt5 = X_test[y_test < 5]
y_test_lt5 = y_test[y_test < 5]
X_train_gte5 = X_train[y_train >= 5]
y_train_gte5 = y_train[y_train >= 5] - 5 # make classes start at 0 for
X_test_gte5 = X_test[y_test >= 5] # np_utils.to_categorical
y_test_gte5 = y_test[y_test >= 5] - 5
# define two groups of layers: feature (convolutions) and classification (dense)
feature_layers = [
Convolution2D(nb_filters, kernel_size, kernel_size,
border_mode='valid',
input_shape=input_shape),
Activation('relu'),
Convolution2D(nb_filters, kernel_size, kernel_size),
Activation('relu'),
MaxPooling2D(pool_size=(pool_size, pool_size)),
Dropout(0.25),
Flatten(),
]
classification_layers = [
Dense(128),
Activation('relu'),
Dropout(0.5),
Dense(nb_classes),
Activation('softmax')
]
# create complete model
model = Sequential(feature_layers + classification_layers)
# train model for 5-digit classification [0..4]
train_model(model,
(X_train_lt5, y_train_lt5),
(X_test_lt5, y_test_lt5), nb_classes)
# freeze feature layers and rebuild model
for l in feature_layers:
l.trainable = False
# transfer: train dense layers for new classification task [5..9]
train_model(model,
(X_train_gte5, y_train_gte5),
(X_test_gte5, y_test_gte5), nb_classes)
Explanation: Dataset Preparation
End of explanation
## your code here
Explanation: Your Turn
Try to Fine Tune a VGG16 Network
End of explanation |
7,995 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Building a Scheme Interpreter
Consider using Python to turn the string "(+ 1 2)" into the actual number 3. How does that happen? This question is really
Step4: Exercise 1
Step6: Exercise 2
Step7: That's it?! Yes, but we need to define some things before that will run. We need to define
Step8: An improper list, the dotted pair
Step9: Make sure that car and cdr can deconstruct a cons cell
Step10: And, a convenience method for constructing Scheme-like lists of multiple items
Step11: Exercise 3
Step12: We'll be doing those three functions together quite often, so let's make a useful function
Step13: Exercise 4 | Python Code:
def tokenizer(string):
Takes a string and segments it into parts.
We break strings up by brackets, and whitespace.
Returns a Python list of strings.
retval = []
current = ""
for i in range(len(string)):
if string[i] in ["(", "[", ")", "]"]:
if current:
retval.append(current)
current = ""
retval.append(string[i])
elif string[i] in [" ", "\t", "\n"]:
if current:
retval.append(current)
current = ""
else:
current += string[i]
if current:
retval.append(current)
return retval
tokenizer((this is a
3.14
(test)))
Explanation: Building a Scheme Interpreter
Consider using Python to turn the string "(+ 1 2)" into the actual number 3. How does that happen? This question is really: what does a programming language do? How does it work? In this chapter, we will answer these questions by building a Scheme interpreter in Python.
Two Steps: Parse and Interpret
In designing a programming language, we break down the process into two steps:
STEP 1: The first step in implementing a programming language is to take a plain string and turn it into what is commonly called an Abstract Syntax Tree, or AST for short. This process is called parsing. ASTs are data structures.
STEP 2: The second step is to build an evaluator that takes ASTs and interprets them. This is called interpreting.
We will now go through the steps of designing a language. As this language will start off as a simple calculator with the syntax looking like Scheme, we'll call this language S-Calc, short for Scheme Calculator.
Parsing
To build a function that will take a string and produce AST, we further break down the parsing into three stages. We could do this all in one function, but it is common to break the process up into smaller chunks to make processing (and understanding/debugging) easier. The three components are:
tokenize - turns a string into tokens
reader - take the tokens and group them
parser - turn the segmented parts into AST
The idea is that we can then take our string "(+ 1 2)" and end up with AST, like so:
python
parser(reader(tokenize("(+ 1 1)")))
The form of the AST can really be any data structure that we decide. For these experiments, we will use very simple Scheme expressions (called s-exp). Thus, the above string might look like this in Scheme:
scheme
(apply-exp
(var-exp +)
((lit-exp 1) (lit-exp 2)))
That is, it is an application-expression composed of the operator (a variable-expression '+') and two literal-expressions 1 and 2 as operands.
We call the syntax of the string the Concrete Syntax as compared to the Abstract Syntax of the AST.
As we have seen, Scheme is a simple language composed of lists, symbols, strings, and numbers. Everything in the language can be parsed into those components, so writing a Scheme parser is pretty easy compared to languages like Python.
Tokenize
To parse S-Calc we first define the lowest level of the process, the tokenizer:
End of explanation
def reader(texp):
Takes the output of the tokenizer, and creates
lists of lists of items. Numbers are represented
as numbers.
current = None
stack = []
for item in texp:
if item.isdigit():
if current is not None:
current.append(eval(item))
else:
current = eval(item)
elif item in ["[", "("]:
if current is not None:
stack.append(current)
current = []
elif item in ["]", ")"]:
if stack:
stack[-1].append(current)
current = stack.pop(-1)
else:
pass
else:
if current is not None:
current.append(item)
else:
current = item
return current
tokenizer("(this is (a) ((list))")
reader(tokenizer("(this is (a) ((list))"))
Explanation: Exercise 1: Try the tokenizer on many different strings. Describe what it does in simple terms based on its input and output.
Reader
The reader will take the tokenized expression (texp) and produced grouped results.
End of explanation
## Version 1:
def parser(rexp):
Reads in a Python list of things, and returns an AST.
if isinstance(rexp, int):
return lit_exp(rexp)
elif isinstance(rexp, str):
return var_exp(rexp)
else:
return app_exp(parser(rexp[0]), List(*map(parser, rexp[1:])))
Explanation: Exercise 2: Try the reader on many different tokenized strings. Describe what it does in simple terms. How does this differ from the lexer?
Parser
The final process of Step 1 is to take the output of the reader and parse it into an AST. For our first S-Calc expression, we just need to handle "(+ 1 2)". That is, we need to handle three things:
numbers - any kind of number
variables, like "+" - anything not a number
application - starts with a parenthesis
End of explanation
EmptyList = "()"
def cons(item1, item2):
return [item1, item2]
def car(exp):
return exp[0]
def cdr(exp):
return exp[1]
def cadr(exp):
return exp[1][0]
def cddr(exp):
return exp[1][1]
def caddr(exp):
return exp[1][1][0]
def List(*args):
"Create a linked-list of items"
retval = EmptyList
for arg in reversed(args):
retval = cons(arg, retval)
return retval
Explanation: That's it?! Yes, but we need to define some things before that will run. We need to define:
list_exp
var_exp
app_exp
To think like a Little Schemer, we define some utility functions in Python so that we can write code as if we were in Scheme. Specifically, let's replicate the linked-list of cons/car/cdr:
End of explanation
cons(1, 2)
Explanation: An improper list, the dotted pair:
End of explanation
car(cons(1, 2))
cdr(cons(1, 2))
Explanation: Make sure that car and cdr can deconstruct a cons cell:
End of explanation
List(1, 2, 3, 4)
Explanation: And, a convenience method for constructing Scheme-like lists of multiple items:
End of explanation
def lit_exp(value):
return List("lit-exp", value)
def var_exp(symbol):
return List("var-exp", symbol)
def app_exp(f, args):
return List("apply-exp", f, args)
parser(reader(tokenizer("1")))
parser(reader(tokenizer("+")))
parser(reader(tokenizer("(+ 1 2)")))
Explanation: Exercise 3: Why does the list above look like this? Is this similar to how Scheme lists exist? Explain.
Now, we can compose our AST constructor functions:
End of explanation
def scalc_parse(string):
return parser(reader(tokenizer(string)))
scalc_parse("652362")
Explanation: We'll be doing those three functions together quite often, so let's make a useful function:
End of explanation
## Version 1:
def evaluator(expr):
if car(expr) == "lit-exp":
return cadr(expr)
elif car(expr) == "var-exp":
return cadr(expr) ## for now, return symbol
elif car(expr) == "apply-exp":
return evaluator_apply(evaluator(cadr(expr)),
Map(evaluator, caddr(expr)))
else:
raise Exception("invalid ast: %s" % expr)
def evaluator_apply(op, operands):
if op == "print":
Print(operands)
elif op == "+":
return car(operands) + cadr(operands)
else:
raise Exception("unknown apply operator: %s" % op)
def Map(f, slist):
if slist == EmptyList:
return EmptyList
else:
return cons( f(car(slist)), Map(f, cdr(slist))) ## recursive!
def Print(slist):
if slist == EmptyList:
return
else:
print(car(slist))
Print(cdr(slist))
Map(lambda v: v, List(1, 2, 3))
expr = scalc_parse("3")
evaluator(expr)
def scalc(string):
return evaluator(scalc_parse(string))
scalc("34")
scalc("(+ 1 1)")
scalc("(print 1 2 3)")
scalc("(+ 1 (+ 100 10))")
Explanation: Exercise 4: Try out the scalc_parser. Can it handle nested mathematical expressions? Why? How does the parser handle recursive expressions?
Interpreter
Now we are ready for Step 2: the interpreter. This function takes an AST expression and interprets it (i.e., gives a result). We will call our interpreter evaluator.
Again, as we only have numbers, symbols, and applications, it only needs to handle those three items. To help with debugging, we will also now add a print application.
End of explanation |
7,996 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integration Exercise 1
Imports
Step2: Trapezoidal rule
The trapezoidal rule generates a numerical approximation to the 1d integral
Step3: Now use scipy.integrate.quad to integrate the f and g functions and see how the result compares with your trapz function. Print the results and errors. | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate
Explanation: Integration Exercise 1
Imports
End of explanation
def trapz(f, a, b, N):
Integrate the function f(x) over the range [a,b] with N points.
x = np.linspace(a,b,N+1)
h = np.diff(x)[1]
y = f(x)
m = .5 * (y[1:(len(y)-1)] + y[2:])
a = sum(h * m)
return(a)
np.linspace(0,1,2)
trapz(f, 0, 1, 1000)
f = lambda x: x**2
g = lambda x: np.sin(x)
I = trapz(f, 0, 1, 1000)
assert np.allclose(I, 0.33333349999999995)
J = trapz(g, 0, np.pi, 1000)
assert np.allclose(J, 1.9999983550656628)
Explanation: Trapezoidal rule
The trapezoidal rule generates a numerical approximation to the 1d integral:
$$ I(a,b) = \int_a^b f(x) dx $$
by dividing the interval $[a,b]$ into $N$ subdivisions of length $h$:
$$ h = (b-a)/N $$
Note that this means the function will be evaluated at $N+1$ points on $[a,b]$. The main idea of the trapezoidal rule is that the function is approximated by a straight line between each of these points.
Write a function trapz(f, a, b, N) that performs trapezoidal rule on the function f over the interval $[a,b]$ with N subdivisions (N+1 points).
End of explanation
integrate.quad(f,0,1)[0] - trapz(f, 0, 1, 1000)
integrate.quad(g,0, np.pi)[0] - trapz(g,0,np.pi, 1000)
assert True # leave this cell to grade the previous one
Explanation: Now use scipy.integrate.quad to integrate the f and g functions and see how the result compares with your trapz function. Print the results and errors.
End of explanation |
7,997 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute power and phase lock in label of the source space
Compute time-frequency maps of power and phase lock in the source space.
The inverse method is linear based on dSPM inverse operator.
The example also shows the difference in the time-frequency maps
when they are computed with and without subtracting the evoked response
from each epoch. The former results in induced activity only while the
latter also includes evoked (stimulus-locked) activity.
Step1: Set parameters | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, source_induced_power
print(__doc__)
Explanation: Compute power and phase lock in label of the source space
Compute time-frequency maps of power and phase lock in the source space.
The inverse method is linear based on dSPM inverse operator.
The example also shows the difference in the time-frequency maps
when they are computed with and without subtracting the evoked response
from each epoch. The former results in induced activity only while the
latter also includes evoked (stimulus-locked) activity.
End of explanation
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
label_name = 'Aud-rh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name
tmin, tmax, event_id = -0.2, 0.5, 2
# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')
inverse_operator = read_inverse_operator(fname_inv)
include = []
raw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + 2 more
# Picks MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True,
stim=False, include=include, exclude='bads')
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
# Load epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), reject=reject,
preload=True)
# Compute a source estimate per frequency band including and excluding the
# evoked response
freqs = np.arange(7, 30, 2) # define frequencies of interest
label = mne.read_label(fname_label)
n_cycles = freqs / 3. # different number of cycle per frequency
# subtract the evoked response in order to exclude evoked activity
epochs_induced = epochs.copy().subtract_evoked()
plt.close('all')
for ii, (this_epochs, title) in enumerate(zip([epochs, epochs_induced],
['evoked + induced',
'induced only'])):
# compute the source space power and the inter-trial coherence
power, itc = source_induced_power(
this_epochs, inverse_operator, freqs, label, baseline=(-0.1, 0),
baseline_mode='percent', n_cycles=n_cycles, n_jobs=1)
power = np.mean(power, axis=0) # average over sources
itc = np.mean(itc, axis=0) # average over sources
times = epochs.times
##########################################################################
# View time-frequency plots
plt.subplots_adjust(0.1, 0.08, 0.96, 0.94, 0.2, 0.43)
plt.subplot(2, 2, 2 * ii + 1)
plt.imshow(20 * power,
extent=[times[0], times[-1], freqs[0], freqs[-1]],
aspect='auto', origin='lower', vmin=0., vmax=30., cmap='RdBu_r')
plt.xlabel('Time (s)')
plt.ylabel('Frequency (Hz)')
plt.title('Power (%s)' % title)
plt.colorbar()
plt.subplot(2, 2, 2 * ii + 2)
plt.imshow(itc,
extent=[times[0], times[-1], freqs[0], freqs[-1]],
aspect='auto', origin='lower', vmin=0, vmax=0.7,
cmap='RdBu_r')
plt.xlabel('Time (s)')
plt.ylabel('Frequency (Hz)')
plt.title('ITC (%s)' % title)
plt.colorbar()
plt.show()
Explanation: Set parameters
End of explanation |
7,998 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple unicycle model of a UAV
Step1: The Vector-Field VF(x)
based on the implicit funtion $\phi$ as taken from Goncalves2010a
Step2: Approximate Distance to Implicit Curve
Step3: Cost Function and Constraints
Step4: Visualization
Step5: MPC Control | Python Code:
%matplotlib inline
import pdb
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def UAVmodel(state,u,dt):
# unpack the state vector
x = state[0]
y = state[1]
theta = state[2]
# unpack the input vectors
v = u[0]
w = u[1]
# compute deltas
dx = v*np.cos(theta)*dt
dy = v*np.sin(theta)*dt
dtheta = w*dt
# new state
new_state = np.zeros(3)
new_state[0] = x + dx
new_state[1] = y + dy
new_state[2] = theta + dtheta
# return the two state derivatives
return new_state
def simpleUAVmodelTestandPlot():
n = 1000
state = np.zeros([3,n])
state[:,0] = [0.0, 0.0, 0.0]
for i in range(1,n):
state[:,i] = UAVmodel(state[:,i-1],[1,5],0.001)
plt.plot(state[0,:], state[1,:]);
plt.xlabel('x');
plt.ylabel('y');
Explanation: Simple unicycle model of a UAV
End of explanation
import numpy as np
def VF_G(y):
return -2/np.pi*np.arctan(10*y)
def VF_phi(x):
return np.power(x[0],4)/16-2*np.power(x[0],2)*np.power(x[1],2)/5+np.power(x[1],4)-1
def VF_phi_grad(x):
grad = np.zeros(2)
grad[0] = 1/4*np.power(x[0],3)-4/5*x[0]*np.power(x[1],2)
grad[1] = 4*np.power(x[1],3)-4/5*x[1]*np.power(x[0],2)
return grad
def VF_alpha(x):
return VF_G(VF_phi(x))
def VF_N(x):
return np.multiply(VF_alpha(x), VF_phi_grad(x))
def VF_H(x):
return 1
def VF_beta(x):
return VF_H(VF_phi(x))
def VF_T(x):
phi_grad = VF_phi_grad(x)
return VF_beta(x) * [-phi_grad[1],phi_grad[0]]
def VF(x):
return VF_N(x) + VF_T(x)
#print(VF_phi([0,-1])==0)
#print(VF_phi([-2,0])==0)
#print(VF_phi_grad([0,-1]))
#print(VF_phi_grad([-2,0]))
#print(VF([0,-1])==[ 4., 0.])
#print(VF([-2,0])==[ 0., -2.])
Explanation: The Vector-Field VF(x)
based on the implicit funtion $\phi$ as taken from Goncalves2010a
End of explanation
from numpy import linalg as LA
from math import atan2
import numpy as np
def approxPointOnImplicitCurve(x,f,df,tangent_function):
#TODO: Maybe use approximation from Taubin1994 instead of numerical approach
eps = 0.1 # tuning parameter
step = 0.05 # tuning parameter
# Offset, to make sure the UAV rotates in the intended direction
scaling_tangent = 0.1 # tuning parameter
# Gradient descent, better would be Newton or quasi Newton
x_temp = x
i = 0
while np.power(f(x_temp),2)>eps and i<100:
grad = df(x_temp)
grad /= LA.norm(grad)
x_temp = x_temp - grad*step
i = i + 1
#if i>100:
# pdb.set_trace()
#print(i)
#tangent_on_curve = np.array(tangent_function(x_temp))
#tangent_on_curve /= LA.norm(tangent_on_curve)
x_on_curve = x_temp #+ tangent_on_curve*scaling_tangent # TODO should be '+' for normal behavior
return x_on_curve
#print(approxDist(np.array([0,-1]),VF_phi,VF_phi_grad)==0)
print(approxPointOnImplicitCurve(np.array([0,-1.5]),VF_phi,VF_phi_grad,VF_T))
#print(approxDist(np.array([-2,0]),VF_phi,VF_phi_grad)==0)
def angleOfTangent(x,tangent_function):
tangent_on_curve = np.array(tangent_function(x))
return atan2(tangent_on_curve[1],tangent_on_curve[0])
#print(angleOfTangent(np.array([0,-1]),VF_T))
#print(angleOfTangent(np.array([-2,0]),VF_T))
Explanation: Approximate Distance to Implicit Curve
End of explanation
from numpy import linalg as LA
import numpy as np
def J(xk,H_p,H_c,V,W,q,weights,t_step,int_t_step,angle_error_weight):
if len(V)!=H_c or len(W)!=H_c:
raise ValueError('Number of Inputs of U is not equivalent to control horizon H_c')
# simulate H_p steps beginning at the current measurement xk
x=tuple()
x = x + (xk,)
for l in np.arange(0,H_p):
#pdb.set_trace()
x_temp = x[l]
for i in np.arange(0,t_step,int_t_step):
if l<H_c:
x_temp = UAVmodel(x_temp,[V[l],W[l]],int_t_step)
else:
x_temp = UAVmodel(x_temp,[V[-1],W[-1]],int_t_step)
x = x + (x_temp,)
# Calculate Weighted State Errors
errors = np.zeros(H_p)
#print('state error')
for i in np.arange(0,H_p):
pos = x[i][0:2]
theta = x[i][-1]
curve_pos = approxPointOnImplicitCurve(pos,VF_phi,VF_phi_grad,VF_T)
curve_theta = angleOfTangent(curve_pos,VF_T)
theta_diff = atan2(np.sin(theta-curve_theta), np.cos(theta-curve_theta))*angle_error_weight
errors[i] = LA.norm(np.hstack([pos-curve_pos,theta_diff]))
#errors[i] = LA.norm(pos-curve_pos)
#print(errors[i])
Q = np.eye(H_p)*q
sumOfStateErrors = np.dot(np.dot(errors,Q),errors)
# Weighted Input Term
sumOfWeightedInputs = np.dot(np.absolute(W),weights)
#print('input punishment')
#print(sumOfWeightedInputs)
return sumOfStateErrors + sumOfWeightedInputs
def generateBounds(H_c,b_l,b_u):
bnds = tuple()
for i in range(0,H_c):
bnds = ((b_l, b_u),) + bnds
return bnds
Explanation: Cost Function and Constraints
End of explanation
%matplotlib inline
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def plotTraj(xk,Model,V,W,t_step,int_t_step):
# simulate H_p steps beginning at the current measurement xk
x=tuple()
x = x + (xk,)
for l in np.arange(0,len(V)):
#pdb.set_trace()
x_temp = x[l]
for i in np.arange(0,t_step,int_t_step):
x_temp = Model(x_temp,[V[l],W[l]],int_t_step)
x = x + (x_temp,)
#pdb.set_trace()
x_all = np.vstack(x)
plt.plot(x_all[:,0],x_all[:,1]);
plt.xlabel('x');
plt.ylabel('y');
def plotTrajCost(xk,Model,V,W,t_step,int_t_step,weights,q):
# simulate H_p steps beginning at the current measurement xk
x=tuple()
x = x + (xk,)
N = len(V)
errors = np.zeros(N)
inputs = np.zeros(N)
for l in np.arange(0,len(V)):
#pdb.set_trace()
x_temp = x[l]
for i in np.arange(0,t_step,int_t_step):
x_temp = Model(x_temp,[V[l],W[l]],int_t_step)
x = x + (x_temp,)
pos = x_temp[0:2]
theta = x_temp[-1]
curve_pos = approxPointOnImplicitCurve(pos,VF_phi,VF_phi_grad,VF_T)
curve_theta = angleOfTangent(curve_pos,VF_T)
theta_diff = atan2(np.sin(theta-curve_theta), np.cos(theta-curve_theta))
errors[l] = np.power(LA.norm(np.hstack([pos-curve_pos,theta_diff])),2)*q
inputs[l] = np.absolute(W[l])*weights[l]
#pdb.set_trace()
plt.plot(range(0,N),errors,label='state error')
plt.plot(range(0,N),inputs,label='weighted input')
plt.plot(range(0,N),errors+inputs,label='sum')
plt.xlabel('inputs');
plt.ylabel('error');
#plt.legend()
#plt.show()
def plotImplCurve(implfun,xmin,xmax,ymin,ymax,eps,N):
#N = 100
#eps = 2e-3
x = np.linspace(xmin, xmax, N)
y = np.linspace(ymin, ymax, N)
X, Y = np.meshgrid(x, y)
Z = np.zeros([N,N])
for i in range(0,N):
for j in range(0,N):
if np.power(implfun([X[i,j],Y[i,j]]),2)<=eps:
#print(implfun([X[i,j],Y[i,j]]))
plt.plot(X[i,j],Y[i,j],'o',color='blue')
#plt.show()
Explanation: Visualization
End of explanation
from scipy.optimize import minimize
from scipy.optimize import brute
import matplotlib.pyplot as plt
# related to plots
from pylab import rcParams
rcParams['figure.figsize'] = 10, 10
#from matplotlib.font_manager import FontProperties
# Constants
H_p = 20
H_c = 10
H_t_step = 0.1 # the time of the piece-wise constant inputs
int_t_step = 0.001 # the small time-steps of the integration, the lower the better
b_l = -2 # lower bound of the angular velocity vector
b_u = 2 # upper bound of the angular velocity vector
Q = 10 # Tuning parameter: scaling for the state error
weights = np.ones(H_c)*1 # Tuning parameter: weight of the input signal, the higher , the less signal is applied
xk = tuple(np.array([0,-3.0,np.pi/2]))# initial point: below curve and straight up np.pi/2 0
angle_error_weight = 0.3 # Tuning parameter: Scaling of the angle-error [-pi/2,pi/2],
# the higher, the more the MPC converges to the shape of the curve
# initial guess
V = np.ones(H_c) # fixed at 1 unit/sec
W = np.ones(H_c)*0
# Constraint Functions
bnds = generateBounds(H_c,b_l,b_u)
objfun = lambda W: J(xk,H_p,H_c,V,W,Q,weights,H_t_step,int_t_step,angle_error_weight)
#objfun(W)
#res = minimize(objfun, W, method='COBYLA',bounds=bnds,options={'maxiter':1000})
res = minimize(objfun, W, method='COBYLA',options={'maxiter':1000})
#SLSQP L-BFGS-B TNC COBYLA
#resbrute = brute(objfun, bnds, Ns=5, full_output=False, disp=True)#Ns=20,
#pdb.set_trace()
print(res)
axarr = plt.subplot(2, 1, 1)
axarr.set_title('Implicit Curve and Trajectory')
plotImplCurve(VF_phi,-3,3,-3,3,2e-3,100)
# Extend the Input Vectors if H_c<H_p
V_total = np.zeros(H_p)
W_total = np.zeros(H_p)
weights_total = np.zeros(H_p)
for i in range(0,H_p):
if i>=H_c:
V_total[i] = V[-1]
W_total[i] = res.x[-1]
weights_total[i] = 0
else:
V_total[i] = V[i]
W_total[i] = res.x[i]
weights_total[i] = weights[i]
plotTraj(xk,UAVmodel,V_total,W_total,H_t_step,int_t_step)
axarr = plt.subplot(2, 1, 2)
axarr.set_title('Cost Function along the simulated Trajectory')
plotTrajCost(xk,UAVmodel,V_total,W_total,H_t_step,int_t_step,weights_total,Q)
#plt.legend()
axarr.legend(loc='upper right', #bbox_to_anchor=(1.5, .45),
fancybox=True, shadow=True)
plt.show()
Explanation: MPC Control
End of explanation |
7,999 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting with matplotlib
1. Getting Started
1.1 What is matplotlib?
Matplotlib is the most popular and mature library for plotting data using
Python. It has all of the functionality you would expect, including the ability to control
the formatting of plots and figures at a very fine level.
The official matplotlib documentation is at http
Step1: 2. Creating Figures
There are two major challenges with creating figures. First is understanding the
syntax to actually make the basic plot appear. Second is formatting the basic plot to look
exactly how you would like it to look. In general, the formatting will probably take you
longer...
Within pyplot (currently imported as 'plt'), there are two basic ways to go about making
plots - using the Matlab-like clone, and using the object-oriented approach. The latter
provides better control over plot features, while only requiring slightly more typing. It's
easy to quickly outgrow the Matlab clone, so we'll go right to the object-oriented syntax.
2.1 A first plot
In simple matplotlib plotting, there are two concepts to distinguish
Step2: First, create an empty figure with 2 subplots
using the subplots method
figure, axes = plt.subplots(rows, columns)
The arguments (1, 2) indicate 1 row and 2 cols
The function plt.subplots returns an object for the figure and for each axes
There are multiple ways to accomplish this same goal, but this is probably the simplest - notice that each subplot is associated with one of the axes objects.
Step3: Now let's actually plot the data using the plot method on an axis
axis.plot(x, y)
You can plot multiple lines on an axis
Step4: Many of the basic formatting problems you have will be solved by the magic of tight_layout. Before you start tweaking how you figure looks, try it out.
plt.tight_layout()
Step5: To save your figure you can use the savefig command
Step6: TRY IT
Create a line graph plotting the function f(x) = x^3 for values of x 0-10.
3. Formatting Figures
The formatting of figures often takes longer than actually setting them up and adding data. There are many different approaches to formatting figures in matplotlib (many goals can be accomplished in different ways, using different commands), and you will come across many of these as you learn more. The tips below give a few simple ways to get started.
3.1 Line formatting
The plot method has several available keyword arguments that you can use to change the line formatting.
color - Chages color of line. examples
Step7: 3.2 Tick marks
You can set the values where the ticks are located using the xticks and yticks methods.
They take a list of values
plt.xticks([val1, val2, val3])
plt.yticks([yval1, yval2, yval3])
Step8: Oh no! That changed it for the last plot but not for the first plot.
To set each plot individually, you need to set the current axis to the subplot you are interested in using the method sca. Then you can use xticks and yticks.
plt.sca(axis)
plt.xticks([val1, val2, val3])
plt.yticks([yval1, yval2, yval3])
Step9: 3.3 Axis limits
Setting the limits of the axes is very similar to setting the ticks. The command to set the limits are xlim and ylim. Remember if you have more than one subplot, you will need to set the current axis before you set that axis' limits.
plt.sca(axis)
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
Step10: 3.4 Setting tick labels
To set the tick labels, you pass a second parameter to the xticks and yticks methods with a list of labels for that axis.
plt.sca(axis)
plt.xticks([tickvalues], [ticklabels])
plt.yticks([tickvalues], [ticklabels])
Step11: 3.5 Legend
When you create a line on a plot, you can pass it a keyword argument label and then create a legend that will use that label using the legend method. The legend method takes an optional parameter of loc for the location of the legend. You can see the values allowed here
Step12: TRY IT
Go back to your plot of f(x) = x^3 for values of x 0-10. Try out some of the formatting options you just learned to make your plot look "just right"
4. Other types of plots
Matplotlib is more than just line plots, let's see what else it can do.
1.1 Other plots
In the examples above, we used the plot method to make line plots. There are also methods to
make scatter plots, barplots, histograms, loglog plots, semilog plots, etc.
# Bar graph
ax.bar(x, y)
# Scatter plot
ax.scatter(x,y)
# Horizontal bar plot
ax.barh(x,y)
# Boxplot
ax.boxplot(x)
# Log-log plot
ax.loglog(x,y)
# Semilog plot
ax.semilogx(x,y)
ax.semilogy(x,y)
Plots too squished? Check out plt.tight_layout()
Step13: Many of the same formatting options as the line plot are available for these additional plots. There are also some other options. The gallery (section 5) is the best place to find all the options.
Let's try changing the marker on the scatter plot
Step14: 4.2 Plotting images
Matplotlib also makes it easy to plot images. For this, you can use the plot method imshow
(syntax borrowed from Matlab).
To load in an image we use the imread function. This takes a file path and reads the file into a numpy ndarray
To plot an image, you can use imshow function giving it an array.
A 1D array will be rendered as grayscale and a 3D or (4D with transparency) array will be a full color image.
To set the colormap of a grayscale image, you can use the optional cmap key word argument to imshow. Options available are listed here
Step15: TRY IT
Plot the cubes from 1-10 in a vertical bar chart and in a scatter plot (2 separate subplots). Change the colors of the bars to green. Change the marker of the scatter plot to plus signs.
5. The matplotlib gallery
It can be very intimidating to try to craft exactly the figure that you want, especially if
you are used to being able to adjust things visually using a program like Excel.
If you get stuck and don't know where to start, or just want to learn more about what
matplotlib can do, a great option is to have a look at the matplotlib gallery, which can be
found at http | Python Code:
# In IPython or the IPython notebook, it's easiest to use the pylab magic, which
# imports matplotlib, numpy, and scipy.
# The matplotlib notebook flag means that plots will be shown interactively in the
# notebooks, rather than in pop-up windows.
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
Explanation: Plotting with matplotlib
1. Getting Started
1.1 What is matplotlib?
Matplotlib is the most popular and mature library for plotting data using
Python. It has all of the functionality you would expect, including the ability to control
the formatting of plots and figures at a very fine level.
The official matplotlib documentation is at http://matplotlib.org/
The matplotlib gallery is at http://matplotlib.org/gallery.html
1.2 Importing matplotlib
Matplotlib is often used through 'pyplot', which provides a high-level interface for
plotting.
End of explanation
# First we make some data to plot
x = np.linspace(-2*np.pi, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
Explanation: 2. Creating Figures
There are two major challenges with creating figures. First is understanding the
syntax to actually make the basic plot appear. Second is formatting the basic plot to look
exactly how you would like it to look. In general, the formatting will probably take you
longer...
Within pyplot (currently imported as 'plt'), there are two basic ways to go about making
plots - using the Matlab-like clone, and using the object-oriented approach. The latter
provides better control over plot features, while only requiring slightly more typing. It's
easy to quickly outgrow the Matlab clone, so we'll go right to the object-oriented syntax.
2.1 A first plot
In simple matplotlib plotting, there are two concepts to distinguish:
Figure - the entire figure, like what you might see in a journal, including all
subplots, axes, lines, labels, etc. The whole enchilada.
Subplot/Axes - one of the sub-sections of the figure, labeled (a), (b), etc. in
articles. Each subplot will contain one Axes object, which is the container where all of the
useful stuff, such as actual lines, legends, labels, etc., are actually housed.
For example, here's how to make one figure with two subplots, the second of which contains
two lines.
End of explanation
fig, axes = plt.subplots(1,2)
Explanation: First, create an empty figure with 2 subplots
using the subplots method
figure, axes = plt.subplots(rows, columns)
The arguments (1, 2) indicate 1 row and 2 cols
The function plt.subplots returns an object for the figure and for each axes
There are multiple ways to accomplish this same goal, but this is probably the simplest - notice that each subplot is associated with one of the axes objects.
End of explanation
fig, axes = plt.subplots(1,2)
# We plot one line on the first axis
axes[0].plot(x, y1)
# and both lines on the second axis
axes[1].plot(x, y1)
axes[1].plot(x, y2);
Explanation: Now let's actually plot the data using the plot method on an axis
axis.plot(x, y)
You can plot multiple lines on an axis
End of explanation
fig, axes = plt.subplots(1,2)
axes[0].plot(x, y1)
axes[1].plot(x, y1)
axes[1].plot(x, y2)
plt.tight_layout();
Explanation: Many of the basic formatting problems you have will be solved by the magic of tight_layout. Before you start tweaking how you figure looks, try it out.
plt.tight_layout()
End of explanation
fig, axes = plt.subplots(1,2)
axes[0].plot(x, y1)
axes[1].plot(x, y1)
axes[1].plot(x, y2)
fig.savefig('first_plot.png', format='png');
Explanation: To save your figure you can use the savefig command:
fig.savefig('fileanme', format='png')
Format options include png, pdf, ps, eps and svg
End of explanation
x = np.linspace(-2*np.pi, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(1,2)
axes[0].plot(x, y1, color='r', linewidth=5)
axes[1].plot(x, y1, color='#ffaa00', linewidth=0.5, linestyle='--')
axes[1].plot(x, y2, color='green', linestyle='-.');
Explanation: TRY IT
Create a line graph plotting the function f(x) = x^3 for values of x 0-10.
3. Formatting Figures
The formatting of figures often takes longer than actually setting them up and adding data. There are many different approaches to formatting figures in matplotlib (many goals can be accomplished in different ways, using different commands), and you will come across many of these as you learn more. The tips below give a few simple ways to get started.
3.1 Line formatting
The plot method has several available keyword arguments that you can use to change the line formatting.
color - Chages color of line. examples: 'red', 'blue', 'r', 'k', 0.5, '#ffaa00', (0,0.5,0.75)
linewidth - Weight of line. Takes float value in points (like font)
linestyle - Solid, dashed, or other. examples: -, --, -.
End of explanation
x = np.linspace(-2*np.pi, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(1,2)
axes[0].plot(x, y1, color='r', linewidth=5)
axes[1].plot(x, y1, color='#ffaa00', linewidth=0.5, linestyle='--')
axes[1].plot(x, y2, color='green', linestyle='-.')
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, 1]);
Explanation: 3.2 Tick marks
You can set the values where the ticks are located using the xticks and yticks methods.
They take a list of values
plt.xticks([val1, val2, val3])
plt.yticks([yval1, yval2, yval3])
End of explanation
x = np.linspace(-2*np.pi, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(1,2)
axes[0].plot(x, y1, color='r', linewidth=5)
axes[1].plot(x, y1, color='#ffaa00', linewidth=0.5, linestyle='--')
axes[1].plot(x, y2, color='green', linestyle='-.')
# Set the current axis to the first subplot
fig.sca(axes[0])
# set x and y ticks
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, 1])
# Set the current axis to the second subplot
fig.sca(axes[1])
# set x and y ticks
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, 1]);
Explanation: Oh no! That changed it for the last plot but not for the first plot.
To set each plot individually, you need to set the current axis to the subplot you are interested in using the method sca. Then you can use xticks and yticks.
plt.sca(axis)
plt.xticks([val1, val2, val3])
plt.yticks([yval1, yval2, yval3])
End of explanation
x = np.linspace(-2*np.pi, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(1,2)
axes[0].plot(x, y1, color='r', linewidth=5)
axes[1].plot(x, y1, color='#ffaa00', linewidth=0.5, linestyle='--')
axes[1].plot(x, y2, color='green', linestyle='-.')
# Set the current axis to the first subplot
fig.sca(axes[0])
# set x and y ticks
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, 1])
# set x and y limits
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1)
# Set the current axis to the second subplot
fig.sca(axes[1])
# set x and y ticks
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, 1])
# set x and y limits
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1);
Explanation: 3.3 Axis limits
Setting the limits of the axes is very similar to setting the ticks. The command to set the limits are xlim and ylim. Remember if you have more than one subplot, you will need to set the current axis before you set that axis' limits.
plt.sca(axis)
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
End of explanation
x = np.linspace(-2*np.pi, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(1,2)
axes[0].plot(x, y1, color='r', linewidth=5)
axes[1].plot(x, y1, color='#ffaa00', linewidth=0.5, linestyle='--')
axes[1].plot(x, y2, color='green', linestyle='-.')
# Set the current axis to the first subplot
fig.sca(axes[0])
# set x and y ticks
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['-pi', '-pi/2', '0', 'pi/2', 'pi'])
# You probably don't want to set the labels when you just want the exact numbers.
plt.yticks([-1, 0, 1], ['-1', '0', '1'])
# set x and y limits
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1)
# Set the current axis to the second subplot
fig.sca(axes[1])
# set x and y ticks
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['-pi', '-pi/2', '0', 'pi/2', 'pi'])
plt.yticks([-1, 0, 1], ['-1', '0', '1'])
# set x and y limits
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1);
Explanation: 3.4 Setting tick labels
To set the tick labels, you pass a second parameter to the xticks and yticks methods with a list of labels for that axis.
plt.sca(axis)
plt.xticks([tickvalues], [ticklabels])
plt.yticks([tickvalues], [ticklabels])
End of explanation
x = np.linspace(-2*np.pi, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(1,2)
# Let's set labels here
axes[0].plot(x, y1, color='r', linewidth=5, label='sin(x)')
axes[1].plot(x, y1, color='#ffaa00', linewidth=0.5, linestyle='--', label='sin(x)')
axes[1].plot(x, y2, color='green', linestyle='-.', label='cos(x)')
# Set the current axis to the first subplot
fig.sca(axes[0])
# set x and y ticks
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['-pi', '-pi/2', '0', 'pi/2', 'pi'])
# You probably don't want to set the labels when you just want the exact numbers.
plt.yticks([-1, 0, 1], ['-1', '0', '1'])
plt.legend(loc='best')
# set x and y limits
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1)
# Set the current axis to the second subplot
fig.sca(axes[1])
# set x and y ticks
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['-pi', '-pi/2', '0', 'pi/2', 'pi'])
plt.yticks([-1, 0, 1], ['-1', '0', '1'])
plt.legend(loc='upper right')
# set x and y limits
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1);
Explanation: 3.5 Legend
When you create a line on a plot, you can pass it a keyword argument label and then create a legend that will use that label using the legend method. The legend method takes an optional parameter of loc for the location of the legend. You can see the values allowed here: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend This is another one of those commands that you need to set the current axis if you have more than one subplot.
plt.plot(x,y, label='my_label')
plt.legend(loc='best')
End of explanation
# Make some data to plot
x = np.arange(0, 100)
y = np.random.rand(100) # 100 random numbers
# Make a figure with 6 subplots and axes
# Notice that we are doing some arguement unpacking to get six subplots. You can use indexing instead if you prefer
fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3, 2)
# Add data to each axis. Optional arguments to each method will customize each plot.
ax1.bar(x,y)
ax2.scatter(x,y)
ax3.barh(x,y)
ax4.boxplot(x)
ax5.loglog(x,y)
ax6.semilogx(x,y)
Explanation: TRY IT
Go back to your plot of f(x) = x^3 for values of x 0-10. Try out some of the formatting options you just learned to make your plot look "just right"
4. Other types of plots
Matplotlib is more than just line plots, let's see what else it can do.
1.1 Other plots
In the examples above, we used the plot method to make line plots. There are also methods to
make scatter plots, barplots, histograms, loglog plots, semilog plots, etc.
# Bar graph
ax.bar(x, y)
# Scatter plot
ax.scatter(x,y)
# Horizontal bar plot
ax.barh(x,y)
# Boxplot
ax.boxplot(x)
# Log-log plot
ax.loglog(x,y)
# Semilog plot
ax.semilogx(x,y)
ax.semilogy(x,y)
Plots too squished? Check out plt.tight_layout()
End of explanation
fig, ax = plt.subplots(1,1)
ax.scatter(x, y, marker='x')
ax.scatter(x, y + 2, marker='>', color='#00aaff')
Explanation: Many of the same formatting options as the line plot are available for these additional plots. There are also some other options. The gallery (section 5) is the best place to find all the options.
Let's try changing the marker on the scatter plot: http://matplotlib.org/exmples/lines_bars_and_markers/marker_reference.html
End of explanation
# Read image from file and display it
img1 = plt.imread('astronaut.png')
# Uncomment following line to prove it still works without the alpha channel
# img1 = img1[:,:, 0:3]
fig, ax = plt.subplots(1,1)
ax.imshow(img1)
# We can plot random noise in the viridis colormap.
img2 = np.random.rand(128, 128)
fig, ax = plt.subplots(1,1)
ax = ax.imshow(img2, cmap='viridis')
Explanation: 4.2 Plotting images
Matplotlib also makes it easy to plot images. For this, you can use the plot method imshow
(syntax borrowed from Matlab).
To load in an image we use the imread function. This takes a file path and reads the file into a numpy ndarray
To plot an image, you can use imshow function giving it an array.
A 1D array will be rendered as grayscale and a 3D or (4D with transparency) array will be a full color image.
To set the colormap of a grayscale image, you can use the optional cmap key word argument to imshow. Options available are listed here: http://matplotlib.org/examples/color/colormaps_reference.html
End of explanation
# %load http://matplotlib.org/mpl_examples/pylab_examples/contour_demo.py
Explanation: TRY IT
Plot the cubes from 1-10 in a vertical bar chart and in a scatter plot (2 separate subplots). Change the colors of the bars to green. Change the marker of the scatter plot to plus signs.
5. The matplotlib gallery
It can be very intimidating to try to craft exactly the figure that you want, especially if
you are used to being able to adjust things visually using a program like Excel.
If you get stuck and don't know where to start, or just want to learn more about what
matplotlib can do, a great option is to have a look at the matplotlib gallery, which can be
found at http://matplotlib.org/gallery.html. A good way to get started is to find a figure
here that sort of looks like what you want, copy the code, and modify it for your own needs.
5.1 Exploring the matplotlib gallery
Have a look at the matplotlib gallery. If find a cool looking figure you can copy the code into a code line. You can of course do this manually but you can also use IPython "load magic" Type %loadpy and then the URL of the py file containing the code, and it will automatically copy it into a cell below. Run the cell with the code to see the
figure. Now you can make small (or large) tweaks to get your perfect figure.
Note that some of the examples might require packages that are not installed on your machine (in particular those that make maps) - if this is the case, pick another example for the purposes of this exercise.
Hint to get the raw python url right click on the source code link towards the top and pick copy link.
End of explanation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.