Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
7,400 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyNNDescent with different metrics
In the initial tutorial we looked at how to get PyNNDescent running on your data, and how to query the indexes it builds. Implicit in all of that was the measure of distance used to determine what counts as the "nearest" neighbors. By default PyNNDescent uses the euclidean metric (because that is what people generally expect when they talk about distance). This is not the only way to measure distance however, and is often not the right choice for very high dimensional data for example. Let's look at how to use PyNNDescent with other metrics.
First we'll need some libraries, and some test data. As before we will use ann-benchmarks for data, so we will reuse the data download function from the previous tutorial.
Step1: Built in metrics
Let's grab some data where euclidean distance doesn't make sense. We'll use the NY-Times dataset, which is a TF-IDF matrix of data generated from NY-Times news stories. The particulars are less important here, but what matters is that the most sensible way to measure distance on this data is with an angular metric, such as cosine distance.
Step2: Now that we have the data we can check the distance measure suggested by ann-benchmarks
Step3: So an angular measure of distance -- cosine distance will suffice. How do we manage to get PyNNDescent working with cosine distance (which isn't even a real metric! it violates the triangle inequality) instead of standard euclidean?
Step4: That's right, it uses the scikit-learn standard of the metric keyword and accepts a string that names the metric. We can now query the index, and it will use that metric in the query as well.
Step5: It is worth noting at this point that these results will probably be a little sub-optimal since angular distances are harder to index, and as a result to get the same level accuracy in the nearest neighbor approximation we should be using a larger value than the default 30 for n_neighbors. Beyond that, however, nothing else changes from the tutorial earlier -- except that we can't use kd-trees to learn the true neighbors, since they require distances that respect the triangle inequality.
How many metrics does PyNNDescent support out of the box? Quite a few actually
Step6: Some of these are repeats or alternate names for the same metric, and some of these are fairly simple, but others, such as spearmanr, or hellinger are useful statistical measures not often implemented elsewhere, and others, such as wasserstein are complex and hard to compute metrics. Having all of these readily available in a fast approximate nearest neighbor library is one of PyNNDescent's strengths.
Custom metrics
We can go even further in terms of interesting metrics however. You can write your own custom metrics and hand them to PyNNDescent to use on your data. There, of course, a few caveats with this. Many nearest neighbor libraries allow for the possibility of user defined metrics. If you are using Python this often ends up coming in two flavours
Step7: Let's start by simply implementing euclidean distance where $d(\mathbf{x},\mathbf{y}) = \sqrt{\sum_i (\mathbf{x}_i - \mathbf{y}_i)^2}$. This is already implemented in PyNNDescent, but it is a simple distance measure that everyone knows and will serve to illustrate the process. First let's write the function -- using numpy functionality this will be fairly short
Step8: Now we need to get the function compiled so PyNNDescent can use it. That is actually as easy as adding a decorator to the top of the function telling numba that it should compile the function when it gets called.
Step9: We can now pass this function directly to PyNNdescent as a metric and everything will "just work". We'll just train on the smaller test set since it will take a while.
Step10: This is a little slower than we might have expected, and that's because a great deal of the computation time is spent evaluating that metric. While numba will compile what we wrote we can make it a little faster if we look through the numba performance tips documentation. The two main things to note are that we can use explicit loops instead of numpy routines, and we can add arguments to the decorator such as fastmath=True to speed things up a little. Let's rewrite it
Step12: That is faster! If we are really on the hunt for performance however, you might note that, for the purposes of finding nearest neighbors the exact values of the distance are not as important as the ordering on distances. In other words we could use the square of euclidean distance and we would get all the same neighbors (since the square root is a monotonic order preserving function of squared euclidean distance). That would, for example, save us a square root computation. We could do the square roots afterwards to just the distances to the nearest neighbors. Let's reproduce what PyNNDescent actually uses internally for euclidean distance
Step13: That is definitely more complicated! Most of it, however, is arguments to the decorator giving it extra typing information to let it squeeze out every drop of performance possible. By default numba will infer types, or even compile different versions for the different types it sees. With a little extra information, however, it can make smarter decisions and optimizations during compilation. Let's see how fast that goes | Python Code:
import pynndescent
import numpy as np
import h5py
from urllib.request import urlretrieve
import os
def get_ann_benchmark_data(dataset_name):
if not os.path.exists(f"{dataset_name}.hdf5"):
print(f"Dataset {dataset_name} is not cached; downloading now ...")
urlretrieve(f"http://ann-benchmarks.com/{dataset_name}.hdf5", f"{dataset_name}.hdf5")
hdf5_file = h5py.File(f"{dataset_name}.hdf5", "r")
return np.array(hdf5_file['train']), np.array(hdf5_file['test']), hdf5_file.attrs['distance']
Explanation: PyNNDescent with different metrics
In the initial tutorial we looked at how to get PyNNDescent running on your data, and how to query the indexes it builds. Implicit in all of that was the measure of distance used to determine what counts as the "nearest" neighbors. By default PyNNDescent uses the euclidean metric (because that is what people generally expect when they talk about distance). This is not the only way to measure distance however, and is often not the right choice for very high dimensional data for example. Let's look at how to use PyNNDescent with other metrics.
First we'll need some libraries, and some test data. As before we will use ann-benchmarks for data, so we will reuse the data download function from the previous tutorial.
End of explanation
nytimes_train, nytimes_test, distance = get_ann_benchmark_data('nytimes-256-angular')
nytimes_train.shape
Explanation: Built in metrics
Let's grab some data where euclidean distance doesn't make sense. We'll use the NY-Times dataset, which is a TF-IDF matrix of data generated from NY-Times news stories. The particulars are less important here, but what matters is that the most sensible way to measure distance on this data is with an angular metric, such as cosine distance.
End of explanation
distance
Explanation: Now that we have the data we can check the distance measure suggested by ann-benchmarks
End of explanation
%%time
index = pynndescent.NNDescent(nytimes_train, metric="cosine")
index.prepare()
Explanation: So an angular measure of distance -- cosine distance will suffice. How do we manage to get PyNNDescent working with cosine distance (which isn't even a real metric! it violates the triangle inequality) instead of standard euclidean?
End of explanation
%%time
neighbors = index.query(nytimes_train)
Explanation: That's right, it uses the scikit-learn standard of the metric keyword and accepts a string that names the metric. We can now query the index, and it will use that metric in the query as well.
End of explanation
for dist in pynndescent.distances.named_distances:
print(dist)
Explanation: It is worth noting at this point that these results will probably be a little sub-optimal since angular distances are harder to index, and as a result to get the same level accuracy in the nearest neighbor approximation we should be using a larger value than the default 30 for n_neighbors. Beyond that, however, nothing else changes from the tutorial earlier -- except that we can't use kd-trees to learn the true neighbors, since they require distances that respect the triangle inequality.
How many metrics does PyNNDescent support out of the box? Quite a few actually:
End of explanation
import numba
Explanation: Some of these are repeats or alternate names for the same metric, and some of these are fairly simple, but others, such as spearmanr, or hellinger are useful statistical measures not often implemented elsewhere, and others, such as wasserstein are complex and hard to compute metrics. Having all of these readily available in a fast approximate nearest neighbor library is one of PyNNDescent's strengths.
Custom metrics
We can go even further in terms of interesting metrics however. You can write your own custom metrics and hand them to PyNNDescent to use on your data. There, of course, a few caveats with this. Many nearest neighbor libraries allow for the possibility of user defined metrics. If you are using Python this often ends up coming in two flavours:
Write some C, C++ or Cython code and compile it against the library itself
Write a python distance function, but lose almost all performance
With PyNNDescent we get a different trade-off. Because we use Numba for just-in-time compiling of Python code instead of a C or C++ backend you don't need to do an offline compilation step and can instead have your custom Python distance function compiled and used on the fly. The cost for that is that the custom distance function you write must be a numba jitted function. This, in turn, means that you can only use Python functionality that is supported by numba. That is still a fairly large amount of functionality, especially when we are talking about numerical work, but it is a limit. It also means that you will need to import numba and decorate your custom distance function accordingly. Let's look at how to do that.
End of explanation
def euclidean(x, y):
return np.sqrt(np.sum((x - y)**2))
Explanation: Let's start by simply implementing euclidean distance where $d(\mathbf{x},\mathbf{y}) = \sqrt{\sum_i (\mathbf{x}_i - \mathbf{y}_i)^2}$. This is already implemented in PyNNDescent, but it is a simple distance measure that everyone knows and will serve to illustrate the process. First let's write the function -- using numpy functionality this will be fairly short:
End of explanation
@numba.jit
def euclidean(x, y):
return np.sqrt(np.sum((x - y)**2))
Explanation: Now we need to get the function compiled so PyNNDescent can use it. That is actually as easy as adding a decorator to the top of the function telling numba that it should compile the function when it gets called.
End of explanation
%%time
index = pynndescent.NNDescent(nytimes_test, metric=euclidean)
Explanation: We can now pass this function directly to PyNNdescent as a metric and everything will "just work". We'll just train on the smaller test set since it will take a while.
End of explanation
@numba.jit(fastmath=True)
def euclidean(x, y):
result = 0.0
for i in range(x.shape[0]):
result += (x[i] - y[i])**2
return np.sqrt(result)
%%time
index = pynndescent.NNDescent(nytimes_test, metric=euclidean)
Explanation: This is a little slower than we might have expected, and that's because a great deal of the computation time is spent evaluating that metric. While numba will compile what we wrote we can make it a little faster if we look through the numba performance tips documentation. The two main things to note are that we can use explicit loops instead of numpy routines, and we can add arguments to the decorator such as fastmath=True to speed things up a little. Let's rewrite it:
End of explanation
@numba.njit(
[
"f4(f4[::1],f4[::1])",
numba.types.float32(
numba.types.Array(numba.types.float32, 1, "C", readonly=True),
numba.types.Array(numba.types.float32, 1, "C", readonly=True),
),
],
fastmath=True,
locals={
"result": numba.types.float32,
"diff": numba.types.float32,
"dim": numba.types.uint32,
"i": numba.types.uint16,
},
)
def squared_euclidean(x, y):
rSquared euclidean distance.
.. math::
D(x, y) = \sum_i (x_i - y_i)^2
result = 0.0
dim = x.shape[0]
for i in range(dim):
diff = x[i] - y[i]
result += diff * diff
return result
Explanation: That is faster! If we are really on the hunt for performance however, you might note that, for the purposes of finding nearest neighbors the exact values of the distance are not as important as the ordering on distances. In other words we could use the square of euclidean distance and we would get all the same neighbors (since the square root is a monotonic order preserving function of squared euclidean distance). That would, for example, save us a square root computation. We could do the square roots afterwards to just the distances to the nearest neighbors. Let's reproduce what PyNNDescent actually uses internally for euclidean distance:
End of explanation
%%time
index = pynndescent.NNDescent(nytimes_test, metric=squared_euclidean)
Explanation: That is definitely more complicated! Most of it, however, is arguments to the decorator giving it extra typing information to let it squeeze out every drop of performance possible. By default numba will infer types, or even compile different versions for the different types it sees. With a little extra information, however, it can make smarter decisions and optimizations during compilation. Let's see how fast that goes:
End of explanation |
7,401 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Study of Correlation Between Building Demolition and Associated Features
Capstone Project for Data Science at Scale on Coursera
Repo is located here
Chen Yang yangcnju@gmail.com
Step1: Objective
Build a model to make predictions on blighted buildings based on real data from data.detroitmi.gov as given by coursera.
Building demolition is very important for the city to turn around and revive its economy. However, it's no easy task. Accurate predictions can provide guidance on potential blighted buildings and help avoid complications at early stages.
Building List
The buildings were defined as described below
Step2: Features
Three kinds (311-calls, blight-violations, and crimes) of incident counts and coordinates (normalized) was used in the end. I also tried to generate more features by differentiating each kind of crimes or each kind of violations in this notebook. However, these differentiated features lead to smaller AUC scores.
Data
The buildings were down-sampled to contain same number of blighted buildings and non-blighted ones.
The ratio between train and test was set at a ratio of 80
Step3: This model resulted in an AUC score of 0.858 on test data. Feature importances are shown below
Step4: Locations were most important features in this model. Although I tried using more features generated by differentiating different kind of crimes or violations, the AUC scores did not improve.
Feature importance can also be viewed using tree representation
Step5: To reduce variance of the model, since overfitting was observed during training. I also tried to reduce variance by including in more nonblighted buildings by sampling again multiple times with replacement (bagging).
A final AUC score of 0.8625 was achieved. The resulted ROC Curve on test data is shown below | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import Image
%matplotlib inline
Explanation: Study of Correlation Between Building Demolition and Associated Features
Capstone Project for Data Science at Scale on Coursera
Repo is located here
Chen Yang yangcnju@gmail.com
End of explanation
# The resulted buildings:
Image("./data/buildings_distribution.png")
Explanation: Objective
Build a model to make predictions on blighted buildings based on real data from data.detroitmi.gov as given by coursera.
Building demolition is very important for the city to turn around and revive its economy. However, it's no easy task. Accurate predictions can provide guidance on potential blighted buildings and help avoid complications at early stages.
Building List
The buildings were defined as described below:
Building sizes were estimated using parcel info downloaded here at data.detroitmi.gov. Details can be found in this notebook.
A event table was constructed from the 4 files (detroit-311.csv, detroit-blight-violations.csv, detroit-crime.csv, and detroit-demolition-permits.tsv) using their coordinates, as shown here.
Buildings were defined using these coordinates with an estimated building size (median of all parcels). Each building was represented as a same sized rectangle.
End of explanation
Image('./data/train_process.png')
Explanation: Features
Three kinds (311-calls, blight-violations, and crimes) of incident counts and coordinates (normalized) was used in the end. I also tried to generate more features by differentiating each kind of crimes or each kind of violations in this notebook. However, these differentiated features lead to smaller AUC scores.
Data
The buildings were down-sampled to contain same number of blighted buildings and non-blighted ones.
The ratio between train and test was set at a ratio of 80:20.
During training using xgboost, the train data was further separated into train and evaluation with a ratio of 80:20 for monitoring.
Model
A Gradient Boosted Tree model using Xgboost achieved AUC score of 0.85 on evaluation data set:
End of explanation
Image('./data/feature_f_scores.png')
Explanation: This model resulted in an AUC score of 0.858 on test data. Feature importances are shown below:
End of explanation
Image('./data/bst_tree.png')
Explanation: Locations were most important features in this model. Although I tried using more features generated by differentiating different kind of crimes or violations, the AUC scores did not improve.
Feature importance can also be viewed using tree representation:
End of explanation
Image('./data/ROC_Curve_combined.png')
Explanation: To reduce variance of the model, since overfitting was observed during training. I also tried to reduce variance by including in more nonblighted buildings by sampling again multiple times with replacement (bagging).
A final AUC score of 0.8625 was achieved. The resulted ROC Curve on test data is shown below:
End of explanation |
7,402 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First BigQuery ML models for Taxifare Prediction
Learning Objectives
* Choose the correct BigQuery ML model type and specify options
* Evaluate the performance of your ML model
* Improve model performance through data quality cleanup
* Create a Deep Neural Network (DNN) using SQL
Overview
In this notebook, we will use BigQuery ML to build our first models for taxifare prediction.BigQuery ML provides a fast way to build ML models on large structured and semi-structured datasets. We'll start by creating a dataset to hold all the models we create in BigQuery.
Set environment variables
Step1: Create a BigQuery Dataset and Google Cloud Storage Bucket
A BigQuery dataset is a container for tables, views, and models built with BigQuery ML. Let's create one called serverlessml if we have not already done so in an earlier lab. We'll do the same for a GCS bucket for our project too.
Step2: Model 1
Step3: Once the training is done, visit the BigQuery Cloud Console and look at the model that has been trained. Then, come back to this notebook.
Note that BigQuery automatically split the data we gave it, and trained on only a part of the data and used the rest for evaluation. We can look at eval statistics on that held-out data
Step4: Let's report just the error we care about, the Root Mean Squared Error (RMSE)
Step5: We told you it was not going to be good! Recall that our heuristic got 8.13, and our target is $6.
Note that the error is going to depend on the dataset that we evaluate it on.
We can also evaluate the model on our own held-out benchmark/test dataset, but we shouldn't make a habit of this (we want to keep our benchmark dataset as the final evaluation, not make decisions using it all along the way. If we do that, our test dataset won't be truly independent).
Step6: What was the RMSE from the above?
TODO 3
Step7: Model 3
Step8: Nice!
Evaluate DNN on benchmark dataset
Let's use the same validation dataset to evaluate -- remember that evaluation metrics depend on the dataset. You can not compare two models unless you have run them on the same withheld data. | Python Code:
PROJECT = !gcloud config get-value project
PROJECT = PROJECT[0]
BUCKET = PROJECT
REGION = "us-central1"
%env PROJECT=$PROJECT
%env BUCKET=$BUCKET
%env REGION=$REGION
Explanation: First BigQuery ML models for Taxifare Prediction
Learning Objectives
* Choose the correct BigQuery ML model type and specify options
* Evaluate the performance of your ML model
* Improve model performance through data quality cleanup
* Create a Deep Neural Network (DNN) using SQL
Overview
In this notebook, we will use BigQuery ML to build our first models for taxifare prediction.BigQuery ML provides a fast way to build ML models on large structured and semi-structured datasets. We'll start by creating a dataset to hold all the models we create in BigQuery.
Set environment variables
End of explanation
%%bash
# Create a BigQuery dataset for serverlessml if it doesn't exist
datasetexists=$(bq ls -d | grep -w serverlessml)
if [ -n "$datasetexists" ]; then
echo -e "BigQuery dataset already exists, let's not recreate it."
else
echo "Creating BigQuery dataset titled: serverlessml"
bq --location=US mk --dataset \
--description 'Taxi Fare' \
$PROJECT:serverlessml
echo "\nHere are your current datasets:"
bq ls
fi
# Create GCS bucket if it doesn't exist already...
exists=$(gsutil ls -d | grep -w gs://${BUCKET}/)
if [ -n "$exists" ]; then
echo -e "Bucket exists, let's not recreate it."
else
echo "Creating a new GCS bucket."
gsutil mb -l ${REGION} gs://${BUCKET}
echo "\nHere are your current buckets:"
gsutil ls
fi
Explanation: Create a BigQuery Dataset and Google Cloud Storage Bucket
A BigQuery dataset is a container for tables, views, and models built with BigQuery ML. Let's create one called serverlessml if we have not already done so in an earlier lab. We'll do the same for a GCS bucket for our project too.
End of explanation
%%bigquery
CREATE OR REPLACE MODEL
serverlessml.model1_rawdata
# TODO 1: Choose the correct ML model_type for forecasting:
# i.e. Linear Regression (linear_reg) or Logistic Regression (logistic_reg)
# Enter in the appropriate ML OPTIONS() in the line below:
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_count * 1.0 AS passengers
FROM
`nyc-tlc.yellow.trips`
WHERE
ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 100000)) = 1
Explanation: Model 1: Raw data
Let's build a model using just the raw data. It's not going to be very good, but sometimes it is good to actually experience this.
The model will take a minute or so to train. When it comes to ML, this is blazing fast.
End of explanation
%%bigquery
# TODO 2: Specify the command to evaluate your newly trained model
SELECT * FROM
Explanation: Once the training is done, visit the BigQuery Cloud Console and look at the model that has been trained. Then, come back to this notebook.
Note that BigQuery automatically split the data we gave it, and trained on only a part of the data and used the rest for evaluation. We can look at eval statistics on that held-out data:
End of explanation
%%bigquery
SELECT
SQRT(mean_squared_error) AS rmse
FROM
ML.EVALUATE(MODEL serverlessml.model1_rawdata)
Explanation: Let's report just the error we care about, the Root Mean Squared Error (RMSE)
End of explanation
%%bigquery
SELECT
SQRT(mean_squared_error) AS rmse
FROM
ML.EVALUATE(MODEL serverlessml.model1_rawdata, (
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_count * 1.0 AS passengers # treat as decimal
FROM
`nyc-tlc.yellow.trips`
WHERE
ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 100000)) = 2
# Placeholder for additional filters as part of TODO 3 later
))
Explanation: We told you it was not going to be good! Recall that our heuristic got 8.13, and our target is $6.
Note that the error is going to depend on the dataset that we evaluate it on.
We can also evaluate the model on our own held-out benchmark/test dataset, but we shouldn't make a habit of this (we want to keep our benchmark dataset as the final evaluation, not make decisions using it all along the way. If we do that, our test dataset won't be truly independent).
End of explanation
%%bigquery
CREATE OR REPLACE TABLE
serverlessml.cleaned_training_data AS
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_count*1.0 AS passengers
FROM
`nyc-tlc.yellow.trips`
WHERE
ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 100000)) = 1
AND trip_distance > 0
AND fare_amount >= 2.5
AND pickup_longitude > -78
AND pickup_longitude < -70
AND dropoff_longitude > -78
AND dropoff_longitude < -70
AND pickup_latitude > 37
AND pickup_latitude < 45
AND dropoff_latitude > 37
AND dropoff_latitude < 45
AND passenger_count > 0
%%bigquery
-- LIMIT 0 is a free query, this allows us to check that the table exists.
SELECT * FROM serverlessml.cleaned_training_data
LIMIT 0
%%bigquery
CREATE OR REPLACE MODEL
serverlessml.model2_cleanup
OPTIONS(input_label_cols=['fare_amount'],
model_type='linear_reg') AS
SELECT
*
FROM
serverlessml.cleaned_training_data
%%bigquery
SELECT
SQRT(mean_squared_error) AS rmse
FROM
ML.EVALUATE(MODEL serverlessml.model2_cleanup)
Explanation: What was the RMSE from the above?
TODO 3: Now apply the below filters to the previous query inside the WHERE clause. Does the performance improve? Why or why not?
sql
AND trip_distance > 0
AND fare_amount >= 2.5
AND pickup_longitude > -78
AND pickup_longitude < -70
AND dropoff_longitude > -78
AND dropoff_longitude < -70
AND pickup_latitude > 37
AND pickup_latitude < 45
AND dropoff_latitude > 37
AND dropoff_latitude < 45
AND passenger_count > 0
Model 2: Apply data cleanup
Recall that we did some data cleanup in the previous lab. Let's do those before training.
This is a dataset that we will need quite frequently in this notebook, so let's extract it first.
End of explanation
%%bigquery
-- This training takes on the order of 15 minutes.
CREATE OR REPLACE MODEL
serverlessml.model3b_dnn
# TODO 4a: Choose correct BigQuery ML model type for DNN and label field
# Options: dnn_regressor, linear_reg, logistic_reg
OPTIONS() AS
SELECT
*
FROM
serverlessml.cleaned_training_data
%%bigquery
SELECT
SQRT(mean_squared_error) AS rmse
FROM
ML.EVALUATE(MODEL serverlessml.model3b_dnn)
Explanation: Model 3: More sophisticated models
What if we try a more sophisticated model? Let's try Deep Neural Networks (DNNs) in BigQuery:
DNN
To create a DNN, simply specify dnn_regressor for the model_type and add your hidden layers.
End of explanation
%%bigquery
SELECT
SQRT(mean_squared_error) AS rmse
# TODO 4b: What is the command to see how well a
# ML model performed? ML.What?
FROM
ML.WHATCOMMAND(MODEL serverlessml.model3b_dnn, (
SELECT
(tolls_amount + fare_amount) AS fare_amount,
pickup_datetime,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_count * 1.0 AS passengers,
'unused' AS key
FROM
`nyc-tlc.yellow.trips`
WHERE
ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 10000)) = 2
AND trip_distance > 0
AND fare_amount >= 2.5
AND pickup_longitude > -78
AND pickup_longitude < -70
AND dropoff_longitude > -78
AND dropoff_longitude < -70
AND pickup_latitude > 37
AND pickup_latitude < 45
AND dropoff_latitude > 37
AND dropoff_latitude < 45
AND passenger_count > 0
))
Explanation: Nice!
Evaluate DNN on benchmark dataset
Let's use the same validation dataset to evaluate -- remember that evaluation metrics depend on the dataset. You can not compare two models unless you have run them on the same withheld data.
End of explanation |
7,403 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Network you'll build will generate a new TV script for a scene at Moe's Tavern.
Get the Data
The data is already provided for you. You'll be using a subset of the original dataset. It consists of only the scenes in Moe's Tavern. This doesn't include other versions of the tavern, like "Moe's Cavern", "Flaming Moe's", "Uncle Moe's Family Feed-Bag", etc..
Step3: Explore the Data
Play around with view_sentence_range to view different parts of the data.
Step6: Implement Preprocessing Functions
The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below
Step9: Tokenize Punctuation
We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".
Implement the function token_lookup to return a dict that will be used to tokenize symbols like "!" into "||Exclamation_Mark||". Create a dictionary for the following symbols where the symbol is the key and value is the token
Step11: Preprocess all the data and save it
Running the code cell below will preprocess all the data and save it to file.
Step13: 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.
Step15: Build the Neural Network
You'll build the components necessary to build a RNN by implementing the following functions below
Step18: Input
Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders
Step21: Build RNN Cell and Initialize
Stack one or more BasicLSTMCells in a MultiRNNCell.
- The Rnn size should be set using rnn_size
- Initalize Cell State using the MultiRNNCell's zero_state() function
- Apply the name "initial_state" to the initial state using tf.identity()
Return the cell and initial state in the following tuple (Cell, InitialState)
Step24: Word Embedding
Apply embedding to input_data using TensorFlow. Return the embedded sequence.
Step27: Build RNN
You created a RNN Cell in the get_init_cell() function. Time to use the cell to create a RNN.
- Build the RNN using the tf.nn.dynamic_rnn()
- Apply the name "final_state" to the final state using tf.identity()
Return the outputs and final_state state in the following tuple (Outputs, FinalState)
Step30: Build the Neural Network
Apply the functions you implemented above to
Step33: Batches
Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements
Step35: Neural Network Training
Hyperparameters
Tune the following parameters
Step37: 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 seq_length and save_dir for generating a new TV script.
Step43: Checkpoint
Step46: Implement Generate Functions
Get Tensors
Get tensors from loaded_graph using the function get_tensor_by_name(). Get the tensors using the following names
Step49: Choose Word
Implement the pick_word() function to select the next word using probabilities.
Step51: Generate TV Script
This will generate the TV script for you. Set gen_length to the length of TV script you want to generate. | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Network you'll build will generate a new TV script for a scene at Moe's Tavern.
Get the Data
The data is already provided for you. You'll be using a subset of the original dataset. It consists of only the scenes in Moe's Tavern. This doesn't include other versions of the tavern, like "Moe's Cavern", "Flaming Moe's", "Uncle Moe's Family Feed-Bag", etc..
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 text.split()})))
scenes = text.split('\n\n')
print('Number of scenes: {}'.format(len(scenes)))
sentence_count_scene = [scene.count('\n') for scene in scenes]
print('Average number of sentences in each scene: {}'.format(np.average(sentence_count_scene)))
sentences = [sentence for scene in scenes for sentence in scene.split('\n')]
print('Number of lines: {}'.format(len(sentences)))
word_count_sentence = [len(sentence.split()) for sentence in sentences]
print('Average number of words in each line: {}'.format(np.average(word_count_sentence)))
print()
print('The sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(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
import numpy as np
import problem_unittests as tests
def create_lookup_tables(text):
Create lookup tables for vocabulary
:param text: The text of tv scripts split into words
:return: A tuple of dicts (vocab_to_int, int_to_vocab)
vocab_to_int = {w : i for i, w in list(enumerate(set(text)))}
int_to_vocab = {i : w for w, i in vocab_to_int.items()}
return vocab_to_int, int_to_vocab
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_create_lookup_tables(create_lookup_tables)
Explanation: Implement Preprocessing Functions
The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:
- Lookup Table
- Tokenize Punctuation
Lookup Table
To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:
- Dictionary to go from the words to an id, we'll call vocab_to_int
- Dictionary to go from the id to word, we'll call int_to_vocab
Return these dictionaries in the following tuple (vocab_to_int, int_to_vocab)
End of explanation
def token_lookup():
Generate a dict to turn punctuation into a token.
:return: Tokenize dictionary where the key is the punctuation and the value is the token
return {"." : "||Period||",
"," : "||Comma||",
"\"" : "||Quotation_Mark||",
";" : "||Semicolon||",
"!" : "||Exclamation_Mark||",
"?" : "||Question_Mark||",
"(" : "||Left_Parentheses||",
")" : "||Right_Parentheses||",
"--" : "||Dash||",
"\n" : "||Return||"}
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_tokenize(token_lookup)
Explanation: Tokenize Punctuation
We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".
Implement the function token_lookup to return a dict that will be used to tokenize symbols like "!" into "||Exclamation_Mark||". Create a dictionary for the following symbols where the symbol is the key and value is the token:
- Period ( . )
- Comma ( , )
- Quotation Mark ( " )
- Semicolon ( ; )
- Exclamation mark ( ! )
- Question mark ( ? )
- Left Parentheses ( ( )
- Right Parentheses ( ) )
- Dash ( -- )
- Return ( \n )
This dictionary will be used to token the symbols and add the delimiter (space) around it. This separates the symbols as it's own word, making it easier for the neural network to predict on the next word. Make sure you don't use a token that could be confused as a word. Instead of using the token "dash", try using something like "||dash||".
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
# Preprocess Training, Validation, and Testing Data
helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)
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 helper
import numpy as np
import problem_unittests as tests
int_text, vocab_to_int, int_to_vocab, token_dict = 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__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer'
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: Build the Neural Network
You'll build the components necessary to build a RNN by implementing the following functions below:
- get_inputs
- get_init_cell
- get_embed
- build_rnn
- build_nn
- get_batches
Check the Version of TensorFlow and Access to GPU
End of explanation
def get_inputs():
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate)
return tf.placeholder(tf.int32, [None, None], "input"), tf.placeholder(tf.int32, [None, None], "targets"), tf.placeholder(tf.float32, None, "lr")
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_get_inputs(get_inputs)
Explanation: Input
Implement the get_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.
- Targets placeholder
- Learning Rate placeholder
Return the placeholders in the following tuple (Input, Targets, LearningRate)
End of explanation
def get_init_cell(batch_size, rnn_size):
Create an RNN Cell and initialize it.
:param batch_size: Size of batches
:param rnn_size: Size of RNNs
:return: Tuple (cell, initialize state)
lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)
#drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=0.5)
cell = tf.contrib.rnn.MultiRNNCell([lstm])
initial_state = cell.zero_state(batch_size, tf.float32)
initial_state = tf.identity(initial_state, "initial_state")
return cell, initial_state
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_get_init_cell(get_init_cell)
Explanation: Build RNN Cell and Initialize
Stack one or more BasicLSTMCells in a MultiRNNCell.
- The Rnn size should be set using rnn_size
- Initalize Cell State using the MultiRNNCell's zero_state() function
- Apply the name "initial_state" to the initial state using tf.identity()
Return the cell and initial state in the following tuple (Cell, InitialState)
End of explanation
def get_embed(input_data, vocab_size, embed_dim):
Create embedding for <input_data>.
:param input_data: TF placeholder for text input.
:param vocab_size: Number of words in vocabulary.
:param embed_dim: Number of embedding dimensions
:return: Embedded input.
embedding = tf.Variable(tf.random_uniform((vocab_size, embed_dim), -1, 1))
return tf.nn.embedding_lookup(embedding, input_data)
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_get_embed(get_embed)
Explanation: Word Embedding
Apply embedding to input_data using TensorFlow. Return the embedded sequence.
End of explanation
def build_rnn(cell, inputs):
Create a RNN using a RNN Cell
:param cell: RNN Cell
:param inputs: Input text data
:return: Tuple (Outputs, Final State)
outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32)
final_state = tf.identity(final_state, "final_state")
return outputs, final_state
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_build_rnn(build_rnn)
Explanation: Build RNN
You created a RNN Cell in the get_init_cell() function. Time to use the cell to create a RNN.
- Build the RNN using the tf.nn.dynamic_rnn()
- Apply the name "final_state" to the final state using tf.identity()
Return the outputs and final_state state in the following tuple (Outputs, FinalState)
End of explanation
def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim):
Build part of the neural network
:param cell: RNN cell
:param rnn_size: Size of rnns
:param input_data: Input data
:param vocab_size: Vocabulary size
:param embed_dim: Number of embedding dimensions
:return: Tuple (Logits, FinalState)
embeddings = get_embed(input_data, vocab_size, embed_dim)
rnn, final_state = build_rnn(cell, embeddings)
logits = tf.contrib.layers.fully_connected(rnn, vocab_size, activation_fn=None,
weights_initializer = tf.truncated_normal_initializer(mean=0, stddev=0.01),
biases_initializer = tf.zeros_initializer())
return logits, final_state
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_build_nn(build_nn)
Explanation: Build the Neural Network
Apply the functions you implemented above to:
- Apply embedding to input_data using your get_embed(input_data, vocab_size, embed_dim) function.
- Build RNN using cell and your build_rnn(cell, inputs) function.
- Apply a fully connected layer with a linear activation and vocab_size as the number of outputs.
Return the logits and final state in the following tuple (Logits, FinalState)
End of explanation
def get_batches(int_text, batch_size, seq_length):
Return batches of input and target
:param int_text: Text with the words replaced by their ids
:param batch_size: The size of batch
:param seq_length: The length of sequence
:return: Batches as a Numpy array
batch_total = batch_size*seq_length
num_batches = len(int_text)//batch_total
x, y = np.array(int_text[:num_batches*batch_total]), np.array(int_text[1:num_batches*batch_total] + [int_text[0]])
x = np.split(x.reshape(batch_size, -1), num_batches, 1)
y = np.split(y.reshape(batch_size, -1), num_batches, 1)
return np.array(list(zip(x, y)))
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_get_batches(get_batches)
Explanation: Batches
Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements:
- The first element is a single batch of input with the shape [batch size, sequence length]
- The second element is a single batch of targets with the shape [batch size, sequence length]
If you can't fill the last batch with enough data, drop the last batch.
For exmple, get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 3, 2) would return a Numpy array of the following:
```
[
# First Batch
[
# Batch of Input
[[ 1 2], [ 7 8], [13 14]]
# Batch of targets
[[ 2 3], [ 8 9], [14 15]]
]
# Second Batch
[
# Batch of Input
[[ 3 4], [ 9 10], [15 16]]
# Batch of targets
[[ 4 5], [10 11], [16 17]]
]
# Third Batch
[
# Batch of Input
[[ 5 6], [11 12], [17 18]]
# Batch of targets
[[ 6 7], [12 13], [18 1]]
]
]
```
Notice that the last target value in the last batch is the first input value of the first batch. In this case, 1. This is a common technique used when creating sequence batches, although it is rather unintuitive.
End of explanation
# Number of Epochs
num_epochs = 100
# Batch Size
batch_size = 256
# RNN Size
rnn_size = 256
# Embedding Dimension Size
embed_dim = 300
# Sequence Length
seq_length = 20
# Learning Rate
learning_rate = 0.01
# Show stats for every n number of batches
show_every_n_batches = 20
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
save_dir = './save'
Explanation: Neural Network Training
Hyperparameters
Tune the following parameters:
Set num_epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set embed_dim to the size of the embedding.
Set seq_length to the length of sequence.
Set learning_rate to the learning rate.
Set show_every_n_batches to the number of batches the neural network should print progress.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
from tensorflow.contrib import seq2seq
train_graph = tf.Graph()
with train_graph.as_default():
vocab_size = len(int_to_vocab)
input_text, targets, lr = get_inputs()
input_data_shape = tf.shape(input_text)
cell, initial_state = get_init_cell(input_data_shape[0], rnn_size)
logits, final_state = build_nn(cell, rnn_size, input_text, vocab_size, embed_dim)
# Probabilities for generating words
probs = tf.nn.softmax(logits, name='probs')
# Loss function
cost = seq2seq.sequence_loss(
logits,
targets,
tf.ones([input_data_shape[0], input_data_shape[1]]))
# 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
batches = get_batches(int_text, batch_size, seq_length)
with tf.Session(graph=train_graph) as sess:
sess.run(tf.global_variables_initializer())
for epoch_i in range(num_epochs):
state = sess.run(initial_state, {input_text: batches[0][0]})
for batch_i, (x, y) in enumerate(batches):
feed = {
input_text: x,
targets: y,
initial_state: state,
lr: learning_rate}
train_loss, state, _ = sess.run([cost, final_state, train_op], feed)
# Show every <show_every_n_batches> batches
if (epoch_i * len(batches) + batch_i) % show_every_n_batches == 0:
print('Epoch {:>3} Batch {:>4}/{} train_loss = {:.3f}'.format(
epoch_i,
batch_i,
len(batches),
train_loss))
# Save Model
saver = tf.train.Saver()
saver.save(sess, save_dir)
print('Model Trained and Saved')
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((seq_length, save_dir))
Explanation: Save Parameters
Save seq_length and save_dir for generating a new TV script.
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
_, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()
seq_length, load_dir = helper.load_params()
Explanation: Checkpoint
End of explanation
def get_tensors(loaded_graph):
Get input, initial state, final state, and probabilities tensor from <loaded_graph>
:param loaded_graph: TensorFlow graph loaded from file
:return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)
# TODO: Implement Function
input_tensor = loaded_graph.get_tensor_by_name("input:0")
initial_state_tensor = loaded_graph.get_tensor_by_name("initial_state:0")
final_state_tensor = loaded_graph.get_tensor_by_name("final_state:0")
probs_tensor = loaded_graph.get_tensor_by_name("probs:0")
return input_tensor, initial_state_tensor, final_state_tensor, probs_tensor
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_get_tensors(get_tensors)
Explanation: Implement Generate Functions
Get Tensors
Get tensors from loaded_graph using the function get_tensor_by_name(). Get the tensors using the following names:
- "input:0"
- "initial_state:0"
- "final_state:0"
- "probs:0"
Return the tensors in the following tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)
End of explanation
def pick_word(probabilities, int_to_vocab):
Pick the next word in the generated text
:param probabilities: Probabilites of the next word
:param int_to_vocab: Dictionary of word ids as the keys and words as the values
:return: String of the predicted word
import operator
max_index, _ = max(enumerate(probabilities), key=operator.itemgetter(1))
return int_to_vocab[max_index]
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_pick_word(pick_word)
Explanation: Choose Word
Implement the pick_word() function to select the next word using probabilities.
End of explanation
gen_length = 200
# homer_simpson, moe_szyslak, or Barney_Gumble
prime_word = 'moe_szyslak'
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
# Load saved model
loader = tf.train.import_meta_graph(load_dir + '.meta')
loader.restore(sess, load_dir)
# Get Tensors from loaded model
input_text, initial_state, final_state, probs = get_tensors(loaded_graph)
# Sentences generation setup
gen_sentences = [prime_word + ':']
prev_state = sess.run(initial_state, {input_text: np.array([[1]])})
# Generate sentences
for n in range(gen_length):
# Dynamic Input
dyn_input = [[vocab_to_int[word] for word in gen_sentences[-seq_length:]]]
dyn_seq_length = len(dyn_input[0])
# Get Prediction
probabilities, prev_state = sess.run(
[probs, final_state],
{input_text: dyn_input, initial_state: prev_state})
pred_word = pick_word(probabilities[dyn_seq_length-1], int_to_vocab)
gen_sentences.append(pred_word)
# Remove tokens
tv_script = ' '.join(gen_sentences)
for key, token in token_dict.items():
ending = ' ' if key in ['\n', '(', '"'] else ''
tv_script = tv_script.replace(' ' + token.lower(), key)
tv_script = tv_script.replace('\n ', '\n')
tv_script = tv_script.replace('( ', '(')
print(tv_script)
Explanation: Generate TV Script
This will generate the TV script for you. Set gen_length to the length of TV script you want to generate.
End of explanation |
7,404 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: Example 2 | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from landlab import RasterModelGrid
from landlab.components import SimpleSubmarineDiffuser
grid = RasterModelGrid((3, 51)) # grid has just one row of core nodes
# Close top and bottom boundaries
grid.set_closed_boundaries_at_grid_edges(False, True, False, True)
# We're required to create a topographic__elevation field at nodes
z = grid.add_zeros("topographic__elevation", at="node")
# Here's our triangular island...
z[:] = (25.0 - np.abs(grid.x_of_node - 25.0)) - 15.0
# ...with a flat seabed at 5 m depth
z[z < -5.0] = -5.0
# We'll keep a copy of the starting elevation for later comparison
z0 = z.copy()
# And we'll create a field to track cumulative deposition
cum_depo = grid.add_zeros("cumulative_deposit__thickness", at="node")
xm = grid.x_of_node[51:102]
zm = z[51:102]
plt.plot(xm, zm, "k")
plt.plot([0, 50], [0, 0], "b:") # add sea level
plt.xlabel("Distance (m)")
plt.ylabel("Elevation (m)")
# Instantiate the component
# (note 1 m2/y is a pretty small diffusivity; just for testing here)
ssd = SimpleSubmarineDiffuser(
grid, sea_level=0.0, wave_base=1.0, shallow_water_diffusivity=1.0
)
for i in range(500):
ssd.run_one_step(0.2)
cum_depo += grid.at_node["sediment_deposit__thickness"]
xm = grid.x_of_node[51:102]
zm = z[51:102]
plt.plot(xm, z0[51:102], "k")
cum_depo[cum_depo < 0.0] = 0.0
plt.plot(xm, zm)
plt.plot([0, 50], [0, 0], "b:")
plt.grid(True)
plt.xlabel("Distance (m)")
plt.ylabel("Elevation (m)")
plt.fill(xm, cum_depo[51:102] - 5.0, "y")
plt.xlabel("Distance (m)")
plt.ylabel("Sediment thickness (m)")
plt.ylim([-5, 10])
Explanation: <a href="http://landlab.github.io"><img style="float: left" src="../../landlab_header.png"></a>
Using the Landlab SimpleSubmarineDiffuser component
<hr>
<small>For more Landlab tutorials, click here: <a href="https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html">https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html</a></small>
<hr>
This tutorial demonstrates how to use the SimpleSubmarineDiffuser component. SimpleSubmarineDiffuser models submarine sediment transport using a diffusion approach, in which the diffusivity varies with water depth. The component sets diffusivity to a (nearly) constant value between sea level and the wave-base depth, and to a value that declines exponentially with depth below the wave base. (The diffusivity on land, meaning locations with an elevation above current sea level, is set to an arbitrarily tiny positive value).
Theory
The mathematics behind SimpleSubmarineDiffuser are as follows. The component represents a discretized numerical solution to the PDE:
$$\frac{\partial \eta}{\partial t} = -\nabla \cdot \mathbf{q_s}$$
$$\mathbf{q_s} = -D(h) \nabla\eta$$
where $\eta$ is surface height, $t$ is time, $\mathbf{q_s}$ is volume sediment transport rate per unit width (in terms of bulk volume, i.e., it incorporates porosity), and $D(h)$ is the transport coefficient (a.k.a., diffusivity) that varies with local water depth $h$.
First we define the applied shallow-water diffusivity, $D_s$, in terms of the local water depth $h$ and tidal range $R_t$. If $R_t = 0$, then $D_s$ is uniform where $h \ge 0$ (i.e., underwater), and negligibly tiny elsewhere (i.e., on land). If $R_t > 0$, then a smoothing function is used to allow the applied diffusivity to increase smoothly from a negligibly small value on land (above ~2x high tide) to its base value, $D_{s0}$ (which is the input parameter shallow_water_diffusivity) below ~2x low-tide elevation:
$$D_s = (\tanh ( -h / R_t ) + 1) / 2$$
With this equation, $D_s \approx 0.02 D_{s0}$ at twice the high-tide height, and $D_s \approx 0.98 D_{s0}$ at twice the low-tide depth. The basic idea is to account in a simple way for tidal variations.
Within the wave zone, $D = D_s$ (which is to say, it is essentially constant except right around mean sea level). Below the wave-base depth, $h_{wb}$, the diffusivity decreases exponentially:
$$D = \begin{cases}
D_s &\mbox{where } h > h_{wb} \
D_s \exp ( -(h - h_{wb}) / h_{wb} ) & \mbox{where } h \ge h_{wb} \end{cases}$$
Numerical implementation
SimpleSubmarineDiffuser uses a forward-in-time, finite-volume method. It is the same method that the LinearDiffuser component uses, because in fact SimpleSubmarineDiffuser uses the solver of LinearDiffuser. The component is implemented as a class that derives directly from the LinearDiffuser class. The run_one_step() method of SimpleSubmarineDiffuser simply updates the current water depth (given sea level and topography), calculates the diffusivity coefficient, and then calls the run_one_step() method for the LinearDiffuser to perform the mass balance.
Technical notes
To avoid divide-by-zero errors, a tiny positive diffusivity (currently 10$^{-20}$ m$^2$/y) is assigned to nodes on land (or more precisely, added to any additional diffusivity that arises from the tanh function; see above).
The component assigns diffusivity values to nodes, but the LinearDiffuser component then translates these to links. It maps diffusivity from nodes to links by using the maximum value of diffusivity of the nodes bounding each link. This means in practice that links that cross the shoreline will tend to have a higher diffusivity than the equations outlined above might suggest. In future, this could be addressed by modifying LinearDiffuser (which, however, could be a compatibility-breaking change unless handled as a user option), or by encoding the solver directly in SimpleSubmarineDiffuser as opposed to borrowing the solver of LinearDiffuser.
Examples
Example 1: Quasi-1D
The first example uses a quasi-1D setup to represent an initial topography with a triangular cross-section.
End of explanation
grid = RasterModelGrid((51, 51))
z = grid.add_zeros("topographic__elevation", at="node")
midpoint = 25.0
# Here we create the cone shape, again with a floor at 5 m depth
dx = np.abs(grid.x_of_node - midpoint)
dy = np.abs(grid.y_of_node - midpoint)
ds = np.sqrt(dx * dx + dy * dy)
z[:] = (midpoint - ds) - 15.0
z[z < -5.0] = -5.0
cum_depo = grid.add_zeros("total_deposit__thickness", at="node")
grid.imshow(z, cmap="coolwarm", vmin=-10)
# Here's a pointillistic side view
plt.plot(grid.x_of_node, z, ".")
plt.plot([0, 50], [0, 0], "b:")
plt.grid(True)
plt.xlabel("Distance (m)")
plt.ylabel("Elevation (m)")
ssd = SimpleSubmarineDiffuser(
grid, sea_level=0.0, wave_base=1.0, shallow_water_diffusivity=1.0
)
for i in range(100):
ssd.run_one_step(0.2)
cum_depo += grid.at_node["sediment_deposit__thickness"]
grid.imshow(z, cmap="coolwarm", vmin=-10)
plt.plot(grid.x_of_node, z, ".")
plt.plot([0, 50], [0, 0], "b:")
plt.grid(True)
plt.xlabel("Distance (m)")
plt.ylabel("Elevation (m)")
# Show the donut-shaped deposit and associated erosion pattern
grid.imshow(cum_depo)
# And show that mass balances (the sum is basically zero, apart
# from a tiny roundoff error)
print(np.sum(cum_depo))
Explanation: Example 2: a conical island
The second example is much like the first, but now in 2D using a cone as the initial topography.
End of explanation |
7,405 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import
Step1: Reading initial data
Step2: Define label
label = signB * signVtx > 0
* same sign of B and vtx -> label = 1
* opposite sign of B and vtx -> label = 0
Step3: Define B-like events for training and others for prediction
Step4: Define features
Step5: Find good vtx to define sign B
trying to guess sign of B based on sign of vtx. If the guess is good, the vtx will be used on next step to train classifier.
2-folding random forest selection for right tagged events
Step7: Training on all vtx
in this case we don't use preselection with RandomForest
DT full
Step8: Report for all vtx
Step9: Calibrating results $p(\text{vrt same sign}|B)$ and combining them
Step10: Comparison of different models
Step11: Implementing the best vertex model
and saving its predictions | Python Code:
import pandas
import numpy
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_curve, roc_auc_score
from rep.metaml import FoldingClassifier
from rep.data import LabeledDataStorage
from rep.report import ClassificationReport
from rep.report.metrics import RocAuc
from utils import get_N_B_events, get_events_number, get_events_statistics
Explanation: Import
End of explanation
import root_numpy
data = pandas.DataFrame(root_numpy.root2array('datasets/1016_vtx.root'))
Explanation: Reading initial data
End of explanation
event_id_column = 'event_id'
data[event_id_column] = data.runNum.apply(str) + '_' + (data.evtNum.apply(int)).apply(str)
# reconstructing sign of B
data['signB'] = data.tagAnswer * (2 * data.iscorrect - 1)
# assure sign is +1 or -1
data['signVtx'] = (data.signVtx.values > 0) * 2 - 1
data['label'] = (data.signVtx.values * data.signB.values > 0) * 1
data.head()
get_events_statistics(data)
N_pass = get_events_number(data)
tagging_efficiency = 1. * N_pass / get_N_B_events()
tagging_efficiency_delta = sqrt(N_pass) / get_N_B_events()
print tagging_efficiency, tagging_efficiency_delta
Bdata_tracks = pandas.read_csv('models/Bdata_tracks_PID_less.csv')
Bdata_tracks.index = Bdata_tracks.event_id
data['initial_pred'] = Bdata_tracks.ix[data.event_id, 'track_relation_prob'].values
Explanation: Define label
label = signB * signVtx > 0
* same sign of B and vtx -> label = 1
* opposite sign of B and vtx -> label = 0
End of explanation
sweight_threshold = 1.
data_sw_passed = data[data.N_sig_sw > sweight_threshold]
data_sw_not_passed = data[data.N_sig_sw <= sweight_threshold]
get_events_statistics(data_sw_passed)
Explanation: Define B-like events for training and others for prediction
End of explanation
features = ['mult', 'nnkrec', 'ptB', 'vflag', 'ipsmean', 'ptmean', 'vcharge',
'svm', 'svp', 'BDphiDir', 'svtau', 'docamax']
Explanation: Define features
End of explanation
data_sw_passed_lds = LabeledDataStorage(data_sw_passed, data_sw_passed.label, data_sw_passed.N_sig_sw)
Explanation: Find good vtx to define sign B
trying to guess sign of B based on sign of vtx. If the guess is good, the vtx will be used on next step to train classifier.
2-folding random forest selection for right tagged events
End of explanation
from hep_ml.decisiontrain import DecisionTrainClassifier
from hep_ml.losses import LogLossFunction
from hep_ml.losses import HessianLossFunction
from hep_ml.commonutils import check_sample_weight
from scipy.special import expit
class LogLossFunctionTagging(HessianLossFunction):
Logistic loss function (logloss), aka binomial deviance, aka cross-entropy,
aka log-likelihood loss.
def fit(self, X, y, sample_weight):
self.sample_weight = check_sample_weight(y, sample_weight=sample_weight,
normalize=True, normalize_by_class=True)
self.initial_pred = numpy.log(X['initial_pred'].values)
self.y_signed = 2 * y - 1
self.minus_y_signed = - self.y_signed
self.y_signed_times_weights = self.y_signed * self.sample_weight
HessianLossFunction.fit(self, X, y, sample_weight=self.sample_weight)
return self
def __call__(self, y_pred):
y_pred = y_pred + self.initial_pred
return numpy.sum(self.sample_weight * numpy.logaddexp(0, self.minus_y_signed * y_pred))
def negative_gradient(self, y_pred):
y_pred = y_pred + self.initial_pred
return self.y_signed_times_weights * expit(self.minus_y_signed * y_pred)
def hessian(self, y_pred):
y_pred = y_pred + self.initial_pred
expits = expit(y_pred)
return self.sample_weight * expits * (1 - expits)
def prepare_tree_params(self, y_pred):
y_pred = y_pred + self.initial_pred
return self.y_signed * expit(self.minus_y_signed * y_pred), self.sample_weight
tt_base = DecisionTrainClassifier(learning_rate=0.02, n_estimators=1500, depth=6,
max_features=8, loss=LogLossFunctionTagging(regularization=100), train_features=features)
tt_folding = FoldingClassifier(tt_base, n_folds=2, random_state=11,
features=features + ['initial_pred'])
%time tt_folding.fit_lds(data_sw_passed_lds)
pass
from scipy.special import expit, logit
data_temp = data_sw_not_passed
print roc_auc_score(data_temp.signB.values, data_temp['initial_pred'].values, sample_weight=data_temp.N_sig_sw.values)
p = tt_folding.predict_proba(data_temp)[:, 1]
print roc_auc_score(data_temp.signB.values,
log(data_temp['initial_pred'].values) + logit(p) * data_temp.signB.values,
sample_weight=data_temp.N_sig_sw.values)
hist(tt_folding.estimators[0].loss.initial_pred, )
pass
Explanation: Training on all vtx
in this case we don't use preselection with RandomForest
DT full
End of explanation
report = ClassificationReport({'tt': tt_folding}, data_sw_passed_lds)
report.learning_curve(RocAuc())
report.compute_metric(RocAuc())
report.roc()
Explanation: Report for all vtx
End of explanation
models = []
from utils import get_result_with_bootstrap_for_given_part
models.append(get_result_with_bootstrap_for_given_part(tagging_efficiency, tagging_efficiency_delta, tt_folding,
[data_sw_passed, data_sw_not_passed],
logistic=True, name="tt-log",
sign_part_column='signVtx', part_name='vertex'))
models.append(get_result_with_bootstrap_for_given_part(tagging_efficiency, tagging_efficiency_delta, tt_folding,
[data_sw_passed, data_sw_not_passed],
logistic=False, name="tt-iso",
sign_part_column='signVtx', part_name='vertex'))
Explanation: Calibrating results $p(\text{vrt same sign}|B)$ and combining them
End of explanation
pandas.concat(models)
pandas.concat(models)
Explanation: Comparison of different models
End of explanation
from utils import prepare_B_data_for_given_part
Bdata_prepared = prepare_B_data_for_given_part(tt_folding, [data_sw_passed, data_sw_not_passed], logistic=False,
sign_part_column='signVtx', part_name='vertex')
Bdata_prepared.to_csv('models/Bdata_vertex_new_loss.csv', header=True, index=False)
Explanation: Implementing the best vertex model
and saving its predictions
End of explanation |
7,406 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
01 - Data Analysis and Preparation
This notebook covers the following tasks
Step1: Setup Google Cloud project
Step2: Set configurations
Step3: 1. Explore the data in BigQuery
Step4: 2. Create data for the ML task
We add a ML_use column for pre-splitting the data, where 80% of the datsa items are set to UNASSIGNED while the other 20% is set to TEST.
This column is used during training to split the dataset for training and test.
In the training phase, the UNASSIGNED are split into train and eval. The TEST split is will be used for the final model validation.
Create destination BigQuery dataset
Step5: Load a sample data to a Pandas DataFrame
Step6: 3. Generate raw data schema
The TensorFlow Data Validation (TFDV) data schema will be used in
Step7: 4. Create Vertex Dataset resource
Step8: Create the dataset resource
Step9: Get the dataset resource
The dataset resource is retrieved by display name. Because multiple datasets can have the same display name, we retrieve the most recent updated one. | Python Code:
import os
import pandas as pd
import tensorflow as tf
import tensorflow_data_validation as tfdv
from google.cloud import bigquery
import matplotlib.pyplot as plt
from google.cloud import aiplatform as vertex_ai
Explanation: 01 - Data Analysis and Preparation
This notebook covers the following tasks:
Perform exploratory data analysis and visualization.
Prepare the data for the ML task in BigQuery.
Generate and fix a TFDV schema for the source data.
Create a Vertex Dataset resource dataset.
Dataset
The Chicago Taxi Trips dataset is one of public datasets hosted with BigQuery, which includes taxi trips from 2013 to the present, reported to the City of Chicago in its role as a regulatory agency. The taxi_trips table size is 70.72 GB and includes more than 195 million records. The dataset includes information about the trips, like pickup and dropoff datetime and location, passengers count, miles travelled, and trip toll.
The ML task is to predict whether a given trip will result in a tip > 20%.
Setup
Import libraries
End of explanation
PROJECT = '[your-project-id]' # Change to your project id.
REGION = 'us-central1' # Change to your region.
if PROJECT == "" or PROJECT is None or PROJECT == "[your-project-id]":
# Get your GCP project id from gcloud
shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT = shell_output[0]
print("Project ID:", PROJECT)
print("Region:", REGION)
Explanation: Setup Google Cloud project
End of explanation
BQ_DATASET_NAME = 'playground_us' # Change to your BQ dataset name.
BQ_TABLE_NAME = 'chicago_taxitrips_prep'
BQ_LOCATION = 'US'
DATASET_DISPLAY_NAME = 'chicago-taxi-tips'
RAW_SCHEMA_DIR = 'src/raw_schema'
Explanation: Set configurations
End of explanation
%%bigquery data
SELECT
CAST(EXTRACT(DAYOFWEEK FROM trip_start_timestamp) AS string) AS trip_dayofweek,
FORMAT_DATE('%A',cast(trip_start_timestamp as date)) AS trip_dayname,
COUNT(*) as trip_count,
FROM `bigquery-public-data.chicago_taxi_trips.taxi_trips`
WHERE
EXTRACT(YEAR FROM trip_start_timestamp) = 2015
GROUP BY
trip_dayofweek,
trip_dayname
ORDER BY
trip_dayofweek
;
data
data.plot(kind='bar', x='trip_dayname', y='trip_count')
Explanation: 1. Explore the data in BigQuery
End of explanation
!bq --location=US mk -d \
$PROJECT:$BQ_DATASET_NAME
sample_size = 1000000
year = 2020
sql_script = '''
CREATE OR REPLACE TABLE `@PROJECT.@DATASET.@TABLE`
AS (
WITH
taxitrips AS (
SELECT
trip_start_timestamp,
trip_seconds,
trip_miles,
payment_type,
pickup_longitude,
pickup_latitude,
dropoff_longitude,
dropoff_latitude,
tips,
fare
FROM
`bigquery-public-data.chicago_taxi_trips.taxi_trips`
WHERE 1=1
AND pickup_longitude IS NOT NULL
AND pickup_latitude IS NOT NULL
AND dropoff_longitude IS NOT NULL
AND dropoff_latitude IS NOT NULL
AND trip_miles > 0
AND trip_seconds > 0
AND fare > 0
AND EXTRACT(YEAR FROM trip_start_timestamp) = @YEAR
)
SELECT
trip_start_timestamp,
EXTRACT(MONTH from trip_start_timestamp) as trip_month,
EXTRACT(DAY from trip_start_timestamp) as trip_day,
EXTRACT(DAYOFWEEK from trip_start_timestamp) as trip_day_of_week,
EXTRACT(HOUR from trip_start_timestamp) as trip_hour,
trip_seconds,
trip_miles,
payment_type,
ST_AsText(
ST_SnapToGrid(ST_GeogPoint(pickup_longitude, pickup_latitude), 0.1)
) AS pickup_grid,
ST_AsText(
ST_SnapToGrid(ST_GeogPoint(dropoff_longitude, dropoff_latitude), 0.1)
) AS dropoff_grid,
ST_Distance(
ST_GeogPoint(pickup_longitude, pickup_latitude),
ST_GeogPoint(dropoff_longitude, dropoff_latitude)
) AS euclidean,
CONCAT(
ST_AsText(ST_SnapToGrid(ST_GeogPoint(pickup_longitude,
pickup_latitude), 0.1)),
ST_AsText(ST_SnapToGrid(ST_GeogPoint(dropoff_longitude,
dropoff_latitude), 0.1))
) AS loc_cross,
IF((tips/fare >= 0.2), 1, 0) AS tip_bin,
IF(RAND() <= 0.8, 'UNASSIGNED', 'TEST') AS ML_use
FROM
taxitrips
LIMIT @LIMIT
)
'''
sql_script = sql_script.replace(
'@PROJECT', PROJECT).replace(
'@DATASET', BQ_DATASET_NAME).replace(
'@TABLE', BQ_TABLE_NAME).replace(
'@YEAR', str(year)).replace(
'@LIMIT', str(sample_size))
print(sql_script)
bq_client = bigquery.Client(project=PROJECT, location=BQ_LOCATION)
job = bq_client.query(sql_script)
_ = job.result()
%%bigquery --project {PROJECT}
SELECT ML_use, COUNT(*)
FROM playground_us.chicago_taxitrips_prep # Change to your BQ dataset and table names.
GROUP BY ML_use
Explanation: 2. Create data for the ML task
We add a ML_use column for pre-splitting the data, where 80% of the datsa items are set to UNASSIGNED while the other 20% is set to TEST.
This column is used during training to split the dataset for training and test.
In the training phase, the UNASSIGNED are split into train and eval. The TEST split is will be used for the final model validation.
Create destination BigQuery dataset
End of explanation
%%bigquery sample_data --project {PROJECT}
SELECT * EXCEPT (trip_start_timestamp, ML_use)
FROM playground_us.chicago_taxitrips_prep # Change to your BQ dataset and table names.
sample_data.head().T
sample_data.tip_bin.value_counts()
sample_data.euclidean.hist()
Explanation: Load a sample data to a Pandas DataFrame
End of explanation
stats = tfdv.generate_statistics_from_dataframe(
dataframe=sample_data,
stats_options=tfdv.StatsOptions(
label_feature='tip_bin',
weight_feature=None,
sample_rate=1,
num_top_values=50
)
)
tfdv.visualize_statistics(stats)
schema = tfdv.infer_schema(statistics=stats)
tfdv.display_schema(schema=schema)
raw_schema_location = os.path.join(RAW_SCHEMA_DIR, 'schema.pbtxt')
tfdv.write_schema_text(schema, raw_schema_location)
Explanation: 3. Generate raw data schema
The TensorFlow Data Validation (TFDV) data schema will be used in:
1. Identify the raw data types and shapes in the data transformation.
2. Create the serving input signature for the custom model.
3. Validate the new raw training data in the TFX pipeline.
End of explanation
vertex_ai.init(
project=PROJECT,
location=REGION
)
Explanation: 4. Create Vertex Dataset resource
End of explanation
bq_uri = f"bq://{PROJECT}.{BQ_DATASET_NAME}.{BQ_TABLE_NAME}"
dataset = vertex_ai.TabularDataset.create(
display_name=DATASET_DISPLAY_NAME, bq_source=bq_uri)
dataset.gca_resource
Explanation: Create the dataset resource
End of explanation
dataset = vertex_ai.TabularDataset.list(
filter=f"display_name={DATASET_DISPLAY_NAME}",
order_by="update_time")[-1]
print("Dataset resource name:", dataset.resource_name)
print("Dataset BigQuery source:", dataset.gca_resource.metadata['inputConfig']['bigquerySource']['uri'])
Explanation: Get the dataset resource
The dataset resource is retrieved by display name. Because multiple datasets can have the same display name, we retrieve the most recent updated one.
End of explanation |
7,407 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring the Lorenz System of Differential Equations
In this Notebook we explore the Lorenz system of differential equations
Step2: Computing the trajectories and plotting the result
We define a function that can integrate the differential equations numerically and then plot the solutions. This function has arguments that control the parameters of the differential equation (\(\sigma\), \(\beta\), \(\rho\)), the numerical integration (N, max_time) and the visualization (angle).
Step3: Let's call the function once to view the solutions. For this set of parameters, we see the trajectories swirling around two points, called attractors.
Step4: Using IPython's interactive function, we can explore how the trajectories behave as we change the various parameters.
Step5: The object returned by interactive is a Widget object and it has attributes that contain the current result and arguments
Step6: After interacting with the system, we can take the result and perform further computations. In this case, we compute the average positions in \(x\), \(y\) and \(z\).
Step7: Creating histograms of the average positions (across different trajectories) show that on average the trajectories swirl about the attractors. | Python Code:
%matplotlib inline
from ipywidgets import interact, interactive
from IPython.display import clear_output, display, HTML
import numpy as np
from scipy import integrate
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import animation
Explanation: Exploring the Lorenz System of Differential Equations
In this Notebook we explore the Lorenz system of differential equations:
$$
\begin{aligned}
\dot{x} & = \sigma(y-x) \
\dot{y} & = \rho x - y - xz \
\dot{z} & = -\beta z + xy
\end{aligned}
$$
This is one of the classic systems in non-linear differential equations. It exhibits a range of different behaviors as the parameters (\(\sigma\), \(\beta\), \(\rho\)) are varied.
Imports
First, we import the needed things from IPython, NumPy, Matplotlib and SciPy.
End of explanation
def solve_lorenz(N=10, angle=0.0, max_time=4.0, sigma=10.0, beta=8./3, rho=28.0):
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('off')
# prepare the axes limits
ax.set_xlim((-25, 25))
ax.set_ylim((-35, 35))
ax.set_zlim((5, 55))
def lorenz_deriv(x_y_z, t0, sigma=sigma, beta=beta, rho=rho):
Compute the time-derivative of a Lorenz system.
x, y, z = x_y_z
return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
# Choose random starting points, uniformly distributed from -15 to 15
np.random.seed(1)
x0 = -15 + 30 * np.random.random((N, 3))
# Solve for the trajectories
t = np.linspace(0, max_time, int(250*max_time))
x_t = np.asarray([integrate.odeint(lorenz_deriv, x0i, t)
for x0i in x0])
# choose a different color for each trajectory
colors = plt.cm.viridis(np.linspace(0, 1, N))
for i in range(N):
x, y, z = x_t[i,:,:].T
lines = ax.plot(x, y, z, '-', c=colors[i])
plt.setp(lines, linewidth=2)
ax.view_init(30, angle)
plt.show()
return t, x_t
Explanation: Computing the trajectories and plotting the result
We define a function that can integrate the differential equations numerically and then plot the solutions. This function has arguments that control the parameters of the differential equation (\(\sigma\), \(\beta\), \(\rho\)), the numerical integration (N, max_time) and the visualization (angle).
End of explanation
t, x_t = solve_lorenz(angle=0, N=10)
Explanation: Let's call the function once to view the solutions. For this set of parameters, we see the trajectories swirling around two points, called attractors.
End of explanation
w = interactive(solve_lorenz, angle=(0.,360.), max_time=(0.1, 4.0),
N=(0,50), sigma=(0.0,50.0), rho=(0.0,50.0))
display(w)
Explanation: Using IPython's interactive function, we can explore how the trajectories behave as we change the various parameters.
End of explanation
t, x_t = w.result
w.kwargs
Explanation: The object returned by interactive is a Widget object and it has attributes that contain the current result and arguments:
End of explanation
xyz_avg = x_t.mean(axis=1)
xyz_avg.shape
Explanation: After interacting with the system, we can take the result and perform further computations. In this case, we compute the average positions in \(x\), \(y\) and \(z\).
End of explanation
plt.hist(xyz_avg[:,0])
plt.title('Average $x(t)$');
plt.hist(xyz_avg[:,1])
plt.title('Average $y(t)$');
Explanation: Creating histograms of the average positions (across different trajectories) show that on average the trajectories swirl about the attractors.
End of explanation |
7,408 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sigma to Pressure Interpolation
By using metpy.calc.log_interp, data with sigma as the vertical coordinate can be
interpolated to isobaric coordinates.
Step1: Data
The data for this example comes from the outer domain of a WRF-ARW model forecast
initialized at 1200 UTC on 03 June 1980. Model data courtesy Matthew Wilson, Valparaiso
University Department of Geography and Meteorology.
Step2: Array of desired pressure levels
Step3: Interpolate The Data
Now that the data is ready, we can interpolate to the new isobaric levels. The data is
interpolated from the irregular pressure values for each sigma level to the new input
mandatory isobaric levels. mpcalc.log_interp will interpolate over a specified dimension
with the axis argument. In this case, axis=1 will correspond to interpolation on the
vertical axis. The interpolated data is output in a list, so we will pull out each
variable for plotting.
Step4: Plotting the Data for 700 hPa. | Python Code:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
from netCDF4 import Dataset, num2date
import metpy.calc as mpcalc
from metpy.cbook import get_test_data
from metpy.plots import add_metpy_logo, add_timestamp
from metpy.units import units
Explanation: Sigma to Pressure Interpolation
By using metpy.calc.log_interp, data with sigma as the vertical coordinate can be
interpolated to isobaric coordinates.
End of explanation
data = Dataset(get_test_data('wrf_example.nc', False))
lat = data.variables['lat'][:]
lon = data.variables['lon'][:]
time = data.variables['time']
vtimes = num2date(time[:], time.units)
temperature = data.variables['temperature'][:] * units.celsius
pres = data.variables['pressure'][:] * units.pascal
hgt = data.variables['height'][:] * units.meter
Explanation: Data
The data for this example comes from the outer domain of a WRF-ARW model forecast
initialized at 1200 UTC on 03 June 1980. Model data courtesy Matthew Wilson, Valparaiso
University Department of Geography and Meteorology.
End of explanation
plevs = [700.] * units.hPa
Explanation: Array of desired pressure levels
End of explanation
height, temp = mpcalc.log_interp(plevs, pres, hgt, temperature, axis=1)
Explanation: Interpolate The Data
Now that the data is ready, we can interpolate to the new isobaric levels. The data is
interpolated from the irregular pressure values for each sigma level to the new input
mandatory isobaric levels. mpcalc.log_interp will interpolate over a specified dimension
with the axis argument. In this case, axis=1 will correspond to interpolation on the
vertical axis. The interpolated data is output in a list, so we will pull out each
variable for plotting.
End of explanation
# Set up our projection
crs = ccrs.LambertConformal(central_longitude=-100.0, central_latitude=45.0)
# Set the forecast hour
FH = 1
# Create the figure and grid for subplots
fig = plt.figure(figsize=(17, 12))
add_metpy_logo(fig, 470, 320, size='large')
# Plot 700 hPa
ax = plt.subplot(111, projection=crs)
ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.75)
ax.add_feature(cfeature.STATES, linewidth=0.5)
# Plot the heights
cs = ax.contour(lon, lat, height[FH, 0, :, :], transform=ccrs.PlateCarree(),
colors='k', linewidths=1.0, linestyles='solid')
ax.clabel(cs, fontsize=10, inline=1, inline_spacing=7,
fmt='%i', rightside_up=True, use_clabeltext=True)
# Contour the temperature
cf = ax.contourf(lon, lat, temp[FH, 0, :, :], range(-20, 20, 1), cmap=plt.cm.RdBu_r,
transform=ccrs.PlateCarree())
cb = fig.colorbar(cf, orientation='horizontal', extend='max', aspect=65, shrink=0.5,
pad=0.05, extendrect='True')
cb.set_label('Celsius', size='x-large')
ax.set_extent([-106.5, -90.4, 34.5, 46.75], crs=ccrs.PlateCarree())
# Make the axis title
ax.set_title('{:.0f} hPa Heights (m) and Temperature (C)'.format(plevs[0].m), loc='center',
fontsize=10)
# Set the figure title
fig.suptitle('WRF-ARW Forecast VALID: {:s} UTC'.format(str(vtimes[FH])), fontsize=14)
add_timestamp(ax, vtimes[FH], y=0.02, high_contrast=True)
plt.show()
Explanation: Plotting the Data for 700 hPa.
End of explanation |
7,409 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Index - Back - Next
Widget List
Complete list
For a complete list of the widgets available to you, you can list the classes in the widget namespace (as seen below). Widget and DOMWidget, not listed below, are base classes.
Step1: Numeric widgets
There are 8 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.
FloatSlider
Step2: Sliders can also be displayed vertically.
Step3: FloatProgress
Step4: BoundedFloatText
Step5: FloatText
Step6: Boolean widgets
There are two widgets that are designed to display a boolean value.
ToggleButton
Step7: Checkbox
Step8: Selection widgets
There are four widgets that can be used to display single selection lists, and one that can be used to display multiple selection lists. All inherit from the same base class. You can specify the enumeration of selectable options by passing a list. 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 returned when an item is selected.
Dropdown
Step9: The following is also valid
Step10: RadioButtons
Step11: Select
Step12: ToggleButtons
Step13: SelectMultiple
Multiple values can be selected with <kbd>shift</kbd> and <kbd>ctrl</kbd> pressed and mouse clicks or arrow keys.
Step14: String widgets
There are 4 widgets that can be used to display a string value. Of those, the Text and Textarea widgets accept input. The Latex and HTML widgets display the string as either Latex or HTML respectively, but do not accept input.
Text
Step15: Textarea
Step16: Latex
Step17: HTML
Step18: Button | Python Code:
from IPython.html import widgets
[n for n in dir(widgets) if not n.endswith('Widget') and n[0] == n[0].upper() and not n[0] == '_']
Explanation: Index - Back - Next
Widget List
Complete list
For a complete list of the widgets available to you, you can list the classes in the widget namespace (as seen below). Widget and DOMWidget, not listed below, are base classes.
End of explanation
widgets.FloatSlider(
value=7.5,
min=5.0,
max=10.0,
step=0.1,
description='Test:',
)
Explanation: Numeric widgets
There are 8 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.
FloatSlider
End of explanation
widgets.FloatSlider(
value=7.5,
min=5.0,
max=10.0,
step=0.1,
description='Test',
orientation='vertical',
)
Explanation: Sliders can also be displayed vertically.
End of explanation
widgets.FloatProgress(
value=7.5,
min=5.0,
max=10.0,
step=0.1,
description='Loading:',
)
Explanation: FloatProgress
End of explanation
widgets.BoundedFloatText(
value=7.5,
min=5.0,
max=10.0,
description='Text:',
)
Explanation: BoundedFloatText
End of explanation
widgets.FloatText(
value=7.5,
description='Any:',
)
Explanation: FloatText
End of explanation
widgets.ToggleButton(
description='Click me',
value=False,
)
Explanation: Boolean widgets
There are two widgets that are designed to display a boolean value.
ToggleButton
End of explanation
widgets.Checkbox(
description='Check me',
value=True,
)
Explanation: Checkbox
End of explanation
from IPython.display import display
w = widgets.Dropdown(
options=['1', '2', '3'],
value='2',
description='Number:',
)
display(w)
w.value
Explanation: Selection widgets
There are four widgets that can be used to display single selection lists, and one that can be used to display multiple selection lists. All inherit from the same base class. You can specify the enumeration of selectable options by passing a list. 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 returned when an item is selected.
Dropdown
End of explanation
w = widgets.Dropdown(
options={'One': 1, 'Two': 2, 'Three': 3},
value=2,
description='Number:',
)
display(w)
w.value
Explanation: The following is also valid:
End of explanation
widgets.RadioButtons(
description='Pizza topping:',
options=['pepperoni', 'pineapple', 'anchovies'],
)
Explanation: RadioButtons
End of explanation
widgets.Select(
description='OS:',
options=['Linux', 'Windows', 'OSX'],
)
Explanation: Select
End of explanation
widgets.ToggleButtons(
description='Speed:',
options=['Slow', 'Regular', 'Fast'],
)
Explanation: ToggleButtons
End of explanation
w = widgets.SelectMultiple(
description="Fruits",
options=['Apples', 'Oranges', 'Pears']
)
display(w)
w.value
Explanation: SelectMultiple
Multiple values can be selected with <kbd>shift</kbd> and <kbd>ctrl</kbd> pressed and mouse clicks or arrow keys.
End of explanation
widgets.Text(
description='String:',
value='Hello World',
)
Explanation: String widgets
There are 4 widgets that can be used to display a string value. Of those, the Text and Textarea widgets accept input. The Latex and HTML widgets display the string as either Latex or HTML respectively, but do not accept input.
Text
End of explanation
widgets.Textarea(
description='String:',
value='Hello World',
)
Explanation: Textarea
End of explanation
widgets.Latex(
value="$$\\frac{n!}{k!(n-k)!} = \\binom{n}{k}$$",
)
Explanation: Latex
End of explanation
widgets.HTML(
value="Hello <b>World</b>"
)
Explanation: HTML
End of explanation
widgets.Button(description='Click me')
Explanation: Button
End of explanation |
7,410 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div style="width
Step1: Next we create an instance of the RadarServer object to point at one of these collections. This downloads some top level metadata and sets things up so we can easily query the server.
Step2: We can use rs.variables to see a list of radar products available to view from this access URL.
Step3: If you're not a NEXRAD radar expert, there is more information available within the metadata downloaded from the server. (NOTE
Step4: We can also see a list of the stations. Each station has associated location information.
Step5: Next, we'll create a new query object to help request the data. Using the chaining methods, let's ask for reflectivity data at the lowest tilt (NOQ) from radar TLX (Oklahoma City) for the current time. We see that when the query is represented as a string, it shows the encoded URL.
Step6: The query also supports time range queries, queries for closest to a lon/lat point, or getting all radars within a lon/lat box.
We can use the RadarServer instance to check our query, to make sure we have required parameters and that we have chosen valid station(s) and variable(s).
Step7: Make the request, which returns an instance of TDSCatalog. This handles parsing the catalog
Step8: We can look at the datasets on the catalog to see what data we found by the query. We find one NIDS file in the return
Step9: Exercise
Step10: We'll use the CDMRemote reader in Siphon and pass it the appropriate access URL. (This will all behave identically to using the 'OPENDAP' access, if we replace the Dataset from Siphon with that from netCDF4).
Step11: The CDMRemote reader provides an interface that is almost identical to the usual python NetCDF interface.
Step12: We pull out the variables we need for azimuth and range, as well as the data itself.
Step13: Then convert the polar coordinates to Cartesian using numpy
Step14: Finally, we plot them up using matplotlib and cartopy. | Python Code:
from siphon.catalog import TDSCatalog
cat = TDSCatalog('http://thredds.ucar.edu/thredds/radarServer/catalog.xml')
list(cat.catalog_refs)
Explanation: <div style="width:1000 px">
<div style="float:right; width:98 px; height:98px;">
<img src="https://raw.githubusercontent.com/Unidata/MetPy/master/metpy/plots/_static/unidata_150x150.png" alt="Unidata Logo" style="height: 98px;">
</div>
<h1>Using Siphon to get NEXRAD Level 3 data from a TDS</h1>
<h3>Unidata Python Workshop</h3>
<div style="clear:both"></div>
</div>
<hr style="height:2px;">
<div style="float:right; width:250 px"><img src="https://upload.wikimedia.org/wikipedia/commons/4/4d/Siphoning.JPG" alt="Siphoning" style="height: 300px;"></div>
Objectives
Learn more about Siphon
Use the RadarServer class to retrieve radar data from a TDS
Plot this data using numpy arrays and matplotlib
In this example, we'll focus on interacting with the Radar Query Service to retrieve radar data.
But first!
Bookmark these resources for when you want to use Siphon later!
+ latest Siphon documentation
+ Siphon github repo
+ TDS documentation
Querying the server
First, we point at the top level of the Radar Query Service (the "Radar Server") to see what radar collections are available:
End of explanation
from siphon.radarserver import RadarServer
rs = RadarServer(cat.catalog_refs['NEXRAD Level III Radar from IDD'].href)
Explanation: Next we create an instance of the RadarServer object to point at one of these collections. This downloads some top level metadata and sets things up so we can easily query the server.
End of explanation
print(sorted(rs.variables))
Explanation: We can use rs.variables to see a list of radar products available to view from this access URL.
End of explanation
sorted(rs.metadata['variables'])
Explanation: If you're not a NEXRAD radar expert, there is more information available within the metadata downloaded from the server. (NOTE: Only the codes above are valid for queries.)
End of explanation
print(sorted(rs.stations))
rs.stations['TLX']
Explanation: We can also see a list of the stations. Each station has associated location information.
End of explanation
from datetime import datetime
query = rs.query()
query.stations('TLX').time(datetime.utcnow()).variables('N0Q')
Explanation: Next, we'll create a new query object to help request the data. Using the chaining methods, let's ask for reflectivity data at the lowest tilt (NOQ) from radar TLX (Oklahoma City) for the current time. We see that when the query is represented as a string, it shows the encoded URL.
End of explanation
rs.validate_query(query)
Explanation: The query also supports time range queries, queries for closest to a lon/lat point, or getting all radars within a lon/lat box.
We can use the RadarServer instance to check our query, to make sure we have required parameters and that we have chosen valid station(s) and variable(s).
End of explanation
catalog = rs.get_catalog(query)
Explanation: Make the request, which returns an instance of TDSCatalog. This handles parsing the catalog
End of explanation
catalog.datasets
Explanation: We can look at the datasets on the catalog to see what data we found by the query. We find one NIDS file in the return
End of explanation
ds = list(catalog.datasets.values())[0]
ds.access_urls
Explanation: Exercise: Querying the radar server
We'll work through doing some more queries on the radar server. Some useful links:
- RadarQuery documentation
- Documentation on Python's datetime.timedelta
See if you can write Python code for the following queries:
Get ZDR (differential reflectivity) for 3 days ago from the radar nearest to Hays, KS (lon -99.324403, lat 38.874929). No map necessary!
Get base reflectivity for the last two hours from all of the radars in Wyoming (call it the bounding box with lower left corner 41.008717, -111.056360 and upper right corner 44.981008, -104.042719)
Pulling out the data
We can pull that dataset out of the dictionary and look at the available access URLs. We see URLs for OPeNDAP, CDMRemote, and HTTPServer (direct download).
End of explanation
from siphon.cdmr import Dataset
data = Dataset(ds.access_urls['CdmRemote'])
Explanation: We'll use the CDMRemote reader in Siphon and pass it the appropriate access URL. (This will all behave identically to using the 'OPENDAP' access, if we replace the Dataset from Siphon with that from netCDF4).
End of explanation
list(data.variables)
Explanation: The CDMRemote reader provides an interface that is almost identical to the usual python NetCDF interface.
End of explanation
rng = data.variables['gate'][:]
az = data.variables['azimuth'][:]
ref = data.variables['BaseReflectivityDR'][:]
Explanation: We pull out the variables we need for azimuth and range, as well as the data itself.
End of explanation
import numpy as np
x = rng * np.sin(np.deg2rad(az))[:, None]
y = rng * np.cos(np.deg2rad(az))[:, None]
ref = np.ma.array(ref, mask=np.isnan(ref))
Explanation: Then convert the polar coordinates to Cartesian using numpy
End of explanation
%matplotlib inline
import matplotlib.pyplot as plt
import cartopy
import cartopy.feature as cfeature
from metpy.plots import ctables # For NWS colortable
# Create projection centered on the radar. This allows us to use x
# and y relative to the radar.
proj = cartopy.crs.LambertConformal(central_longitude=data.RadarLongitude,
central_latitude=data.RadarLatitude)
# New figure with specified projection
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(1, 1, 1, projection=proj)
ax.add_feature(cfeature.STATES.with_scale('50m'), linewidth=2)
# Set limits in lat/lon space
ax.set_extent([data.RadarLongitude - 2.5, data.RadarLongitude + 2.5,
data.RadarLatitude - 2.5, data.RadarLatitude + 2.5])
# Get the NWS typical reflectivity color table, along with an appropriate norm that
# starts at 5 dBz and has steps in 5 dBz increments
norm, cmap = ctables.registry.get_with_steps('NWSReflectivity', 5, 5)
mesh = ax.pcolormesh(x, y, ref, cmap=cmap, norm=norm, zorder=0)
Explanation: Finally, we plot them up using matplotlib and cartopy.
End of explanation |
7,411 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Project 2
Step1: Now, can you find out the following facts about the dataset?
- Total number of students
- Number of students who passed
- Number of students who failed
- Graduation rate of the class (%)
- Number of features
Use the code block below to compute these values. Instructions/steps are marked using TODOs.
Step2: 3. Preparing the Data
In this section, we will prepare the data for modeling, training and testing.
Identify feature and target columns
It is often the case that the data you obtain contains non-numeric features. This can be a problem, as most machine learning algorithms expect numeric data to perform computations with.
Let's first separate our data into feature and target columns, and see if any features are non-numeric.<br/>
Note
Step3: Preprocess feature columns
As you can see, there are several non-numeric columns that need to be converted! Many of them are simply yes/no, e.g. internet. These can be reasonably converted into 1/0 (binary) values.
Other columns, like Mjob and Fjob, have more than two values, and are known as categorical variables. The recommended way to handle such a column is to create as many columns as possible values (e.g. Fjob_teacher, Fjob_other, Fjob_services, etc.), and assign a 1 to one of them and 0 to all others.
These generated columns are sometimes called dummy variables, and we will use the pandas.get_dummies() function to perform this transformation.
Step4: Split data into training and test sets
So far, we have converted all categorical features into numeric values. In this next step, we split the data (both features and corresponding labels) into training and test sets.
Step5: 4. Training and Evaluating Models
Choose 3 supervised learning models that are available in scikit-learn, and appropriate for this problem. For each model
Step6: 5. Choosing the Best Model
Based on the experiments you performed earlier, in 1-2 paragraphs explain to the board of supervisors what single model you chose as the best model. Which model is generally the most appropriate based on the available data, limited resources, cost, and performance?
In 1-2 paragraphs explain to the board of supervisors in layman's terms how the final model chosen is supposed to work (for example if you chose a Decision Tree or Support Vector Machine, how does it make a prediction).
Fine-tune the model. Use Gridsearch with at least one important parameter tuned and with at least 3 settings. Use the entire training set for this.
What is the model's final F<sub>1</sub> score? | Python Code:
# Import libraries
import numpy as np
import pandas as pd
# Read student data
student_data = pd.read_csv("student-data.csv")
print "Student data read successfully!"
# Note: The last column 'passed' is the target/label, all other are feature columns
student_data.head()
Explanation: Project 2: Supervised Learning
Building a Student Intervention System
1. Classification vs Regression
Your goal is to identify students who might need early intervention - which type of supervised machine learning problem is this, classification or regression? Why?
2. Exploring the Data
Let's go ahead and read in the student dataset first.
To execute a code cell, click inside it and press Shift+Enter.
End of explanation
shape = student_data.shape
n_students = shape[0]
n_features = shape[1]-1 # the last column is the target
n_passed = len(student_data[student_data.passed == 'yes'])
n_failed = len(student_data[student_data.passed == 'no'])
grad_rate = 100*float(n_passed)/n_students
print "Total number of students: {}".format(n_students)
print "Number of students who passed: {}".format(n_passed)
print "Number of students who failed: {}".format(n_failed)
print "Number of features: {}".format(n_features)
print "Graduation rate of the class: {:.2f}%".format(grad_rate)
Explanation: Now, can you find out the following facts about the dataset?
- Total number of students
- Number of students who passed
- Number of students who failed
- Graduation rate of the class (%)
- Number of features
Use the code block below to compute these values. Instructions/steps are marked using TODOs.
End of explanation
# Extract feature (X) and target (y) columns
feature_cols = list(student_data.columns[:-1]) # all columns but last are features
target_col = student_data.columns[-1] # last column is the target/label
print "Feature column(s):-\n{}".format(feature_cols)
print "Target column: {}".format(target_col)
X_all = student_data[feature_cols] # feature values for all students
y_all = student_data[target_col] # corresponding targets/labels
print "\nFeature values:-"
print X_all.head() # print the first 5 rows
Explanation: 3. Preparing the Data
In this section, we will prepare the data for modeling, training and testing.
Identify feature and target columns
It is often the case that the data you obtain contains non-numeric features. This can be a problem, as most machine learning algorithms expect numeric data to perform computations with.
Let's first separate our data into feature and target columns, and see if any features are non-numeric.<br/>
Note: For this dataset, the last column ('passed') is the target or label we are trying to predict.
End of explanation
# Preprocess feature columns
def preprocess_features(X):
outX = pd.DataFrame(index=X.index) # output dataframe, initially empty
# Check each column
for col, col_data in X.iteritems():
# If data type is non-numeric, try to replace all yes/no values with 1/0
if col_data.dtype == object:
col_data = col_data.replace(['yes', 'no'], [1, 0])
# Note: This should change the data type for yes/no columns to int
# If still non-numeric, convert to one or more dummy variables
if col_data.dtype == object:
col_data = pd.get_dummies(col_data, prefix=col) # e.g. 'school' => 'school_GP', 'school_MS'
outX = outX.join(col_data) # collect column(s) in output dataframe
return outX
X_all = preprocess_features(X_all)
print "Processed feature columns ({}):-\n{}".format(len(X_all.columns), list(X_all.columns))
Explanation: Preprocess feature columns
As you can see, there are several non-numeric columns that need to be converted! Many of them are simply yes/no, e.g. internet. These can be reasonably converted into 1/0 (binary) values.
Other columns, like Mjob and Fjob, have more than two values, and are known as categorical variables. The recommended way to handle such a column is to create as many columns as possible values (e.g. Fjob_teacher, Fjob_other, Fjob_services, etc.), and assign a 1 to one of them and 0 to all others.
These generated columns are sometimes called dummy variables, and we will use the pandas.get_dummies() function to perform this transformation.
End of explanation
# First, decide how many training vs test samples you want
num_all = student_data.shape[0] # same as len(student_data)
num_train = 300 # about 75% of the data
num_test = num_all - num_train
# TODO: Then, select features (X) and corresponding labels (y) for the training and test sets
# Note: Shuffle the data or randomly select samples to avoid any bias due to ordering in the dataset
indices = range(num_all)
import random
random.shuffle(indices)
train_indices = indices[:num_train]
test_indices = indices[-num_test:]
X_train = X_all.iloc[train_indices]
y_train = y_all[train_indices]
X_test = X_all.iloc[test_indices]
y_test = y_all[test_indices]
print "Training set: {} samples".format(X_train.shape[0])
print "Test set: {} samples".format(X_test.shape[0])
# Note: If you need a validation set, extract it from within training data
Explanation: Split data into training and test sets
So far, we have converted all categorical features into numeric values. In this next step, we split the data (both features and corresponding labels) into training and test sets.
End of explanation
# Train a model
import time
def train_classifier(clf, X_train, y_train):
print "Training {}...".format(clf.__class__.__name__)
start = time.time()
clf.fit(X_train, y_train)
end = time.time()
print "Done!\nTraining time (secs): {:.3f}".format(end - start)
# TODO: Choose a model, import it and instantiate an object
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
# Fit model to training data
train_classifier(clf, X_train, y_train) # note: using entire training set here
print clf # you can inspect the learned model by printing it
# Predict on training set and compute F1 score
from sklearn.metrics import f1_score
def predict_labels(clf, features, target):
print "Predicting labels using {}...".format(clf.__class__.__name__)
start = time.time()
y_pred = clf.predict(features)
end = time.time()
print "Done!\nPrediction time (secs): {:.3f}".format(end - start)
return f1_score(target.values, y_pred, pos_label='yes')
train_f1_score = predict_labels(clf, X_train, y_train)
print "F1 score for training set: {}".format(train_f1_score)
# Predict on test data
print "F1 score for test set: {}".format(predict_labels(clf, X_test, y_test))
# Train and predict using different training set sizes
def train_predict(clf, X_train, y_train, X_test, y_test):
print "------------------------------------------"
print "Training set size: {}".format(len(X_train))
train_classifier(clf, X_train, y_train)
print "F1 score for training set: {}".format(predict_labels(clf, X_train, y_train))
print "F1 score for test set: {}".format(predict_labels(clf, X_test, y_test))
num_all = student_data.shape[0] # same as len(student_data)
num_test = 95
test_indices = indices[-num_test:]
X_test = X_all.iloc[test_indices]
y_test = y_all[test_indices]
indices = range(num_all)
import random
random.shuffle(indices)
def try_different_training_sizes(clf):
# TODO: Run the helper function above for desired subsets of training data
# Note: Keep the test set constant
for size in (100, 200, 300):
train_indices = indices[:size]
X_train = X_all.iloc[train_indices]
y_train = y_all[train_indices]
print(train_predict(clf, X_train, y_train, X_test, y_test))
# using DecisionTreeClassifier
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
try_different_training_sizes(clf)
# TODO: Train and predict using two other models
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import BaggingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
nb = GaussianNB()
bc = BaggingClassifier()
knc = KNeighborsClassifier()
svc = SVC()
try_different_training_sizes(bc)
try_different_training_sizes(nb)
try_different_training_sizes(knc)
try_different_training_sizes(svc)
Explanation: 4. Training and Evaluating Models
Choose 3 supervised learning models that are available in scikit-learn, and appropriate for this problem. For each model:
What is the theoretical O(n) time & space complexity in terms of input size?
What are the general applications of this model? What are its strengths and weaknesses?
Given what you know about the data so far, why did you choose this model to apply?
Fit this model to the training data, try to predict labels (for both training and test sets), and measure the F<sub>1</sub> score. Repeat this process with different training set sizes (100, 200, 300), keeping test set constant.
Produce a table showing training time, prediction time, F<sub>1</sub> score on training set and F<sub>1</sub> score on test set, for each training set size.
Note: You need to produce 3 such tables - one for each model.
End of explanation
# TODO: Fine-tune your model and report the best F1 score
Explanation: 5. Choosing the Best Model
Based on the experiments you performed earlier, in 1-2 paragraphs explain to the board of supervisors what single model you chose as the best model. Which model is generally the most appropriate based on the available data, limited resources, cost, and performance?
In 1-2 paragraphs explain to the board of supervisors in layman's terms how the final model chosen is supposed to work (for example if you chose a Decision Tree or Support Vector Machine, how does it make a prediction).
Fine-tune the model. Use Gridsearch with at least one important parameter tuned and with at least 3 settings. Use the entire training set for this.
What is the model's final F<sub>1</sub> score?
End of explanation |
7,412 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Motor Controller Sizing
There are a lot of things that go into sizing a motor controller. This will look at the torque needed to climb an incline. From that, and some data found on the internet, we can assume the required current and choose our motor controller.
Setup Needed Functions and Libraries
Step2: R2 isn't expected to do a lot of up hill climbing. For reference, power wheelchair ramp slope is 7.2 degrees to bound what kind of slope R2 could encounter in the school.
First, let's build a bunch of Imperial to SI units coversions.
Step3: Flat Floor
Step4: Wheelchair Ramp
If we look at the robot climbing a wheelchair ramp (7.2 deg), then the force/torques to not fall are
Step6: Range of Incline Angles | Python Code:
from __future__ import division
from __future__ import print_function
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from math import sin, pi, tan
Explanation: Motor Controller Sizing
There are a lot of things that go into sizing a motor controller. This will look at the torque needed to climb an incline. From that, and some data found on the internet, we can assume the required current and choose our motor controller.
Setup Needed Functions and Libraries
End of explanation
def lbf2N(w):
return w*4.448
def deg2rad(d):
return d*pi/180
def in2mm(i):
return i*25.4
def Nm2lbfin(nm):
return nm*8.851
# unknown table of values for motors
motor_t = [.22, 12.1, 19.8, 28.1, 38, 49.6, 60.1, 69.1, 81.3, 91.4, 100.7] # lbf-in
motor_c = [6.2, 10.2, 12.9, 15.6, 19.5, 23.6, 27.9, 31.3, 36.8, 41.4, 46.1] # Amps
plt.plot(motor_c, motor_t)
plt.grid(True)
plt.xlabel('Current [A]')
plt.ylabel('Torque [lbf-in]')
plt.title('NPC-2212 Motor Performance')
def force_total(inc):
Calculate the total force the wheels must overcome. This
is a function of both gravity pulling the robot down the ramp
and the frictional force between the wheels and the floor.
Returns the force ONE motor must overcome to not slide down the ramp.
w_N = lbf2N(90) # weight in N
# http://www.engineeringtoolbox.com/rolling-friction-resistance-d_1303.html
# 0.03 car tires on cobbles - large worn
frict_coeff = 0.03 # coefficient of friction, guess based on searching internet
force_fric = w_N*frict_coeff*2 # 2 leg wheels on the floor
force_incline = w_N*sin(deg2rad(inc)) # gravity pulling the robot down the ramp
return (force_fric + force_incline)/2 # divide by 2 because 2 leg motors
def torque(f):
r_wheel = in2mm(2.5) # wheel radius in mm
return f*r_wheel/1000
Explanation: R2 isn't expected to do a lot of up hill climbing. For reference, power wheelchair ramp slope is 7.2 degrees to bound what kind of slope R2 could encounter in the school.
First, let's build a bunch of Imperial to SI units coversions.
End of explanation
f = force_total(0)
t = torque(f)
print('force', f, 'N')
print('torque', t, ' Nm or ', Nm2lbfin(t), 'lbf-in')
Explanation: Flat Floor
End of explanation
f = force_total(7.2)
t = torque(f)
print('force', f, 'N')
print('torque', t, ' Nm or ', Nm2lbfin(t), 'lbf-in')
Explanation: Wheelchair Ramp
If we look at the robot climbing a wheelchair ramp (7.2 deg), then the force/torques to not fall are:
End of explanation
def wrapper(angles):
This is just a wrapper on the above functions so it is easier to find
the needed torque.
Arguments:
angles: an array of angles in degrees
Returns an array of torques
# w_N = lbf2N(70) # robot weight in N
# frict_coeff = 0.15
# r_wheel = in2mm(2.5) # wheel radius in mm
t = [] # output array of torques
for a in angles:
ff = force_total(a)
tt = torque(ff)
t.append(Nm2lbfin(tt))
return t
# plot some stuff
plt.subplot(1, 2, 1)
plt.plot(motor_c, motor_t)
plt.grid(True)
plt.xlabel('Current [A]')
plt.ylabel('Torque [lbf-in]')
plt.title('NPC-2212 Motor Performance')
plt.subplot(1,2,2)
x = range(0, 21)
y = wrapper(x)
plt.plot(x, y)
plt.grid(True)
plt.xlabel('Incline [degree]')
plt.ylabel('Torque [lbf-in]')
Explanation: Range of Incline Angles
End of explanation |
7,413 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> 2c. Loading large datasets progressively with the tf.data.Dataset </h1>
In this notebook, we continue reading the same small dataset, but refactor our ML pipeline in two small, but significant, ways
Step1: <h2> 1. Refactor the input </h2>
Read data created in Lab1a, but this time make it more general, so that we can later handle large datasets. We use the Dataset API for this. It ensures that, as data gets delivered to the model in mini-batches, it is loaded from disk only when needed.
Step2: <h2> 2. Refactor the way features are created. </h2>
For now, pass these through (same as previous lab). However, refactoring this way will enable us to break the one-to-one relationship between inputs and features.
Step3: <h2> Create and train the model </h2>
Note that we train for num_steps * batch_size examples.
Step4: <h3> Evaluate model </h3>
As before, evaluate on the validation data. We'll do the third refactoring (to move the evaluation into the training loop) in the next lab. | Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.5
from google.cloud import bigquery
import tensorflow as tf
import numpy as np
import shutil
print(tf.__version__)
Explanation: <h1> 2c. Loading large datasets progressively with the tf.data.Dataset </h1>
In this notebook, we continue reading the same small dataset, but refactor our ML pipeline in two small, but significant, ways:
Refactor the input to read data from disk progressively.
Refactor the feature creation so that it is not one-to-one with inputs.
The Pandas function in the previous notebook first read the whole data into memory -- on a large dataset, this won't be an option.
End of explanation
CSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key']
DEFAULTS = [[0.0], [-74.0], [40.0], [-74.0], [40.7], [1.0], ['nokey']]
def read_dataset(filename, mode, batch_size = 512):
def decode_csv(row):
columns = tf.compat.v1.decode_csv(row, record_defaults = DEFAULTS)
features = dict(zip(CSV_COLUMNS, columns))
features.pop('key') # discard, not a real feature
label = features.pop('fare_amount') # remove label from features and store
return features, label
# Create list of file names that match "glob" pattern (i.e. data_file_*.csv)
filenames_dataset = tf.data.Dataset.list_files(filename, shuffle=False)
# Read lines from text files
textlines_dataset = filenames_dataset.flat_map(tf.data.TextLineDataset)
# Parse text lines as comma-separated values (CSV)
dataset = textlines_dataset.map(decode_csv)
# Note:
# use tf.data.Dataset.flat_map to apply one to many transformations (here: filename -> text lines)
# use tf.data.Dataset.map to apply one to one transformations (here: text line -> feature list)
if mode == tf.estimator.ModeKeys.TRAIN:
num_epochs = None # loop indefinitely
dataset = dataset.shuffle(buffer_size = 10 * batch_size, seed=2)
else:
num_epochs = 1 # end-of-input after this
dataset = dataset.repeat(num_epochs).batch(batch_size)
return dataset
def get_train_input_fn():
return read_dataset('./taxi-train.csv', mode = tf.estimator.ModeKeys.TRAIN)
def get_valid_input_fn():
return read_dataset('./taxi-valid.csv', mode = tf.estimator.ModeKeys.EVAL)
Explanation: <h2> 1. Refactor the input </h2>
Read data created in Lab1a, but this time make it more general, so that we can later handle large datasets. We use the Dataset API for this. It ensures that, as data gets delivered to the model in mini-batches, it is loaded from disk only when needed.
End of explanation
INPUT_COLUMNS = [
tf.feature_column.numeric_column('pickuplon'),
tf.feature_column.numeric_column('pickuplat'),
tf.feature_column.numeric_column('dropofflat'),
tf.feature_column.numeric_column('dropofflon'),
tf.feature_column.numeric_column('passengers'),
]
def add_more_features(feats):
# Nothing to add (yet!)
return feats
feature_cols = add_more_features(INPUT_COLUMNS)
Explanation: <h2> 2. Refactor the way features are created. </h2>
For now, pass these through (same as previous lab). However, refactoring this way will enable us to break the one-to-one relationship between inputs and features.
End of explanation
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
OUTDIR = 'taxi_trained'
shutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time
model = tf.compat.v1.estimator.LinearRegressor(
feature_columns = feature_cols, model_dir = OUTDIR)
model.train(input_fn = get_train_input_fn, steps = 200)
Explanation: <h2> Create and train the model </h2>
Note that we train for num_steps * batch_size examples.
End of explanation
metrics = model.evaluate(input_fn = get_valid_input_fn, steps = None)
print('RMSE on dataset = {}'.format(np.sqrt(metrics['average_loss'])))
Explanation: <h3> Evaluate model </h3>
As before, evaluate on the validation data. We'll do the third refactoring (to move the evaluation into the training loop) in the next lab.
End of explanation |
7,414 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup data directory
Step1: Download database files
Step2: download a small test dataset
ATT | Python Code:
cd /usr/local/notebooks
mkdir -p ./data
cd ./data
Explanation: Setup data directory
End of explanation
!wget https://s3.amazonaws.com/ssusearchdb/SSUsearch_db.tgz
!tar -xzvf SSUsearch_db.tgz
Explanation: Download database files
End of explanation
!wget https://s3.amazonaws.com/ssusearchdb/test.tgz
!tar -xzvf test.tgz
ls test/data/
Explanation: download a small test dataset
ATT: for real (larger) dataset, make sure there is enough disk space.
End of explanation |
7,415 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scientific Computing with Python
This is a course about applying computer programming to problems of modeling physical systems and analysing data related to those systems. We'll be using a programming language called "Python 3". The first project is a "getting started" experience where you start to use the programming environment, become familiar with the basic elements of the language and, more or less, "learn your way around." Let's get started!
Installing/Accessing Python/Jupyter Notebook
The most reliable method of setting up an environment on your local computer is to use Anaconda. This will work and allow you to write code even without an internet connection. Unfortuantely it's not as convenient for collaborative work. For collaboration the easiest approach is to use deepnote. Finally, an option that works well with Google Drive is Google's own "colab" which works OK, but it's not as good with real-time interactive collaboration.
Notebook UI + Help
Before we get too far, first click on the "Help" menu and choose "User Interface Tour" and then "Keyboard Shortcuts". Look over these and remember where they are if you get stuck. You'll also see that under the "Help" menu there are links to module specific help sites for all the major python packages we'll be using this semester.
Built in types
First things first. Python comes with many "built in" types. These are things like integers, floating point numbers, srings, tuples, lists and dictionaries. Let's go over those one at a time.
Integers and floats are easy
Step1: Like most programming languages you can operate on these values using unary and binary operators, like so
Step2: Tuples and Lists
These guys are used to track collections of things. For example you can have a list of integers like so
Step3: The difference between these guys is that a list is 'mutable' and a tuple is not. In other words you can change a list by inserting, appending and deleting elements of the list, but a tuple, once born, cannot be modified.
Step4: Items within Tuples and lists can be accessed using their "index". Note that index values start at "0"
Step5: Note
Step6: Strings
A string is a collection of characters, which like a list can be indexed, but has extra methods that only make sense for strings. We use string to manage textual data.
Step8: String methods
You can manipulate strings by using built-in methods of string objects like so
Step9: Dictionaries
A dictionary is a structured type, similar a list in that it can be indexed, but not ordered like a list
Step10: import this
While you can do a lot with built-in python types, for many things we have to do in scientific computing it makes sense to import additional functionality using an "import" statement. Let's import the Pandas libaray using the python import statment
Step11: The most important object defined in pandas is the DataFrame. Here's one way to create a DataFrame with pandas using a dictionary
Step12: This creates a DataFrame with two "Columns" x and y. You can fetch the columns individually
Step13: Logic and Loops
It's hard to do much without loops sooner or later! There are two basic types of loops in python "for" and "while". The while loop executes the statements within it's scope until a logical expression becomes False. A for loop executes the statements within it's scope for every element of a sequence (e.g., a list, tuple, or any other sequence type). Basically if you have a sequence you need to iterate over, use a for loop. On the other hand, if you want to iterate until some condition is met, then use a while.
Here's an example
Step14: Functions
We often need to encapsulate code so that it can be easily re-used. This is a part of breaking down problems into smaller parts that are more manageable. Functions are easy to define in python, the basic syntax is | Python Code:
#
# When the cursor is in this cell hit "shift enter" to execute the python code here
#
x=3 # x is assigned an integer value of 3
y=2.4 # y is assigned a floating point value of 2.4
print("x and y are:", x, 'and',y)
Explanation: Scientific Computing with Python
This is a course about applying computer programming to problems of modeling physical systems and analysing data related to those systems. We'll be using a programming language called "Python 3". The first project is a "getting started" experience where you start to use the programming environment, become familiar with the basic elements of the language and, more or less, "learn your way around." Let's get started!
Installing/Accessing Python/Jupyter Notebook
The most reliable method of setting up an environment on your local computer is to use Anaconda. This will work and allow you to write code even without an internet connection. Unfortuantely it's not as convenient for collaborative work. For collaboration the easiest approach is to use deepnote. Finally, an option that works well with Google Drive is Google's own "colab" which works OK, but it's not as good with real-time interactive collaboration.
Notebook UI + Help
Before we get too far, first click on the "Help" menu and choose "User Interface Tour" and then "Keyboard Shortcuts". Look over these and remember where they are if you get stuck. You'll also see that under the "Help" menu there are links to module specific help sites for all the major python packages we'll be using this semester.
Built in types
First things first. Python comes with many "built in" types. These are things like integers, floating point numbers, srings, tuples, lists and dictionaries. Let's go over those one at a time.
Integers and floats are easy:
End of explanation
z=x+y
print("The value of z is:", z)
Explanation: Like most programming languages you can operate on these values using unary and binary operators, like so:
End of explanation
aList = [1,2,9,4,7]
print("We have a list:", aList, "with a length of:", len(aList))
aTuple = (1,2,9,4,7)
print("We have a tuple:", aTuple, "with a length of:", len(aTuple))
Explanation: Tuples and Lists
These guys are used to track collections of things. For example you can have a list of integers like so:
End of explanation
aList.append(17)
print("We now have a modified list:", aList, "with a length of ", len(aList))
aTuple.append(12) # this will fail! You can't append to a tuple.
Explanation: The difference between these guys is that a list is 'mutable' and a tuple is not. In other words you can change a list by inserting, appending and deleting elements of the list, but a tuple, once born, cannot be modified.
End of explanation
print("element 3 of the list is", aList[3])
print("element 27 of the tuple is", aTuple[27]) # this will fail! There is no such element.
Explanation: Items within Tuples and lists can be accessed using their "index". Note that index values start at "0":
End of explanation
print(aList*3)
print(aTuple*4)
Explanation: Note: When you "multiply" a list or a tuple by an integer you get copies of the original:
End of explanation
aString = "hello there world!"
print("We have a string:", aString, "whose length is:", len(aString))
print("the 9th element of aString is", aString[9])
Explanation: Strings
A string is a collection of characters, which like a list can be indexed, but has extra methods that only make sense for strings. We use string to manage textual data.
End of explanation
print(aString.split()) # split a string on spaces, convert to a list
bString=1,2,3,4
5,6,7,8
9,10,11,12
print("Here's what bString looks like:", repr(bString))
print("Let's split the lines:", bString.splitlines())
print(aString.upper())
Explanation: String methods
You can manipulate strings by using built-in methods of string objects like so:
End of explanation
aDict = {'a':1, 'b':"sam", 'joe':3.1415927}
print("We have a dictionary with keys:", aDict.keys())
print("It as values:", aDict.values())
print("And items:", aDict.items())
print("You can index it like an array:", aDict['joe'])
Explanation: Dictionaries
A dictionary is a structured type, similar a list in that it can be indexed, but not ordered like a list:
End of explanation
# tell the plotting system that we want plots inside the notebook
%matplotlib inline
import pandas as pd # we're renaming pandas as 'pd' here to save typing
Explanation: import this
While you can do a lot with built-in python types, for many things we have to do in scientific computing it makes sense to import additional functionality using an "import" statement. Let's import the Pandas libaray using the python import statment:
End of explanation
myDF = pd.DataFrame({'x':[1,2,3,4,5], 'y':[9,8,7,6,5]})
Explanation: The most important object defined in pandas is the DataFrame. Here's one way to create a DataFrame with pandas using a dictionary:
End of explanation
print("Here is x:", myDF.x.values)
print("Here is y:", myDF.y.values)
#
# It is possible to plot directly from the DataFrame
#
myDF.plot('x','y')
Explanation: This creates a DataFrame with two "Columns" x and y. You can fetch the columns individually:
End of explanation
print("Starting with:", repr(bString)) # show the raw string
for s in bString.splitlines():
print("Breaking down the string:", s)
for n in s.split(','):
print("Found the item:", n)
#
# another way with the while loop
#
cList=bString.splitlines()
while len(cList)>0:
s=cList.pop(0) # pop off the zeroth element of the list
for n in s.split(','):
print("Found item:", n)
Explanation: Logic and Loops
It's hard to do much without loops sooner or later! There are two basic types of loops in python "for" and "while". The while loop executes the statements within it's scope until a logical expression becomes False. A for loop executes the statements within it's scope for every element of a sequence (e.g., a list, tuple, or any other sequence type). Basically if you have a sequence you need to iterate over, use a for loop. On the other hand, if you want to iterate until some condition is met, then use a while.
Here's an example:
End of explanation
def myFunction(x): # function to compute 1.0/(x**2 + 1.0)
aLocalVar = x*x+1.0 # this is x**2 + 1.0
return 1.0/aLocalVar # finally 1.0/(x**2 + 1.0)
for i in range(10):
print("i=",i,"myFunction(i):", myFunction(i))
Explanation: Functions
We often need to encapsulate code so that it can be easily re-used. This is a part of breaking down problems into smaller parts that are more manageable. Functions are easy to define in python, the basic syntax is:
End of explanation |
7,416 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Color palette with python
Germain Salvato Vallverdu germain.vallverdu@univ-pau.fr
This notebook aims to present several ways to manage color palette with python, mainly for plot purpose.
Import some packages
Step3: Functions
Define convenient functions to plot a matplotlib colormap or a list of colors with matplotlib.
See this gist
Step4: Color models
How to define a color ?
RGB
Step5: Sequential palettes
Color scale
Use it if there is an order between the data
Example
Step6: Reverse order
In matplotlib all palettes suffixed by _r are reversed.
Step7: Divergent palettes
Usefull if there is a central value which play a specific role
values disposed around zero
Example
Step8: Build a custum color palette
some tools
matplotlib colormaps
seaborn palettes
colorlover palettes
With matplotlib
matplotlib colormaps
matplotlib colormaps are in matplotlib.cm module
colormap allows to map values on a color scale
Example colormap summer
Step9: colormap returns a rgba color.
Step10: X is a float number or a list or an array
X must be between 0 and plt.cm.colormap.N
You can define opacity
Step11: You can change interval values using Normalize
Step12: With colorlover
Step13: Colorlover provides function to set up a color palette
py
import colorlover as cl
cl.colorsys
Step14: Divergent color palette PuOr with 4 colors
Step15: conversion in RGB triplets
In order to use this palette with matplotlib you have to convert it in true RGB triplets.
Step16: With seaborn
Step17: The documentation is really clear and provides a nice tutorial seaborn color palettes. The following juste provides simple exampl cases.
py
import seaborn as sns
seaborn provides several functions in order to build and show color palettes. For example, in order to show the current palette
Step18: A qualitative palette
Step19: A sequential palette
Step20: A divergente palette | Python Code:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from IPython.display import HTML # intégration notebook
%matplotlib inline
Explanation: Color palette with python
Germain Salvato Vallverdu germain.vallverdu@univ-pau.fr
This notebook aims to present several ways to manage color palette with python, mainly for plot purpose.
Import some packages
End of explanation
def plot_cmap(cmap, ncolor=6):
A convenient function to plot colors of a matplotlib cmap
Args:
ncolor (int): number of color to show
cmap: a cmap object or a matplotlib color name
if isinstance(cmap, str):
try:
cm = plt.get_cmap(cmap)
except ValueError:
print("WARNINGS :", cmap, " is not a known colormap")
cm = plt.cm.gray
else:
cm = cmap
with plt.rc_context(plt.rcParamsDefault):
fig = plt.figure(figsize=(6, 1), frameon=False)
ax = fig.add_subplot(111)
ax.pcolor(np.linspace(1, ncolor, ncolor).reshape(1, ncolor), cmap=cm)
ax.set_title(cm.name)
xt = ax.set_xticks([])
yt = ax.set_yticks([])
return fig
def show_colors(colors):
Draw a square for each color contained in the colors list
given in argument.
with plt.rc_context(plt.rcParamsDefault):
fig = plt.figure(figsize=(6, 1), frameon=False)
ax = fig.add_subplot(111)
for x, color in enumerate(colors):
ax.add_patch(
mpl.patches.Rectangle(
(x, 0), 1, 1, facecolor=color
)
)
ax.set_xlim((0, len(colors)))
ax.set_ylim((0, 1))
ax.set_xticks([])
ax.set_yticks([])
ax.set_aspect("equal")
return fig
Explanation: Functions
Define convenient functions to plot a matplotlib colormap or a list of colors with matplotlib.
See this gist
End of explanation
plot_cmap("Dark2", 4)
plot_cmap("Dark2", 4).savefig("img/qualitative.png", bbox_inches="tight")
Explanation: Color models
How to define a color ?
RGB : Red Green Blue, additive color model
HSL : Hue Saturation Light
CMYK- : Cyan Magenta Yellow Black, soustractive color model
RGB
Red Green Blue
an additive color model
set "the amount" of a each based color
each color is defined by un nombre between 0 and 255 (8 bits = 1 octet)
red (255, 0, 0)
green (0, 255, 0)
blue (0, 0, 255)
HTML color codes
HTML color codes are another way to define a RGB color using an hexadecimal numeral system.
HTML color starts with a # character
the folowing 6 characters defines the intensity of red, green and blue colors
each pair correspond to a number in hexadecimal numeral system from 0 to FF (255)
example : #2D85C9 <-> (48, 133, 201)
2D -> 48
85 -> 133
C9 -> 201
RGB and RGBA
extension of RGB model
a for alpha (canal alpha)
RGBA = RGB + opacity
opicty is defined between 0 (transparent) and 1 (opaque)
HSL
Hue, staturation, light
Closer to the human perception of the color than RGB model
Hue is define on a wheel from an angle between 0 and 360°
Saturation and light are defined between 0 et 100%
CYMK
Cyan Yellow Magenta Black
Based on a substractive color model
Used by printers
Several kinds of palette
qualitative palettes
sequential palettes
divergentes palettes
Qualitatives palettes
Used to distinguish several groups of data without order or relationship
Example
End of explanation
plot_cmap("Blues", 8)
plot_cmap("Blues", 8).savefig("img/sequentielle.png", bbox_inches="tight")
Explanation: Sequential palettes
Color scale
Use it if there is an order between the data
Example
End of explanation
plot_cmap("Blues_r", 8)
plot_cmap("Blues_r", 8).savefig("img/sequentielle_r.png", bbox_inches="tight")
Explanation: Reverse order
In matplotlib all palettes suffixed by _r are reversed.
End of explanation
plot_cmap("coolwarm", 9)
plot_cmap("coolwarm", 9).savefig("img/divergente.png", bbox_inches="tight")
Explanation: Divergent palettes
Usefull if there is a central value which play a specific role
values disposed around zero
Example
End of explanation
plot_cmap(plt.cm.summer, 6)
plot_cmap(plt.cm.summer, 6).savefig("img/summer.png", bbox_inches="tight")
Explanation: Build a custum color palette
some tools
matplotlib colormaps
seaborn palettes
colorlover palettes
With matplotlib
matplotlib colormaps
matplotlib colormaps are in matplotlib.cm module
colormap allows to map values on a color scale
Example colormap summer
End of explanation
plt.cm.summer(X=42)
Explanation: colormap returns a rgba color.
End of explanation
print("Max val = ", plt.cm.summer.N)
palette = plt.cm.summer(X=[1, 50, 100, 200], alpha=.6)
print(palette)
show_colors(palette)
show_colors(palette).savefig("img/mpl_palette1.png")
Explanation: X is a float number or a list or an array
X must be between 0 and plt.cm.colormap.N
You can define opacity
End of explanation
normalize = mpl.colors.Normalize(vmin=-5, vmax=5)
palette = plt.cm.summer(X=normalize([-4, -2, 0, 2, 4]), alpha=1)
print(palette)
show_colors(palette)
show_colors(palette).savefig("img/mpl_palette2.png")
Explanation: You can change interval values using Normalize
End of explanation
import colorlover as cl
Explanation: With colorlover
End of explanation
HTML(cl.to_html(cl.scales["4"]["div"]))
Explanation: Colorlover provides function to set up a color palette
py
import colorlover as cl
cl.colorsys : conversion between color models
cl.scales : color palette
cl.to_HTML : help function to show the palette
cl.scales has to be used following :
py
cl.scales["number"]["type"]["name"]
where
number is a number between 3 and 12 included
type is : div, seq or qual
name is the palette name
All palettes are not available for all combinations.
For example, this is divergent palettes with 4 colors. You have to use cl.to_html to get an html version and HTML() to ask the notebook to display the html code and show the palette.
End of explanation
cl.scales["4"]["div"]["PuOr"]
Explanation: Divergent color palette PuOr with 4 colors :
End of explanation
cl.to_numeric(cl.scales["4"]["div"]["PuOr"])
Explanation: conversion in RGB triplets
In order to use this palette with matplotlib you have to convert it in true RGB triplets.
End of explanation
import seaborn as sns
Explanation: With seaborn
End of explanation
current_palette = sns.color_palette()
sns.palplot(current_palette)
Explanation: The documentation is really clear and provides a nice tutorial seaborn color palettes. The following juste provides simple exampl cases.
py
import seaborn as sns
seaborn provides several functions in order to build and show color palettes. For example, in order to show the current palette :
End of explanation
sns.palplot(sns.color_palette("husl", 8))
Explanation: A qualitative palette
End of explanation
sns.palplot(sns.light_palette("violet", 4))
Explanation: A sequential palette
End of explanation
sns.palplot(sns.diverging_palette(220, 20, n=5))
Explanation: A divergente palette
End of explanation |
7,417 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ch 07
Step1: Instead of feeding all the training data to the training op, we will feed data in small batches
Step2: Define the autoencoder class
Step3: The Iris dataset is often used as a simple training dataset to check whether a classification algorithm is working. The sklearn library comes with it, pip install sklearn. | Python Code:
import tensorflow as tf
import numpy as np
Explanation: Ch 07: Concept 01
Autoencoder
All we'll need is TensorFlow and NumPy:
End of explanation
def get_batch(X, size):
a = np.random.choice(len(X), size, replace=False)
return X[a]
Explanation: Instead of feeding all the training data to the training op, we will feed data in small batches:
End of explanation
class Autoencoder:
def __init__(self, input_dim, hidden_dim, epoch=500, batch_size=10, learning_rate=0.001):
self.epoch = epoch
self.batch_size = batch_size
self.learning_rate = learning_rate
# Define input placeholder
x = tf.placeholder(dtype=tf.float32, shape=[None, input_dim])
# Define variables
with tf.name_scope('encode'):
weights = tf.Variable(tf.random_normal([input_dim, hidden_dim], dtype=tf.float32), name='weights')
biases = tf.Variable(tf.zeros([hidden_dim]), name='biases')
encoded = tf.nn.sigmoid(tf.matmul(x, weights) + biases)
with tf.name_scope('decode'):
weights = tf.Variable(tf.random_normal([hidden_dim, input_dim], dtype=tf.float32), name='weights')
biases = tf.Variable(tf.zeros([input_dim]), name='biases')
decoded = tf.matmul(encoded, weights) + biases
self.x = x
self.encoded = encoded
self.decoded = decoded
# Define cost function and training op
self.loss = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(self.x, self.decoded))))
self.all_loss = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(self.x, self.decoded)), 1))
self.train_op = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss)
# Define a saver op
self.saver = tf.train.Saver()
def train(self, data):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(self.epoch):
for j in range(500):
batch_data = get_batch(data, self.batch_size)
l, _ = sess.run([self.loss, self.train_op], feed_dict={self.x: batch_data})
if i % 50 == 0:
print('epoch {0}: loss = {1}'.format(i, l))
self.saver.save(sess, './model.ckpt')
self.saver.save(sess, './model.ckpt')
def test(self, data):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
hidden, reconstructed = sess.run([self.encoded, self.decoded], feed_dict={self.x: data})
print('input', data)
print('compressed', hidden)
print('reconstructed', reconstructed)
return reconstructed
def get_params(self):
with tf.Session() as sess:
self.saver.restore(sess, './model.ckpt')
weights, biases = sess.run([self.weights1, self.biases1])
return weights, biases
def classify(self, data, labels):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.saver.restore(sess, './model.ckpt')
hidden, reconstructed = sess.run([self.encoded, self.decoded], feed_dict={self.x: data})
reconstructed = reconstructed[0]
# loss = sess.run(self.all_loss, feed_dict={self.x: data})
print('data', np.shape(data))
print('reconstructed', np.shape(reconstructed))
loss = np.sqrt(np.mean(np.square(data - reconstructed), axis=1))
print('loss', np.shape(loss))
horse_indices = np.where(labels == 7)[0]
not_horse_indices = np.where(labels != 7)[0]
horse_loss = np.mean(loss[horse_indices])
not_horse_loss = np.mean(loss[not_horse_indices])
print('horse', horse_loss)
print('not horse', not_horse_loss)
return hidden[7,:]
def decode(self, encoding):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.saver.restore(sess, './model.ckpt')
reconstructed = sess.run(self.decoded, feed_dict={self.encoded: encoding})
img = np.reshape(reconstructed, (32, 32))
return img
Explanation: Define the autoencoder class:
End of explanation
from sklearn import datasets
hidden_dim = 1
data = datasets.load_iris().data
input_dim = len(data[0])
ae = Autoencoder(input_dim, hidden_dim)
ae.train(data)
ae.test([[8, 4, 6, 2]])
Explanation: The Iris dataset is often used as a simple training dataset to check whether a classification algorithm is working. The sklearn library comes with it, pip install sklearn.
End of explanation |
7,418 | 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="#Building-an-ANN" data-toc-modified-id="Building-an-ANN-1"><span class="toc-item-num">1 </span>Building an ANN</a></div><div class="lev2 toc-item"><a href="#Installing-packages" data-toc-modified-id="Installing-packages-11"><span class="toc-item-num">1.1 </span>Installing packages</a></div><div class="lev2 toc-item"><a href="#Data-Preprocessing" data-toc-modified-id="Data-Preprocessing-12"><span class="toc-item-num">1.2 </span>Data Preprocessing</a></div><div class="lev2 toc-item"><a href="#Building-an-ANN" data-toc-modified-id="Building-an-ANN-13"><span class="toc-item-num">1.3 </span>Building an ANN</a></div><div class="lev2 toc-item"><a href="#Making-predictions-and-evaluating-the-model" data-toc-modified-id="Making-predictions-and-evaluating-the-model-14"><span class="toc-item-num">1.4 </span>Making predictions and evaluating the model</a></div><div class="lev2 toc-item"><a href="#Evaluating,-Improving-and-Tuning-the-ANN" data-toc-modified-id="Evaluating,-Improving-and-Tuning-the-ANN-15"><span class="toc-item-num">1.5 </span>Evaluating, Improving and Tuning the ANN</a></div>
# Building an ANN
Credit
Step1: Data Preprocessing
Step2: y (actual value)
Step3: Building an ANN
Step4: Making predictions and evaluating the model
Step5: Evaluating, Improving and Tuning the ANN
Using K-Fold Cross validation with Keras | Python Code:
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# pip install tensorflow
# Installing Keras
# pip install --upgrade keras
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Building-an-ANN" data-toc-modified-id="Building-an-ANN-1"><span class="toc-item-num">1 </span>Building an ANN</a></div><div class="lev2 toc-item"><a href="#Installing-packages" data-toc-modified-id="Installing-packages-11"><span class="toc-item-num">1.1 </span>Installing packages</a></div><div class="lev2 toc-item"><a href="#Data-Preprocessing" data-toc-modified-id="Data-Preprocessing-12"><span class="toc-item-num">1.2 </span>Data Preprocessing</a></div><div class="lev2 toc-item"><a href="#Building-an-ANN" data-toc-modified-id="Building-an-ANN-13"><span class="toc-item-num">1.3 </span>Building an ANN</a></div><div class="lev2 toc-item"><a href="#Making-predictions-and-evaluating-the-model" data-toc-modified-id="Making-predictions-and-evaluating-the-model-14"><span class="toc-item-num">1.4 </span>Making predictions and evaluating the model</a></div><div class="lev2 toc-item"><a href="#Evaluating,-Improving-and-Tuning-the-ANN" data-toc-modified-id="Evaluating,-Improving-and-Tuning-the-ANN-15"><span class="toc-item-num">1.5 </span>Evaluating, Improving and Tuning the ANN</a></div>
# Building an ANN
Credit: [Deep Learning A-Z™: Hands-On Artificial Neural Networks](https://www.udemy.com/deeplearning/learn/v4/content)
- [Getting the dataset](https://www.superdatascience.com/deep-learning/)
## Installing packages
End of explanation
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('./Artificial_Neural_Networks/Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values
Explanation: Data Preprocessing
End of explanation
print (X.shape)
X
print (y.shape)
y
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]
print (X.shape)
X
print (y.shape)
y
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
Explanation: y (actual value): exited, this is the value we are trying to predict, which means if the customer stays or exit the bank.
End of explanation
# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense
# Initialising the ANN
classifier = Sequential()
# Adding the input layer and the first hidden layer
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
# Adding the second hidden layer
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
# Adding the output layer
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
# Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Fitting the ANN to the Training set
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)
Explanation: Building an ANN
End of explanation
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
cm
Explanation: Making predictions and evaluating the model
End of explanation
# Evaluating the ANN
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
from keras.models import Sequential
from keras.layers import Dense
def build_classifier():
classifier = Sequential()
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
return classifier
classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100)
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)
mean = accuracies.mean()
variance = accuracies.std()
# Improving the ANN
# Dropout Regularization to reduce overfitting if needed
# Tuning the ANN
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
def build_classifier(optimizer):
classifier = Sequential()
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
# classifier.add(Dropout(p = 0.1))
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
# classifier.add(Dropout(p = 0.1))
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
classifier.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy'])
return classifier
classifier = KerasClassifier(build_fn = build_classifier)
parameters = {'batch_size': [25, 32],
'epochs': [100, 500],
'optimizer': ['adam', 'rmsprop']}
grid_search = GridSearchCV(estimator = classifier,
param_grid = parameters,
scoring = 'accuracy',
cv = 10)
grid_search = grid_search.fit(X_train, y_train)
best_parameters = grid_search.best_params_
best_accuracy = grid_search.best_score_
Explanation: Evaluating, Improving and Tuning the ANN
Using K-Fold Cross validation with Keras
End of explanation |
7,419 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RTA workload
The RTA or RTApp workload represents a type of workload obtained using the rt-app test application.
More details on the test application can be found at https
Step1: Test environment setup
For more details on this please check out examples/utils/testenv_example.ipynb.
Step2: Workload configuration
To create an instance of an RTApp workload generator you need to provide the following
Step3: The output of the previous cell reports the main properties of the generated
tasks. Thus for example we see that the first task is configure to be
Step4: Workload execution
Step5: Collected results
Step6: Trace inspection
More information on visualization and trace inspection can be found in examples/trappy.
Step7: RTApp task performance plots | Python Code:
import logging
from conf import LisaLogging
LisaLogging.setup()
# Generate plots inline
%pylab inline
import json
import os
# Support to initialise and configure your test environment
import devlib
from env import TestEnv
# Support to configure and run RTApp based workloads
from wlgen import RTA, Periodic, Ramp, Step, Pulse
# Suport for FTrace events parsing and visualization
import trappy
# Support for performance analysis of RTApp workloads
from perf_analysis import PerfAnalysis
Explanation: RTA workload
The RTA or RTApp workload represents a type of workload obtained using the rt-app test application.
More details on the test application can be found at https://github.com/scheduler-tools/rt-app.
End of explanation
# Setup a target configuration
my_target_conf = {
# Define the kind of target platform to use for the experiments
"platform" : 'linux', # Linux system, valid other options are:
# android - access via ADB
# linux - access via SSH
# host - direct access
# Preload settings for a specific target
"board" : 'juno', # juno - JUNO board with mainline hwmon
# Define devlib module to load
"modules" : [
'bl', # enable big.LITTLE support
'cpufreq' # enable CPUFreq support
],
# Account to access the remote target
"host" : '192.168.0.1',
"username" : 'root',
"password" : 'juno',
# Comment the following line to force rt-app calibration on your target
"rtapp-calib" : {
'0': 361, '1': 138, '2': 138, '3': 352, '4': 360, '5': 353
}
}
# Setup the required Test Environment supports
my_tests_conf = {
# Binary tools required to run this experiment
# These tools must be present in the tools/ folder for the architecture
"tools" : ['rt-app', 'taskset', 'trace-cmd'],
# FTrace events end buffer configuration
"ftrace" : {
"events" : [
"sched_switch",
"cpu_frequency"
],
"buffsize" : 10240
},
}
# Initialize a test environment using
# - the provided target configuration (my_target_conf)
# - the provided test configuration (my_test_conf)
te = TestEnv(target_conf=my_target_conf, test_conf=my_tests_conf)
target = te.target
Explanation: Test environment setup
For more details on this please check out examples/utils/testenv_example.ipynb.
End of explanation
# Create a new RTApp workload generator using the calibration values
# reported by the TestEnv module
rtapp = RTA(target, 'simple', calibration=te.calibration())
# Configure this RTApp instance to:
rtapp.conf(
# 1. generate a "profile based" set of tasks
kind='profile',
# 2. define the "profile" of each task
params={
# 3. PERIODIC task
#
# This class defines a task which load is periodic with a configured
# period and duty-cycle.
#
# This class is a specialization of the 'pulse' class since a periodic
# load is generated as a sequence of pulse loads.
#
# Args:
# cuty_cycle_pct (int, [0-100]): the pulses load [%]
# default: 50[%]
# duration_s (float): the duration in [s] of the entire workload
# default: 1.0[s]
# period_ms (float): the period used to define the load in [ms]
# default: 100.0[ms]
# delay_s (float): the delay in [s] before ramp start
# default: 0[s]
# sched (dict): the scheduler configuration for this task
# cpus (list): the list of CPUs on which task can run
'task_per20': Periodic(
period_ms=100, # period
duty_cycle_pct=20, # duty cycle
duration_s=5, # duration
cpus=None, # run on all CPUS
sched={
"policy": "FIFO", # Run this task as a SCHED_FIFO task
},
delay_s=0 # start at the start of RTApp
).get(),
# 4. RAMP task
#
# This class defines a task which load is a ramp with a configured number
# of steps according to the input parameters.
#
# Args:
# start_pct (int, [0-100]): the initial load [%], (default 0[%])
# end_pct (int, [0-100]): the final load [%], (default 100[%])
# delta_pct (int, [0-100]): the load increase/decrease [%],
# default: 10[%]
# increase if start_prc < end_prc
# decrease if start_prc > end_prc
# time_s (float): the duration in [s] of each load step
# default: 1.0[s]
# period_ms (float): the period used to define the load in [ms]
# default: 100.0[ms]
# delay_s (float): the delay in [s] before ramp start
# default: 0[s]
# loops (int): number of time to repeat the ramp, with the
# specified delay in between
# default: 0
# sched (dict): the scheduler configuration for this task
# cpus (list): the list of CPUs on which task can run
'task_rmp20_5-60': Ramp(
period_ms=100, # period
start_pct=5, # intial load
end_pct=65, # end load
delta_pct=20, # load % increase...
time_s=1, # ... every 1[s]
cpus="0" # run just on first CPU
).get(),
# 5. STEP task
#
# This class defines a task which load is a step with a configured
# initial and final load.
#
# Args:
# start_pct (int, [0-100]): the initial load [%]
# default 0[%])
# end_pct (int, [0-100]): the final load [%]
# default 100[%]
# time_s (float): the duration in [s] of the start and end load
# default: 1.0[s]
# period_ms (float): the period used to define the load in [ms]
# default 100.0[ms]
# delay_s (float): the delay in [s] before ramp start
# default 0[s]
# loops (int): number of time to repeat the ramp, with the
# specified delay in between
# default: 0
# sched (dict): the scheduler configuration for this task
# cpus (list): the list of CPUs on which task can run
'task_stp10-50': Step(
period_ms=100, # period
start_pct=0, # intial load
end_pct=50, # end load
time_s=1, # ... every 1[s]
delay_s=0.5 # start .5[s] after the start of RTApp
).get(),
# 6. PULSE task
#
# This class defines a task which load is a pulse with a configured
# initial and final load.
#
# The main difference with the 'step' class is that a pulse workload is
# by definition a 'step down', i.e. the workload switch from an finial
# load to a final one which is always lower than the initial one.
# Moreover, a pulse load does not generate a sleep phase in case of 0[%]
# load, i.e. the task ends as soon as the non null initial load has
# completed.
#
# Args:
# start_pct (int, [0-100]): the initial load [%]
# default: 0[%]
# end_pct (int, [0-100]): the final load [%]
# default: 100[%]
# NOTE: must be lower than start_pct value
# time_s (float): the duration in [s] of the start and end load
# default: 1.0[s]
# NOTE: if end_pct is 0, the task end after the
# start_pct period completed
# period_ms (float): the period used to define the load in [ms]
# default: 100.0[ms]
# delay_s (float): the delay in [s] before ramp start
# default: 0[s]
# loops (int): number of time to repeat the ramp, with the
# specified delay in between
# default: 0
# sched (dict): the scheduler configuration for this task
# cpus (list): the list of CPUs on which task can run
'task_pls5-80': Pulse(
period_ms=100, # period
start_pct=65, # intial load
end_pct=5, # end load
time_s=1, # ... every 1[s]
delay_s=0.5 # start .5[s] after the start of RTApp
).get(),
},
# 7. use this folder for task logfiles
run_dir=target.working_directory
);
Explanation: Workload configuration
To create an instance of an RTApp workload generator you need to provide the following:
- target: target device configuration
- name: name of workload. This is the name of the JSON configuration file reporting the generated RTApp configuration.
- calibration: CPU load calibration values, measured on each core.
An RTApp workload is defined by specifying a kind, provided below through rtapp.conf, which represents the way we want to define the behavior of each task.
The possible kinds of workloads are profile and custom. It's very important to notice that periodic is no longer considered a "kind" of workload but a "class" within the profile kind.
<br><br>
As you see below, when "kind" is "profile", the tasks generated by this workload have a profile which is defined by a sequence of phases. These phases are defined according to the following grammar:<br>
- params := {task, ...} <br>
- task := NAME : {SCLASS, PRIO, [phase, ...]}<br>
- phase := (PTIME, PERIOD, DCYCLE)<br> <br>
There are some pre-defined task classes for the profile kind:
- Step: the load of this task is a step with a configured initial and final load.
- Pulse: the load of this task is a pulse with a configured initial and final load.The main difference with the 'step' class is that a pulse workload is by definition a 'step down', i.e. the workload switches from an initial load to a final one which is always lower than the initial one. Moreover, a pulse load does not generate a sleep phase in case of 0[%] load, i.e. the task ends as soon as the non null initial load has completed.
- Ramp: the load of this task is a ramp with a configured number of steps determined by the input parameters.
- Periodic: the load of this task is periodic with a configured period and duty-cycle.<br><br>
The one below is a workload mix having all types of workloads described above, but each of them can also be specified serapately in the RTApp parameters.
End of explanation
# Initial phase and pinning parameters
ramp = Ramp(period_ms=100, start_pct=5, end_pct=65, delta_pct=20, time_s=1, cpus="0")
# Following phases
medium_slow = Periodic(duty_cycle_pct=10, duration_s=5, period_ms=100)
high_fast = Periodic(duty_cycle_pct=60, duration_s=5, period_ms=10)
medium_fast = Periodic(duty_cycle_pct=10, duration_s=5, period_ms=1)
high_slow = Periodic(duty_cycle_pct=60, duration_s=5, period_ms=100)
#Compose the task
complex_task = ramp + medium_slow + high_fast + medium_fast + high_slow
# Configure this RTApp instance to:
# rtapp.conf(
# # 1. generate a "profile based" set of tasks
# kind='profile',
#
# # 2. define the "profile" of each task
# params={
# 'complex' : complex_task.get()
# },
#
# # 6. use this folder for task logfiles
# run_dir='/tmp'
#)
Explanation: The output of the previous cell reports the main properties of the generated
tasks. Thus for example we see that the first task is configure to be:
- named task_per20
- executed as a SCHED_FIFO task
- generating a load which is calibrated with respect to the CPU 1
- with one single "phase" which defines a peripodic load for the duration of 5[s]
- that periodic load consistes of 50 cycles
- each cycle has a period of 100[ms] and a duty-cycle of 20%,
which means that the task, for every cycle, will run for 20[ms] and then sleep for 80[ms]
All these properties are translated into a JSON configuration file for RTApp which you can see in Collected results below.<br>
Workload composition
Another way of specifying the phases of a task is through workload composition, described in the next cell.<br>
NOTE: We are just giving this as an example of specifying a workload, but this configuration won't be the one used for the following execution and analysis cells. You need to uncomment these lines if you want to use the composed workload.
End of explanation
logging.info('#### Setup FTrace')
te.ftrace.start()
logging.info('#### Start energy sampling')
te.emeter.reset()
logging.info('#### Start RTApp execution')
rtapp.run(out_dir=te.res_dir, cgroup="")
logging.info('#### Read energy consumption: %s/energy.json', te.res_dir)
nrg_report = te.emeter.report(out_dir=te.res_dir)
logging.info('#### Stop FTrace')
te.ftrace.stop()
trace_file = os.path.join(te.res_dir, 'trace.dat')
logging.info('#### Save FTrace: %s', trace_file)
te.ftrace.get_trace(trace_file)
logging.info('#### Save platform description: %s/platform.json', te.res_dir)
(plt, plt_file) = te.platform_dump(te.res_dir)
Explanation: Workload execution
End of explanation
# Inspect the JSON file used to run the application
with open('{}/simple_00.json'.format(te.res_dir), 'r') as fh:
rtapp_json = json.load(fh, )
logging.info('Generated RTApp JSON file:')
print json.dumps(rtapp_json, indent=4, sort_keys=True)
# All data are produced in the output folder defined by the TestEnv module
logging.info('Content of the output folder %s', te.res_dir)
!ls -la {te.res_dir}
# Dump the energy measured for the LITTLE and big clusters
logging.info('Energy: %s', nrg_report.report_file)
print json.dumps(nrg_report.channels, indent=4, sort_keys=True)
# Dump the platform descriptor, which could be useful for further analysis
# of the generated results
logging.info('Platform description: %s', plt_file)
print json.dumps(plt, indent=4, sort_keys=True)
Explanation: Collected results
End of explanation
# NOTE: The interactive trace visualization is available only if you run
# the workload to generate a new trace-file
trappy.plotter.plot_trace(te.res_dir)
Explanation: Trace inspection
More information on visualization and trace inspection can be found in examples/trappy.
End of explanation
# Parse the RT-App generate log files to compute performance metrics
pa = PerfAnalysis(te.res_dir)
# For each task which has generated a logfile, plot its performance metrics
for task in pa.tasks():
pa.plotPerf(task, "Performance plots for task [{}] ".format(task))
Explanation: RTApp task performance plots
End of explanation |
7,420 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 1
Step1: To download data, we need to identify the relevant tables containing the variables of interest to us.
One way to do this would be to refer to the ACS documentation, in particular the Table Shells
(https
Step2: (Please note that searching Census variables and printing out a single table rely on previously downloaded information from the Census API, because otherwise every time we did this we would have to download data for all variables.) Once we have identified a table of interest, we can use censusdata.printtable to show all variables
included in the table
Step3: After identifying relevant variables, we then need to identify the geographies of interest. We are interested in block groups in Cook County, Illinois, so first we look for the geographic identifier (FIPS code)
for Illinois, then the identifiers for all counties with Illinois to find Cook County
Step4: Now that we have identified the variables and geographies of interest, we can download the data using censusdata.download and compute variables for the percent unemployed and the percent with no high school degree
Step5: Next, we show the 30 block groups in Cook County with the highest rate of unemployment, and the percent with no high school degree in those block groups.
Step6: Finally, we show the correlation between these two variables across all Cook County block groups | Python Code:
import pandas as pd
import censusdata
pd.set_option('display.expand_frame_repr', False)
pd.set_option('display.precision', 2)
Explanation: Example 1: Downloading Block Group Data and Exporting to CSV
As a first example, let's suppose we're interested in unemployment and high school dropout rates
for block groups in Cook County, Illinois, which contains Chicago, IL.
We begin by importing the censusdata and pandas modules, and setting some display options in pandas for
nicer output:
End of explanation
censusdata.search('acs5', 2015, 'label', 'unemploy')[80:90]
censusdata.search('acs5', 2015, 'concept', 'education')[350:400]
Explanation: To download data, we need to identify the relevant tables containing the variables of interest to us.
One way to do this would be to refer to the ACS documentation, in particular the Table Shells
(https://www.census.gov/programs-surveys/acs/technical-documentation/summary-file-documentation.html). Alternatively, it is possible to do this from within Python. censusdata.search will search for given text patterns. The downside to this is output can be voluminous, as in the following searches, as ACS frequently provides a large number of different tabulations related to a given topic area. Below, we limit the output to the relevant variables:
End of explanation
censusdata.printtable(censusdata.censustable('acs5', 2015, 'B23025'))
censusdata.printtable(censusdata.censustable('acs5', 2015, 'B15003'))
Explanation: (Please note that searching Census variables and printing out a single table rely on previously downloaded information from the Census API, because otherwise every time we did this we would have to download data for all variables.) Once we have identified a table of interest, we can use censusdata.printtable to show all variables
included in the table:
End of explanation
censusdata.geographies(censusdata.censusgeo([('state', '*')]), 'acs5', 2015)
censusdata.geographies(censusdata.censusgeo([('state', '17'), ('county', '*')]), 'acs5', 2015)
Explanation: After identifying relevant variables, we then need to identify the geographies of interest. We are interested in block groups in Cook County, Illinois, so first we look for the geographic identifier (FIPS code)
for Illinois, then the identifiers for all counties with Illinois to find Cook County:
End of explanation
cookbg = censusdata.download('acs5', 2015,
censusdata.censusgeo([('state', '17'), ('county', '031'), ('block group', '*')]),
['B23025_003E', 'B23025_005E', 'B15003_001E', 'B15003_002E', 'B15003_003E',
'B15003_004E', 'B15003_005E', 'B15003_006E', 'B15003_007E', 'B15003_008E',
'B15003_009E', 'B15003_010E', 'B15003_011E', 'B15003_012E', 'B15003_013E',
'B15003_014E', 'B15003_015E', 'B15003_016E'])
cookbg['percent_unemployed'] = cookbg.B23025_005E / cookbg.B23025_003E * 100
cookbg['percent_nohs'] = (cookbg.B15003_002E + cookbg.B15003_003E + cookbg.B15003_004E
+ cookbg.B15003_005E + cookbg.B15003_006E + cookbg.B15003_007E + cookbg.B15003_008E
+ cookbg.B15003_009E + cookbg.B15003_010E + cookbg.B15003_011E + cookbg.B15003_012E
+ cookbg.B15003_013E + cookbg.B15003_014E +
cookbg.B15003_015E + cookbg.B15003_016E) / cookbg.B15003_001E * 100
cookbg = cookbg[['percent_unemployed', 'percent_nohs']]
cookbg.describe()
Explanation: Now that we have identified the variables and geographies of interest, we can download the data using censusdata.download and compute variables for the percent unemployed and the percent with no high school degree:
End of explanation
cookbg.sort_values('percent_unemployed', ascending=False).head(30)
Explanation: Next, we show the 30 block groups in Cook County with the highest rate of unemployment, and the percent with no high school degree in those block groups.
End of explanation
cookbg.corr()
Explanation: Finally, we show the correlation between these two variables across all Cook County block groups:
End of explanation |
7,421 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example data
Step1: VectorAssembler
To fit a ML model in pyspark, we need to combine all feature columns into one single column of vectors
Step2: Assemble feature columns into one single feacturesCol with VectorAssembler
Step3: Convert sparse vectors in featuresCol to dense vectors | Python Code:
import pandas as pd
pdf = pd.DataFrame({
'x1': ['a','a','b','b', 'b', 'c'],
'x2': ['apple', 'orange', 'orange','orange', 'peach', 'peach'],
'x3': [1, 1, 2, 2, 2, 4],
'x4': [2.4, 2.5, 3.5, 1.4, 2.1,1.5],
'y1': [1, 0, 1, 0, 0, 1],
'y2': ['yes', 'no', 'no', 'yes', 'yes', 'yes']
})
df = spark.createDataFrame(pdf)
df.show()
Explanation: Example data
End of explanation
from pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler
from pyspark.ml import Pipeline
all_stages = [StringIndexer(inputCol=c, outputCol='idx_' + c) for c in ['x1', 'x2', 'x3']] + \
[OneHotEncoder(inputCol='idx_' + c, outputCol='ohe_' + c) for c in ['x1', 'x2', 'x3']]
all_stages
df_new = Pipeline(stages=all_stages).fit(df).transform(df)
df_new.show()
Explanation: VectorAssembler
To fit a ML model in pyspark, we need to combine all feature columns into one single column of vectors: the featuresCol. The VectorAssembler can be used to combine multiple OneHotEncoder columns and other continuous variable columns into one single column.
The example below shows how to combine three OneHotEncoder columns and one numeric column into a featureCol column.
StringIndex and OneHotEncode categorical columns
End of explanation
df_assembled = VectorAssembler(inputCols=['ohe_x1', 'ohe_x2', 'ohe_x3', 'x4'], outputCol='featuresCol')\
.transform(df_new)\
.drop('idx_x1', 'idx_x2', 'idx_x3')
df_assembled.show(truncate=False)
Explanation: Assemble feature columns into one single feacturesCol with VectorAssembler
End of explanation
from pyspark.sql.functions import udf
from pyspark.sql.types import *
from pyspark.ml.linalg import SparseVector, DenseVector
def dense_features_col(x):
return(x.toArray().dtype)
dense_features_col_udf = udf(dense_features_col, returnType=StringType())
df_assembled.rdd.map(lambda x: x['featuresCol']).take(4)
df_assembled.rdd.map(lambda x: list(x['featuresCol'].toArray())).take(5)
Explanation: Convert sparse vectors in featuresCol to dense vectors
End of explanation |
7,422 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Passband Luminosity
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
Step1: And we'll add a single light curve dataset so that we can see how passband luminosities affect the resulting synthetic light curve model.
Step2: Lastly, just to make things a bit easier and faster, we'll turn off irradiation (reflection), use blackbody atmospheres, and disable limb-darkening (so that we can play with weird temperatures without having to worry about falling of the grids).
Step3: Relevant Parameters & Methods
A pblum_mode parameter exists for each LC dataset in the bundle. This parameter defines how passband luminosities are handled. The subsections below describe the use and parameters exposed depening on the value of this parameter.
Step4: For any of these modes, you can expose the intrinsic (excluding extrinsic effects such as spots and irradiation) and extrinsic computed luminosities of each star (in each dataset) by calling b.compute_pblums.
Note that as its an aspect-dependent effect, boosting is ignored in all of these output values.
Step5: For more details, see the section below on "Accessing Model Luminosities" as well as the b.compute_pblums API docs
The table below provides a brief summary of all available pblum_mode options. Details are given in the remainder of the tutorial.
| pblum_mode | intent |
|-------------------|--------|
| component-coupled | provide pblum for one star (by default L1), compute pblums for other stars from atmosphere tables |
| decoupled | provide pblums for each star independently |
| absolute | obtain unscaled pblums, in passband watts, computed from atmosphere tables |
| dataset-scaled | calculate each pblum from the scaling factor between absolute fluxes and each dataset |
| dataset-coupled | same as above, but all datasets are scaled with the same scaling factor |
pblum_mode = 'component-coupled'
pblum_mode='component-coupled' is the default option and maintains the default behavior from previous releases. Here the user provides passband luminosities for a single star in the system for the given dataset/passband, and all other stars are scaled accordingly.
By default, the value of pblum is set for the primary star in the system, but we can instead provide pblum for the secondary star by changing the value of pblum_component.
Step6: Note that in general (for the case of a spherical star), a pblum of 4pi will result in an out-of-eclipse flux of ~1.
Now let's just reset to the default case where the primary star has a provided (default) pblum of 4pi.
Step7: NOTE
Step8: Let's see how changing the value of pblum affects the computed light curve. By default, pblum is set to be 4 pi, giving a total flux for the primary star of ~1.
Since the secondary star in the default binary is identical to the primary star, we'd expect an out-of-eclipse flux of the binary to be ~2.
Step9: If we now set pblum to be only 2 pi, we should expect the luminosities as well as entire light curve to be scaled in half.
Step10: And if we halve the temperature of the secondary star - the resulting light curve changes to the new sum of fluxes, where the primary star dominates since the secondary star flux is reduced by a factor of 16, so we expect a total out-of-eclipse flux of ~0.5 + ~0.5/16 = ~0.53.
Step11: Let us undo our changes before we look at decoupled luminosities.
Step12: pblum_mode = 'decoupled'
The luminosities are decoupled when pblums are provided for the individual components. To accomplish this, set pblum_mode to 'decoupled'.
Step13: Now we see that both pblum parameters are available and can have different values.
Step14: If we set these to 4pi, then we'd expect each star to contribute 1.0 in flux units, meaning the baseline of the light curve should be at approximately 2.0
Step15: Now let's make a significant temperature-ratio by making a very cool secondary star. Since the luminosities are decoupled - this temperature change won't affect the resulting light curve very much (compare this to the case above with coupled luminosities). What is happening here is that even though the secondary star is cooler, its luminosity is being rescaled to the same value as the primary star, so the eclipse depth doesn't change (you would see a similar lack-of-effect if you changed the radii - although in that case the eclipse widths would still change due to the change in geometry).
Step16: In most cases you will not want decoupled luminosities as they can easily break the self-consistency of your model.
Now we'll just undo our changes before we look at accessing model luminosities.
Step17: pblum_mode = 'absolute'
By setting pblum_mode to 'absolute', luminosities and fluxes will be returned in absolute units and not rescaled. Note that third light and distance will still affect the resulting flux levels.
Step18: As we no longer provide pblum values to scale, those parameters are not visible when filtering.
Step19: (note the exponent on the y-axis of the above figure)
pblum_mode = 'dataset-scaled'
Setting pblum_mode to 'dataset-scaled' is only allowed if fluxes are attached to the dataset itself. Let's use our existing model to generate "fake" data and then populate the dataset.
Step20: Now if we set pblum_mode to 'dataset-scaled', the resulting model will be scaled to best fit the data. Note that in this mode we cannot access computed luminosities via b.compute_pblums (without providing model - we'll get back to that in a minute), nor can we access scaled intensities from the mesh.
Step21: The model stores the scaling factor used between the absolute fluxes and the relative fluxes that best fit to the observational data.
Step22: We can then access the scaled luminosities by passing the model tag to b.compute_pblums. Keep in mind this only scales the absolute luminosities by flux_scale so assumes a fixed distance@system. This is useful though if we wanted to use 'dataset-scaled' to get an estimate for pblum before changing to 'component-coupled' and optimizing or marginalizing over pblum.
Step23: Before moving on, let's remove our fake data (and reset pblum_mode or else PHOEBE will complain about the lack of data).
Step24: pblum_mode = 'dataset-coupled'
Setting pblum_mode to 'dataset-coupled' allows for the same scaling factor to be applied to two different datasets. In order to see this in action, we'll add another LC dataset in a different passband.
Step25: Here we see the pblum_mode@lc01 is set to 'component-coupled' meaning it will follow the rules described earlier where pblum is provided for the primary component and the secondary is coupled to that. pblum_mode@lc02 is set to 'dataset-coupled' with pblum_dataset@lc01 pointing to 'lc01'.
Step26: Accessing Model Luminosities
Passband luminosities at t0@system per-star (including following all coupling logic) can be computed and exposed on the fly by calling compute_pblums.
Step27: By default this exposes 'pblum' and 'pblum_ext' for all component-dataset pairs in the form of a dictionary. Alternatively, you can pass a label or list of labels to component and/or dataset.
Step28: For more options, see the b.compute_pblums API docs.
Note that this same logic is applied (at t0) to initialize all passband luminosities within the backend, so there is no need to call compute_pblums before run_compute.
In order to access passband luminosities at times other than t0, you can add a mesh dataset and request the pblum_ext column to be exposed. For stars that have pblum defined (as opposed to coupled to another star or dataset), this value should be equivalent to the value of the parameter (at t0 if no features or irradiation are present, and in simple circular cases will probably be equivalent at all times).
Let's create a mesh dataset at a few times and then access the synthetic luminosities.
Step29: Since the luminosities are passband-dependent, they are stored with the same dataset as the light curve (or RV), but with the mesh method, and are available at each of the times at which a mesh was stored.
Step30: Now let's compare the value of the synthetic luminosities to those of the input pblum
Step31: In this case, since our two stars are identical, the synthetic luminosity of the secondary star should be the same as the primary (and the same as pblum@primary).
Step32: However, if we change the temperature of the secondary star again, since the pblums are coupled, we'd expect the synthetic luminosity of the primary to remain fixed but the secondary to decrease.
Step33: And lastly, if we re-enable irradiation, we'll see that the extrinsic luminosities do not match the prescribed value of pblum (an intrinsic luminosity).
Step34: Now, we'll just undo our changes before continuing
Step35: Role of Pblum
Let's now look at the intensities in the mesh to see how they're being scaled under-the-hood. First we'll recompute our model with the equal temperatures and irradiation disabled (to ignore the difference between pblum and pblum_ext).
Step36: 'abs_normal_intensities' are the intensities per triangle in absolute units, i.e. W/m^3.
Step37: The values of 'normal_intensities', however, are significantly samller (in this case). These are the intensities in relative units which will eventually be integrated to give us flux for a light curve.
Step38: 'normal_intensities' are scaled from 'abs_normal_intensities' so that the computed luminosity matches the prescribed luminosity (pblum).
Here we compute the luminosity by summing over each triangle's intensity in the normal direction, and multiply it by pi to account for blackbody intensity emitted in all directions in the solid angle, and by the area of that triangle. | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
import phoebe
from phoebe import u # units
import numpy as np
logger = phoebe.logger()
b = phoebe.default_binary()
Explanation: Passband Luminosity
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
b.add_dataset('lc', times=phoebe.linspace(0,1,101), dataset='lc01')
Explanation: And we'll add a single light curve dataset so that we can see how passband luminosities affect the resulting synthetic light curve model.
End of explanation
b.set_value('irrad_method', 'none')
b.set_value_all('ld_mode', 'manual')
b.set_value_all('ld_func', 'linear')
b.set_value_all('ld_coeffs', [0.])
b.set_value_all('ld_mode_bol', 'manual')
b.set_value_all('ld_func_bol', 'linear')
b.set_value_all('ld_coeffs_bol', [0.])
b.set_value_all('atm', 'blackbody')
Explanation: Lastly, just to make things a bit easier and faster, we'll turn off irradiation (reflection), use blackbody atmospheres, and disable limb-darkening (so that we can play with weird temperatures without having to worry about falling of the grids).
End of explanation
print(b.get_parameter(qualifier='pblum_mode', dataset='lc01'))
Explanation: Relevant Parameters & Methods
A pblum_mode parameter exists for each LC dataset in the bundle. This parameter defines how passband luminosities are handled. The subsections below describe the use and parameters exposed depening on the value of this parameter.
End of explanation
print(b.compute_pblums())
Explanation: For any of these modes, you can expose the intrinsic (excluding extrinsic effects such as spots and irradiation) and extrinsic computed luminosities of each star (in each dataset) by calling b.compute_pblums.
Note that as its an aspect-dependent effect, boosting is ignored in all of these output values.
End of explanation
print(b.filter(qualifier='pblum'))
print(b.get_parameter(qualifier='pblum_component'))
b.set_value('pblum_component', 'secondary')
print(b.filter(qualifier='pblum'))
Explanation: For more details, see the section below on "Accessing Model Luminosities" as well as the b.compute_pblums API docs
The table below provides a brief summary of all available pblum_mode options. Details are given in the remainder of the tutorial.
| pblum_mode | intent |
|-------------------|--------|
| component-coupled | provide pblum for one star (by default L1), compute pblums for other stars from atmosphere tables |
| decoupled | provide pblums for each star independently |
| absolute | obtain unscaled pblums, in passband watts, computed from atmosphere tables |
| dataset-scaled | calculate each pblum from the scaling factor between absolute fluxes and each dataset |
| dataset-coupled | same as above, but all datasets are scaled with the same scaling factor |
pblum_mode = 'component-coupled'
pblum_mode='component-coupled' is the default option and maintains the default behavior from previous releases. Here the user provides passband luminosities for a single star in the system for the given dataset/passband, and all other stars are scaled accordingly.
By default, the value of pblum is set for the primary star in the system, but we can instead provide pblum for the secondary star by changing the value of pblum_component.
End of explanation
b.set_value('pblum_component', 'primary')
print(b.get_parameter(qualifier='pblum', component='primary'))
Explanation: Note that in general (for the case of a spherical star), a pblum of 4pi will result in an out-of-eclipse flux of ~1.
Now let's just reset to the default case where the primary star has a provided (default) pblum of 4pi.
End of explanation
print(b.compute_pblums())
Explanation: NOTE: other parameters also affect flux-levels, including limb darkening, third light, boosting, irradiation, and distance
If we call b.compute_pblums, we'll see that the computed intrinsic luminosity of the primary star (pblum@primary@lc01) matches the value of the parameter above.
End of explanation
b.run_compute()
afig, mplfig = b.plot(show=True)
Explanation: Let's see how changing the value of pblum affects the computed light curve. By default, pblum is set to be 4 pi, giving a total flux for the primary star of ~1.
Since the secondary star in the default binary is identical to the primary star, we'd expect an out-of-eclipse flux of the binary to be ~2.
End of explanation
b.set_value('pblum', component='primary', value=2*np.pi)
print(b.compute_pblums())
b.run_compute()
afig, mplfig = b.plot(show=True)
Explanation: If we now set pblum to be only 2 pi, we should expect the luminosities as well as entire light curve to be scaled in half.
End of explanation
b.set_value('teff', component='secondary', value=0.5 * b.get_value('teff', component='primary'))
print(b.filter(qualifier='teff'))
print(b.compute_pblums())
b.run_compute()
afig, mplfig = b.plot(show=True)
Explanation: And if we halve the temperature of the secondary star - the resulting light curve changes to the new sum of fluxes, where the primary star dominates since the secondary star flux is reduced by a factor of 16, so we expect a total out-of-eclipse flux of ~0.5 + ~0.5/16 = ~0.53.
End of explanation
b.set_value_all('teff', 6000)
b.set_value_all('pblum', 4*np.pi)
Explanation: Let us undo our changes before we look at decoupled luminosities.
End of explanation
b.set_value('pblum_mode', 'decoupled')
Explanation: pblum_mode = 'decoupled'
The luminosities are decoupled when pblums are provided for the individual components. To accomplish this, set pblum_mode to 'decoupled'.
End of explanation
print(b.filter(qualifier='pblum'))
Explanation: Now we see that both pblum parameters are available and can have different values.
End of explanation
b.set_value_all('pblum', 4*np.pi)
print(b.compute_pblums())
b.run_compute()
afig, mplfig = b.plot(show=True)
Explanation: If we set these to 4pi, then we'd expect each star to contribute 1.0 in flux units, meaning the baseline of the light curve should be at approximately 2.0
End of explanation
print(b.filter(qualifier='teff'))
b.set_value('teff', component='secondary', value=3000)
print(b.compute_pblums())
b.run_compute()
afig, mplfig = b.plot(show=True)
Explanation: Now let's make a significant temperature-ratio by making a very cool secondary star. Since the luminosities are decoupled - this temperature change won't affect the resulting light curve very much (compare this to the case above with coupled luminosities). What is happening here is that even though the secondary star is cooler, its luminosity is being rescaled to the same value as the primary star, so the eclipse depth doesn't change (you would see a similar lack-of-effect if you changed the radii - although in that case the eclipse widths would still change due to the change in geometry).
End of explanation
b.set_value_all('teff', 6000)
b.set_value_all('pblum', 4*np.pi)
Explanation: In most cases you will not want decoupled luminosities as they can easily break the self-consistency of your model.
Now we'll just undo our changes before we look at accessing model luminosities.
End of explanation
b.set_value('pblum_mode', 'absolute')
Explanation: pblum_mode = 'absolute'
By setting pblum_mode to 'absolute', luminosities and fluxes will be returned in absolute units and not rescaled. Note that third light and distance will still affect the resulting flux levels.
End of explanation
print(b.filter(qualifier='pblum'))
print(b.compute_pblums())
b.run_compute()
afig, mplfig = b.plot(show=True)
Explanation: As we no longer provide pblum values to scale, those parameters are not visible when filtering.
End of explanation
fluxes = b.get_value('fluxes', context='model') * 0.8 + (np.random.random(101) * 0.1)
b.set_value('fluxes', context='dataset', value=fluxes)
afig, mplfig = b.plot(context='dataset', show=True)
Explanation: (note the exponent on the y-axis of the above figure)
pblum_mode = 'dataset-scaled'
Setting pblum_mode to 'dataset-scaled' is only allowed if fluxes are attached to the dataset itself. Let's use our existing model to generate "fake" data and then populate the dataset.
End of explanation
b.set_value('pblum_mode', 'dataset-scaled')
print(b.compute_pblums())
b.run_compute()
afig, mplfig = b.plot(show=True)
Explanation: Now if we set pblum_mode to 'dataset-scaled', the resulting model will be scaled to best fit the data. Note that in this mode we cannot access computed luminosities via b.compute_pblums (without providing model - we'll get back to that in a minute), nor can we access scaled intensities from the mesh.
End of explanation
print(b.get_parameter(qualifier='flux_scale', context='model'))
Explanation: The model stores the scaling factor used between the absolute fluxes and the relative fluxes that best fit to the observational data.
End of explanation
print(b.compute_pblums(model='latest'))
Explanation: We can then access the scaled luminosities by passing the model tag to b.compute_pblums. Keep in mind this only scales the absolute luminosities by flux_scale so assumes a fixed distance@system. This is useful though if we wanted to use 'dataset-scaled' to get an estimate for pblum before changing to 'component-coupled' and optimizing or marginalizing over pblum.
End of explanation
b.set_value('pblum_mode', 'component-coupled')
b.set_value('fluxes', context='dataset', value=[])
Explanation: Before moving on, let's remove our fake data (and reset pblum_mode or else PHOEBE will complain about the lack of data).
End of explanation
b.add_dataset('lc', times=phoebe.linspace(0,1,101),
ld_mode='manual', ld_func='linear', ld_coeffs=[0],
passband='Johnson:B', dataset='lc02')
b.set_value('pblum_mode', dataset='lc02', value='dataset-coupled')
Explanation: pblum_mode = 'dataset-coupled'
Setting pblum_mode to 'dataset-coupled' allows for the same scaling factor to be applied to two different datasets. In order to see this in action, we'll add another LC dataset in a different passband.
End of explanation
print(b.filter('pblum*'))
print(b.compute_pblums())
b.run_compute()
afig, mplfig = b.plot(show=True, legend=True)
Explanation: Here we see the pblum_mode@lc01 is set to 'component-coupled' meaning it will follow the rules described earlier where pblum is provided for the primary component and the secondary is coupled to that. pblum_mode@lc02 is set to 'dataset-coupled' with pblum_dataset@lc01 pointing to 'lc01'.
End of explanation
print(b.compute_pblums())
Explanation: Accessing Model Luminosities
Passband luminosities at t0@system per-star (including following all coupling logic) can be computed and exposed on the fly by calling compute_pblums.
End of explanation
print(b.compute_pblums(dataset='lc01', component='primary'))
Explanation: By default this exposes 'pblum' and 'pblum_ext' for all component-dataset pairs in the form of a dictionary. Alternatively, you can pass a label or list of labels to component and/or dataset.
End of explanation
b.add_dataset('mesh', times=np.linspace(0,1,5), dataset='mesh01', columns=['areas', 'pblum_ext@lc01', 'ldint@lc01', 'ptfarea@lc01', 'abs_normal_intensities@lc01', 'normal_intensities@lc01'])
b.run_compute()
Explanation: For more options, see the b.compute_pblums API docs.
Note that this same logic is applied (at t0) to initialize all passband luminosities within the backend, so there is no need to call compute_pblums before run_compute.
In order to access passband luminosities at times other than t0, you can add a mesh dataset and request the pblum_ext column to be exposed. For stars that have pblum defined (as opposed to coupled to another star or dataset), this value should be equivalent to the value of the parameter (at t0 if no features or irradiation are present, and in simple circular cases will probably be equivalent at all times).
Let's create a mesh dataset at a few times and then access the synthetic luminosities.
End of explanation
print(b.filter(qualifier='pblum_ext', context='model').twigs)
Explanation: Since the luminosities are passband-dependent, they are stored with the same dataset as the light curve (or RV), but with the mesh method, and are available at each of the times at which a mesh was stored.
End of explanation
t0 = b.get_value('t0@system')
print(b.get_value(qualifier='pblum_ext', time=t0, component='primary', kind='mesh', context='model'))
print(b.get_value('pblum@primary@dataset'))
print(b.compute_pblums(component='primary', dataset='lc01'))
Explanation: Now let's compare the value of the synthetic luminosities to those of the input pblum
End of explanation
print(b.get_value(qualifier='pblum_ext', time=t0, component='primary', kind='mesh', context='model'))
print(b.get_value(qualifier='pblum_ext', time=t0, component='secondary', kind='mesh', context='model'))
Explanation: In this case, since our two stars are identical, the synthetic luminosity of the secondary star should be the same as the primary (and the same as pblum@primary).
End of explanation
b['teff@secondary@component'] = 3000
print(b.compute_pblums(dataset='lc01'))
b.run_compute()
print(b.get_value(qualifier='pblum_ext', time=t0, component='primary', kind='mesh', context='model'))
print(b.get_value(qualifier='pblum_ext', time=t0, component='secondary', kind='mesh', context='model'))
Explanation: However, if we change the temperature of the secondary star again, since the pblums are coupled, we'd expect the synthetic luminosity of the primary to remain fixed but the secondary to decrease.
End of explanation
print(b['ld_mode'])
print(b['atm'])
b.run_compute(irrad_method='horvat')
print(b.get_value(qualifier='pblum_ext', time=t0, component='primary', kind='mesh', context='model'))
print(b.get_value('pblum@primary@dataset'))
print(b.compute_pblums(dataset='lc01', irrad_method='horvat'))
Explanation: And lastly, if we re-enable irradiation, we'll see that the extrinsic luminosities do not match the prescribed value of pblum (an intrinsic luminosity).
End of explanation
b.set_value_all('teff@component', 6000)
Explanation: Now, we'll just undo our changes before continuing
End of explanation
b.run_compute()
areas = b.get_value(qualifier='areas', dataset='mesh01', time=t0, component='primary', unit='m^2')
ldint = b.get_value(qualifier='ldint', component='primary', time=t0)
ptfarea = b.get_value(qualifier='ptfarea', component='primary', time=t0)
abs_normal_intensities = b.get_value(qualifier='abs_normal_intensities', dataset='lc01', time=t0, component='primary')
normal_intensities = b.get_value(qualifier='normal_intensities', dataset='lc01', time=t0, component='primary')
Explanation: Role of Pblum
Let's now look at the intensities in the mesh to see how they're being scaled under-the-hood. First we'll recompute our model with the equal temperatures and irradiation disabled (to ignore the difference between pblum and pblum_ext).
End of explanation
print(np.median(abs_normal_intensities))
Explanation: 'abs_normal_intensities' are the intensities per triangle in absolute units, i.e. W/m^3.
End of explanation
print(np.median(normal_intensities))
Explanation: The values of 'normal_intensities', however, are significantly samller (in this case). These are the intensities in relative units which will eventually be integrated to give us flux for a light curve.
End of explanation
pblum = b.get_value(qualifier='pblum', component='primary', context='dataset')
print(np.sum(normal_intensities * ldint * np.pi * areas) * ptfarea, pblum)
Explanation: 'normal_intensities' are scaled from 'abs_normal_intensities' so that the computed luminosity matches the prescribed luminosity (pblum).
Here we compute the luminosity by summing over each triangle's intensity in the normal direction, and multiply it by pi to account for blackbody intensity emitted in all directions in the solid angle, and by the area of that triangle.
End of explanation |
7,423 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<header class="w3-container w3-teal">
<img src="images/utfsm.png" alt="" height="100px" align="left"/>
<img src="images/mat.png" alt="" height="100px" align="right"/>
</header>
<br/><br/><br/><br/><br/>
MAT281
Laboratorio Aplicaciones de la Matemática en la Ingeniería
Clasificación de dígitos con k Nearest Neighbors
INSTRUCCIONES
Anoten su nombre y rol en la celda siguiente.
Desarrollen los problemas de manera secuencial.
Guarden constantemente con Ctr-S para evitar sorpresas.
Reemplacen en las celdas de código donde diga #FIX_ME por el código correspondiente.
Ejecuten cada celda de código utilizando Ctr-Enter
Step1: Observación
Este laboratorio utiliza la librería sklearn (oficialmente llamada scikit learn), de la cual utilizaremos el método de k Nearest Neighbors.
Problema
Step2: 1.2 Visualizando los datos
Para visualizar los datos utilizaremos el método imshow de pyplot. Resulta necesario convertir el arreglo desde las dimensiones (1,64) a (8,8) para que la imagen sea cuadrada y pueda distinguirse el dígito. Superpondremos además el label correspondiente al dígito, mediante el método text. Realizaremos lo anterior para los primeros 25 datos del archivo.
Step3: 2. Entrenando el modelo
2.1 Entrenamiento trivial
Entrenaremos el modelo con 1 vecino y verificaremos el error de predicción en el set de entrenamiento.
Step4: [10%] Desafío 1
¿Porqué el error de entrenamiento es 0 en el modelo?
RESPONDA AQUI
2.2 Buscando el valor de k más apropiado
A partir del análisis del punto anterior, nos damos cuenta de la necesidad de
Step5: 2.3 Visualizado el error de predicción
Podemos visualizar los datos anteriores utilizando el siguiente código, que requiere que sd_error_for k y mean_error_for_k hayan sido apropiadamente definidos.
Step6: [10%] Desafío 3
¿Qué patrón se observa en los datos? ¿Qué valor de $k$ elegirá para el algoritmo?
RESPONDA AQUI
2.4 Entrenando con todos los datos
A partir de lo anterior, se fija el número de vecinos $k$ y se procede a entrenar el modelo con todos los datos.
Step7: 2.5 Predicción en testing dataset
Ahora que el modelo kNN ha sido completamente entrenado, calcularemos el error de predicción en un set de datos completamente nuevo
Step8: 2.6 Visualización de etiquetas correctas
Puesto que tenemos las etiquetas verdaderas en el set de entrenamiento, podemos visualizar que números han sido correctamente etiquetados. Ejecute el código a continuación.
Step9: 2.7 Visualización de etiquetas incorrectas
Más interesante que el gráfico anterior, resulta considerar los casos donde los dígitos han sido incorrectamente etiquetados.
[15%] Desafio 5
Modifique el código anteriormente provisto para que muestre los dígitos incorrectamente etiquetados, cambiando apropiadamente la máscara. Cambie también el color de la etiqueta desde verde a rojo, para indicar una mala etiquetación.
Step10: 2.8 Análisis del error
Después de la exploración visual de los resultados, queremos obtener el error de predicción real del modelo.
[10%] Desafío 6
Complete el código, obteniendo el error de clasificación para cada dígito. ¿Existen dígitos más fáciles o difíciles de clasificar?
RESPONDER AQUI
Step11: 2.9 Análisis del error (cont. de)
El siguiente código muestra el error de clasificación, permitiendo verificar que números son confundibles
Step12: A partir de lo anterior, vemos observamos que los mayores errores son
Step13: Nuestro algoritmo no utiliza los distintos niveles de rojo (R), verde (G) y azul (B), y solamente le importa la luminancia $L$ de la imagen
Step14: Visualicemos la imagen obtenida
Step15: Veamos que nos daría la predicción con kNN. Recuerde que tiene el modelo ya ha sido cargado en memoria y se encuenta en la variable kNN.
Step16: 3.2 Carga de datos
Realicemos ahora la predicción para todas las imágenes de manera simultánea. Para ello abriremos cada imagen, realizaremos los arreglos de luminancia y escalamiento, y almacenaremos el arreglo en una fila de una matriz.
Step17: 3.2 Visualización de resultados | Python Code:
# Configuracion para recargar módulos y librerías
%reload_ext autoreload
%autoreload 2
%matplotlib inline
from IPython.display import Image as ShowImage
from IPython.core.display import HTML
HTML(open("style/mat281.css", "r").read())
from mat281_code.lab import greetings
alumno_1 = ("Sebastian Flores", "2004001-7")
alumno_2 = ("Maria Jose Vargas", "2004007-8")
HTML(greetings(alumno_1, alumno_2))
Explanation: <header class="w3-container w3-teal">
<img src="images/utfsm.png" alt="" height="100px" align="left"/>
<img src="images/mat.png" alt="" height="100px" align="right"/>
</header>
<br/><br/><br/><br/><br/>
MAT281
Laboratorio Aplicaciones de la Matemática en la Ingeniería
Clasificación de dígitos con k Nearest Neighbors
INSTRUCCIONES
Anoten su nombre y rol en la celda siguiente.
Desarrollen los problemas de manera secuencial.
Guarden constantemente con Ctr-S para evitar sorpresas.
Reemplacen en las celdas de código donde diga #FIX_ME por el código correspondiente.
Ejecuten cada celda de código utilizando Ctr-Enter
End of explanation
import numpy as np
XY_tv = np.loadtxt("data/optdigits.train", delimiter=",", dtype=np.int8)
print XY_tv
X_tv = XY_tv[:,:64]
Y_tv = XY_tv[:, 64]
print X_tv.shape
print Y_tv.shape
print X_tv[0,:]
print X_tv[0,:].reshape(8,8)
print Y_tv[0]
Explanation: Observación
Este laboratorio utiliza la librería sklearn (oficialmente llamada scikit learn), de la cual utilizaremos el método de k Nearest Neighbors.
Problema: clasificación de dígitos
En este laboratorio realizaremos el trabajo de reconocer un dígito a partir de una imagen.
El repositorio con los datos se encuentra en el siguiente link, pero los datos ya han sido incluídos en el directorio data/.
Contenido
El laboratorio consiste de 4 secciones:
1. Exploración de los datos.
2. Entrenando el modelo kNN.
3. Estimación del error de predicción de dígitos utilizando kNN.
4. Aplicación a dígitos propios.
1. Exploración de los datos
Los datos se encuentran en 2 archivos, data/optdigits.train y data/optdigits.test. Como su nombre lo indica, el set data/optdigits.train contiene los ejemplos que deben ser usados para entrenar el modelo, mientras que el set data/optdigits.test se utilizará para obtener una estimación del error de predicción.
Ambos archivos comparten el mismo formato: cada línea contiene 65 valores. Los 64 primeros corresponden a la representación de la imagen en escala de grises (0-blanco, 255-negro), y el valor 65 corresponde al dígito de la imágene (0-9).
1.1 Cargando los datos
Para cargar los datos, utilizamos np.loadtxt con los parámetros extra delimiter (para indicar que el separador será en esta ocasión una coma) y con el dype np.int8 (para que su representación en memoria sea la mínima posible, 8 bits en vez de 32/64 bits para un float).
End of explanation
from matplotlib import pyplot as plt
# Well plot the first nx*ny examples
nx, ny = 5, 5
fig, ax = plt.subplots(nx, ny, figsize=(12,12))
for i in range(nx):
for j in range(ny):
index = j+ny*i
data = X_tv[index,:].reshape(8,8)
label = Y_tv[index]
ax[i][j].imshow(data, interpolation='nearest', cmap=plt.get_cmap('gray_r'))
ax[i][j].text(7, 0, str(int(label)), horizontalalignment='center',
verticalalignment='center', fontsize=10, color='blue')
ax[i][j].get_xaxis().set_visible(False)
ax[i][j].get_yaxis().set_visible(False)
plt.show()
Explanation: 1.2 Visualizando los datos
Para visualizar los datos utilizaremos el método imshow de pyplot. Resulta necesario convertir el arreglo desde las dimensiones (1,64) a (8,8) para que la imagen sea cuadrada y pueda distinguirse el dígito. Superpondremos además el label correspondiente al dígito, mediante el método text. Realizaremos lo anterior para los primeros 25 datos del archivo.
End of explanation
from sklearn.neighbors import KNeighborsClassifier
k = 1
kNN = KNeighborsClassifier(n_neighbors=k)
kNN.fit(X_tv, Y_tv)
Y_pred = kNN.predict(X_tv)
n_errors = sum(Y_pred!=Y_tv)
print "Hay %d errores de un total de %d ejemplos de entrenamiento" %(n_errors, len(Y_tv))
Explanation: 2. Entrenando el modelo
2.1 Entrenamiento trivial
Entrenaremos el modelo con 1 vecino y verificaremos el error de predicción en el set de entrenamiento.
End of explanation
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
template = "k={0:,d}: {1:.1f} +- {2:.1f} errores de clasificación de un total de {3:,d} puntos"
# Fitting the model
mean_error_for_k = []
std_error_for_k = []
k_range = ##FIX ME##
for k in k_range:
errors_k = []
for i in ##FIX ME##:
kNN = ##FIX ME##
X_train, X_valid, Y_train, Y_valid = ##FIX ME##
kNN.fit(X_train, Y_train)
# Predicting values
Y_valid_pred = kNN.predict(X_valid)
# Count the errors
n_errors = ##FIX ME##
# Add them to vector
errors_k.append(100.*n_errors/len(Y_valid))
errors = np.array(errors_k)
print template.format(k, errors.mean(), errors.std(), len(Y_valid))
mean_error_for_k.append(errors.mean())
std_error_for_k.append(errors.std())
Explanation: [10%] Desafío 1
¿Porqué el error de entrenamiento es 0 en el modelo?
RESPONDA AQUI
2.2 Buscando el valor de k más apropiado
A partir del análisis del punto anterior, nos damos cuenta de la necesidad de:
1. Calcular el error en un set distinto al utilizado para entrenar.
2. Calcular el mejor valor de vecinos para el algoritmo.
[20%] Desafío 2
Complete el código entregado a continuación, de modo que se calcule el error de predicción (en porcentaje) de kNN, para k entre 1 y 10 (ambos incluidos). Realice una división en set de entrenamiento (75%) y de validación (25%), y calcule el valor promedio y desviación estándar del error de predicción (en porcentaje), tomando al menos 20 repeticiones para cada valor de k.
OBS: Ejecución de la celda debería tomar alrededor de 5 minutos.
End of explanation
mean = np.array(mean_error_for_k)
std = np.array(std_error_for_k)
plt.figure(figsize=(12,8))
plt.plot(k_range, mean - std, "k:")
plt.plot(k_range, mean , "r.-")
plt.plot(k_range, mean + std, "k:")
plt.xlabel("Numero de vecinos k")
plt.ylabel("Error de clasificacion")
plt.show()
Explanation: 2.3 Visualizado el error de predicción
Podemos visualizar los datos anteriores utilizando el siguiente código, que requiere que sd_error_for k y mean_error_for_k hayan sido apropiadamente definidos.
End of explanation
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
import numpy as np
k = 2
kNN = KNeighborsClassifier(n_neighbors=k)
kNN.fit(X_tv, Y_tv)
Explanation: [10%] Desafío 3
¿Qué patrón se observa en los datos? ¿Qué valor de $k$ elegirá para el algoritmo?
RESPONDA AQUI
2.4 Entrenando con todos los datos
A partir de lo anterior, se fija el número de vecinos $k$ y se procede a entrenar el modelo con todos los datos.
End of explanation
# Cargando el archivo data/optdigits.tes
XY_test = ##FIX ME##
X_test = ##FIX ME##
Y_test = ##FIX ME##
# Predicción de etiquetas
Y_pred = ##FIX ME##
Explanation: 2.5 Predicción en testing dataset
Ahora que el modelo kNN ha sido completamente entrenado, calcularemos el error de predicción en un set de datos completamente nuevo: el set de testing.
[15%] Desafío 4
Complete el código a continuación, para cargar los datos del set de entrenamiento y realizar una predicción de los dígitos de cada imagen. No cambie los nombres de las variables.
End of explanation
from matplotlib import pyplot as plt
# Mostrar los datos correctos
mask = (Y_pred==Y_test)
X_aux = X_test[mask]
Y_aux_true = Y_test[mask]
Y_aux_pred = Y_pred[mask]
# We'll plot the first 100 examples, randomly choosen
nx, ny = 5, 5
fig, ax = plt.subplots(nx, ny, figsize=(12,12))
for i in range(nx):
for j in range(ny):
index = j+ny*i
data = X_aux[index,:].reshape(8,8)
label_pred = str(int(Y_aux_pred[index]))
label_true = str(int(Y_aux_true[index]))
ax[i][j].imshow(data, interpolation='nearest', cmap=plt.get_cmap('gray_r'))
ax[i][j].text(0, 0, label_pred, horizontalalignment='center',
verticalalignment='center', fontsize=10, color='green')
ax[i][j].text(7, 0, label_true, horizontalalignment='center',
verticalalignment='center', fontsize=10, color='blue')
ax[i][j].get_xaxis().set_visible(False)
ax[i][j].get_yaxis().set_visible(False)
plt.show()
Explanation: 2.6 Visualización de etiquetas correctas
Puesto que tenemos las etiquetas verdaderas en el set de entrenamiento, podemos visualizar que números han sido correctamente etiquetados. Ejecute el código a continuación.
End of explanation
##FIX ME##
Explanation: 2.7 Visualización de etiquetas incorrectas
Más interesante que el gráfico anterior, resulta considerar los casos donde los dígitos han sido incorrectamente etiquetados.
[15%] Desafio 5
Modifique el código anteriormente provisto para que muestre los dígitos incorrectamente etiquetados, cambiando apropiadamente la máscara. Cambie también el color de la etiqueta desde verde a rojo, para indicar una mala etiquetación.
End of explanation
# Error global
mask = (Y_pred!=Y_test)
error_prediccion = ##FIX ME##
print "Error de predicción total de %.1f " %error_prediccion
for digito in range(0,10):
mask_digito = ##FIX ME##
Y_test_digito = Y_test[mask_digito]
Y_pred_digito = Y_pred[mask_digito]
error_prediccion = 100.*sum((Y_pred_digito!=Y_test_digito)) / len(Y_pred_digito)
print "Error de predicción para digito %d de %.1f " %(digito, error_prediccion)
Explanation: 2.8 Análisis del error
Después de la exploración visual de los resultados, queremos obtener el error de predicción real del modelo.
[10%] Desafío 6
Complete el código, obteniendo el error de clasificación para cada dígito. ¿Existen dígitos más fáciles o difíciles de clasificar?
RESPONDER AQUI
End of explanation
from sklearn.metrics import confusion_matrix as cm
cm = cm(Y_test, Y_pred)
print cm
# As in http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.hot):
plt.figure(figsize=(10,10))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(10)
plt.xticks(tick_marks, tick_marks)
plt.yticks(tick_marks, tick_marks)
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
return None
# Compute confusion matrix
plt.figure()
plot_confusion_matrix(cm)
# Normalize the confusion matrix by row (i.e by the number of samples
# in each class)
cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
plot_confusion_matrix(cm_normalized, title='Normalized confusion matrix')
Explanation: 2.9 Análisis del error (cont. de)
El siguiente código muestra el error de clasificación, permitiendo verificar que números son confundibles
End of explanation
from PIL import Image
import numpy as np
# Data
input_image = "mis_digitos/0.jpg"
# Read image
image = Image.open(input_image, 'r')
width, height = image.size
print "La imagen tiene %dx%d=%d pixeles" %(width, height, width*height)
X_rgb = np.array(image.getdata(), dtype=np.uint8) # x_i = (R_i, G_i, B_i)
#X_rgb = X_rgb.reshape(height,width,3)
print X_rgb[:,0] # Rojo
print X_rgb[:,1] # Verde
print X_rgb[:,2] # Azul
Explanation: A partir de lo anterior, vemos observamos que los mayores errores son:
* El 2 puede clasificarse erróneamente como 1 (pero no viceversa).
* El 7 puede clasificarse erróneamente como 9 (pero no viceversa).
* El 8 puede clasificarse erróneamente como 1 (pero no viceversa).
* El 9 puede clasificarse erróneamente como 3 (pero no viceversa).
3. Digitos propios
Para ver que tan bien resulta la predicción en sus propios dígitos, usted ha escrito los dígitos en un papel y le ha sacado una fotografía.
<img src="mis_digitos/0-9.jpg" alt="" width="800px" align="middle"/>
Después de regular la luminosidad, recortarlos apropiadamente y escalarlos a 8x8 pixeles, ha obtenido las siguientes imágenes:
<p><br>
<img src="mis_digitos/0.jpg" alt="" width="50px" align="left"/>
<img src="mis_digitos/1.jpg" alt="" width="50px" align="left"/>
<img src="mis_digitos/2.jpg" alt="" width="50px" align="left"/>
<img src="mis_digitos/3.jpg" alt="" width="50px" align="left"/>
<img src="mis_digitos/4.jpg" alt="" width="50px" align="left"/>
<img src="mis_digitos/5.jpg" alt="" width="50px" align="left"/>
<img src="mis_digitos/6.jpg" alt="" width="50px" align="left"/>
<img src="mis_digitos/7.jpg" alt="" width="50px" align="left"/>
<img src="mis_digitos/8.jpg" alt="" width="50px" align="left"/>
<img src="mis_digitos/9.jpg" alt="" width="50px" align="left"/>
</p>
3.1 Cargando datos de digitos
Para cargar los datos, necesitamos utilizar la librería PIL. Ilustraremos el funcionamiento con la imagen del dígito 0, que se encuentra en mis_digitos/0.jpg.
End of explanation
X = 255 - (X_rgb[:,0] + X_rgb[:,1] + X_rgb[:,2])/3.
digito = 300 * (X-X.min())/(X.max()-X.min())
digito[digito>255] = 255
Explanation: Nuestro algoritmo no utiliza los distintos niveles de rojo (R), verde (G) y azul (B), y solamente le importa la luminancia $L$ de la imagen:
$$ L = (R + G + B)/3 $$
Esto es razonable, pues no nos interesa el color del lápiz que realizó el dígito, sino la forma de éste.
Resulta además escalar para que la imagen tenga presente el valor máximo y mínimo (no depende de la iluminación de la imagen), es decir, que se cumpla $min(X) = 0$ y $max(X) = 255$.
End of explanation
data = digito.reshape(8,8)
plt.imshow(data, interpolation='nearest', cmap=plt.get_cmap('gray_r'))
plt.show()
Explanation: Visualicemos la imagen obtenida
End of explanation
label = kNN.predict(digito)
print label
Explanation: Veamos que nos daría la predicción con kNN. Recuerde que tiene el modelo ya ha sido cargado en memoria y se encuenta en la variable kNN.
End of explanation
X_mis_digitos = np.zeros([10,64])
Y_mis_digitos = np.zeros(10)
for i in range(10):
template = "mis_digitos/{0}.jpg"
archivo = template.format(i)
print "Abriendo archivo", archivo
image = Image.open(archivo, 'r')
X_rgb = np.array(image.getdata(), dtype=np.uint8) # x_i = (R_i, G_i, B_i)
X = 255 - (X_rgb[:,0] + X_rgb[:,1] + X_rgb[:,2])/3.
digito = 300 * (X-X.min())/(X.max()-X.min())
digito[digito>255] = 255
X_mis_digitos[i,:] = digito
Y_mis_digitos[i] = i
# Realizar la predicción simultánea
Y_pred = kNN.predict(X_mis_digitos)
Explanation: 3.2 Carga de datos
Realicemos ahora la predicción para todas las imágenes de manera simultánea. Para ello abriremos cada imagen, realizaremos los arreglos de luminancia y escalamiento, y almacenaremos el arreglo en una fila de una matriz.
End of explanation
from matplotlib import pyplot as plt
X_aux = X_mis_digitos
Y_aux_true = Y_mis_digitos
Y_aux_pred = Y_pred
nx, ny = 2, 5
fig, ax = plt.subplots(nx, ny, figsize=(20,10))
for i in range(nx):
for j in range(ny):
index = j+ny*i
data = X_aux[index,:].reshape(8,8)
label_pred = str(int(Y_aux_pred[index]))
label_true = str(int(Y_aux_true[index]))
if label_true == label_pred:
color = "green"
else:
color = "red"
ax[i][j].imshow(data, interpolation='nearest', cmap=plt.get_cmap('gray_r'))
ax[i][j].text(0, 0, label_pred, horizontalalignment='center',
verticalalignment='center', fontsize=10, color=color)
ax[i][j].text(7, 0, label_true, horizontalalignment='center',
verticalalignment='center', fontsize=10, color='blue')
ax[i][j].get_xaxis().set_visible(False)
ax[i][j].get_yaxis().set_visible(False)
plt.show()
Explanation: 3.2 Visualización de resultados
End of explanation |
7,424 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running Tune experiments with HEBOSearch
In this tutorial we introduce HEBO, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with ZOOpt and, as a result, allow you to seamlessly scale up a HEBO optimization process - without sacrificing performance.
Heteroscadastic Evolutionary Bayesian Optimization (HEBO) does not rely on the gradient of the objective function, but instead, learns from samples of the search space. It is suitable for optimizing functions that are nondifferentiable, with many local minima, or even unknown but only testable. This necessarily makes the algorithm belong to the domain of "derivative-free optimization" and "black-box optimization".
In this example we minimize a simple objective to briefly demonstrate the usage of HEBO with Ray Tune via HEBOSearch. It's useful to keep in mind that despite the emphasis on machine learning experiments, Ray Tune optimizes any implicit or explicit objective. Here we assume zoopt==0.4.1 library is installed. To learn more, please refer to the HEBO website.
Step1: Click below to see all the imports we need for this example.
You can also launch directly into a Binder instance to run this notebook yourself.
Just click on the rocket symbol at the top of the navigation.
Step2: Let's start by defining a simple evaluation function.
We artificially sleep for a bit (0.1 seconds) to simulate a long-running ML experiment.
This setup assumes that we're running multiple steps of an experiment and try to tune two hyperparameters,
namely width and height, and activation.
Step3: Next, our objective function takes a Tune config, evaluates the score of your experiment in a training loop,
and uses tune.report to report the score back to Tune.
Step4: While defining the search algorithm, we may choose to provide an initial set of hyperparameters that we believe are especially promising or informative, and
pass this information as a helpful starting point for the HyperOptSearch object.
We also set the maximum concurrent trials to 8.
Step5: The number of samples is the number of hyperparameter combinations that will be tried out. This Tune run is set to 1000 samples.
(you can decrease this if it takes too long on your machine).
Step6: Next we define a search space. The critical assumption is that the optimal hyperparamters live within this space. Yet, if the space is very large, then those hyperparameters may be difficult to find in a short amount of time.
Step7: Finally, we run the experiment to "min"imize the "mean_loss" of the objective by searching search_config via algo, num_samples times. This previous sentence is fully characterizes the search problem we aim to solve. With this in mind, notice how efficient it is to execute tune.run().
Step8: Here are the hyperparamters found to minimize the mean loss of the defined objective. | Python Code:
# !pip install ray[tune]
!pip install HEBO==0.3.2
Explanation: Running Tune experiments with HEBOSearch
In this tutorial we introduce HEBO, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with ZOOpt and, as a result, allow you to seamlessly scale up a HEBO optimization process - without sacrificing performance.
Heteroscadastic Evolutionary Bayesian Optimization (HEBO) does not rely on the gradient of the objective function, but instead, learns from samples of the search space. It is suitable for optimizing functions that are nondifferentiable, with many local minima, or even unknown but only testable. This necessarily makes the algorithm belong to the domain of "derivative-free optimization" and "black-box optimization".
In this example we minimize a simple objective to briefly demonstrate the usage of HEBO with Ray Tune via HEBOSearch. It's useful to keep in mind that despite the emphasis on machine learning experiments, Ray Tune optimizes any implicit or explicit objective. Here we assume zoopt==0.4.1 library is installed. To learn more, please refer to the HEBO website.
End of explanation
import time
import ray
from ray import tune
from ray.tune.suggest.hebo import HEBOSearch
Explanation: Click below to see all the imports we need for this example.
You can also launch directly into a Binder instance to run this notebook yourself.
Just click on the rocket symbol at the top of the navigation.
End of explanation
def evaluate(step, width, height, activation):
time.sleep(0.1)
activation_boost = 10 if activation=="relu" else 1
return (0.1 + width * step / 100) ** (-1) + height * 0.1 + activation_boost
Explanation: Let's start by defining a simple evaluation function.
We artificially sleep for a bit (0.1 seconds) to simulate a long-running ML experiment.
This setup assumes that we're running multiple steps of an experiment and try to tune two hyperparameters,
namely width and height, and activation.
End of explanation
def objective(config):
for step in range(config["steps"]):
score = evaluate(step, config["width"], config["height"], config["activation"])
tune.report(iterations=step, mean_loss=score)
ray.init(configure_logging=False)
Explanation: Next, our objective function takes a Tune config, evaluates the score of your experiment in a training loop,
and uses tune.report to report the score back to Tune.
End of explanation
previously_run_params = [
{"width": 10, "height": 0, "activation": "relu"},
{"width": 15, "height": -20, "activation": "tanh"},
]
known_rewards = [-189, -1144]
max_concurrent = 8
algo = HEBOSearch(
metric="mean_loss",
mode="min",
points_to_evaluate=previously_run_params,
evaluated_rewards=known_rewards,
random_state_seed=123,
max_concurrent=max_concurrent,
)
Explanation: While defining the search algorithm, we may choose to provide an initial set of hyperparameters that we believe are especially promising or informative, and
pass this information as a helpful starting point for the HyperOptSearch object.
We also set the maximum concurrent trials to 8.
End of explanation
num_samples = 1000
# If 1000 samples take too long, you can reduce this number.
# We override this number here for our smoke tests.
num_samples = 10
Explanation: The number of samples is the number of hyperparameter combinations that will be tried out. This Tune run is set to 1000 samples.
(you can decrease this if it takes too long on your machine).
End of explanation
search_config = {
"steps": 100,
"width": tune.uniform(0, 20),
"height": tune.uniform(-100, 100),
"activation": tune.choice(["relu, tanh"])
}
Explanation: Next we define a search space. The critical assumption is that the optimal hyperparamters live within this space. Yet, if the space is very large, then those hyperparameters may be difficult to find in a short amount of time.
End of explanation
analysis = tune.run(
objective,
metric="mean_loss",
mode="min",
name="hebo_exp_with_warmstart",
search_alg=algo,
num_samples=num_samples,
config=search_config
)
Explanation: Finally, we run the experiment to "min"imize the "mean_loss" of the objective by searching search_config via algo, num_samples times. This previous sentence is fully characterizes the search problem we aim to solve. With this in mind, notice how efficient it is to execute tune.run().
End of explanation
print("Best hyperparameters found were: ", analysis.best_config)
ray.shutdown()
Explanation: Here are the hyperparamters found to minimize the mean loss of the defined objective.
End of explanation |
7,425 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dual CRISPR Screen Analysis
Count Combination
Amanda Birmingham, CCBB, UCSD (abirmingham@ucsd.edu)
Instructions
To run this notebook reproducibly, follow these steps
Step1: CCBB Library Imports
Step2: Automated Set-Up
Step3: Count Combination Functions
Step4: Input Count Filenames
Step5: Count Combination Execution | Python Code:
g_timestamp = ""
g_dataset_name = "20160510_A549"
g_count_alg_name = "19mer_1mm_py"
g_fastq_counts_dir = '/Users/Birmingham/Repositories/ccbb_tickets/20160210_mali_crispr/data/interim/20160510_D00611_0278_BHK55CBCXX_A549'
g_fastq_counts_run_prefix = "19mer_1mm_py_20160615223822"
g_collapsed_counts_dir = "/Users/Birmingham/Repositories/ccbb_tickets/20160210_mali_crispr/data/processed/20160510_A549"
g_collapsed_counts_run_prefix = ""
g_combined_counts_dir = ""
g_combined_counts_run_prefix = ""
g_code_location = "/Users/Birmingham/Repositories/ccbb_tickets/20160210_mali_crispr/src/python"
Explanation: Dual CRISPR Screen Analysis
Count Combination
Amanda Birmingham, CCBB, UCSD (abirmingham@ucsd.edu)
Instructions
To run this notebook reproducibly, follow these steps:
1. Click Kernel > Restart & Clear Output
2. When prompted, click the red Restart & clear all outputs button
3. Fill in the values for your analysis for each of the variables in the Input Parameters section
4. Click Cell > Run All
<a name = "input-parameters"></a>
Input Parameters
End of explanation
import sys
sys.path.append(g_code_location)
Explanation: CCBB Library Imports
End of explanation
# %load -s describe_var_list /Users/Birmingham/Repositories/ccbb_tickets/20160210_mali_crispr/src/python/ccbbucsd/utilities/analysis_run_prefixes.py
def describe_var_list(input_var_name_list):
description_list = ["{0}: {1}\n".format(name, eval(name)) for name in input_var_name_list]
return "".join(description_list)
from ccbbucsd.utilities.analysis_run_prefixes import check_or_set, get_run_prefix, get_timestamp
g_timestamp = check_or_set(g_timestamp, get_timestamp())
g_collapsed_counts_dir = check_or_set(g_collapsed_counts_dir, g_fastq_counts_dir)
g_collapsed_counts_run_prefix = check_or_set(g_collapsed_counts_run_prefix,
get_run_prefix(g_dataset_name, g_count_alg_name, g_timestamp))
g_combined_counts_dir = check_or_set(g_combined_counts_dir, g_collapsed_counts_dir)
g_combined_counts_run_prefix = check_or_set(g_combined_counts_run_prefix, g_collapsed_counts_run_prefix)
print(describe_var_list(['g_timestamp','g_collapsed_counts_dir','g_collapsed_counts_run_prefix',
'g_combined_counts_dir', 'g_combined_counts_run_prefix']))
from ccbbucsd.utilities.files_and_paths import verify_or_make_dir
verify_or_make_dir(g_collapsed_counts_dir)
verify_or_make_dir(g_combined_counts_dir)
Explanation: Automated Set-Up
End of explanation
# %load -s get_counts_file_suffix /Users/Birmingham/Repositories/ccbb_tickets/20160210_mali_crispr/src/python/ccbbucsd/malicrispr/construct_counter.py
def get_counts_file_suffix():
return "counts.txt"
# %load /Users/Birmingham/Repositories/ccbb_tickets/20160210_mali_crispr/src/python/ccbbucsd/malicrispr/count_combination.py
# ccbb libraries
from ccbbucsd.utilities.analysis_run_prefixes import strip_run_prefix
from ccbbucsd.utilities.files_and_paths import build_multipart_fp, group_files, get_filepaths_by_prefix_and_suffix
# project-specific libraries
from ccbbucsd.malicrispr.count_files_and_dataframes import get_counts_df
__author__ = "Amanda Birmingham"
__maintainer__ = "Amanda Birmingham"
__email__ = "abirmingham@ucsd.edu"
__status__ = "prototype"
def get_collapsed_counts_file_suffix():
return "collapsed.txt"
def get_combined_counts_file_suffix():
return "counts_combined.txt"
def group_lane_and_set_files(filepaths):
# NB: this regex assumes read designator has *already* been removed
# and replaced with _ as done by group_read_pairs
return group_files(filepaths, "_L\d\d\d_\d\d\d", "")
def combine_count_files(counts_fp_for_dataset, run_prefix):
combined_df = None
for curr_counts_fp in counts_fp_for_dataset:
count_header, curr_counts_df = get_counts_df(curr_counts_fp, run_prefix)
if combined_df is None:
combined_df = curr_counts_df
else:
combined_df[count_header] = curr_counts_df[count_header]
return combined_df
def write_collapsed_count_files(input_dir, output_dir, curr_run_prefix, counts_run_prefix, counts_suffix, counts_collapsed_file_suffix):
counts_fps_for_dataset = get_filepaths_by_prefix_and_suffix(input_dir, counts_run_prefix, counts_suffix)
fps_by_sample = group_lane_and_set_files(counts_fps_for_dataset)
for curr_sample, curr_fps in fps_by_sample.items():
stripped_sample = strip_run_prefix(curr_sample, counts_run_prefix)
output_fp = build_multipart_fp(output_dir, [curr_run_prefix, stripped_sample, counts_collapsed_file_suffix])
combined_df = None
for curr_fp in curr_fps:
count_header, curr_counts_df = get_counts_df(curr_fp, counts_run_prefix)
if combined_df is None:
combined_df = curr_counts_df
combined_df.rename(columns = {count_header:stripped_sample}, inplace = True)
else:
combined_df[stripped_sample] = combined_df[stripped_sample] + curr_counts_df[count_header]
combined_df.to_csv(output_fp, sep="\t", index=False)
def write_combined_count_file(input_dir, output_dir, curr_run_prefix, counts_run_prefix, counts_suffix, combined_suffix):
output_fp = build_multipart_fp(output_dir, [curr_run_prefix, combined_suffix])
counts_fps_for_run = get_filepaths_by_prefix_and_suffix(input_dir, counts_run_prefix, counts_suffix)
combined_df = combine_count_files(counts_fps_for_run, curr_run_prefix)
combined_df.to_csv(output_fp, sep="\t", index=False)
Explanation: Count Combination Functions
End of explanation
from ccbbucsd.utilities.files_and_paths import summarize_filenames_for_prefix_and_suffix
print(summarize_filenames_for_prefix_and_suffix(g_fastq_counts_dir, g_fastq_counts_run_prefix, get_counts_file_suffix()))
Explanation: Input Count Filenames
End of explanation
write_collapsed_count_files(g_fastq_counts_dir, g_collapsed_counts_dir, g_collapsed_counts_run_prefix,
g_fastq_counts_run_prefix, get_counts_file_suffix(), get_collapsed_counts_file_suffix())
write_combined_count_file(g_collapsed_counts_dir, g_combined_counts_dir, g_collapsed_counts_run_prefix,
g_combined_counts_run_prefix, get_collapsed_counts_file_suffix(),
get_combined_counts_file_suffix())
Explanation: Count Combination Execution
End of explanation |
7,426 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train an Agent using Generative Adversarial Imitation Learning
The idea of generative adversarial imitation learning is to train a discriminator network to distinguish between expert trajectories and learner trajectories.
The learner is trained using a traditional reinforcement learning algorithm such as PPO and is rewarded for trajectories that make the discriminator think that it was an expert trajectory.
As usual, we first need an expert.
Note that we now use a variant of the CartPole environment from the seals package, which has fixed episode durations. Read more about why we do this here.
Step1: We generate some expert trajectories, that the discriminator needs to distinguish from the learner's trajectories.
Step2: Now we are ready to set up our GAIL trainer.
Note, that the reward_net is actually the network of the discriminator.
We evaluate the learner before and after training so we can see if it made any progress.
Step3: When we look at the histograms of rewards before and after learning, we can see that the learner is not perfect yet, but it made some progress at least.
If not, just re-run the above cell. | Python Code:
from stable_baselines3 import PPO
from stable_baselines3.ppo import MlpPolicy
import gym
import seals
env = gym.make("seals/CartPole-v0")
expert = PPO(
policy=MlpPolicy,
env=env,
seed=0,
batch_size=64,
ent_coef=0.0,
learning_rate=0.0003,
n_epochs=10,
n_steps=64,
)
expert.learn(1000) # Note: set to 100000 to train a proficient expert
Explanation: Train an Agent using Generative Adversarial Imitation Learning
The idea of generative adversarial imitation learning is to train a discriminator network to distinguish between expert trajectories and learner trajectories.
The learner is trained using a traditional reinforcement learning algorithm such as PPO and is rewarded for trajectories that make the discriminator think that it was an expert trajectory.
As usual, we first need an expert.
Note that we now use a variant of the CartPole environment from the seals package, which has fixed episode durations. Read more about why we do this here.
End of explanation
from imitation.data import rollout
from imitation.data.wrappers import RolloutInfoWrapper
from stable_baselines3.common.vec_env import DummyVecEnv
rollouts = rollout.rollout(
expert,
DummyVecEnv([lambda: RolloutInfoWrapper(gym.make("seals/CartPole-v0"))] * 5),
rollout.make_sample_until(min_timesteps=None, min_episodes=60),
)
Explanation: We generate some expert trajectories, that the discriminator needs to distinguish from the learner's trajectories.
End of explanation
from imitation.algorithms.adversarial.gail import GAIL
from imitation.rewards.reward_nets import BasicRewardNet
from imitation.util.networks import RunningNorm
from stable_baselines3 import PPO
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.vec_env import DummyVecEnv, SubprocVecEnv
import gym
import seals
venv = DummyVecEnv([lambda: gym.make("seals/CartPole-v0")] * 8)
learner = PPO(
env=venv,
policy=MlpPolicy,
batch_size=64,
ent_coef=0.0,
learning_rate=0.0003,
n_epochs=10,
)
reward_net = BasicRewardNet(
venv.observation_space, venv.action_space, normalize_input_layer=RunningNorm
)
gail_trainer = GAIL(
demonstrations=rollouts,
demo_batch_size=1024,
gen_replay_buffer_capacity=2048,
n_disc_updates_per_round=4,
venv=venv,
gen_algo=learner,
reward_net=reward_net,
)
learner_rewards_before_training, _ = evaluate_policy(
learner, venv, 100, return_episode_rewards=True
)
gail_trainer.train(20000) # Note: set to 300000 for better results
learner_rewards_after_training, _ = evaluate_policy(
learner, venv, 100, return_episode_rewards=True
)
Explanation: Now we are ready to set up our GAIL trainer.
Note, that the reward_net is actually the network of the discriminator.
We evaluate the learner before and after training so we can see if it made any progress.
End of explanation
import matplotlib.pyplot as plt
import numpy as np
print(np.mean(learner_rewards_after_training))
print(np.mean(learner_rewards_before_training))
plt.hist(
[learner_rewards_before_training, learner_rewards_after_training],
label=["untrained", "trained"],
)
plt.legend()
plt.show()
Explanation: When we look at the histograms of rewards before and after learning, we can see that the learner is not perfect yet, but it made some progress at least.
If not, just re-run the above cell.
End of explanation |
7,427 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sympy is a Python package used for solving equations using symbolic math.
Let's solve the following problem with SymPy.
Given
Step1: We need to define six different symbols
Step2: Next we'll create two expressions for our two equations. We can subtract the %crystallinity from the left side of the equation to set the equation to zero.
$$ \%crystallinity = \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% $$
$$ \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% - \%crystallinity = 0 $$
Sub in $\rho_s = \rho_1$ and $\rho_s = \rho_2$ to each of the expressions.
Step3: Now we'll substitue in the values of $\rho_1 = 0.904$ and $c_1 = 0.628$ into our first expression.
Step4: Now we'll substitue our the values of $\rho_2 = 0.895$ and $c_2 = 0.544$ into our second expression.
Step5: To solve the two equations for the to unknows $\rho_a$ and $\rho_b$, use SymPy's nonlinsolve() function. Pass in a list of the two expressions and followed by a list of the two variables to solve for.
Step6: We see that the value of $\rho_a = 0.840789$ and $\rho_c = 0.94613431$.
The solution is a SymPy FiniteSet object. To pull the values of $\rho_a$ and $\rho_c$ out of the FiniteSet, use the syntax sol.args[0][<var num>]. | Python Code:
from sympy import symbols, nonlinsolve
Explanation: Sympy is a Python package used for solving equations using symbolic math.
Let's solve the following problem with SymPy.
Given:
The density of two different polymer samples $\rho_1$ and $\rho_2$ are measured.
$$ \rho_1 = 0.904 \ g/cm^3 $$
$$ \rho_2 = 0.895 \ g/cm^3 $$
The percent crystalinity of the two samples ($\%c_1 $ and $\%c_2$) is known.
$$ \%c_1 = 62.8 \% $$
$$ \%c_2 = 54.4 \% $$
The percent crystalinity of a polymer sample is related to the density of 100% amorphus regions ($\rho_a$) and 100% crystaline regions ($\rho_c$) according to:
$$ \%crystallinity = \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% $$
Find:
Find the density of 100% amorphus regions ($\rho_a$) and the density of 100% crystaline regions ($\rho_c$) for this polymer.
Solution:
There are a couple functions we need from Sympy. We'll need the symbols function to create our symbolic math variables and we need the nonlinsolve function to solve a system of non-linear equations.
End of explanation
pc, pa, p1, p2, c1, c2 = symbols('pc pa p1 p2 c1 c2')
Explanation: We need to define six different symbols: $$\rho_c, \rho_a, \rho_1, \rho_2, c_1, c_2$$
End of explanation
expr1 = ( (pc*(p1-pa) ) / (p1*(pc-pa)) - c1)
expr2 = ( (pc*(p2-pa) ) / (p2*(pc-pa)) - c2)
Explanation: Next we'll create two expressions for our two equations. We can subtract the %crystallinity from the left side of the equation to set the equation to zero.
$$ \%crystallinity = \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% $$
$$ \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% - \%crystallinity = 0 $$
Sub in $\rho_s = \rho_1$ and $\rho_s = \rho_2$ to each of the expressions.
End of explanation
expr1 = expr1.subs(p1, 0.904)
expr1 = expr1.subs(c1, 0.628)
expr1
Explanation: Now we'll substitue in the values of $\rho_1 = 0.904$ and $c_1 = 0.628$ into our first expression.
End of explanation
expr2 = expr2.subs(p2, 0.895)
expr2 = expr2.subs(c2, 0.544)
expr2
Explanation: Now we'll substitue our the values of $\rho_2 = 0.895$ and $c_2 = 0.544$ into our second expression.
End of explanation
nonlinsolve([expr1,expr2],[pa,pc])
Explanation: To solve the two equations for the to unknows $\rho_a$ and $\rho_b$, use SymPy's nonlinsolve() function. Pass in a list of the two expressions and followed by a list of the two variables to solve for.
End of explanation
sol = nonlinsolve([expr1,expr2],[pa,pc])
type(sol)
sol.args
sol.args[0]
sol.args[0][0]
pa = sol.args[0][0]
pc = sol.args[0][1]
print(f' Density of 100% amorphous polymer, pa = {round(pa,2)} g/cm3')
print(f' Density of 100% crystaline polymer, pc = {round(pc,2)} g/cm3')
Explanation: We see that the value of $\rho_a = 0.840789$ and $\rho_c = 0.94613431$.
The solution is a SymPy FiniteSet object. To pull the values of $\rho_a$ and $\rho_c$ out of the FiniteSet, use the syntax sol.args[0][<var num>].
End of explanation |
7,428 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
新增刪修格式
GET - 查詢 (Retrieve)
```
r = requests.get(url, params=API_KEY)
query by record ID
Step1: 查詢單筆資料
Step2: 新增資料
Step3: 刪除資料
Step4: 修改資料 | Python Code:
query_string = {'api_key':'keyshdNC8CZdj1xgo', 'maxRecords':'100', 'pageSize':'2',
'filterByFormula':'{屬種} = "new type"'} #pageSize:一個頁面顯示(取回)幾筆資料
r = requests.get(url, params=query_string)
r.status_code
r.text
Explanation: 新增刪修格式
GET - 查詢 (Retrieve)
```
r = requests.get(url, params=API_KEY)
query by record ID:
query_by_id_url = url +"/"+ "record_id"
r = requests.get(query_by_id_url, headers=(Aut_cxt_header))
```
POST - 新增 (Create)
~~#POST with form-encoded data~~
~~(不使用) r = requests.post(url, data=payload, headers=(Aut_cxt_header))~~
```
POST with JSON import json
r = requests.post(url, data=json.dumps(payload), headers=(Aut_cxt_header))
```
PATCH - 修改 (Update)部份欄位:some (but not all) fields
query_by_id_url = url +"/"+ "record_id"
r = requests.patch(query_by_id_url, data=json.dumps(payload), headers=(Aut_cxt_header))
PUT - 修改 (Update)全部欄位:all fields
query_by_id_url = url +"/"+ "record_id"
r = requests.put(query_by_id_url, data=json.dumps(payload), headers=(Aut_cxt_header))
DELETE - 刪除 (Delete)
query_by_id_url = url +"/"+ "delete target record id"
r = requests.delete(query_by_id_url, headers=(Aut_header))
查詢語法
```
requests.post?
Signature: requests.post(url, data=None, json=None, **kwargs)
Docstring:
Sends a POST request.
:param url: URL for the new :class:Request object.
:param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:Request.
:param json: (optional) json data to send in the body of the :class:Request.
:param **kwargs: Optional arguments that request takes.
:return: :class:Response <Response> object
:rtype: requests.Response
File: c:\anaconda3\lib\site-packages\requests\api.py
Type: function
```
Http Status Code: (API Error code)
https://airtable.com/appNcYtL8fFZa1STA/api/docs#curl/errors:servererrorcodes
帶查詢條件: maxrecord, pagesize, and api_key
https://api.airtable.com/v0/appNcYtL8fFZa1STA/iris?maxRecords=100&pageSize=2&api_key=keyshdNC8CZdj1xgo
Pagination (關於分頁設定,pageSize預設100筆)
The server returns one page of records at a time. Each page will contain pageSize records, which is 100 by default.
offset (分頁的下一頁面第一筆記錄的ID)
If there are more records, the response will contain an offset. To fetch the next page of records, include offset in the next request's parameters.
End of explanation
#查詢單筆資料
query_by_id_url = url +"/"+ "rec06Uv00gLHpXCsK" #url+record_id
r = requests.get(query_by_id_url, headers=(Aut_cxt_header)) #also,it's work that Authorization send by query string.
r.status_code
query_by_id_url
r.text
Explanation: 查詢單筆資料
End of explanation
r = requests.post(url, data=json.dumps(payload), headers=(Aut_cxt_header))
r.status_code
r.text #剛才新增的記錄資料,會被 Return.
Explanation: 新增資料
End of explanation
query_by_id_url = url +"/"+ "recXX06GaZcWsjdxk" #url+record_id
r = requests.delete(query_by_id_url, headers=(Aut_header))
r.status_code
query_by_id_url
Explanation: 刪除資料
End of explanation
query_by_id_url = url +"/"+ "rec7FyUfaCBL944p7"
payload = {
"fields": {
"花萼長度": "11",
"花萼寬度": "11",
"花瓣長度": "11",
"花瓣寬度": "11",
"屬種": "new type"
}
}
r = requests.put(query_by_id_url, data=json.dumps(payload), headers=(Aut_cxt_header))
r.status_code
r.text
Explanation: 修改資料
End of explanation |
7,429 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
局部异常因子方法发现异常点
局部异常因子(Local Outlier Factor,LOF)也是一种异常检测算法,它对数据实例的局部密度和邻居进行比较,判断这个数据是否属于相似的密度的区域,它适合从那些簇个数未知,簇的密度和大小各不相同的数据中筛选出异常点。
从k近邻算法启发来
Step1: 局部异常因子计算出每个点的局部密度,通过它与K最近邻的点的距离来评估点的局部密度,并与邻居的密度进行比较,以此找出异常点--异常点比邻居的密度要低得多
为了理解LOF,先了解一些术语的定义
* 对象P的K距离:对象P与它第K个最近邻的距离,K是算法的参数
P的K距离邻居:到P的距离小于或等于P到第K个最邻近的距离的所有对象的集合Q
* 从P到Q的可达距离:P与它的第K个最近邻的距离和P和Q之间的距离中的最大者。
P的局部可达密度(local Reachability Density of P):K距离邻居和K与其邻居的可达距离之和的比值
* P的局部异常因子(Local Outlier Factor of P) | Python Code:
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
instance = np.matrix([[0,0],[0,1],[1,1],[1,0],[5,0]])
x = np.squeeze(np.asarray(instance[:,0]))
y = np.squeeze(np.asarray(instance[:,1]))
plt.cla()
plt.figure(1)
plt.scatter(x,y)
plt.show()
Explanation: 局部异常因子方法发现异常点
局部异常因子(Local Outlier Factor,LOF)也是一种异常检测算法,它对数据实例的局部密度和邻居进行比较,判断这个数据是否属于相似的密度的区域,它适合从那些簇个数未知,簇的密度和大小各不相同的数据中筛选出异常点。
从k近邻算法启发来
End of explanation
# 获取点两两之间的距离pairwise_distance
distance = 'manhattan'
from sklearn.metrics import pairwise_distances
dist = pairwise_distances(instance,metric=distance)
print dist
# 计算K距离,使用heapq来获得K最近邻
k = 2
# 计算K距离
import heapq
# k_distance的值是tuple
k_distance = defaultdict(tuple)
# 对每个点计算
for i in range(instance.shape[0]):
# 获取它与所有其点之间的距离
distances = dist[i].tolist()
# 获得K最近邻
ksmallest = heapq.nsmallest(k+1,distances)[1:][k-1]
# 获取索引号
ksmallest_idx = distances.index(ksmallest)
# 记录下每个点到第K个最近邻以及到它的距离
k_distance[i]=(ksmallest,ksmallest_idx)
# 计算K距离邻居
def all_indices(value,inlist):
out_indices = []
idx = -1
while True:
try:
idx = inlist.index(value,idx+1)
out_indices.append(idx)
except ValueError:
break
return out_indices
# 计算K距离邻居
k_distance_neig = defaultdict(list)
for i in range(instance.shape[0]):
# 获得它到所有邻居点的距离
distances = dist[i].tolist()
print 'k distance neighbourhood',i
print distances
# 获得从第1到第k的最近邻
ksmallest = heapq.nsmallest(k+1,distances)[1:]
print ksmallest
ksmallest_set = set(ksmallest)
print ksmallest_set
ksmallest_idx = []
# 获取k里最小的元素的索引号
for x in ksmallest_set:
ksmallest_idx.append(all_indices(x,distances))
# 将列表的列表转换为列表
ksmallest_idx = [item for sublist in ksmallest_idx for item in sublist]
# 对每个点保存
k_distance_neig[i].extend(zip(ksmallest,ksmallest_idx))
print k_distance_neig
# 计算可达距离和LRD
# 局部可达密度
local_reach_density = defaultdict(float)
for i in range(instance.shape[0]):
# LRD分子,k距离邻居的个数
no_neighbours = len(k_distance_neig[i])
denom_sum = 0
# 可达距离求和
for neigh in k_distance_neig[i]:
denom_sum += max(k_distance[neigh[1]][0],neigh[0])
local_reach_density[i] = no_neighbours/(1.0*denom_sum)
# 计算LOF
lof_list = []
for i in range(instance.shape[0]):
lrd_sum = 0
rdist_sum = 0
for neigh in k_distance_neig[i]:
lrd_sum +=local_reach_density[neigh[1]]
rdist_sum += max(k_distance[neigh[1]][0],neigh[0])
lof_list.append((i,lrd_sum*rdist_sum))
print lof_list
Explanation: 局部异常因子计算出每个点的局部密度,通过它与K最近邻的点的距离来评估点的局部密度,并与邻居的密度进行比较,以此找出异常点--异常点比邻居的密度要低得多
为了理解LOF,先了解一些术语的定义
* 对象P的K距离:对象P与它第K个最近邻的距离,K是算法的参数
P的K距离邻居:到P的距离小于或等于P到第K个最邻近的距离的所有对象的集合Q
* 从P到Q的可达距离:P与它的第K个最近邻的距离和P和Q之间的距离中的最大者。
P的局部可达密度(local Reachability Density of P):K距离邻居和K与其邻居的可达距离之和的比值
* P的局部异常因子(Local Outlier Factor of P):P与它的K最近邻的局部可达性的比值的平均值
End of explanation |
7,430 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Why EP-ABC can produce too narrow posteriors
When you use EP-ABC for inference you may notice that your posterior distributions appear suspiciously narrow, i.e., you may not belief the certainty indicated by EP-ABC inference. Your suspicions can be correct
Step1: Recursive Sampling of a Gaussian
The following cell repeatedly runs a recursive sampling process and plots the average drifts of mean and standard deviation across the repetitions.
Step2: The generated plots should have a relatively flat, thick, black line in the middle which suggests that mean and standard deviation did not change much when averaged across repetitions. The shading, representing the area of double standard deviation across repetitions, however, should become wider as more recursive sampling steps are taken, indicating that in some repetitions there was a considerable drift of the distribution (see below for plots of individual trajectories).
You may now want to see how these curves change, when you manipulate the number of samples, or degrees of freedom (ddof) used to estimate standard deviations from samples. Increasing the number of samples is generally good and leads to a reduction of mean drift and a narrowing of the shading, meaning that also the drift in individual repetitions of recursive sampling is small. Setting ddof=0, which is the standard setting of numpy (!), leads to severe shrinkage of the sampled distribution.
Individual recursive sampling trajectories
To get a feeling for the variability of recursive sampling trajectories across repetitions the following cell will plot a single (random) trajectory computed above. | Python Code:
def plot_mean_with_std(mean, std, std_mult=2, xvals=None, ax=None):
if xvals is None:
xvals = np.arange(mean.shape[0])
if ax is None:
ax = plt.axes()
ax.plot(mean, 'k', lw=3)
ax.fill_between(xvals, mean + std_mult*std, mean - std_mult*std,
edgecolor='k', facecolor='0.7')
def plot_single_trajectory(means, stds, rep=None):
if rep is None:
rep = np.random.randint(means.shape[0])
xvals = np.arange(means.shape[1])
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True)
ax1.set_title('repetition %d' % rep)
plot_mean_with_std(means[rep, :], stds[rep, :], xvals=xvals, ax=ax1)
ax2.set_ylabel('mean')
ax2.plot(xvals, means[rep, :], 'k', lw=3, label='mean')
ax3.set_ylabel('std')
ax3.plot(xvals, stds[rep, :], 'k', lw=1, label='std')
diff = means[rep, :] - means[rep, 0]
print('largest deviation from initial mean: %6.1f%% (of initial std)'
% (diff[np.abs(diff).argmax()] / stds[rep, 0] * 100, ) )
diff = stds[rep, :] - stds[rep, 0]
print('largest deviation from initial std: %6.1f%%'
% (diff[np.abs(diff).argmax()] / stds[rep, 0] * 100, ) )
def plot_distribution_drift(means, stds):
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.set_title('average drift of mean (+- 2*std)')
plot_mean_with_std(means.mean(axis=0), means.std(axis=0), ax=ax1)
ax2.set_title('average drift of std (+- 2*std)')
plot_mean_with_std(stds.mean(axis=0), stds.std(axis=0), ax=ax2)
Explanation: Why EP-ABC can produce too narrow posteriors
When you use EP-ABC for inference you may notice that your posterior distributions appear suspiciously narrow, i.e., you may not belief the certainty indicated by EP-ABC inference. Your suspicions can be correct: The posteriors inferred by EP-ABC sometimes tend to be too narrow. The fault lies within the recursive sampling process used in EP-ABC: The main mechanism is to maintain an estimate of the posterior distribution from which you sample and then re-estimate the posterior distribution based on a subset of the samples compatible with a data point. If the distribution from which you sample has some sampling error, your next estimate of that distribution will deviate even more from the underlying distribution, especially, if the sampling error consistently deviates in one direction. This is exactly what can happen in individual runs of EP-ABC.
In the following, I will demonstrate drifting distribution estimates by recursively sampling from a Gaussian. Ideally, the estimated mean and standard deviation would remain stable, but sampling error lets them drift. The question, therefore, is how strong the drift is and whether it has a trend.
Sampling theory
It is known, but rarely appreciated, that the square root of an unbiased estimate of variance consistently underestimates the standard deviation. Because we use standard deviations when sampling from a Gaussian (also in EP-ABC), recursively sampling from a Gaussian will shrink its standard deviation, even though we may have no bias in estimating the variance of the distribution. Actually, it's not so hard to compute an unbiased estimate of the standard deviation, at least approximately: Instead of dividing by $N-1$, as in the unbiased estimate of variance, we only have to divide by $N-1.5$. I have implemented this in EP-ABC to reduce the shrinking of posteriors. Below you can see for yourself what effect this has.
Some plotting functions
I here define some plotting functions used below.
End of explanation
# number of recursive steps
nsteps = 200
# number of samples drawn from distribution
nsamples = 500
# number of repetitions of recursive sampling
nrep = 100
# initial mean
mu = 23
# initial standard deviation
sigma = 100
# degrees of freedom determining the divisor for
# the estimation of standard deviation (1.5~unbiased)
ddof = 1.5
means = np.full((nrep, nsteps), np.nan)
means[:, 0] = mu
stds = np.full((nrep, nsteps), np.nan)
stds[:, 0] = sigma
for r in range(nrep):
for s in range(1, nsteps):
S = np.random.normal(means[r, s-1], stds[r, s-1], nsamples)
means[r, s] = S.mean()
stds[r, s] = S.std(ddof=ddof)
plot_distribution_drift(means, stds)
print('after %d steps with %d samples:' % (nsteps, nsamples))
print('difference in mean mean: %6.1f%% (of initial std)' % (
(means[:, -1].mean() - mu) / sigma * 100, ))
print('difference in mean std: %6.1f%%' % ((stds[:, -1].mean() - sigma) /
sigma * 100, ))
Explanation: Recursive Sampling of a Gaussian
The following cell repeatedly runs a recursive sampling process and plots the average drifts of mean and standard deviation across the repetitions.
End of explanation
plot_single_trajectory(means, stds)
Explanation: The generated plots should have a relatively flat, thick, black line in the middle which suggests that mean and standard deviation did not change much when averaged across repetitions. The shading, representing the area of double standard deviation across repetitions, however, should become wider as more recursive sampling steps are taken, indicating that in some repetitions there was a considerable drift of the distribution (see below for plots of individual trajectories).
You may now want to see how these curves change, when you manipulate the number of samples, or degrees of freedom (ddof) used to estimate standard deviations from samples. Increasing the number of samples is generally good and leads to a reduction of mean drift and a narrowing of the shading, meaning that also the drift in individual repetitions of recursive sampling is small. Setting ddof=0, which is the standard setting of numpy (!), leads to severe shrinkage of the sampled distribution.
Individual recursive sampling trajectories
To get a feeling for the variability of recursive sampling trajectories across repetitions the following cell will plot a single (random) trajectory computed above.
End of explanation |
7,431 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples of propagating uncertainties in mocsy
<hr>
James Orr - 11 November 2018<br>
<img align="left" width="60%" src="http
Step1: 1.2 Import standard python libraries
Step2: 1.3 Import mocsy (after specifying location of its shared object file)
The first uncommented line below is the subdirectory where the make command was executed (where mocsy.so is located)
Step3: 2. Compute derived variables using mocsy's vars routine
For starters, begin with a simple example of how to call (in python) mocsy's most used routine, vars
Some basic documentation
Step4: Specify input variables and options
Step5: Call the vars routine
Step6: Print output
Step7: 3. Example use of errors routine
Step8: Define errors
Step9: Basic call to errors routine
Step10: Call errors specifying most all of the arguments, including the optional ones for just the errors routine (r, epk, and ebt).
In the cell below, the results would be identical if those 3 options were not present, because the values listed are the defaults in the errors routine
Step11: 3.2 Errors, assuming defaults for r, epK, eBt
Step12: 3.3 Errors, specifying 0 for r, epK, eBt
Step13: 3.3 Errors, specifying r=1.0 | Python Code:
%%bash
pwd
mkdir code
cd code
git clone https://github.com/jamesorr/mocsy.git
cd mocsy
make
pwd
Explanation: Examples of propagating uncertainties in mocsy
<hr>
James Orr - 11 November 2018<br>
<img align="left" width="60%" src="http://www.lsce.ipsl.fr/Css/img/banniere_LSCE_75.png" ><br><br>
LSCE/IPSL, CEA-CNRS-UVSQ, Gif-sur-Yvette, France
<hr>
Table of contents:
Download, build, and import mocsy
Simple use of mocsy's vars routine
Simple use of mocsy's errors routine
1. Setup
1.1 Download and build mocsy (Do this only once)
Put code into ./code/mocsy subdirectory and build mocsy.so for import into python
The build process might take a couple of minutes, depending our your computer
End of explanation
## Preliminaries
import numpy as np
import pandas as pd
import os, sys
Explanation: 1.2 Import standard python libraries
End of explanation
# Comment out 1st line below, and Uncomment 2nd line below (if you have run the cell above under section 1.1)
mocsy_dir = "/homel/orr/Software/fortran/mocsy"
#mocsy_dir = "./code/mocsy"
sys.path.append (mocsy_dir)
import mocsy
Explanation: 1.3 Import mocsy (after specifying location of its shared object file)
The first uncommented line below is the subdirectory where the make command was executed (where mocsy.so is located)
End of explanation
print mocsy.mvars.vars.__doc__
Explanation: 2. Compute derived variables using mocsy's vars routine
For starters, begin with a simple example of how to call (in python) mocsy's most used routine, vars
Some basic documentation
End of explanation
# Options:
optCON = 'mol/kg'
optT = 'Tinsitu'
optP = 'm'
#optB = 'l10'
optB = 'u74'
optK1K2 = 'l'
optKf = 'dg'
# Standard 6 input variables
temp = 18.0
sal = 35.0
alk = 2300.e-6
dic = 2000.e-6
#phos = 2.0e-6
#sil = 60.0e-6
phos = 0.0e-6
sil = 0.0e-6
# Other standard input (depth, atm pressure, latitude)
depth = 0.
Patm = 1.0
lat = 0.
Explanation: Specify input variables and options
End of explanation
ph, pco2, fco2, co2, hco3, co3, OmegaA, OmegaC, BetaD, rhoSW, p, tempis = mocsy.mvars.vars(
temp, sal, alk, dic, sil, phos, Patm, depth, lat,
optCON, optT, optP, optb=optB, optk1k2=optK1K2, optkf=optKf )
Explanation: Call the vars routine
End of explanation
print ph, pco2, fco2, co2, hco3, co3, OmegaA, OmegaC, BetaD, rhoSW, p, tempis
Explanation: Print output
End of explanation
print mocsy.merrors.__doc__
Explanation: 3. Example use of errors routine
End of explanation
#etemp, esal = 0.01, 0.01
etemp, esal = 0.0, 0.0
ealk, edic = 2e-6, 2e-6
esil = 5e-6
ephos = 0.1e-6
Explanation: Define errors
End of explanation
[eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC] = \
mocsy.merrors(
temp, sal, alk, dic, sil, phos, Patm, depth, lat,
etemp, esal, ealk, edic, esil, ephos,
optCON, optT, optP, optb=optB, optk1k2=optK1K2, optkf=optKf, optgas='Pinsitu', ebt=0.01)
print eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC
[eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC] = \
mocsy.merrors(
temp, sal, alk, dic, sil, phos, Patm, depth, lat,
etemp, esal, ealk, edic, esil, ephos,
optCON, optT, optP, optb=optB, optk1k2=optK1K2, optkf=optKf, optgas='Pinsitu')
print eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC
Explanation: Basic call to errors routine
End of explanation
[eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC] = \
mocsy.merrors(
temp, sal, alk, dic, sil, phos, Patm, depth, lat,
etemp, esal, ealk, edic, esil, ephos,
optCON, optT, optP, optb=optB, optk1k2=optK1K2, optkf=optKf,
r=0.0, epk=np.array([0.002,0.0075,0.015,0.01,0.01,0.02,0.02]), ebt=0.02)
print eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC
Explanation: Call errors specifying most all of the arguments, including the optional ones for just the errors routine (r, epk, and ebt).
In the cell below, the results would be identical if those 3 options were not present, because the values listed are the defaults in the errors routine:
* r = 0.0 (no correlation between uncertainties in input pair (ealk and edic).
* epk = a 7-member vector for the uncertainties in the equil. constants (K0, K1, K2, Kb, Kw, Ka, Kc) in pK units
* ebt = the uncertainty in total boron, a relative fractional error [i.e., ebt = 0.02 is a 2% error, the default]
3.1 Errors, specifying standard r, epK, eBt
End of explanation
[eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC] = \
mocsy.merrors(
temp, sal, alk, dic, sil, phos, Patm, depth, lat,
etemp, esal, ealk, edic, esil, ephos,
optCON, optT, optP, optb=optB, optk1k2=optK1K2, optkf=optKf)
print eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC
Explanation: 3.2 Errors, assuming defaults for r, epK, eBt
End of explanation
[eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC] = \
mocsy.merrors(
temp, sal, alk, dic, sil, phos, Patm, depth, lat,
etemp, esal, ealk, edic, esil, ephos,
optCON, optT, optP, optb=optB, optk1k2=optK1K2, optkf=optKf,
epk=np.array([0.000,0.000,0.00,0.00,0.00,0.00,0.00]), ebt=0.00)
print eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC
Explanation: 3.3 Errors, specifying 0 for r, epK, eBt
End of explanation
[eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC] = \
mocsy.merrors(
temp, sal, alk, dic, sil, phos, Patm, depth, lat,
etemp, esal, ealk, edic, esil, ephos,
optCON, optT, optP, optb=optB, optk1k2=optK1K2, optkf=optKf, r=1.0)
print eH, epCO2, efCO2, eCO2, eHCO3, eCO3, eOmegaA, eOmegaC
Explanation: 3.3 Errors, specifying r=1.0
End of explanation |
7,432 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ATM 623
Step1: Contents
A single layer atmosphere
Introducing the two-layer grey gas model
Tuning the grey gas model to observations
Level of emission
Radiative forcing in the 2-layer grey gas model
Radiative equilibrium in the 2-layer grey gas model
Summary
<a id='section1'></a>
1. A single layer atmosphere
We will make our first attempt at quantifying the greenhouse effect in the simplest possible greenhouse model
Step2: Longwave emissions
Let's denote the emissions from each layer as
\begin{align}
E_s &= \sigma T_s^4 \
E_0 &= \epsilon \sigma T_0^4 \
E_1 &= \epsilon \sigma T_1^4
\end{align}
recognizing that $E_0$ and $E_1$ contribute to both the upwelling and downwelling beams.
Step3: Shortwave radiation
Since we have assumed the atmosphere is transparent to shortwave, the incident beam $Q$ passes unchanged from the top to the surface, where a fraction $\alpha$ is reflected upward out to space.
Step4: Upwelling beam
Let $U$ be the upwelling flux of longwave radiation.
The upward flux from the surface to layer 0 is
$$ U_0 = E_s $$
(just the emission from the suface).
Step5: Following this beam upward, we can write the upward flux from layer 0 to layer 1 as the sum of the transmitted component that originated below layer 0 and the new emissions from layer 0
Step6: Continuing to follow the same beam, the upwelling flux above layer 1 is
$$ U_2 = (1-\epsilon) U_1 + E_1 $$
Step7: Since there is no more atmosphere above layer 1, this upwelling flux is our Outgoing Longwave Radiation for this model
Step8: The three terms in the above expression represent the contributions to the total OLR that originate from each of the three levels.
Let's code this up explicitly for future reference
Step9: Downwelling beam
Let $D$ be the downwelling longwave beam. Since there is no longwave radiation coming in from space, we begin with
Step10: Between layer 1 and layer 0 the beam contains emissions from layer 1
Step11: Finally between layer 0 and the surface the beam contains a transmitted component and the emissions from layer 0
Step12: This $D_0$ is what we call the back radiation, i.e. the longwave radiation from the atmosphere to the surface.
<a id='section3'></a>
3. Tuning the grey gas model to observations
In building our new model we have introduced exactly one parameter, the absorptivity $\epsilon$. We need to choose a value for $\epsilon$.
We will tune our model so that it reproduces the observed global mean OLR given observed global mean temperatures.
To get appropriate temperatures for $T_s, T_0, T_1$, let's revisit the global, annual mean lapse rate plot from NCEP Reanalysis data from the previous lecture.
Temperatures
First, we set
$$T_s = 288 \text{ K} $$
From the lapse rate plot, an average temperature for the layer between 1000 and 500 hPa is
$$ T_0 = 275 \text{ K}$$
Defining an average temperature for the layer between 500 and 0 hPa is more ambiguous because of the lapse rate reversal at the tropopause. We will choose
$$ T_1 = 230 \text{ K}$$
From the graph, this is approximately the observed global mean temperature at 275 hPa or about 10 km.
Step13: OLR
From the observed global energy budget we set
$$ OLR = 238.5 \text{ W m}^{-2} $$
Solving for $\epsilon$
We wrote down the expression for OLR as a function of temperatures and absorptivity in our model above.
We just need to equate this to the observed value and solve a quadratic equation for $\epsilon$.
This is where the real power of the symbolic math toolkit comes in.
Subsitute in the numerical values we are interested in
Step14: We have a quadratic equation for $\epsilon$.
Now use the sympy.solve function to solve the quadratic
Step15: There are two roots, but the second one is unphysical since we must have $0 < \epsilon < 1$.
Just for fun, here is a simple of example of filtering a list using powerful Python list comprehension syntax
Step16: We conclude that our tuned value is
$$ \epsilon = 0.586 $$
This is the absorptivity that guarantees that our model reproduces the observed OLR given the observed tempertures.
Step17: <a id='section4'></a>
4. Level of emission
Even in this very simple greenhouse model, there is no single level at which the OLR is generated.
The three terms in our formula for OLR tell us the contributions from each level.
Step18: Now evaluate these expressions for our tuned temperature and absorptivity
Step19: So we are getting about 67 W m$^{-2}$ from the surface, 79 W m$^{-2}$ from layer 0, and 93 W m$^{-2}$ from the top layer.
In terms of fractional contributions to the total OLR, we have (limiting the output to two decimal places)
Step20: Notice that the largest single contribution is coming from the top layer. This is in spite of the fact that the emissions from this layer are weak, because it is so cold.
Comparing to observations, the actual contribution to OLR from the surface is about 22 W m$^{-2}$ (or about 9% of the total), not 67 W m$^{-2}$. So we certainly don't have all the details worked out yet!
As we will see later, to really understand what sets that observed 22 W m$^{-2}$, we will need to start thinking about the spectral dependence of the longwave absorptivity.
<a id='section5'></a>
5. Radiative forcing in the 2-layer grey gas model
Adding some extra greenhouse absorbers will mean that a greater fraction of incident longwave radiation is absorbed in each layer.
Thus $\epsilon$ must increase as we add greenhouse gases.
Suppose we have $\epsilon$ initially, and the absorptivity increases to $\epsilon_2 = \epsilon + \delta_\epsilon$.
Suppose further that this increase happens abruptly so that there is no time for the temperatures to respond to this change. We hold the temperatures fixed in the column and ask how the radiative fluxes change.
Do you expect the OLR to increase or decrease?
Let's use our two-layer leaky greenhouse model to investigate the answer.
The components of the OLR before the perturbation are
Step21: After the perturbation we have
Step22: Let's take the difference
Step23: To make things simpler, we will neglect the terms in $\delta_\epsilon^2$. This is perfectly reasonably because we are dealing with small perturbations where $\delta_\epsilon << \epsilon$.
Telling sympy to set the quadratic terms to zero gives us
Step24: Recall that the three terms are the contributions to the OLR from the three different levels. In this case, the changes in those contributions after adding more absorbers.
Now let's divide through by $\delta_\epsilon$ to get the normalized change in OLR per unit change in absorptivity
Step25: Now look at the sign of each term. Recall that $0 < \epsilon < 1$. Which terms in the OLR go up and which go down?
THIS IS VERY IMPORTANT, SO STOP AND THINK ABOUT IT.
The contribution from the surface must decrease, while the contribution from the top layer must increase.
When we add absorbers, the average level of emission goes up!
"Radiative forcing" is the change in radiative flux at TOA after adding absorbers
In this model, only the longwave flux can change, so we define the radiative forcing as
$$ R = - \delta OLR $$
(with the minus sign so that $R$ is positive when the climate system is gaining extra energy).
We just worked out that whenever we add some extra absorbers, the emissions to space (on average) will originate from higher levels in the atmosphere.
What does this mean for OLR? Will it increase or decrease?
To get the answer, we just have to sum up the three contributions we wrote above
Step26: Is this a positive or negative number? The key point is this
Step27: which then simplifies to
Step28: The answer is zero
For an isothermal atmosphere, there is no change in OLR when we add extra greenhouse absorbers. Hence, no radiative forcing and no greenhouse effect.
Why?
The level of emission still must go up. But since the temperature at the upper level is the same as everywhere else, the emissions are exactly the same.
The radiative forcing (change in OLR) depends on the lapse rate!
For a more realistic example of radiative forcing due to an increase in greenhouse absorbers, we can substitute in our tuned values for temperature and $\epsilon$.
We'll express the answer in W m$^{-2}$ for a 1% increase in $\epsilon$.
The three components of the OLR change are
Step29: And the net radiative forcing is
Step30: So in our example, the OLR decreases by 2.2 W m$^{-2}$, or equivalently, the radiative forcing is +2.2 W m$^{-2}$.
What we have just calculated is this
Step31: Net absorption is the flux convergence in each layer
(difference between what's coming in the bottom and what's going out the top of each layer)
Step32: Radiative equilibrium means net absorption is ZERO in the atmosphere
The only other heat source is the shortwave heating at the surface.
In matrix form, here is the system of equations to be solved
Step33: Just as we did for the 1-layer model, it is helpful to rewrite this system using the definition of the emission temperture $T_e$
$$ (1-\alpha) Q = \sigma T_e^4 $$
Step34: In this form we can see that we actually have a linear system of equations for a set of variables $T_s^4, T_0^4, T_1^4$.
We can solve this matrix problem to get these as functions of $T_e^4$.
Step35: This produces a dictionary of solutions for the fourth power of the temperatures!
A little manipulation gets us the solutions for temperatures that we want
Step36: In more familiar notation, the radiative equilibrium solution is thus
\begin{align}
T_s &= T_e \left( \frac{2+\epsilon}{2-\epsilon} \right)^{1/4} \
T_0 &= T_e \left( \frac{1+\epsilon}{2-\epsilon} \right)^{1/4} \
T_1 &= T_e \left( \frac{ 1}{2 - \epsilon} \right)^{1/4}
\end{align}
Plugging in the tuned value $\epsilon = 0.586$ gives
Step37: Now we just need to know the Earth's emission temperature $T_e$!
(Which we already know is about 255 K)
Step38: Now we finally get our solution for radiative equilibrium
Step39: Compare these to the values we derived from the observed lapse rates
Step40: The radiative equilibrium solution is substantially warmer at the surface and colder in the lower troposphere than reality.
This is a very general feature of radiative equilibrium, and we will see it again very soon in this course.
<a id='section7'></a>
7. Summary
Key physical lessons
Putting a layer of longwave absorbers above the surface keeps the surface substantially warmer, because of the backradiation from the atmosphere (greenhouse effect).
The grey gas model assumes that each layer absorbs and emits a fraction $\epsilon$ of its blackbody value, independent of wavelength.
With incomplete absorption ($\epsilon < 1$), there are contributions to the OLR from every level and the surface (there is no single level of emission)
Adding more absorbers means that contributions to the OLR from upper levels go up, while contributions from the surface go down.
This upward shift in the weighting of different levels is what we mean when we say the level of emission goes up.
The radiative forcing caused by an increase in absorbers depends on the lapse rate.
For an isothermal atmosphere the radiative forcing is zero and there is no greenhouse effect
The radiative forcing is positive for our atmosphere because tropospheric temperatures tends to decrease with height.
Pure radiative equilibrium produces a warm surface and cold lower troposphere.
This is unrealistic, and suggests that crucial heat transfer mechanisms are missing from our model.
And on the Python side...
Did we need sympy to work all this out? No, of course not. We could have solved the 3x3 matrix problems by hand. But computer algebra can be very useful and save you a lot of time and error, so it's good to invest some effort into learning how to use it.
Hopefully these notes provide a useful starting point.
A follow-up assignment
You are now ready to tackle Assignment 5, where you are asked to extend this grey-gas analysis to many layers.
For more than a few layers, the analytical approach we used here is no longer very useful. You will code up a numerical solution to calculate OLR given temperatures and absorptivity, and look at how the lapse rate determines radiative forcing for a given increase in absorptivity.
<div class="alert alert-success">
[Back to ATM 623 notebook home](../index.ipynb)
</div>
Version information | Python Code:
# Ensure compatibility with Python 2 and 3
from __future__ import print_function, division
Explanation: ATM 623: Climate Modeling
Brian E. J. Rose, University at Albany
Lecture 7: Elementary greenhouse models
Warning: content out of date and not maintained
You really should be looking at The Climate Laboratory book by Brian Rose, where all the same content (and more!) is kept up to date.
Here you are likely to find broken links and broken code.
About these notes:
This document uses the interactive Jupyter notebook format. The notes can be accessed in several different ways:
The interactive notebooks are hosted on github at https://github.com/brian-rose/ClimateModeling_courseware
The latest versions can be viewed as static web pages rendered on nbviewer
A complete snapshot of the notes as of May 2017 (end of spring semester) are available on Brian's website.
Also here is a legacy version from 2015.
Many of these notes make use of the climlab package, available at https://github.com/brian-rose/climlab
End of explanation
import sympy
# Allow sympy to produce nice looking equations as output
sympy.init_printing()
# Define some symbols for mathematical quantities
# Assume all quantities are positive (which will help simplify some expressions)
epsilon, T_e, T_s, T_0, T_1, sigma = \
sympy.symbols('epsilon, T_e, T_s, T_0, T_1, sigma', positive=True)
# So far we have just defined some symbols, e.g.
T_s
# We have hard-coded the assumption that the temperature is positive
sympy.ask(T_s>0)
Explanation: Contents
A single layer atmosphere
Introducing the two-layer grey gas model
Tuning the grey gas model to observations
Level of emission
Radiative forcing in the 2-layer grey gas model
Radiative equilibrium in the 2-layer grey gas model
Summary
<a id='section1'></a>
1. A single layer atmosphere
We will make our first attempt at quantifying the greenhouse effect in the simplest possible greenhouse model: a single layer of atmosphere that is able to absorb and emit longwave radiation.
<img src='../images/1layerAtm_sketch.png'>
Assumptions
Atmosphere is a single layer of air at temperature $T_a$
Atmosphere is completely transparent to shortwave solar radiation.
The surface absorbs shortwave radiation $(1-\alpha) Q$
Atmosphere is completely opaque to infrared radiation
Both surface and atmosphere emit radiation as blackbodies ($\sigma T_s^4, \sigma T_a^4$)
Atmosphere radiates equally up and down ($\sigma T_a^4$)
There are no other heat transfer mechanisms
We can now use the concept of energy balance to ask what the temperature need to be in order to balance the energy budgets at the surface and the atmosphere, i.e. the radiative equilibrium temperatures.
Energy balance at the surface
\begin{align}
\text{energy in} &= \text{energy out} \
(1-\alpha) Q + \sigma T_a^4 &= \sigma T_s^4 \
\end{align}
The presence of the atmosphere above means there is an additional source term: downwelling infrared radiation from the atmosphere.
We call this the back radiation.
Energy balance for the atmosphere
\begin{align}
\text{energy in} &= \text{energy out} \
\sigma T_s^4 &= A\uparrow + A\downarrow = 2 \sigma T_a^4 \
\end{align}
which means that
$$ T_s = 2^\frac{1}{4} T_a \approx 1.2 T_a $$
So we have just determined that, in order to have a purely radiative equilibrium, we must have $T_s > T_a$.
The surface must be warmer than the atmosphere.
Solve for the radiative equilibrium surface temperature
Now plug this into the surface equation to find
$$ \frac{1}{2} \sigma T_s^4 = (1-\alpha) Q $$
and use the definition of the emission temperature $T_e$ to write
$$ (1-\alpha) Q = \sigma T_e^4 $$
In fact, in this model, $T_e$ is identical to the atmospheric temperature $T_a$, since all the OLR originates from this layer.
Solve for the surface temperature:
$$ T_s = 2^\frac{1}{4} T_e $$
Putting in observed numbers, $T_e = 255$ K gives a surface temperature of
$$T_s = 303 ~\text{K}$$
This model is one small step closer to reality: surface is warmer than atmosphere, emissions to space generated in the atmosphere, atmosphere heated from below and helping to keep surface warm.
BUT our model now overpredicts the surface temperature by about 15ºC (or K).
Ideas about why?
Basically we just need to read our list of assumptions above and realize that none of them are very good approximations:
Atmosphere absorbs some solar radiation.
Atmosphere is NOT a perfect absorber of longwave radiation
Absorption and emission varies strongly with wavelength (atmosphere does not behave like a blackbody).
Emissions are not determined by a single temperature $T_a$ but by the detailed vertical profile of air temperture.
Energy is redistributed in the vertical by a variety of dynamical transport mechanisms (e.g. convection and boundary layer turbulence).
<a id='section2'></a>
2. Introducing the two-layer grey gas model
Let's generalize the above model just a little bit to build a slighly more realistic model of longwave radiative transfer.
We will address two shortcomings of our single-layer model:
1. No vertical structure
2. 100% longwave opacity
Relaxing these two assumptions gives us what turns out to be a very useful prototype model for understanding how the greenhouse effect works.
Assumptions
The atmosphere is transparent to shortwave radiation (still)
Divide the atmosphere up into two layers of equal mass (the dividing line is thus at 500 hPa pressure level)
Each layer absorbs only a fraction $\epsilon$ of whatever longwave radiation is incident upon it.
We will call the fraction $\epsilon$ the absorptivity of the layer.
Assume $\epsilon$ is the same in each layer
This is called the grey gas model, where grey here means the emission and absorption have no spectral dependence.
We can think of this model informally as a "leaky greenhouse".
Note that the assumption that $\epsilon$ is the same in each layer is appropriate if the absorption is actually carried out by a gas that is well-mixed in the atmosphere.
Out of our two most important absorbers:
CO$_2$ is well mixed
H$_2$O is not (mostly confined to lower troposphere due to strong temperature dependence of the saturation vapor pressure).
But we will ignore this aspect of reality for now.
In order to build our model, we need to introduce one additional piece of physics known as Kirchoff's Law:
$$ \text{absorptivity} = \text{emissivity} $$
So if a layer of atmosphere at temperature $T$ absorbs a fraction $\epsilon$ of incident longwave radiation, it must emit
$$ \epsilon ~\sigma ~T^4 $$
both up and down.
A sketch of the radiative fluxes in the 2-layer atmosphere
<img src='../images/2layerAtm_sketch.png'>
Surface temperature is $T_s$
Atm. temperatures are $T_0, T_1$ where $T_0$ is closest to the surface.
absorptivity of atm layers is $\epsilon$
Surface emission is $\sigma T_s^4$
Atm emission is $\epsilon \sigma T_0^4, \epsilon \sigma T_1^4$ (up and down)
Absorptivity = emissivity for atmospheric layers
a fraction $(1-\epsilon)$ of the longwave beam is transmitted through each layer
A fun aside: symbolic math with the sympy package
This two-layer grey gas model is simple enough that we can work out all the details algebraically. There are three temperatures to keep track of $(T_s, T_0, T_1)$, so we will have 3x3 matrix equations.
We all know how to work these things out with pencil and paper. But it can be tedious and error-prone.
Symbolic math software lets us use the computer to automate a lot of tedious algebra.
The sympy package is a powerful open-source symbolic math library that is well-integrated into the scientific Python ecosystem.
End of explanation
# Define these operations as sympy symbols
# And display as a column vector:
E_s = sigma*T_s**4
E_0 = epsilon*sigma*T_0**4
E_1 = epsilon*sigma*T_1**4
E = sympy.Matrix([E_s, E_0, E_1])
E
Explanation: Longwave emissions
Let's denote the emissions from each layer as
\begin{align}
E_s &= \sigma T_s^4 \
E_0 &= \epsilon \sigma T_0^4 \
E_1 &= \epsilon \sigma T_1^4
\end{align}
recognizing that $E_0$ and $E_1$ contribute to both the upwelling and downwelling beams.
End of explanation
# Define some new symbols for shortwave radiation
Q, alpha = sympy.symbols('Q, alpha', positive=True)
# Create a dictionary to hold our numerical values
tuned = {}
tuned[Q] = 341.3 # global mean insolation in W/m2
tuned[alpha] = 101.9/Q.subs(tuned) # observed planetary albedo
tuned[sigma] = 5.67E-8 # Stefan-Boltzmann constant in W/m2/K4
tuned
# Numerical value for emission temperature
#T_e.subs(tuned)
Explanation: Shortwave radiation
Since we have assumed the atmosphere is transparent to shortwave, the incident beam $Q$ passes unchanged from the top to the surface, where a fraction $\alpha$ is reflected upward out to space.
End of explanation
U_0 = E_s
U_0
Explanation: Upwelling beam
Let $U$ be the upwelling flux of longwave radiation.
The upward flux from the surface to layer 0 is
$$ U_0 = E_s $$
(just the emission from the suface).
End of explanation
U_1 = (1-epsilon)*U_0 + E_0
U_1
Explanation: Following this beam upward, we can write the upward flux from layer 0 to layer 1 as the sum of the transmitted component that originated below layer 0 and the new emissions from layer 0:
$$ U_1 = (1-\epsilon) U_0 + E_0 $$
End of explanation
U_2 = (1-epsilon) * U_1 + E_1
Explanation: Continuing to follow the same beam, the upwelling flux above layer 1 is
$$ U_2 = (1-\epsilon) U_1 + E_1 $$
End of explanation
U_2
Explanation: Since there is no more atmosphere above layer 1, this upwelling flux is our Outgoing Longwave Radiation for this model:
$$ OLR = U_2 $$
End of explanation
# Define the contributions to OLR originating from each level
OLR_s = (1-epsilon)**2 *sigma*T_s**4
OLR_0 = epsilon*(1-epsilon)*sigma*T_0**4
OLR_1 = epsilon*sigma*T_1**4
OLR = OLR_s + OLR_0 + OLR_1
print( 'The expression for OLR is')
OLR
Explanation: The three terms in the above expression represent the contributions to the total OLR that originate from each of the three levels.
Let's code this up explicitly for future reference:
End of explanation
fromspace = 0
D_2 = fromspace
Explanation: Downwelling beam
Let $D$ be the downwelling longwave beam. Since there is no longwave radiation coming in from space, we begin with
End of explanation
D_1 = (1-epsilon)*D_2 + E_1
D_1
Explanation: Between layer 1 and layer 0 the beam contains emissions from layer 1:
$$ D_1 = (1-\epsilon)D_2 + E_1 = E_1 $$
End of explanation
D_0 = (1-epsilon)*D_1 + E_0
D_0
Explanation: Finally between layer 0 and the surface the beam contains a transmitted component and the emissions from layer 0:
$$ D_0 = (1-\epsilon) D_1 + E_0 = \epsilon(1-\epsilon) \sigma T_1^4 + \epsilon \sigma T_0^4$$
End of explanation
# add to our dictionary of values:
tuned[T_s] = 288.
tuned[T_0] = 275.
tuned[T_1] = 230.
tuned
Explanation: This $D_0$ is what we call the back radiation, i.e. the longwave radiation from the atmosphere to the surface.
<a id='section3'></a>
3. Tuning the grey gas model to observations
In building our new model we have introduced exactly one parameter, the absorptivity $\epsilon$. We need to choose a value for $\epsilon$.
We will tune our model so that it reproduces the observed global mean OLR given observed global mean temperatures.
To get appropriate temperatures for $T_s, T_0, T_1$, let's revisit the global, annual mean lapse rate plot from NCEP Reanalysis data from the previous lecture.
Temperatures
First, we set
$$T_s = 288 \text{ K} $$
From the lapse rate plot, an average temperature for the layer between 1000 and 500 hPa is
$$ T_0 = 275 \text{ K}$$
Defining an average temperature for the layer between 500 and 0 hPa is more ambiguous because of the lapse rate reversal at the tropopause. We will choose
$$ T_1 = 230 \text{ K}$$
From the graph, this is approximately the observed global mean temperature at 275 hPa or about 10 km.
End of explanation
# the .subs() method for a sympy symbol means
# substitute values in the expression using the supplied dictionary
# Here we use observed values of Ts, T0, T1
OLR2 = OLR.subs(tuned)
OLR2
Explanation: OLR
From the observed global energy budget we set
$$ OLR = 238.5 \text{ W m}^{-2} $$
Solving for $\epsilon$
We wrote down the expression for OLR as a function of temperatures and absorptivity in our model above.
We just need to equate this to the observed value and solve a quadratic equation for $\epsilon$.
This is where the real power of the symbolic math toolkit comes in.
Subsitute in the numerical values we are interested in:
End of explanation
# The sympy.solve method takes an expression equal to zero
# So in this case we subtract the tuned value of OLR from our expression
eps_solution = sympy.solve(OLR2 - 238.5, epsilon)
eps_solution
Explanation: We have a quadratic equation for $\epsilon$.
Now use the sympy.solve function to solve the quadratic:
End of explanation
# Give me only the roots that are between zero and 1!
list_result = [eps for eps in eps_solution if 0<eps<1]
print( list_result)
# The result is a list with a single element.
# We need to slice the list to get just the number:
eps_tuned = list_result[0]
print( eps_tuned)
Explanation: There are two roots, but the second one is unphysical since we must have $0 < \epsilon < 1$.
Just for fun, here is a simple of example of filtering a list using powerful Python list comprehension syntax:
End of explanation
tuned[epsilon] = eps_tuned
tuned
Explanation: We conclude that our tuned value is
$$ \epsilon = 0.586 $$
This is the absorptivity that guarantees that our model reproduces the observed OLR given the observed tempertures.
End of explanation
OLRterms = sympy.Matrix([OLR_s, OLR_0, OLR_1])
OLRterms
Explanation: <a id='section4'></a>
4. Level of emission
Even in this very simple greenhouse model, there is no single level at which the OLR is generated.
The three terms in our formula for OLR tell us the contributions from each level.
End of explanation
OLRtuned = OLRterms.subs(tuned)
OLRtuned
Explanation: Now evaluate these expressions for our tuned temperature and absorptivity:
End of explanation
sympy.N(OLRtuned / 239., 2)
Explanation: So we are getting about 67 W m$^{-2}$ from the surface, 79 W m$^{-2}$ from layer 0, and 93 W m$^{-2}$ from the top layer.
In terms of fractional contributions to the total OLR, we have (limiting the output to two decimal places):
End of explanation
OLRterms
Explanation: Notice that the largest single contribution is coming from the top layer. This is in spite of the fact that the emissions from this layer are weak, because it is so cold.
Comparing to observations, the actual contribution to OLR from the surface is about 22 W m$^{-2}$ (or about 9% of the total), not 67 W m$^{-2}$. So we certainly don't have all the details worked out yet!
As we will see later, to really understand what sets that observed 22 W m$^{-2}$, we will need to start thinking about the spectral dependence of the longwave absorptivity.
<a id='section5'></a>
5. Radiative forcing in the 2-layer grey gas model
Adding some extra greenhouse absorbers will mean that a greater fraction of incident longwave radiation is absorbed in each layer.
Thus $\epsilon$ must increase as we add greenhouse gases.
Suppose we have $\epsilon$ initially, and the absorptivity increases to $\epsilon_2 = \epsilon + \delta_\epsilon$.
Suppose further that this increase happens abruptly so that there is no time for the temperatures to respond to this change. We hold the temperatures fixed in the column and ask how the radiative fluxes change.
Do you expect the OLR to increase or decrease?
Let's use our two-layer leaky greenhouse model to investigate the answer.
The components of the OLR before the perturbation are
End of explanation
delta_epsilon = sympy.symbols('delta_epsilon')
OLRterms_pert = OLRterms.subs(epsilon, epsilon+delta_epsilon)
OLRterms_pert
Explanation: After the perturbation we have
End of explanation
deltaOLR = OLRterms_pert - OLRterms
deltaOLR
Explanation: Let's take the difference
End of explanation
deltaOLR_linear = sympy.expand(deltaOLR).subs(delta_epsilon**2, 0)
deltaOLR_linear
Explanation: To make things simpler, we will neglect the terms in $\delta_\epsilon^2$. This is perfectly reasonably because we are dealing with small perturbations where $\delta_\epsilon << \epsilon$.
Telling sympy to set the quadratic terms to zero gives us
End of explanation
deltaOLR_per_deltaepsilon = \
sympy.simplify(deltaOLR_linear / delta_epsilon)
deltaOLR_per_deltaepsilon
Explanation: Recall that the three terms are the contributions to the OLR from the three different levels. In this case, the changes in those contributions after adding more absorbers.
Now let's divide through by $\delta_\epsilon$ to get the normalized change in OLR per unit change in absorptivity:
End of explanation
R = -sum(deltaOLR_per_deltaepsilon)
R
Explanation: Now look at the sign of each term. Recall that $0 < \epsilon < 1$. Which terms in the OLR go up and which go down?
THIS IS VERY IMPORTANT, SO STOP AND THINK ABOUT IT.
The contribution from the surface must decrease, while the contribution from the top layer must increase.
When we add absorbers, the average level of emission goes up!
"Radiative forcing" is the change in radiative flux at TOA after adding absorbers
In this model, only the longwave flux can change, so we define the radiative forcing as
$$ R = - \delta OLR $$
(with the minus sign so that $R$ is positive when the climate system is gaining extra energy).
We just worked out that whenever we add some extra absorbers, the emissions to space (on average) will originate from higher levels in the atmosphere.
What does this mean for OLR? Will it increase or decrease?
To get the answer, we just have to sum up the three contributions we wrote above:
End of explanation
R.subs([(T_0, T_s), (T_1, T_s)])
Explanation: Is this a positive or negative number? The key point is this:
It depends on the temperatures, i.e. on the lapse rate.
Greenhouse effect for an isothermal atmosphere
Stop and think about this question:
If the surface and atmosphere are all at the same temperature, does the OLR go up or down when $\epsilon$ increases (i.e. we add more absorbers)?
Understanding this question is key to understanding how the greenhouse effect works.
Let's solve the isothermal case
We will just set $T_s = T_0 = T_1$ in the above expression for the radiative forcing.
End of explanation
sympy.simplify(R.subs([(T_0, T_s), (T_1, T_s)]))
Explanation: which then simplifies to
End of explanation
deltaOLR_per_deltaepsilon.subs(tuned) * 0.01
Explanation: The answer is zero
For an isothermal atmosphere, there is no change in OLR when we add extra greenhouse absorbers. Hence, no radiative forcing and no greenhouse effect.
Why?
The level of emission still must go up. But since the temperature at the upper level is the same as everywhere else, the emissions are exactly the same.
The radiative forcing (change in OLR) depends on the lapse rate!
For a more realistic example of radiative forcing due to an increase in greenhouse absorbers, we can substitute in our tuned values for temperature and $\epsilon$.
We'll express the answer in W m$^{-2}$ for a 1% increase in $\epsilon$.
The three components of the OLR change are
End of explanation
R.subs(tuned) * 0.01
Explanation: And the net radiative forcing is
End of explanation
# Upwelling and downwelling beams as matrices
U = sympy.Matrix([U_0, U_1, U_2])
D = sympy.Matrix([D_0, D_1, D_2])
# Net flux, positive up
F = U-D
F
Explanation: So in our example, the OLR decreases by 2.2 W m$^{-2}$, or equivalently, the radiative forcing is +2.2 W m$^{-2}$.
What we have just calculated is this:
Given the observed lapse rates, a small increase in absorbers will cause a small decrease in OLR.
The greenhouse effect thus gets stronger, and energy will begin to accumulate in the system -- which will eventually cause temperatures to increase as the system adjusts to a new equilibrium.
<a id='section6'></a>
6. Radiative equilibrium in the 2-layer grey gas model
In the previous section we:
made no assumptions about the processes that actually set the temperatures.
used the model to calculate radiative fluxes, given observed temperatures.
stressed the importance of knowing the lapse rates in order to know how an increase in emission level would affect the OLR, and thus determine the radiative forcing.
A key question in climate dynamics is therefore this:
What sets the lapse rate?
It turns out that lots of different physical processes contribute to setting the lapse rate.
Understanding how these processes acts together and how they change as the climate changes is one of the key reasons for which we need more complex climate models.
For now, we will use our prototype greenhouse model to do the most basic lapse rate calculation: the radiative equilibrium temperature.
We assume that
the only exchange of energy between layers is longwave radiation
equilibrium is achieved when the net radiative flux convergence in each layer is zero.
Compute the radiative flux convergence
First, the net upwelling flux is just the difference between flux up and flux down:
End of explanation
# define a vector of absorbed radiation -- same size as emissions
A = E.copy()
# absorbed radiation at surface
A[0] = F[0]
# Compute the convergence
for n in range(2):
A[n+1] = -(F[n+1]-F[n])
A
Explanation: Net absorption is the flux convergence in each layer
(difference between what's coming in the bottom and what's going out the top of each layer)
End of explanation
radeq = sympy.Equality(A, sympy.Matrix([(1-alpha)*Q, 0, 0]))
radeq
Explanation: Radiative equilibrium means net absorption is ZERO in the atmosphere
The only other heat source is the shortwave heating at the surface.
In matrix form, here is the system of equations to be solved:
End of explanation
radeq2 = radeq.subs([((1-alpha)*Q, sigma*T_e**4)])
radeq2
Explanation: Just as we did for the 1-layer model, it is helpful to rewrite this system using the definition of the emission temperture $T_e$
$$ (1-\alpha) Q = \sigma T_e^4 $$
End of explanation
# Solve for radiative equilibrium
fourthpower = sympy.solve(radeq2, [T_s**4, T_1**4, T_0**4])
fourthpower
Explanation: In this form we can see that we actually have a linear system of equations for a set of variables $T_s^4, T_0^4, T_1^4$.
We can solve this matrix problem to get these as functions of $T_e^4$.
End of explanation
# need the symbolic fourth root operation
from sympy.simplify.simplify import nthroot
fourthpower_list = [fourthpower[key] for key in [T_s**4, T_0**4, T_1**4]]
solution = sympy.Matrix([nthroot(item,4) for item in fourthpower_list])
# Display result as matrix equation!
T = sympy.Matrix([T_s, T_0, T_1])
sympy.Equality(T, solution)
Explanation: This produces a dictionary of solutions for the fourth power of the temperatures!
A little manipulation gets us the solutions for temperatures that we want:
End of explanation
Tsolution = solution.subs(tuned)
# Display result as matrix equation!
sympy.Equality(T, Tsolution)
Explanation: In more familiar notation, the radiative equilibrium solution is thus
\begin{align}
T_s &= T_e \left( \frac{2+\epsilon}{2-\epsilon} \right)^{1/4} \
T_0 &= T_e \left( \frac{1+\epsilon}{2-\epsilon} \right)^{1/4} \
T_1 &= T_e \left( \frac{ 1}{2 - \epsilon} \right)^{1/4}
\end{align}
Plugging in the tuned value $\epsilon = 0.586$ gives
End of explanation
# Here's how to calculate T_e from the observed values
sympy.solve(((1-alpha)*Q - sigma*T_e**4).subs(tuned), T_e)
# Need to unpack the list
Te_value = sympy.solve(((1-alpha)*Q - sigma*T_e**4).subs(tuned), T_e)[0]
Te_value
Explanation: Now we just need to know the Earth's emission temperature $T_e$!
(Which we already know is about 255 K)
End of explanation
# Output 4 significant digits
Trad = sympy.N(Tsolution.subs([(T_e, Te_value)]), 4)
sympy.Equality(T, Trad)
Explanation: Now we finally get our solution for radiative equilibrium
End of explanation
sympy.Equality(T, T.subs(tuned))
Explanation: Compare these to the values we derived from the observed lapse rates:
End of explanation
%load_ext version_information
%version_information sympy
Explanation: The radiative equilibrium solution is substantially warmer at the surface and colder in the lower troposphere than reality.
This is a very general feature of radiative equilibrium, and we will see it again very soon in this course.
<a id='section7'></a>
7. Summary
Key physical lessons
Putting a layer of longwave absorbers above the surface keeps the surface substantially warmer, because of the backradiation from the atmosphere (greenhouse effect).
The grey gas model assumes that each layer absorbs and emits a fraction $\epsilon$ of its blackbody value, independent of wavelength.
With incomplete absorption ($\epsilon < 1$), there are contributions to the OLR from every level and the surface (there is no single level of emission)
Adding more absorbers means that contributions to the OLR from upper levels go up, while contributions from the surface go down.
This upward shift in the weighting of different levels is what we mean when we say the level of emission goes up.
The radiative forcing caused by an increase in absorbers depends on the lapse rate.
For an isothermal atmosphere the radiative forcing is zero and there is no greenhouse effect
The radiative forcing is positive for our atmosphere because tropospheric temperatures tends to decrease with height.
Pure radiative equilibrium produces a warm surface and cold lower troposphere.
This is unrealistic, and suggests that crucial heat transfer mechanisms are missing from our model.
And on the Python side...
Did we need sympy to work all this out? No, of course not. We could have solved the 3x3 matrix problems by hand. But computer algebra can be very useful and save you a lot of time and error, so it's good to invest some effort into learning how to use it.
Hopefully these notes provide a useful starting point.
A follow-up assignment
You are now ready to tackle Assignment 5, where you are asked to extend this grey-gas analysis to many layers.
For more than a few layers, the analytical approach we used here is no longer very useful. You will code up a numerical solution to calculate OLR given temperatures and absorptivity, and look at how the lapse rate determines radiative forcing for a given increase in absorptivity.
<div class="alert alert-success">
[Back to ATM 623 notebook home](../index.ipynb)
</div>
Version information
End of explanation |
7,433 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev2 toc-item"><a href="#start" data-toc-modified-id="start-01"><span class="toc-item-num">0.1 </span>start</a></div><div class="lev2 toc-item"><a href="#Bootstrap-regions-file" data-toc-modified-id="Bootstrap-regions-file-02"><span class="toc-item-num">0.2 </span>Bootstrap regions file</a></div><div class="lev3 toc-item"><a href="#estimate-SAF's" data-toc-modified-id="estimate-SAF's-021"><span class="toc-item-num">0.2.1 </span>estimate SAF's</a></div><div class="lev2 toc-item"><a href="#Get-intersection-of-sites-between-ERY-and-PAR" data-toc-modified-id="Get-intersection-of-sites-between-ERY-and-PAR-03"><span class="toc-item-num">0.3 </span>Get intersection of sites between ERY and PAR</a></div><div class="lev2 toc-item"><a href="#plot-SFS-from-only-overlapping-sites" data-toc-modified-id="plot-SFS-from-only-overlapping-sites-04"><span class="toc-item-num">0.4 </span>plot SFS from only overlapping sites</a></div><div class="lev2 toc-item"><a href="#Bootstrap-regions-file-from-only-overlapping-sites" data-toc-modified-id="Bootstrap-regions-file-from-only-overlapping-sites-05"><span class="toc-item-num">0.5 </span>Bootstrap regions file from only overlapping sites</a></div><div class="lev3 toc-item"><a href="#bootstrap-regions-file" data-toc-modified-id="bootstrap-regions-file-051"><span class="toc-item-num">0.5.1 </span>bootstrap regions file</a></div><div class="lev3 toc-item"><a href="#estimate-SAF-files" data-toc-modified-id="estimate-SAF-files-052"><span class="toc-item-num">0.5.2 </span>estimate SAF files</a></div><div class="lev2 toc-item"><a href="#Bootstrap-regions-file-from-including-non-overlapping-sites" data-toc-modified-id="Bootstrap-regions-file-from-including-non-overlapping-sites-06"><span class="toc-item-num">0.6 </span>Bootstrap regions file from including non-overlapping sites</a></div><div class="lev2 toc-item"><a href="#quick-tests" data-toc-modified-id="quick-tests-07"><span class="toc-item-num">0.7 </span>quick tests</a></div>
>In the bootstrap, you divide your sequence data into regions that can (ideally) be considered independent. Then you resample from those regions and generate new frequency spectra, using all the SNPs from each sampled region.
>Have you run any power tests? Running fits on simulated data from a plausible demographic history will give you insight as to whether it's even possible to reconstruct the history with the sample size you have.
In principle, I could simulate data sets under a RSC model with `ms` and see whether I can infer a Ti > 0.
>When doing the non-parametric bootstrapping, you want to bootstrap over regions of the genome, not just SNPs. This is because we want our resampling to capture the correlati ons between the SNPs caused by linkage. So instead of resampling from the SNPs, you'd resample from regions you've sequenced. For example, you could break the genome up into 1 Mb chunks and resample over those. The exact region breakdown isn't critical, as long as they are large compared to the typical scale of LD in your organism.
>We typically run several optimizations on each bootstrap data set, to help ensure we find the true best fit. (Often we run optimizations until the best-3 results are all within some delta of each other.)
>if your bootstraps aren't normally distributed, it's better to report confidence intervals as quantiles, e.g. 2.5-97.5%. You can also try a log-transform.
>By default dadi masks entries for which it is having computational problems, and this can cause LLs too look too good.
I need to look out for this. dadi should emit a warning when it does this.
## start
Step1: The sites file to use is ../ParEry.noSEgt2.nogtQ99Cov.noDUST.3.15.noTGCAGG.ANGSD_combinedNegFisFiltered.noGtQ99GlobalCov.sorted.sites.
Step2: The sites file needs to be sorted on column 1 (contig ids) for indexing. Lexicographical sorting seems to be enough, but I like to have the contigs sorted numerically by id. Therefore the fancy key function.
Step3: Since the sites file is 28Mb large, I cannot create too many of them at one time without using up a lot of storage. I will therefore try to create them as they are needed for SAF calculation and then erase them again to free up storage.
Step4: This only takes 6 minutes to finish.
Step5: Practically the same number of SNP's as in the bootstrapped SFS! That's not a good sign.
Step6: The bootstrap SFS is practically identical to the data SFS ?!
So the sites function to angsd or realSFS cannot be used for bootstrapping (see angsd issue #81).
However, since the contigs are the independent units I want to resample over, it may be possible to use a bootstrapped regions file.
Bootstrap regions file
Step7: I have run angsd with GNU parallel on the split regions files and the data for ERY, then merged the SAF files with realSFS cat. Printing the merged SAF file with realSFS print then emits the following error message
Step8: Now let's introduce a split about every 10 contigs.
Step9: This looks good. No repetitions of contigs are spread over splits.
Step10: That is plenty of file names to choose from.
Step11: This seems to do the right thing.
Step12: That looks good
Step13: This looks really good. I am convinced that this bootstrapping works!
Now I need to create an programme that does this over and over again.
Step14: estimate SAF's
Step15: This stops with an error. Apparently, finding the overlap in sites between two bootstrapped SAF files is not straightforward. See ANGSD issue #86.
read in a regions file containing all contigs
bootstrap those contigs
turn bootstrapped contigs array into a Counter dict
clean split_rf and SAF/ERY and SAF/PAR directory
write out split rf files
run angsd on split rf files in parallel for ERY and for PAR
concatenate split saf files for ERY and PAR
estimate 1D SFS
estimate 2D SFS
Get intersection of sites between ERY and PAR
I would like to create a sites file that only contains sites for which there are at least 9 individuals in each population with read data. I have previously created SAF files for each population including only sites with read data from at least 9 individuals. I have extracted those sites from the SAF files. While doing that I also sorted on contig number, then on position within contig. This will be required by the following algorithm for finding the intersection between these two sites files.
Step16: That seems to work correctly.
Step17: The unfolded 2D SFS estimated with these two SAF files and realSFS contains 1.13 million sites (see line 1449 in assembly.sh), summing over the SFS. So this seems to have worked correctly.
Another way to get to the overlapping sites is directly from the samtools depth file. See line 1320 in assembly.sh for the command line that created a depth file for the final filtered sites that I used for ANGSD analysis.
Counting sites with at least 9 individuals with read data in ERY and PAR in the depth file confirms that the number of overlapping sites must be around 1.13 million (see assembly.sh, line 2541 onwards). However, the numbers counted from the depth file are slightly higher than the number of sites in the SAF files, probably due to some additional filtering via the angsd -dosaf commands (see line 1426 onwards in assembly.sh). It really can only be the mapping quality filter. Note that the site coverages in the depth file were from reads with MQ at least 5. It could be that -Q 5 in the samtools depth command means >=5, whereas minMapQ 5 for ANGSD means >5.
Step18: It is this file
Step19: I would have expected these 1D SFS to look more like the marginal spectra from the 2D spectrum (see 05_2D_models.ipynb). For the estimation of these SFS's, I have run realSFS without the accelerated mode and specified convergence parameters that allowed it to find a unique optimum (as I observed with previous 1D SFS from also non-overlapping sites). The 2D SFS I had estimated with the accelerated algorithm (see line 1439 in assembly.sh). So maybe it is not fully converged.
Step20: This is the same number of sites as in the 2D SFS.
Step21: The marginal spectrum for ERY had 31,162 segregating sites.
Step22: The marginal spectrum for PAR had 41,419 segregating sites.
Step23: The $\pi_{site}$ for ERY from the marginal spectrum was 0.006530.
Step24: The $\pi_{site}$ for PAR from the marginal spectrum was 0.007313.
I have estimated a 2D SFS from the SAF files created with the overlapping.sites file above (see line 2622 in assembly.sh)
Step25: To estimate this 2D SFS, I (inadvertently) ran realSFS specifying the PAR SAF file before the ERY SAF file. So the axis labelling needs to be switched or the matrix transposed.
Step26: I think it would be good to plot the residuals between this and my previous 2D SFS, that I estimated without exhaustive search and used for $F_{ST}$ estimation as well as all 2D model fitting so far.
I have previously estimated a 2D SFS from SAF files that contained all sites with at least 9 individuals with read data in the population. realSFS had automatically determined the intersection of sites between ERY and PAR when estimating the 2D SFS. I have estimated this previous 2D SFS without exhaustive optimisation.
Step27: Apparently, there are large absolute differences in the [0, 1] and [1, 0] frequency classes as might be expected, since these have the highest expected count. The new 2D SFS (with exhaustive optimisation) has many more SNP's in those two frequency classes.
Step28: The new 2D SFS seems to have fewer middle and high frequency SNP's in PAR that are absent from ERY (lowest row) and more low frequency variants, shared and unshared (lower left corner) than the previous 2D SFS.
Step29: The marginal 1D spectra from the 2D spectrum look very similar to the directly estimated 1D SFS's. This is as expected, since both are estimated from the same sites
Step30: These are small residuals.
Step31: Unsurprisingly, the marginal spectra also look very similar to the marginal spectra taken from the 2D SFS optimised without exhaustive search. So, the difference between the spectra estimated from full SAF files and the spectra estimated from fully overlapping SAF files is not due to differences in the degree of optimisation of the SFS.
Step32: All three 2D spectra contain the same number of sites, indicating that they were indeed estimated from the same sites. Then why are the 2D spectra so different if estimated with SAF files containing only overlapping sites or with SAF files containing also non-overlapping sites. This does not make sense to me.
Bootstrap regions file from only overlapping sites
read in a regions file containing all contigs
bootstrap those contigs
turn bootstrapped contigs array into a Counter dict
clean split_rf and SAF/ERY and SAF/PAR directory
write out split rf files
run angsd on split rf files in parallel for ERY and for PAR
concatenate split saf files for ERY and PAR
estimate 1D SFS
estimate 2D SFS
The regions file is really small. So I am first going to create 200 bootstrapped regions files.
Then I will do the SAF estimation for these bootstrapped regions files. The SAF files are about 100MB large. So keeping them will require several giga bytes of storage, but I have that on /data3, where there is currently 1.7TB storage available.
Finally, I am going to estimate 1D SFS from these SAF files.
bootstrap regions file
Step34: Now, let's redo this 199 times.
Step35: estimate SAF files
I need to read in the bootstrapped regions files again and split them for parallisation of SAF creation, but in a way that allows concatenation of split SAF files. This means repeated contigs must not be spread over split regions files. Otherwise realSFS cat throws an error message.
Step36: I would like to extract the bootstrap index from the regions file name.
Step38: Clear the directory that takes split regions files, to receive new one
Step39: Estimate SAF files in parallel
Step40: Concatenate split SAF files
Step41: Note that I need to give the concatenated SAF file the index of the bootstrap repetition.
Step42: I think it would be best to put the steps of creating SAF files into a separate Python script to run in the background. I have put the code into the script estimate_SAFs.py.
Bootstrap regions file from including non-overlapping sites
Step44: I am going to bootstrap all.rf.
Step45: quick tests | Python Code:
# which *sites
% ll ../*sites
Explanation: Table of Contents
<p><div class="lev2 toc-item"><a href="#start" data-toc-modified-id="start-01"><span class="toc-item-num">0.1 </span>start</a></div><div class="lev2 toc-item"><a href="#Bootstrap-regions-file" data-toc-modified-id="Bootstrap-regions-file-02"><span class="toc-item-num">0.2 </span>Bootstrap regions file</a></div><div class="lev3 toc-item"><a href="#estimate-SAF's" data-toc-modified-id="estimate-SAF's-021"><span class="toc-item-num">0.2.1 </span>estimate SAF's</a></div><div class="lev2 toc-item"><a href="#Get-intersection-of-sites-between-ERY-and-PAR" data-toc-modified-id="Get-intersection-of-sites-between-ERY-and-PAR-03"><span class="toc-item-num">0.3 </span>Get intersection of sites between ERY and PAR</a></div><div class="lev2 toc-item"><a href="#plot-SFS-from-only-overlapping-sites" data-toc-modified-id="plot-SFS-from-only-overlapping-sites-04"><span class="toc-item-num">0.4 </span>plot SFS from only overlapping sites</a></div><div class="lev2 toc-item"><a href="#Bootstrap-regions-file-from-only-overlapping-sites" data-toc-modified-id="Bootstrap-regions-file-from-only-overlapping-sites-05"><span class="toc-item-num">0.5 </span>Bootstrap regions file from only overlapping sites</a></div><div class="lev3 toc-item"><a href="#bootstrap-regions-file" data-toc-modified-id="bootstrap-regions-file-051"><span class="toc-item-num">0.5.1 </span>bootstrap regions file</a></div><div class="lev3 toc-item"><a href="#estimate-SAF-files" data-toc-modified-id="estimate-SAF-files-052"><span class="toc-item-num">0.5.2 </span>estimate SAF files</a></div><div class="lev2 toc-item"><a href="#Bootstrap-regions-file-from-including-non-overlapping-sites" data-toc-modified-id="Bootstrap-regions-file-from-including-non-overlapping-sites-06"><span class="toc-item-num">0.6 </span>Bootstrap regions file from including non-overlapping sites</a></div><div class="lev2 toc-item"><a href="#quick-tests" data-toc-modified-id="quick-tests-07"><span class="toc-item-num">0.7 </span>quick tests</a></div>
>In the bootstrap, you divide your sequence data into regions that can (ideally) be considered independent. Then you resample from those regions and generate new frequency spectra, using all the SNPs from each sampled region.
>Have you run any power tests? Running fits on simulated data from a plausible demographic history will give you insight as to whether it's even possible to reconstruct the history with the sample size you have.
In principle, I could simulate data sets under a RSC model with `ms` and see whether I can infer a Ti > 0.
>When doing the non-parametric bootstrapping, you want to bootstrap over regions of the genome, not just SNPs. This is because we want our resampling to capture the correlati ons between the SNPs caused by linkage. So instead of resampling from the SNPs, you'd resample from regions you've sequenced. For example, you could break the genome up into 1 Mb chunks and resample over those. The exact region breakdown isn't critical, as long as they are large compared to the typical scale of LD in your organism.
>We typically run several optimizations on each bootstrap data set, to help ensure we find the true best fit. (Often we run optimizations until the best-3 results are all within some delta of each other.)
>if your bootstraps aren't normally distributed, it's better to report confidence intervals as quantiles, e.g. 2.5-97.5%. You can also try a log-transform.
>By default dadi masks entries for which it is having computational problems, and this can cause LLs too look too good.
I need to look out for this. dadi should emit a warning when it does this.
## start
End of explanation
from collections import defaultdict
# open sites file and read into dictionary
# contigs as keys, with sites as values collected in array
SITES = defaultdict(list)
with open("../ParEry.noSEgt2.nogtQ99Cov.noDUST.3.15.noTGCAGG.ANGSD_combinedNegFisFiltered.noGtQ99GlobalCov.sorted.sites") as sites_file:
for line in sites_file:
contig, site = line.strip().split()
SITES[contig].append(site)
print SITES['Contig_16']
import numpy as np
# efficient bootstrapping of keys with numpy
# np.random.choice
n_contigs = len(SITES.keys())
boot_contigs = np.random.choice(SITES.keys(), size=n_contigs, replace=True)
boot_contigs[:10]
print n_contigs
print len(boot_contigs)
# print the number of different contigs in the bootstrap resample
print len(set(boot_contigs))
i=0
for contig in sorted(boot_contigs):
i+=1
if not i> 10:
print contig
i=0
for contig in sorted(boot_contigs, key=lambda x: int(x.replace("Contig_", ""))):
i+=1
if not i> 10:
print contig
Explanation: The sites file to use is ../ParEry.noSEgt2.nogtQ99Cov.noDUST.3.15.noTGCAGG.ANGSD_combinedNegFisFiltered.noGtQ99GlobalCov.sorted.sites.
End of explanation
# write out bootstrapped *sites file
with open("0_boot.sites", "w") as out:
for contig in sorted(boot_contigs, key=lambda x: int(x.replace("Contig_", ""))):
for site in range(len(SITES[contig])):
out.write(contig + "\t" + SITES[contig][site] + "\n")
Explanation: The sites file needs to be sorted on column 1 (contig ids) for indexing. Lexicographical sorting seems to be enough, but I like to have the contigs sorted numerically by id. Therefore the fancy key function.
End of explanation
import subprocess32 as sp
# index sites file
sp.call("angsd sites index 0_boot.sites 2>/dev/null", shell=True)
# create regions file
sp.call("cut -f 1 0_boot.sites | uniq > 0_boot.rf", shell=True)
cmd = "angsd -bam {0}.slim.bamfile.list -ref Big_Data_ref.fa -anc Big_Data_ref.fa -out SAF/{0}/{0}.unfolded.{1} -fold 0 \
-sites {1}.sites -rf {1}.rf -only_proper_pairs 0 -baq 1 -minMapQ 5 -minInd 9 -GL 1 -doSaf 1 -nThreads 1 2>/dev/null"
for POP in ['ERY', 'PAR']:
print cmd.format(POP, "0_boot")
# create SAF files for ERY and PAR, for several bootstraps at the same time
running = []
cmd = "angsd -bam {0}.slim.bamfile.list -ref Big_Data_ref.fa -anc Big_Data_ref.fa -out SAF/{0}/{0}.unfolded.{1} -fold 0 \
-sites {1}.sites -rf {1}.rf -only_proper_pairs 0 -baq 1 -minMapQ 5 -minInd 9 -GL 1 -doSaf 1 -nThreads 1 2>/dev/null"
for POP in ['ERY', 'PAR']:
#print cmd % (POP, "0_boot.sites", "0_boot.rf")
p = sp.Popen(cmd.format(POP, "0_boot"), shell=True)
running.append(p)
Explanation: Since the sites file is 28Mb large, I cannot create too many of them at one time without using up a lot of storage. I will therefore try to create them as they are needed for SAF calculation and then erase them again to free up storage.
End of explanation
# estimate 2D unfolded SFS with realSFS allowing enough iterations to reach convergence, one bootstrap at a time
cmd = "realSFS -P 12 -maxIter 50000 -tole 1e-6 -m 0 SAF/ERY/ERY.unfolded.{}.saf.idx SAF/PAR/PAR.unfolded.{}.saf.idx 2>/dev/null >SFS/{}.2dsfs"
# clean up sites file, regions file, split regions files and SAF files
% ll SFS
import numpy
import sys
sys.path.insert(0, '/home/claudius/Downloads/dadi')
import dadi
boot_2dsfs = dadi.Spectrum.from_file('SFS/0_boot.2dsfs.dadi')
boot_2dsfs.sample_sizes
boot_2dsfs.pop_ids = ['ery', 'par']
boot_2dsfs.S()
%matplotlib inline
import pylab
pylab.rcParams['font.size'] = 14.0
pylab.rcParams['figure.figsize'] = [12.0, 10.0]
dadi.Plotting.plot_single_2d_sfs(boot_2dsfs, vmin=1, cmap=pylab.cm.jet)
!pwd
% ll ../../DADI/dadiExercises/
sfs2d = dadi.Spectrum.from_file('../../DADI/dadiExercises/EryPar.unfolded.2dsfs.dadi_format')
sfs2d.sample_sizes
sfs2d.pop_ids = ['ery', 'par']
sfs2d.S()
Explanation: This only takes 6 minutes to finish.
End of explanation
(sfs2d - boot_2dsfs).sum()
Explanation: Practically the same number of SNP's as in the bootstrapped SFS! That's not a good sign.
End of explanation
# write out bootstrapped *rf file
with open("0_boot_regions.rf", "w") as out:
for contig in sorted(boot_contigs, key=lambda x: int(x.replace("Contig_", ""))):
out.write(contig + "\n")
% ll
# split regions file
sp.call("split -l 500 0_boot_regions.rf SPLIT_RF/", shell=True)
% ll SAF
Explanation: The bootstrap SFS is practically identical to the data SFS ?!
So the sites function to angsd or realSFS cannot be used for bootstrapping (see angsd issue #81).
However, since the contigs are the independent units I want to resample over, it may be possible to use a bootstrapped regions file.
Bootstrap regions file
End of explanation
from collections import Counter
# turn array of contigs into a hash with counts
boot_contigs_dict = Counter(boot_contigs)
i=0
for k,v in boot_contigs_dict.items():
print k, v
i+=1
if i > 10:
break
len(boot_contigs_dict.keys())
i=0
for k,v in sorted(boot_contigs_dict.items(), key=lambda x: int(x[0].replace("Contig_", ""))):
for _ in range(v):
print k
i+=1
if i > 10:
break
Explanation: I have run angsd with GNU parallel on the split regions files and the data for ERY, then merged the SAF files with realSFS cat. Printing the merged SAF file with realSFS print then emits the following error message:
Problem with chr: Contig_20977, key already exists, saffile needs to be sorted. (sort your -rf that you used for input)
So it looks as though realSFS is really picky about contigs occurring more than once in the SAF file, which precludes bootstrapping.
http://www.popgen.dk/angsd/index.php/RealSFS
./realSFS cat
-> This will cat together .saf files from angsd
-> regions has to be disjoint between saf files. This WONT be checked (alot) !
-> This has only been tested on safs for different chrs !
I am going to try and create SAF files which do not overlap in the contigs that they contain. For that I need to split the regions file in a way that repeated contig names (they are sorted) do not end up in different split region files.
End of explanation
i=0
c = 0
for k,v in sorted(boot_contigs_dict.items(), key=lambda x: int(x[0].replace("Contig_", ""))):
c+=v
if c > 10:
print "***************\n"
c=v
for _ in range(v):
print k
i+=1
if i > 20:
break
Explanation: Now let's introduce a split about every 10 contigs.
End of explanation
import string
string.letters
from itertools import product
for n in product(string.lowercase, repeat=2):
print n[0] + n[1] + " ",
len([n for n in product(string.lowercase, repeat=2)])
Explanation: This looks good. No repetitions of contigs are spread over splits.
End of explanation
# write out bootstrapped *rf file
import string
c = 0 # initialise contig count
# create iterator over filenames
fnames = product(string.lowercase, repeat=2)
# get next file name from iterator
fn = fnames.next()
# open new file for writing and get filehandle
out = open("split_rf/" + fn[0] + fn[1], "w")
# iterate over Counter dict of bootstrapped contigs, key=contig name, value=count (rep)
for contig,rep in sorted(boot_contigs_dict.items(), key=lambda x: int(x[0].replace("Contig_", ""))):
c+=rep
if c > 500: # write up to 500 contigs to each split rf file
out.close() # close current rf file
fn = fnames.next() # get next file name from iterator
out = open("split_rf/" + fn[0] + fn[1], "w") # open new rf file for writing
c = rep
for _ in range(rep): # write contig name to rf file as often as it occurs in the bootstrap resample
out.write(contig + "\n")
Explanation: That is plenty of file names to choose from.
End of explanation
# read in bootstrapped spectrum
fs_ery_boot = dadi.Spectrum.from_file("SAF/with_nonoverlap_boot.rf/ERY/ERY.unfolded.sfs.boot.dadi")
fs_ery_boot
% ll ../SFS/ERY/
# read in original spectrum
fs_ery = dadi.Spectrum.from_file("../SFS/ERY/ERY.unfolded.sfs.dadi")
fs_ery
pylab.plot(fs_ery.fold(), "ro-", label="original")
pylab.plot(fs_ery_boot.fold(), 'bs-', label="bootstrapped")
pylab.legend()
# get number of segregating sites for original spectrum
fs_ery.S()
# get number of segregating sites for bootstrapped spectrum
fs_ery_boot.S()
# get total number of sites in the original spectrum
fs_ery.data.sum()
# get total number of sites in the bootstrapped spectrum
fs_ery_boot.data.sum()
Explanation: This seems to do the right thing.
End of explanation
% ll
# open sites file and read into dictionary
# contigs as keys, with sites as values collected in array
SITES = defaultdict(list)
with open("all.sites") as sites_file:
for line in sites_file:
contig, site = line.strip().split()
SITES[contig].append(site)
# efficient bootstrapping of keys with numpy
# np.random.choice
n_contigs = len(SITES.keys())
boot_contigs = np.random.choice(SITES.keys(), size=n_contigs, replace=True)
# turn array of contigs into a hash with counts
boot_contigs_dict = Counter(boot_contigs)
len(boot_contigs_dict)
# write out bootstrapped *rf file
import string
c = 0 # initialise contig count
# create iterator over filenames
fnames = product(string.lowercase, repeat=2)
# get next file name from iterator
fn = fnames.next()
# open new file for writing and get filehandle
out = open("split_rf/" + fn[0] + fn[1], "w")
# iterate over Counter dict of bootstrapped contigs, key=contig name, value=count (rep)
for contig,rep in sorted(boot_contigs_dict.items(), key=lambda x: int(x[0].replace("Contig_", ""))):
c+=rep
if c > 500: # write up to 500 contigs to each split rf file
out.close() # close current rf file
fn = fnames.next() # get next file name from iterator
out = open("split_rf/" + fn[0] + fn[1], "w") # open new rf file for writing
c = rep
for _ in range(rep): # write contig name to rf file as often as it occurs in the bootstrap resample
out.write(contig + "\n")
boot_contigs_dict['Contig_10071']
fs_ery_boot_1 = dadi.Spectrum.from_file("SAF/with_nonoverlap_boot.rf/ERY/ERY.unfolded.sfs.boot_1.dadi")
pylab.plot(fs_ery.fold(), "ro-", label="original")
pylab.plot(fs_ery_boot_1.fold(), 'bs-', label="bootstrapped")
pylab.legend()
fs_ery_boot_1.data.sum()
Explanation: That looks good: similar but not almost identical values.
This really does look like a proper bootstrap!
I need to generate a second bootstrapped SFS to convince myself that this is actually working.
End of explanation
import numpy as np
# open regions file and read into numpy array
REGIONS = []
with open("all.rf") as regions_file:
for line in regions_file:
contig = line.strip()
REGIONS.append(contig)
REGIONS[:10]
len(REGIONS)
# efficient bootstrapping of contigs with numpy
# np.random.choice
n_contigs = len(REGIONS)
boot_contigs = np.random.choice(REGIONS, size=n_contigs, replace=True)
from collections import Counter
boot_contigs_dict = Counter(boot_contigs)
len(boot_contigs_dict)
% ll
% ll split_rf/
import subprocess32 as sp
# remove split regions files from previous bootstrap
sp.call("rm -f split_rf/*", shell=True)
% ll split_rf/
% ll SAF/ERY
sp.call("rm -f SAF/ERY/*", shell=True)
sp.call("rm -f SAF/PAR/*", shell=True)
# write out bootstrapped *rf files
import string
from itertools import product
c = 0 # initialise contig count
# create iterator over filenames
fnames = product(string.lowercase, repeat=2)
# get next file name from iterator
fn = fnames.next()
# open new file for writing and get filehandle
out = open("split_rf/" + fn[0] + fn[1], "w")
# iterate over Counter dict of bootstrapped contigs, key=contig name, value=count (rep)
for contig,rep in sorted(boot_contigs_dict.items(), key=lambda x: int(x[0].replace("Contig_", ""))):
c+=rep
if c > 500: # write up to 500 contigs to each split rf file
out.close() # close current rf file
fn = fnames.next() # get next file name from iterator
out = open("split_rf/" + fn[0] + fn[1], "w") # open new rf file for writing
c = rep
for _ in range(rep): # write contig name to rf file as often as it occurs in the bootstrap resample
out.write(contig + "\n")
Explanation: This looks really good. I am convinced that this bootstrapping works!
Now I need to create an programme that does this over and over again.
End of explanation
cmd = 'ls split_rf/* | parallel -j 12 "angsd -bam PAR.slim.bamfile.list -ref Big_Data_ref.fa -anc Big_Data_ref.fa -out SAF/PAR/PAR.unfolded.{/} -fold 0 \
-sites all.sites -rf {} -only_proper_pairs 0 -baq 1 -minMapQ 5 -minInd 9 -GL 1 -doSaf 1 -nThreads 1 2>/dev/null"'
cmd
sp.call(cmd, shell=True)
cmd = cmd.replace("PAR", "ERY")
cmd
sp.call(cmd, shell=True)
cmd = "realSFS cat -outnames SAF/ERY/ERY.unfolded.merged SAF/ERY/*saf.idx 2>/dev/null"
cmd
sp.call(cmd, shell=True)
cmd = cmd.replace("ERY", "PAR")
sp.call(cmd, shell=True)
cmd = "realSFS SAF/ERY/ERY.unfolded.merged.saf.idx -P 20 2>/dev/null > SFS/1D/ERY/ERY.unfolded.{0:04d}.sfs".format(1)
cmd
p = sp.Popen(cmd, shell=True)
cmd = cmd.replace("ERY", "PAR")
cmd
p.poll()
p = sp.Popen(cmd, shell=True)
p.poll()
cmd = "realSFS SAF/ERY/ERY.unfolded.merged.saf.idx SAF/PAR/PAR.unfolded.merged.saf.idx -P 20 2>/dev/null > SFS/2D/EryPar.unfolded.{0:04d}.sfs2d".format(1)
cmd
% ll SAF/ERY/ERY.unfolded.merged.saf.idx SAF/PAR/PAR.unfolded.merged.saf.idx
sp.call(cmd, shell=True)
Explanation: estimate SAF's
End of explanation
% ll ../SAFs/ERY/*sites
% ll ../SAFs/PAR/*sites
ery_sites = open("../SAFs/ERY/ERY.sites", "r")
par_sites = open("../SAFs/PAR/PAR.sites", "r")
from itertools import izip
i=0
for ery,par in izip(ery_sites, par_sites):
i+=1
print ery.rstrip(), par.rstrip()
if i>10: break
ery_sites.seek(0)
par_sites.seek(0)
i=0
ery_forward = True
par_forward = True
while 1:
# stop loop when reaching end of file
if ery_forward:
try:
ery = ery_sites.next()
except:
break
if par_forward:
try:
par = par_sites.next()
except:
break
# extract contig ID and position within contig
e = ery.replace("Contig_", "").rstrip().split()
p = par.replace("Contig_", "").rstrip().split()
# if contig ID of ery lower than of par
if int(e[0]) < int(p[0]):
ery_forward = True
par_forward = False
elif int(e[0]) > int(p[0]):
ery_forward = False
par_forward = True
# if position within contig of ery lower than of par
elif int(e[1]) < int(p[1]):
ery_forward = True
par_forward = False
elif int(e[1]) > int(p[1]):
ery_forward = False
par_forward = True
else:
print ery,
ery_forward = True
par_forward = True
i+=1
if i > 200: break
Explanation: This stops with an error. Apparently, finding the overlap in sites between two bootstrapped SAF files is not straightforward. See ANGSD issue #86.
read in a regions file containing all contigs
bootstrap those contigs
turn bootstrapped contigs array into a Counter dict
clean split_rf and SAF/ERY and SAF/PAR directory
write out split rf files
run angsd on split rf files in parallel for ERY and for PAR
concatenate split saf files for ERY and PAR
estimate 1D SFS
estimate 2D SFS
Get intersection of sites between ERY and PAR
I would like to create a sites file that only contains sites for which there are at least 9 individuals in each population with read data. I have previously created SAF files for each population including only sites with read data from at least 9 individuals. I have extracted those sites from the SAF files. While doing that I also sorted on contig number, then on position within contig. This will be required by the following algorithm for finding the intersection between these two sites files.
End of explanation
def printIntersection(fh_1, fh_2, out_fh):
ery_forward = True
par_forward = True
while 1:
# stop loop when reaching end of file
if ery_forward:
try:
ery = fh_1.next()
except:
break
if par_forward:
try:
par = fh_2.next()
except:
break
# extract contig ID and position within contig
e = ery.replace("Contig_", "").rstrip().split()
p = par.replace("Contig_", "").rstrip().split()
# if contig ID of ery lower than of par
if int(e[0]) < int(p[0]):
ery_forward = True
par_forward = False
elif int(e[0]) > int(p[0]):
ery_forward = False
par_forward = True
# if position within contig of ery lower than in par
elif int(e[1]) < int(p[1]):
ery_forward = True
par_forward = False
elif int(e[1]) > int(p[1]):
ery_forward = False
par_forward = True
else:
out_fh.write(ery)
ery_forward = True
par_forward = True
?int
ery_sites = open("../SAFs/ERY/ERY.sites", "r")
par_sites = open("../SAFs/PAR/PAR.sites", "r")
ery_sites.seek(0)
par_sites.seek(0)
out = open("from_SAFs_minInd9_overlapping.sites", "w")
printIntersection(ery_sites, par_sites, out)
% ll
! wc -l from_SAFs_minInd9_overlapping.sites
Explanation: That seems to work correctly.
End of explanation
% ll ../Quality_Control/
Explanation: The unfolded 2D SFS estimated with these two SAF files and realSFS contains 1.13 million sites (see line 1449 in assembly.sh), summing over the SFS. So this seems to have worked correctly.
Another way to get to the overlapping sites is directly from the samtools depth file. See line 1320 in assembly.sh for the command line that created a depth file for the final filtered sites that I used for ANGSD analysis.
Counting sites with at least 9 individuals with read data in ERY and PAR in the depth file confirms that the number of overlapping sites must be around 1.13 million (see assembly.sh, line 2541 onwards). However, the numbers counted from the depth file are slightly higher than the number of sites in the SAF files, probably due to some additional filtering via the angsd -dosaf commands (see line 1426 onwards in assembly.sh). It really can only be the mapping quality filter. Note that the site coverages in the depth file were from reads with MQ at least 5. It could be that -Q 5 in the samtools depth command means >=5, whereas minMapQ 5 for ANGSD means >5.
End of explanation
import numpy as np
import sys
sys.path.insert(0, '/home/claudius/Downloads/dadi')
import dadi
% ll minInd9_overlapping/SFS/ERY
fs_ery = dadi.Spectrum.from_file("minInd9_overlapping/SFS/original/ERY/ERY.unfolded.sfs.dadi")
fs_ery.pop_ids = ['ery']
fs_par = dadi.Spectrum.from_file("minInd9_overlapping/SFS/original/PAR/PAR.unfolded.sfs.dadi")
fs_par.pop_ids = ['par']
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = [6, 5]
plt.rcParams['font.size'] = 10
Explanation: It is this file: ParEry.noSEgt2.nogtQ99Cov.noDUST.3.15.noTGCAGG.ANGSD_combinedNegFisFiltered.noGtQ99GlobalCov.sorted.depths.gz.
The sites in this depth file have at least 15 individuals with each at least 3x coverage. The first two columns in this file are contig ID and position. The remaining 36 columns contain the coverage for each individual. I believe columns 3 to 20 belong to ERY individuals and columns 21 to 38 to PAR individuals. Is used gawk commands to extract those sites (see line 2544 onwards in assembly.sh). The number of overlapping sites counted from the depth file is 1,143,453. So slightly higher than the overlap between the two SAF files. I am therefore going to use the sites file created from the overlap between the SAF files.
plot SFS from only overlapping sites
I have estimated 1D SFS for ERY and PAR using this sites file containing only overlapping sites. See assembly.sh, line 2576 onwards, for the details.
End of explanation
print fs_ery.data.sum()
print fs_par.data.sum()
Explanation: I would have expected these 1D SFS to look more like the marginal spectra from the 2D spectrum (see 05_2D_models.ipynb). For the estimation of these SFS's, I have run realSFS without the accelerated mode and specified convergence parameters that allowed it to find a unique optimum (as I observed with previous 1D SFS from also non-overlapping sites). The 2D SFS I had estimated with the accelerated algorithm (see line 1439 in assembly.sh). So maybe it is not fully converged.
End of explanation
fs_ery.S()
Explanation: This is the same number of sites as in the 2D SFS.
End of explanation
fs_par.S()
Explanation: The marginal spectrum for ERY had 31,162 segregating sites.
End of explanation
fs_ery.pi()/fs_ery.data.sum()
Explanation: The marginal spectrum for PAR had 41,419 segregating sites.
End of explanation
fs_par.pi()/fs_par.data.sum()
Explanation: The $\pi_{site}$ for ERY from the marginal spectrum was 0.006530.
End of explanation
# get 2D SFS estimated from SAF files containing only overlapping sites
sfs2d_unfolded = dadi.Spectrum.from_file("minInd9_overlapping/SFS/original/EryPar.unfolded.sfs.dadi")
sfs2d_unfolded.pop_ids = ['ery', 'par']
dadi.Plotting.plot_single_2d_sfs(sfs2d_unfolded, vmin=1, cmap='jet')
Explanation: The $\pi_{site}$ for PAR from the marginal spectrum was 0.007313.
I have estimated a 2D SFS from the SAF files created with the overlapping.sites file above (see line 2622 in assembly.sh): from_SAFs_minInd9_overlapping.sites. I have done an exhaustive optimisation which took almost 6 hours on all 24 virtual cores of huluvu.
End of explanation
sfs2d_unfolded.pop_ids = ['par', 'ery']
sfs2d = sfs2d_unfolded.fold()
dadi.Plotting.plot_single_2d_sfs(sfs2d, vmin=1, cmap='jet')
# transpose the matrix
sfs2d = dadi.Spectrum.transpose(sfs2d)
sfs2d.pop_ids.reverse()
dadi.Plotting.plot_single_2d_sfs(sfs2d, vmin=1, cmap='jet')
Explanation: To estimate this 2D SFS, I (inadvertently) ran realSFS specifying the PAR SAF file before the ERY SAF file. So the axis labelling needs to be switched or the matrix transposed.
End of explanation
# get previous 2D SFS
prev_sfs2d_unfolded = dadi.Spectrum.from_file("../../DADI/dadiExercises/EryPar.unfolded.2dsfs.dadi_format")
prev_sfs2d_unfolded.pop_ids = ['ery', 'par']
prev_sfs2d = prev_sfs2d_unfolded.fold()
# get residuals between previous and new 2D SFS
resid = prev_sfs2d - sfs2d
# plot absolute residuals
plt.figure(figsize=(6,5))
dadi.Plotting.plot_2d_resid(resid)
Explanation: I think it would be good to plot the residuals between this and my previous 2D SFS, that I estimated without exhaustive search and used for $F_{ST}$ estimation as well as all 2D model fitting so far.
I have previously estimated a 2D SFS from SAF files that contained all sites with at least 9 individuals with read data in the population. realSFS had automatically determined the intersection of sites between ERY and PAR when estimating the 2D SFS. I have estimated this previous 2D SFS without exhaustive optimisation.
End of explanation
# plot Poisson residuals, saturating at 20 standard deviations in the heatmap of residuals
dadi.Plotting.plot_2d_comp_Poisson(data=prev_sfs2d, model=sfs2d, vmin=1, resid_range=20, title=['previous 2D SFS', 'new 2D SFS'])
Explanation: Apparently, there are large absolute differences in the [0, 1] and [1, 0] frequency classes as might be expected, since these have the highest expected count. The new 2D SFS (with exhaustive optimisation) has many more SNP's in those two frequency classes.
End of explanation
fs_ery_m = sfs2d.marginalize([1])
fs_par_m = sfs2d.marginalize([0])
max(fs_ery_m.data[1:]), max(fs_ery.fold().data[1:]), max(fs_par_m.data[1:]), max(fs_par.fold().data[1:])
plt.figure(figsize=(14, 7))
m = max(fs_ery_m.data[1:]), max(fs_ery.fold().data[1:]), max(fs_par_m.data[1:]), max(fs_par.fold().data[1:])
plt.subplot(121)
plt.plot(fs_ery_m, 'ro-', label='ery')
plt.plot(fs_par_m, 'g^-', label = 'par')
plt.ylim(0, max(m)*1.1)
plt.grid()
plt.legend()
plt.xlabel('minor allele frequency')
plt.ylabel('SNP count')
plt.title('marginal 1D SFS')
plt.subplot(122)
plt.plot(fs_ery.fold(), 'ro-', label='ery')
plt.plot(fs_par.fold(), 'g^-', label = 'par')
plt.ylim(0, max(m)*1.1)
plt.grid()
plt.legend()
plt.xlabel('minor allele frequency')
plt.ylabel('SNP count')
plt.title('1D SFS')
Explanation: The new 2D SFS seems to have fewer middle and high frequency SNP's in PAR that are absent from ERY (lowest row) and more low frequency variants, shared and unshared (lower left corner) than the previous 2D SFS.
End of explanation
# get re-stimated 2D SFS from non-fully-overlapping SAF files
prev_sfs2d_unfolded_exhaust = dadi.Spectrum.from_file("../FST/EryPar.unfolded.exhaustive.2dsfs.dadi")
prev_sfs2d_unfolded_exhaust.pop_ids = ['ery', 'par']
prev_sfs2d_exhaust = prev_sfs2d_unfolded_exhaust.fold()
# get residuals betwee non-exhaust and exhaust 2D SFS,
# both estimated from non-fully-overlapping SAF files
resid = prev_sfs2d - prev_sfs2d_exhaust
# plot absolute residuals
plt.figure(figsize=(6,5))
dadi.Plotting.plot_2d_resid(resid)
Explanation: The marginal 1D spectra from the 2D spectrum look very similar to the directly estimated 1D SFS's. This is as expected, since both are estimated from the same sites: those that have at least 9 individuals with read data in both ERY and PAR.
I have now re-estimated the 2D SFS from SAF files containing also non-overlapping sites with exhaustive search parameters (see line 2629 in assembly.sh).
End of explanation
# plot Poisson residuals, saturating at 20 standard deviations in the heatmap of residuals
dadi.Plotting.plot_2d_comp_Poisson(data=prev_sfs2d, model=prev_sfs2d_exhaust, vmin=1, \
resid_range=20, title=['non-exhaustive', 'exhaustive'])
fs_ery = prev_sfs2d_exhaust.marginalize([1])
fs_par = prev_sfs2d_exhaust.marginalize([0])
plt.figure(figsize=(6,5))
plt.plot(fs_ery, 'ro-', label='ery')
plt.plot(fs_par, 'g^-', label = 'par')
plt.grid()
plt.legend()
plt.xlabel('minor allele frequency')
plt.ylabel('SNP count')
plt.title('marginal 1D SFS')
Explanation: These are small residuals.
End of explanation
# total number of sites in previous non-exhaust 2D SFS
prev_sfs2d.data.sum()
# total number of sites in previous exhaust 2D SFS
prev_sfs2d_exhaust.data.sum()
# notal number of sites in new exhaust 2D SFS (from fully overlapping SAF files)
sfs2d.data.sum()
Explanation: Unsurprisingly, the marginal spectra also look very similar to the marginal spectra taken from the 2D SFS optimised without exhaustive search. So, the difference between the spectra estimated from full SAF files and the spectra estimated from fully overlapping SAF files is not due to differences in the degree of optimisation of the SFS.
End of explanation
% ll *rf
regions = []
with open("from_SAFs_minInd9_overlapping.rf", "r") as rf:
for r in rf:
regions.append(r.rstrip())
regions[:10]
len(regions)
len(set(regions))
import numpy as np
# efficient bootstrapping of array with numpy
# np.random.choice
n_contigs = len(regions)
boot_contigs = np.random.choice(regions, size=n_contigs, replace=True)
len(boot_contigs)
len(set(boot_contigs))
# write out bootstrapped *regions file
with open("minInd9_overlapping/BOOT_RF/0_boot.rf", "w") as out:
for contig in sorted(boot_contigs, key=lambda x: int(x.replace("Contig_", ""))):
out.write(contig + "\n")
Explanation: All three 2D spectra contain the same number of sites, indicating that they were indeed estimated from the same sites. Then why are the 2D spectra so different if estimated with SAF files containing only overlapping sites or with SAF files containing also non-overlapping sites. This does not make sense to me.
Bootstrap regions file from only overlapping sites
read in a regions file containing all contigs
bootstrap those contigs
turn bootstrapped contigs array into a Counter dict
clean split_rf and SAF/ERY and SAF/PAR directory
write out split rf files
run angsd on split rf files in parallel for ERY and for PAR
concatenate split saf files for ERY and PAR
estimate 1D SFS
estimate 2D SFS
The regions file is really small. So I am first going to create 200 bootstrapped regions files.
Then I will do the SAF estimation for these bootstrapped regions files. The SAF files are about 100MB large. So keeping them will require several giga bytes of storage, but I have that on /data3, where there is currently 1.7TB storage available.
Finally, I am going to estimate 1D SFS from these SAF files.
bootstrap regions file
End of explanation
def bootstrapContigs(regions, index):
takes an array of contig ID's and an index for the bootstrap repetition
import numpy as np
# get number of contigs to resample
n_contigs = len(regions)
# resample contigs with replacement (bootstrap)
boot_contigs = np.random.choice(regions, size=n_contigs, replace=True)
# write out bootstrapped *regions file
with open("minInd9_overlapping/BOOT_RF/{:03d}_boot.rf".format(index), "w") as out:
for contig in sorted(boot_contigs, key=lambda x: int(x.replace("Contig_", ""))):
out.write(contig + "\n")
for index in range(1, 200):
bootstrapContigs(regions, index)
Explanation: Now, let's redo this 199 times.
End of explanation
from glob import glob
sorted(glob("minInd9_overlapping/BOOT_RF/*"))[:10]
Explanation: estimate SAF files
I need to read in the bootstrapped regions files again and split them for parallisation of SAF creation, but in a way that allows concatenation of split SAF files. This means repeated contigs must not be spread over split regions files. Otherwise realSFS cat throws an error message.
End of explanation
import re
p = re.compile(r'\d+')
for rf in sorted(glob("minInd9_overlapping/BOOT_RF/*"))[:20]:
#print rf
m = p.findall(rf)
print m[1]
# the same as above without a pre-compiled RE object
for rf in sorted(glob("minInd9_overlapping/BOOT_RF/*"))[:20]:
print re.findall(r'\d+', rf)[-1]
# read in one bootstrapped regions file
boot_contigs = []
with open("minInd9_overlapping/BOOT_RF/000_boot.rf", "r") as boot_rf:
for contig in boot_rf:
boot_contigs.append(contig.rstrip())
from collections import Counter
# turn array of contigs into a hash with counts
boot_contigs_dict = Counter(boot_contigs)
i=0
for contig,count in boot_contigs_dict.items():
print contig, "\t", count
i+=1
if i > 10: break
Explanation: I would like to extract the bootstrap index from the regions file name.
End of explanation
% ll split_rf/
import subprocess32 as sp
sp.call("rm -f split_rf/*", shell=True)
% ll split_rf/
import string
from itertools import product
# create iterator over filenames
fnames = product(string.lowercase, repeat=2)
def split_regions_file(boot_contigs_dict, fnames, size):
takes Counter dictionary of bootstrapped contigs
and an iterator over filenames to choose
writes out split regions files with repetitions of contigs
NOT spread over different split regions files
c = 0 # initialise contig count
# get next file name from iterator
fn = fnames.next()
# open new file for writing and get filehandle
out = open("split_rf/" + fn[0] + fn[1], "w")
# iterate over Counter dict of bootstrapped contigs, key=contig name, value=count (rep)
for contig,rep in sorted(boot_contigs_dict.items(), key=lambda x: int(x[0].replace("Contig_", ""))):
c+=rep
if c > size: # write up to 'size' contigs to each split rf file
out.close() # close current rf file
fn = fnames.next() # get next file name from iterator
out = open("split_rf/" + fn[0] + fn[1], "w") # open new rf file for writing
c = rep
for _ in range(rep): # write contig name to rf file as often as it occurs in the bootstrap resample
out.write(contig + "\n")
split_regions_file(boot_contigs_dict, fnames, 400)
! wc -l split_rf/*
Explanation: Clear the directory that takes split regions files, to receive new one:
End of explanation
cmd = 'ls split_rf/* | parallel -j 12 "angsd -bam PAR.slim.bamfile.list -ref Big_Data_ref.fa \
-anc Big_Data_ref.fa -out minInd9_overlapping/SAF/bootstrap/PAR/{/}.unfolded -fold 0 \
-sites from_SAFs_minInd9_overlapping.sites -rf {} -only_proper_pairs 0 -baq 1 -minMapQ 5 -minInd 9 -GL 1 -doSaf 1 -nThreads 1 2>/dev/null"'
cmd
sp.Popen(cmd, shell=True)
% ll minInd9_overlapping/SAF/bootstrap/PAR/
Explanation: Estimate SAF files in parallel:
End of explanation
index = '000'
cmd = "realSFS cat -outnames minInd9_overlapping/SAF/bootstrap/PAR/{}.unfolded minInd9_overlapping/SAF/bootstrap/PAR/*saf.idx 2>/dev/null".format(index)
cmd
Explanation: Concatenate split SAF files:
End of explanation
sp.call(cmd, shell=True)
# concatenated SAF file begins with "PAR"
# remove all split SAF files, they are not need anymore
sp.call("rm -f minInd9_overlapping/SAF/bootstrap/PAR/[a-z]*", shell=True)
% ll minInd9_overlapping/SAF/bootstrap/PAR/[0-9]*
% ll minInd9_overlapping/SAF/bootstrap/PAR/[!0-9]*
Explanation: Note that I need to give the concatenated SAF file the index of the bootstrap repetition.
End of explanation
% ll *rf
Explanation: I think it would be best to put the steps of creating SAF files into a separate Python script to run in the background. I have put the code into the script estimate_SAFs.py.
Bootstrap regions file from including non-overlapping sites
End of explanation
regions = []
with open("all.rf", "r") as rf:
for r in rf:
regions.append(r.rstrip())
len(regions)
len(set(regions))
import numpy as np
# efficient bootstrapping of array with numpy
# np.random.choice
n_contigs = len(regions)
boot_contigs = np.random.choice(regions, size=n_contigs, replace=True)
len(boot_contigs)
len(set(boot_contigs))
def bootstrapContigs(regions, index):
takes an array of contig ID's and an index for the bootstrap repetition
import numpy as np
# get number of contigs to resample
n_contigs = len(regions)
# resample contigs with replacement (bootstrap)
boot_contigs = np.random.choice(regions, size=n_contigs, replace=True)
# write out bootstrapped *regions file
with open("including_non-overlapping/BOOT_RF/{:03d}_boot.rf".format(index), "w") as out:
for contig in sorted(boot_contigs, key=lambda x: int(x.replace("Contig_", ""))):
out.write(contig + "\n")
for index in range(0, 200):
bootstrapContigs(regions, index)
Explanation: I am going to bootstrap all.rf.
End of explanation
a = ['par', 'ery']
a.reverse()
a
"{:03d}".format(50)
ery_sites.seek(0)
par_sites.seek(0)
ery = ery_sites.next()
par = par_sites.next()
e = ery.replace("Contig_", "").rstrip().split()
p = par.replace("Contig_", "").rstrip().split()
print e
print p
i = 0
while 1:
i+=1
print i
if i>9: break
s = 'abcdefg'
it = iter(s)
it
while 1:
try:
print it.next()
except:
break
str.replace?
str.strip?
print ery_sites.next()
print ery_sites.next()
ery_sites.seek(0)
print ery_sites.next()
s = 'abcdefg'
it = iter(s)
it
print it.next()
for l in it:
print l
it
arr = ['aa', 'bb']
"".join(arr)
str.join?
Explanation: quick tests
End of explanation |
7,434 | 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="#Summary" data-toc-modified-id="Summary-1"><span class="toc-item-num">1 </span>Summary</a></div><div class="lev1 toc-item"><a href="#Version-Control" data-toc-modified-id="Version-Control-2"><span class="toc-item-num">2 </span>Version Control</a></div><div class="lev1 toc-item"><a href="#Change-Log" data-toc-modified-id="Change-Log-3"><span class="toc-item-num">3 </span>Change Log</a></div><div class="lev1 toc-item"><a href="#Setup" data-toc-modified-id="Setup-4"><span class="toc-item-num">4 </span>Setup</a></div><div class="lev1 toc-item"><a href="#Login()" data-toc-modified-id="Login()-5"><span class="toc-item-num">5 </span>Login()</a></div><div class="lev2 toc-item"><a href="#Web-service-call" data-toc-modified-id="Web-service-call-51"><span class="toc-item-num">5.1 </span>Web service call</a></div><div class="lev3 toc-item"><a href="#Get-data" data-toc-modified-id="Get-data-511"><span class="toc-item-num">5.1.1 </span>Get data</a></div><div class="lev3 toc-item"><a href="#Data-inspection-(Login)" data-toc-modified-id="Data-inspection-(Login)-512"><span class="toc-item-num">5.1.2 </span>Data inspection (Login)</a></div><div class="lev2 toc-item"><a href="#Helper-function" data-toc-modified-id="Helper-function-52"><span class="toc-item-num">5.2 </span>Helper function</a></div><div class="lev3 toc-item"><a href="#Usage" data-toc-modified-id="Usage-521"><span class="toc-item-num">5.2.1 </span>Usage</a></div><div class="lev2 toc-item"><a href="#Client-function" data-toc-modified-id="Client-function-53"><span class="toc-item-num">5.3 </span>Client function</a></div>
# Summary
Part of the blog series related to making web service calls to Eoddata.com. Overview of the web service can be found [here](http
Step1: Change Log
Date Created
Step2: Login()
Web service call
Step3: Get data
Step4: Data inspection (Login)
Step5: Helper function
Step6: Usage
Step7: Client function | Python Code:
%run ../../code/version_check.py
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Summary" data-toc-modified-id="Summary-1"><span class="toc-item-num">1 </span>Summary</a></div><div class="lev1 toc-item"><a href="#Version-Control" data-toc-modified-id="Version-Control-2"><span class="toc-item-num">2 </span>Version Control</a></div><div class="lev1 toc-item"><a href="#Change-Log" data-toc-modified-id="Change-Log-3"><span class="toc-item-num">3 </span>Change Log</a></div><div class="lev1 toc-item"><a href="#Setup" data-toc-modified-id="Setup-4"><span class="toc-item-num">4 </span>Setup</a></div><div class="lev1 toc-item"><a href="#Login()" data-toc-modified-id="Login()-5"><span class="toc-item-num">5 </span>Login()</a></div><div class="lev2 toc-item"><a href="#Web-service-call" data-toc-modified-id="Web-service-call-51"><span class="toc-item-num">5.1 </span>Web service call</a></div><div class="lev3 toc-item"><a href="#Get-data" data-toc-modified-id="Get-data-511"><span class="toc-item-num">5.1.1 </span>Get data</a></div><div class="lev3 toc-item"><a href="#Data-inspection-(Login)" data-toc-modified-id="Data-inspection-(Login)-512"><span class="toc-item-num">5.1.2 </span>Data inspection (Login)</a></div><div class="lev2 toc-item"><a href="#Helper-function" data-toc-modified-id="Helper-function-52"><span class="toc-item-num">5.2 </span>Helper function</a></div><div class="lev3 toc-item"><a href="#Usage" data-toc-modified-id="Usage-521"><span class="toc-item-num">5.2.1 </span>Usage</a></div><div class="lev2 toc-item"><a href="#Client-function" data-toc-modified-id="Client-function-53"><span class="toc-item-num">5.3 </span>Client function</a></div>
# Summary
Part of the blog series related to making web service calls to Eoddata.com. Overview of the web service can be found [here](http://ws.eoddata.com/data.asmx).
* ** View the master post of this series to build a secure credentials file.** It is used in all posts related to this series.
* Download the [class definition file](https://adriantorrie.github.io/downloads/code/eoddata.py) for an easy to use client, which is demonstrated below
* This post covers the `Login` call: http://ws.eoddata.com/data.asmx?op=Login
# Version Control
End of explanation
%run ../../code/eoddata.py
from getpass import getpass
import requests as r
import xml.etree.cElementTree as etree
ws = 'http://ws.eoddata.com/data.asmx'
ns='http://ws.eoddata.com/Data'
session = r.Session()
username = getpass()
password = getpass()
Explanation: Change Log
Date Created: 2017-03-25
Date of Change Change Notes
-------------- ----------------------------------------------------------------
2017-03-25 Initial draft
Setup
End of explanation
call = 'Login'
url = '/'.join((ws, call))
payload = {'Username': username, 'Password': password}
response = session.get(url, params=payload, stream=True)
if response.status_code == 200:
root = etree.parse(response.raw).getroot()
Explanation: Login()
Web service call
End of explanation
token = root.get('Token')
token
Explanation: Get data
End of explanation
dir(root)
for item in root.items():
print (item)
for key in root.keys():
print (key)
print(root.get('Message'))
print(root.get('Token'))
print(root.get('DataFormat'))
print(root.get('Header'))
print(root.get('Suffix'))
Explanation: Data inspection (Login)
End of explanation
def Login(session, username, password):
call = 'Login'
url = '/'.join((ws, call))
payload = {'Username': username, 'Password': password}
response = session.get(url, params=payload, stream=True)
if response.status_code == 200:
root = etree.parse(response.raw).getroot()
return root.get('Token')
Explanation: Helper function
End of explanation
token = Login(session, username, password)
token
Explanation: Usage
End of explanation
# pass in username and password
eoddata = Client(username, password)
token = eoddata.get_token()
eoddata.close_session()
print('token: {}'.format(token))
# initialise using secure credentials file
eoddata = Client()
token = eoddata.get_token()
eoddata.close_session()
print('token: {}'.format(token))
# no need to manually close the session when using a with block
with (Client()) as eoddata:
print('token: {}'.format(eoddata.get_token()))
Explanation: Client function
End of explanation |
7,435 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This IPython notebook illustrates how to down sample two large tables that are loaded in the memory
Step1: Down sampling is typically done when the input tables are large (e.g. each containing more than 100K tuples). For the purposes of this notebook we will use two large datasets
Step2: In the down_sample command, set the size to the number of tuples that should be sampled from B (this would be the size of sampled B table) and set the y_param to be the number of matching tuples to be picked from A.
In the above, we set the number of tuples to be sampled from B to be 1000. We set the y_param to 1 meaning that for each tuple sampled from B pick one matching tuple from A. | Python Code:
import py_entitymatching as em
Explanation: This IPython notebook illustrates how to down sample two large tables that are loaded in the memory
End of explanation
# Read the CSV files
A = em.read_csv_metadata('./citeseer.csv',low_memory=False) # setting the parameter low_memory to False to speed up loading.
B = em.read_csv_metadata('./dblp.csv', low_memory=False)
len(A), len(B)
A.head()
B.head()
# Set 'id' as the keys to the input tables
em.set_key(A, 'id')
em.set_key(B, 'id')
# Display the keys
em.get_key(A), em.get_key(B)
# Downsample the datasets
sample_A, sample_B = em.down_sample(A, B, size=1000, y_param=1)
Explanation: Down sampling is typically done when the input tables are large (e.g. each containing more than 100K tuples). For the purposes of this notebook we will use two large datasets: Citeseer and DBLP. You can download Citeseer dataset from http://pages.cs.wisc.edu/~anhai/data/falcon_data/citations/citeseer.csv and DBLP dataset from http://pages.cs.wisc.edu/~anhai/data/falcon_data/citations/dblp.csv. Once downloaded, save these datasets as 'citeseer.csv' and 'dblp.csv' in the current directory.
End of explanation
# Display the lengths of sampled datasets
len(sample_A), len(sample_B)
Explanation: In the down_sample command, set the size to the number of tuples that should be sampled from B (this would be the size of sampled B table) and set the y_param to be the number of matching tuples to be picked from A.
In the above, we set the number of tuples to be sampled from B to be 1000. We set the y_param to 1 meaning that for each tuple sampled from B pick one matching tuple from A.
End of explanation |
7,436 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FashionMNIST classification with Multilayer perceptrons
https
Step1: Preparing the dataset
Download and convert to float
Step2: IMPORTANT
Step3: Understanding the sizes of the data
Make sure you always understand the output of tensor.size()
Train size X image_x X image_y
Step4: Are the classes equally distributed?
Step5: Flatten images
Step6: Splitting the train set into train and dev set
Step7: Helper class that creates minibatches
Step8: Testing the iterator
Step9: Neural network
Definition
Step10: Model instance
Step11: Loss function and optimizer
Step12: Sanity check
The model should perform close to random at this point.
Note we compute accuracy manually. Make sure you understand it.
Step13: Training loop
Step14: Test accuarcy
Step15: Plot loss functions, accuracies
Step16: Overfitting
We'll train a larger network on a much smaller set
Step17: Gotchas
List elements are not trained
Modules such as nn.Linear are not registered as parameters if they're not direct attributes of a module.
In this example we add two extra layers as a list to the module
Step18: they are not part of the model
Step19: One solution is nn.ModuleList
Step20: Using the GPU
Step21: Moving things manually to the GPU | Python Code:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from torchvision import datasets
import torch
import torch.nn as nn
import torch.optim as optim
Explanation: FashionMNIST classification with Multilayer perceptrons
https://github.com/zalandoresearch/fashion-mnist
Exercises
Try changing the model and training parameters (hidden size, epoch, batch size).
Add another hidden layer to the model.
All input values are between 0 to 255 (RGB brightness values). Normalize them (scale them to between 0 and 1). You should see a small increase in accuracy.
Try standardizing the input values (mean 0, std 1).
Implement early stopping. Instead of a fix number of epochs, train until the model stops improving on the dev set. If the dev loss stop decreasing for a few epochs, training should stop.
We plot one random sample and its label. Plot a random sample from each class on 10 subplots.
Limit printing the loss and the accuracy to every 10th epoch instead of every epoch.
ADVANCED: replace the network with a convolutional neural network. Convolutions should work on 2D images, change the preprocessing steps accordingly. You should see a big increase in accuracy.
End of explanation
train_data = datasets.FashionMNIST('data', download=True, train=True)
# we need FloatTensors as input
train_X = train_data.data.float()
train_y = train_data.targets
test_data = datasets.FashionMNIST('data', download=True, train=False)
test_X = test_data.data.float()
test_y = test_data.targets
Explanation: Preparing the dataset
Download and convert to float
End of explanation
labels = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
idx = np.random.randint(len(train_X))
sample_X = train_X[idx].numpy()
sample_y = train_y[idx].numpy()
print("Label: {}".format(labels[sample_y]))
plt.imshow(sample_X, 'gray')
Explanation: IMPORTANT: Inspect the dataset manually
We will plot a random sample with its labels:
End of explanation
train_X.size()
Explanation: Understanding the sizes of the data
Make sure you always understand the output of tensor.size()
Train size X image_x X image_y
End of explanation
np.unique(train_y.numpy(), return_counts=True)
Explanation: Are the classes equally distributed?
End of explanation
print("Before flattening:")
print("Train size:", train_X.size(), train_y.size())
print("Test size:", test_X.size(), test_y.size())
train_X = train_X.view(-1, 28 * 28).squeeze(1)
test_X = test_X.view(-1, 28 * 28).squeeze(1)
print("\nAfter flattening:")
print("Train size:", train_X.size(), train_y.size())
print("Test size:", test_X.size(), test_y.size())
Explanation: Flatten images
End of explanation
all_idx = np.arange(len(train_X))
np.random.shuffle(all_idx)
train_idx = all_idx[:50000]
dev_idx = all_idx[50000:]
print("The overlap between train and dev should be an empty set:", set(train_idx) & set(dev_idx))
print("")
dev_X = train_X[dev_idx]
dev_y = train_y[dev_idx]
train_X = train_X[train_idx]
train_y = train_y[train_idx]
print("Train size:", train_X.size(), train_y.size())
print("Dev size:", dev_X.size(), dev_y.size())
print("Test size:", test_X.size(), test_y.size())
Explanation: Splitting the train set into train and dev set
End of explanation
class BatchedIterator:
def __init__(self, X, y, batch_size):
self.X = X
self.y = y
self.batch_size = batch_size
def iterate_once(self):
for start in range(0, len(self.X), self.batch_size):
end = start + self.batch_size
yield self.X[start:end], self.y[start:end]
Explanation: Helper class that creates minibatches
End of explanation
train_iter = BatchedIterator(train_X, train_y, 33333)
for batch in train_iter.iterate_once():
print(batch[0].size(), batch[1].size())
Explanation: Testing the iterator:
End of explanation
class SimpleClassifier(nn.Module):
def __init__(self, input_dim, output_dim, hidden_dim):
super().__init__()
self.input_layer = nn.Linear(input_dim, hidden_dim)
self.relu = nn.ReLU()
self.output_layer = nn.Linear(hidden_dim, output_dim)
def forward(self, X):
h = self.input_layer(X)
h = self.relu(h)
out = self.output_layer(h)
return out
Explanation: Neural network
Definition
End of explanation
model = SimpleClassifier(
input_dim=train_X.size(1),
output_dim=10,
hidden_dim=50
)
model
for n, p in model.named_parameters():
print(n, p.size())
Explanation: Model instance
End of explanation
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
Explanation: Loss function and optimizer
End of explanation
test_pred = model(test_X).max(axis=1)[1]
test_acc = torch.eq(test_pred, test_y).sum().float() / len(test_X)
test_acc
Explanation: Sanity check
The model should perform close to random at this point.
Note we compute accuracy manually. Make sure you understand it.
End of explanation
batch_size = 1000
train_iter = BatchedIterator(train_X, train_y, batch_size)
dev_iter = BatchedIterator(dev_X, dev_y, batch_size)
test_iter = BatchedIterator(test_X, test_y, batch_size)
all_train_loss = []
all_dev_loss = []
all_train_acc = []
all_dev_acc = []
n_epochs = 10
for epoch in range(n_epochs):
# training loop
for bi, (batch_x, batch_y) in enumerate(train_iter.iterate_once()):
y_out = model(batch_x)
loss = criterion(y_out, batch_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# one train epoch finished, evaluate on the train and the dev set (NOT the test)
train_out = model(train_X)
train_loss = criterion(train_out, train_y)
all_train_loss.append(train_loss.item())
train_pred = train_out.max(axis=1)[1]
train_acc = torch.eq(train_pred, train_y).sum().float() / len(train_X)
all_train_acc.append(train_acc)
dev_out = model(dev_X)
dev_loss = criterion(dev_out, dev_y)
all_dev_loss.append(dev_loss.item())
dev_pred = dev_out.max(axis=1)[1]
dev_acc = torch.eq(dev_pred, dev_y).sum().float() / len(dev_X)
all_dev_acc.append(dev_acc)
print(f"Epoch: {epoch}\n train accuracy: {train_acc} train loss: {train_loss}")
print(f" dev accuracy: {dev_acc} dev loss: {dev_loss}")
Explanation: Training loop
End of explanation
test_pred = model(test_X).max(axis=1)[1]
test_acc = torch.eq(test_pred, test_y).sum().float() / len(test_X)
test_acc
Explanation: Test accuarcy
End of explanation
plt.plot(all_train_loss, label='train')
plt.plot(all_dev_loss, label='dev')
plt.legend()
plt.plot(all_train_acc, label='train')
plt.plot(all_dev_acc, label='dev')
plt.legend()
Explanation: Plot loss functions, accuracies
End of explanation
toy_X = train_X[:5]
toy_y = train_y[:5]
model = SimpleClassifier(
input_dim=train_X.size(1),
output_dim=10,
hidden_dim=500
)
optimizer = optim.Adam(model.parameters())
batch_size = 20
toy_train_iter = BatchedIterator(toy_X, toy_y, batch_size)
all_train_loss = []
all_dev_loss = []
all_train_acc = []
all_dev_acc = []
n_epochs = 20
for epoch in range(n_epochs):
# training loop
for bi, (batch_x, batch_y) in enumerate(toy_train_iter.iterate_once()):
y_out = model(batch_x)
loss = criterion(y_out, batch_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# one train epoch finished, evaluate on the train and the dev set (NOT the test)
train_out = model(toy_X)
train_loss = criterion(train_out, toy_y)
all_train_loss.append(train_loss.item())
train_pred = train_out.max(axis=1)[1]
train_acc = torch.eq(train_pred, toy_y).sum().float() / len(toy_X)
all_train_acc.append(train_acc)
dev_out = model(dev_X)
dev_loss = criterion(dev_out, dev_y)
all_dev_loss.append(dev_loss.item())
dev_pred = dev_out.max(axis=1)[1]
dev_acc = torch.eq(dev_pred, dev_y).sum().float() / len(dev_X)
all_dev_acc.append(dev_acc)
fig, ax = plt.subplots(1, 2, figsize=(12, 5))
ax[0].set_title("Loss")
ax[1].set_title("Accuracy")
ax[0].set_xlabel("epoch")
ax[1].set_xlabel("epoch")
ax[0].plot(all_train_loss, label='train')
ax[0].plot(all_dev_loss, label='dev')
ax[1].plot(all_train_acc, label='train')
ax[1].plot(all_dev_acc, label='dev')
plt.legend()
Explanation: Overfitting
We'll train a larger network on a much smaller set:
End of explanation
class SimpleClassifier(nn.Module):
def __init__(self, input_dim, output_dim,
hidden_dim):
super().__init__()
self.input_layer = nn.Linear(
input_dim, hidden_dim)
# let's add some extra layers in a list
self.extra_layers = [
nn.Linear(hidden_dim, 100),
nn.ReLU(),
nn.Linear(100, hidden_dim),
nn.ReLU(),
]
self.relu = nn.ReLU()
self.output_layer = nn.Linear(
hidden_dim, output_dim)
def forward(self, X):
h = self.input_layer(X)
h = self.relu(h)
# passing through extra layers
for layer in self.extra_layers:
h = layer(h)
out = self.output_layer(h)
return out
Explanation: Gotchas
List elements are not trained
Modules such as nn.Linear are not registered as parameters if they're not direct attributes of a module.
In this example we add two extra layers as a list to the module:
End of explanation
m = SimpleClassifier(4, 5, 6)
print(m)
print("Parameters:")
for name, param in m.named_parameters():
print("Name: {}, size: {}".format(name, param.size()))
Explanation: they are not part of the model
End of explanation
class SimpleClassifier(nn.Module):
def __init__(self, input_dim, output_dim,
hidden_dim):
super().__init__()
self.input_layer = nn.Linear(
input_dim, hidden_dim)
# use ModuleList
self.extra_layers = nn.ModuleList([
nn.Linear(hidden_dim, 100),
nn.ReLU(),
nn.Linear(100, hidden_dim),
nn.ReLU(),
])
self.relu = nn.ReLU()
self.output_layer = nn.Linear(
hidden_dim, output_dim)
def forward(self, X):
h = self.input_layer(X)
h = self.relu(h)
# passing through extra layers
for layer in self.extra_layers:
h = layer(h)
out = self.output_layer(h)
return out
m = SimpleClassifier(4, 5, 6)
print(m)
print("Parameters:")
for name, param in m.named_parameters():
print("Name: {}, size: {}".format(name, param.size()))
Explanation: One solution is nn.ModuleList
End of explanation
use_cuda = torch.cuda.is_available()
print(use_cuda)
Explanation: Using the GPU
End of explanation
if use_cuda:
model = model.cuda()
criterion = criterion.cuda()
Explanation: Moving things manually to the GPU:
model: move once
criterion: move once
data: move one batch at a time
This should be automatically handled by your code the following way:
End of explanation |
7,437 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyTimeSeries
Test for pytimeseries package
Importamos la librería
Step1: Preparación de los datos
pytimeseries recibe una serie de pandas para analizar. A continuación se muestra la preparación de los datos para una serie que inicialmente está en csv.
Elegir una serie de tiempo
Step2: Convertir en fechas la columna que indica los meses
Step3: Asignar las fechas a los datos
Step4: Inferir la frecuencia de los datos automáticamente
Step5: Visualización de la serie
Análisis exploratorio de los datos
Gráfica de la serie
Step6: ACF
Step7: PACF
Step8: QQ Plot
Step9: Histograma
Step10: Gráfica de densidad
Step11: Test de normalidad
Step12: Especificación de la serie
El modelo puede recibir una serie de tiempo transformada de la siguiente manera
Step13: Estimación (Modelo AR)
Utilizando el modelo de statsmodels
```python
X = base_model(self.ts).specify(trans = self.trans, trend = self.trend, seasonal = self.seasonal)
model = statsmodels.tsa.ar_model.AR(X.residuals)
model_fit = model.fit()
estimation = model_fit.predict()
X.estimation = estimation
X.restore(trans = self.trans, trend = self.trend, seasonal = self.seasonal)
super().set_residuals(X.residuals)
``` | Python Code:
import pytimeseries
import pandas
import matplotlib
Explanation: PyTimeSeries
Test for pytimeseries package
Importamos la librería
End of explanation
tserie = pandas.read_csv('champagne.csv', index_col='Month')
print(tserie)
Explanation: Preparación de los datos
pytimeseries recibe una serie de pandas para analizar. A continuación se muestra la preparación de los datos para una serie que inicialmente está en csv.
Elegir una serie de tiempo
End of explanation
rng = pandas.to_datetime(tserie.index)
print(rng)
Explanation: Convertir en fechas la columna que indica los meses
End of explanation
tserie.reindex(rng)
Explanation: Asignar las fechas a los datos
End of explanation
frq = pandas.infer_freq(tserie.index)
print(frq)
Explanation: Inferir la frecuencia de los datos automáticamente
End of explanation
pytimeseries.series_viewer(tserie).time_plot()
matplotlib.pyplot.show()
Explanation: Visualización de la serie
Análisis exploratorio de los datos
Gráfica de la serie
End of explanation
pytimeseries.series_viewer(tserie).ACF_plot()
matplotlib.pyplot.show()
Explanation: ACF
End of explanation
pytimeseries.series_viewer(tserie).PACF_plot()
matplotlib.pyplot.show()
Explanation: PACF
End of explanation
pytimeseries.series_viewer(tserie).qq_plot()
matplotlib.pyplot.show()
Explanation: QQ Plot
End of explanation
pytimeseries.series_viewer(tserie).histogram()
matplotlib.pyplot.show()
Explanation: Histograma
End of explanation
pytimeseries.series_viewer(tserie).density_plot()
matplotlib.pyplot.show()
Explanation: Gráfica de densidad
End of explanation
nt = pytimeseries.series_viewer(tserie).normality()
print(nt)
Explanation: Test de normalidad
End of explanation
matplotlib.pyplot.plot(tserie.values)
pytimeseries.base_model(ts = tserie).specify(trans = 'log')
matplotlib.pyplot.show()
Explanation: Especificación de la serie
El modelo puede recibir una serie de tiempo transformada de la siguiente manera:
trans = Transformaciones directas de la serie:
- log
- log10
- sqrt
- cbrt
- boxcox
trend = Eliminando la tendencia:
- linear
- cuadratic
- cubic
- diff1
- diff2
seasonal = Estacionalidad (de acuerdo a la frecuencia):
- poly2
- diff
- (dummy)
También la combinación de ellas
End of explanation
model = pytimeseries.AR_p(ts = tserie, trans='sqrt', trend = 'linear', seasonal = 'poly2')
result = model.estimate()
matplotlib.pyplot.plot(tserie.values)
matplotlib.pyplot.plot(result.X.original)
matplotlib.pyplot.plot(result.X.residuals)
matplotlib.pyplot.plot(result.X.estimation)
matplotlib.pyplot.show()
Explanation: Estimación (Modelo AR)
Utilizando el modelo de statsmodels
```python
X = base_model(self.ts).specify(trans = self.trans, trend = self.trend, seasonal = self.seasonal)
model = statsmodels.tsa.ar_model.AR(X.residuals)
model_fit = model.fit()
estimation = model_fit.predict()
X.estimation = estimation
X.restore(trans = self.trans, trend = self.trend, seasonal = self.seasonal)
super().set_residuals(X.residuals)
```
End of explanation |
7,438 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hackathon de Nanterre
17 octobre 2015
Coder la ville...
... en Python
Step1: Lecture des données relatives aux acteurs du numérique (www.datea.pe)
Step2: Lecture des données relatives aux équipements de Nanterre (www.nanterre.fr)
Step3: Fonction d'affichage des data
Step4: Les différents types d'équipement
Step5: Cartographie des équipements et des acteurs du numérique | Python Code:
import pandas as pnd
import matplotlib.pylab as plt
import matplotlib.patches as mpatches
from IPython.display import HTML
%matplotlib inline
img = plt.imread("rueildigital.jpg")
plt.axis('off')
plt.imshow(img);
Explanation: Hackathon de Nanterre
17 octobre 2015
Coder la ville...
... en Python
End of explanation
HTML("<iframe src='http://datea.pe/NanterreDigital/nanterredigital?tab=map' width=600 height=400>")
df = pnd.read_csv("NanterreDigital_17-10-2015.csv")
df.head(10)
df.info()
Explanation: Lecture des données relatives aux acteurs du numérique (www.datea.pe)
End of explanation
HTML("<iframe src='http://www.nanterre.fr/1522-les-equipements.htm' width=600 height=400>")
df2 = pnd.read_csv("BDE-Equipements-Nanterre-Liste.csv",encoding="latin-1")
df2.head(10)
Explanation: Lecture des données relatives aux équipements de Nanterre (www.nanterre.fr)
End of explanation
def display(what):
ax = df2.plot(x="X_WGS84",y="Y_WGS84",kind='scatter',edgecolor = 'none');
ax.set_title("Nanterre")
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
df3=df2[df2["TYPE"]==what]
ax.scatter(df3["X_WGS84"],df3["Y_WGS84"],c='r',edgecolor = 'none')
ax.scatter(df["longitude"],df["latitude"],c='g',edgecolor = 'none',s=30)
blue_patch = mpatches.Patch(color='blue', label='Equipements')
red_patch = mpatches.Patch(color='red', label=what)
black_patch = mpatches.Patch(color='green', label='Acteurs du numérique')
plt.legend(bbox_to_anchor=(1.45, 0.85), handles=[blue_patch, red_patch, black_patch])
Explanation: Fonction d'affichage des data
End of explanation
df2["TYPE"].value_counts()
Explanation: Les différents types d'équipement
End of explanation
display("Vie Sociale")
Explanation: Cartographie des équipements et des acteurs du numérique
End of explanation |
7,439 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Fully-Connected Neural Nets
In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.
In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a forward and a backward function. The forward function will receive inputs, weights, and other parameters and will return both an output and a cache object storing data needed for the backward pass, like this
Step4: Affine layer
Step5: Affine layer
Step6: ReLU layer
Step7: ReLU layer
Step8: "Sandwich" layers
There are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file cs231n/layer_utils.py.
For now take a look at the affine_relu_forward and affine_relu_backward functions, and run the following to numerically gradient check the backward pass
Step9: Loss layers
Step10: Two-layer network
In the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.
Open the file cs231n/classifiers/fc_net.py and complete the implementation of the TwoLayerNet class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation.
Step11: Solver
In the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.
Open the file cs231n/solver.py and read through it to familiarize yourself with the API. After doing so, use a Solver instance to train a TwoLayerNet that achieves at least 50% accuracy on the validation set.
Step12: Multilayer network
Next you will implement a fully-connected network with an arbitrary number of hidden layers.
Read through the FullyConnectedNet class in the file cs231n/classifiers/fc_net.py.
Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon.
Initial loss and gradient check
As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?
For gradient checking, you should expect to see errors around 1e-6 or less.
Step14: As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs.
Step16: Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs.
Step17: Inline question
Step18: Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster.
Step19: RMSProp and Adam
RMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.
In the file cs231n/optim.py, implement the RMSProp update rule in the rmsprop function and implement the Adam update rule in the adam function, and check your implementations using the tests below.
[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop
Step20: Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules
Step21: Train a good model!
Train the best fully-connected model that you can on CIFAR-10, storing your best model in the best_model variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.
If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.
You might find it useful to complete the BatchNormalization.ipynb and Dropout.ipynb notebooks before completing this part, since those techniques can help you train powerful models.
Step22: Test you model
Run your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. | Python Code:
# As usual, a bit of setup
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from cs231n.solver import Solver
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading external modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
def rel_error(x, y):
returns relative error
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
# Load the (preprocessed) CIFAR10 data.
data = get_CIFAR10_data()
for k, v in data.iteritems():
print '%s: ' % k, v.shape
Explanation: Fully-Connected Neural Nets
In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.
In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a forward and a backward function. The forward function will receive inputs, weights, and other parameters and will return both an output and a cache object storing data needed for the backward pass, like this:
```python
def layer_forward(x, w):
Receive inputs x and weights w
# Do some computations ...
z = # ... some intermediate value
# Do some more computations ...
out = # the output
cache = (x, w, z, out) # Values we need to compute gradients
return out, cache
```
The backward pass will receive upstream derivatives and the cache object, and will return gradients with respect to the inputs and weights, like this:
```python
def layer_backward(dout, cache):
Receive derivative of loss with respect to outputs and cache,
and compute derivative with respect to inputs.
# Unpack cache values
x, w, z, out = cache
# Use values in cache to compute derivatives
dx = # Derivative of loss with respect to x
dw = # Derivative of loss with respect to w
return dx, dw
```
After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.
In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch Normalization as a tool to more efficiently optimize deep networks.
End of explanation
# Test the affine_forward function
num_inputs = 2
input_shape = (4, 5, 6)
output_dim = 3
input_size = num_inputs * np.prod(input_shape)
weight_size = output_dim * np.prod(input_shape)
x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape)
w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim)
b = np.linspace(-0.3, 0.1, num=output_dim)
out, _ = affine_forward(x, w, b)
correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297],
[ 3.25553199, 3.5141327, 3.77273342]])
# Compare your output with ours. The error should be around 1e-9.
print 'Testing affine_forward function:'
print 'difference: ', rel_error(out, correct_out)
Explanation: Affine layer: foward
Open the file cs231n/layers.py and implement the affine_forward function.
Once you are done you can test your implementaion by running the following:
End of explanation
# Test the affine_backward function
x = np.random.randn(10, 2, 3)
w = np.random.randn(6, 5)
b = np.random.randn(5)
dout = np.random.randn(10, 5)
dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout)
dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout)
db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout)
_, cache = affine_forward(x, w, b)
dx, dw, db = affine_backward(dout, cache)
# The error should be around 1e-10
print 'Testing affine_backward function:'
print 'dx error: ', rel_error(dx_num, dx)
print 'dw error: ', rel_error(dw_num, dw)
print 'db error: ', rel_error(db_num, db)
Explanation: Affine layer: backward
Now implement the affine_backward function and test your implementation using numeric gradient checking.
End of explanation
# Test the relu_forward function
x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4)
out, _ = relu_forward(x)
correct_out = np.array([[ 0., 0., 0., 0., ],
[ 0., 0., 0.04545455, 0.13636364,],
[ 0.22727273, 0.31818182, 0.40909091, 0.5, ]])
# Compare your output with ours. The error should be around 1e-8
print 'Testing relu_forward function:'
print 'difference: ', rel_error(out, correct_out)
Explanation: ReLU layer: forward
Implement the forward pass for the ReLU activation function in the relu_forward function and test your implementation using the following:
End of explanation
x = np.random.randn(10, 10)
dout = np.random.randn(*x.shape)
dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout)
_, cache = relu_forward(x)
dx = relu_backward(dout, cache)
# The error should be around 1e-12
print 'Testing relu_backward function:'
print 'dx error: ', rel_error(dx_num, dx)
Explanation: ReLU layer: backward
Now implement the backward pass for the ReLU activation function in the relu_backward function and test your implementation using numeric gradient checking:
End of explanation
from cs231n.layer_utils import affine_relu_forward, affine_relu_backward
x = np.random.randn(2, 3, 4)
w = np.random.randn(12, 10)
b = np.random.randn(10)
dout = np.random.randn(2, 10)
out, cache = affine_relu_forward(x, w, b)
dx, dw, db = affine_relu_backward(dout, cache)
dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout)
dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout)
db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout)
print 'Testing affine_relu_forward:'
print 'dx error: ', rel_error(dx_num, dx)
print 'dw error: ', rel_error(dw_num, dw)
print 'db error: ', rel_error(db_num, db)
Explanation: "Sandwich" layers
There are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file cs231n/layer_utils.py.
For now take a look at the affine_relu_forward and affine_relu_backward functions, and run the following to numerically gradient check the backward pass:
End of explanation
num_classes, num_inputs = 10, 50
x = 0.001 * np.random.randn(num_inputs, num_classes)
y = np.random.randint(num_classes, size=num_inputs)
dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False)
loss, dx = svm_loss(x, y)
# Test svm_loss function. Loss should be around 9 and dx error should be 1e-9
print 'Testing svm_loss:'
print 'loss: ', loss
print 'dx error: ', rel_error(dx_num, dx)
dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False)
loss, dx = softmax_loss(x, y)
# Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8
print '\nTesting softmax_loss:'
print 'loss: ', loss
print 'dx error: ', rel_error(dx_num, dx)
Explanation: Loss layers: Softmax and SVM
You implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in cs231n/layers.py.
You can make sure that the implementations are correct by running the following:
End of explanation
N, D, H, C = 3, 5, 50, 7
X = np.random.randn(N, D)
y = np.random.randint(C, size=N)
std = 1e-2
model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std)
print 'Testing initialization ... '
W1_std = abs(model.params['W1'].std() - std)
b1 = model.params['b1']
W2_std = abs(model.params['W2'].std() - std)
b2 = model.params['b2']
assert W1_std < std / 10, 'First layer weights do not seem right'
assert np.all(b1 == 0), 'First layer biases do not seem right'
assert W2_std < std / 10, 'Second layer weights do not seem right'
assert np.all(b2 == 0), 'Second layer biases do not seem right'
print 'Testing test-time forward pass ... '
model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H)
model.params['b1'] = np.linspace(-0.1, 0.9, num=H)
model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C)
model.params['b2'] = np.linspace(-0.9, 0.1, num=C)
X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T
scores = model.loss(X)
correct_scores = np.asarray(
[[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096],
[12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143],
[12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]])
scores_diff = np.abs(scores - correct_scores).sum()
assert scores_diff < 1e-6, 'Problem with test-time forward pass'
print 'Testing training loss (no regularization)'
y = np.asarray([0, 5, 1])
loss, grads = model.loss(X, y)
correct_loss = 3.4702243556
assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss'
model.reg = 1.0
loss, grads = model.loss(X, y)
correct_loss = 26.5948426952
assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss'
for reg in [0.0, 0.7]:
print 'Running numeric gradient check with reg = ', reg
model.reg = reg
loss, grads = model.loss(X, y)
for name in sorted(grads):
f = lambda _: model.loss(X, y)[0]
grad_num = eval_numerical_gradient(f, model.params[name], verbose=False)
print '%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))
Explanation: Two-layer network
In the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.
Open the file cs231n/classifiers/fc_net.py and complete the implementation of the TwoLayerNet class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation.
End of explanation
model = TwoLayerNet()
solver = None
##############################################################################
# TODO: Use a Solver instance to train a TwoLayerNet that achieves at least #
# 50% accuracy on the validation set. #
##############################################################################
solver = Solver(model, data,
update_rule='sgd',
optim_config={
'learning_rate': 1e-3,
},
lr_decay=0.95,
num_epochs=10, batch_size=100,
print_every=100)
solver.train()
##############################################################################
# END OF YOUR CODE #
##############################################################################
# Run this cell to visualize training loss and train / val accuracy
plt.subplot(2, 1, 1)
plt.title('Training loss')
plt.plot(solver.loss_history, 'o')
plt.xlabel('Iteration')
plt.subplot(2, 1, 2)
plt.title('Accuracy')
plt.plot(solver.train_acc_history, '-o', label='train')
plt.plot(solver.val_acc_history, '-o', label='val')
plt.plot([0.5] * len(solver.val_acc_history), 'k--')
plt.xlabel('Epoch')
plt.legend(loc='lower right')
plt.gcf().set_size_inches(15, 12)
plt.show()
Explanation: Solver
In the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.
Open the file cs231n/solver.py and read through it to familiarize yourself with the API. After doing so, use a Solver instance to train a TwoLayerNet that achieves at least 50% accuracy on the validation set.
End of explanation
N, D, H1, H2, C = 2, 15, 20, 30, 10
X = np.random.randn(N, D)
y = np.random.randint(C, size=(N,))
for reg in [0, 3.14]:
print 'Running check with reg = ', reg
model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,
reg=reg, weight_scale=5e-2, dtype=np.float64)
loss, grads = model.loss(X, y)
print 'Initial loss: ', loss
for name in sorted(grads):
f = lambda _: model.loss(X, y)[0]
grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)
print '%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))
Explanation: Multilayer network
Next you will implement a fully-connected network with an arbitrary number of hidden layers.
Read through the FullyConnectedNet class in the file cs231n/classifiers/fc_net.py.
Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon.
Initial loss and gradient check
As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?
For gradient checking, you should expect to see errors around 1e-6 or less.
End of explanation
# TODO: Use a three-layer Net to overfit 50 training examples.
num_train = 50
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
weight_scale = 1e-2
learning_rate = 1e-4
model = FullyConnectedNet([100, 100],
weight_scale=weight_scale, dtype=np.float64)
solver = Solver(model, small_data,
print_every=10, num_epochs=20, batch_size=25,
update_rule='sgd',
optim_config={
'learning_rate': learning_rate,
}
)
solver.train()
def train_model(weight_scale, learning_rate, verbose=False):
model = FullyConnectedNet([100, 100],
weight_scale=weight_scale, dtype=np.float64)
solver = Solver(model, small_data,
print_every=10, num_epochs=20, batch_size=25,
update_rule='sgd',
optim_config={
'learning_rate': learning_rate,
},
verbose=verbose
)
solver.train()
return solver.train_acc_history[-1], solver.val_acc_history[-1]
weight_scales = [1e-03, 1e-02, 1e-01]
learning_rates = [1e-5, 1e-4, 1e-3]
for scale in weight_scales:
for rate in learning_rates:
train_acc, val_acc = train_model(scale, rate)
print('scale: %f, rate: %f, train_acc: %f, val_acc: %f' % (
scale, rate, train_acc, val_acc))
plt.plot(solver.loss_history, 'o')
plt.title('Training loss history')
plt.xlabel('Iteration')
plt.ylabel('Training loss')
plt.show()
Explanation: As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs.
End of explanation
# TODO: Use a five-layer Net to overfit 50 training examples.
num_train = 50
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
learning_rate = 1e-3
weight_scale = 1e-5
model = FullyConnectedNet([100, 100, 100, 100],
weight_scale=weight_scale, dtype=np.float64)
solver = Solver(model, small_data,
print_every=10, num_epochs=20, batch_size=25,
update_rule='sgd',
optim_config={
'learning_rate': learning_rate,
}
)
solver.train()
def train_model(weight_scale, learning_rate, verbose=False):
model = FullyConnectedNet([100, 100, 100, 100],
weight_scale=weight_scale, dtype=np.float64)
solver = Solver(model, small_data,
print_every=10, num_epochs=20, batch_size=25,
update_rule='sgd',
optim_config={
'learning_rate': learning_rate,
},
verbose=verbose
)
solver.train()
return solver.train_acc_history[-1], solver.val_acc_history[-1]
weight_scales = [1e-03, 1e-02, 1e-01]
learning_rates = [1e-5, 1e-4, 1e-3]
for scale in weight_scales:
for rate in learning_rates:
train_acc, val_acc = train_model(scale, rate)
print('scale: %f, rate: %f, train_acc: %f, val_acc: %f' % (
scale, rate, train_acc, val_acc))
plt.plot(solver.loss_history, 'o')
plt.title('Training loss history')
plt.xlabel('Iteration')
plt.ylabel('Training loss')
plt.show()
Explanation: Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs.
End of explanation
from cs231n.optim import sgd_momentum
N, D = 4, 5
w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D)
dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D)
v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D)
config = {'learning_rate': 1e-3, 'velocity': v}
next_w, _ = sgd_momentum(w, dw, config=config)
expected_next_w = np.asarray([
[ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789],
[ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526],
[ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263],
[ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]])
expected_velocity = np.asarray([
[ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158],
[ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105],
[ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053],
[ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]])
print 'next_w error: ', rel_error(next_w, expected_next_w)
print 'velocity error: ', rel_error(expected_velocity, config['velocity'])
Explanation: Inline question:
Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net?
Answer:
[FILL THIS IN]
Update rules
So far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD.
SGD+Momentum
Stochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochstic gradient descent.
Open the file cs231n/optim.py and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function sgd_momentum and run the following to check your implementation. You should see errors less than 1e-8.
End of explanation
num_train = 4000
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
solvers = {}
for update_rule in ['sgd', 'sgd_momentum']:
print 'running with ', update_rule
model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2)
solver = Solver(model, small_data,
num_epochs=5, batch_size=100,
update_rule=update_rule,
optim_config={
'learning_rate': 1e-2,
},
verbose=True)
solvers[update_rule] = solver
solver.train()
print
plt.subplot(3, 1, 1)
plt.title('Training loss')
plt.xlabel('Iteration')
plt.subplot(3, 1, 2)
plt.title('Training accuracy')
plt.xlabel('Epoch')
plt.subplot(3, 1, 3)
plt.title('Validation accuracy')
plt.xlabel('Epoch')
for update_rule, solver in solvers.iteritems():
plt.subplot(3, 1, 1)
plt.plot(solver.loss_history, 'o', label=update_rule)
plt.subplot(3, 1, 2)
plt.plot(solver.train_acc_history, '-o', label=update_rule)
plt.subplot(3, 1, 3)
plt.plot(solver.val_acc_history, '-o', label=update_rule)
for i in [1, 2, 3]:
plt.subplot(3, 1, i)
plt.legend(loc='upper center', ncol=4)
plt.gcf().set_size_inches(15, 15)
plt.show()
Explanation: Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster.
End of explanation
# Test RMSProp implementation; you should see errors less than 1e-7
from cs231n.optim import rmsprop
N, D = 4, 5
w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D)
dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D)
cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D)
config = {'learning_rate': 1e-2, 'cache': cache}
next_w, _ = rmsprop(w, dw, config=config)
expected_next_w = np.asarray([
[-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247],
[-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774],
[ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447],
[ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]])
expected_cache = np.asarray([
[ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321],
[ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377],
[ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936],
[ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]])
print 'next_w error: ', rel_error(expected_next_w, next_w)
print 'cache error: ', rel_error(expected_cache, config['cache'])
# Test Adam implementation; you should see errors around 1e-7 or less
from cs231n.optim import adam
N, D = 4, 5
w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D)
dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D)
m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D)
v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D)
config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5}
next_w, _ = adam(w, dw, config=config)
expected_next_w = np.asarray([
[-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977],
[-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929],
[ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969],
[ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]])
expected_v = np.asarray([
[ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,],
[ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,],
[ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,],
[ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]])
expected_m = np.asarray([
[ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474],
[ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316],
[ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158],
[ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]])
print 'next_w error: ', rel_error(expected_next_w, next_w)
print 'v error: ', rel_error(expected_v, config['v'])
print 'm error: ', rel_error(expected_m, config['m'])
Explanation: RMSProp and Adam
RMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.
In the file cs231n/optim.py, implement the RMSProp update rule in the rmsprop function and implement the Adam update rule in the adam function, and check your implementations using the tests below.
[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).
[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015.
End of explanation
learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3}
for update_rule in ['adam', 'rmsprop']:
print 'running with ', update_rule
model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2)
solver = Solver(model, small_data,
num_epochs=5, batch_size=100,
update_rule=update_rule,
optim_config={
'learning_rate': learning_rates[update_rule]
},
verbose=True)
solvers[update_rule] = solver
solver.train()
print
plt.subplot(3, 1, 1)
plt.title('Training loss')
plt.xlabel('Iteration')
plt.subplot(3, 1, 2)
plt.title('Training accuracy')
plt.xlabel('Epoch')
plt.subplot(3, 1, 3)
plt.title('Validation accuracy')
plt.xlabel('Epoch')
for update_rule, solver in solvers.iteritems():
plt.subplot(3, 1, 1)
plt.plot(solver.loss_history, 'o', label=update_rule)
plt.subplot(3, 1, 2)
plt.plot(solver.train_acc_history, '-o', label=update_rule)
plt.subplot(3, 1, 3)
plt.plot(solver.val_acc_history, '-o', label=update_rule)
for i in [1, 2, 3]:
plt.subplot(3, 1, i)
plt.legend(loc='upper center', ncol=4)
plt.gcf().set_size_inches(15, 15)
plt.show()
Explanation: Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules:
End of explanation
best_model = None
################################################################################
# TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might #
# batch normalization and dropout useful. Store your best model in the #
# best_model variable. #
################################################################################
def train_model(weight_scale, learning_rate, verbose=False):
model = FullyConnectedNet([100, 100, 100, 100, 100],
weight_scale=weight_scale)
solver = Solver(model, data,
num_epochs=10, batch_size=200,
update_rule='adam',
optim_config={
'learning_rate': learning_rate
},
verbose=verbose
)
solver.train()
return model, solver.train_acc_history[-1], solver.val_acc_history[-1]
weight_scales = [5e-3, 5e-2, 5e-1]
learning_rates = [1e-4, 1e-3, 1e-2]
best_val_acc = -1
for scale in weight_scales:
for rate in learning_rates:
model, train_acc, val_acc = train_model(scale, rate)
if val_acc > best_val_acc:
best_val_acc = val_acc
best_model = model
print('scale: %f, rate: %f, train_acc: %f, val_acc: %f' % (
scale, rate, train_acc, val_acc))
################################################################################
# END OF YOUR CODE #
################################################################################
Explanation: Train a good model!
Train the best fully-connected model that you can on CIFAR-10, storing your best model in the best_model variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.
If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.
You might find it useful to complete the BatchNormalization.ipynb and Dropout.ipynb notebooks before completing this part, since those techniques can help you train powerful models.
End of explanation
X_val = data['X_val']
y_val = data['y_val']
X_test = data['X_test']
y_test = data['y_test']
y_test_pred = np.argmax(best_model.loss(X_test), axis=1)
y_val_pred = np.argmax(best_model.loss(X_val), axis=1)
print 'Validation set accuracy: ', (y_val_pred == y_val).mean()
print 'Test set accuracy: ', (y_test_pred == y_test).mean()
Explanation: Test you model
Run your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set.
End of explanation |
7,440 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
If you don't care about the confidence interval of parameter
Step1: If you want the confidence intervals | Python Code:
from lmfit.models import GaussianModel
# initialize the gaussian model
gm = GaussianModel()
# take a look at the parameter names
print gm.param_names
# I get RuntimeError since my numpy version is a little old
# guess parameters
par_guess = gm.guess(n,x=xpos)
# fit data
result = gm.fit(n, par_guess, x=xpos, method='leastsq')
# quick look at result
print result.fit_report()
# get best fit error and stderr
print result.params['amplitude'].value,result.params['amplitude'].stderr
print result.params['center'].value,result.params['center'].stderr
print result.params['sigma'].value,result.params['sigma'].stderr
fig = plt.figure()
plt.hist(xdata, bins=bins)
plt.plot(xpos, result.best_fit, 'green')
Explanation: If you don't care about the confidence interval of parameter
End of explanation
import lmfit
def my_gaussian_model(p, x, y):
a = np.float(p['a'])
b = np.float(p['b'])
c = np.float(p['c'])
return a/np.sqrt(2.*c) * np.exp( -np.power(x-b,2.)/2./np.power(c, 2.)) - y
pars = lmfit.Parameters()
pars.add_many(('a',0.1), ('b',0.1), ('c',0.1))
# initialize the minimizer
mini = lmfit.Minimizer(my_gaussian_model, pars, (xpos, n))
# do the minimization
result = mini.minimize(method='leastsq')
# print the fit report
print lmfit.fit_report(mini.params)
# NOTE
# the parameter 'a' in function my_gaussian_model is different from the built-in model in lmfit
# so the amplitude value is a little different
# predit the confidence interval of all parameters
ci, trace = lmfit.conf_interval(mini, sigmas=[0.68,0.95],
trace=True, verbose=False)
# ci = lmfit.conf_interval(mini)
lmfit.printfuncs.report_ci(ci)
print ci.values()
a,b,prob = trace['a']['a'], trace['a']['b'], trace['a']['prob']
cx, cy, grid = lmfit.conf_interval2d(mini, 'a','b',30,30)
plt.contourf(cx, cy, grid, np.linspace(0,1,11))
plt.xlabel('a')
plt.colorbar()
plt.ylabel('b')
Explanation: If you want the confidence intervals
End of explanation |
7,441 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The
Step1: Here for convenience we read the evoked dataset from a file.
Step2: Notice that the reader function returned a list of evoked instances. This is
because you can store multiple categories into a single file. Here we have
categories of
['Left Auditory', 'Right Auditory', 'Left Visual', 'Right Visual'].
We can also use condition parameter to read in only one category.
Step3: If you're gone through the tutorials of raw and epochs datasets, you're
probably already familiar with the
Step4: The evoked data structure also contains some new attributes easily
accessible
Step5: The data is also easily accessible. Since the evoked data arrays are usually
much smaller than raw or epochs datasets, they are preloaded into the memory
when the evoked object is constructed. You can access the data as a numpy
array.
Step6: The data is arranged in an array of shape (n_channels, n_times). Notice
that unlike epochs, evoked object does not support indexing. This means that
to access the data of a specific channel you must use the data array
directly.
Step7: If you want to import evoked data from some other system and you have it in a
numpy array you can use | Python Code:
import os.path as op
import mne
Explanation: The :class:Evoked <mne.Evoked> data structure: evoked/averaged data
The :class:Evoked <mne.Evoked> data structure is mainly used for storing
averaged data over trials. In MNE the evoked objects are usually created by
averaging epochs data with :func:mne.Epochs.average.
End of explanation
data_path = mne.datasets.sample.data_path()
fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')
evokeds = mne.read_evokeds(fname, baseline=(None, 0), proj=True)
print(evokeds)
Explanation: Here for convenience we read the evoked dataset from a file.
End of explanation
evoked = mne.read_evokeds(fname, condition='Left Auditory')
evoked.apply_baseline((None, 0)).apply_proj()
print(evoked)
Explanation: Notice that the reader function returned a list of evoked instances. This is
because you can store multiple categories into a single file. Here we have
categories of
['Left Auditory', 'Right Auditory', 'Left Visual', 'Right Visual'].
We can also use condition parameter to read in only one category.
End of explanation
print(evoked.info)
print(evoked.times)
Explanation: If you're gone through the tutorials of raw and epochs datasets, you're
probably already familiar with the :class:Info <mne.Info> attribute.
There is nothing new or special with the evoked.info. All the relevant
info is still there.
End of explanation
print(evoked.nave) # Number of averaged epochs.
print(evoked.first) # First time sample.
print(evoked.last) # Last time sample.
print(evoked.comment) # Comment on dataset. Usually the condition.
print(evoked.kind) # Type of data, either average or standard_error.
Explanation: The evoked data structure also contains some new attributes easily
accessible:
End of explanation
data = evoked.data
print(data.shape)
Explanation: The data is also easily accessible. Since the evoked data arrays are usually
much smaller than raw or epochs datasets, they are preloaded into the memory
when the evoked object is constructed. You can access the data as a numpy
array.
End of explanation
print('Data from channel {0}:'.format(evoked.ch_names[10]))
print(data[10])
Explanation: The data is arranged in an array of shape (n_channels, n_times). Notice
that unlike epochs, evoked object does not support indexing. This means that
to access the data of a specific channel you must use the data array
directly.
End of explanation
evoked = mne.EvokedArray(data, evoked.info, tmin=evoked.times[0])
evoked.plot(time_unit='s')
Explanation: If you want to import evoked data from some other system and you have it in a
numpy array you can use :class:mne.EvokedArray for that. All you need is
the data and some info about the evoked data. For more information, see
tut_creating_data_structures.
End of explanation |
7,442 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Label and feature engineering
Learning objectives
Step1: Create time-series features and determine label based on market movement
Summary of base tables
Step2: Label engineering
Ultimately, we need to end up with a single label for each day. The label takes on 3 values
Step3: The stock market is going up on average.
Learning objective 2
Step6: Add time series features
<h3><font color="#4885ed">Compute price features using analytics functions</font> </h3>
In addition, we will also build time-series features using the min, max, mean, and std (can you think of any over functions to use?). To do this, let's use analytic functions in BigQuery (also known as window functions).
An analytic function is a function that computes aggregate values over a group of rows. Unlike aggregate functions, which return a single aggregate value for a group of rows, analytic functions return a single value for each row by computing the function over a group of input rows.
Using the AVG analytic function, we can compute the average close price of a given symbol over the past week (5 business days)
Step8: Compute percentage change, then self join with prices from S&P index.
We will also compute price change of S&P index, GSPC. We do this so we can compute the normalized percentage change.
<h3><font color="#4885ed">Compute normalized price change (%)</font> </h3>
Before we can create our labels we need to normalize the price change using the S&P 500 index. The normalization using the S&P index fund helps ensure that the future price of a stock is not due to larger market effects. Normalization helps us isolate the factors contributing to the performance of a stock_market.
Let's use the normalization scheme from by subtracting the scaled difference in the S&P 500 index during the same time period.
In Python
Step9: Compute normalized price change (shown above).
Let's join scaled price change (tomorrow_close / close) with the gspc symbol (symbol for the S&P index). Then we can normalize using the scheme described above.
Learning objective 3
Step10: Verify results
Step11: <h3><font color="#4885ed">Join with S&P 500 table and Create labels
Step12: The dataset is still quite large and the majority of the days the market STAYs. Let's focus our analysis on dates where earnings per share (EPS) information is released by the companies. The EPS data has 3 key columns surprise, reported_EPS, and consensus_EPS
Step13: The surprise column indicates the difference between the expected (consensus expected eps by analysts) and the reported eps. We can join this table with our derived table to focus our analysis during earnings periods
Step16: Feature exploration
Now that we have created our recent movements of the company’s stock price, let's visualize our features. This will help us understand the data better and possibly spot errors we may have made during our calculations.
As a reminder, we calculated the scaled prices 1 week, 1 month, and 1 year before the date that we are predicting at.
Let's write a re-usable function for aggregating our features.
Learning objective 2
Step18: Let's look at results by day-of-week, month, etc. | Python Code:
PROJECT = !(gcloud config get-value core/project)
PROJECT = PROJECT[0]
import pandas as pd
from google.cloud import bigquery
from IPython import get_ipython
from IPython.core.magic import register_cell_magic
bq = bigquery.Client(project=PROJECT)
# Allow you to easily have Python variables in SQL query.
@register_cell_magic("with_globals")
def with_globals(line, cell):
contents = cell.format(**globals())
if "print" in line:
print(contents)
get_ipython().run_cell(contents)
def create_dataset():
dataset = bigquery.Dataset(bq.dataset("stock_market"))
try:
bq.create_dataset(dataset) # Will fail if dataset already exists.
print("Dataset created")
except:
print("Dataset already exists")
create_dataset()
Explanation: Label and feature engineering
Learning objectives:
Learn how to use BigQuery to build time-series features and labels for forecasting
Learn how to visualize and explore features.
Learn effective scaling and normalizing techniques to improve our modeling results
Now that we have explored the data, let's start building our features, so we can build a model.
<h3><font color="#4885ed">Feature Engineering</font> </h3>
Use the price_history table, we can look at past performance of a given stock, to try to predict it's future stock price. In this notebook we will be focused on cleaning and creating features from this table.
There are typically two different approaches to creating features with time-series data.
One approach is aggregate the time-series into "static" features, such as "min_price_over_past_month" or "exp_moving_avg_past_30_days". Using this approach, we can use a deep neural network or a more "traditional" ML model to train. Notice we have essentially removed all sequention information after aggregating. This assumption can work well in practice.
A second approach is to preserve the ordered nature of the data and use a sequential model, such as a recurrent neural network. This approach has a nice benefit that is typically requires less feature engineering. Although, training sequentially models typically takes longer.
In this notebook, we will build features and also create rolling windows of the ordered time-series data.
<h3><font color="#4885ed">Label Engineering</font> </h3>
We are trying to predict if the stock will go up or down. In order to do this we will need to "engineer" our label by looking into the future and using that as the label. We will be using the LAG function in BigQuery to do this. Visually this looks like:
Import libraries; setup
End of explanation
%%with_globals
%%bigquery --project {PROJECT}
SELECT count(*) as cnt
FROM `stock_src.price_history`
%%with_globals
%%bigquery --project {PROJECT}
SELECT count(*) as cnt
FROM `stock_src.snp500`
Explanation: Create time-series features and determine label based on market movement
Summary of base tables
End of explanation
%%with_globals print
%%bigquery df --project {PROJECT}
CREATE OR REPLACE TABLE `stock_market.price_history_delta`
AS
(
WITH shifted_price AS
(
SELECT *,
(LAG(close, 1) OVER (PARTITION BY symbol order by Date DESC)) AS tomorrow_close
FROM `stock_src.price_history`
WHERE Close > 0
)
SELECT a.*,
(tomorrow_close - Close) AS tomo_close_m_close
FROM shifted_price a
)
%%with_globals
%%bigquery --project {PROJECT}
SELECT *
FROM stock_market.price_history_delta
ORDER by Date
LIMIT 100
Explanation: Label engineering
Ultimately, we need to end up with a single label for each day. The label takes on 3 values: {down, stay, up}, where down and up indicates the normalized price (more on this below) went down 1% or more and up 1% or more, respectively. stay indicates the stock remained within 1%.
The steps are:
Compare close price and open price
Compute price features using analytics functions
Compute normalized price change (%)
Join with S&P 500 table
Create labels (up, down, stay)
<h3><font color="#4885ed">Compare close price and open price</font> </h3>
For each row, get the close price of yesterday and the open price of tomorrow using the LAG function. We will determine tomorrow's close - today's close.
Shift to get tomorrow's close price.
Learning objective 1
End of explanation
%%with_globals print
%%bigquery --project {PROJECT}
SELECT
AVG(close) AS avg_close,
AVG(tomorrow_close) AS avg_tomo_close,
AVG(tomorrow_close) - AVG(close) AS avg_change,
COUNT(*) cnt
FROM
stock_market.price_history_delta
Explanation: The stock market is going up on average.
Learning objective 2
End of explanation
def get_window_fxn(agg_fxn, n_days):
Generate a time-series feature.
E.g., Compute the average of the price over the past 5 days.
SCALE_VALUE = "close"
sql =
({agg_fxn}(close) OVER (PARTITION BY symbol
ORDER BY Date
ROWS BETWEEN {n_days} PRECEDING AND 1 PRECEDING))/{scale}
AS close_{agg_fxn}_prior_{n_days}_days.format(
agg_fxn=agg_fxn, n_days=n_days, scale=SCALE_VALUE
)
return sql
WEEK = 5
MONTH = 20
YEAR = 52 * 5
agg_funcs = ("MIN", "MAX", "AVG", "STDDEV")
lookbacks = (WEEK, MONTH, YEAR)
sqls = []
for fxn in agg_funcs:
for lookback in lookbacks:
sqls.append(get_window_fxn(fxn, lookback))
time_series_features_sql = ",".join(sqls) # SQL string.
def preview_query():
print(time_series_features_sql[0:1000])
preview_query()
%%with_globals print
%%bigquery --project {PROJECT}
CREATE OR REPLACE TABLE stock_market.price_features_delta
AS
SELECT *
FROM
(SELECT *,
{time_series_features_sql},
-- Also get the raw time-series values; will be useful for the RNN model.
(ARRAY_AGG(close) OVER (PARTITION BY symbol
ORDER BY Date
ROWS BETWEEN 260 PRECEDING AND 1 PRECEDING))
AS close_values_prior_260,
ROW_NUMBER() OVER (PARTITION BY symbol ORDER BY Date) AS days_on_market
FROM stock_market.price_history_delta)
WHERE days_on_market > {YEAR}
%%bigquery --project {PROJECT}
SELECT *
FROM stock_market.price_features_delta
ORDER BY symbol, Date
LIMIT 10
Explanation: Add time series features
<h3><font color="#4885ed">Compute price features using analytics functions</font> </h3>
In addition, we will also build time-series features using the min, max, mean, and std (can you think of any over functions to use?). To do this, let's use analytic functions in BigQuery (also known as window functions).
An analytic function is a function that computes aggregate values over a group of rows. Unlike aggregate functions, which return a single aggregate value for a group of rows, analytic functions return a single value for each row by computing the function over a group of input rows.
Using the AVG analytic function, we can compute the average close price of a given symbol over the past week (5 business days):
python
(AVG(close) OVER (PARTITION BY symbol
ORDER BY Date
ROWS BETWEEN 5 PRECEDING AND 1 PRECEDING)) / close
AS close_avg_prior_5_days
Learning objective 1
End of explanation
scaled_change = (50.59 - 50.69) / 50.69
scaled_s_p = (939.38 - 930.09) / 930.09
normalized_change = scaled_change - scaled_s_p
print(
scaled change: {:2.3f}
scaled_s_p: {:2.3f}
normalized_change: {:2.3f}
.format(
scaled_change, scaled_s_p, normalized_change
)
)
Explanation: Compute percentage change, then self join with prices from S&P index.
We will also compute price change of S&P index, GSPC. We do this so we can compute the normalized percentage change.
<h3><font color="#4885ed">Compute normalized price change (%)</font> </h3>
Before we can create our labels we need to normalize the price change using the S&P 500 index. The normalization using the S&P index fund helps ensure that the future price of a stock is not due to larger market effects. Normalization helps us isolate the factors contributing to the performance of a stock_market.
Let's use the normalization scheme from by subtracting the scaled difference in the S&P 500 index during the same time period.
In Python:
```python
Example calculation.
scaled_change = (50.59 - 50.69) / 50.69
scaled_s_p = (939.38 - 930.09) / 930.09
normalized_change = scaled_change - scaled_s_p
assert normalized_change == ~1.2%
```
End of explanation
snp500_index = "gspc"
%%with_globals print
%%bigquery --project {PROJECT}
CREATE OR REPLACE TABLE stock_market.price_features_norm_per_change
AS
WITH
all_percent_changes AS
(
SELECT *, (tomo_close_m_close / Close) AS scaled_change
FROM `stock_market.price_features_delta`
),
s_p_changes AS
(SELECT
scaled_change AS s_p_scaled_change,
date
FROM all_percent_changes
WHERE symbol="{snp500_index}")
SELECT all_percent_changes.*,
s_p_scaled_change,
(scaled_change - s_p_scaled_change)
AS normalized_change
FROM
all_percent_changes LEFT JOIN s_p_changes
--# Add S&P change to all rows
ON all_percent_changes.date = s_p_changes.date
Explanation: Compute normalized price change (shown above).
Let's join scaled price change (tomorrow_close / close) with the gspc symbol (symbol for the S&P index). Then we can normalize using the scheme described above.
Learning objective 3
End of explanation
%%with_globals print
%%bigquery df --project {PROJECT}
SELECT *
FROM stock_market.price_features_norm_per_change
LIMIT 10
df.head()
Explanation: Verify results
End of explanation
down_thresh = -0.01
up_thresh = 0.01
%%with_globals print
%%bigquery df --project {PROJECT}
CREATE OR REPLACE TABLE stock_market.percent_change_sp500
AS
SELECT *,
CASE WHEN normalized_change < {down_thresh} THEN 'DOWN'
WHEN normalized_change > {up_thresh} THEN 'UP'
ELSE 'STAY'
END AS direction
FROM stock_market.price_features_norm_per_change features
INNER JOIN `stock_src.snp500`
USING (symbol)
%%with_globals print
%%bigquery --project {PROJECT}
SELECT direction, COUNT(*) as cnt
FROM stock_market.percent_change_sp500
GROUP BY direction
%%with_globals print
%%bigquery df --project {PROJECT}
SELECT *
FROM stock_market.percent_change_sp500
LIMIT 20
df.columns
Explanation: <h3><font color="#4885ed">Join with S&P 500 table and Create labels: {`up`, `down`, `stay`}</font> </h3>
Join the table with the list of S&P 500. This will allow us to limit our analysis to S&P 500 companies only.
Finally we can create labels. The following SQL statement should do:
sql
CASE WHEN normalized_change < -0.01 THEN 'DOWN'
WHEN normalized_change > 0.01 THEN 'UP'
ELSE 'STAY'
END
Learning objective 1
End of explanation
%%with_globals print
%%bigquery --project {PROJECT}
SELECT *
FROM `stock_src.eps`
LIMIT 10
Explanation: The dataset is still quite large and the majority of the days the market STAYs. Let's focus our analysis on dates where earnings per share (EPS) information is released by the companies. The EPS data has 3 key columns surprise, reported_EPS, and consensus_EPS:
End of explanation
%%with_globals print
%%bigquery --project {PROJECT}
CREATE OR REPLACE TABLE stock_market.eps_percent_change_sp500
AS
SELECT a.*, b.consensus_EPS, b.reported_EPS, b.surprise
FROM stock_market.percent_change_sp500 a
INNER JOIN `stock_src.eps` b
ON a.Date = b.date
AND a.symbol = b.symbol
%%with_globals print
%%bigquery --project {PROJECT}
SELECT *
FROM stock_market.eps_percent_change_sp500
LIMIT 5
%%with_globals print
%%bigquery --project {PROJECT}
SELECT direction, COUNT(*) as cnt
FROM stock_market.eps_percent_change_sp500
GROUP BY direction
Explanation: The surprise column indicates the difference between the expected (consensus expected eps by analysts) and the reported eps. We can join this table with our derived table to focus our analysis during earnings periods:
End of explanation
def get_aggregate_stats(field, round_digit=2):
Run SELECT ... GROUP BY field, rounding to nearest digit.
df = bq.query(
SELECT {field}, COUNT(*) as cnt
FROM
(SELECT ROUND({field}, {round_digit}) AS {field}
FROM stock_market.eps_percent_change_sp500) rounded_field
GROUP BY {field}
ORDER BY {field}.format(
field=field, round_digit=round_digit, PROJECT=PROJECT
)
).to_dataframe()
return df.dropna()
field = "close_AVG_prior_260_days"
CLIP_MIN, CLIP_MAX = 0.1, 4.0
df = get_aggregate_stats(field)
values = df[field].clip(CLIP_MIN, CLIP_MAX)
counts = 100 * df["cnt"] / df["cnt"].sum() # Percentage.
ax = values.hist(weights=counts, bins=30, figsize=(10, 5))
ax.set(xlabel=field, ylabel="%");
field = "normalized_change"
CLIP_MIN, CLIP_MAX = -0.1, 0.1
df = get_aggregate_stats(field, round_digit=3)
values = df[field].clip(CLIP_MIN, CLIP_MAX)
counts = 100 * df["cnt"] / df["cnt"].sum() # Percentage.
ax = values.hist(weights=counts, bins=50, figsize=(10, 5))
ax.set(xlabel=field, ylabel="%");
Explanation: Feature exploration
Now that we have created our recent movements of the company’s stock price, let's visualize our features. This will help us understand the data better and possibly spot errors we may have made during our calculations.
As a reminder, we calculated the scaled prices 1 week, 1 month, and 1 year before the date that we are predicting at.
Let's write a re-usable function for aggregating our features.
Learning objective 2
End of explanation
VALID_GROUPBY_KEYS = (
"DAYOFWEEK",
"DAY",
"DAYOFYEAR",
"WEEK",
"MONTH",
"QUARTER",
"YEAR",
)
DOW_MAPPING = {
1: "Sun",
2: "Mon",
3: "Tues",
4: "Wed",
5: "Thur",
6: "Fri",
7: "Sun",
}
def groupby_datetime(groupby_key, field):
if groupby_key not in VALID_GROUPBY_KEYS:
raise Exception("Please use a valid groupby_key.")
sql =
SELECT {groupby_key}, AVG({field}) as avg_{field}
FROM
(SELECT {field},
EXTRACT({groupby_key} FROM date) AS {groupby_key}
FROM stock_market.eps_percent_change_sp500) foo
GROUP BY {groupby_key}
ORDER BY {groupby_key} DESC.format(
groupby_key=groupby_key, field=field, PROJECT=PROJECT
)
print(sql)
df = bq.query(sql).to_dataframe()
if groupby_key == "DAYOFWEEK":
df.DAYOFWEEK = df.DAYOFWEEK.map(DOW_MAPPING)
return df.set_index(groupby_key).dropna()
field = "normalized_change"
df = groupby_datetime("DAYOFWEEK", field)
ax = df.plot(kind="barh", color="orange", alpha=0.7)
ax.grid(which="major", axis="y", linewidth=0)
field = "close"
df = groupby_datetime("DAYOFWEEK", field)
ax = df.plot(kind="barh", color="orange", alpha=0.7)
ax.grid(which="major", axis="y", linewidth=0)
field = "normalized_change"
df = groupby_datetime("MONTH", field)
ax = df.plot(kind="barh", color="blue", alpha=0.7)
ax.grid(which="major", axis="y", linewidth=0)
field = "normalized_change"
df = groupby_datetime("QUARTER", field)
ax = df.plot(kind="barh", color="green", alpha=0.7)
ax.grid(which="major", axis="y", linewidth=0)
field = "close"
df = groupby_datetime("YEAR", field)
ax = df.plot(kind="line", color="purple", alpha=0.7)
ax.grid(which="major", axis="y", linewidth=0)
field = "normalized_change"
df = groupby_datetime("YEAR", field)
ax = df.plot(kind="line", color="purple", alpha=0.7)
ax.grid(which="major", axis="y", linewidth=0)
Explanation: Let's look at results by day-of-week, month, etc.
End of explanation |
7,443 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Old version that was developed here (now probably out of sync with official version in PISA...)
Step1: Testing out a container class but that | Python Code:
print hash_obj([0, 1, 2])
bits = 64*2
n_elements = 200
np.log10(2*2**bits/(n_elements*(n_elements-1)))
Explanation: Old version that was developed here (now probably out of sync with official version in PISA...):
python
def hash_obj(obj):
hash_val, = struct.unpack('<q', hashlib.md5(
pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
).digest()[:8])
return hash_val
End of explanation
l = list(['zero', 'one', 'two'])
l.__getitem__(0)
[x for x in l.__iter__()]
l.__setitem__(1, 1)
print l
l.__getslice__(1,3)
l.__setslice__(1, 3, ('b', 'c'))
print l
from functools import total_ordering
from collections import OrderedDict
from pisa.core.param import Param, ParamSet
p0 = Param(name='c', value=1.5, prior=None, range=[1,2],
is_fixed=False, is_discrete=False, tex=r'\int{\rm c}')
p1 = Param(name='a', value=2.5, prior=None, range=[1,5],
is_fixed=False, is_discrete=False, tex=r'{\rm a}')
p2 = Param(name='b', value=1.5, prior=None, range=[1,2],
is_fixed=False, is_discrete=False, tex=r'{\rm b}')
c = ParamSet(p0, p1, p2)
print c.values
print c[0]
c[0].value = 1
print c.values
print c.tex
c.values = [3, 2, 1]
print c.values
print c.values[0]
print c[0].value
print 'priors:', c.priors
print 'names:', c.names
print c['a']
print c['a'].value
c['a'].value = 33
print c['a'].value
print c['c'].is_fixed
c['c'].is_fixed = True
print c['c'].is_fixed
print c.are_fixed
c.fix('c')
print c.are_fixed
c.unfix('a')
print c.are_fixed
c.unfix([0,1,2])
print c.are_fixed
fixed_params = c.fixed
print fixed_params.are_fixed
free_params = c.free
print free_params.are_fixed
print c.free.values
print c.values_hash
print c.fixed.values_hash
print c.free.values_hash
print c[0].state
print c.state_hash
print c.fixed.state_hash
print c.free.state_hash
print 'fixed:', c.fixed.names
print 'fixed, discrete:', c.fixed.discrete.names
print 'fixed, continuous:', c.fixed.continuous.names
print 'free:', c.free.names
print 'free, discrete:', c.free.discrete.names
print 'free, continuous:', c.free.continuous.names
print 'continuous, free:', c.continuous.free.names
print 'free, continuous hash:', c.free.continuous.values_hash
print 'continuous, free hash:', c.continuous.free.values_hash
print c.b.prior
print c.priors_llh
Explanation: Testing out a container class but that:
* c[0] = 1 assigns 1 to the object that lives at position 0
* c['aeff_scale'] = 1 has the same effect
* c returns values for all objects in c
* c.values does the same
* c.values[2:8] = [6, 1, 8, 9, 5] assigns those values to the values properties of the third through seventh entities in c
* c.priors returns priors for all objects in c
End of explanation |
7,444 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Galaxies that are missing from Simard+2011
Summary
* A total of 44 galaxies are not in galfit sample
* 31/44 are not in the SDSS catalog, so these would not have been targeted by Simard+2011
* this is not true because simard drew from phot catalog. Need to check all.
* 1 arcmin cutouts show
Step1: Galaxies not in SDSS phot catalog
Step2: Galaxies in SDSS but no B/T fit
Step3: Download SDSS Images
Step4: NSAID 69538 (244.060699, 34.258434)
http
Step5: NSAID 143514 (202.163284, 11.387049)
(too bright)
NSAID 163615 (202.697357, 11.200765)
(too bright)
NSAID 146832 (243.526657, 34.870651)
BINNED1 SATURATED INTERP COSMIC_RAY CHILD
(saturated)
NSAID 146875 (244.288803, 34.878895)
DEBLENDED_AT_EDGE BINNED1 NOTCHECKED INTERP CHILD EDGE
r = 13.92
(too bright)
NSAID 165409 (220.235657, 3.527517)
DEBLEND_NOPEAK INTERP_CENTER BINNED1 DEBLENDED_AS_PSF INTERP CHILD
r = 18.82
(deblended and too faint)
NSAID 166699 (241.500229, 22.641125)
BAD_MOVING_FIT MOVED BINNED1 INTERP COSMIC_RAY CHILD
r = 15.01, ext_r = 0.18
(not sure)
NSAID 146638 (241.287476, 17.729904)
STATIONARY BINNED1 SATURATED INTERP COSMIC_RAY CHILD
r = 13.57, ext_r = .13
(too bright, saturated)
NSAID 146659 (241.416641, 18.055758)
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
r = 14.52, ext_r = 0.14
(not sure)
NSAID 146664 (241.435760, 17.715572)
STATIONARY MOVED BINNED1 INTERP COSMIC_RAY CHILD
r = 14.65, ext_r = 0.13
(not sure)
not in simard
NSAID 140139 (175.954529, 19.968401)
DEBLEND_DEGENERATE PSF_FLUX_INTERP DEBLENDED_AT_EDGE BAD_MOVING_FIT MOVED BINNED1 INTERP COSMIC_RAY NODEBLEND CHILD BLENDED
r = 13.78, ext_r = 0.06
(too bright)
NSAID 140160 (176.071716, 20.223295)
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
r = 13.90, ext_r = 0.06
(too bright)
NSAID 140174 (176.204865, 19.795046)
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
r = 13.18, ext_r = 0.07
(too bright)
NSAID 140175 (176.195999, 20.125084)
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
r = 13.38, ext_r = 0.07
not in simard
NSAID 140187 (176.228104, 20.017143)
STATIONARY BINNED1 INTERP CHILD
r = 16.19, ext_r = 0.08
(not sure)
not in simard
NSAID 146094 (230.452133, 8.410197)
STATIONARY BINNED1 CHILD
r = 15.86, ext_r = 0.10
(not sure)
IN SIMARD!!!
NSAID 146121 (230.750824, 8.465475)
MOVED BINNED1 INTERP COSMIC_RAY CHILD
r = 15.80, ext_r = 0.09
NSAID 146127 (230.785812, 8.334576)
PSF_FLUX_INTERP INTERP_CENTER STATIONARY BINNED1 INTERP NOPETRO NODEBLEND CHILD BLENDED
r = 17.20, ext_r = 0.09
(blended?)
NSAID 146130 (230.800995, 8.549866)
BINNED1 INTERP COSMIC_RAY CHILD
r = 15.36, ext_r = 0.09
(not sure, maybe blended?)
NSAID 145965 (228.749756, 6.804669)
STATIONARY MOVED BINNED1 INTERP COSMIC_RAY NOPETRO CHILD
r = 16.70, ext_r = 0.10
(no petro)
NSAID 145984 (229.076614, 6.803605)
BINNED1 INTERP COSMIC_RAY CHILD
r = 15.72, ext_r = 0.1
(not sure)
NSAID 145998 (229.185364, 7.021626)
NSAID 145999 (229.187805, 7.055664)
NSAID 146012 (229.295181, 6.941795)
NSAID 146041 (229.713806, 6.435888)
NSAID 166042 (228.910904, 8.302397)
NSAID 166044 (228.936951, 6.958703)
NSAID 166083 (229.217957, 6.539137)
NSAID 142797 (195.073654, 27.955275)
NSAID 142819 (195.169479, 28.519848)
NSAID 142833 (195.214752, 28.042875)
NSAID 162838 (195.280670, 28.121592)
Oh No!
seems like galaxies that are in simard are not in my catalog | Python Code:
%run ~/Dropbox/pythonCode/LCSanalyzeblue.py
t = s.galfitflag & s.lirflag & s.sizeflag & ~s.agnflag & s.sbflag
galfitnogim = t & ~s.gim2dflag
sum(galfitnogim)
Explanation: Galaxies that are missing from Simard+2011
Summary
* A total of 44 galaxies are not in galfit sample
* 31/44 are not in the SDSS catalog, so these would not have been targeted by Simard+2011
* this is not true because simard drew from phot catalog. Need to check all.
* 1 arcmin cutouts show: 5 have a bright star overlapping or nearby the galaxy, 2
have a close companion.
* 69538 has problem with NSA coords
* 68342 - not in DR7 for some reason
By galaxy:
NSAID 70630 (202.306824, 11.275839)
STATIONARY BAD_MOVING_FIT BINNED1 INTERP COSMIC_RAY CHILD
r = 13.87 (too bright)
NSAID 70685 (202.269455, 12.238585)
DEBLENDED_AT_EDGE STATIONARY MOVED BINNED1 DEBLENDED_AS_PSF INTERP CHILD,
affected by point source that is offset from center of galaxy. might a foreground star.
(blended)
NSAID 43712 (244.129181, 35.708172)
BINNED1 INTERP COSMIC_RAY CHILD
r = 13.66 (too bright)
NSAID 69538 (244.060699, 34.258434)
NSA has problem with coords, chose nearby pt source rather than galaxy
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
r = 18.83 (too faint)
NSAID 18158 (219.578888, 3.639615)
PSF_FLUX_INTERP INTERP_CENTER BAD_MOVING_FIT BINNED1 NOTCHECKED SATURATED INTERP COSMIC_RAY CHILD
r = 15.31, ext_r = 0.11
(not sure)
NSAID 68283 (242.047577, 24.507439)
not in dr7?
NSAID 68286 (241.749313, 24.160772)
STATIONARY MOVED BINNED1 INTERP COSMIC_RAY NOPETRO NODEBLEND CHILD BLENDED PrimTarget
r = 17.66, ext_r = 0.2 (too faint)
NSAID 68299 (240.918945, 24.602676)
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
r = 15.4, ext_r = 0.2
(not sure) why this is not in simard
NSAID 68342 (241.297867, 24.960102)
does not come up under dr7 search. get nearby object instead
NSAID 113068 (175.995667, 20.077011)
STATIONARY MOVED BINNED1 INTERP COSMIC_RAY CHILD
r = 13.74, ext_r = 0.06 (too bright)
NSAID 72631 (230.999481, 8.508963)
MAYBE_CR BAD_MOVING_FIT MOVED BINNED1 INTERP CHILD
Type probably not 3
r = 16.98, ext_r = 0.1
NSAID 103927 (194.490204, 27.443319)
STATIONARY BINNED1 INTERP CHILD
r = 17.64, ext_r = 0.02 (maybe petro r is too faint?)
(too faint?)
NSAID 103966 (194.025421, 27.677467)
DEBLEND_DEGENERATE BAD_MOVING_FIT MOVED BINNED1 INTERP COSMIC_RAY NODEBLEND CHILD BLENDED
r = 15.13, ext_r = 0.02
(not sure) why this isn't in simard
End of explanation
s.s.ISDSS[galfitnogim]
print sum(s.s.ISDSS[galfitnogim] == -1)
Explanation: Galaxies not in SDSS phot catalog
End of explanation
galfitsdssnogim = galfitnogim & (s.s.ISDSS != -1)
sum(galfitsdssnogim)
s.s.NSAID[galfitsdssnogim]
Explanation: Galaxies in SDSS but no B/T fit
End of explanation
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.table import Table
try:
# Python 3.x
from urllib.parse import urlencode
from urllib.request import urlretrieve
except ImportError:
# Python 2.x
from urllib import urlencode
from urllib import urlretrieve
import IPython.display
r = 22.5 - 2.5*log10(s.s.NMGY[:,4])
flag = galfitnogim & (r >= 14.) & (r <= 18.)
print sum(flag)
ra = s.s.RA[flag]
dec = s.s.DEC[flag]
ids = s.s.NSAID[flag]
coords = SkyCoord(ra*u.deg, dec*u.deg, frame='icrs')
testcoord = coords[0]
impix = 100
imsize = 1*u.arcmin
cutoutbaseurl = 'http://skyservice.pha.jhu.edu/DR12/ImgCutout/getjpeg.aspx'
for i in range(len(coords.ra)):
query_string = urlencode(dict(ra=coords[i].ra.deg,
dec=coords[i].dec.deg,
width=impix, height=impix,
scale=imsize.to(u.arcsec).value/impix))
url = cutoutbaseurl + '?' + query_string
# this downloads the image to your disk
urlretrieve(url, 'images/'+str(ids[i])+'_SDSS_cutout.jpg')
print 'NSAID %i (%10.6f, %10.6f)'%(ids[i],ra[i],dec[i])
t = IPython.display.Image('images/'+str(ids[i])+'_SDSS_cutout.jpg')
IPython.display.display(t)
for i in range(10,len(ids)):
print '* NSAID %i (%10.6f, %10.6f)'%(ids[i],ra[i],dec[i])
print 'http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=%.5f&dec=%.5f'%(ra[i],dec[i])
Explanation: Download SDSS Images
End of explanation
for i in range(len(coords.ra)):
query_string = urlencode(dict(ra=coords[i].ra.deg,
dec=coords[i].dec.deg,
width=impix, height=impix,
scale=imsize.to(u.arcsec).value/impix))
url = cutoutbaseurl + '?' + query_string
# this downloads the image to your disk
urlretrieve(url, 'images/'+str(nsaids[i])+'_SDSS_cutout.jpg')
print i, nsaids[i],coords[i].ra,coords[i].dec
print 'NSAID %i (%10.6f, %10.6f)'%(nsaids[i],coords[i].ra.deg,coords[i].dec)
t = IPython.display.Image('images/'+str(nsaids[i])+'_SDSS_cutout.jpg')
IPython.display.display(t)
for i in range(len(coords.ra)):
print 'NSAID %i (%10.6f, %10.6f)'%(ids[i],ra[i],dec[i])
ids = where(galfitnogim & (s.s.ISDSS == -1))
print ids
Explanation: NSAID 69538 (244.060699, 34.258434)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=244.06070&dec=34.25843
too faint according to DR7 catalog
NSAID 18158 (219.578888, 3.639615)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=219.57889&dec=3.63961
PSF_FLUX_INTERP INTERP_CENTER BAD_MOVING_FIT BINNED1 NOTCHECKED SATURATED INTERP COSMIC_RAY CHILD
(saturated)
NSAID 165409 (220.235657, 3.527517)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=220.23566&dec=3.52752
DEBLEND_NOPEAK INTERP_CENTER BINNED1 DEBLENDED_AS_PSF INTERP CHILD
(blended)
NSAID 68283 (242.047577, 24.507439)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=242.04758&dec=24.50744
not in DR7
NSAID 68286 (241.749313, 24.160772)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=241.74931&dec=24.16077
STATIONARY MOVED BINNED1 INTERP COSMIC_RAY NOPETRO NODEBLEND CHILD BLENDED
NOT IN SIMARD
(too faint maybe?)
NSAID 68299 (240.918945, 24.602676)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=240.91895&dec=24.60268
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
(not sure)
NOT IN SIMARD
NSAID 68342 (241.297867, 24.960102)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=241.29787&dec=24.96010
TOO_FEW_GOOD_DETECTIONS PSF_FLUX_INTERP INTERP_CENTER BINNED1 DEBLENDED_AS_PSF INTERP NOPETRO CHILD
BAD COORDS in DR7? Image on website above does not match with galaxy.
NSAID 166124 (230.213974, 8.623065)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=230.21397&dec=8.62306
BINNED1 INTERP CHILD
NOT IN SIMARD CAT
(not sure)
NSAID 146012 (229.295181, 6.941795)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=229.29518&dec=6.94179
BINNED1 NOTCHECKED SATURATED INTERP COSMIC_RAY CHILD
(saturated)
NSAID 166042 (228.910904, 8.302397)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=228.91090&dec=8.30240
DEBLEND_DEGENERATE PSF_FLUX_INTERP BAD_MOVING_FIT MOVED BINNED1 INTERP COSMIC_RAY NODEBLEND CHILD BLENDED
NOT IN SIMARD
(not sure)
NSAID 142819 (195.169479, 28.519848)
http://cas.sdss.org/dr7/en/tools/explore/obj.asp?ra=195.16948&dec=28.51985
DEBLENDED_AT_EDGE BAD_MOVING_FIT BINNED1 DEBLENDED_AS_PSF NOTCHECKED INTERP NODEBLEND CHILD BLENDED EDGE
(too faint, blended)
End of explanation
lcs = fits.getdata('/Users/rfinn/research/LocalClusters/NSAmastertables/LCS_all_size.fits')
gim = fits.getdata('/Users/rfinn/research/SimardSDSS2011/table1.fits')virgocat = SkyCoord(vdat.RA*u.degree,vdat.DEC*u.degree,frame='icrs')
from astropy.coordinates import SkyCoord
from astropy import units as u
%matplotlib inline
lcat = SkyCoord(lcs.RA*u.degree,lcs.DEC*u.degree,frame='icrs')
gcat = SkyCoord(gim._RAJ2000*u.degree,gim._DEJ2000*u.degree,frame='icrs')
index,dist2d,dist3d = lcat.match_to_catalog_sky(gcat)
plt.figure()
plt.plot
# only keep matches with matched RA and Dec w/in 1 arcsec
matchflag = dist2d.degree < 3./3600
matchedarray1=np.zeros(len(lcat),dtype=gim.dtype)
matchedarray1[matchflag] = gim[index[matchflag]]
print 'percent of LCS galaxies matched = %.1f'%(sum(matchflag)*1./len(matchflag)*100.)
# get rid of names that start with __
# these cause trouble in the analysis program
t = []
for a in matchedarray1.dtype.names:
t.append(a)
for i in range(len(t)):
if t[i].startswith('__'):
t[i] = t[i][2:]
t = tuple(t)
#print t
matchedarray1.dtype.names = t
outfile = '/Users/rfinn/research/LocalClusters/NSAmastertables/LCS_all.gim2d.tab1.fits'
fits.writeto(outfile,matchedarray1,overwrite=True)
diff = (lcs.B_T_r - matchedarray1['B_T_r'])
bad_matches = (abs(diff) > .01) & matchflag
print 'number of bad matches = ',sum(bad_matches)
s.s.NSAID[bad_matches]
plt.figure()
plt.plot(lcs.RA[bad_matches],lcs.DEC[bad_matches],'ko')
print lcs.CLUSTER[bad_matches]
print sum(s.galfitflag[bad_matches])
print sum(diff < 0.)
outfile = '/Users/rfinn/research/LocalClusters/NSAmastertables/LCS_all.gim2d.tab1.fits'
gdat = fits.getdata(outfile)
gdat.__B_T_r
Explanation: NSAID 143514 (202.163284, 11.387049)
(too bright)
NSAID 163615 (202.697357, 11.200765)
(too bright)
NSAID 146832 (243.526657, 34.870651)
BINNED1 SATURATED INTERP COSMIC_RAY CHILD
(saturated)
NSAID 146875 (244.288803, 34.878895)
DEBLENDED_AT_EDGE BINNED1 NOTCHECKED INTERP CHILD EDGE
r = 13.92
(too bright)
NSAID 165409 (220.235657, 3.527517)
DEBLEND_NOPEAK INTERP_CENTER BINNED1 DEBLENDED_AS_PSF INTERP CHILD
r = 18.82
(deblended and too faint)
NSAID 166699 (241.500229, 22.641125)
BAD_MOVING_FIT MOVED BINNED1 INTERP COSMIC_RAY CHILD
r = 15.01, ext_r = 0.18
(not sure)
NSAID 146638 (241.287476, 17.729904)
STATIONARY BINNED1 SATURATED INTERP COSMIC_RAY CHILD
r = 13.57, ext_r = .13
(too bright, saturated)
NSAID 146659 (241.416641, 18.055758)
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
r = 14.52, ext_r = 0.14
(not sure)
NSAID 146664 (241.435760, 17.715572)
STATIONARY MOVED BINNED1 INTERP COSMIC_RAY CHILD
r = 14.65, ext_r = 0.13
(not sure)
not in simard
NSAID 140139 (175.954529, 19.968401)
DEBLEND_DEGENERATE PSF_FLUX_INTERP DEBLENDED_AT_EDGE BAD_MOVING_FIT MOVED BINNED1 INTERP COSMIC_RAY NODEBLEND CHILD BLENDED
r = 13.78, ext_r = 0.06
(too bright)
NSAID 140160 (176.071716, 20.223295)
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
r = 13.90, ext_r = 0.06
(too bright)
NSAID 140174 (176.204865, 19.795046)
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
r = 13.18, ext_r = 0.07
(too bright)
NSAID 140175 (176.195999, 20.125084)
STATIONARY BINNED1 INTERP COSMIC_RAY CHILD
r = 13.38, ext_r = 0.07
not in simard
NSAID 140187 (176.228104, 20.017143)
STATIONARY BINNED1 INTERP CHILD
r = 16.19, ext_r = 0.08
(not sure)
not in simard
NSAID 146094 (230.452133, 8.410197)
STATIONARY BINNED1 CHILD
r = 15.86, ext_r = 0.10
(not sure)
IN SIMARD!!!
NSAID 146121 (230.750824, 8.465475)
MOVED BINNED1 INTERP COSMIC_RAY CHILD
r = 15.80, ext_r = 0.09
NSAID 146127 (230.785812, 8.334576)
PSF_FLUX_INTERP INTERP_CENTER STATIONARY BINNED1 INTERP NOPETRO NODEBLEND CHILD BLENDED
r = 17.20, ext_r = 0.09
(blended?)
NSAID 146130 (230.800995, 8.549866)
BINNED1 INTERP COSMIC_RAY CHILD
r = 15.36, ext_r = 0.09
(not sure, maybe blended?)
NSAID 145965 (228.749756, 6.804669)
STATIONARY MOVED BINNED1 INTERP COSMIC_RAY NOPETRO CHILD
r = 16.70, ext_r = 0.10
(no petro)
NSAID 145984 (229.076614, 6.803605)
BINNED1 INTERP COSMIC_RAY CHILD
r = 15.72, ext_r = 0.1
(not sure)
NSAID 145998 (229.185364, 7.021626)
NSAID 145999 (229.187805, 7.055664)
NSAID 146012 (229.295181, 6.941795)
NSAID 146041 (229.713806, 6.435888)
NSAID 166042 (228.910904, 8.302397)
NSAID 166044 (228.936951, 6.958703)
NSAID 166083 (229.217957, 6.539137)
NSAID 142797 (195.073654, 27.955275)
NSAID 142819 (195.169479, 28.519848)
NSAID 142833 (195.214752, 28.042875)
NSAID 162838 (195.280670, 28.121592)
Oh No!
seems like galaxies that are in simard are not in my catalog :(
Going to read in my catalog
read in simard catalog
match them
and then see what's going on
End of explanation |
7,445 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1.9 查找两字典的相同点
怎样在两字典中寻找相同点(相同的key or 相同的 value)
Step1: 为寻找两字典的相同点 可通过简单的在两字典keys() or items() method 中Return 结果 进行set 操作
Step2: 以上操作亦可用于修改or过滤dict element <br> if you want 以现有dict 来构造一个排除指定key的new dict 下面利用dict 推到来实现 this 需求
Step3: 当然 'w'并没有出现在a中 就算for 上也无大碍
一个dict 即 a key and value 's set 的映射关系<br>dict 的 keys() method to Return a 展现 key set 's key view object
键视图 (dict.keys())
支持set 操作 比如 并 交 差运算 【这样 就不用将key 转换成set】
元素视图 (dict.items())
支持set运算
值视图 (dict.values()
不支持set 运算 若是需要set操作 【这样 就需要将value 转换成set】
1.10 删除序列相同元素并保持顺序
怎样在一个序列上保持顺序的同时并消除重复的值
if sequence 上的value 都是 hashalbe 类型 则可利用set or generator 来实现
Step4: 上述方法仅仅在sequence 中element 属于hashable (不能改变其顺序 同时其存储结构亦不可改变)
Step5: 这里key args 指定一个函数 将sequence element 转换成 hashable 类型
Step6: 若是仅仅为了除重 将之转化成set类型即可
Step7: 不过这样即会使元素本身顺序改变 生成的结果中element 位置被打乱<br>使用generator 可让函数更加通用 以下是对文件本身进行消除重复行
Step8: 本身somefile 中有10行zlxs 结果显示一行<br>key 函数 模仿了 sorted min max 函数内置函数的类似功能 key 多了这个以lambda 匿名函数的大力帮助
1.11 命名切片
你的程序已经出现一大堆无法直视的硬编码切片下标
Step9: 提高代码的可读性与可维护性
Step10: 此时a是一个slice object 可以分别调用 start stop step
Step11: 序列出现次数最多的元素
怎么找出序列中的出现次数的元素
collections.Counter 类即专门为此类问题设计 同时拥有most_common 方法直接获得
Step12: 作为输入 Counter对象可接受任意的hashable sequence 对象 在底层实现上,一个Counter 对象即为一个dict 将element 映射到他出现的次数上
Step13: 若是又有另一个dict中的words 若是想加上计算其中的频率
Step14: 上述示例中morewords还有eyes单词 所以 利用for循环 可利用Counter对象再次计算 还可以使用update method
Step15: Counter instance 是一个鲜为人知的特性 可与数学运算操作结合 | Python Code:
a = {
'x':1,
'y':2,
'z':3
}
b = {
'w':10,
'x':11,
'y':2
}
# In a ::: x : 1 ,y : 2
# In b ::: x : 11,y : 2
Explanation: 1.9 查找两字典的相同点
怎样在两字典中寻找相同点(相同的key or 相同的 value)
End of explanation
# Find keys in common
kc = a.keys() & b.keys()
print('a 和 b 共有的键',kc)
# Find keys in a that are not in b
knb = a.keys() - b.keys()
print('a 有的键 而 b 没有的键',knb)
# Find (key value) pair in common
kv = a.items() & b.items()
print('a 和 b 共有的元素',kv)
Explanation: 为寻找两字典的相同点 可通过简单的在两字典keys() or items() method 中Return 结果 进行set 操作
End of explanation
# Make a new dictionary with certain keys remove
c = {key : a[key] for key in a.keys() - {'z','w'}}
# c 排除Le {'z' and 'w'}对应的value
print(c)
Explanation: 以上操作亦可用于修改or过滤dict element <br> if you want 以现有dict 来构造一个排除指定key的new dict 下面利用dict 推到来实现 this 需求
End of explanation
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
a = [1,3,5,6,7,8,1,5,1,10]
list(dedupe(a))
len(a)- len(_)
Explanation: 当然 'w'并没有出现在a中 就算for 上也无大碍
一个dict 即 a key and value 's set 的映射关系<br>dict 的 keys() method to Return a 展现 key set 's key view object
键视图 (dict.keys())
支持set 操作 比如 并 交 差运算 【这样 就不用将key 转换成set】
元素视图 (dict.items())
支持set运算
值视图 (dict.values()
不支持set 运算 若是需要set操作 【这样 就需要将value 转换成set】
1.10 删除序列相同元素并保持顺序
怎样在一个序列上保持顺序的同时并消除重复的值
if sequence 上的value 都是 hashalbe 类型 则可利用set or generator 来实现
End of explanation
def dedupe2(items,key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
Explanation: 上述方法仅仅在sequence 中element 属于hashable (不能改变其顺序 同时其存储结构亦不可改变)
End of explanation
b = [{'x':1,'y':2},{'x':1,'y':3},{'x':1,'y':2},{'x':1,'y':4}]
bd = list(dedupe2(b,key=lambda d: (d['x'],d['y'])))
bd2 = list(dedupe2(b,key=lambda d: (d['x'])))
print('删除满足重复的d[\'x\'],d[\'y\']格式的元素')
bd
# 因为以上格式而又不重复的即为此3 其中{'x':1,'y':2}重复了两次 则被删除
print('删除满足重复的d[\'x\']格式的元素')
bd2
# 因为以上格式而又不重复的即为此2 b中所有元素 都是以{'x': 1开始的 所以返回第一个element
Explanation: 这里key args 指定一个函数 将sequence element 转换成 hashable 类型
End of explanation
ra = [1,1,1,1,1,1,1]
set(ra)
Explanation: 若是仅仅为了除重 将之转化成set类型即可
End of explanation
with open('somefile.txt','r') as f:
for line in dedupe2(f):
print(line)
Explanation: 不过这样即会使元素本身顺序改变 生成的结果中element 位置被打乱<br>使用generator 可让函数更加通用 以下是对文件本身进行消除重复行
End of explanation
ns = ''
for nn in range(10):
ns += str(nn)
ns = ns*3
Explanation: 本身somefile 中有10行zlxs 结果显示一行<br>key 函数 模仿了 sorted min max 函数内置函数的类似功能 key 多了这个以lambda 匿名函数的大力帮助
1.11 命名切片
你的程序已经出现一大堆无法直视的硬编码切片下标
End of explanation
items = [1,2,3,4,5,6,7,8,9]
a = slice(2,4)
items[2:4]
items[a]
items[a] =[10,11]
items
del items[a]
items
Explanation: 提高代码的可读性与可维护性
End of explanation
s = slice(5,10,2)
print('s 起始',s.start)
print('s 终末',s.stop)
print('s 公差',s.step)
st = 'helloworld'
a.indices(len(s))
Explanation: 此时a是一个slice object 可以分别调用 start stop step
End of explanation
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
# 找出words 中 出现频率最高的单词
from collections import Counter
word_counts = Counter(words)
# 出现频率最高德3个单词
top_three = word_counts.most_common(3)
print(top_three)
Explanation: 序列出现次数最多的元素
怎么找出序列中的出现次数的元素
collections.Counter 类即专门为此类问题设计 同时拥有most_common 方法直接获得
End of explanation
word_counts['not']
word_counts['eyes']
Explanation: 作为输入 Counter对象可接受任意的hashable sequence 对象 在底层实现上,一个Counter 对象即为一个dict 将element 映射到他出现的次数上
End of explanation
morewords = ['why','are','you','looking','in','eyes']
for word in morewords:
word_counts[word] += 1
word_counts['eyes']
Explanation: 若是又有另一个dict中的words 若是想加上计算其中的频率
End of explanation
word_counts.update(morewords)
word_counts['eyes']
Explanation: 上述示例中morewords还有eyes单词 所以 利用for循环 可利用Counter对象再次计算 还可以使用update method
End of explanation
a = Counter(words)
b = Counter(morewords)
a
b
# combine counts
# 合并
c = a + b
print(c)
# Subtract counts
# 减取
d = a -b
print(d)
Explanation: Counter instance 是一个鲜为人知的特性 可与数学运算操作结合
End of explanation |
7,446 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Purchase frequency
In this notebook we create a table grouping transaction information by customers’ purchase frequency. This is done with functions from the pandas librairie such as df.groupby() and df.cut().
Step1: Query data into Contiamo
Step2: Select data from march 2017
Step3: Create an intermediate table
Step4: Create final table | Python Code:
import pandas as pd
import contiamo
Explanation: Purchase frequency
In this notebook we create a table grouping transaction information by customers’ purchase frequency. This is done with functions from the pandas librairie such as df.groupby() and df.cut().
End of explanation
transactions = %contiamo query query:sql:48590597:411:g71GXzJjsx4Uvad11ouKjoYbQUNNPy-qRMKkBNZfyx4
customers = %contiamo query query:sql:48590597:441:MG5W2dMjXzYgsHsgdQYzmhv44dxEQX2Lodu5Uh2Hx_s
applications = %contiamo query query:sql:48590597:442:-gz3nbw1fdmtSXkD4zGNA-cVa7s6sQtRn8upCSn6uys
Explanation: Query data into Contiamo
End of explanation
transactions = transactions.loc[(transactions['Field transaction date date'] <= 20170331) & (transactions['Field transaction date date'] >= 20170301)]
df = pd.DataFrame({
'customer_id' : transactions['Field customer id'],
'revenue' : pd.to_numeric(transactions['Field app price']),
'n_of_purchases' : [1]*len(transactions)
})
df.head()
Explanation: Select data from march 2017
End of explanation
total_users = df['customer_id'].nunique()
#Grouping by customer id
pf = df.groupby('customer_id').agg({
'revenue' : 'sum',
'n_of_purchases' : 'sum'
}).reset_index()
#Selection of data to create 'No. of Purchases', 'No. of UAUs'and 'Total Revenue'columns
x = pf.groupby('n_of_purchases').agg({
'customer_id': 'size',
'revenue' : 'sum',
})
x = x.reset_index()
#Renaming columns
x.rename(columns = {'customer_id': 'n_of_users'}, inplace=True)
#Creation of '% of Total UAUs' and 'Total transations'columns
x['percentage_of_users'] = 100 * x['n_of_users'] / total_users
x['total_transactions'] = x['n_of_purchases'] * x['n_of_users']
#Creation of 'No. of Purchases' buckets
x['n_of_purchases'] = pd.cut(x['n_of_purchases'], bins=[0,1,2,3,5,8,13,21,34,55,float('inf')])
x.head()
Explanation: Create an intermediate table
End of explanation
#Grouping data by 'No. of Purchases' buckets
y = x.groupby('n_of_purchases').agg({
'revenue': 'sum',
'n_of_users': 'sum',
'percentage_of_users' : 'sum',
'total_transactions': 'sum',
})
y = y.reset_index()
#Creation of 'Average revenue per user' and 'Average transaction price' colums
y['average_revenue_per_user'] = y['revenue'] / y['n_of_users']
y['average_transaction_price'] = y['revenue'] / y['total_transactions']
#Putting the colums in the right order
cols = ['n_of_purchases','n_of_users', 'percentage_of_users', 'revenue', 'average_revenue_per_user', 'total_transactions', 'average_transaction_price']
y = y[cols]
#Renaming the 'No. of Purchases' buckets
y['n_of_purchases']=y['n_of_purchases'].astype(str)
y = y.replace({'n_of_purchases': {
'(0, 1]': '1',
'(1, 2]' : '2',
'(2, 3]' : '3',
'(3, 5]' : '4-5',
'(5, 8]' : '6-8',
'(8, 13]' : '9-13',
'(13, 21]' : '14-21',
'(21, 34]' : '22-34',
'(34, 55]' : '35-55',
'(55, inf]' : 'Above 55',
}})
y
Explanation: Create final table
End of explanation |
7,447 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: CMU Mocap Database
Motion capture data from the CMU motion capture data base (CMU Motion
Capture Lab, 2003).
You can download any subject and motion from the data set. Here we will
download motions 02 and 21 from subject 16.
Step2: The data dictionary contains the keys ‘Y’ and ‘skel,’ which represent
the data and the skeleton..
Step3: And extra information about the data is included, as standard, under the
keys info and details.
Step4: Fit GP-LVM
The original data has the figure moving across the floor during the
motion capture sequence. We can make the figure walk ‘in place,’ by
setting the x, y, z positions of the root node to zero. This makes it
easier to visualize the result.
Step5: We can also remove the mean of the data.
Step6: Now we create the GP-LVM model.
Step7: Now we optimize the model.
Step8: Plotting the skeleton | Python Code:
import matplotlib.pyplot as plt
plt.style.use("seaborn-pastel")
%%capture
%pip install --upgrade git+https://github.com/lawrennd/ods
%pip install --upgrade git+https://github.com/SheffieldML/GPy.git
import GPy, pods
import numpy as np
np.random.seed(42)
Explanation: <a href="https://colab.research.google.com/github/probml/probml-notebooks/blob/main/notebooks/gplvm_mocap.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Gaussian proceess latent variable model for motion capture data
http://inverseprobability.com/gpy-gallery/gallery/cmu-mocap-gplvm
Author: Aditya Ravuri
Setup
End of explanation
subject = "16"
motion = ["02", "21"]
data = pods.datasets.cmu_mocap(subject, motion)
Explanation: CMU Mocap Database
Motion capture data from the CMU motion capture data base (CMU Motion
Capture Lab, 2003).
You can download any subject and motion from the data set. Here we will
download motions 02 and 21 from subject 16.
End of explanation
data["Y"].shape
print(data["citation"])
Explanation: The data dictionary contains the keys ‘Y’ and ‘skel,’ which represent
the data and the skeleton..
End of explanation
print(data["info"])
print(data["details"])
Explanation: And extra information about the data is included, as standard, under the
keys info and details.
End of explanation
# Make figure move in place.
data["Y"][:, 0:3] = 0.0
Explanation: Fit GP-LVM
The original data has the figure moving across the floor during the
motion capture sequence. We can make the figure walk ‘in place,’ by
setting the x, y, z positions of the root node to zero. This makes it
easier to visualize the result.
End of explanation
Y = data["Y"]
Explanation: We can also remove the mean of the data.
End of explanation
model = GPy.models.GPLVM(Y, 2, init="PCA", normalizer=True)
Explanation: Now we create the GP-LVM model.
End of explanation
model.optimize(optimizer="lbfgs", messages=True, max_f_eval=1e4, max_iters=1e4)
Explanation: Now we optimize the model.
End of explanation
%matplotlib inline
def plot_skeleton(ax, Y_vec):
Z = data["skel"].to_xyz(Y_vec)
ax.scatter(Z[:, 0], Z[:, 2], Z[:, 1], marker=".", color="b")
connect = data["skel"].connection_matrix() # Get the connectivity matrix.
I, J = np.nonzero(connect)
xyz = np.zeros((len(I) * 3, 3))
idx = 0
for i, j in zip(I, J):
xyz[idx] = Z[i, :]
xyz[idx + 1] = Z[j, :]
xyz[idx + 2] = [np.nan] * 3
idx += 3
line_handle = ax.plot(xyz[:, 0], xyz[:, 2], xyz[:, 1], "-", color="b")
ax.set_xlim(-15, 15)
ax.set_ylim(-15, 15)
ax.set_zlim(-15, 15)
ax.set_yticks([])
ax.set_xticks([])
ax.set_zticks([])
plt.tight_layout()
# fig = plt.figure(figsize=(7,2.5))
fig = plt.figure(figsize=(14, 5))
ax_a = fig.add_subplot(131)
ax_a.set_title("Latent Space")
n = len(Y)
idx_a = 51 # jumping
idx_b = 180 # standing
other_indices = np.arange(n)[~np.isin(range(n), [idx_a, idx_b])]
jump = np.arange(n)[data["lbls"][:, 0] == 1]
walk = np.arange(n)[data["lbls"][:, 0] == 0]
jump = jump[jump != idx_a]
walk = walk[walk != idx_b]
ax_a.scatter(model.X[jump, 0], model.X[jump, 1], label="jumping motion")
ax_a.scatter(model.X[walk, 0], model.X[walk, 1], label="walking motion")
ax_a.scatter(model.X[idx_a, 0], model.X[idx_a, 1], label="Pose A", marker="^", s=150, c="red")
ax_a.scatter(model.X[idx_b, 0], model.X[idx_b, 1], label="Pose B", marker="+", s=150, c="red")
ax_a.legend(loc="lower left") # , fontsize='x-small')
plt.tight_layout()
ax_b = fig.add_subplot(132, projection="3d")
plot_skeleton(ax_b, Y[idx_a, :])
ax_b.set_title("Pose A")
ax_c = fig.add_subplot(133, projection="3d")
plot_skeleton(ax_c, Y[idx_b, :])
ax_c.set_title("Pose B")
# print(fig)
plt.savefig("gplvm-mocap.pdf")
plt.show()
Explanation: Plotting the skeleton
End of explanation |
7,448 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cookbook
Step1: Import Python libraries
The call to %matplotlib inline here enables support for plotting directly inside the notebook.
Step2: Quick guide (tldr;)
The following cell shows the quickest way to results. Further explanation of all of the features and options is provided further below.
Step3: Full guide
In the most common use you'll want to plot the first two PCs, then inspect the output, remove any obvious outliers, and then redo the pca. It's often desirable to import a vcf file directly rather than to use the ipyrad assembly, so here we'll demonstrate this.
Step4: Here we can just load the vcf file directly into the pca analysis module. Then ask for the samples in samples_vcforder, which is the order in which they are written in the vcf.
Step5: Now construct the default plot, which shows all samples and PCs 1 and 2. By default all samples are assigned to one population, so everything will be the same color.
Step6: Population assignment for sample colors
In the tl;dr example the assembly of our simulated data had included a pop_assign_file so the pca() was smart enough to find this and color samples accordingly. In some cases you might not have used a pops file, so it's also possible to specify population assignments in a dictionary. The format of the dictionary should have populations as keys and lists of samples as values. Sample names need to be identical to the names in the vcf file, which we can verify with the samples_vcforder property of the pca object.
Step7: This is just much nicer looking now, and it's also much more straightforward to interpret.
Removing "bad" samples and replotting.
In PC analysis, it's common for "bad" samples to dominate several of the first PCs, and thus "pop out" in a degenerate looking way. Bad samples of this kind can often be attributed to poor sequence quality or sample misidentifcation. Samples with lots of missing data tend to pop way out on their own, causing distortion in the signal in the PCs. Normally it's best to evaluate the quality of the sample, and if it can be seen to be of poor quality, to remove it and replot the PCA. The Pedicularis dataset is actually very nice, and clean, but for the sake of demonstration lets imagine the cyathophylloides samples are "bad samples".
We can see that the cyathophylloides samples have particularly high values of PC2, so we can target them for removal in this way.
Step8: Inspecting PCs directly
At any time after calling plot() you can inspect the PCs for all the samples using the pca.pcs property. The PC values are saved internally in a convenient pandas dataframe format.
Step9: Looking at PCs other than 1 & 2
PCs 1 and 2 by definition explain the most variation in the data, but sometimes PCs further down the chain can also be useful and informative. The plot function makes it simple to ask for PCs directly.
Step10: It's nice to see PCs 1-4 here, but it's kind of stupid to plot the legend twice, so we can just turn off the legend on the first plot.
Step11: Controlling colors
You might notice the default color scheme is unobtrusive, but perhaps not to your liking. There are two ways of modifying the color scheme, one simple and one more complicated, but which gives extremely fine grained control over colors.
Colors for the more complicated method can be specified according to python color conventions. I find this visual page of python color names useful.
Step12: Dealing with missing data
RAD-seq datasets are often characterized by moderate to high levels of missing data. While there may be many thousands or tens of thousands of loci recovered overall, the number of loci that are recovered in all sequenced samples is often quite small. The distribution of depth of coverage per locus is a complicated function of the size of the genome of the focal organism, the restriction enzyme(s) used, the size selection tolerances, and the sequencing effort.
Both model-based (STRUCTURE and the like) and model-free (PCA/sNMF/etc) genetic "clustering" methods are sensitive to missing data. Light to moderate missing data that is distributed randomly among samples is often not enough to seriously impact the results. These are, after all, only exploratory methods. However, if missing data is biased in some way then it can distort the number of inferred populations and/or the relationships among these. For example, if several unrelated samples recover relatively few loci, for whatever reason (mistakes during library prep, failed sequencing, etc), clustering methods may erroniously identify this as true "similarity" with respect to the rest of the samples, and create spurious clusters.
In the end, all these methods must do something with sites that are uncalled in some samples. Some methods adopt a strategy of silently asigning missing sites the "Reference" base. Others, assign missing sites the average base.
There are several ways of dealing with this
Step13: This is useful, but it doesn't give us a clear direction for how to go about dealing with the missingness. One way to reduce missing data is to reduce the tolerance for samples ungenotyped at a snp. The other way to reduce missing data is to remove samples with very poor sequencing. To this end, the .missingness() function will show a table of number of retained snps for various of these conditions.
Step14: Here the columns indicate progressive removal of the samples with the fewest number of snps. So "Full" indicates retention of all samples. "2E_0" shows # snps after removing this sample (as it has the most missing data). "2F_0" shows the # snps after removing both this sample & "2E_0". And so on. You can see as we move from left to right the total number of snps goes down, but also so does the amount of missingness.
Rows indicate thresholds for number of allowed missing samples per snp. The "0" row shows the condition of allowing 0 missing samples, so this is the complete data matrix. The "1" row shows # of snps retained if you allow 1 missing sample. And so on.
Filter by missingness threshold - trim_missing()
The trim_missing() function takes one argument, namely the maximum number of missing samples per snp. Then it removes all sites that don't pass this threshold.
Step15: You can see that this also has the effect of reducing the amount of missingness per sample.
Step16: NB
Step17: Imputing missing genotypes
McVean (2008) recommends filling missing sites with the average genotype of the population, so that's what we're doing here. For each population, we determine the average genotype at any site with missing data, and then fill in the missing sites with this average. In this case, if the average "genotype" is "./.", then this is what gets filled in, so essentially any site missing more than 50% of the data isn't getting imputed. If two genotypes occur with equal frequency then the average is just picked as the first one.
Step18: In comparing this missingness matrix with the previous one, you can see that indeed some snps are being recovered (though not many, again because of the clean simulated data).
You can also examine the effect of imputation on the amount of missingness per sample. You can see it doesn't have as drastic of an effect as trimming, but it does have some effect, plus you are retaining more data!
Step19: Dealing with unequal sampling
Unequal sampling of populations can potentially distort PC analysis (see for example Bradburd et al 2016). Model based ancestry analysis suffers a similar limitation Puechmaille 2016). McVean (2008) recommends downsampling larger populations, but nobody likes throwing away data. Weighted PCA was proposed, but has not been adopted by the community.
Step20: Dealing with linked snps | Python Code:
## conda install ipyrad -c ipyrad
## conda install -c conda-forge scikit-allel
Explanation: Cookbook: PCA analyses
As part of the ipyrad.analysis toolkit we've created convenience functions for easily performing exploratory principal component analysis (PCA) on your data. PCA is a very standard dimension-reduction technique that is often used to get a general sense of how samples are related to one another. PCA has the advantage over STRUCTURE type analyases in that it is very fast. Similar to STRUCTURE, PCA can be used to produce simple and intuitive plots that can be used to guide downstream analysis. There are three very nice papers that talk about the application and interpretation of PCA in the context of population genetics:
Reich et al (2008) Principal component analysis of genetic data
Novembre & Stephens (2008) Interpreting principal component analyses of spatial population genetic variation
McVean (2009) A genealogical interpretation of principal components analysis
A note on Jupyter/IPython
This is a Jupyter notebook, a reproducible and executable document. The code in this notebook is Python (2.7), and should be executed either in a jupyter-notebook, like this one, or in an IPython terminal. Execute each cell in order to reproduce our entire analysis. The example data set used in this analysis is from the empirical example ipyrad tutorial.
Required software
You can easily install the required software for this notebook with a locally installed conda environment. Just run the commented code below in a terminal. If you are working on an HPC cluster you do not need administrator privileges to install the software in this way, since it is only installed locally.
End of explanation
%matplotlib inline
import ipyrad
import ipyrad.analysis as ipa ## ipyrad analysis toolkit
Explanation: Import Python libraries
The call to %matplotlib inline here enables support for plotting directly inside the notebook.
End of explanation
## Load your assembly
data = ipyrad.load_json("/tmp/ipyrad-test/rad.json")
## Create they pca object
pca = ipa.pca(data)
## Bam!
pca.plot()
Explanation: Quick guide (tldr;)
The following cell shows the quickest way to results. Further explanation of all of the features and options is provided further below.
End of explanation
## Path to the input vcf, in this case it's just the vcf from our ipyrad pedicularis assembly
vcffile = "/home/isaac/ipyrad/test-data/pedicularis/ped_outfiles/ped.vcf"
Explanation: Full guide
In the most common use you'll want to plot the first two PCs, then inspect the output, remove any obvious outliers, and then redo the pca. It's often desirable to import a vcf file directly rather than to use the ipyrad assembly, so here we'll demonstrate this.
End of explanation
pca = ipa.pca(vcffile)
print(pca.samples_vcforder)
Explanation: Here we can just load the vcf file directly into the pca analysis module. Then ask for the samples in samples_vcforder, which is the order in which they are written in the vcf.
End of explanation
pca.plot()
Explanation: Now construct the default plot, which shows all samples and PCs 1 and 2. By default all samples are assigned to one population, so everything will be the same color.
End of explanation
pops_dict = {
"superba":["29154_superba_SRR1754715"],
"thamno":["30556_thamno_SRR1754720", "33413_thamno_SRR1754728"],
"cyathophylla":["30686_cyathophylla_SRR1754730"],
"przewalskii":["32082_przewalskii_SRR1754729", "33588_przewalskii_SRR1754727"],
"rex":["35236_rex_SRR1754731", "35855_rex_SRR1754726", "38362_rex_SRR1754725",\
"39618_rex_SRR1754723", "40578_rex_SRR1754724"],
"cyathophylloides":["41478_cyathophylloides_SRR1754722", "41954_cyathophylloides_SRR1754721"]
}
pca = ipa.pca(vcffile, pops_dict)
pca.plot()
Explanation: Population assignment for sample colors
In the tl;dr example the assembly of our simulated data had included a pop_assign_file so the pca() was smart enough to find this and color samples accordingly. In some cases you might not have used a pops file, so it's also possible to specify population assignments in a dictionary. The format of the dictionary should have populations as keys and lists of samples as values. Sample names need to be identical to the names in the vcf file, which we can verify with the samples_vcforder property of the pca object.
End of explanation
## pca.pcs is a property of the pca object that is populated after the plot() function is called. It contains
## the first 10 PCs for each sample. We construct a 'mask' based on the value of PC2, which here is the '1' in
## the first line of code (numpy arrays are 0-indexed and it's typical for PCs to be 1-indexed)
mask = pca.pcs.values[:, 1] > 500
print(mask)
## You can see here that the mask is a list of booleans that is the same length as the number of samples.
## We can use this list to print out the names of just the samples of interest
print(pca.samples_vcforder[mask])
## We can then use this list of "bad" samples in a call to pca.remove_samples
## and then replot the new pca
pca.remove_samples(pca.samples_vcforder[mask])
## Lets prove that they're gone now
print(pca.samples_vcforder)
## and do the plot
pca.plot()
Explanation: This is just much nicer looking now, and it's also much more straightforward to interpret.
Removing "bad" samples and replotting.
In PC analysis, it's common for "bad" samples to dominate several of the first PCs, and thus "pop out" in a degenerate looking way. Bad samples of this kind can often be attributed to poor sequence quality or sample misidentifcation. Samples with lots of missing data tend to pop way out on their own, causing distortion in the signal in the PCs. Normally it's best to evaluate the quality of the sample, and if it can be seen to be of poor quality, to remove it and replot the PCA. The Pedicularis dataset is actually very nice, and clean, but for the sake of demonstration lets imagine the cyathophylloides samples are "bad samples".
We can see that the cyathophylloides samples have particularly high values of PC2, so we can target them for removal in this way.
End of explanation
pca.pcs
Explanation: Inspecting PCs directly
At any time after calling plot() you can inspect the PCs for all the samples using the pca.pcs property. The PC values are saved internally in a convenient pandas dataframe format.
End of explanation
## Lets reload the full dataset so we have all the samples
pca = ipa.pca(vcffile, pops_dict)
pca.plot(pcs=[3,4])
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12, 5))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
pca.plot(ax=ax1, pcs=[1, 2])
pca.plot(ax=ax2, pcs=[3, 4])
Explanation: Looking at PCs other than 1 & 2
PCs 1 and 2 by definition explain the most variation in the data, but sometimes PCs further down the chain can also be useful and informative. The plot function makes it simple to ask for PCs directly.
End of explanation
fig = plt.figure(figsize=(12, 5))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
pca.plot(ax=ax1, pcs=[1, 2], legend=False)
pca.plot(ax=ax2, pcs=[3, 4])
Explanation: It's nice to see PCs 1-4 here, but it's kind of stupid to plot the legend twice, so we can just turn off the legend on the first plot.
End of explanation
## Here's the simple way, just pass in a matplotlib cmap, or even better, the name of a cmap
pca.plot(cmap="jet")
## Here's the harder way that gives you uber control. Pass in a dictionary mapping populations to colors.
my_colors = {
"rex":"aliceblue",
"thamno":"crimson",
"przewalskii":"deeppink",
"cyathophylloides":"fuchsia",
"cyathophylla":"goldenrod",
"superba":"black"
}
pca.plot(cdict=my_colors)
Explanation: Controlling colors
You might notice the default color scheme is unobtrusive, but perhaps not to your liking. There are two ways of modifying the color scheme, one simple and one more complicated, but which gives extremely fine grained control over colors.
Colors for the more complicated method can be specified according to python color conventions. I find this visual page of python color names useful.
End of explanation
pca.get_missing_per_sample()
Explanation: Dealing with missing data
RAD-seq datasets are often characterized by moderate to high levels of missing data. While there may be many thousands or tens of thousands of loci recovered overall, the number of loci that are recovered in all sequenced samples is often quite small. The distribution of depth of coverage per locus is a complicated function of the size of the genome of the focal organism, the restriction enzyme(s) used, the size selection tolerances, and the sequencing effort.
Both model-based (STRUCTURE and the like) and model-free (PCA/sNMF/etc) genetic "clustering" methods are sensitive to missing data. Light to moderate missing data that is distributed randomly among samples is often not enough to seriously impact the results. These are, after all, only exploratory methods. However, if missing data is biased in some way then it can distort the number of inferred populations and/or the relationships among these. For example, if several unrelated samples recover relatively few loci, for whatever reason (mistakes during library prep, failed sequencing, etc), clustering methods may erroniously identify this as true "similarity" with respect to the rest of the samples, and create spurious clusters.
In the end, all these methods must do something with sites that are uncalled in some samples. Some methods adopt a strategy of silently asigning missing sites the "Reference" base. Others, assign missing sites the average base.
There are several ways of dealing with this:
One method is to simply eliminate all loci with missing data. This can be ok for SNP chip type data, where missingness is very sparse. For RAD-Seq type data, eliminating data for all missing loci often results in a drastic reduction in the size of the final data matrix. Assemblies with thousands of loci can be pared down to only tens or hundreds of loci.
Another method is to impute missing data. This is rarely done for RAD-Seq type data, comparatively speaking. Or at least it is rarely done intentionally.
A third method is to downsample using a hypergeometric projection. This is the strategy adopted by dadi in the construction of the SFS (which abhors missing data). It's a little complicated though, so we'll only look at the first two strategies.
Inspect the amount of missing data under various conditions
The pca module has various functions for inspecting missing data. The simples is the get_missing_per_sample() function, which does exactly what it says. It displays the number of ungenotyped snps per sample in the final data matrix. Here you can see that since we are using simulated data the amount of missing data is very low, but in real data these numbers will be considerable.
End of explanation
pca.missingness()
Explanation: This is useful, but it doesn't give us a clear direction for how to go about dealing with the missingness. One way to reduce missing data is to reduce the tolerance for samples ungenotyped at a snp. The other way to reduce missing data is to remove samples with very poor sequencing. To this end, the .missingness() function will show a table of number of retained snps for various of these conditions.
End of explanation
pca.trim_missing(1)
pca.missingness()
Explanation: Here the columns indicate progressive removal of the samples with the fewest number of snps. So "Full" indicates retention of all samples. "2E_0" shows # snps after removing this sample (as it has the most missing data). "2F_0" shows the # snps after removing both this sample & "2E_0". And so on. You can see as we move from left to right the total number of snps goes down, but also so does the amount of missingness.
Rows indicate thresholds for number of allowed missing samples per snp. The "0" row shows the condition of allowing 0 missing samples, so this is the complete data matrix. The "1" row shows # of snps retained if you allow 1 missing sample. And so on.
Filter by missingness threshold - trim_missing()
The trim_missing() function takes one argument, namely the maximum number of missing samples per snp. Then it removes all sites that don't pass this threshold.
End of explanation
pca.get_missing_per_sample()
Explanation: You can see that this also has the effect of reducing the amount of missingness per sample.
End of explanation
## Voila. Back to the full dataset.
pca = ipa.pca(data)
pca.missingness()
Explanation: NB: This operation is destructive of the data inside the pca object. It doesn't do anything to your data on file, though, so if you want to rewind you can just reload your vcf file.
End of explanation
pca.fill_missing()
pca.missingness()
Explanation: Imputing missing genotypes
McVean (2008) recommends filling missing sites with the average genotype of the population, so that's what we're doing here. For each population, we determine the average genotype at any site with missing data, and then fill in the missing sites with this average. In this case, if the average "genotype" is "./.", then this is what gets filled in, so essentially any site missing more than 50% of the data isn't getting imputed. If two genotypes occur with equal frequency then the average is just picked as the first one.
End of explanation
pca.get_missing_per_sample()
Explanation: In comparing this missingness matrix with the previous one, you can see that indeed some snps are being recovered (though not many, again because of the clean simulated data).
You can also examine the effect of imputation on the amount of missingness per sample. You can see it doesn't have as drastic of an effect as trimming, but it does have some effect, plus you are retaining more data!
End of explanation
{x:len(y) for x, y in pca.pops.items()}
Explanation: Dealing with unequal sampling
Unequal sampling of populations can potentially distort PC analysis (see for example Bradburd et al 2016). Model based ancestry analysis suffers a similar limitation Puechmaille 2016). McVean (2008) recommends downsampling larger populations, but nobody likes throwing away data. Weighted PCA was proposed, but has not been adopted by the community.
End of explanation
prettier_labels = {
"32082_przewalskii":"przewalskii",
"33588_przewalskii":"przewalskii",
"41478_cyathophylloides":"cyathophylloides",
"41954_cyathophylloides":"cyathophylloides",
"29154_superba":"superba",
"30686_cyathophylla":"cyathophylla",
"33413_thamno":"thamno",
"30556_thamno":"thamno",
"35236_rex":"rex",
"40578_rex":"rex",
"35855_rex":"rex",
"39618_rex":"rex",
"38362_rex":"rex"
}
Explanation: Dealing with linked snps
End of explanation |
7,449 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 7 - Refining a triangulation
We have seen how the standard meshes can be uniformly refined to finer resolution. The routines used for this task are available to the stripy user for non-uniform refinement as well.
Notebook contents
Uniform meshes
Refinement strategies
Visualisation
Targetted refinement
Visualisation
Step1: Uniform meshes by refinement
The refinement_level parameter of the stripy meshes makes repeated loops determining the bisection points of all the existing edges in the triangulation and then creating a new triangulation that includes these points and the original ones. These refinement operations can also be used for non-uniform refinement.
Step2: Refinement strategies
Five refinement strategies
Step3: Visualisation of refinement strategies
Step4: Targetted refinement
Here we refine a triangulation to a specific criterion - resolving two points in distinct triangles or with distinct nearest neighbour vertices.
Step5: Visualisation of targetted refinement | Python Code:
import stripy as stripy
import numpy as np
Explanation: Example 7 - Refining a triangulation
We have seen how the standard meshes can be uniformly refined to finer resolution. The routines used for this task are available to the stripy user for non-uniform refinement as well.
Notebook contents
Uniform meshes
Refinement strategies
Visualisation
Targetted refinement
Visualisation
End of explanation
ico0 = stripy.spherical_meshes.icosahedral_mesh(refinement_levels=0)
ico1 = stripy.spherical_meshes.icosahedral_mesh(refinement_levels=1)
ico2 = stripy.spherical_meshes.icosahedral_mesh(refinement_levels=2)
ico3 = stripy.spherical_meshes.icosahedral_mesh(refinement_levels=3)
ico4 = stripy.spherical_meshes.icosahedral_mesh(refinement_levels=4)
ico5 = stripy.spherical_meshes.icosahedral_mesh(refinement_levels=5)
ico6 = stripy.spherical_meshes.icosahedral_mesh(refinement_levels=6)
ico7 = stripy.spherical_meshes.icosahedral_mesh(refinement_levels=7)
print("Size of mesh - 1 {}".format(ico1.points.shape[0]))
print("Size of mesh - 2 {}".format(ico2.points.shape[0]))
print("Size of mesh - 3 {}".format(ico3.points.shape[0]))
print("Size of mesh - 4 {}".format(ico4.points.shape[0]))
print("Size of mesh - 5 {}".format(ico5.points.shape[0]))
print("Size of mesh - 6 {}".format(ico6.points.shape[0]))
print("Size of mesh - 7 {}".format(ico7.points.shape[0]))
Explanation: Uniform meshes by refinement
The refinement_level parameter of the stripy meshes makes repeated loops determining the bisection points of all the existing edges in the triangulation and then creating a new triangulation that includes these points and the original ones. These refinement operations can also be used for non-uniform refinement.
End of explanation
mlons, mlats = ico3.midpoint_refine_triangulation_by_vertices(vertices=[1,2,3,4,5,6,7,8,9,10])
ico3mv = stripy.sTriangulation(mlons, mlats)
mlons, mlats = ico3.edge_refine_triangulation_by_vertices(vertices=[1,2,3,4,5,6,7,8,9,10])
ico3ev = stripy.sTriangulation(mlons, mlats)
mlons, mlats = ico3.centroid_refine_triangulation_by_vertices(vertices=[1,2,3,4,5,6,7,8,9,10])
ico3cv = stripy.sTriangulation(mlons, mlats)
mlons, mlats = ico3.edge_refine_triangulation_by_triangles(triangles=[1,2,3,4,5,6,7,8,9,10])
ico3et = stripy.sTriangulation(mlons, mlats)
mlons, mlats = ico3.centroid_refine_triangulation_by_triangles(triangles=[1,2,3,4,5,6,7,8,9,10])
ico3ct = stripy.sTriangulation(mlons, mlats)
print ico3mv.npoints, ico3mv.simplices.shape[0]
print ico3ev.npoints, ico3ev.simplices.shape[0]
print ico3cv.npoints, ico3cv.simplices.shape[0]
print ico3et.npoints, ico3et.simplices.shape[0]
print ico3ct.npoints, ico3ct.simplices.shape[0]
Explanation: Refinement strategies
Five refinement strategies:
Bisect all segments connected to a given node
Refine all triangles connected to a given node by adding a point at the centroid or bisecting all edges
Refune a given triangle by adding a point at the centroid or bisecting all edges
These are provided as follows:
End of explanation
import matplotlib.pyplot as plt
%matplotlib inline
import gdal
import cartopy
import cartopy.crs as ccrs
def mesh_fig(mesh, meshR, name):
fig = plt.figure(figsize=(10, 10), facecolor="none")
ax = plt.subplot(111, projection=ccrs.Orthographic(central_longitude=0.0, central_latitude=0.0, globe=None))
ax.coastlines(color="lightgrey")
ax.set_global()
generator = mesh
refined = meshR
lons0 = np.degrees(generator.lons)
lats0 = np.degrees(generator.lats)
lonsR = np.degrees(refined.lons)
latsR = np.degrees(refined.lats)
lst = refined.lst
lptr = refined.lptr
ax.scatter(lons0, lats0, color="Red",
marker="o", s=150.0, transform=ccrs.Geodetic())
ax.scatter(lonsR, latsR, color="DarkBlue",
marker="o", s=50.0, transform=ccrs.Geodetic())
segs = refined.identify_segments()
for s1, s2 in segs:
ax.plot( [lonsR[s1], lonsR[s2]],
[latsR[s1], latsR[s2]],
linewidth=0.5, color="black", transform=ccrs.Geodetic())
fig.savefig(name, dpi=250, transparent=True)
return
mesh_fig(ico3, ico3mv, "EdgeByVertex1to10" )
mesh_fig(ico3, ico3ev, "EdgeByVertexT1to10" )
mesh_fig(ico3, ico3cv, "CentroidByVertexT1to10" )
mesh_fig(ico3, ico3et, "EdgeByTriangle1to10" )
mesh_fig(ico3, ico3ct, "CentroidByTriangle1to10" )
Explanation: Visualisation of refinement strategies
End of explanation
points = np.array([[ 0.03, 0.035], [0.05, 0.055]]).T
triangulations = [ico1]
nearest, distances = triangulations[-1].nearest_vertex(points[:,0], points[:,1])
max_depth = 15
while nearest[0] == nearest[1] and max_depth > 0:
lons, lats = triangulations[-1].centroid_refine_triangulation_by_vertices(vertices=nearest[0])
new_triangulation = stripy.sTriangulation(lons, lats)
nearest, distances = new_triangulation.nearest_vertex(points[:,0], points[:,1])
triangulations.append(new_triangulation)
max_depth -= 1
print "refinement_steps =", len(triangulations)
centroid_triangulations = triangulations[:]
triangulations = [ico1]
nearest, distances = triangulations[-1].nearest_vertex(points[:,0], points[:,1])
max_depth = 15
while nearest[0] == nearest[1] and max_depth > 0:
lons, lats = triangulations[-1].edge_refine_triangulation_by_vertices(vertices=nearest[0])
new_triangulation = stripy.sTriangulation(lons, lats)
nearest, distances = new_triangulation.nearest_vertex(points[:,0], points[:,1])
triangulations.append(new_triangulation)
max_depth -= 1
print "refinement_steps =", len(triangulations)
edge_triangulations = triangulations[:]
triangulations = [ico1]
in_triangle = triangulations[-1].containing_triangle(points[:,0], points[:,1])
max_depth = 100
while in_triangle[0] == in_triangle[1] and max_depth > 0:
lons, lats = triangulations[-1].edge_refine_triangulation_by_triangles(in_triangle[0])
new_triangulation = stripy.sTriangulation(lons, lats)
in_triangle = new_triangulation.containing_triangle(points[:,0], points[:,1])
triangulations.append(new_triangulation)
print in_triangle
if in_triangle.shape[0] == 0:
break
max_depth -= 1
print "refinement_steps =", len(triangulations)
edge_t_triangulations = triangulations[:]
triangulations = [ico1]
in_triangle = triangulations[-1].containing_triangle(points[:,0], points[:,1])
max_depth = 100
while in_triangle[0] == in_triangle[1] and max_depth > 0:
lons, lats = triangulations[-1].centroid_refine_triangulation_by_triangles(in_triangle[0])
new_triangulation = stripy.sTriangulation(lons, lats)
in_triangle = new_triangulation.containing_triangle(points[:,0], points[:,1])
triangulations.append(new_triangulation)
print in_triangle
if in_triangle.shape[0] == 0:
break
max_depth -= 1
print "refinement_steps =", len(triangulations)
centroid_t_triangulations = triangulations[:]
Explanation: Targetted refinement
Here we refine a triangulation to a specific criterion - resolving two points in distinct triangles or with distinct nearest neighbour vertices.
End of explanation
import lavavu
## The four different triangulation strategies
t1 = edge_triangulations[-1]
t2 = edge_t_triangulations[-1]
t3 = centroid_triangulations[-1]
t4 = centroid_t_triangulations[-1]
## Fire up the viewer
lv = lavavu.Viewer(border=False, background="#FFFFFF", resolution=[1000,600], near=-10.0)
## Add the nodes to mark the original triangulation
nodes = lv.points("nodes", pointsize=10.0, pointtype="shiny", colour="#448080", opacity=0.75)
nodes.vertices(ico1.points*1.01)
nodes2 = lv.points("SplitPoints", pointsize=2.0, pointtype="shiny", colour="#FF3300", opacity=1.0)
nodes2.vertices(np.array(stripy.spherical.lonlat2xyz(points[:,0], points[:,1])).T * 1.01)
##
tris1w = lv.triangles("t1w", wireframe=True, colour="#444444", opacity=0.8)
tris1w.vertices(t1.points)
tris1w.indices(t1.simplices)
tris1s = lv.triangles("t1s", wireframe=False, colour="#77ff88", opacity=0.8)
tris1s.vertices(t1.points*0.999)
tris1s.indices(t1.simplices)
tris2w = lv.triangles("t2w", wireframe=True, colour="#444444", opacity=0.8)
tris2w.vertices(t2.points)
tris2w.indices(t2.simplices)
tris2s = lv.triangles("t2s", wireframe=False, colour="#77ff88", opacity=0.8)
tris2s.vertices(t2.points*0.999)
tris2s.indices(t2.simplices)
tris3w = lv.triangles("t3w", wireframe=True, colour="#444444", opacity=0.8)
tris3w.vertices(t3.points)
tris3w.indices(t3.simplices)
tris3s = lv.triangles("t3s", wireframe=False, colour="#77ff88", opacity=0.8)
tris3s.vertices(t3.points*0.999)
tris3s.indices(t3.simplices)
tris4w = lv.triangles("t4w", wireframe=True, colour="#444444", opacity=0.8)
tris4w.vertices(t4.points)
tris4w.indices(t4.simplices)
tris4s = lv.triangles("t4s", wireframe=False, colour="#77ff88", opacity=0.8)
tris4s.vertices(t4.points*0.999)
tris4s.indices(t4.simplices)
lv.hide("t1s")
lv.hide("t1w")
lv.hide("t2s")
lv.hide("t2w")
lv.hide("t4s")
lv.hide("t4w")
lv.translation(0.0, 0.0, -3.748)
lv.rotation(37.5, -90.0, -37.5)
lv.control.Panel()
lv.control.Button(command="hide triangles; show t1s; show t1w; redraw", label="EBV")
lv.control.Button(command="hide triangles; show t2s; show t2w; redraw", label="EBT")
lv.control.Button(command="hide triangles; show t3s; show t3w; redraw", label="CBV")
lv.control.Button(command="hide triangles; show t4s; show t4w; redraw", label="CBT")
lv.control.show()
import matplotlib.pyplot as plt
%matplotlib inline
import gdal
import cartopy
import cartopy.crs as ccrs
def mesh_fig(mesh, meshR, name):
fig = plt.figure(figsize=(10, 10), facecolor="none")
ax = plt.subplot(111, projection=ccrs.Orthographic(central_longitude=0.0, central_latitude=0.0, globe=None))
ax.coastlines(color="lightgrey")
ax.set_global()
generator = mesh
refined = meshR
lons0 = np.degrees(generator.lons)
lats0 = np.degrees(generator.lats)
lonsR = np.degrees(refined.lons)
latsR = np.degrees(refined.lats)
ax.scatter(lons0, lats0, color="Red",
marker="o", s=150.0, transform=ccrs.Geodetic())
ax.scatter(lonsR, latsR, color="DarkBlue",
marker="o", s=50.0, transform=ccrs.Geodetic())
ax.scatter(np.degrees(points[:,0]), np.degrees(points[:,1]), marker="s", s=50,
color="#885500", transform=ccrs.Geodetic())
segs = refined.identify_segments()
for s1, s2 in segs:
ax.plot( [lonsR[s1], lonsR[s2]],
[latsR[s1], latsR[s2]],
linewidth=0.5, color="black", transform=ccrs.Geodetic())
fig.savefig(name, dpi=250, transparent=True)
return
mesh_fig(edge_triangulations[0], edge_triangulations[-1], "EdgeByVertex" )
T = edge_triangulations[-1]
E = np.array(T.edge_lengths()).T
A = np.array(T.areas()).T
equant = np.max(E, axis=1) / np.min(E, axis=1)
size_ratio = np.sqrt(np.max(A) / np.min(A))
print "EBV", T.simplices.shape[0], equant.max(), equant.min(), size_ratio
mesh_fig(edge_t_triangulations[0], edge_t_triangulations[-1], "EdgeByTriangle" )
T = edge_t_triangulations[-1]
E = np.array(T.edge_lengths()).T
A = np.array(T.areas()).T
equant = np.max(E, axis=1) / np.min(E, axis=1)
size_ratio = np.sqrt(np.max(A) / np.min(A))
print "EBT", T.simplices.shape[0], equant.max(), equant.min(), size_ratio
mesh_fig(centroid_triangulations[0], centroid_triangulations[-1], "CentroidByVertex" )
T = centroid_triangulations[-1]
E = np.array(T.edge_lengths()).T
A = np.array(T.areas()).T
equant = np.max(E, axis=1) / np.min(E, axis=1)
size_ratio = np.sqrt(np.max(A) / np.min(A))
print "CBV", T.simplices.shape[0], equant.max(), equant.min(), size_ratio
mesh_fig(centroid_t_triangulations[0], centroid_t_triangulations[-1], "CentroidByTriangle" )
T = centroid_t_triangulations[-1]
E = np.array(T.edge_lengths()).T
A = np.array(T.areas()).T
equant = np.max(E, axis=1) / np.min(E, axis=1)
size_ratio = np.sqrt(np.max(A) / np.min(A))
print "CBT", T.simplices.shape[0], equant.max(), equant.min(), size_ratio
Explanation: Visualisation of targetted refinement
End of explanation |
7,450 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rulefit Boston Housing Demo
Rulefit algorithm aims for a compromise between interpretability and complexity of the resulting model. While simpler ML algorithms usually miss interaction effects or require advanced methods to uncover interaction effects, rulefit learns a sparse linear model that include automatically detected interaction effects in the form of decision rules. After that, new features are created in the form of decision rules and a transparent model is built using these features.
Example
Step1: Before training a rulefit model, we will train a tree based model for comparison. By default, rulefit uses H2ORandomForestEstimator in the following configuration
Step2: As we can see, RM and LSTAT are the most significant features affecting the house price.
Now, let's create a rulefit model to a create custom rules for more explainability and interpretability
Step3: Rulefits's rule importance table shows all the predictors with non-zero LASSO coefficients. Predictors can be linear (variable name prefixed with "linear.") or a rule (rule identificator as a variable name, e.g. M0T43N16 means this rule comes from the tree based model n.0, tree n.43, node n.16). This table holds values of LASSO coefficient and support of undrlying predictor as a factors of predictor importances. In case of rule predictor, also it's language representation is present.
Let's look closer on resulting predictors. From the table we can see that the rules selected by rulefit as most important have LSTAT or RM variables present. Those which were by far the top 2 most important variables of previous H2ORandomForestEstimator model.
Let's try to interpret significant rules
Step4: Which means that the most expensive houses have 7 or more rooms and are in areas with low nitric oxides concentration and with possibly high proportion of historical buildings.
The full text of M0T42N16 is
Step5: Which means that big houses (7 or more rooms) in areas with very-low-to-zero crime rate and very-low-to-zero percentage of lower status of the population are more expensive to live in.
The full text of M0T31N21 is
Step6: Which can be interpreted as
Step7: Please note, that linear predictor applies to all the observations and that col-wise sums of this output divided by the number of observations represents a support of each rule.
Apart of that, Friedman and Popescu defines (https
Step8: Hence, we can get global importances calculated out of combined importance factors like
Step9: Which gives us a slightly reordered list of importances | Python Code:
import h2o
from h2o.estimators.random_forest import H2ORandomForestEstimator
h2o.init()
train = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/BostonHousing.csv")
x = train.columns
y = "medv"
x.remove(y)
x.remove("b")
train['medv'].hist()
train.head()
Explanation: Rulefit Boston Housing Demo
Rulefit algorithm aims for a compromise between interpretability and complexity of the resulting model. While simpler ML algorithms usually miss interaction effects or require advanced methods to uncover interaction effects, rulefit learns a sparse linear model that include automatically detected interaction effects in the form of decision rules. After that, new features are created in the form of decision rules and a transparent model is built using these features.
Example: IF the number of rooms > 2 AND the age of the house < 15 THEN 1 ELSE 0 (lower than medium)
The general algorithm flow:
Algorithm fits a tree ensemble to the data, builds a rule ensemble by traversing each tree. This results in many rules but majority of them not informative.
After that, it evaluates the rules on the data to build a rule feature set and fits a sparse linear model (LASSO) to the rule feature set joined with the original feature set, to select the best ones.
Boston house prices dataset:
The response variable is the price of the houses and the goal is to produce a model with significant variables that can predict the house price using the given explanatory variables. Each record describes a Boston suburb or town. The data was created from the Boston Standard Metropolitan Statistical Area (SMSA) in the 70s. The attributes are defined as follows:
CRIM: per capita crime rate by town
ZN: proportion of residential land zoned for lots over 25000 sq. ft.
INDUS: proportion of non retail business acres per town
CHAS: Charles River dummy var (= 1 if tract bounds rivers; 0 othervise)
NOX: nitric oxides concentration (parts per 10 milion)
RM: average number of rooms per dweling
AGE: proportion of owner-occupied units built prior to 1940
DIS: weighed distances to five Boston employment centers
RAD: index of accesibility to radial highways
TAX: full value property=tax rate per 10000 USD
PTRATIO: pupil-teacher ratio by town
B: 1000(Bk - 0.63)2 where Bk is the proportion of blacks by town
LSTAT: % lower status of the population
MEDV: Median value of owner-occupied homes in 1000s USD
End of explanation
drf = H2ORandomForestEstimator(ntrees=50, seed=123, max_depth=3)
drf.train(y=y,x=x,training_frame=train)
print("RMSE: ")
print(drf.training_model_metrics()['RMSE'])
drf.varimp_plot()
Explanation: Before training a rulefit model, we will train a tree based model for comparison. By default, rulefit uses H2ORandomForestEstimator in the following configuration:
End of explanation
from h2o.estimators.rulefit import H2ORuleFitEstimator
rf = H2ORuleFitEstimator(seed=123, lambda_=.5 )#, model_type="rules")
rf.train(y=y, x=x, training_frame=train)
print("RMSE: ")
print(rf.training_model_metrics()['RMSE'])
rf.rule_importance()
Explanation: As we can see, RM and LSTAT are the most significant features affecting the house price.
Now, let's create a rulefit model to a create custom rules for more explainability and interpretability:
End of explanation
rf.rule_importance()[4][2]
Explanation: Rulefits's rule importance table shows all the predictors with non-zero LASSO coefficients. Predictors can be linear (variable name prefixed with "linear.") or a rule (rule identificator as a variable name, e.g. M0T43N16 means this rule comes from the tree based model n.0, tree n.43, node n.16). This table holds values of LASSO coefficient and support of undrlying predictor as a factors of predictor importances. In case of rule predictor, also it's language representation is present.
Let's look closer on resulting predictors. From the table we can see that the rules selected by rulefit as most important have LSTAT or RM variables present. Those which were by far the top 2 most important variables of previous H2ORandomForestEstimator model.
Let's try to interpret significant rules:
The full text of M0T41N18 is:
End of explanation
rf.rule_importance()[4][3]
Explanation: Which means that the most expensive houses have 7 or more rooms and are in areas with low nitric oxides concentration and with possibly high proportion of historical buildings.
The full text of M0T42N16 is:
End of explanation
rf.rule_importance()[4][6]
Explanation: Which means that big houses (7 or more rooms) in areas with very-low-to-zero crime rate and very-low-to-zero percentage of lower status of the population are more expensive to live in.
The full text of M0T31N21 is:
End of explanation
predicted_rules = rf.predict_rules(train, ["M0T31N21", "M0T42N16", "linear.rm"])
predicted_rules.head()
Explanation: Which can be interpreted as: "with increasing distance from Boston employment centers and increasing pupil-teacher ratio, the price of majority of the house degrades" (since majority of the houses in our dataset have 6 or more rooms).
We can also find out at which specific rows the certain rules apply or not:
End of explanation
def FPimportance(data, lasso_coef, support, is_rule):
if is_rule:
import math
return abs(lasso_coef) * math.sqrt(support * (1 - support))
else:
return abs(lasso_coef) * data.sd()[0]
Explanation: Please note, that linear predictor applies to all the observations and that col-wise sums of this output divided by the number of observations represents a support of each rule.
Apart of that, Friedman and Popescu defines (https://arxiv.org/abs/0811.1679) the rulefit-specific global measure of predictors importance as follows:
End of explanation
def calculate_FPimportance(input, data):
result = dict()
for x in range(len(input[1])):
if input[1][x].startswith('linear.'):
result[input[1][x]] = FPimportance(data[input[1][x][len("linear."):]], input[2][x], input[3][x], False)
else:
result[input[1][x]] = FPimportance(None, input[2][x], input[3][x], True)
return result
FPimportances = calculate_FPimportance(rf.rule_importance(), train)
import operator
sorted_FPimportances = sorted(FPimportances.items(), key=operator.itemgetter(1), reverse=True)
Explanation: Hence, we can get global importances calculated out of combined importance factors like:
End of explanation
sorted_FPimportances
Explanation: Which gives us a slightly reordered list of importances:
End of explanation |
7,451 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3
Step1: Answer
Step2: 4
Step3: Answer
Step4: 5
Step5: 6
Step6: 7
Step7: 10 | Python Code:
import math
Explanation: 3: The math module
Instructions
Use the sqrt() function within the math module to assign the square root of 16.0 to a.
Use the ceil() function within the math module to assign the ceiling of 111.3 to b.
Use the floor() function within the math module to assign the floor of 89.9 to c.
End of explanation
a = math.sqrt(16.0)
b = math.ceil(111.3)
c = math.floor(89.9)
print(a, b, c)
Explanation: Answer
End of explanation
import math
print(math.pi)
Explanation: 4: Variables within modules
Instructions
Assign the square root of pi to a.
Assign the ceiling of pi to b.
Assign the floor of pi to c.
End of explanation
PI = math.pi
a = math.sqrt(PI)
b = math.ceil(PI)
c = math.floor(PI)
print(a, b, c)
Explanation: Answer
End of explanation
import csv
f = open("nfl.csv")
csvreader = csv.reader(f)
nfl = list(csvreader)
print(nfl)
Explanation: 5: The csv module
Instructions
Read in all of the data from "nfl.csv" into a list variable named nfl using the csv module.
Answer
End of explanation
import csv
f = open("nfl.csv")
reader = csv.reader(f)
data = list(reader)
patriots_wins = 0
for row in data:
if row[2] == "New England Patriots":
patriots_wins += 1
print(patriots_wins)
Explanation: 6: Counting how many times a team won
Instructions
Fill in the mission code to do the following:
Import and use the csv module to load data from our "nfl.csv" file.
Count how many games the "New England Patriots" won from 2009-2013. To do this, set a counter to 0, and increment by 1 whenever you see a row whose winner column is equal to "New England Patriots".
Assign the count to patriots_wins.
Answer
End of explanation
import csv
f = open("nfl.csv", 'r')
nfl = list(csv.reader(f))
# Define your function here
def nfl_wins(team):
team_wins = 0
for row in nfl:
if row[2] == team:
team_wins += 1
return team_wins
cowboys_wins = nfl_wins("Dallas Cowboys")
falcons_wins = nfl_wins("Atlanta Falcons")
print(cowboys_wins, falcons_wins)
Explanation: 7: Making a function to count wins
Instructions
Write a function called nfl_wins that will take a team name as input.
The function should return the number of wins the team had from 2009-2013.
Use the function to assign the number of wins by the "Dallas Cowboys" to cowboys_wins.
Use the function to assign the number of wins by the "Atlanta Falcons" to falcons_wins.
End of explanation
import csv
f = open("nfl.csv", 'r')
nfl = list(csv.reader(f))
def nfl_wins(team):
count = 0
for row in nfl:
if row[2] == team:
count = count + 1
return count
def nfl_wins_in_a_year(team, year):
count = 0
for row in nfl:
if row[0] == year and row[2] == team:
count = count + 1
return count
browns_2010_wins = nfl_wins_in_a_year("Cleveland Browns", "2010")
eagles_2011_wins = nfl_wins_in_a_year("Philadelphia Eagles", "2011")
print(browns_2010_wins, eagles_2011_wins)
Explanation: 10: Counting wins in a given year
Instructions
Modify the nfl_wins function so that it takes a team name, in the form of a string, and a year, also in the form of a string, as input. Call this new function nfl_wins_in_a_year
Your function should output the number of wins the team had in the given year, as an integer. Use the and operator to combine booleans, checking whether the desired team won and whether the game happened in the correct year for each row in the dataset.
Use your function to assign the number of wins by the "Cleveland Browns" in "2010" to browns_2010_wins.
Use your function to assign the number of wins by the "Philadelphia Eagles" in "2011" to eagles_2011_wins.
End of explanation |
7,452 | Given the following text description, write Python code to implement the functionality described.
Description:
You'll be given a string of words, and your task is to count the number
of boredoms. A boredom is a sentence that starts with the word "I".
Sentences are delimited by '.', '?' or '!'.
For example:
This is how the function will work:
is_bored("Hello world")
0
This is how the function will work:
is_bored("The sky is blue. The sun is shining. I love this weather")
1
| Python Code:
def is_bored(S):
import re
sentences = re.split(r'[.?!]\s*', S)
return sum(sentence[0:2] == 'I ' for sentence in sentences) |
7,453 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text Using Markdown
If you double click on this cell, you will see the text change so that all of the formatting is removed. This allows you to edit this block of text. This block of text is written using Markdown, which is a way to format text using headers, links, italics, and many other options. Hit shift + enter or shift + return on your keyboard to show the formatted text again. This is called "running" the cell, and you can also do it using the run button in the toolbar.
Code cells
One great advantage of IPython notebooks is that you can show your Python code alongside the results, add comments to the code, or even add blocks of text using Markdown. These notebooks allow you to collaborate with others and share your work. The following cell is a code cell.
Step1: Nicely formatted results
IPython notebooks allow you to display nicely formatted results, such as plots and tables, directly in
the notebook. You'll learn how to use the following libraries later on in this course, but for now here's a
preview of what IPython notebook can do.
Step2: Creating cells
To create a new code cell, click "Insert > Insert Cell [Above or Below]". A code cell will automatically be created.
To create a new markdown cell, first follow the process above to create a code cell, then change the type from "Code" to "Markdown" using the dropdown next to the run, stop, and restart buttons.
Re-running cells
If you find a bug in your code, you can always update the cell and re-run it. However, any cells that come afterward won't be automatically updated. Try it out below. First run each of the three cells. The first two don't have any output, but you will be able to tell they've run because a number will appear next to them, for example, "In [5]". The third cell should output the message "Intro to Data Analysis is awesome!" | Python Code:
# Hit shift + enter or use the run button to run this cell and see the results
print('hello world')
# The last line of every code cell will be displayed by default,
# even if you don't print it. Run this cell to see how this works.
2 + 2 # The result of this line will not be displayed
3 + 3 # The result of this line will be displayed, because it is the last line of the cell
Explanation: Text Using Markdown
If you double click on this cell, you will see the text change so that all of the formatting is removed. This allows you to edit this block of text. This block of text is written using Markdown, which is a way to format text using headers, links, italics, and many other options. Hit shift + enter or shift + return on your keyboard to show the formatted text again. This is called "running" the cell, and you can also do it using the run button in the toolbar.
Code cells
One great advantage of IPython notebooks is that you can show your Python code alongside the results, add comments to the code, or even add blocks of text using Markdown. These notebooks allow you to collaborate with others and share your work. The following cell is a code cell.
End of explanation
# If you run this cell, you should see the values displayed as a table.
# Pandas is a software library for data manipulation and analysis. You'll learn to use it later in this course.
import pandas as pd
df = pd.DataFrame({'a': [2, 4, 6, 8], 'b': [1, 3, 5, 7]})
df
# If you run this cell, you should see a scatter plot of the function y = x^2
%pylab inline
import matplotlib.pyplot as plt
xs = range(-30, 31)
ys = [x ** 2 for x in xs]
plt.scatter(xs, ys)
# Dictionaries
words = {}
words['Hello'] = 'Bonjour'
words['Yes'] = 'Oui'
words['No'] = 'Non'
words['Bye'] = 'Au Revoir'
print(words)
print(words['Hello'])
print(words['No'])
Explanation: Nicely formatted results
IPython notebooks allow you to display nicely formatted results, such as plots and tables, directly in
the notebook. You'll learn how to use the following libraries later on in this course, but for now here's a
preview of what IPython notebook can do.
End of explanation
class_name = "Jesse B"
message = class_name + " is awesome!"
message
Explanation: Creating cells
To create a new code cell, click "Insert > Insert Cell [Above or Below]". A code cell will automatically be created.
To create a new markdown cell, first follow the process above to create a code cell, then change the type from "Code" to "Markdown" using the dropdown next to the run, stop, and restart buttons.
Re-running cells
If you find a bug in your code, you can always update the cell and re-run it. However, any cells that come afterward won't be automatically updated. Try it out below. First run each of the three cells. The first two don't have any output, but you will be able to tell they've run because a number will appear next to them, for example, "In [5]". The third cell should output the message "Intro to Data Analysis is awesome!"
End of explanation |
7,454 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
External data
Helper functions to download the fastai datasets
To download any of the datasets or pretrained weights, simply run untar_data by passing any dataset name mentioned above like so
Step1: This is a basic Config file that consists of data, model, storage and archive.
All future downloads occur at the paths defined in the config file based on the type of download. For example, all future fastai datasets are downloaded to the data while all pretrained model weights are download to model unless the default download location is updated.
Step2: URLs -
Step3: The default local path is at ~/.fastai/archive/ but this can be updated by passing a different c_key. Note
Step4: untar_data -
Step7: untar_data is a thin wrapper for FastDownload.get. It downloads and extracts url, by default to subdirectories of ~/.fastai, and returns the path to the extracted data. Setting the force_download flag to 'True' will overwrite any existing copy of the data already present. For an explanation of the c_key parameter, see URLs.
Step8: Export - | Python Code:
#|export
@lru_cache(maxsize=None)
def fastai_cfg() -> Config: # Config that contains default download paths for `data`, `model`, `storage` and `archive`
"`Config` object for fastai's `config.ini`"
return Config(Path(os.getenv('FASTAI_HOME', '~/.fastai')), 'config.ini', create=dict(
data = 'data', archive = 'archive', storage = 'tmp', model = 'models'))
Explanation: External data
Helper functions to download the fastai datasets
To download any of the datasets or pretrained weights, simply run untar_data by passing any dataset name mentioned above like so:
```python
path = untar_data(URLs.PETS)
path.ls()
(#7393) [Path('/home/ubuntu/.fastai/data/oxford-iiit-pet/images/keeshond_34.jpg'),...]
```
To download model pretrained weights:
```python
path = untar_data(URLs.PETS)
path.ls()
(#2) [Path('/home/ubuntu/.fastai/data/wt103-bwd/itos_wt103.pkl'),Path('/home/ubuntu/.fastai/data/wt103-bwd/lstm_bwd.pth')]
```
Datasets
A complete list of datasets that are available by default inside the library are:
Main datasets
ADULT_SAMPLE: A small of the adults dataset to predict whether income exceeds $50K/yr based on census data.
BIWI_SAMPLE: A BIWI kinect headpose database. The dataset contains over 15K images of 20 people (6 females and 14 males - 4 people were recorded twice). For each frame, a depth image, the corresponding rgb image (both 640x480 pixels), and the annotation is provided. The head pose range covers about +-75 degrees yaw and +-60 degrees pitch.
CIFAR: The famous cifar-10 dataset which consists of 60000 32x32 colour images in 10 classes, with 6000 images per class.
COCO_SAMPLE: A sample of the coco dataset for object detection.
COCO_TINY: A tiny version of the coco dataset for object detection.
HUMAN_NUMBERS: A synthetic dataset consisting of human number counts in text such as one, two, three, four.. Useful for experimenting with Language Models.
IMDB: The full IMDB sentiment analysis dataset.
IMDB_SAMPLE: A sample of the full IMDB sentiment analysis dataset.
ML_SAMPLE: A movielens sample dataset for recommendation engines to recommend movies to users.
ML_100k: The movielens 100k dataset for recommendation engines to recommend movies to users.
MNIST_SAMPLE: A sample of the famous MNIST dataset consisting of handwritten digits.
MNIST_TINY: A tiny version of the famous MNIST dataset consisting of handwritten digits.
MNIST_VAR_SIZE_TINY:
PLANET_SAMPLE: A sample of the planets dataset from the Kaggle competition Planet: Understanding the Amazon from Space.
PLANET_TINY: A tiny version of the planets dataset from the Kaggle competition Planet: Understanding the Amazon from Space for faster experimentation and prototyping.
IMAGENETTE: A smaller version of the imagenet dataset pronounced just like 'Imagenet', except with a corny inauthentic French accent.
IMAGENETTE_160: The 160px version of the Imagenette dataset.
IMAGENETTE_320: The 320px version of the Imagenette dataset.
IMAGEWOOF: Imagewoof is a subset of 10 classes from Imagenet that aren't so easy to classify, since they're all dog breeds.
IMAGEWOOF_160: 160px version of the ImageWoof dataset.
IMAGEWOOF_320: 320px version of the ImageWoof dataset.
IMAGEWANG: Imagewang contains Imagenette and Imagewoof combined, but with some twists that make it into a tricky semi-supervised unbalanced classification problem
IMAGEWANG_160: 160px version of Imagewang.
IMAGEWANG_320: 320px version of Imagewang.
Kaggle competition datasets
DOGS: Image dataset consisting of dogs and cats images from Dogs vs Cats kaggle competition.
Image Classification datasets
CALTECH_101: Pictures of objects belonging to 101 categories. About 40 to 800 images per category. Most categories have about 50 images. Collected in September 2003 by Fei-Fei Li, Marco Andreetto, and Marc 'Aurelio Ranzato.
CARS: The Cars dataset contains 16,185 images of 196 classes of cars.
CIFAR_100: The CIFAR-100 dataset consists of 60000 32x32 colour images in 100 classes, with 600 images per class.
CUB_200_2011: Caltech-UCSD Birds-200-2011 (CUB-200-2011) is an extended version of the CUB-200 dataset, with roughly double the number of images per class and new part location annotations
FLOWERS: 17 category flower dataset by gathering images from various websites.
FOOD:
MNIST: MNIST dataset consisting of handwritten digits.
PETS: A 37 category pet dataset with roughly 200 images for each class.
NLP datasets
AG_NEWS: The AG News corpus consists of news articles from the AG’s corpus of news articles on the web pertaining to the 4 largest classes. The dataset contains 30,000 training and 1,900 testing examples for each class.
AMAZON_REVIEWS: This dataset contains product reviews and metadata from Amazon, including 142.8 million reviews spanning May 1996 - July 2014.
AMAZON_REVIEWS_POLARITY: Amazon reviews dataset for sentiment analysis.
DBPEDIA: The DBpedia ontology dataset contains 560,000 training samples and 70,000 testing samples for each of 14 nonoverlapping classes from DBpedia.
MT_ENG_FRA: Machine translation dataset from English to French.
SOGOU_NEWS: The Sogou-SRR (Search Result Relevance) dataset was constructed to support researches on search engine relevance estimation and ranking tasks.
WIKITEXT: The WikiText language modeling dataset is a collection of over 100 million tokens extracted from the set of verified Good and Featured articles on Wikipedia.
WIKITEXT_TINY: A tiny version of the WIKITEXT dataset.
YAHOO_ANSWERS: YAHOO's question answers dataset.
YELP_REVIEWS: The Yelp dataset is a subset of YELP businesses, reviews, and user data for use in personal, educational, and academic purposes
YELP_REVIEWS_POLARITY: For sentiment classification on YELP reviews.
Image localization datasets
BIWI_HEAD_POSE: A BIWI kinect headpose database. The dataset contains over 15K images of 20 people (6 females and 14 males - 4 people were recorded twice). For each frame, a depth image, the corresponding rgb image (both 640x480 pixels), and the annotation is provided. The head pose range covers about +-75 degrees yaw and +-60 degrees pitch.
CAMVID: Consists of driving labelled dataset for segmentation type models.
CAMVID_TINY: A tiny camvid dataset for segmentation type models.
LSUN_BEDROOMS: Large-scale Image Dataset using Deep Learning with Humans in the Loop
PASCAL_2007: Pascal 2007 dataset to recognize objects from a number of visual object classes in realistic scenes.
PASCAL_2012: Pascal 2012 dataset to recognize objects from a number of visual object classes in realistic scenes.
Audio classification
MACAQUES: 7285 macaque coo calls across 8 individuals from Distributed acoustic cues for caller identity in macaque vocalization.
ZEBRA_FINCH: 3405 zebra finch calls classified across 11 call types. Additional labels include name of individual making the vocalization and its age.
Medical imaging datasets
SIIM_SMALL: A smaller version of the SIIM dataset where the objective is to classify pneumothorax from a set of chest radiographic images.
TCGA_SMALL: A smaller version of the TCGA-OV dataset with subcutaneous and visceral fat segmentations. Citations:
Holback, C., Jarosz, R., Prior, F., Mutch, D. G., Bhosale, P., Garcia, K., … Erickson, B. J. (2016). Radiology Data from The Cancer Genome Atlas Ovarian Cancer [TCGA-OV] collection. The Cancer Imaging Archive. http://doi.org/10.7937/K9/TCIA.2016.NDO1MDFQ
Clark K, Vendt B, Smith K, Freymann J, Kirby J, Koppel P, Moore S, Phillips S, Maffitt D, Pringle M, Tarbox L, Prior F. The Cancer Imaging Archive (TCIA): Maintaining and Operating a Public Information Repository, Journal of Digital Imaging, Volume 26, Number 6, December, 2013, pp 1045-1057. https://link.springer.com/article/10.1007/s10278-013-9622-7
Pretrained models
OPENAI_TRANSFORMER: The GPT2 Transformer pretrained weights.
WT103_FWD: The WikiText-103 forward language model weights.
WT103_BWD: The WikiText-103 backward language model weights.
Config
End of explanation
cfg = fastai_cfg()
cfg.data,cfg.path('data')
#|export
def fastai_path(folder:str) -> Path:
"Local path to `folder` in `Config`"
return fastai_cfg().path(folder)
fastai_path('archive')
Explanation: This is a basic Config file that consists of data, model, storage and archive.
All future downloads occur at the paths defined in the config file based on the type of download. For example, all future fastai datasets are downloaded to the data while all pretrained model weights are download to model unless the default download location is updated.
End of explanation
#|export
class URLs():
"Global constants for dataset and model URLs."
LOCAL_PATH = Path.cwd()
MDL = 'http://files.fast.ai/models/'
GOOGLE = 'https://storage.googleapis.com/'
S3 = 'https://s3.amazonaws.com/fast-ai-'
URL = f'{S3}sample/'
S3_IMAGE = f'{S3}imageclas/'
S3_IMAGELOC = f'{S3}imagelocal/'
S3_AUDI = f'{S3}audio/'
S3_NLP = f'{S3}nlp/'
S3_COCO = f'{S3}coco/'
S3_MODEL = f'{S3}modelzoo/'
# main datasets
ADULT_SAMPLE = f'{URL}adult_sample.tgz'
BIWI_SAMPLE = f'{URL}biwi_sample.tgz'
CIFAR = f'{URL}cifar10.tgz'
COCO_SAMPLE = f'{S3_COCO}coco_sample.tgz'
COCO_TINY = f'{S3_COCO}coco_tiny.tgz'
HUMAN_NUMBERS = f'{URL}human_numbers.tgz'
IMDB = f'{S3_NLP}imdb.tgz'
IMDB_SAMPLE = f'{URL}imdb_sample.tgz'
ML_SAMPLE = f'{URL}movie_lens_sample.tgz'
ML_100k = 'https://files.grouplens.org/datasets/movielens/ml-100k.zip'
MNIST_SAMPLE = f'{URL}mnist_sample.tgz'
MNIST_TINY = f'{URL}mnist_tiny.tgz'
MNIST_VAR_SIZE_TINY = f'{S3_IMAGE}mnist_var_size_tiny.tgz'
PLANET_SAMPLE = f'{URL}planet_sample.tgz'
PLANET_TINY = f'{URL}planet_tiny.tgz'
IMAGENETTE = f'{S3_IMAGE}imagenette2.tgz'
IMAGENETTE_160 = f'{S3_IMAGE}imagenette2-160.tgz'
IMAGENETTE_320 = f'{S3_IMAGE}imagenette2-320.tgz'
IMAGEWOOF = f'{S3_IMAGE}imagewoof2.tgz'
IMAGEWOOF_160 = f'{S3_IMAGE}imagewoof2-160.tgz'
IMAGEWOOF_320 = f'{S3_IMAGE}imagewoof2-320.tgz'
IMAGEWANG = f'{S3_IMAGE}imagewang.tgz'
IMAGEWANG_160 = f'{S3_IMAGE}imagewang-160.tgz'
IMAGEWANG_320 = f'{S3_IMAGE}imagewang-320.tgz'
# kaggle competitions download dogs-vs-cats -p {DOGS.absolute()}
DOGS = f'{URL}dogscats.tgz'
# image classification datasets
CALTECH_101 = f'{S3_IMAGE}caltech_101.tgz'
CARS = f'{S3_IMAGE}stanford-cars.tgz'
CIFAR_100 = f'{S3_IMAGE}cifar100.tgz'
CUB_200_2011 = f'{S3_IMAGE}CUB_200_2011.tgz'
FLOWERS = f'{S3_IMAGE}oxford-102-flowers.tgz'
FOOD = f'{S3_IMAGE}food-101.tgz'
MNIST = f'{S3_IMAGE}mnist_png.tgz'
PETS = f'{S3_IMAGE}oxford-iiit-pet.tgz'
# NLP datasets
AG_NEWS = f'{S3_NLP}ag_news_csv.tgz'
AMAZON_REVIEWS = f'{S3_NLP}amazon_review_full_csv.tgz'
AMAZON_REVIEWS_POLARITY = f'{S3_NLP}amazon_review_polarity_csv.tgz'
DBPEDIA = f'{S3_NLP}dbpedia_csv.tgz'
MT_ENG_FRA = f'{S3_NLP}giga-fren.tgz'
SOGOU_NEWS = f'{S3_NLP}sogou_news_csv.tgz'
WIKITEXT = f'{S3_NLP}wikitext-103.tgz'
WIKITEXT_TINY = f'{S3_NLP}wikitext-2.tgz'
YAHOO_ANSWERS = f'{S3_NLP}yahoo_answers_csv.tgz'
YELP_REVIEWS = f'{S3_NLP}yelp_review_full_csv.tgz'
YELP_REVIEWS_POLARITY = f'{S3_NLP}yelp_review_polarity_csv.tgz'
# Image localization datasets
BIWI_HEAD_POSE = f"{S3_IMAGELOC}biwi_head_pose.tgz"
CAMVID = f'{S3_IMAGELOC}camvid.tgz'
CAMVID_TINY = f'{URL}camvid_tiny.tgz'
LSUN_BEDROOMS = f'{S3_IMAGE}bedroom.tgz'
PASCAL_2007 = f'{S3_IMAGELOC}pascal_2007.tgz'
PASCAL_2012 = f'{S3_IMAGELOC}pascal_2012.tgz'
# Audio classification datasets
MACAQUES = f'{GOOGLE}ml-animal-sounds-datasets/macaques.zip'
ZEBRA_FINCH = f'{GOOGLE}ml-animal-sounds-datasets/zebra_finch.zip'
# Medical Imaging datasets
#SKIN_LESION = f'{S3_IMAGELOC}skin_lesion.tgz'
SIIM_SMALL = f'{S3_IMAGELOC}siim_small.tgz'
TCGA_SMALL = f'{S3_IMAGELOC}tcga_small.tgz'
#Pretrained models
OPENAI_TRANSFORMER = f'{S3_MODEL}transformer.tgz'
WT103_FWD = f'{S3_MODEL}wt103-fwd.tgz'
WT103_BWD = f'{S3_MODEL}wt103-bwd.tgz'
def path(
url:str='.', # File to download
c_key:str='archive' # Key in `Config` where to save URL
) -> Path:
"Local path where to download based on `c_key`"
fname = url.split('/')[-1]
local_path = URLs.LOCAL_PATH/('models' if c_key=='model' else 'data')/fname
if local_path.exists(): return local_path
return fastai_path(c_key)/fname
Explanation: URLs -
End of explanation
url = URLs.PETS
local_path = URLs.path(url)
test_eq(local_path.parent, fastai_path('archive'))
local_path
local_path = URLs.path(url, c_key='model')
test_eq(local_path.parent, fastai_path('model'))
local_path
Explanation: The default local path is at ~/.fastai/archive/ but this can be updated by passing a different c_key. Note: c_key should be one of 'archive', 'data', 'model', 'storage'.
End of explanation
#|export
def untar_data(
url:str, # File to download
archive:Path=None, # Optional override for `Config`'s `archive` key
data:Path=None, # Optional override for `Config`'s `data` key
c_key:str='data', # Key in `Config` where to extract file
force_download:bool=False, # Setting to `True` will overwrite any existing copy of data
base:str='~/.fastai' # Directory containing config file and base of relative paths
) -> Path: # Path to extracted file(s)
"Download `url` using `FastDownload.get`"
d = FastDownload(fastai_cfg(), module=fastai.data, archive=archive, data=data, base=base)
return d.get(url, force=force_download, extract_key=c_key)
Explanation: untar_data -
End of explanation
untar_data(URLs.MNIST_SAMPLE)
#|hide
#Check all URLs are in the download_checks.py file and match for downloaded archives
# from fastdownload import read_checks
# fd = FastDownload(fastai_cfg(), module=fastai.data)
# _whitelist = "MDL LOCAL_PATH URL WT103_BWD WT103_FWD GOOGLE".split()
# checks = read_checks(fd.module)
# for d in dir(URLs):
# if d.upper() == d and not d.startswith("S3") and not d in _whitelist:
# url = getattr(URLs, d)
# assert url in checks,f{d} is not in the check file for all URLs.
# To fix this, you need to run the following code in this notebook before making a PR (there is a commented cell for this below):
# url = URLs.{d}
# fd.get(url, force=True)
# fd.update(url)
#
# f = fd.download(url)
# assert fd.check(url, f),fThe log we have for {d} in checks does not match the actual archive.
# To fix this, you need to run the following code in this notebook before making a PR (there is a commented cell for this below):
# url = URLs.{d}
# _add_check(url, URLs.path(url))
#
Explanation: untar_data is a thin wrapper for FastDownload.get. It downloads and extracts url, by default to subdirectories of ~/.fastai, and returns the path to the extracted data. Setting the force_download flag to 'True' will overwrite any existing copy of the data already present. For an explanation of the c_key parameter, see URLs.
End of explanation
#|hide
from nbdev.export import notebook2script
notebook2script()
Explanation: Export -
End of explanation |
7,455 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align = 'center'> Neural Networks Demystified </h1>
<h2 align = 'center'> Part 7
Step1: Last time, we trained our Neural Network, and it made suspiciously good predictions of your test score based on how many hours you slept, and how many hours you studied the night before. Before we celebrate and begin changing our sleep and study habits, we need some way to ensure that our model reflects the real world.
To do this, let’s first spend some time thinking about data. Like a lot of data, our input and output values come from real world observations. The assumption here is that there is some underlying process, and our observations give us insight into the process - BUT our observations are not the same thing as the process, they are just a sample.
Our observation says that when we sleep for 3 hours and study for 5 hours, the grade we earned was a 75. But does this mean that every time you sleep for 3 hours and study for 5 hours you will earn a 75? Of course not, because there are other variables that matter here, such as the difficulty of test, or whether you’ve been paying attention in lectures – we could quantify these variables to build a better model, but even if we did, there would still an element of uncertainty that we could never explicitly model – for example, maybe the test was multiple choice, and you guessed on a few problems.
One way to think about this problem is that observations are composed of signal and noise. Nate Silver, the guy who correctly predicted the US election results for 50 out of 50 US states in 2012, wrote a great book on exactly this. The idea is that we’re interested in an underlying process, the signal, but in real data, our signal will always be obscured by some level of noise.
An interesting example of this shows up when comparing the SAT scores of students who take the SAT both Junior and Senior year. Right on the college board’s website it says
Step2: So it appears our model is overfitting, but how do we know for sure? A widely accepted method is to split our data into 2 portions
Step3: So now that we know overfitting is a problem, but how do we fix it? One way is to throw more data at the problem. A simple rule of thumb as presented by Yaser Abu-Mostaf is his excellent machine learning course available from Caltech, is that you should have at least 10 times as many examples as the degrees for freedom in your model. For us, since we have 9 weights that can change, we would need 90 observations, which we certainly don’t have.
Link to course
Step4: If we train our model now, we see that the fit is still good, but our model is no longer interested in “exactly” fitting our data. Further, our training and testing errors are much closer, and we’ve successfully reduced overfitting on this dataset. To further reduce overfitting, we could increase lambda. | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('S4ZUwgesjS8')
Explanation: <h1 align = 'center'> Neural Networks Demystified </h1>
<h2 align = 'center'> Part 7: Overfitting, Testing, and Regularization </h2>
<h4 align = 'center' > @stephencwelch </h4>
End of explanation
%pylab inline
from partSix import *
NN = Neural_Network()
# X = (hours sleeping, hours studying), y = Score on test
X = np.array(([3,5], [5,1], [10,2], [6,1.5]), dtype=float)
y = np.array(([75], [82], [93], [70]), dtype=float)
#Plot projections of our new data:
fig = figure(0,(8,3))
subplot(1,2,1)
scatter(X[:,0], y)
grid(1)
xlabel('Hours Sleeping')
ylabel('Test Score')
subplot(1,2,2)
scatter(X[:,1], y)
grid(1)
xlabel('Hours Studying')
ylabel('Test Score')
#Normalize
X = X/np.amax(X, axis=0)
y = y/100 #Max test score is 100
#Train network with new data:
T = trainer(NN)
T.train(X,y)
#Plot cost during training:
plot(T.J)
grid(1)
xlabel('Iterations')
ylabel('Cost')
#Test network for various combinations of sleep/study:
hoursSleep = linspace(0, 10, 100)
hoursStudy = linspace(0, 5, 100)
#Normalize data (same way training data way normalized)
hoursSleepNorm = hoursSleep/10.
hoursStudyNorm = hoursStudy/5.
#Create 2-d versions of input for plotting
a, b = meshgrid(hoursSleepNorm, hoursStudyNorm)
#Join into a single input matrix:
allInputs = np.zeros((a.size, 2))
allInputs[:, 0] = a.ravel()
allInputs[:, 1] = b.ravel()
allOutputs = NN.forward(allInputs)
#Contour Plot:
yy = np.dot(hoursStudy.reshape(100,1), np.ones((1,100)))
xx = np.dot(hoursSleep.reshape(100,1), np.ones((1,100))).T
CS = contour(xx,yy,100*allOutputs.reshape(100, 100))
clabel(CS, inline=1, fontsize=10)
xlabel('Hours Sleep')
ylabel('Hours Study')
#3D plot:
#Uncomment to plot out-of-notebook (you'll be able to rotate)
#%matplotlib qt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')
#Scatter training examples:
ax.scatter(10*X[:,0], 5*X[:,1], 100*y, c='k', alpha = 1, s=30)
surf = ax.plot_surface(xx, yy, 100*allOutputs.reshape(100, 100), \
cmap=cm.jet, alpha = 0.5)
ax.set_xlabel('Hours Sleep')
ax.set_ylabel('Hours Study')
ax.set_zlabel('Test Score')
Explanation: Last time, we trained our Neural Network, and it made suspiciously good predictions of your test score based on how many hours you slept, and how many hours you studied the night before. Before we celebrate and begin changing our sleep and study habits, we need some way to ensure that our model reflects the real world.
To do this, let’s first spend some time thinking about data. Like a lot of data, our input and output values come from real world observations. The assumption here is that there is some underlying process, and our observations give us insight into the process - BUT our observations are not the same thing as the process, they are just a sample.
Our observation says that when we sleep for 3 hours and study for 5 hours, the grade we earned was a 75. But does this mean that every time you sleep for 3 hours and study for 5 hours you will earn a 75? Of course not, because there are other variables that matter here, such as the difficulty of test, or whether you’ve been paying attention in lectures – we could quantify these variables to build a better model, but even if we did, there would still an element of uncertainty that we could never explicitly model – for example, maybe the test was multiple choice, and you guessed on a few problems.
One way to think about this problem is that observations are composed of signal and noise. Nate Silver, the guy who correctly predicted the US election results for 50 out of 50 US states in 2012, wrote a great book on exactly this. The idea is that we’re interested in an underlying process, the signal, but in real data, our signal will always be obscured by some level of noise.
An interesting example of this shows up when comparing the SAT scores of students who take the SAT both Junior and Senior year. Right on the college board’s website it says: “The higher a student's scores as a junior, the more likely that student's subsequent scores will drop”. Why would this be? It seems like students who did well junior year would also do well senior year. We can make sense of this by considering that SAT scores are composed of a signal and a noise component – the signal being the underlying aptitude of the student, and the noise being other factors that effect test scores, basically if the student had a good day or not. Of the students who did well the first time, we expect a disproportionate number to have had a good day – and since having a good day is random, when these students have a regular or bad test day on their next test, their scores will go down.
So if we can convince our model to fit the signal and not the noise, we should be able to avoid overfitting. First, we’ll work on diagnosing overfitting, then we’ll work on fixing it. Last time we showed our model predictions across the input space for various combinations of hours sleeping and hours studying. We’ll add a couple more data points to make overfitting a bit more obvious and retrain our model on the new dataset. If we re-examine our predictions across our sample space, we begin to see some strange behavior. Neural networks are really powerful learning models, and we see here that all that power has been used to fit our data really closely – which creates a problem - our model is no longer reflective of the real world. According to our model, in some cases, studying more will actually push our score down, this seems unlikely - hopefully studying more will not decrease your score.
End of explanation
#Training Data:
trainX = np.array(([3,5], [5,1], [10,2], [6,1.5]), dtype=float)
trainY = np.array(([75], [82], [93], [70]), dtype=float)
#Testing Data:
testX = np.array(([4, 5.5], [4.5,1], [9,2.5], [6, 2]), dtype=float)
testY = np.array(([70], [89], [85], [75]), dtype=float)
#Normalize:
trainX = trainX/np.amax(trainX, axis=0)
trainY = trainY/100 #Max test score is 100
#Normalize by max of training data:
testX = testX/np.amax(trainX, axis=0)
testY = testY/100 #Max test score is 100
##Need to modify trainer class a bit to check testing error during training:
class trainer(object):
def __init__(self, N):
#Make Local reference to network:
self.N = N
def callbackF(self, params):
self.N.setParams(params)
self.J.append(self.N.costFunction(self.X, self.y))
self.testJ.append(self.N.costFunction(self.testX, self.testY))
def costFunctionWrapper(self, params, X, y):
self.N.setParams(params)
cost = self.N.costFunction(X, y)
grad = self.N.computeGradients(X,y)
return cost, grad
def train(self, trainX, trainY, testX, testY):
#Make an internal variable for the callback function:
self.X = trainX
self.y = trainY
self.testX = testX
self.testY = testY
#Make empty list to store training costs:
self.J = []
self.testJ = []
params0 = self.N.getParams()
options = {'maxiter': 200, 'disp' : True}
_res = optimize.minimize(self.costFunctionWrapper, params0, jac=True, method='BFGS', \
args=(trainX, trainY), options=options, callback=self.callbackF)
self.N.setParams(_res.x)
self.optimizationResults = _res
#Train network with new data:
NN = Neural_Network()
T = trainer(NN)
T.train(trainX, trainY, testX, testY)
#Plot cost during training:
plot(T.J)
plot(T.testJ)
grid(1)
xlabel('Iterations')
ylabel('Cost')
Explanation: So it appears our model is overfitting, but how do we know for sure? A widely accepted method is to split our data into 2 portions: training and testing. We won’t touch our testing data while training the model, and only use it to see how we’re doing – our testing data is a simulation of the real world. We can plot the error on our training and testing sets as we train our model and identify the exact point at which overfitting begins. We can also plot testing and training error as a function of model complexity a see similar behavior.
End of explanation
#Regularization Parameter:
Lambda = 0.0001
#Need to make changes to costFunction and costFunctionPrim:
def costFunction(self, X, y):
#Compute cost for given X,y, use weights already stored in class.
self.yHat = self.forward(X)
J = 0.5*sum((y-self.yHat)**2)/X.shape[0] + (self.lambd/2)*(sum(self.W1**2)+sum(self.W2**2))
return J
def costFunctionPrime(self, X, y):
#Compute derivative with respect to W and W2 for a given X and y:
self.yHat = self.forward(X)
delta3 = np.multiply(-(y-self.yHat), self.sigmoidPrime(self.z3))
#Add gradient of regularization term:
dJdW2 = np.dot(self.a2.T, delta3)/X.shape[0] + self.lambd*self.W2
delta2 = np.dot(delta3, self.W2.T)*self.sigmoidPrime(self.z2)
#Add gradient of regularization term:
dJdW1 = np.dot(X.T, delta2)/X.shape[0] + self.lambd*self.W1
return dJdW1, dJdW2
#New complete class, with changes:
class Neural_Network(object):
def __init__(self, Lambda=0):
#Define Hyperparameters
self.inputLayerSize = 2
self.outputLayerSize = 1
self.hiddenLayerSize = 3
#Weights (parameters)
self.W1 = np.random.randn(self.inputLayerSize,self.hiddenLayerSize)
self.W2 = np.random.randn(self.hiddenLayerSize,self.outputLayerSize)
#Regularization Parameter:
self.Lambda = Lambda
def forward(self, X):
#Propogate inputs though network
self.z2 = np.dot(X, self.W1)
self.a2 = self.sigmoid(self.z2)
self.z3 = np.dot(self.a2, self.W2)
yHat = self.sigmoid(self.z3)
return yHat
def sigmoid(self, z):
#Apply sigmoid activation function to scalar, vector, or matrix
return 1/(1+np.exp(-z))
def sigmoidPrime(self,z):
#Gradient of sigmoid
return np.exp(-z)/((1+np.exp(-z))**2)
def costFunction(self, X, y):
#Compute cost for given X,y, use weights already stored in class.
self.yHat = self.forward(X)
J = 0.5*sum((y-self.yHat)**2)/X.shape[0] + (self.Lambda/2)*(sum(self.W1**2)+sum(self.W2**2))
return J
def costFunctionPrime(self, X, y):
#Compute derivative with respect to W and W2 for a given X and y:
self.yHat = self.forward(X)
delta3 = np.multiply(-(y-self.yHat), self.sigmoidPrime(self.z3))
#Add gradient of regularization term:
dJdW2 = np.dot(self.a2.T, delta3)/X.shape[0] + self.Lambda*self.W2
delta2 = np.dot(delta3, self.W2.T)*self.sigmoidPrime(self.z2)
#Add gradient of regularization term:
dJdW1 = np.dot(X.T, delta2)/X.shape[0] + self.Lambda*self.W1
return dJdW1, dJdW2
#Helper functions for interacting with other methods/classes
def getParams(self):
#Get W1 and W2 Rolled into vector:
params = np.concatenate((self.W1.ravel(), self.W2.ravel()))
return params
def setParams(self, params):
#Set W1 and W2 using single parameter vector:
W1_start = 0
W1_end = self.hiddenLayerSize*self.inputLayerSize
self.W1 = np.reshape(params[W1_start:W1_end], \
(self.inputLayerSize, self.hiddenLayerSize))
W2_end = W1_end + self.hiddenLayerSize*self.outputLayerSize
self.W2 = np.reshape(params[W1_end:W2_end], \
(self.hiddenLayerSize, self.outputLayerSize))
def computeGradients(self, X, y):
dJdW1, dJdW2 = self.costFunctionPrime(X, y)
return np.concatenate((dJdW1.ravel(), dJdW2.ravel()))
Explanation: So now that we know overfitting is a problem, but how do we fix it? One way is to throw more data at the problem. A simple rule of thumb as presented by Yaser Abu-Mostaf is his excellent machine learning course available from Caltech, is that you should have at least 10 times as many examples as the degrees for freedom in your model. For us, since we have 9 weights that can change, we would need 90 observations, which we certainly don’t have.
Link to course: https://work.caltech.edu/telecourse.html
Another popular and effective way to mitigate overfitting is to use a technique called regularization. One way to implement regularization is to add a term to our cost function that penalizes overly complex models. A simple, but effective way to do this is to add together the square of our weights to our cost function, this way, models with larger magnitudes of weights, cost more. We’ll need to normalize the other part of our cost function to ensure that our ratio of the two error terms does not change with respect to the number of examples. We’ll introduce a regularization hyper parameter, lambda, that will allow us to tune the relative cost – higher values of lambda will impose bigger penalties for high model complexity.
End of explanation
NN = Neural_Network(Lambda=0.0001)
#Make sure our gradients our correct after making changes:
numgrad = computeNumericalGradient(NN, X, y)
grad = NN.computeGradients(X,y)
#Should be less than 1e-8:
norm(grad-numgrad)/norm(grad+numgrad)
T = trainer(NN)
T.train(X,y,testX,testY)
plot(T.J)
plot(T.testJ)
grid(1)
xlabel('Iterations')
ylabel('Cost')
allOutputs = NN.forward(allInputs)
#Contour Plot:
yy = np.dot(hoursStudy.reshape(100,1), np.ones((1,100)))
xx = np.dot(hoursSleep.reshape(100,1), np.ones((1,100))).T
CS = contour(xx,yy,100*allOutputs.reshape(100, 100))
clabel(CS, inline=1, fontsize=10)
xlabel('Hours Sleep')
ylabel('Hours Study')
#3D plot:
##Uncomment to plot out-of-notebook (you'll be able to rotate)
#%matplotlib qt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(10*X[:,0], 5*X[:,1], 100*y, c='k', alpha = 1, s=30)
surf = ax.plot_surface(xx, yy, 100*allOutputs.reshape(100, 100), \
cmap=cm.jet, alpha = 0.5)
ax.set_xlabel('Hours Sleep')
ax.set_ylabel('Hours Study')
ax.set_zlabel('Test Score')
Explanation: If we train our model now, we see that the fit is still good, but our model is no longer interested in “exactly” fitting our data. Further, our training and testing errors are much closer, and we’ve successfully reduced overfitting on this dataset. To further reduce overfitting, we could increase lambda.
End of explanation |
7,456 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Does RFT FDR control the nominal FDR value?
In this notebook, I made a small simulation, to verify that the RFT peak FDR procedure does not control the overall FDR but the conditional FDR (for all peaks above u)
Step1: Define the p-value for peaks using RFT
Step2: Loop over simulations for different significance thresholds to see overall FDR
Step3: Plot figure of random field
Step4: Plot results | Python Code:
% matplotlib inline
import os
import numpy as np
import nibabel as nib
from nipy.labs.utils.simul_multisubject_fmri_dataset import surrogate_3d_dataset
import nipy.algorithms.statistics.rft as rft
from __future__ import print_function, division
import math
import matplotlib.pyplot as plt
import palettable.colorbrewer as cb
from nipype.interfaces import fsl
import pandas as pd
import nipy.algorithms.statistics.intvol as intvol
from matplotlib import colors
import scipy.stats as stats
import statsmodels.sandbox.stats.multicomp as multicomp
Explanation: Does RFT FDR control the nominal FDR value?
In this notebook, I made a small simulation, to verify that the RFT peak FDR procedure does not control the overall FDR but the conditional FDR (for all peaks above u)
End of explanation
def nulprobdensRFT(exc,peaks):
f0 = exc*np.exp(-exc*(peaks-exc))
return f0
Explanation: Define the p-value for peaks using RFT
End of explanation
thres = [0.01,0.02,0.03,0.04,0.05]
res = {}
means = []
exc = 3
for alphval in thres:
print(alphval)
hatFDR = []
for k in range(5000):
smooth_FWHM = 3
smooth_sd = smooth_FWHM/(2*math.sqrt(2*math.log(2)))
data = surrogate_3d_dataset(n_subj=1,sk=smooth_sd,shape=(50,50,50),noise_level=1)
data[0:25,0:25,0:25] = data[0:25,0:25,0:25]+2.5
img=nib.Nifti1Image(data,np.eye(4))
img.to_filename("files/RF.nii.gz")
cl=fsl.model.Cluster()
cl.inputs.threshold = exc
cl.inputs.in_file="files/RF.nii.gz"
cl.inputs.out_localmax_txt_file="files/locmax.txt"
cl.inputs.num_maxima=1000000
cl.inputs.connectivity=26
cl.inputs.terminal_output='none'
cl.run()
peaks = pd.read_csv("files/locmax.txt",sep="\t").drop('Unnamed: 5',1)
peaks.Value = peaks.Value
peaks['Pvals'] = nulprobdensRFT(exc,peaks.Value)
psorted = np.sort(peaks.Pvals)
qsorted = (np.array(range(len(psorted)))/len(psorted))*alphval
pr = [1 if a<b else 0 for a,b in zip(psorted,qsorted)]
if np.sum(pr)==0:
peaks['Significant'] = 0
FDRh = 0
else:
pr = [x for x,val in enumerate(pr) if val == True]
pthres = max(qsorted[pr])
peaks['Significant'] = peaks.Pvals<pthres
truth = []
for i in range(len(peaks)):
peak_act = peaks.x[i] in range(25) and peaks.y[i] in range(25) and peaks.z[i] in range(25)
truth.append(peak_act)
peaks['Truth'] = truth
FP = np.sum([a and not b for a,b in zip(peaks.Significant == 1,peaks.Truth)])
TP = np.sum([a and b for a,b in zip(peaks.Significant == 1,peaks.Truth)])
FDRh = FP/(TP+FP)
hatFDR.append(FDRh)
res[alphval] = hatFDR
mn = np.nanmean(res[alphval])
print(mn)
means.append(mn)
Explanation: Loop over simulations for different significance thresholds to see overall FDR
End of explanation
plt.figure(figsize=(6,4))
plt.imshow(data[0:50,0:50,1])
plt.colorbar()
plt.show()
Explanation: Plot figure of random field: 1/8 of the field is with signal
End of explanation
means = []
for alpha in thres:
means.append(np.nanmean(res[alpha]))
cols = cb.qualitative.Set2_8.mpl_colors
plt.figure(figsize=(6,4))
plt.plot(np.arange(0.01,0.05,0.001),np.arange(0.01,0.05,0.001),color='grey')
plt.plot(thres,means,linewidth=3,color=cols[0])
plt.xlabel("nominal FDR")
plt.ylabel("observed FDR")
plt.xlim(0.01,0.05)
plt.ylim(0.01,0.05)
Explanation: Plot results
End of explanation |
7,457 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Root Finding and Optimization
GOAL
Step3: Fixed Point Iteration
How do we go about solving this?
Could try to solve at least partially for $r$
Step4: Guess at $r_0$ and check to see what direction we need to go...
$r_0 = 0.0800$, $g(r_0) - r_0 = -0.009317550125425428$
$r_1 = 0.0850$, $g(r_1) - r_1 = -0.00505763375972$
$r_2 = 0.0875$, $g(r_2) - r_2 = -0.00257275331014$
A bit tedious, we can also make this algorithmic
Step5: Example 2
Step6: Example 3
Step7: These are equivalent problems! Something is awry...
Analysis of Fixed Point Iteration
Theorem
Step8: Additionally, suppose $g'(x)$ is defined for $x \in [a,b]$ and $\exists K < 1$ s.t. $|g'(x)| \leq K < 1 ~~~ \forall ~~~ x \in (a,b)$, then $g$ has a unique fixed point $P \in [a,b]$
Step9: Theorem 2
Step10: Better ways for root-finding/optimization
If $x^$ is a fixed point of $g(x)$ then $x^$ is also a root of $f(x^) = g(x^) - x^$ s.t. $f(x^) = 0$.
$$f(r) = r - \frac{m P}{A} \left [ \left (1 + \frac{r}{m} \right)^{m n} - 1 \right ] =0 $$
or
$$f(r) = A - \frac{m P}{r} \left [ \left (1 + \frac{r}{m} \right)^{m n} - 1 \right ] =0 $$
Classical Methods
Bisection (linear convergence)
Newton's Method (quadratic convergence)
Secant Method (super-linear)
Combined Methods
RootSafe (Newton + Bisection)
Brent's Method (Secant + Bisection)
Bracketing and Bisection
A bracket is an interval $[a,b]$ s.t. $\text{sign}(f(a)) \neq \text{sign}(f(b))$.
Theorem
Step11: Bisection Algorithm
Given a bracket $[a,b]$ and a function $f(x)$ -
1. Initialize with bracket
2. Iterate
1. Cut bracket in half and check to see where the zero is
2. Set bracket to new bracket based on what direction we went
Step12: Convergence of Bisection
$$|e_{k+1}| = C |e_k|^n$$
$$e_k \approx \Delta x_k$$
$$e_{k+1} \approx \frac{1}{2} \Delta x_k$$
$$|e_{k+1}| = \frac{1}{2} |e_k|$$
$\Rightarrow$ Linear convergence
Newton's Method (Newton-Raphson)
Given a bracket, bisection is guaranteed to converge linearly to a root
However bisection uses almost no information about $f(x)$ beyond its sign at a point
Basic Idea
Step13: Algorithm
Initialize $x_k$
Begin loop and calculate what $x_{k+1}$
Check stopping criteria
Step14: Example
Step15: Other Issues
Need to supply both $f(x)$ and $f'(x)$, could be expensive
Example
Step16: Algorithm
Given $f(x)$, given bracket $[a,b]$, a TOLERANCE, and a MAX_STEPS
Initialize $x_1 = a$, $x_2 = b$, $f_1 = f(x_1)$, and $f_2 = f(x_2)$
Loop until either MAX_STEPS is reached or TOLERANCE is achieved
Calculate new update $x_{k+1}$
Check for convergence and break if reached
Update parameters $x_1$, $x_2$, $f_1 = f(x_1)$ and $f_2(x_2)$
Celebrate
Step18: Comments
Secant method as shown is equivalent to linear interpolation
Can use higher order interpolation for higher order secant methods
Convergence is not quite quadratic
Not gauranteed to converge
Do not preserve brackets
Almost as good as Newton's method if your initial guess is good.
Hybrid Methods
Combine attributes of methods with others to make one great algorithm to rule them all (not really)
Goals
Robustness
Step19: Interpolation Approach
Successive parabolic interpolation - similar to secant method
Basic idea
Step20: Scipy Optimization
Scipy contains a lot of ways for optimization! | Python Code:
def total_value(P, m, r, n):
Total value of portfolio given parameters
Based on following formula:
A = \frac{P}{(r / m)} \left[ \left(1 + \frac{r}{m} \right)^{m \cdot n}
- 1 \right ]
:Input:
- *P* (float) - Payment amount per compounding period
- *m* (int) - number of compounding periods per year
- *r* (float) - annual interest rate
- *n* (float) - number of years to retirement
:Returns:
(float) - total value of portfolio
return P / (r / float(m)) * ( (1.0 + r / float(m))**(float(m) * n)
- 1.0)
P = 1500.0
m = 12
n = 20.0
r = numpy.linspace(0.05, 0.1, 100)
goal = 1e6
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(r, total_value(P, m, r, n))
axes.plot(r, numpy.ones(r.shape) * goal, 'r--')
axes.set_xlabel("r (interest rate)")
axes.set_ylabel("A (total value)")
axes.set_title("When can I retire?")
axes.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))
plt.show()
Explanation: Root Finding and Optimization
GOAL: Find where $f(x) = 0$.
Example: Future Time Annuity
When can I retire?
$$ A = \frac{P}{(r / m)} \left[ \left(1 + \frac{r}{m} \right)^{m \cdot n} - 1 \right ] $$
$P$ is payment amount per compounding period
$m$ number of compounding periods per year
$r$ annual interest rate
$n$ number of years to retirement
$A$ total value after $n$ years
If I want to retire in 20 years what does $r$ need to be?
Set $P = \frac{\$18,000}{12} = \$1500, ~~~~ m=12, ~~~~ n=20$.
End of explanation
def g(P, m, r, n, A):
Reformulated minimization problem
Based on following formula:
g(r) = \frac{P \cdot m}{A} \left[ \left(1 + \frac{r}{m} \right)^{m \cdot n} - 1 \right ]
:Input:
- *P* (float) - Payment amount per compounding period
- *m* (int) - number of compounding periods per year
- *r* (float) - annual interest rate
- *n* (float) - number of years to retirement
- *A* (float) - total value after $n$ years
:Returns:
(float) - value of g(r)
return P * m / A * ( (1.0 + r / float(m))**(float(m) * n)
- 1.0)
P = 1500.0
m = 12
n = 20.0
r = numpy.linspace(0.00, 0.1, 100)
goal = 1e6
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(r, g(P, m, r, n, goal))
axes.plot(r, r, 'r--')
axes.set_xlabel("r (interest rate)")
axes.set_ylabel("$g(r)$")
axes.set_title("When can I retire?")
axes.set_ylim([0, 0.12])
axes.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))
plt.show()
Explanation: Fixed Point Iteration
How do we go about solving this?
Could try to solve at least partially for $r$:
$$ A = \frac{P}{(r / m)} \left[ \left(1 + \frac{r}{m} \right)^{m \cdot n} - 1 \right ] ~~~~ \Rightarrow ~~~~~$$
$$ r = \frac{P \cdot m}{A} \left[ \left(1 + \frac{r}{m} \right)^{m \cdot n} - 1 \right ] ~~~~ \Rightarrow ~~~~~$$
$$ r = g(r)$$
or
$$ g(r) - r = 0$$
End of explanation
r = 0.09
for steps in xrange(10):
print "r = ", r
print "Residual = ", g(P, m, r, n, goal) - r
r = g(P, m, r, n, goal)
print
Explanation: Guess at $r_0$ and check to see what direction we need to go...
$r_0 = 0.0800$, $g(r_0) - r_0 = -0.009317550125425428$
$r_1 = 0.0850$, $g(r_1) - r_1 = -0.00505763375972$
$r_2 = 0.0875$, $g(r_2) - r_2 = -0.00257275331014$
A bit tedious, we can also make this algorithmic:
End of explanation
x = numpy.linspace(0.2, 1.0, 100)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(x, numpy.exp(-x), 'r')
axes.plot(x, x, 'b')
axes.set_xlabel("x")
axes.set_ylabel("f(x)")
x = 0.4
for steps in xrange(7):
print "x = ", x
print "Residual = ", numpy.exp(-x) - x
x = numpy.exp(-x)
print
axes.plot(x, numpy.exp(-x),'o',)
plt.show()
Explanation: Example 2:
Let $f(x) = x - e^{-x}$, solve $f(x) = 0$
Equivalent to $x = e^{-x}$ or $x = g(x)$ where $g(x) = e^{-x}$
Note that this problem is equivalent to $x = -\ln x$.
End of explanation
x = numpy.linspace(0.1, 1.0, 100)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(x, -numpy.log(x), 'r')
axes.plot(x, x, 'b')
axes.set_xlabel("x")
axes.set_ylabel("f(x)")
axes.set_ylim([0.0, 1.5])
x = 0.5
for steps in xrange(3):
print "x = ", x
print "Residual = ", numpy.log(x) + x
x = -numpy.log(x)
print
axes.plot(x, -numpy.log(x),'o',)
plt.show()
Explanation: Example 3:
Let $f(x) = \ln x + x$ and solve $f(x) = 0$ or $x = -\ln x$.
End of explanation
x = numpy.linspace(0.0, 1.0, 100)
# Plot function and intercept
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(x, numpy.exp(-x), 'r')
axes.plot(x, x, 'b')
axes.set_xlabel("x")
axes.set_ylabel("f(x)")
# Plot domain and range
axes.plot(numpy.ones(x.shape) * 0.4, x, '--k')
axes.plot(numpy.ones(x.shape) * 0.8, x, '--k')
axes.plot(x, numpy.ones(x.shape) * numpy.exp(-0.4), '--k')
axes.plot(x, numpy.ones(x.shape) * numpy.exp(-0.8), '--k')
axes.set_xlim((0.0, 1.0))
axes.set_ylim((0.0, 1.0))
plt.show()
x = numpy.linspace(0.1, 1.0, 100)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(x, -numpy.log(x), 'r')
axes.plot(x, x, 'b')
axes.set_xlabel("x")
axes.set_ylabel("f(x)")
axes.set_xlim([0.1, 1.0])
axes.set_ylim([0.1, 1.0])
# Plot domain and range
axes.plot(numpy.ones(x.shape) * 0.4, x, '--k')
axes.plot(numpy.ones(x.shape) * 0.8, x, '--k')
axes.plot(x, numpy.ones(x.shape) * -numpy.log(0.4), '--k')
axes.plot(x, numpy.ones(x.shape) * -numpy.log(0.8), '--k')
plt.show()
Explanation: These are equivalent problems! Something is awry...
Analysis of Fixed Point Iteration
Theorem: Existence and uniqueness of fixed point problems
Assume $g \in C[a, b]$, if the range of the mapping $y = g(x)$ satisfies $y \in [a, b]~~~ \forall~~~ x \in [a, b]$ then $g$ has a fixed point in $[a, b]$.
End of explanation
x = numpy.linspace(0.4, 0.8, 100)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(x, -numpy.exp(-x), 'r')
axes.set_xlabel("x")
axes.set_ylabel("f(x)")
plt.show()
Explanation: Additionally, suppose $g'(x)$ is defined for $x \in [a,b]$ and $\exists K < 1$ s.t. $|g'(x)| \leq K < 1 ~~~ \forall ~~~ x \in (a,b)$, then $g$ has a unique fixed point $P \in [a,b]$
End of explanation
import sympy
m, P, A, r, n = sympy.symbols('m, P, A, r, n')
(m * P / A * ((1 + r / m)**(m * n) - 1)).diff(r)
Explanation: Theorem 2: Asymptotic convergence behavior of fixed point iterations
$$x_{k+1} = g(x_k)$$
Assume that $\exists ~ x^$ s.t. $x^ = g(x^*)$
$$x_k = x^ + e_k ~~~~~~~~~~~~~~ x_{k+1} = x^ + e_{k+1}$$
$$x^ + e_{k+1} = g(x^ + e_k)$$
Using a Taylor expansion we know
$$g(x^ + e_k) = g(x^) + g'(x^) e_k + \frac{g''(x^) e_k^2}{2}$$
$$x^ + e_{k+1} = g(x^) + g'(x^) e_k + \frac{g''(x^) e_k^2}{2}$$
Note that because $x^ = g(x^)$ these terms cancel leaving
$$e_{k+1} = g'(x^) e_k + \frac{g''(x^) e_k^2}{2}$$
So if $|g'(x^*)| \leq K < 1$ we can conclude that
$$|e_{k+1}| = K |e_k|$$
which shows convergence (although somewhat arbitrarily fast).
Convergence of iterative schemes
Given any iterative scheme where
$$|e_{k+1}| = C |e_k|^n$$
If $C < 1$ and
- $n=1$ then the scheme is linearly convergence
- $n=2$ then the scheme exhibits quadratic convergence
- $n > 1$ the scheme can also be called superlinearly convergent
If $C > 1$ then the scheme is divergent
Examples Revisited
$g(x) = e^{-x}$ with $x^* \approx 0.56$
$$|g'(x^)| = |-e^{-x^}| \approx 0.56$$
$g(x) = - \ln x$ with $x^* \approx 0.56$
$$|g'(x^)| = \frac{1}{|x^|} \approx 1.79$$
$g(r) = \frac{m P}{A} ((1 + \frac{r}{m})^{mn} - 1)$ with $r^* \approx 0.09$
$$|g'(r^*)| = \frac{P m n}{A} \left(1 + \frac{r}{m} \right)^{m n - 1} \approx 2.15$$
End of explanation
P = 1500.0
m = 12
n = 20.0
A = 1e6
r = numpy.linspace(0.05, 0.1, 100)
f = lambda r, A, m, P, n: A - m * P / r * ((1.0 + r / m)**(m * n) - 1.0)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(r, f(r, A, m, P, n), 'b')
axes.plot(r, numpy.zeros(r.shape),'r--')
axes.set_xlabel("r (%)")
axes.set_ylabel("f(r)")
axes.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))
a = 0.075
b = 0.095
axes.plot(a, f(a, A, m, P, n), 'ko')
axes.plot([a, a], [0.0, f(a, A, m, P, n)], 'k--')
axes.plot(b, f(b, A, m, P, n), 'ko')
axes.plot([b, b], [f(b, A, m, P, n), 0.0], 'k--')
plt.show()
Explanation: Better ways for root-finding/optimization
If $x^$ is a fixed point of $g(x)$ then $x^$ is also a root of $f(x^) = g(x^) - x^$ s.t. $f(x^) = 0$.
$$f(r) = r - \frac{m P}{A} \left [ \left (1 + \frac{r}{m} \right)^{m n} - 1 \right ] =0 $$
or
$$f(r) = A - \frac{m P}{r} \left [ \left (1 + \frac{r}{m} \right)^{m n} - 1 \right ] =0 $$
Classical Methods
Bisection (linear convergence)
Newton's Method (quadratic convergence)
Secant Method (super-linear)
Combined Methods
RootSafe (Newton + Bisection)
Brent's Method (Secant + Bisection)
Bracketing and Bisection
A bracket is an interval $[a,b]$ s.t. $\text{sign}(f(a)) \neq \text{sign}(f(b))$.
Theorem: If $f(x) \in C[a,b]$ and $\text{sign}(f(a)) \neq \text{sign}(f(b))$ then there exists a number $c \in (a,b)$ s.t. $f(c) = 0$. (proof uses intermediate value theorem)
End of explanation
P = 1500.0
m = 12
n = 20.0
A = 1e6
r = numpy.linspace(0.05, 0.11, 100)
f = lambda r, A=A, m=m, P=P, n=n: A - m * P / r * ((1.0 + r / m)**(m * n) - 1.0)
# Initialize bracket
a = 0.07
b = 0.10
# Setup figure to plot convergence
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(r, f(r, A, m, P, n), 'b')
axes.plot(r, numpy.zeros(r.shape),'r--')
axes.set_xlabel("r (%)")
axes.set_ylabel("f(r)")
# axes.set_xlim([0.085, 0.091])
axes.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))
axes.plot(a, f(a, A, m, P, n), 'ko')
axes.plot([a, a], [0.0, f(a, A, m, P, n)], 'k--')
axes.plot(b, f(b, A, m, P, n), 'ko')
axes.plot([b, b], [f(b, A, m, P, n), 0.0], 'k--')
# Algorithm parameters
TOLERANCE = 1e-4
MAX_STEPS = 100
# Initialize loop
f_a = f(a)
f_b = f(b)
delta_x = b - a
# Loop until we reach the TOLERANCE or we take MAX_STEPS
for step in xrange(MAX_STEPS):
c = a + delta_x / 2.0
f_c = f(c)
if numpy.sign(f_a) != numpy.sign(f_c):
b = c
f_b = f_c
else:
a = c
f_a = f_c
delta_x = b - a
# Plot iteration
axes.text(c, f(c), str(step))
# Check tolerance - Could also check the size of delta_x
if numpy.abs(f_c) < TOLERANCE:
break
if step == MAX_STEPS:
print "Reached maximum number of steps!"
else:
print "Success!"
print " x* = %s" % c
print " f(x*) = %s" % f(c)
print " number of steps = %s" % step
Explanation: Bisection Algorithm
Given a bracket $[a,b]$ and a function $f(x)$ -
1. Initialize with bracket
2. Iterate
1. Cut bracket in half and check to see where the zero is
2. Set bracket to new bracket based on what direction we went
End of explanation
P = 1500.0
m = 12
n = 20.0
A = 1e6
r = numpy.linspace(0.05, 0.11, 100)
f = lambda r, A=A, m=m, P=P, n=n: \
A - m * P / r * ((1.0 + r / m)**(m * n) - 1.0)
f_prime = lambda r, A=A, m=m, P=P, n=n: \
-P*m*n*(1.0 + r/m)**(m*n)/(r*(1.0 + r/m)) \
+ P*m*((1.0 + r/m)**(m*n) - 1.0)/r**2
# Algorithm parameters
MAX_STEPS = 100
TOLERANCE = 1e-4
# Initial guess
x_k = 0.06
# Setup figure to plot convergence
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(r, f(r), 'b')
axes.plot(r, numpy.zeros(r.shape),'r--')
# Plot x_k point
axes.plot([x_k, x_k], [0.0, f(x_k)], 'k--')
axes.plot(x_k, f(x_k), 'ko')
axes.text(x_k, -5e4, "$x_k$", fontsize=16)
axes.text(x_k, f(x_k) + 2e4, "$f(x_k)$", fontsize=16)
axes.plot(r, f_prime(x_k) * (r - x_k) + f(x_k), 'k')
# Plot x_{k+1} point
x_k = x_k - f(x_k) / f_prime(x_k)
axes.plot([x_k, x_k], [0.0, f(x_k)], 'k--')
axes.plot(x_k, f(x_k), 'ko')
axes.text(x_k, 1e4, "$x_k$", fontsize=16)
axes.text(0.089, f(x_k) - 2e4, "$f(x_k)$", fontsize=16)
axes.set_xlabel("r (%)")
axes.set_ylabel("f(r)")
axes.set_title("Newton-Raphson Steps")
axes.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))
plt.show()
Explanation: Convergence of Bisection
$$|e_{k+1}| = C |e_k|^n$$
$$e_k \approx \Delta x_k$$
$$e_{k+1} \approx \frac{1}{2} \Delta x_k$$
$$|e_{k+1}| = \frac{1}{2} |e_k|$$
$\Rightarrow$ Linear convergence
Newton's Method (Newton-Raphson)
Given a bracket, bisection is guaranteed to converge linearly to a root
However bisection uses almost no information about $f(x)$ beyond its sign at a point
Basic Idea: Given $f(x)$ and $f'(x)$ use a linear approximation to $f(x)$ "locally" and use x-intercept of the resulting line to predict where $x^*$ might be.
Given current location $x_k$, we have $f(x_k)$ and $f'(x_k)$ and form a line through the point $(x_k, f(x_k))$:
Form equation for the line:
$$y = f'(x_k) x + b$$
Solve for the y-intercept value $b$
$$f(x_k) = f'(x_k) x_k + b$$
$$b = f(x_k) - f'(x_k) x_k$$
and simplify.
$$y = f'(x_k) x + f(x_k) - f'(x_k) x_k$$
$$y = f'(x_k) (x - x_k) + f(x_k)$$
Now find the intersection of our line and the x-axis (i.e. when $y = 0$) and use the resulting value of $x$ to set $x_{k+1}$
$$0 = f'(x_k) (x_{k+1}-x_k) + f(x_k)$$
$$x_{k+1} = x_k-\frac{f(x_k)}{f'(x_k)}$$
End of explanation
P = 1500.0
m = 12
n = 20.0
A = 1e6
r = numpy.linspace(0.05, 0.11, 100)
f = lambda r, A=A, m=m, P=P, n=n: \
A - m * P / r * ((1.0 + r / m)**(m * n) - 1.0)
f_prime = lambda r, A=A, m=m, P=P, n=n: \
-P*m*n*(1.0 + r/m)**(m*n)/(r*(1.0 + r/m)) \
+ P*m*((1.0 + r/m)**(m*n) - 1.0)/r**2
# Algorithm parameters
MAX_STEPS = 100
TOLERANCE = 1e-4
# Initial guess
x_k = 0.06
# Setup figure to plot convergence
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(r, f(r), 'b')
axes.plot(r, numpy.zeros(r.shape),'r--')
for n in xrange(1, MAX_STEPS + 1):
axes.text(x_k, f(x_k), str(n))
x_k = x_k - f(x_k) / f_prime(x_k)
if numpy.abs(f(x_k)) < TOLERANCE:
break
if n == MAX_STEPS:
print "Reached maximum number of steps!"
else:
print "Success!"
print " x* = %s" % x_k
print " f(x*) = %s" % f(x_k)
print " number of steps = %s" % n
axes.set_xlabel("r (%)")
axes.set_ylabel("f(r)")
axes.set_title("Newton-Raphson Steps")
axes.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))
plt.show()
Explanation: Algorithm
Initialize $x_k$
Begin loop and calculate what $x_{k+1}$
Check stopping criteria
End of explanation
x = numpy.linspace(0, 2, 1000)
f = lambda x: numpy.sin(2.0 * numpy.pi * x)
f_prime = lambda x: 2.0 * numpy.pi * numpy.cos(2.0 * numpy.pi * x)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(x, f(x),'b')
axes.plot(x, f_prime(x), 'r')
axes.set_xlabel("x")
axes.set_ylabel("y")
axes.set_title("Comparison of $f(x)$ and $f'(x)$")
axes.set_ylim((-2,2))
axes.set_xlim((0,2))
axes.plot(x, numpy.zeros(x.shape), 'k--')
x_k = 0.3
axes.plot([x_k, x_k], [0.0, f(x_k)], 'ko')
axes.plot([x_k, x_k], [0.0, f(x_k)], 'k--')
axes.plot(x, f_prime(x_k) * (x - x_k) + f(x_k), 'k')
x_k = x_k - f(x_k) / f_prime(x_k)
axes.plot([x_k, x_k], [0.0, f(x_k)], 'ko')
axes.plot([x_k, x_k], [0.0, f(x_k)], 'k--')
plt.show()
x = numpy.linspace(0, 2, 1000)
f = lambda x: numpy.sin(2.0 * numpy.pi * x)
x_kp = lambda x: x - 1.0 / (2.0 * numpy.pi) * numpy.tan(2.0 * numpy.pi * x)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(x, f(x),'b')
axes.plot(x, x_kp(x), 'r')
axes.set_xlabel("x")
axes.set_ylabel("y")
axes.set_title("Comparison of $f(x)$ and $f'(x)$")
axes.set_ylim((-2,2))
axes.set_xlim((0,2))
axes.plot(x, numpy.zeros(x.shape), 'k--')
plt.show()
Explanation: Example:
$$f(x) = x - e^{-x}$$
$$f'(x) = 1 + e^{-x}$$
$$x_{k+1} = x_k - \frac{f(x_k)}{f'(x_k)} = x_k - \frac{x_k - e^{-x_k}}{1 + e^{-x_k}}$$
Asymptotic Convergence of Newton's Method
For a simple root (non-multiplicative) - Let $g(x) = x - \frac{f(x)}{f'(x)}$, then
$$x_{k+1} = g(x_k)$$
Definitions of errors and iteration:
$$x_{k+1} = x^ + e_{k+1} ~~~~~ x_k = x^ + e_k$$
General Taylor expansion:
$$x^ + e_{k+1} = g(x^ + e_k) = g(x^) + g'(x^) e_k + \frac{g''(x^*) e_k^2}{2!} + \ldots$$
Note that as before $x^$ and $g(x^)$ cancel:
$$e_{k+1} = g'(x^) e_k + \frac{g''(x^) e_k^2}{2!} + \ldots$$
What about $g'(x^*)$ though:
$$g'(x) = 1 - \frac{f'(x)}{f'(x)} + \frac{f(x)}{f''(x)}$$
which simplifies when evaluated at $x = x^*$ to
$$g'(x^) = \frac{f(x^)}{f''(x^*)} = 0$$
The expansion then simplifies to
$$e_{k+1} = \frac{g''(x^*) e_k^2}{2!} + \ldots$$
leading to the conclusion that
$$|e_{k+1}| = \left | \frac{g''(x^*)}{2!} \right | |e_k|^2$$
Newton's method is therefore quadratically convergent where the the constant is controlled by the second derivative.
For a multiple root (e.g. $f(x) = (x-1)^2$) the case is not particularly rosey unfortunately.
Example:
$f(x) = \sin (2 \pi x)$
$$x_{k+1} = x_k - \frac{\sin (2 \pi x)}{2 \pi \cos (2 \pi x)}= x_k - \frac{1}{2 \pi} \tan (2 \pi x)$$
End of explanation
P = 1500.0
m = 12
n = 20.0
A = 1e6
r = numpy.linspace(0.05, 0.11, 100)
f = lambda r, A=A, m=m, P=P, n=n: \
A - m * P / r * ((1.0 + r / m)**(m * n) - 1.0)
# Initial guess
x_k = 0.07
x_km = 0.06
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(r, f(r), 'b')
axes.plot(r, numpy.zeros(r.shape),'r--')
axes.plot(x_k, 0.0, 'ko')
axes.plot(x_k, f(x_k), 'ko')
axes.plot([x_k, x_k], [0.0, f(x_k)], 'k--')
axes.plot(x_km, 0.0, 'ko')
axes.plot(x_km, f(x_km), 'ko')
axes.plot([x_km, x_km], [0.0, f(x_km)], 'k--')
axes.plot(r, (f(x_k) - f(x_km)) / (x_k - x_km) * (r - x_k) + f(x_k), 'k')
x_kp = x_k - (f(x_k) * (x_k - x_km) / (f(x_k) - f(x_km)))
axes.plot(x_kp, 0.0, 'ro')
axes.plot([x_kp, x_kp], [0.0, f(x_kp)], 'r--')
axes.plot(x_kp, f(x_kp), 'ro')
axes.set_xlabel("r (%)")
axes.set_ylabel("f(r)")
axes.set_title("Secant Method")
axes.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))
plt.show()
Explanation: Other Issues
Need to supply both $f(x)$ and $f'(x)$, could be expensive
Example: FTV equation $f(r) = A - \frac{m P}{r} \left[ \left(1 + \frac{r}{m} \right )^{m n} - 1\right]$
Can use symbolic differentiation (sympy)
Secant Methods
Is there a method with the convergence of Newton's method but without the extra derivatives? Maybe something that calculates the derivative rather than expects it?
Given $x_k$ and $x_{k-1}$ represent the derivative as
$$f'(x) \approx \frac{f(x_k) - f(x_{k-1})}{x_k - x_{k-1}}$$
Combining this with the basic approach of Newton leads to
$$x_{k+1} = x_k - \frac{f(x_k) (x_k - x_{k-1}) }{f(x_k) - f(x_{k-1})}$$
This leads to superlinear convergence (the exponent on the convergence is $\approx 1.7$)
Alternative interpretation, fit a line through two points and see where they intersect the x-axis.
$$(x_k, f(x_k)) ~~~~~ (x_{k-1}, f(x_{k-1})$$
$$y = \frac{f(x_k) - f(x_{k-1})}{x_k - x_{k-1}} (x - x_k) + b$$
$$b = f(x_{k-1}) - \frac{f(x_k) - f(x_{k-1})}{x_k - x_{k-1}} (x_{k-1} - x_k)$$
$$ y = \frac{f(x_k) - f(x_{k-1})}{x_k - x_{k-1}} (x - x_k) + f(x_k)$$
Now solve for $x_{k+1}$ which is where the line intersects the x-axies ($y=0$)
$$0 = \frac{f(x_k) - f(x_{k-1})}{x_k - x_{k-1}} (x_{k+1} - x_k) + f(x_k)$$
$$x_{k+1} = x_k - \frac{f(x_k) (x_k - x_{k-1})}{f(x_k) - f(x_{k-1})}$$
End of explanation
P = 1500.0
m = 12
n = 20.0
A = 1e6
r = numpy.linspace(0.05, 0.11, 100)
f = lambda r, A=A, m=m, P=P, n=n: \
A - m * P / r * ((1.0 + r / m)**(m * n) - 1.0)
f_prime = lambda r, A=A, m=m, P=P, n=n: \
-P*m*n*(1.0 + r/m)**(m*n)/(r*(1.0 + r/m)) \
+ P*m*((1.0 + r/m)**(m*n) - 1.0)/r**2
# Algorithm parameters
MAX_STEPS = 100
TOLERANCE = 1e-4
# Initial guess
x_k = 0.07
x_km = 0.06
# Setup figure to plot convergence
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(r, f(r), 'b')
axes.plot(r, numpy.zeros(r.shape),'r--')
for n in xrange(1, MAX_STEPS + 1):
axes.plot(x_k, f(x_k), 'o')
x_kp = x_k - f(x_k) * (x_k - x_km) / (f(x_k) - f(x_km))
x_km = x_k
x_k = x_kp
if numpy.abs(f(x_k)) < TOLERANCE:
break
if n == MAX_STEPS:
print "Reached maximum number of steps!"
else:
print "Success!"
print " x* = %s" % x_k
print " f(x*) = %s" % f(x_k)
print " number of steps = %s" % n
axes.set_xlabel("r (%)")
axes.set_ylabel("f(r)")
axes.set_title("Secant Method")
axes.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))
plt.show()
Explanation: Algorithm
Given $f(x)$, given bracket $[a,b]$, a TOLERANCE, and a MAX_STEPS
Initialize $x_1 = a$, $x_2 = b$, $f_1 = f(x_1)$, and $f_2 = f(x_2)$
Loop until either MAX_STEPS is reached or TOLERANCE is achieved
Calculate new update $x_{k+1}$
Check for convergence and break if reached
Update parameters $x_1$, $x_2$, $f_1 = f(x_1)$ and $f_2(x_2)$
Celebrate
End of explanation
# New Test Function!
def f(t):
Simple function for minimization demos
return -3.0 * numpy.exp(-(t - 0.3)**2 / (0.1)**2) \
+ numpy.exp(-(t - 0.6)**2 / (0.2)**2) \
+ numpy.exp(-(t - 1.0)**2 / (0.2)**2) \
+ numpy.sin(t) \
- 2.0
t = numpy.linspace(0, 2, 200)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(t, f(t))
axes.set_xlabel("t (days)")
axes.set_ylabel("People (N)")
axes.set_title("Decrease in Population due to SPAM Poisoning")
plt.show()
phi = (numpy.sqrt(5.0) - 1.0) / 2.0
TOLERANCE = 1e-4
MAX_STEPS = 100
a = 0.2
b = 0.5
c = b - phi * (b - a)
d = a + phi * (b - a)
t = numpy.linspace(0, 2, 200)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(t, f(t))
axes.set_xlabel("t (days)")
axes.set_ylabel("People (N)")
axes.set_title("Decrease in Population due to SPAM Poisoning")
success = False
for n in xrange(1, MAX_STEPS + 1):
axes.plot(a, f(a),'ko')
axes.plot(b, f(b),'ko')
fc = f(c)
fd = f(d)
if fc < fd:
b = d
d = c
c = b - phi * (b - a)
else:
a = c
c = d
d = a + phi * (b - a)
if numpy.abs(b - a) < TOLERANCE:
success = True
break
if success:
print "Success!"
print " t* = %s" % str((b + a) / 2.0)
print " f(t*) = %s" % f((b + a) / 2.0)
print " number of steps = %s" % n
else:
print "Reached maximum number of steps!"
plt.show()
Explanation: Comments
Secant method as shown is equivalent to linear interpolation
Can use higher order interpolation for higher order secant methods
Convergence is not quite quadratic
Not gauranteed to converge
Do not preserve brackets
Almost as good as Newton's method if your initial guess is good.
Hybrid Methods
Combine attributes of methods with others to make one great algorithm to rule them all (not really)
Goals
Robustness: Given a bracket $[a,b]$, maintain bracket
Efficiency: Use superlinear convergent methods when possible
Options
Methods requiring $f'(x)$
NewtSafe (RootSafe, Numerical Recipes)
Newton's Method within a bracket, Bisection otherwise
Methods not requiring $f'(x)$
Brent's Algorithm (zbrent, Numerical Recipes)
Combination of bisection, secant and inverse quadratic interpolation
scipy.optimize package
Optimization (finding extrema)
I want to find the extrema of a function $f(x)$ on a given interval $[a,b]$.
A few approaches:
- Bracketing Algorithms: Golden-Section Search (linear)
- Interpolation Alogithms: Repeated parabolic interpolation
- Hybrid Algorithms
Bracketing Algorithm (Golden Section Search)
Given $f(x) \in C[a,b]$ that is convex over an interval $x \in [a,b]$ reduce the interval size until it brackets the minimum.
Note that we no longer have the $x=0$ help we had before so bracketing and doing bisection is a bit more tricky in this case. In particular choosing your initial bracket is important!
Bracketing Algorithm (Golden Section Search)
Given $f(x) \in C[a,b]$ that is convex over an interval $x \in [a,b]$ reduce the interval size until it brackets the minimum.
Note that we no longer have the $x=0$ help we had before so bracketing and doing bisection is a bit more tricky in this case. In particular choosing your initial bracket is important!
Golden Section Search - Picking Intervals
We also may want to choose the search points $c$ and $d$ so that the distance between $a$ and $d$, say $\Delta_{ad}$, and $b$ and $c$, say $\Delta_{bc}$, is carefully choosen. For Golden Section Search we require that these are equal. This tells use where to put $d$ but not $c$. The Golden Section Search also requires that $b$ should be choosen so that the spacing between the points have the same porportion as $(a, c, d)$ and $(c, d, b)$.
Ok, that's weird. Also, why are we calling this thing "Golden"?
Mathematically:
If $f(d) > f(c)$ then
$$\frac{\Delta_{cd}}{\Delta_{ca}} = \frac{\Delta_{ca}}{\Delta_{bc}}$$
If $f(d) < f(c)$ then
$$\frac{\Delta_{cd}}{\Delta_{bc} - \Delta_{cd}} = \frac{\Delta_{ca}}{\Delta_{bc}}$$
Eliminating $\Delta_{cd}$ leads to the equation
$$\left( \frac{\Delta_cb}{\Delta_{ca}} \right )^2 = \frac{\Delta_cb}{\Delta_{ca}} + 1$$
Solving this leads to
$$ \frac{\Delta_cb}{\Delta_{ca}} = \varphi$$
where $\varphi$ is the golden ratio!
$$\varphi = \frac{1 \pm \sqrt{5}}{2}$$
Algorithm
Initialize bracket $[a,b]$ and compute $f_a = f(a)$ and $f_b = f(b)$, $\Delta x = b-a$
Initialize points $c = b - \varphi * (b - a)$ and $d = a + \varphi * (b -a)$
Loop
Evaluate $f_c$ and $f_d$
If $f_c < f_d$ then we pick the left interval for the next iteration
and otherwise pick the right interval
Check size of bracket for convergence $\Delta_{cd} <$ TOLERANCE
End of explanation
MAX_STEPS = 100
TOLERANCE = 1e-4
a = 0.5
b = 0.2
x = numpy.array([a, b, (a + b) / 2.0])
t = numpy.linspace(0, 2, 200)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(t, f(t))
axes.set_xlabel("t (days)")
axes.set_ylabel("People (N)")
axes.set_title("Decrease in Population due to SPAM Poisoning")
axes.plot(x[0], f(x[0]), 'ko')
axes.plot(x[1], f(x[1]), 'ko')
success = False
for n in xrange(1, MAX_STEPS + 1):
axes.plot(x[2], f(x[2]), 'ko')
poly = numpy.polyfit(x, f(x), 2)
axes.plot(t, poly[0] * t**2 + poly[1] * t + poly[2], 'r--')
x[0] = x[1]
x[1] = x[2]
x[2] = -poly[1] / (2.0 * poly[0])
if numpy.abs(x[2] - x[1]) / numpy.abs(x[2]) < TOLERANCE:
success = True
break
if success:
print "Success!"
print " t* = %s" % x[2]
print " f(t*) = %s" % f(x[2])
print " number of steps = %s" % n
else:
print "Reached maximum number of steps!"
axes.set_ylim((-5, 0.0))
plt.show()
Explanation: Interpolation Approach
Successive parabolic interpolation - similar to secant method
Basic idea: Fit polynomial to function using three points, find it's minima, and guess new points based on that minima
Algorithm
Given $f(x)$ and $[a,b]$
1. Initialize $x = [a, b, (a+b)/2]$
1. Loop
1. Evaluate function $f(x)$
1. Use a polynomial fit to the function:
$$p(x) = p_0 x^2 + p_1 x + p_2$$
Calculate the minimum:
$$p'(x) = 2 p_0 x + b = 0 ~~~~ \Rightarrow ~~~~ x = -b / (2 p_0)$$
Calculate new interval
Check tolerance
End of explanation
import scipy.optimize as optimize
optimize.golden(f, brack=(0.2, 0.25, 0.5))
Explanation: Scipy Optimization
Scipy contains a lot of ways for optimization!
End of explanation |
7,458 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Use Case 3
Step1: Open MODIS/Aqua files with chlorophyll in the North Sea and fetch data
Step2: Plot chlorophyll-a maps in swath projection
Step3: Colocate data. Reproject both images onto the same Domain. | Python Code:
# download sample files
!wget -P data -nc ftp://ftp.nersc.no/nansat/test_data/obpg_l2/A2015121113500.L2_LAC.NorthNorwegianSeas.hdf
!wget -P data -nc ftp://ftp.nersc.no/nansat/test_data/obpg_l2/A2015122122000.L2_LAC.NorthNorwegianSeas.hdf
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import Image
%matplotlib inline
from nansat import *
Explanation: Use Case 3: Colocate different data
End of explanation
n1 = Nansat('data/A2015121113500.L2_LAC.NorthNorwegianSeas.hdf')
chlor_a1 = n1['chlor_a']
n2 = Nansat('data/A2015122122000.L2_LAC.NorthNorwegianSeas.hdf')
chlor_a2 = n2['chlor_a']
Explanation: Open MODIS/Aqua files with chlorophyll in the North Sea and fetch data
End of explanation
plt.figure(figsize=(5,5))
plt.subplot(121)
plt.imshow(chlor_a1, vmin=0, vmax=3)
plt.subplot(122)
plt.imshow(chlor_a2, vmin=0, vmax=3)
plt.show()
Explanation: Plot chlorophyll-a maps in swath projection
End of explanation
# define domain in longlat projection
d = Domain('+proj=stere +lat_0=58 +lon_0=5 +no_defs',
'-te -300000 -300000 300000 300000 -tr 3000 3000')
# reproject first image and get matrix with reprojected chlorophyll
n1.reproject(d)
chlor_a1 = n1['chlor_a']
# reproject second image and get matrix with reprojected chlorophyll
n2.reproject(d)
chlor_a2 = n2['chlor_a']
# get mask of land and set values of land pixels to NAN (not-a-number)
mask1 = n1.watermask()[1]
chlor_a1[mask1 == 2] = np.nan
chlor_a2[mask1 == 2] = np.nan
# prepare landmask for plotting: land pixels=1, water pixels=NaN
landmask = 1 - mask1.astype(float)
landmask[landmask == 0] = np.nan
plt.figure(figsize=(10,10))
plt.subplot(121)
plt.imshow(chlor_a1, vmin=0, vmax=5)
plt.imshow(landmask, cmap='gray')
plt.subplot(122)
plt.imshow(chlor_a2, vmin=0, vmax=5)
plt.imshow(landmask, cmap='gray')
plt.show()
# replace negative values (clouds) by NAN
chlor_a1[chlor_a1 < 0] = np.nan
chlor_a2[chlor_a2 < 0] = np.nan
# find difference
chlor_diff = chlor_a2 - chlor_a1
# plot
plt.figure(figsize=(5,5))
plt.imshow(chlor_diff, vmin=-0.1, vmax=2);plt.colorbar()
plt.imshow(landmask, cmap='gray')
plt.show()
# get transect - vector of data from 2D matrix from known locations
points = [[200, 75], [150, 150]]
t1 = n1.get_transect(points, ['chlor_a'], lonlat=False)
chl1 = t1['chlor_a']
lon1 = t1['lon']
lat1 = t1['lat']
t2 = n2.get_transect(points, ['chlor_a'], lonlat=False)
chl2 = t2['chlor_a']
# replace negative values with NAN
chl1 = np.array(chl1)
chl2 = np.array(chl2)
chl1[(chl1 < 0) + (chl1 > 5)] = np.nan
chl2[(chl2 < 0) + (chl2 > 5)] = np.nan
print (n1.time_coverage_start)
# plot
plt.plot(lon1, chl1, '-', label=n1.time_coverage_start)
plt.plot(lon1, chl2, '-', label=n2.time_coverage_start)
plt.legend()
plt.xlabel('longitude')
plt.ylabel('chlorphyll-a')
plt.show()
Explanation: Colocate data. Reproject both images onto the same Domain.
End of explanation |
7,459 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cloud Data Center
Step1: Data Center IP Traffic | Python Code:
import matplotlib.pyplot as plt
import csv
a = []
b = []
with open('data/dc_hyperscale.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=';')
for row in plots:
a.append(int(row[0]))
b.append(int(row[1]))
plt.bar(a,b, label='Hyperscale Data Centers')
plt.xlabel('Ano \n Figura 1')
plt.ylabel('Número')
plt.title('Crescimento Global de Data Center')
plt.legend()
plt.show()
Explanation: Cloud Data Center: Analisando a demanda de utilização
## Luciano Eduardo Caciato
### Faculdade de Engenharia Elétrica e de Computação - UNICAMP
### Reprodutibilidade em Pesquisa Computacional
1. Introdução
Vivemos um momento de transformação, novamente, após a onda da virtualização de servidores e consolidação dos data centers na década passada, agora a nuvem computacional está contribuindo na competitividade das empresas e no avanço das pesquisas nas universidades.
A computação em nuvem chegou em 2017, e está ajudando a transformar as empresas proporcionando o ganho de eficiência à medida que escalam seus recursos computacionais para atender seus clientes.
No âmbito das universidades está contribuindo na disponibilidade de recursos computacionais para o processamento e armazenamento das pesquisas e também em novos ambientes que estão sendo criados e utilizados pelos docentes e alunos. O serviço mais utilizados é IaaS (Infrastruture as a Service).
Esses ambientes são processados em várias data centers espalhados pelo mundo, que entregam os recursos computacionais conforme a demanda. Nosso objetivo neste artigo é analisar a utlização dos data centers de nuvem através de pesquisas mercadológicas e utilização da infraestrutura.
Palavras Chave: Cloud Computing, Virtualização e Data Center.
2. Data Center em Nuvem
Numa simples pesquisa na Internet ou em qualquer revista de tecnologia o termo “seus dados estão na nuvem” cada vez mais fazem parte de nosso cotidiano porém ainda existem dúvidas sobre esses nomes tecnológicos, como data center, data center em nuvem e demanda de utilização, então vamos esclarecer de forma simples o que são esses três nomes:
Data Center: Local Físico construído em alvenaria ou material similar, com sistemas de refrigeração e eletricidade tolerantes a falhas e com sistemas rígidos de controle de acesso às pessoas. Neste local são hospedadas as redes de comunicação para a interconexão entre os dispositivos, servidores que fornecem o processamento e memória destinados para a computação e o storage para o armazenamento das informações.
Data Center em Nuvem: É a abstração do data center físico para lógico através da utilização do software especializado chamado virtualização onde permite a desacoplação do meio físico para o meio lógico, criando um grande pool de recursos contendo porções de processamento, memória, armazenamento e rede. E na nuvem que nada mais é que a Internet que é o meio de interconexão desses data centers e também a provedora dos serviços de nuvem.
Demanda de utilização: É a medição realizada em pontos da Internet com o objetivo de medir quanto está sendo utilizado os recursos computacionais e prever a necessidade de investimento em dinheiro e tecnologia para garantir o crescimento.
Após o esclarecimento desses termos veremos a seguir as demandas.
Ao analisarmos as demandas e crescimento das nuvens computacionais é possível levantarmos centenas de informações. Neste artigo veremos duas demandas de data center: Hyperscale Data Centers e Data Center IP Traffic.
Hyperscale Data Centers: É um data center projetado para um crescimento escalável de forma rápida, garantindo assim a entrega quase que imediata do recurso computacional. A arquitetura desde modelo é baseado em servidores pequenos com processador, memória, disco e rede, denominado como nó e o conjunto desses nós é um cluster. Nesta análise como está a demanda por esse tipo de data center, conforme figura 1.
End of explanation
import matplotlib.pyplot as plt
import csv
a = []
b = []
with open('data/dc_ip_traffic.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=';')
for row in plots:
a.append(float(row[0]))
b.append(float(row[1]))
plt.bar(a,b, label='Demanda')
plt.xlabel('Ano \n Figura 2')
plt.ylabel('Zettabytes por ano')
plt.title('Crescimento Global de Data Center\n Traffic IP')
plt.legend()
plt.show()
Explanation: Data Center IP Traffic: Quando dissemos a nuvem é composta por vários data centers interligados pela Internet, ou seja, quando olhamos o tráfego de rede percebemos que a maior parte começa e termina em um data center e esse é noss próximo objetivo, verificar qual é esse crescimento conforme a figura 2.
End of explanation |
7,460 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hybrid integrations with MERCURIUS
REBOUND comes with several integrators, each of which has its own advantages and disadvantages. MERCURIUS is a hybrid integrastor that is very similar to the hybrid integrator in John Chambers' Mercury code (J. E. Chambers 1999). It uses a symplectic Wisdom-Holman integrator when particles are far apart from each other and switches over to a high order integrator during close encounters. Specifically, MERCURIUS uses the efficient WHFast and IAS15 integrators internally.
Let's start out by showcasing the problem with traditional fixed timestep integrators such as WHFast. We setup a simulation of the outer solar system and increase the masses of the planets by a factor of 50.
Step1: Let us integrate this system for a few hundred years. An instability will occur. We can then measure the energy error, which is a good estimate as to how accurate the integration was.
Step2: An energy error that large means we basically go it wrong completely. Let's try this again but use MERCURIUS.
Step3: As you can see MERCURIUS is able to integrate this system with much better accuracy. When a close encounter occurs, it automatically (and smoothly!) switches to the IAS15 integrator. When there is not close encounter, you still get all the benefits in terms of speed an accuracy from a symplectic integrator.
There are a few options to adjust MERCURIUS. First of all, because it uses IAS15 internally, you may want to set a minimal timestep for IAS15. This ensures that IAS15 never stalls while it is tries to resolve one very close encounter and can be done with the following command
Step4: You also may want to change the critical distance at which MERCURIUS switches over from pure WHFast to IAS15. This is expressed in units of Hill radii. The default is 3 Hill radii, in the following we change it to 5 Hill radii | Python Code:
import math
import rebound, rebound.data
%matplotlib inline
sim = rebound.Simulation()
rebound.data.add_outer_solar_system(sim) # add some particles for testing
for i in range(1,sim.N):
sim.particles[i].m *= 50.
sim.integrator = "WHFast" # This will end badly!
sim.dt = sim.particles[1].P * 0.002 # Timestep a small fraction of innermost planet's period
sim.move_to_com()
E0 = sim.calculate_energy() # Calculate initial energy
rebound.OrbitPlot(sim);
Explanation: Hybrid integrations with MERCURIUS
REBOUND comes with several integrators, each of which has its own advantages and disadvantages. MERCURIUS is a hybrid integrastor that is very similar to the hybrid integrator in John Chambers' Mercury code (J. E. Chambers 1999). It uses a symplectic Wisdom-Holman integrator when particles are far apart from each other and switches over to a high order integrator during close encounters. Specifically, MERCURIUS uses the efficient WHFast and IAS15 integrators internally.
Let's start out by showcasing the problem with traditional fixed timestep integrators such as WHFast. We setup a simulation of the outer solar system and increase the masses of the planets by a factor of 50.
End of explanation
sim.integrate(600*2.*math.pi)
E1 = sim.calculate_energy()
print("Relative energy error with WHFast: %f"%((E0-E1)/E0))
Explanation: Let us integrate this system for a few hundred years. An instability will occur. We can then measure the energy error, which is a good estimate as to how accurate the integration was.
End of explanation
sim = rebound.Simulation()
rebound.data.add_outer_solar_system(sim) # add some particles for testing
for i in range(1,sim.N):
sim.particles[i].m *= 50.
sim.integrator = "mercurius"
sim.dt = sim.particles[1].P * 0.002 # Timestep a small fraction of innermost planet's period
sim.move_to_com()
E0 = sim.calculate_energy() # Calculate initial energy
sim.integrate(600*2.*math.pi)
E1 = sim.calculate_energy()
print("Relative energy error with MERCURIUS: %e"%((E1-E0)/E0))
Explanation: An energy error that large means we basically go it wrong completely. Let's try this again but use MERCURIUS.
End of explanation
# Sets the minimal timestep to a fraction of the global timestep
sim.ri_ias15.min_dt = 1e-4 * sim.dt
Explanation: As you can see MERCURIUS is able to integrate this system with much better accuracy. When a close encounter occurs, it automatically (and smoothly!) switches to the IAS15 integrator. When there is not close encounter, you still get all the benefits in terms of speed an accuracy from a symplectic integrator.
There are a few options to adjust MERCURIUS. First of all, because it uses IAS15 internally, you may want to set a minimal timestep for IAS15. This ensures that IAS15 never stalls while it is tries to resolve one very close encounter and can be done with the following command:
End of explanation
sim.ri_mercurius.hillfac = 5
Explanation: You also may want to change the critical distance at which MERCURIUS switches over from pure WHFast to IAS15. This is expressed in units of Hill radii. The default is 3 Hill radii, in the following we change it to 5 Hill radii:
End of explanation |
7,461 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Traverse a Square - Part 1 - Simply Does It
In this notebook and the next, you will explore various strategies for programming a robot to traverse a regular two dimensional shape, such as a square.
These strategies will address two different sorts of concern
Step1: Driving the Robot - Forwards, Backwards, Turns
The Pioneer P3-DX robot is a general purpose, two wheeled research robot.
<img alt="" src="../images/V-REP_PRO_EDU_-pioneer.png" />
The simulator provides access to two separate motors, defined as rotational joints with velocity control - which means we can set the speed (and direction of rotation) of them.
We have defined a Python class, PioneerP3DX, that contains methods that allow you to drive the robot forwards and backwards, either at a default speed (2.0) or at a specified speed.
move forwards
Step2: In the code cell below, see if you can write a programme that drives the robot forwards at speed 0.5 for 3 seconds.
Step3: How would you get the robot to drive forwards for 2 seconds and then backwards for 3 seconds? Modify your programme in the cell above and try it out.
Can you get the robot to drive forwards and then backwards using just the .move_forwards() method?
HINT
Step4: A Simple Square
So now you should be able to drive your robot forward, and backwards, and make it turn on the spot in either direction.
Do you think you could get it to describe a square?
In the code cell below, see if you can write a programme to drive the robot forward a short way, turn through ninety degrees, and then move forwards a short distance again.
You may find it takes a few attempts to tune the turn speed and time settings correctly so that the robot turns the correct amount.
To see how right angled the turn actually was, you may find it useful to view the robot from above - change the camera view from the top toolbar.
Don't spend too long on this - you may find that getting exactly 90 degrees every time is virtually impossible.
To see the trace clearly, you may want to pick up the robot and move it out of the way once the programme has finished. Do this by
Step5: Once you have have found some values that allow your robot to turn through ninety degrees or so, see if you can get your robot to draw out a square.
Again, don't spend too long on this. An approxi-square that looks like a bent coathanger may be the best you can get.
Step6: So how did you do?
And what does your programme look like?
I'm going to hazard a few guesses.
First, calling the trace a square may have been a little hopeful.
Second, the angle turned at each corner may have been different even using the same values, or th robot may have turned different amounts with the same settings on different runs.
Third, your programme was possibly quite long and filled with lots of repeating statements and numbers.
So what happened?
Rubbish Square
Using time to set the turn angle and side length is hazardous. The simulator is doing lots of calculations. Depending on what other activities are going on on your computer, the amount of processor time allocated to the simulator each second may differ from second to second.
Different number of calculations means different number of (calculated) simulator steps, which in turn means different result in the simulated view.
Long Programme With Lots of Steps and Repeated Numbers
You may have found your programme looked something like the one shown below (hopefully with some comments...) | Python Code:
%run 'Set-up.ipynb'
%run 'Loading scenes.ipynb'
%run 'vrep_models/PioneerP3DX.ipynb'
Explanation: Traverse a Square - Part 1 - Simply Does It
In this notebook and the next, you will explore various strategies for programming a robot to traverse a regular two dimensional shape, such as a square.
These strategies will address two different sorts of concern:
how to use programming constructs to create programmes that are concise and easy to maintain;
how to control a robot reliably.
End of explanation
%%vrepsim '../scenes/OU_Pioneer.ttt' PioneerP3DX
# Use the time library to set a wait duration
import time
#Tell the robot to move forward by setting both motors to speed 1
robot.move_forward(1)
#Wait for two seconds
time.sleep(2)
#At the end of the programme the simulation stops
#The robot returns to its original location
Explanation: Driving the Robot - Forwards, Backwards, Turns
The Pioneer P3-DX robot is a general purpose, two wheeled research robot.
<img alt="" src="../images/V-REP_PRO_EDU_-pioneer.png" />
The simulator provides access to two separate motors, defined as rotational joints with velocity control - which means we can set the speed (and direction of rotation) of them.
We have defined a Python class, PioneerP3DX, that contains methods that allow you to drive the robot forwards and backwards, either at a default speed (2.0) or at a specified speed.
move forwards: .move_forward() or .move_forward(SPEED)
move backwards: .move_backward() or .move_backward(SPEED)
Remember, if you omit a SPEED value, the default value 2.0 is used. If you use a negative value, the direction of travel is the opposite to the direction given as the method name.
Run the following code cell and watch the behaviour of the robot.
End of explanation
%%vrepsim '../scenes/OU_Pioneer.ttt' PioneerP3DX
# Use the time library to set a wait duration
import time
#YOUR CODE HERE
Explanation: In the code cell below, see if you can write a programme that drives the robot forwards at speed 0.5 for 3 seconds.
End of explanation
%%vrepsim '../scenes/OU_Pioneer.ttt' PioneerP3DX
# Use the time library to set a wait duration
import time
#YOUR CODE HERE
#FOR EXAMPLE, TO DRIVE CLOCKWISE, USE: robot.rotate_right()
#DON'T FORGET TO USE time.wait(TIME_IN_SECONDS) to give the robot time to turn
Explanation: How would you get the robot to drive forwards for 2 seconds and then backwards for 3 seconds? Modify your programme in the cell above and try it out.
Can you get the robot to drive forwards and then backwards using just the .move_forwards() method?
HINT: setting the speed to a negative value reverses the direction of travel.
The forwards and backwards commands are actually implemented by calling another method that sets the speed of each motor separately:
.set_two_motor(SPEED_LEFT_MOTOR, SPEED_RIGHT_MOTOR)
In particular:
the .move_forward(SPEED) command calls .set_two_motor(SPEED, SPEED)
the .move_backward(SPEED) command calls .set_two_motor(-SPEED, -SPEED)
Turning on the Spot
To turn on the spot in a counter-clockwise direction, that is, towards the left, we can set one motor to drive forwards at one speed and the other to drive backwards at the same speed. For example:
.rotate_left(SPEED) calls .set_two_motor(-SPEED, SPEED)
As before, if you omit the SPEED parameter, a default value (again set to 2.0) is used.
How do you think the .rotate_right() method might be defined?
Use the following code cell to write a programme to turn the Pioneer robot slowly on the spot in one direction for 2 seconds, and then faster on the spot and in the opposite direction for a further three seconds.
Also explore what happens if you call the .set_two_motor() method using different speeds for the left and right motors, in either the same, or different, directions.
End of explanation
%%vrepsim '../scenes/OU_Pioneer.ttt' PioneerP3DX
import time
#try to get the robot to draw an L shape: forward, right angle turn, forward
Explanation: A Simple Square
So now you should be able to drive your robot forward, and backwards, and make it turn on the spot in either direction.
Do you think you could get it to describe a square?
In the code cell below, see if you can write a programme to drive the robot forward a short way, turn through ninety degrees, and then move forwards a short distance again.
You may find it takes a few attempts to tune the turn speed and time settings correctly so that the robot turns the correct amount.
To see how right angled the turn actually was, you may find it useful to view the robot from above - change the camera view from the top toolbar.
Don't spend too long on this - you may find that getting exactly 90 degrees every time is virtually impossible.
To see the trace clearly, you may want to pick up the robot and move it out of the way once the programme has finished. Do this by:
select the Pioneer_3dx robot object in the Scene Hierarchy;
select the Object / Item Shift option in the top toolbar (the cube with four arrows coming out of it);
drag the robot out of the way.
Additional resources:
how to change the simulator camera view.
End of explanation
%%vrepsim '../scenes/OU_Pioneer.ttt' PioneerP3DX
import time
#Program to draw a square
Explanation: Once you have have found some values that allow your robot to turn through ninety degrees or so, see if you can get your robot to draw out a square.
Again, don't spend too long on this. An approxi-square that looks like a bent coathanger may be the best you can get.
End of explanation
%%vrepsim '../scenes/OU_Pioneer.ttt' PioneerP3DX
import time
#side 1
robot.move_forward()
time.sleep(1)
#turn 1
robot.rotate_left(1.8)
time.sleep(0.45)
#side 2
robot.move_forward()
time.sleep(1)
#turn 2
robot.rotate_left(1.8)
time.sleep(0.45)
#side 3
robot.move_forward()
time.sleep(1)
#turn 3
robot.rotate_left(1.8)
time.sleep(0.45)
#side 4
robot.move_forward()
time.sleep(1)
Explanation: So how did you do?
And what does your programme look like?
I'm going to hazard a few guesses.
First, calling the trace a square may have been a little hopeful.
Second, the angle turned at each corner may have been different even using the same values, or th robot may have turned different amounts with the same settings on different runs.
Third, your programme was possibly quite long and filled with lots of repeating statements and numbers.
So what happened?
Rubbish Square
Using time to set the turn angle and side length is hazardous. The simulator is doing lots of calculations. Depending on what other activities are going on on your computer, the amount of processor time allocated to the simulator each second may differ from second to second.
Different number of calculations means different number of (calculated) simulator steps, which in turn means different result in the simulated view.
Long Programme With Lots of Steps and Repeated Numbers
You may have found your programme looked something like the one shown below (hopefully with some comments...):
End of explanation |
7,462 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Here is my code: | Problem:
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
words = load_data()
count = CountVectorizer(lowercase=False, token_pattern='[a-zA-Z0-9$&+:;=@#|<>^*()%-]+')
vocabulary = count.fit_transform([words])
feature_names = count.get_feature_names_out() |
7,463 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Importing data
Getting data from kaggle first
Step1: Baseline model
Step2: Deep Forest
By Hand
Step3: This is not very handy, not at all. We already see a lot of code duplication, and one may feel there may be a way to abstract a lot of the logic that is happening here, in a way that is more flexible and powerful that all this boilerplate code.
With API
Step4: Going Further | Python Code:
import pkg_resources
raw_data = pd.read_csv(pkg_resources.resource_stream('deepforest', 'data/train.csv'))
clean_data = raw_data.drop(["Cabin", "Name", "PassengerId", "Ticket"], axis=1)
clean_data = pd.get_dummies(clean_data).fillna(-1)
train, test = train_test_split(clean_data)
def split_x_y(dataframe, target):
return dataframe.drop(target, axis=1), dataframe[target]
X_train, y_train = split_x_y(train, "Survived")
X_test, y_test = split_x_y(test, "Survived")
Explanation: Importing data
Getting data from kaggle first :
End of explanation
rf = RandomForestClassifier(n_estimators=100, n_jobs=-1)
rf.fit(X_train, y_train)
y_pred = rf.predict_proba(X_test)
auc = roc_auc_score(y_true=y_test, y_score=y_pred[:, 1])
auc
Explanation: Baseline model
End of explanation
from sklearn.model_selection import StratifiedKFold
rf1 = RandomForestClassifier(n_estimators=100, n_jobs=-1, max_depth=4)
rf2 = RandomForestClassifier(n_estimators=100, n_jobs=-1, max_depth=10)
rf1.fit(X_train, y_train)
y_pred_train_1 = rf1.predict_proba(X_train)
y_pred_test_1 = rf1.predict_proba(X_test)
y_pred_train_1 = pd.DataFrame(y_pred_train_1, columns=["rf1_0", "rf1_1"], index=X_train.index)
y_pred_test_1 = pd.DataFrame(y_pred_test_1, columns=["rf1_0", "rf1_1"], index=X_test.index)
rf2.fit(X_train, y_train)
y_pred_train_2 = rf2.predict_proba(X_train)
y_pred_test_2 = rf2.predict_proba(X_test)
y_pred_train_2 = pd.DataFrame(y_pred_train_2, columns=["rf2_0", "rf2_1"], index=X_train.index)
y_pred_test_2 = pd.DataFrame(y_pred_test_2, columns=["rf2_0", "rf2_1"], index=X_test.index)
hidden_train_1 = pd.concat([X_train, y_pred_train_1, y_pred_train_2], axis=1)
hidden_test_1 = pd.concat([X_test, y_pred_test_1, y_pred_test_2], axis=1)
hidden_train_1.head()
rf3 = RandomForestClassifier(n_estimators=300, n_jobs=-1)
rf3.fit(hidden_train_1, y_train)
y_pred3 = rf3.predict_proba(hidden_test_1)
roc_auc_score(y_test, y_pred3[:, 1])
Explanation: Deep Forest
By Hand
End of explanation
from deepforest.layer import Layer, InputLayer
input_layer = InputLayer(RandomForestClassifier(n_estimators=100, n_jobs=-1, max_depth=4),
RandomForestClassifier(n_estimators=100, n_jobs=-1, max_depth=10))
hidden_layer = Layer(input_layer,
RandomForestClassifier(n_estimators=50, n_jobs=-1, max_depth=4),
RandomForestClassifier(n_estimators=50, n_jobs=-1, max_depth=10))
hidden_layer.fit(X_train, y_train)
pd.DataFrame(hidden_layer.predict(X_test), index=X_test.index)
Explanation: This is not very handy, not at all. We already see a lot of code duplication, and one may feel there may be a way to abstract a lot of the logic that is happening here, in a way that is more flexible and powerful that all this boilerplate code.
With API
End of explanation
def random_forest_generator():
for i in range(2, 15, 2):
yield RandomForestClassifier(n_estimators=100,
n_jobs=-1,
min_samples_leaf=5,
max_depth=i)
for i in range(2, 15, 2):
yield RandomForestClassifier(n_estimators=100,
n_jobs=-1,
max_features=1,
min_samples_leaf=5,
max_depth=i)
def paper_like_generator():
for i in range(2):
yield RandomForestClassifier(n_estimators=1000,
n_jobs=-1,
min_samples_leaf=10)
for i in range(2):
yield RandomForestClassifier(n_estimators=1000,
n_jobs=-1,
max_features=1,
min_samples_leaf=10)
def build_input_layer():
return InputLayer(*paper_like_generator())
def build_hidden_layer(layer):
return Layer(layer, *paper_like_generator())
def build_output_layer(layer):
return Layer(layer,
RandomForestClassifier(n_estimators=500,
n_jobs=-1,
min_samples_leaf=5,
max_depth=10))
input_l = build_input_layer()
hidden_1 = build_hidden_layer(input_l)
hidden_2 = build_hidden_layer(hidden_1)
hidden_3 = build_hidden_layer(hidden_2)
hidden_4 = build_hidden_layer(hidden_3)
output_l = build_output_layer(hidden_4)
output_l.fit(X_train, y_train)
y_pred = output_l.predict(X_test)
y_pred
roc_auc_score(y_test, y_pred[:, 1])
Explanation: Going Further
End of explanation |
7,464 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Basic Stellar Photometry
Measuring Flux in 1D
Version 0.1
In this notebook we will introduce some basic concepts related to measuring the flux of a point source. As this is an introduction, several challenges associated with image processing will be ignored or simplified (for example, we will simulate stars in 1 dimension). Nevertheless, the concepts below adapt nicely to charge coupled devices (CCDs) with a small field of view ($\ll 1\,\deg^{2}$), and where stellar crowding is minimal. A good reference for such problems is the Handbook for CCD Astronomy by Steve Howell. However, as we will see throughout this session, the basic methods introduced here are insufficient for an ~all sky survey with a large field-of-view detector, as will be conducted by the Vera C. Rubin Observatory. We will learn more about those challenges and solutions in later lectures.
The problems below are inspired by Robert Lupton (who has forgotten more about image processing than I will ever know), so it may be worthwhile to checkout his original notebook.
By AA Miller (CIERA/Northwestern & Adler)
Step2: Problem 1) An (oversimplified) 1-D Model
For this introductory problem we are going to simulate a 1 dimensional detector. Simulated stars that are detected by said detector will have Gaussian profiles $\mathcal{N}(\mu, \sigma^2)$, with mean position $\mu$ and variance $\sigma^2$.
As observed by LSST, all stars are point sources that reflect the point spread function (PSF), which is produced by a combination of the atmosphere, telescope, and detector. A standard measure of the PSF's width is the Full Width Half Maximum (FWHM). For a Gaussian the FWHM = $2\sqrt{2 \ln (2)} \sigma \approx 2.3548\,\sigma$.
In addition to the signal from the stars, the 1D detector also detects a smooth background of light from several sources (the atmosphere, the detector, etc). We will refer to this background simply as "The Sky."
Problem 1a
Write a function phi() to simulate a (noise-free) 1D Gaussian PSF. The function should take mu and fwhm as arguments, and evaluate the PSF along a user-supplied array x.
Step3: Helper Function
CCDs measure pixelated signals. To clearly remind ourselves that that is the case, I have created a helper function that shows the pixelated counts in our 1D detector. The function assumes that the input positions are the left edge of the pixel.
You can use this function throughout the notebook below.
Step4: Problem 1b
Plot the noise-free PSF for a star with a profile defined by $\mu = 10$ and $\mathrm{FWHM} = 3$.
Estimate the total flux of this star by "integrating" over the counts measured by the detector. If you are clever in the definition of your pixels, this integration reduces to a sum.
Hint - think about your input grid of pixels. Can you have a non-integer number of pixels? Also - the flux should be evaluated at the center of the pixel.
Step5: Problem 1c
Now add sky noise to the detector (for now we will assume the sky noise is constant in every pixel). We will define the the sky as S, and the total stellar flux as F.
Plot the simulated counts for S = 100 and F = 500. (Use the same stellar profile as 1b)
Step6: Problem 2) Add Noise
For optical detectors (such as those used by the Rubin Observatory), the noise $n$ in a pixel is almost entirely shot noise due to the finite number of photons that have been detected. Therefore, within each pixel if the "true" signal in the detector would produce $n$ photons, then the noise/uncertainty in each pixel follows a Poisson distribution, which has the property that the mean $\lambda$ is equal to the variance $\lambda$. If $n \gg 1$ then $P(\lambda) \approx \mathcal{N}(\lambda, \lambda)$. We will make this simplifying assumption for the remainder of this problem.
Problem 2a
Plot the noisy counts in each pixel for the simulated signal (star + sky) in 1c. Visually compare these results to your previous plot.
Hint - you may find the function np.random.normal() or np.random.poisson() helpful.
Step7: Problem 2b
Estimate the flux of the star using the same method you used in 1b.
Does your estimate match your expectation? (recall that $F = 500$)
If not, why not?
Step8: write your answer here
The estimated flux is much, much, much larger than the true flux of the star.
Problem 2c
The flux has been measured incorrectly because we are counting photons from the "sky."
Subtract the sky background S from the counts in the detector and once again estimate the flux using the same method as 1b.
Does your estimate match your expectation? (recall that $F = 500$)
Note - estimating the value of the "sky" background in real life is extremely difficult and an entire lecture will be devoted to this topic
Step9: write your answer here
The flux is underestimated using this particular method.
We will now examine alternative methods of estimating the flux.
Problem 3) Aperture Flux Measurements
In some sense, 2c provides the most simplistic method for estimating the flux of star (add up all the counts after subtracting th background). This solution, however, cannot generalize to any sort of real life problem because there are always multiple stars (and galaxies) detected in every individual image.
However, we can approximate the above procedure by "isolating" the individual stars in any image (say by taking a 10x10 cutout around each star), and then estimating the flux in a similar fashion. As we are about to show, the size of the box (or more appropriately a circle for 2D optical images) is critical when estimating the flux.
Problem 3a
Write a function simulate() to simulate the noisy count measurements of a star with centroid mu, FWHM fwhm, sky background S, and flux F.
Hint - it may be helpful to plot the output of your function.
Step10: We will now perform aperture photometry. In optical astronomy, most apertures are a top-hat function, and the flux is estimated by multiplying the aperture by the (background-subtracted) signal and summing the resulting output. In 2D apertures are typically a circle, for the remainder of this 1D problem we will use a top-hat aperture. If the aperture contains partial pixels, then the counts in pixels with parial coverage are multiplied by the fractional coverage of the pixel.
Problem 3b
Using an aperture with a radius of 5 pixels centered on the source (i.e. the aperture is 10 pixels long), measure the flux from a star centered at mu = 20, with fwhm = 5, S = 100, and F = 1000. Assume you can perfectly measure the background, and subtract this prior to measuring the flux.
Extra long Hint - if you create your aperture using a single np.where() command (or similar) you are not going to get the correct answer. To quickly see why this is the case, imagine you'd been asked to use an aperture with a radius of 3.2 pixels. Thus, properly calculating the aperture requires a bit of thought. A for loop is a fairly intuitive way to handle this problem (though it can also be done with a series of where commands, and both possibilities will be presented in the solutions).
DO NOT SPEND TOO MUCH TIME ON THIS PROBLEM If you get stuck, use a single np.where() command. When you plot the results in the 3c you'll see how things are off, but this won't affect the general results in the remainder of the notebook.
Step11: Problem 3c
Plot the simulated counts from 3b and overplot your aperture. You may want to multiple the aperture by a factor of 100 to see it better.
Hint – after you have run pixel_plot() you will need to call matplotlib functions directly (e.g., plt.plot) to overplot on the pixel data. Also, if you created an aperture_mask in 3b it may help to plot that as well.
Step12: Problem 3c
Write a Monte Carlo simulator to estimate the mean and standard deviation of the flux from the simulated star.
Food for thought - what do you notice if you run your simulator many times?
Step13: Problem 4) Avoid Arbitrary Numbers -- the Curve of Growth
In Problem 3 we decided to use an aperture radius of 5. Why?
(In practice, an aperture radius equal to the FWHM is a pretty good choice, as we will show below. However, this is not optimal in all situations)
We will now try to optimize the choice of aperture for the star in question.
Problem 4a
Using your solution to Problem 3, write a function aperture_flux() that estimates the mean flux and it's variance in a given aperture of size ap_radius for a simulated star.
Hint - this function is going to have many inputs, ap_radius, the position of the star, the flux of the star, the FWHM of the star, a pixel grid, the value of the sky background, and the number of simulations per input radius.
Step14: Problem 4b
Confirm your function works by calculating the mean and variance of the flux in a 5 pixel radius aperture.
Step15: Problem 4c
Build successively larger apertures with sizes increasing from a radius of 1 to 10 pixels. Measure the mean and variance for each aperture size. Plot the results.
Which aperture size has the smallest variance? Is this aperture best?
Do these results make sense?
Step16: write your answer here
An aperture with a radius = 1 pixel has the smallest variance, however, this significantly underestimates the true flux. On the other hand, all the apertures with $r \gtrsim 7$ pixels do a seemingly equally good job of estimating the flux, but they have high variance estimates.
The fact that the small apertures do a poor job of estimating the flux makes sense because they are excluding clear signal from the source.
Small apertures fail to measure all the light from the source. Large apertures do measure all the light, but at the cost of higher variance.
In practice, these challenges can be alleviated if the point spread function is known. (This is a challenging problem and the subject of an entire lecture this week, as the PSF is essentially never known a priori and must be estimated from the images themselves.)
In this case, we know the PSF is a 1D Gaussian. We can therefore calculate "aperture corrections" to determine the flux at any radius on the above plot (known as the curve of growth -- in some cases the aperture corrections can be determined directly from the curve of growth but that can be challenging on real images, as things like stellar blends remove all the simplicity of the single star problem that we have here).
To determine the aperture correction at any radius $r$, we can simply integrate a Gaussian (our know PSF for this simulated problem) over the size of the aperture and then divide the aperture flux (and standard deviation) by this result to estimate the true flux in each aperture.
This can easily be done for our 1D Gaussian with scipy.
Step17: Problem 4d
Calculate the analytic curve of growth for each of your apertures from 4c. Re-plot the (corrected) flux in each aperture. Do you notice anything different?
Hint – recall the relation between FWHM and the standard deviation for a Gaussian.
Step18: Problem 4e
Plot the uncertainty on the flux estimate (i.e., the square root of the variance) as a function of aperture radius.
Now which aperture size do you think is best?
Step19: write your answer here
The optimal radius appears to be ~4 pixels. (Note - this is really close to the FWHM as we discussed previously)
Here we have discovered a universal truth about aperture photometry
Step20: Problem 4g
Leaving all other variables the same, estimate the optimal aperture size (i.e. maximize the signal-to-noise ratio) for a star with a flux of 10.
What is the optimal aperture size?
Can you even measure the flux of this star?
Step21: Upshot
Dropping simple apertures on an image provides a fast and simple method to estimate the flux of a star.
This approach comes at a cost, however, as the aperture method employed here provides high variance estimates of the flux.
Fortunately, it is possible to do much better via PSF photometry (and in fact, the Cramer-Rao bound mathematically proves that PSF photometry is the lowest variance estimator of the flux of a star). This means that aperture photometry is never better than PSF photometry despite some claims to contrary in the literature. There are cases where the PSF is extremely difficult to estimate, in which case aperture photometry may be the only decent way to estimate the flux, but even then PSF photometry would be better.
(Technically speaking, aperture photometry is PSF photometry. The catch is that the PSF model (a 1D or circular top hat) is a terrible match to the actual aparition of the stars on the image. When the model of the PSF is good, and in the case of our simulated data set we know the PSF perfectly, then PSF flux estimates will be a minimum variance estimator.)
Problem 5/Challenge Problem) PSF Flux measurement
We are going to cover PSF modeling and PSF photometry in far greater detail later this week, but here we are going to quickly meausure the flux using a model of the PSF, which we will compare to the aperture results.
Problem 5a
Create the psf model, psf, which is equivalent to a noise-free star with fwhm = 5.
Step22: Problem 5b
Using the same parameters as problem 3, simulate a star and measure it's PSF flux.
Hint - you may find the minimize function from scipy.optimize helpful.
Step23: Problem 5c
Following 4a write a function to simulate many realizations of the star and estimate the flux and variance using the PSF model.
How does the PSF estimate compare to the aperture estimate? | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook
Explanation: Introduction to Basic Stellar Photometry
Measuring Flux in 1D
Version 0.1
In this notebook we will introduce some basic concepts related to measuring the flux of a point source. As this is an introduction, several challenges associated with image processing will be ignored or simplified (for example, we will simulate stars in 1 dimension). Nevertheless, the concepts below adapt nicely to charge coupled devices (CCDs) with a small field of view ($\ll 1\,\deg^{2}$), and where stellar crowding is minimal. A good reference for such problems is the Handbook for CCD Astronomy by Steve Howell. However, as we will see throughout this session, the basic methods introduced here are insufficient for an ~all sky survey with a large field-of-view detector, as will be conducted by the Vera C. Rubin Observatory. We will learn more about those challenges and solutions in later lectures.
The problems below are inspired by Robert Lupton (who has forgotten more about image processing than I will ever know), so it may be worthwhile to checkout his original notebook.
By AA Miller (CIERA/Northwestern & Adler)
End of explanation
def phi(x, mu, fwhm):
Evalute the 1d PSF N(mu, sigma^2) along x
Parameters
----------
x : array-like of shape (n_pixels,)
detector pixel number
mu : float
mean position of the 1D star
fwhm : float
Full-width half-maximum of the stellar profile on the detector
Returns
-------
flux : array-like of shape (n_pixels,)
Flux in each pixel of the input array
sigma = fwhm/2.3548
flux = 1/np.sqrt(2*np.pi*sigma**2)*np.exp(-(x - mu)**2/(2*sigma**2))
return flux
Explanation: Problem 1) An (oversimplified) 1-D Model
For this introductory problem we are going to simulate a 1 dimensional detector. Simulated stars that are detected by said detector will have Gaussian profiles $\mathcal{N}(\mu, \sigma^2)$, with mean position $\mu$ and variance $\sigma^2$.
As observed by LSST, all stars are point sources that reflect the point spread function (PSF), which is produced by a combination of the atmosphere, telescope, and detector. A standard measure of the PSF's width is the Full Width Half Maximum (FWHM). For a Gaussian the FWHM = $2\sqrt{2 \ln (2)} \sigma \approx 2.3548\,\sigma$.
In addition to the signal from the stars, the 1D detector also detects a smooth background of light from several sources (the atmosphere, the detector, etc). We will refer to this background simply as "The Sky."
Problem 1a
Write a function phi() to simulate a (noise-free) 1D Gaussian PSF. The function should take mu and fwhm as arguments, and evaluate the PSF along a user-supplied array x.
End of explanation
from matplotlib.ticker import MultipleLocator
def pixel_plot(pix, counts):
'''Make a pixelated 1D plot'''
fig, ax = plt.subplots()
ax.step(pix, counts,
where='post')
ax.set_xlabel('pixel number')
ax.set_ylabel('relative counts')
ax.xaxis.set_minor_locator(MultipleLocator(1))
ax.xaxis.set_major_locator(MultipleLocator(5))
fig.tight_layout()
Explanation: Helper Function
CCDs measure pixelated signals. To clearly remind ourselves that that is the case, I have created a helper function that shows the pixelated counts in our 1D detector. The function assumes that the input positions are the left edge of the pixel.
You can use this function throughout the notebook below.
End of explanation
x = np.linspace(0,30,31)
pixel_plot(x, phi(x+.5, 10, 3))
print("The flux of the star is: {:.3f}".format(sum(phi(x+.5, 10, 3))))
Explanation: Problem 1b
Plot the noise-free PSF for a star with a profile defined by $\mu = 10$ and $\mathrm{FWHM} = 3$.
Estimate the total flux of this star by "integrating" over the counts measured by the detector. If you are clever in the definition of your pixels, this integration reduces to a sum.
Hint - think about your input grid of pixels. Can you have a non-integer number of pixels? Also - the flux should be evaluated at the center of the pixel.
End of explanation
S = 100
F = 500
pixel_plot(x, S*np.ones_like(x) + F*phi(x+0.5, 10, 3))
Explanation: Problem 1c
Now add sky noise to the detector (for now we will assume the sky noise is constant in every pixel). We will define the the sky as S, and the total stellar flux as F.
Plot the simulated counts for S = 100 and F = 500. (Use the same stellar profile as 1b)
End of explanation
np.random.seed(2020)
signal = S + F*phi(x+0.5, 10, 3)
signal_plus_noise = np.random.normal(signal, np.sqrt(signal))
pixel_plot(x, signal_plus_noise)
Explanation: Problem 2) Add Noise
For optical detectors (such as those used by the Rubin Observatory), the noise $n$ in a pixel is almost entirely shot noise due to the finite number of photons that have been detected. Therefore, within each pixel if the "true" signal in the detector would produce $n$ photons, then the noise/uncertainty in each pixel follows a Poisson distribution, which has the property that the mean $\lambda$ is equal to the variance $\lambda$. If $n \gg 1$ then $P(\lambda) \approx \mathcal{N}(\lambda, \lambda)$. We will make this simplifying assumption for the remainder of this problem.
Problem 2a
Plot the noisy counts in each pixel for the simulated signal (star + sky) in 1c. Visually compare these results to your previous plot.
Hint - you may find the function np.random.normal() or np.random.poisson() helpful.
End of explanation
print('The total flux = {:.4f}'.format(np.sum(signal_plus_noise)))
Explanation: Problem 2b
Estimate the flux of the star using the same method you used in 1b.
Does your estimate match your expectation? (recall that $F = 500$)
If not, why not?
End of explanation
print('The total flux = {:.4f}'.format(np.sum(signal_plus_noise - S)))
Explanation: write your answer here
The estimated flux is much, much, much larger than the true flux of the star.
Problem 2c
The flux has been measured incorrectly because we are counting photons from the "sky."
Subtract the sky background S from the counts in the detector and once again estimate the flux using the same method as 1b.
Does your estimate match your expectation? (recall that $F = 500$)
Note - estimating the value of the "sky" background in real life is extremely difficult and an entire lecture will be devoted to this topic
End of explanation
def simulate(x, mu, fwhm, S, F):
'''simulate a noisy stellar signal
Parameters
----------
x : array-like
detector pixel number
mu : float
mean position of the 1D star
fwhm : float
Full-width half-maximum of the stellar profile on the detector
S : float
Constant sky background in each pixel
F : float
Total stellar flux
Returns
-------
noisy_counts : array-like (same shape as x)
the (noisy) number of counts in each pixel
'''
source = F * phi(x+np.mean(np.diff(x))/2, mu, fwhm)
sky_plus_source = S * np.ones_like(x) + source
noisy_flux = np.random.normal(sky_plus_source, np.sqrt(sky_plus_source))
return noisy_flux
Explanation: write your answer here
The flux is underestimated using this particular method.
We will now examine alternative methods of estimating the flux.
Problem 3) Aperture Flux Measurements
In some sense, 2c provides the most simplistic method for estimating the flux of star (add up all the counts after subtracting th background). This solution, however, cannot generalize to any sort of real life problem because there are always multiple stars (and galaxies) detected in every individual image.
However, we can approximate the above procedure by "isolating" the individual stars in any image (say by taking a 10x10 cutout around each star), and then estimating the flux in a similar fashion. As we are about to show, the size of the box (or more appropriately a circle for 2D optical images) is critical when estimating the flux.
Problem 3a
Write a function simulate() to simulate the noisy count measurements of a star with centroid mu, FWHM fwhm, sky background S, and flux F.
Hint - it may be helpful to plot the output of your function.
End of explanation
x = np.linspace(0,40,41)
mu = 20
S = 100
fwhm = 5
F = 1000
sim_star = simulate(x, mu, fwhm, S, F)
ap_radius = 5
aperture_mask = np.zeros_like(x)
# somewhat vectorized solution
aperture_mask[np.where((np.abs(x + 1 - mu) <= ap_radius) &
(np.abs(x - mu) <= ap_radius))] = 1
low_pix = np.where((np.abs(x + 1 - mu) <= ap_radius) &
(np.abs(x - mu) > ap_radius))
aperture_mask[low_pix] = ap_radius - (mu - (x[low_pix] + 1))
high_pix = np.where((np.abs(x + 1 - mu) > ap_radius) &
(np.abs(x - mu) <= ap_radius))
aperture_mask[high_pix] = ap_radius - (x[high_pix] - mu)
# for loop solution
# for pix_num, pix in enumerate(x):
# if 0 <= np.abs(mu - (pix + 1)) <= ap_radius:
# aperture_mask[pix_num] = min(1, np.abs(ap_radius - np.abs(pix + 1 - mu)))
# if 0 <= pix - mu <= ap_radius:
# aperture_mask[pix_num] = min(1, ap_radius - np.abs(pix - mu))
ap_flux = np.sum((sim_star - S)*aperture_mask)
print("The star has flux = {:.3f}".format(ap_flux))
Explanation: We will now perform aperture photometry. In optical astronomy, most apertures are a top-hat function, and the flux is estimated by multiplying the aperture by the (background-subtracted) signal and summing the resulting output. In 2D apertures are typically a circle, for the remainder of this 1D problem we will use a top-hat aperture. If the aperture contains partial pixels, then the counts in pixels with parial coverage are multiplied by the fractional coverage of the pixel.
Problem 3b
Using an aperture with a radius of 5 pixels centered on the source (i.e. the aperture is 10 pixels long), measure the flux from a star centered at mu = 20, with fwhm = 5, S = 100, and F = 1000. Assume you can perfectly measure the background, and subtract this prior to measuring the flux.
Extra long Hint - if you create your aperture using a single np.where() command (or similar) you are not going to get the correct answer. To quickly see why this is the case, imagine you'd been asked to use an aperture with a radius of 3.2 pixels. Thus, properly calculating the aperture requires a bit of thought. A for loop is a fairly intuitive way to handle this problem (though it can also be done with a series of where commands, and both possibilities will be presented in the solutions).
DO NOT SPEND TOO MUCH TIME ON THIS PROBLEM If you get stuck, use a single np.where() command. When you plot the results in the 3c you'll see how things are off, but this won't affect the general results in the remainder of the notebook.
End of explanation
pixel_plot(x, sim_star-S)
# add aperture
plt.plot([0,mu-ap_radius, mu-ap_radius, mu+ap_radius,mu+ap_radius, np.max(x)], [0,0,100,100,0,0])
# add aperture_mask -- only different with non-integer aperture radius
plt.step(x, aperture_mask*100, where='post')
Explanation: Problem 3c
Plot the simulated counts from 3b and overplot your aperture. You may want to multiple the aperture by a factor of 100 to see it better.
Hint – after you have run pixel_plot() you will need to call matplotlib functions directly (e.g., plt.plot) to overplot on the pixel data. Also, if you created an aperture_mask in 3b it may help to plot that as well.
End of explanation
sim_fluxes = np.empty(1000)
for sim_num, dummy in enumerate(sim_fluxes):
sim_star = simulate(x, mu, 5, S, 1000)
ap_radius = 5
aperture_mask = np.zeros_like(x)
# somewhat vectorized solution
aperture_mask[np.where((np.abs(x + 1 - mu) <= ap_radius) &
(np.abs(x - mu) <= ap_radius))] = 1
low_pix = np.where((np.abs(x + 1 - mu) <= ap_radius) &
(np.abs(x - mu) > ap_radius))
aperture_mask[low_pix] = ap_radius - (mu - (x[low_pix] + 1))
high_pix = np.where((np.abs(x + 1 - mu) > ap_radius) &
(np.abs(x - mu) <= ap_radius))
aperture_mask[high_pix] = ap_radius - (x[high_pix] - mu)
ap_flux = np.sum((sim_star - S)*aperture_mask)
sim_fluxes[sim_num] = ap_flux
print("The mean flux = {:.3f} with variance = {:.3f}".format(np.mean(sim_fluxes),
np.var(sim_fluxes, ddof=1)))
Explanation: Problem 3c
Write a Monte Carlo simulator to estimate the mean and standard deviation of the flux from the simulated star.
Food for thought - what do you notice if you run your simulator many times?
End of explanation
def aperture_flux(ap_radius,
x=np.linspace(0,40,41),
mu=20,
fwhm=5,
S=100,
F=1000,
n_sim=1000):
'''Measure mean and variance of flux in a given aperture
Parameters
----------
ap_radius : float
radius of the top hat aperture
x : array-like (default: np.arange(0,40,41))
grid of simulated pixels
mu : float (default: 20)
position of the star
fhwm : float (default: 5)
FWHM of the stellar profile
S : float (default: 100)
level of the sky background
F : float (default: 1000)
stellar flux
n_sim : float (default: 1000)
number of simulations
Returns
-------
mean_flux, variance
'''
sim_fluxes = np.empty(n_sim)
for sim_num, dummy in enumerate(sim_fluxes):
sim_star = simulate(x, mu, fwhm, S, F)
aperture_mask = np.zeros_like(x)
# somewhat vectorized solution
aperture_mask[np.where((np.abs(x + 1 - mu) <= ap_radius) &
(np.abs(x - mu) <= ap_radius))] = 1
low_pix = np.where((np.abs(x + 1 - mu) <= ap_radius) &
(np.abs(x - mu) > ap_radius))
aperture_mask[low_pix] = ap_radius - (mu - (x[low_pix] + 1))
high_pix = np.where((np.abs(x + 1 - mu) > ap_radius) &
(np.abs(x - mu) <= ap_radius))
aperture_mask[high_pix] = ap_radius - (x[high_pix] - mu)
ap_flux = np.sum((sim_star - S)*aperture_mask)
sim_fluxes[sim_num] = ap_flux
return np.mean(sim_fluxes), np.var(sim_fluxes, ddof=1)
Explanation: Problem 4) Avoid Arbitrary Numbers -- the Curve of Growth
In Problem 3 we decided to use an aperture radius of 5. Why?
(In practice, an aperture radius equal to the FWHM is a pretty good choice, as we will show below. However, this is not optimal in all situations)
We will now try to optimize the choice of aperture for the star in question.
Problem 4a
Using your solution to Problem 3, write a function aperture_flux() that estimates the mean flux and it's variance in a given aperture of size ap_radius for a simulated star.
Hint - this function is going to have many inputs, ap_radius, the position of the star, the flux of the star, the FWHM of the star, a pixel grid, the value of the sky background, and the number of simulations per input radius.
End of explanation
mean, var = aperture_flux(5)
print('The mean flux in a r = 5 pix aperture is {:.4f} +/- {:.4f}'.format(mean, np.sqrt(var)))
Explanation: Problem 4b
Confirm your function works by calculating the mean and variance of the flux in a 5 pixel radius aperture.
End of explanation
ap_array = np.arange(1,15)
ap_mean = np.zeros_like(ap_array)
ap_var = np.zeros_like(ap_array)
for ap_num, ap_rad in enumerate(ap_array):
ap_mean[ap_num], ap_var[ap_num] = aperture_flux(ap_rad, n_sim=5000)
fig, ax = plt.subplots()
ax.errorbar(ap_array, ap_mean, np.sqrt(ap_var))
ax.hlines(1000, 0,15, linestyles='dashed')
ax.text(1,1030,r'$F_\mathrm{true} = 1000$')
ax.set_xlabel('aperture radius (pix)')
ax.set_ylabel('mean flux')
fig.tight_layout()
print('aperture radius = {} has the smallest variance'.format(ap_array[np.argmin(ap_var)]))
Explanation: Problem 4c
Build successively larger apertures with sizes increasing from a radius of 1 to 10 pixels. Measure the mean and variance for each aperture size. Plot the results.
Which aperture size has the smallest variance? Is this aperture best?
Do these results make sense?
End of explanation
from scipy.stats import norm
def curve_of_growth(r):
'''Return aperture correction for aperture of size r
Parameters
----------
r : float
radius of the aperture, in units of the
Gaussian standard deviation
Returns
-------
apcor : float
the aperture correction at radius r
'''
return norm.cdf(r) - norm.cdf(-r)
Explanation: write your answer here
An aperture with a radius = 1 pixel has the smallest variance, however, this significantly underestimates the true flux. On the other hand, all the apertures with $r \gtrsim 7$ pixels do a seemingly equally good job of estimating the flux, but they have high variance estimates.
The fact that the small apertures do a poor job of estimating the flux makes sense because they are excluding clear signal from the source.
Small apertures fail to measure all the light from the source. Large apertures do measure all the light, but at the cost of higher variance.
In practice, these challenges can be alleviated if the point spread function is known. (This is a challenging problem and the subject of an entire lecture this week, as the PSF is essentially never known a priori and must be estimated from the images themselves.)
In this case, we know the PSF is a 1D Gaussian. We can therefore calculate "aperture corrections" to determine the flux at any radius on the above plot (known as the curve of growth -- in some cases the aperture corrections can be determined directly from the curve of growth but that can be challenging on real images, as things like stellar blends remove all the simplicity of the single star problem that we have here).
To determine the aperture correction at any radius $r$, we can simply integrate a Gaussian (our know PSF for this simulated problem) over the size of the aperture and then divide the aperture flux (and standard deviation) by this result to estimate the true flux in each aperture.
This can easily be done for our 1D Gaussian with scipy.
End of explanation
cog = curve_of_growth(ap_array/(2.5/np.sqrt(2*np.log(2))))
fig, ax = plt.subplots()
ax.errorbar(ap_array, ap_mean/cog, np.sqrt(ap_var)/cog)
ax.hlines(1000, 0,15, linestyles='dashed')
# ax.text(1,1030,r'$F_\mathrm{true} = 1000$')
ax.set_xlabel('aperture radius (pix)')
ax.set_ylabel('(aperture corrected) mean flux')
fig.tight_layout()
Explanation: Problem 4d
Calculate the analytic curve of growth for each of your apertures from 4c. Re-plot the (corrected) flux in each aperture. Do you notice anything different?
Hint – recall the relation between FWHM and the standard deviation for a Gaussian.
End of explanation
fig, ax = plt.subplots()
ax.plot(ap_array, np.sqrt(ap_var)/cog)
ax.set_xlabel('aperture radius (pix)')
ax.set_ylabel('uncertainty in F')
fig.tight_layout()
Explanation: Problem 4e
Plot the uncertainty on the flux estimate (i.e., the square root of the variance) as a function of aperture radius.
Now which aperture size do you think is best?
End of explanation
ap_mean = np.zeros_like(ap_array)
ap_var = np.zeros_like(ap_array)
for ap_num, ap_rad in enumerate(ap_array):
ap_mean[ap_num], ap_var[ap_num] = aperture_flux(ap_rad, F=1e4, n_sim=3000)
fig, ax = plt.subplots()
ax.plot(ap_array, np.sqrt(ap_var)/cog)
ax.set_xlabel('aperture radius (pix)')
ax.set_ylabel('uncertainty in F')
fig.tight_layout()
print('The optimal aperture is {} pix'.format(ap_array[np.argmin(np.sqrt(ap_var)/cog)]))
Explanation: write your answer here
The optimal radius appears to be ~4 pixels. (Note - this is really close to the FWHM as we discussed previously)
Here we have discovered a universal truth about aperture photometry: very small and very large apertures produce lower signal-to-noise estimates than something in between.
However, the optimal value of that something in between is different for every star (as you will show below).
Problem 4f
Leaving all other variables the same, estimate the optimal aperture size (i.e. maximize the signal-to-noise ratio) for a star with a flux of 10000.
What is the optimal aperture size?
Hint –– you only need to repeat 4c and 4e for this answer.
End of explanation
ap_mean = np.zeros_like(ap_array)
ap_var = np.zeros_like(ap_array)
for ap_num, ap_rad in enumerate(ap_array):
ap_mean[ap_num], ap_var[ap_num] = aperture_flux(ap_rad, F=10, n_sim=3000)
fig, ax = plt.subplots()
ax.plot(ap_array, np.sqrt(ap_var)/cog)
ax.set_xlabel('aperture radius (pix)')
ax.set_ylabel('uncertainty in F')
fig.tight_layout()
print('The optimal aperture is {} pix'.format(ap_array[np.argmin(np.sqrt(ap_var)/cog)]))
Explanation: Problem 4g
Leaving all other variables the same, estimate the optimal aperture size (i.e. maximize the signal-to-noise ratio) for a star with a flux of 10.
What is the optimal aperture size?
Can you even measure the flux of this star?
End of explanation
psf = phi(x+.5, mu, fwhm)
Explanation: Upshot
Dropping simple apertures on an image provides a fast and simple method to estimate the flux of a star.
This approach comes at a cost, however, as the aperture method employed here provides high variance estimates of the flux.
Fortunately, it is possible to do much better via PSF photometry (and in fact, the Cramer-Rao bound mathematically proves that PSF photometry is the lowest variance estimator of the flux of a star). This means that aperture photometry is never better than PSF photometry despite some claims to contrary in the literature. There are cases where the PSF is extremely difficult to estimate, in which case aperture photometry may be the only decent way to estimate the flux, but even then PSF photometry would be better.
(Technically speaking, aperture photometry is PSF photometry. The catch is that the PSF model (a 1D or circular top hat) is a terrible match to the actual aparition of the stars on the image. When the model of the PSF is good, and in the case of our simulated data set we know the PSF perfectly, then PSF flux estimates will be a minimum variance estimator.)
Problem 5/Challenge Problem) PSF Flux measurement
We are going to cover PSF modeling and PSF photometry in far greater detail later this week, but here we are going to quickly meausure the flux using a model of the PSF, which we will compare to the aperture results.
Problem 5a
Create the psf model, psf, which is equivalent to a noise-free star with fwhm = 5.
End of explanation
from scipy.optimize import minimize
# minimize the square of the residuals to determine flux
def sum_res(A, flux=sim_star-S, model=psf):
return sum((flux - A*model)**2)
sim_star = simulate(x, mu, fwhm, S, F)
psf_flux = minimize(sum_res, 980, args=(sim_star-S, psf))
print("The PSF flux is {:.3f}".format(psf_flux.x[0]))
Explanation: Problem 5b
Using the same parameters as problem 3, simulate a star and measure it's PSF flux.
Hint - you may find the minimize function from scipy.optimize helpful.
End of explanation
sim_fluxes = np.empty(5000)
for sim_num, dummy in enumerate(sim_fluxes):
sim_star = simulate(x, mu, fwhm, S, F)
psf_flux = minimize(sum_res, 980, args=(sim_star-S, psf))
sim_fluxes[sim_num] = psf_flux.x[0]
print("The mean flux = {:.3f} with variance = {:.3f}".format(np.mean(sim_fluxes),
np.var(sim_fluxes, ddof=1)))
Explanation: Problem 5c
Following 4a write a function to simulate many realizations of the star and estimate the flux and variance using the PSF model.
How does the PSF estimate compare to the aperture estimate?
End of explanation |
7,465 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Compare CoNLL files against themselves
We're now using the official CoNLL scorer to compare each
MAZ176 coreference annotated document against itself.
All comparisons should result in an F1 of 100%
Step4: Do all metrics choke on the same files?
Step6: Hypothesis 1
Step7: Initially, this was true. After Markus fixed a bunch of annotations,
Hypothesis 1 could not be validated any longer.
Hypothesis 2
Step9: potential error
markable is both primmark and secmark
Step10: Hypothesis 2 doesn't hold.
Let's check files w/out ambiguous coreference chains that scorer.pl doesn't like
Step13: Visualizing ambiguous coreference annotations with discoursegraphs
fortunately, the current version doesn't have any
Step14: Are there any files without chains? no!
Step15: What's wrong with the remaining files?
files that produces an F1 of less than 100%
most of them are just off by one allegedly 'invented' entity
Step17: Are the coreferences of the remaining files okay?
they seem okay, but contain numerous near-identity relations
Step18: TODO | Python Code:
import sys
def has_valid_annotation(mmax_file, scorer_path, metric, verbose=False):
Parameters
----------
metric : str
muc, bcub, ceafm, ceafe, blanc
verbose : bool or str
True, False or 'very'
scorer = sh.Command(scorer_path)
mdg = MMAXDocumentGraph(mmax_file)
conll_fname = '/tmp/{}.conll'.format(os.path.basename(mmax_file))
write_conll(mdg, conll_fname)
try:
results = scorer(metric, conll_fname, conll_fname)
scores_str = results.stdout.splitlines()[-2]
if not scores_str.endswith('100%'):
if verbose == 'very':
sys.stderr.write("{}\n{}\n".format(conll_fname, results))
elif verbose:
sys.stderr.write("{}\n{}\n".format(conll_fname, scores_str))
return False
except sh.ErrorReturnCode as e:
if verbose:
sys.stderr.write("Error in '{}'\n{}".format(conll_fname, e))
return False
return True
def get_bad_scoring_files(mmax_dir, scorer_path, metric, verbose=False):
returns filepaths of MMAX2 coreference files which don't produce perfect
results when testing them against themselves with scorer.pl
bad_files = []
for mmax_file in glob.glob(os.path.join(mmax_dir, '*.mmax')):
if not has_valid_annotation(mmax_file, scorer_path, metric, verbose=verbose):
bad_files.append(mmax_file)
return bad_files
blanc_errors = get_bad_scoring_files(MMAX_DIR, SCORER_PATH, 'blanc', verbose=True)
Explanation: Compare CoNLL files against themselves
We're now using the official CoNLL scorer to compare each
MAZ176 coreference annotated document against itself.
All comparisons should result in an F1 of 100%
End of explanation
bad_scoring_files = {}
for metric in ('muc', 'bcub', 'ceafm', 'ceafe', 'blanc'):
bad_scoring_files[metric] = get_bad_scoring_files(MMAX_DIR, SCORER_PATH, metric, verbose=False)
for metric in bad_scoring_files:
print "number of erroneous files found by '{}': {}".format(metric, len(bad_scoring_files[metric]))
all_bad_files = set()
for metric in bad_scoring_files:
all_bad_files.update(bad_scoring_files[metric])
print "total number of erroneous files:", len(all_bad_files)
from discoursegraphs import get_pointing_chains
from discoursegraphs.readwrite.mmax2 import spanstring2text
def print_all_chains(docgraph):
print a list of all pointing chains (i.e coreference chains)
contained in a document graph
for chain in get_pointing_chains(docgraph):
for node_id in chain:
print node_id, spanstring2text(docgraph, docgraph.node[node_id][docgraph.ns+':span'])
print '\n'
mdg = MMAXDocumentGraph(os.path.join(MMAX_DIR, 'maz-3377.mmax'))
print_all_chains(mdg)
Explanation: Do all metrics choke on the same files?
End of explanation
from itertools import combinations
def get_ambiguous_markables(mmax_docgraph):
returns a list of markables that occur in more than one coreference chain
ambiguous_markables = []
chain_sets = (set(chain) for chain in get_pointing_chains(mmax_docgraph))
for chain1, chain2 in combinations(chain_sets, 2):
chain_intersect = chain1.intersection(chain2)
if chain_intersect:
ambiguous_markables.extend(chain_intersect)
return ambiguous_markables
files_with_ambigious_chains = []
for mmax_file in glob.glob(os.path.join(MMAX_DIR, '*.mmax')):
mdg = MMAXDocumentGraph(mmax_file)
if get_ambiguous_markables(mdg):
files_with_ambigious_chains.append(mmax_file)
print "# of files with ambiguous coreference chains: ", len(files_with_ambigious_chains)
print "# of files scorer.pl doesn't like: ", len(bad_scoring_files)
if len(files_with_ambigious_chains) > 0:
print "percent of files w/ ambiguous chains that scorer.pl doesn't like:", \
len( set(files_with_ambigious_chains).intersection(set(bad_scoring_files)) ) / len(files_with_ambigious_chains) * 100
Explanation: Hypothesis 1: all markables occurring in more than one coreference chain produce scoring errors
End of explanation
# test this with
# markable_32 auf beiden Seiten
# markable_56 Arafat Scharon
mdg = MMAXDocumentGraph(os.path.join(MMAX_DIR, 'maz-19074.mmax'))
mdg.node['markable_56']
Explanation: Initially, this was true. After Markus fixed a bunch of annotations,
Hypothesis 1 could not be validated any longer.
Hypothesis 2: non-contiguous markables cause trouble
End of explanation
from discoursegraphs import get_span, select_nodes_by_layer
def get_noncontiguous_markables(docgraph):
return all markables that don't represent adjacent tokens
noncontiguous_markables = []
id2index = {tok_id:i for i, tok_id in enumerate(docgraph.tokens)}
for markable in select_nodes_by_layer(docgraph, docgraph.ns+':markable'):
span_token_ids = get_span(docgraph, markable)
for span_index, tok_id in enumerate(span_token_ids[:-1]):
tok_index = id2index[tok_id]
next_tok_id = span_token_ids[span_index+1]
next_tok_index = id2index[next_tok_id]
if next_tok_index - tok_index != 1:
noncontiguous_markables.append(markable)
return noncontiguous_markables
files_with_noncontiguous_markables = []
for mmax_file in glob.glob(os.path.join(MMAX_DIR, '*.mmax')):
mdg = MMAXDocumentGraph(mmax_file)
if get_noncontiguous_markables(mdg):
files_with_noncontiguous_markables.append(mmax_file)
print "# of files with non-continuous markables: ", len(files_with_noncontiguous_markables)
print "# of files scorer.pl doesn't like: ", len(bad_scoring_files)
print "percent of files w/ non-continuous markables that scorer.pl doesn't like:", \
len( set(files_with_noncontiguous_markables).intersection(set(bad_scoring_files)) ) / len(files_with_noncontiguous_markables) * 100
Explanation: potential error
markable is both primmark and secmark
End of explanation
mysterious_files = [os.path.basename(fname)
for fname in set(all_bad_files).difference(set(files_with_ambigious_chains))]
len(mysterious_files)
# for fname in mysterious_files:
# mdg = MMAXDocumentGraph(os.path.join(MMAX_DIR, fname))
# print fname, '\n==============\n\n'
# try:
# print_all_chains(mdg)
# except Exception as e:
# print "\n{} FAILED: {}".format(fname, e)
Explanation: Hypothesis 2 doesn't hold.
Let's check files w/out ambiguous coreference chains that scorer.pl doesn't like
End of explanation
from collections import defaultdict
import networkx as nx
from discoursegraphs import get_text
def get_ambiguous_chains(mmax_docgraph, token_labels=False):
Returns a list of networkx graphs that represent ambiguous
coreference chains. An ambiguous chain represents two or more
coreference chains that share at least one markable.
There should be no ambiguous coreference chains, but the
current version of our annotation guidelines allow them. // SRSLY?
ambiguous_markables = get_ambiguous_markables(mmax_docgraph)
coreference_chains = get_pointing_chains(mmax_docgraph)
markable2chain = defaultdict(list)
for i, chain in enumerate(coreference_chains):
for markable in chain:
if markable in ambiguous_markables:
markable2chain[markable].append(i)
chain_graphs = []
for markable in markable2chain:
ambig_chain_ids = markable2chain[markable]
chain_graph = nx.MultiDiGraph()
chain_graph.name = mmax_docgraph.name
for chain_id in ambig_chain_ids:
ambig_chain = coreference_chains[chain_id]
for i, markable in enumerate(ambig_chain[:-1]):
chain_graph.add_edge(markable, ambig_chain[i+1])
if token_labels:
for markable in chain_graph.nodes_iter():
markable_text = get_text(mmax_docgraph, markable)
chain_graph.node[markable]['label'] = markable_text
chain_graphs.append(chain_graph)
return chain_graphs
def merge_ambiguous_chains(ambiguous_chains):
Parameters
----------
ambiguous_chains : list of MultiDiGraph
a list of graphs, each representing an ambiguous coreference chain
merged_chain = nx.DiGraph(nx.compose_all(ambiguous_chains))
merged_chain.add_node('name', shape='tab',
color='blue',
label=ambiguous_chains[0].name)
for node in merged_chain:
if merged_chain.in_degree(node) > 1 \
or merged_chain.out_degree(node) > 1:
merged_chain.node[node]['color'] = 'red'
return merged_chain
len(files_with_ambigious_chains) # nothing to see here, move on!
Explanation: Visualizing ambiguous coreference annotations with discoursegraphs
fortunately, the current version doesn't have any
End of explanation
from discoursegraphs import info
files_without_chains = []
for mmax_file in glob.glob(os.path.join(MMAX_DIR, '*.mmax')):
mdg = MMAXDocumentGraph(mmax_file)
if not get_pointing_chains(mdg):
files_without_chains.append(os.path.basename(mmax_file))
# info(mdg)
# print '\n\n'
print files_without_chains
Explanation: Are there any files without chains? no!
End of explanation
for fname in mysterious_files:
has_valid_annotation(os.path.join(MMAX_DIR, fname), SCORER_PATH, 'muc', verbose='very')
Explanation: What's wrong with the remaining files?
files that produces an F1 of less than 100%
most of them are just off by one allegedly 'invented' entity
End of explanation
def get_all_good_scoring_files(mmax_dir, scorer_path, verbose=False):
returns filepaths of MMAX2 coreference files which don't produce perfect
results when testing them against themselves with scorer.pl
all_mmax_files = glob.glob(os.path.join(mmax_dir, '*.mmax'))
all_bad_files = set()
metrics = ['muc', 'bcub', 'ceafm', 'ceafe', 'blanc']
for mmax_file in all_mmax_files:
for metric in metrics:
if not has_valid_annotation(mmax_file, scorer_path, metric, verbose=verbose):
all_bad_files.add(mmax_file)
break # continue with next mmax file
return set(all_mmax_files).difference(all_bad_files)
all_good_scoring_files = get_all_good_scoring_files(MMAX_DIR, SCORER_PATH)
len(all_good_scoring_files)
# for fname in all_good_scoring_files:
# mdg = dg.read_mmax2(fname)
# bname = os.path.basename(fname)
# print bname, '\n==============\n\n'
# try:
# # [the dog]_{markable_23} means that [the dog] is part of a
# # coreference chain whose first element is markable_23
# print dg.readwrite.brackets.gen_bracketed_output(mdg), '\n\n'
# except KeyError as e:
# print "Error in {}: {}".format(bname, e)
# print dg.get_text(mdg)
# try:
# print_all_chains(mdg)
# except Exception as e:
# print "\n{} FAILED: {}".format(fname, e)
Explanation: Are the coreferences of the remaining files okay?
they seem okay, but contain numerous near-identity relations
End of explanation
MMAX_DIR
mmax_14172 = os.path.join(MMAX_DIR, 'maz-14172.mmax')
mdg = dg.read_mmax2(mmax_14172)
print_all_chains(mdg)
Explanation: TODO: check this rare key error
End of explanation |
7,466 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exponential Weighted Moving Average (EWMA)
Pro jednoduchost výpočtu patří exponenciální vážený klouzavý průměr (EWMA) k hojně využívaným nástrojům pro analýzu dat, machine learning, atd. Narozdíl od jiných typů klouzavých průměrů (Simple, Exponential Moving Average, atd.) s větší periodou než 2, nepotřebuje EWMA k výpočtu aktuální hodnoty znát historii předchozích hodnot. Stačí k tomu pouze fixní váha w (ta určuje jak velká historie se bere v potaz), hodnota aktuálního prvku a předchozí vypočítaná hodnota EWMA.
Obecný výpočet EWMA
Hodnota EWMA pro každý prvek EWMA se vypočítá podle vzorce
Step1: EWMA za posledních 20 prvků
Pokud chci vypočítat EWMA s vlivem posledních 20 prvků na výsledek, váhu vypočítám podle výše zmíněného vzorce
Step2: EWMA na cenovém grafu se obvykle počítá z Close/Last ceny, vzorec bude vypadat takto
Step3: Pandas využívá tzv. smoothing factor namísto váhy
Jednoduché a optimalizované řešení lze naleznout v knihovně Pandas po použití exponenciálně vážené rolling funkce df.ewm(). Tahle funkce obsahuje parametr alpha, který reprezentuje tzv. smoothing factor. Pandas namísto váhy používá tento smoothing factor k výpočtu takto (zdroj
Step4: Případná nepřesnost může být způsobena přesností čísel s desetinnou čárkou - více zde
Step5: Pro názornost rozdílu mezi jednoduchým klouzavým průměrem (Simple Moving Average) a EWMA uvedu příklad
Step6: A nakonec si průmery zobrazím v grafu | Python Code:
import datetime
start = datetime.datetime(2018, 1, 1)
end = datetime.datetime(2019, 1, 1)
spy_data = pdr.data.DataReader('SPY', 'yahoo', start, end)
spy_data.drop(['High', 'Low', 'Open', 'Close', 'Volume'], axis=1, inplace=True) # these columns are not needed
spy_data.head(5)
Explanation: Exponential Weighted Moving Average (EWMA)
Pro jednoduchost výpočtu patří exponenciální vážený klouzavý průměr (EWMA) k hojně využívaným nástrojům pro analýzu dat, machine learning, atd. Narozdíl od jiných typů klouzavých průměrů (Simple, Exponential Moving Average, atd.) s větší periodou než 2, nepotřebuje EWMA k výpočtu aktuální hodnoty znát historii předchozích hodnot. Stačí k tomu pouze fixní váha w (ta určuje jak velká historie se bere v potaz), hodnota aktuálního prvku a předchozí vypočítaná hodnota EWMA.
Obecný výpočet EWMA
Hodnota EWMA pro každý prvek EWMA se vypočítá podle vzorce:
$$
y_t = wy_{t-1} + (1-w)x_t
$$
$y_t$ je výsledek EWMA
$w$ je definovaná váha, kde $w \in (0,1)$
$y_{t-1}$ je přechozí výsledek EWMA, pokud jde o první prvek, obvykle se inicializuje hodnotou 0, nebo aktuální měřenou hodnotou
$x_t$ je hodnota aktuálního prvku
Vztah váhy a historie, která má vliv na aktuální výsledek
Po matematickém odvození můžeme zjistit, kolik hodnot zpětně má vliv na aktuální výsledek. Vzorec pro výpočet periody $p \approx \frac{1}{1-w}$, který uvádí Andrew Ng ve výukovém video na youtube, bohužel obsahuje nepřesnost, správně by mělo být:
$$
p \approx \frac{2}{1-w}
$$
$w$ je definovaná váha, kde $w \in (0,1)$
$p$ je perioda, kde $p \geq 1$
Perioda nám říká, že další prvky v hlouběji v historii mají zanedbatelný vliv na výsledek EWMA pro aktuální prvek.
Jednoduše z předchozího vzorce lze odvodit jakou váhu w mám zvolit:
$$
w \approx 1 - \frac{2}{p}
$$
$w$ je definovaná váha, kde $w \in (0,1)$
$p$ je perioda, kde $p \geq 1$
Příklad EWMA a cenový graf
Nejprve ale získám data:
End of explanation
p = 20
w = 1-(2/p)
w
Explanation: EWMA za posledních 20 prvků
Pokud chci vypočítat EWMA s vlivem posledních 20 prvků na výsledek, váhu vypočítám podle výše zmíněného vzorce:
End of explanation
spy_data['EWMA_mannualy'] = spy_data['Adj Close']
for i in range(spy_data.shape[0]):
if i==0:
spy_data['EWMA_mannualy'][i] = spy_data['Adj Close'][i]
continue
spy_data['EWMA_mannualy'][i] = w*spy_data['EWMA_mannualy'][i-1] + (1-w)*spy_data['Adj Close'][i]
spy_data.head()
Explanation: EWMA na cenovém grafu se obvykle počítá z Close/Last ceny, vzorec bude vypadat takto:
$$
y_t = wy_{y-1} + (1-w)c_t
$$
$y_t$ je hodnota EWMA pro aktuální cenu
$w$ je definovaná váha, kde $w \in (0,1)$
$y_{t-1}$ je přechozí výsledek EWMA, pokud jde o první hodnotu, obvykle se inicializuje hodnotou 0, nebo aktuální měřenou hodnotou
$c_t$ je aktuální hodnota Close ceny
Následující kód slouží pouze pro demonstrativní účely použití vzorce.
End of explanation
a = 1-w
a
Explanation: Pandas využívá tzv. smoothing factor namísto váhy
Jednoduché a optimalizované řešení lze naleznout v knihovně Pandas po použití exponenciálně vážené rolling funkce df.ewm(). Tahle funkce obsahuje parametr alpha, který reprezentuje tzv. smoothing factor. Pandas namísto váhy používá tento smoothing factor k výpočtu takto (zdroj: dokumentace k pandas):
$$
y_t = (1-\alpha)y_{t-1} + \alpha C_t
$$
$y_t$ je hodnota EWMA pro aktuální cenu
$\alpha$ smoothing factor, kde $\alpha \in (0,1)$
$y_{t-1}$ je přechozí výsledek EWMA, pokud jde o první hodnotu, obvykle se inicializuje hodnotou 0, nebo aktuální měřenou hodnotou
$C_t$ je aktuální hodnota Close ceny
Po odvození lze jednoduše vypočítat smoothing factor z váhy:
$$
\alpha = 1-w
$$
$w$ je váha, kde $w \in (0,1)$
$\alpha$ smoothing factor, kde $\alpha \in (0,1)$
Nebo smoothing factor z periody:
$$
\alpha \approx \frac{2}{p}
$$
$p$ je perioda, kde $p \geq 1$
$\alpha$ smoothing factor, kde $\alpha \in (0,1)$
Pozn.: zde se neshodnu s pandas, který periodu označuje jako span parametr a v dokumentaci figuruje vzorec $\alpha = \frac{2}{p+1}$. To by mi pak ale nekorespondovalo s Andrew Ng.
End of explanation
spy_data['EWMA'] = spy_data['Adj Close'].ewm(alpha=0.1, adjust=False).mean()
spy_data['EWMA_period'] = spy_data['Adj Close'].ewm(span=p, adjust=False).mean()
spy_data.head()
Explanation: Případná nepřesnost může být způsobena přesností čísel s desetinnou čárkou - více zde: https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems
End of explanation
spy_data['SMA'] = spy_data['Adj Close'].rolling(p).mean()
Explanation: Pro názornost rozdílu mezi jednoduchým klouzavým průměrem (Simple Moving Average) a EWMA uvedu příklad:
End of explanation
spy_data[['Adj Close', 'EWMA_mannualy', 'EWMA', 'EWMA_period', 'SMA']].plot(figsize=(16,10));
Explanation: A nakonec si průmery zobrazím v grafu:
End of explanation |
7,467 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Doppler shifts
Exploring doppler shift on precision and quality. Specifically in the K-band
Step1: Applying doppler shifts of $+/- 200$ km/s only produce changes of $< \pm0.1$ m/s for conditions 1 and 3, and $\pm 2$ m/s for condition 2.
There is a slight slope due to the shape of the input spectrum.
Step2: Applying the telluric mask reduces the spectrum analyzed to 40%, This inclusion for barycentric shift reduces this to 12% of the original spectra so there is a large increase in RV error.
Cross correlations
Computing the cross between the synthetic spectrum and atmospheric model
Step3: Auto Correletations | Python Code:
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
import PyAstronomy.pyasl as pyasl
from astropy import constants as const
from eniric import config
import eniric
# config.cache["location"] = None # Disable caching for these tests
config.cache["location"] = ".joblib" # Enable caching
from eniric.broaden import rotational_convolution, resolution_convolution
from eniric.utilities import band_limits, load_aces_spectrum, wav_selector
from scripts.phoenix_precision import convolve_and_resample
from eniric.snr_normalization import snr_constant_band
from eniric.precision import rv_precision, quality
from eniric.utilities import doppler_shift_wav, doppler_shift_flux
from eniric.atmosphere import Atmosphere
# Convolution settings
epsilon = 0.6
vsini = 10.0
R = 40000
wav1, flux1 = load_aces_spectrum([3900, 4.5, 0.0, 0])
kmin_, kmax_ = band_limits("K")
# To avoid the strong telluric band limititations will shrink limits
span = kmax_ - kmin_
kmin_ = kmin_ + 0.1 * span
kmax_ = kmax_ - 0.1 * span
from eniric.utilities import doppler_limits
# doppler resilient boundraries
rvmax = 10000 # km/s
kmin_dop, kmax_dop = doppler_limits(rvmax, kmin_, kmax_)
wav1, flux1 = wav_selector(wav1, flux1, kmin_dop, kmax_dop)
# PyAstronomy requires even spaced wavelength (eniric does not)
wav = np.linspace(wav1[0], wav1[-1], len(wav1))
flux = np.interp(wav, wav1, flux1)
# Normalization
const = snr_constant_band(wav, flux, snr=100, band="K")
flux = flux / const
atm__ = Atmosphere.from_file(atmmodel="../../data/atmmodel/Average_TAPAS_2014.dat")
atm_ = atm__.copy()
atm_.wave_select(kmin_dop, kmax_dop)
atm_.mask_transmission(depth=2)
# atm_.barycenter_broaden(30,consecutive_test=False)
atm_2 = atm_.copy()
atm_.wave_select(kmin_dop, kmax_dop)
def qfunc(wav, flux):
# Func to calculate the 4 precision versions
atm = atm_.at(wav)
rva = rv_precision(wav, flux)
rvb = rv_precision(wav, flux, mask=atm.mask)
rvc = rv_precision(wav, flux, mask=atm.transmission ** 2)
q = quality(wav, flux)
return rva, rvb, rvc, q
shifts = np.arange(-200, 200, 1)
# shifts = [1000]
rv1s, rv2s, rv3s, qs = [], [], [], []
nwav, _ = wav_selector(wav, flux, kmin_, kmax_)
for shift in tqdm(shifts):
nflux = doppler_shift_flux(wav, flux, shift, new_wav=nwav)
a, b, c, d = qfunc(nwav, nflux)
rv1s.append(a.value)
rv2s.append(b.value)
rv3s.append(c.value)
qs.append(d)
# rv2 with bary shifted mask
atm_2.barycenter_broaden(30, consecutive_test=False)
def qfunc2(wav, flux):
# Func to calculate the 4 precision versions
atm = atm_2.at(wav)
rvb = rv_precision(wav, flux, mask=atm.mask)
return rvb
rv2s_bary = []
for shift in tqdm(shifts):
nflux = doppler_shift_flux(wav, flux, shift, new_wav=nwav)
b2 = qfunc2(nwav, nflux)
rv2s_bary.append(b2.value)
fig, axs = plt.subplots(5, 1, sharex=True, figsize=(10, 7))
axs[0].plot(shifts, rv1s, "o-", label="rv1")
axs[0].legend(loc=1)
axs[0].set_ylabel("Precision (m/s)")
axs[1].plot(shifts, rv2s, "x-", label="rv2 without Bary")
axs[1].legend(loc=1)
axs[1].set_ylabel("Precision (m/s)")
axs[2].plot(shifts, rv2s_bary, "x-", label="rv2 with Bary")
axs[2].legend(loc=1)
axs[2].set_ylabel("Precision (m/s)")
axs[3].plot(shifts, rv3s, ".-", label="rv3")
axs[3].legend(loc=1)
axs[3].set_ylabel("Precision (m/s)")
axs[4].plot(shifts, qs, "o-", label="quality")
axs[4].set_xlabel("RV (km/s)")
axs[4].set_ylabel("Quality")
plt.legend()
plt.show()
Explanation: Doppler shifts
Exploring doppler shift on precision and quality. Specifically in the K-band
End of explanation
atm_spec = atm_.at(wav)
sum1, len1 = np.sum(atm_spec.mask), len(atm_spec.mask)
atm_spec2 = atm_2.at(wav) # With bary shift
sum2, len2 = np.sum(atm_spec2.mask), len(atm_spec2.mask)
print("Telluric mask: {0:d}/{1:d} = {2:.03}%".format(sum1, len1, 100 * sum1 / len1))
print(
"Mask with Bary shift:: {0:d}/{1:d} = {2:4.03}%".format(
sum2, len2, 100 * sum2 / len2
)
)
Explanation: Applying doppler shifts of $+/- 200$ km/s only produce changes of $< \pm0.1$ m/s for conditions 1 and 3, and $\pm 2$ m/s for condition 2.
There is a slight slope due to the shape of the input spectrum.
End of explanation
from PyAstronomy.pyasl import crosscorrRV
# Cross correlation of spectra wth telluric mask
xwav = np.linspace(kmin_, kmax_, len(wav1))
xflux = np.interp(xwav, wav1, flux1)
# trans = atm_.at(xwav).transmission()
print(len(xwav), len(atm_.wl))
s, corr = crosscorrRV(
xwav,
xflux,
atm_.wl,
atm_.transmission,
rvmin=-200,
rvmax=200,
drv=2,
mode="doppler",
skipedge=10000,
)
# Cross correlation of spectra wth telluric mask
# PyAstronomy requires even spaced wavelength (eniric does not)
xwav = np.linspace(kmin_, kmax_, len(wav1))
xflux = np.interp(xwav, wav1, flux1)
atm2 = atm_.at(xwav)
s2, corr2 = crosscorrRV(
atm2.wl,
atm2.transmission,
wav1,
flux1,
rvmin=-200,
rvmax=200,
drv=1,
mode="doppler",
skipedge=10000,
)
# Cross correlations
plt.plot(s, corr / np.mean(corr), label="template=atm")
plt.plot(s2, corr2 / np.mean(corr2), label="template=spectrum")
plt.xlabel("RV shift (km/s)")
plt.ylabel("Correlation")
plt.legend()
plt.show()
Explanation: Applying the telluric mask reduces the spectrum analyzed to 40%, This inclusion for barycentric shift reduces this to 12% of the original spectra so there is a large increase in RV error.
Cross correlations
Computing the cross between the synthetic spectrum and atmospheric model
End of explanation
wavauto, corr_wav_auto = crosscorrRV(
wav1,
flux1,
wav1,
flux1,
rvmin=-200,
rvmax=200,
drv=1,
mode="doppler",
skipedge=10000,
)
atmauto, corr_atm_auto = crosscorrRV(
atm2.wl,
atm2.transmission,
atm2.wl,
atm2.transmission,
rvmin=-200,
rvmax=200,
drv=1,
mode="doppler",
skipedge=10000,
)
plt.plot(wavauto, corr_wav_auto/max(corr_wav_auto), label="Spectrum Autocorrelation")
plt.plot(atmauto, corr_atm_auto/max(corr_atm_auto), label="Atmosphere Autocorrelation")
plt.plot(s, corr/max(corr), label="Cross Correlation")
plt.legend()
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(s,corr/np.max(corr),"g", label="xcorr")
ax2.plot(shifts, rv3s, "b--",label="RV3")
ax1.set_xlabel("RV shift (km/s)")
ax1.set_ylabel('Xcorr', color='g')
ax2.set_ylabel('Precision', color='b')
#plt.legend()
plt.show()
Explanation: Auto Correletations
End of explanation |
7,468 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Initialize set up
Amplifyer is fet -15V and = +85V
Calibrate strain gauge to zero with the kinesis software
Pull fiber back
Set nicard to -3.75
Step1: Move close with fiber | Python Code:
mynicard._write_cavity_ao(np.array([0.0],dtype=float), start=True)
Explanation: Initialize set up
Amplifyer is fet -15V and = +85V
Calibrate strain gauge to zero with the kinesis software
Pull fiber back
Set nicard to -3.75
End of explanation
first_resonances = cavitylogic.get_nth_full_sweep(sweep_number=1)
cavitylogic.ramp_popt = cavitylogic._fit_ramp(xdata=cavitylogic.time_trim[::10], ydata=cavitylogic.volts_trim[cavitylogic.ramp_channel,::10])
Modes = cavitylogic._ni.sweep_function(cavitylogic.RampUp_time[first_resonances],*cavitylogic.ramp_popt)
cavitylogic.linewidth_measurement(Modes,target_mode = 32, repeat=1, freq=40)
high_mode=50
low_mode=0
cavitylogic.current_mode_number=50
for i in range(5):
cavitylogic.current_mode_number +=1
corrected_resonances = cavitylogic.get_nth_full_sweep(sweep_number=2+i)
target_mode = cavitylogic.get_target_mode(corrected_resonances, low_mode=low_mode, high_mode=high_mode, plot=True)
cavitylogic.ramp_popt = cavitylogic._fit_ramp(xdata=cavitylogic.time_trim[::10], ydata=cavitylogic.volts_trim[cavitylogic.ramp_channel,::10])
Modes = cavitylogic._ni.sweep_function(cavitylogic.RampUp_time[corrected_resonances],*cavitylogic.ramp_popt)
cavitylogic.linewidth_measurement(Modes,target_mode = target_mode, repeat=5, freq=40)
cavitylogic.mode_shift_list
signal_a= cavitylogic.first_sweep[cavitylogic.first_corrected_resonances[0:55]]
signal_b= cavitylogic.RampUp_signalR[corrected_resonances[0:55]]
MODsignal_a = signal_a - signal_a.mean()
MODsignal_a = -MODsignal_a / MODsignal_a.std()
MODsignal_b = signal_b - signal_b.mean()
MODsignal_b = -MODsignal_b / MODsignal_b.std()
# Calculate cross correlation function https://en.wikipedia.org/wiki/Cross-correlation
xcorr = np.correlate(MODsignal_a, MODsignal_b, 'same')
nsamples = MODsignal_b.size
dt = np.arange(-nsamples / 2, nsamples / 2, dtype=int)
t_delay = dt[xcorr.argmax()]
plt.plot(dt,xcorr)
plt.show()
plt.plot(MODsignal_a)
plt.plot(MODsignal_b)
print(t_delay)
Explanation: Move close with fiber
End of explanation |
7,469 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment
Polyglot has polarity lexicons for 136 languages.
The scale of the words' polarity consisted of three degrees
Step1: Polarity
To inquiry the polarity of a word, we can just call its own attribute polarity
Step2: Entity Sentiment
We can calculate a more sphosticated sentiment score for an entity that is mentioned in text as the following
Step3: First, we need split the text into sentneces, this will limit the words tha affect the sentiment of an entity to the words mentioned in the sentnece.
Step4: Second, we extract the entities
Step5: Finally, for each entity we identified, we can calculate the strength of the positive or negative sentiment it has on a scale from 0-1 | Python Code:
from polyglot.downloader import downloader
print(downloader.supported_languages_table("sentiment2", 3))
from polyglot.text import Text
Explanation: Sentiment
Polyglot has polarity lexicons for 136 languages.
The scale of the words' polarity consisted of three degrees: +1 for positive words, and -1 for negatives words.
Neutral words will have a score of 0.
Languages Coverage
End of explanation
text = Text("The movie was really good.")
print("{:<16}{}".format("Word", "Polarity")+"\n"+"-"*30)
for w in text.words:
print("{:<16}{:>2}".format(w, w.polarity))
Explanation: Polarity
To inquiry the polarity of a word, we can just call its own attribute polarity
End of explanation
blob = ("Barack Obama gave a fantastic speech last night. "
"Reports indicate he will move next to New Hampshire.")
text = Text(blob)
Explanation: Entity Sentiment
We can calculate a more sphosticated sentiment score for an entity that is mentioned in text as the following:
End of explanation
first_sentence = text.sentences[0]
print(first_sentence)
Explanation: First, we need split the text into sentneces, this will limit the words tha affect the sentiment of an entity to the words mentioned in the sentnece.
End of explanation
first_entity = first_sentence.entities[0]
print(first_entity)
Explanation: Second, we extract the entities
End of explanation
first_entity.positive_sentiment
first_entity.negative_sentiment
Explanation: Finally, for each entity we identified, we can calculate the strength of the positive or negative sentiment it has on a scale from 0-1
End of explanation |
7,470 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Для удобного получения твитов пользователей будем использовать библиотеку tweepy.
Step1: Вводим данные разработчика.
Step2: Получаем доступ к Twitter API.
Step3: Теперь считаем твиты каждого моего подписчика. Будем брать последние 100 твитов.
Step4: Данные получены, теперь нужно их красиво оформить в файл.
Для этого запишем данные в DataFrame из библиотеки pandas. | Python Code:
import warnings
warnings.filterwarnings('ignore')
import tweepy
Explanation: Для удобного получения твитов пользователей будем использовать библиотеку tweepy.
End of explanation
access_token = ""
access_token_secret = ""
consumer_key = ""
consumer_secret = ""
# Чтобы получить данные разработчика, нужно зарегистрироваться на https://dev.twitter.com и добавить свое приложение.
Explanation: Вводим данные разработчика.
End of explanation
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
Explanation: Получаем доступ к Twitter API.
End of explanation
def limit_handled(cursor):
while True:
try:
yield cursor.next()
except tweepy.RateLimitError:
time.sleep(15 * 60)
print('raised RateLimitError')
data = {}
for friend in limit_handled(tweepy.Cursor(api.friends).items()):
user_timeline = api.user_timeline(screen_name=friend.screen_name, count=100)
tweets = []
for status in user_timeline:
tweets.append(status.text)
# У некоторых пользователей может быть меньше 100 твитов, поэтому будем дополнять их пустыми строками,
# чтобы дальше было удобнее работать с записью в файл
while (len(tweets) < 100):
tweets.append('')
data.update({friend.screen_name : tweets})
Explanation: Теперь считаем твиты каждого моего подписчика. Будем брать последние 100 твитов.
End of explanation
import pandas as pd
df = pd.DataFrame.from_dict(data)
df.to_csv('twitter-data.csv', encoding='utf8')
Explanation: Данные получены, теперь нужно их красиво оформить в файл.
Для этого запишем данные в DataFrame из библиотеки pandas.
End of explanation |
7,471 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parcel loading
Given a set of parcels (assumes GDB format) from the parcel provider, this notebook will load individual features (from the parcel provider -- currently each feature-type is a county) into respective tables in postgres. Unfortunately due to the nature of the OpenFileGDB driver provided by GDAL (also experienced w/ the ESRI FileGDB driver) loading into a single homogeneous table was not working and loading all feature types (eg. separate tables for each feature type) would also error out at about 30% of parcels loaded.
This notebook also assumes that the feature tables for every feature have already been created (eg. as the result of a failed bulk load). Empty tables will be backfilled with feature data (in chunks of 50 counties at a time) and also compare feature counts per table to the parcel provider's metadata.
Step2: Load into individual parcel tables in chunks
Step3: Validate loading
Step15: Consolidate into single table
Create destination parcels table | Python Code:
import psycopg2 as pg
import pandas as pd
import os
conn = pg.connect('service=parcels')
conn_str = os.environ.get('PARCELS_CONNECTION')
Explanation: Parcel loading
Given a set of parcels (assumes GDB format) from the parcel provider, this notebook will load individual features (from the parcel provider -- currently each feature-type is a county) into respective tables in postgres. Unfortunately due to the nature of the OpenFileGDB driver provided by GDAL (also experienced w/ the ESRI FileGDB driver) loading into a single homogeneous table was not working and loading all feature types (eg. separate tables for each feature type) would also error out at about 30% of parcels loaded.
This notebook also assumes that the feature tables for every feature have already been created (eg. as the result of a failed bulk load). Empty tables will be backfilled with feature data (in chunks of 50 counties at a time) and also compare feature counts per table to the parcel provider's metadata.
End of explanation
def chunks(l, n):
Yield successive n-sized chunks from l.
for i in range(0, len(l), n):
yield l[i:i + n]
with conn.cursor() as cur:
cur.execute("select table_name from information_schema.tables where table_schema = 'core_logic_2018'")
res = cur.fetchall()
tables = [x[0] for x in res]
res = []
with conn.cursor() as cur:
for t in tables:
cur.execute("select count(1) from core_logic_2018.{}".format(t))
res.append({'table': t, 'count': cur.fetchone()[0]})
to_do = filter(lambda x: x['count'] == 0, res)
for table_list in chunks(map(lambda x: x['table'], to_do), 50):
tables = ' '.join(table_list)
print "Loading {}".format(tables)
!GDAL_MAX_DATASET_POOL_SIZE=100 ogr2ogr -f "PostgreSQL" PG:"$conn_str" ut_parcel_premium.gdb/ $tables -progress -lco SCHEMA=core_logic_2018 -lco OVERWRITE=yes --config PG_USE_COPY YES
Explanation: Load into individual parcel tables in chunks
End of explanation
df = pd.read_csv("./parcel-meta.csv")
for r in res:
row = df[df.Filename == r['table']]
if int(row['Records']) != r['count']:
display('Mismatch on parcel: {} csv count {} != db count of {}'.format(row['Filename'], row['Records'], r['count']))
Explanation: Validate loading
End of explanation
with conn.cursor() as c:
c.execute('CREATE TABLE public.parcels_2018 AS TABLE public.parcels WITH NO DATA;')
conn.commit()
sql =
insert into public.parcels_2018 (ogc_fid, wkb_geometry, parcel_id, state_code, cnty_code, apn,
apn2, addr, city, state, zip, plus, std_addr, std_city, std_state,
std_zip, std_plus, fips_code, unfrm_apn, apn_seq_no, frm_apn,
orig_apn, acct_no, census_tr, block_nbr, lot_nbr, land_use, m_home_ind,
prop_ind, own_cp_ind, tot_val, lan_val, imp_val, tot_val_cd,
lan_val_cd, assd_val, assd_lan, assd_imp, mkt_val, mkt_lan, mkt_imp,
appr_val, appr_lan, appr_imp, tax_amt, tax_yr, assd_yr, ubld_sq_ft,
bld_sq_ft, liv_sq_ft, gr_sq_ft, yr_blt, eff_yr_blt, bedrooms,
rooms, bld_code, bld_imp_cd, condition, constr_typ, ext_walls,
quality, story_nbr, bld_units, units_nbr)
select {}, shape, parcel_id, state_code, cnty_code, apn,
apn2, addr, city, state, zip, plus, std_addr, std_city, std_state,
std_zip, std_plus, fips_code, unfrm_apn, apn_seq_no, frm_apn,
orig_apn, acct_no, census_tr, block_nbr, lot_nbr, land_use, m_home_ind,
prop_ind, own_cp_ind, tot_val, lan_val, imp_val, tot_val_cd,
lan_val_cd, assd_val, assd_lan, assd_imp, mkt_val, mkt_lan, mkt_imp,
appr_val, appr_lan, appr_imp, tax_amt, tax_yr, assd_yr, ubld_sq_ft,
bld_sq_ft, liv_sq_ft, gr_sq_ft, yr_blt, eff_yr_blt, bedrooms,
rooms, bld_code, bld_imp_cd, condition, constr_typ, ext_walls,
quality, story_nbr, bld_units, units_nbr
from core_logic_2018.{}
try:
for r in res[50:]:
with conn.cursor() as c:
c.execute("select count(1) from information_schema.columns where table_name = %(table)s and table_schema = 'core_logic_2018' and column_name = 'objectid'",
r)
id_col = 'objectid' if c.fetchone()[0] == 1 else 'ogc_fid'
c.execute(sql.format(id_col, r['table']))
conn.commit()
except Exception as e:
print(e)
conn.rollback()
with conn.cursor() as c:
c.execute(CREATE INDEX ON public.parcels_2018 USING btree (census_tr COLLATE pg_catalog."default");)
c.execute(CREATE INDEX ON public.parcels_2018 USING btree ("substring"(census_tr::text, 0, 7) COLLATE pg_catalog."default");)
c.execute(CREATE INDEX ON public.parcels_2018 USING btree (city COLLATE pg_catalog."default", state COLLATE pg_catalog."default");)
c.execute(CREATE INDEX ON public.parcels_2018 USING btree (fips_code COLLATE pg_catalog."default");)
c.execute(CREATE INDEX ON public.parcels_2018 USING btree (land_use COLLATE pg_catalog."default");)
c.execute(CREATE UNIQUE INDEX ON public.parcels_2018 USING btree (parcel_id);)
c.execute(CREATE INDEX ON public.parcels_2018 USING gist (wkb_geometry);)
c.execute(CREATE INDEX ON public.parcels_2018 USING btree (state_code COLLATE pg_catalog."default", "substring"(census_tr::text, 0, 7) COLLATE pg_catalog."default");)
c.execute(CREATE INDEX ON public.parcels_2018 USING btree (state COLLATE pg_catalog."default");)
c.execute(CREATE INDEX ON public.parcels_2018 USING btree (story_nbr);)
Explanation: Consolidate into single table
Create destination parcels table
End of explanation |
7,472 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple Rotations
Author
Step1: Use the Q8 class that places these 4 numbers in 8 slots like so
Step3: If you are unfamiliar with this notation, the $I^2 = -1,\, i^3=-i,\, j^3=-j,\, k^3=-k$. Only positive numbers are used, with additive inverse put in these placeholders.
To do a rotation, one needs to pre-multiply by a quaternion, then post-multiply by its inverse. By doing so, the norm of R will not change because quaternions are a normed division algebra. A quaternion times its inverse has a norm of unity.
Step4: Should we expect the first term to change? Look into the triple product first term where I use Capital variable for 3-vectors to simplify the presentation
Step5: The first term does change! At least in the non-reduced Q8 format, there is a change because it is composed of the positive and negative terms we saw in the algebra problem. For example, there is the vector identity W.WxR=0. The cross product makes a vector that is 90 degrees to both W and R. The dot product of that cross product with W is zero because nothing is in the direction of W anymore. This shows up algebraically because the 6 terms of the cross product have three positive terms and three negative terms that exactly cancel when dotted to W. But the values remain in the $I^0$ and $I^2$ terms until Q8 is reduced.
When the Q8 is reduced, it ends up being a 5 as expected. This may be of interest because we keep more information about the change with the eight positions to fill in the Q8 representation (none of which are empty after the rotation).
We expect the square of the norms to be identical in the reduce form
Step6: If squared, the reduced interval should be the same too
Step7: But what should we make of these non-reduced calculations? Here is my speculation. In classical physics, one always, always, always uses the reduced form of a Q8 quaternion measurement. Classical physics involves one thing doing something. Physics gets odd when dealing with relativistic quantum feild theory. That is a rare sport played only when a one packet of protons collides with another inside an atom smasher. In those entirely odd situations, one must start thinking about multiple particles because we cannot know what happened, there is too much energy around, so we sum over all possible histories.
It is simple to move an event to another place in space-time the same distance from the origin. Because it is a transient event, it feels fleeting, which it should.
Rotations as a Well-behaved Function
Do rotations preserve the group structure of quaternions with multiplication? If it did, then
Step8: This looks well-behaved because the the U and V if the U and V form a product before being applied, it results in the same answer as doing one after the other. I was a bit surprised this work without having to reduce the results.
A Rotation of Time and Space
A rotation in time is commonly called a boost. The idea is that one gets a boost in speed, and that will change measurements of both time and distance. If one rushes toward the source of a signal, both the measurement of time and distance will get shorter in a way that keeps the interval the same.
There are published claims in the literature that a boost cannot be done with real-valued quaternions. This may be because people followed the form of rotations in space too closely. It is true that swapping hyperbolic cosines for cosines, and hyperbolic sines for sines does not create a Lorentz boost. Rotations are known as a compact Lie group while boosts form a group that is not compact. A slightly more complicated combination of the hyperbolic trig functions does do the work
Step9: The reduced interval is $124 \,I^2$, whether boosted or not. The norm will shrink because all the number are a little smaller, no longer quite (5, 6, 7, 8).
Step10: Rotations in Space and Time
Quaternions are just numbers. This makes combining transformations trivial. A measurement can be rotated and boosted. The only thing that should be unchanged is the interval
Step11: Because of the rotation, the z value was larger. It is a safe bet that the norm turns out to be smaller as happened before
Step12: Ratios at Work
An angle is a ratio, this side over that side. The velocity used in a boost is a ratio of distance over time. Say we have a reference observer who measures the interval between two events. If another observer see the same events, but was standing on his head, we migh expect the headstand to change how the crazy observer places his numbers into the three spatial slots. Yet the two observers should agree to the inteval, and they do.
The same happens if there is an observer travelling at a constant velocity relative to the referene observer. It is not surprizing that the math machinery is different because a spatial rotation is different from moving along at certain velocity.
Combining the spatial rotations and boosts can be done, creating messy results, except for the interval that remains the same. | Python Code:
%%capture
from Q_tool_devo import Q8;
U=Q8([1,2,-3,4])
V=Q8([4,-2,3,1])
R=Q8([5,6,7,-8])
Explanation: Simple Rotations
Author: Doug sweetser@alum.mit.edu
A deep leason from special relativity is that all measurements start as events in space-time. A measurment such as the length of a rod would appear to only involve space. Yet one needs a signal from both ends that gets received by the observer. And who is the observer? Every other system in the Universe is allowed. Since observers can be in very different states, that means the raw data these different observers collect from the same signals can be different. Special relaitivty helps determine what can be agreed upon, namely the interval for two inertial reference frame observers.
Spatial Rotations
In this iPython notebook, the one thing quaternions are known for - doing 3D spatial rotations - will be examined. When working with quaternions, it is not possible to work in just three spatial dimensions. There is always a fourth dimension, namely time. Even when thinking about spatial rotations, one must work with events in space-time.
Create a couple of quaternions to play with.
End of explanation
print(U)
print(R)
Explanation: Use the Q8 class that places these 4 numbers in 8 slots like so:
End of explanation
def rotate_R_by_U(R, U):
Given a space-time number R, rotate it by Q.
return U.triple_product(R, U.invert())
R_rotated = rotate_R_by_U(R,U)
Explanation: If you are unfamiliar with this notation, the $I^2 = -1,\, i^3=-i,\, j^3=-j,\, k^3=-k$. Only positive numbers are used, with additive inverse put in these placeholders.
To do a rotation, one needs to pre-multiply by a quaternion, then post-multiply by its inverse. By doing so, the norm of R will not change because quaternions are a normed division algebra. A quaternion times its inverse has a norm of unity.
End of explanation
print(R_rotated)
print(R_rotated.reduce())
Explanation: Should we expect the first term to change? Look into the triple product first term where I use Capital variable for 3-vectors to simplify the presentation:
$$\begin{align}(u, W)&(t, R)(u, -W)/(u^2 + W \cdot W)\
&= (u t - W \cdot R, u R + W t + W \times R)(u, -W)/(u^2 + W \cdot W)\
&=(u^2 t - uW \cdot R + u W \cdot R + W \cdot W t - W \cdot W \times R, ...)/(u^2 + W \cdot W)\
&=\left(\frac{u^2 + W \cdot W}{u^2 + W \cdot W}t,...\right) = (t, ...)\end{align}$$
Another way to see this is that the norm of $||R||$ does not change. That means the scalar plust the 3-vector norm do not change. While the 3-vector can shift who has values, the first term only has one term so should not change.
Now look at the rotated event.
End of explanation
print(R.norm_squared())
print(R_rotated.norm_squared())
print(R_rotated.norm_squared().reduce())
Explanation: The first term does change! At least in the non-reduced Q8 format, there is a change because it is composed of the positive and negative terms we saw in the algebra problem. For example, there is the vector identity W.WxR=0. The cross product makes a vector that is 90 degrees to both W and R. The dot product of that cross product with W is zero because nothing is in the direction of W anymore. This shows up algebraically because the 6 terms of the cross product have three positive terms and three negative terms that exactly cancel when dotted to W. But the values remain in the $I^0$ and $I^2$ terms until Q8 is reduced.
When the Q8 is reduced, it ends up being a 5 as expected. This may be of interest because we keep more information about the change with the eight positions to fill in the Q8 representation (none of which are empty after the rotation).
We expect the square of the norms to be identical in the reduce form:
End of explanation
print(R.square().reduce())
print(R_rotated.square())
print(R_rotated.square().reduce())
Explanation: If squared, the reduced interval should be the same too:
End of explanation
product_UV = rotate_R_by_U(R, V.product(U))
product_rotations = rotate_R_by_U(rotate_R_by_U(R, V), U)
print(product_UV)
print(product_rotations)
print(product_UV.reduce())
print(product_rotations.reduce())
Explanation: But what should we make of these non-reduced calculations? Here is my speculation. In classical physics, one always, always, always uses the reduced form of a Q8 quaternion measurement. Classical physics involves one thing doing something. Physics gets odd when dealing with relativistic quantum feild theory. That is a rare sport played only when a one packet of protons collides with another inside an atom smasher. In those entirely odd situations, one must start thinking about multiple particles because we cannot know what happened, there is too much energy around, so we sum over all possible histories.
It is simple to move an event to another place in space-time the same distance from the origin. Because it is a transient event, it feels fleeting, which it should.
Rotations as a Well-behaved Function
Do rotations preserve the group structure of quaternions with multiplication? If it did, then:
$$\rm{Rot}(VU) R = \rm{Rot}(V) \rm{Rot}(U) R $$
The product of V*U into the rotation function is identical to doing one after the other.
End of explanation
R_boosted=R.boost(0.01,0.02, 0.003)
print("boosted: {}".format(R_boosted.reduce()))
print(R.square().reduce())
print(R_boosted.square())
print(R_boosted.square().reduce())
Explanation: This looks well-behaved because the the U and V if the U and V form a product before being applied, it results in the same answer as doing one after the other. I was a bit surprised this work without having to reduce the results.
A Rotation of Time and Space
A rotation in time is commonly called a boost. The idea is that one gets a boost in speed, and that will change measurements of both time and distance. If one rushes toward the source of a signal, both the measurement of time and distance will get shorter in a way that keeps the interval the same.
There are published claims in the literature that a boost cannot be done with real-valued quaternions. This may be because people followed the form of rotations in space too closely. It is true that swapping hyperbolic cosines for cosines, and hyperbolic sines for sines does not create a Lorentz boost. Rotations are known as a compact Lie group while boosts form a group that is not compact. A slightly more complicated combination of the hyperbolic trig functions does do the work:
$$\begin{align} b \rightarrow b' = &(\cosh(\alpha), \sinh(\alpha) (t, R) (\cosh(\alpha), -\sinh(\alpha) \&- \frac{1}{2}(((\cosh(\alpha), \sinh(\alpha) (\cosh(\alpha), \sinh(\alpha) (t,R))^ -((\cosh(\alpha), -\sinh(\alpha) (\cosh(\alpha), -\sinh(\alpha) (t,R))^)\
&=(\cosh(\alpha) t - \sinh(\alpha) R, \cosh(\alpha) R - \sinh(\alpha) t)\end{align}$$
End of explanation
print(R.norm_squared().reduce())
print(R_boosted.norm_squared())
print(R_boosted.norm_squared().reduce())
Explanation: The reduced interval is $124 \,I^2$, whether boosted or not. The norm will shrink because all the number are a little smaller, no longer quite (5, 6, 7, 8).
End of explanation
R_rotated_and_boosted = R_rotated.boost(0.01,0.02, 0.003)
print("rotated and boosted: {}".format(R_rotated_and_boosted.reduce()))
print(R.square().reduce())
print(R_rotated_and_boosted.square())
print(R_rotated_and_boosted.square().reduce())
Explanation: Rotations in Space and Time
Quaternions are just numbers. This makes combining transformations trivial. A measurement can be rotated and boosted. The only thing that should be unchanged is the interval:
End of explanation
print(R.norm_squared().reduce())
print(R_rotated_and_boosted.norm_squared())
print(R_rotated_and_boosted.norm_squared().reduce())
Explanation: Because of the rotation, the z value was larger. It is a safe bet that the norm turns out to be smaller as happened before:
End of explanation
print(R.product(U).dif(U.product(R)))
print(R.vahlen_conj().product(U.vahlen_conj()).dif(U.vahlen_conj().product(R.vahlen_conj())))
print(R.vahlen_conj("'").product(U.vahlen_conj("'")).dif(U.vahlen_conj("'").product(R.vahlen_conj("'"))))
Explanation: Ratios at Work
An angle is a ratio, this side over that side. The velocity used in a boost is a ratio of distance over time. Say we have a reference observer who measures the interval between two events. If another observer see the same events, but was standing on his head, we migh expect the headstand to change how the crazy observer places his numbers into the three spatial slots. Yet the two observers should agree to the inteval, and they do.
The same happens if there is an observer travelling at a constant velocity relative to the referene observer. It is not surprizing that the math machinery is different because a spatial rotation is different from moving along at certain velocity.
Combining the spatial rotations and boosts can be done, creating messy results, except for the interval that remains the same.
End of explanation |
7,473 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spectral clustering for image segmentation
In this example, an image with connected circles is generated and
spectral clustering is used to separate the circles.
In these settings, the
Step1: 4 circles
Step2: 2 circles | Python Code:
print(__doc__)
# Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn.feature_extraction import image
from sklearn.cluster import spectral_clustering
l = 100
x, y = np.indices((l, l))
print(x.shape)
print(y.shape)
center1 = (28, 24)
center2 = (40, 50)
center3 = (67, 58)
center4 = (24, 70)
radius1, radius2, radius3, radius4 = 16, 14, 15, 14
circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1 ** 2
circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2 ** 2
circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3 ** 2
circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4 ** 2
Explanation: Spectral clustering for image segmentation
In this example, an image with connected circles is generated and
spectral clustering is used to separate the circles.
In these settings, the :ref:spectral_clustering approach solves the problem
know as 'normalized graph cuts': the image is seen as a graph of
connected voxels, and the spectral clustering algorithm amounts to
choosing graph cuts defining regions while minimizing the ratio of the
gradient along the cut, and the volume of the region.
As the algorithm tries to balance the volume (ie balance the region
sizes), if we take circles with different sizes, the segmentation fails.
In addition, as there is no useful information in the intensity of the image,
or its gradient, we choose to perform the spectral clustering on a graph
that is only weakly informed by the gradient. This is close to performing
a Voronoi partition of the graph.
In addition, we use the mask of the objects to restrict the graph to the
outline of the objects. In this example, we are interested in
separating the objects one from the other, and not from the background.
End of explanation
img = circle1 + circle2 + circle3 + circle4
# We use a mask that limits to the foreground: the problem that we are
# interested in here is not separating the objects from the background,
# but separating them one from the other.
mask = img.astype(bool)
img = img.astype(float)
img += 1 + 0.2 * np.random.randn(*img.shape)
# Convert the image into a graph with the value of the gradient on the
# edges.
graph = image.img_to_graph(img, mask=mask)
# Take a decreasing function of the gradient: we take it weakly
# dependent from the gradient the segmentation is close to a voronoi
graph.data = np.exp(-graph.data / graph.data.std())
# Force the solver to be arpack, since amg is numerically
# unstable on this example
labels = spectral_clustering(graph, n_clusters=4, eigen_solver='arpack')
label_im = -np.ones(mask.shape)
label_im[mask] = labels
plt.matshow(img)
plt.matshow(label_im)
Explanation: 4 circles
End of explanation
img = circle1 + circle2
mask = img.astype(bool)
img = img.astype(float)
img += 1 + 0.2 * np.random.randn(*img.shape)
graph = image.img_to_graph(img, mask=mask)
graph.data = np.exp(-graph.data / graph.data.std())
labels = spectral_clustering(graph, n_clusters=2, eigen_solver='arpack')
label_im = -np.ones(mask.shape)
label_im[mask] = labels
plt.matshow(img)
plt.matshow(label_im)
plt.show()
Explanation: 2 circles
End of explanation |
7,474 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SPINSpy Tutorial (2D)
Step1: If we want to use our shiny python scripts, we'll need to import them too.
Step2: If we want a quick man-page style summary, we can call help(spy). We can also call help(spy.<func>) for more information on the function <func>. Since the data that we're looking at is in a different directory, let's specify that now.
Note
Step3: Reading Full Files
Now that we have all of our tools, let's start doing! Let's see what we have first.
Step4: We have q (potential vorticity, this is a QG example). Let's read and plot our initial q field.
Step5: What did that just do? Let's break it down and look at the inputs.
'q'
Step6: Note that this is ordered as (Nx,Ny). If we had wanted MATLAB style ordering (Ny,Nx), we could have used the optional argument ordering = 'matlab' (useful for some plotting). The default is ordering = 'natural' (useful because it feels right).
Loading Grids and Simulation Information
To begin, let's load in our grid. Since we aren't dealing with mapped grids, we only need vectors (the default behaviour).
Step7: Perfect, now we have our grid vectors. We can also load in grid information, such as the domain size and limits. This is stored in a class that has a method called display. These are illustrated below.
Step8: Plotting
We now have our grid vectors and potential vorticity loaded into memory, so it's time to try some plotting! A standard plotting library in python is matplotlib, which replicates many of MATLAB's 2D plotting functions. For example, here we have a pcolor and contour plot. | Python Code:
%matplotlib inline
# Tells the system to plot in-line, only necessary for iPython notebooks,
# not regular command-line python
import numpy as np
import os
import sys
import matplotlib.pyplot as plt
import time
# Now that we have our packages, we need data. The file 'make_2d_data.py' will
# generate a sample data set. Let's run that now (may take a minute)
execfile('make_2d_data.py')
Explanation: SPINSpy Tutorial (2D):
This document will (hopefully) show you everything that you need to know to be able to process your SPINS outputs using python (why python? Because it's not MATLAB). This tutorial will assume that you have a basic understanding of python syntax.
To begin, we import some useful packages. Base python is fairly bare-bones, but you'll find that there's a package for almost anything that you want.
End of explanation
import spinspy as spy
import matpy as mp
Explanation: If we want to use our shiny python scripts, we'll need to import them too.
End of explanation
help(spy.set_path)
print('=======')
print('=======')
print('=======')
help(spy)
spy.set_path('Data/2d')
Explanation: If we want a quick man-page style summary, we can call help(spy). We can also call help(spy.<func>) for more information on the function <func>. Since the data that we're looking at is in a different directory, let's specify that now.
Note: This means that you don't need to be in the same directory as your data.
End of explanation
ls Data/2d
Explanation: Reading Full Files
Now that we have all of our tools, let's start doing! Let's see what we have first.
End of explanation
q = spy.reader('q', 0, [0,-1], [0,-1])
Explanation: We have q (potential vorticity, this is a QG example). Let's read and plot our initial q field.
End of explanation
q.shape
Explanation: What did that just do? Let's break it down and look at the inputs.
'q' : This tells the function which variable to load (in this case, q)
0 : This is the index, so we will load q.0.
[0,-1] : The x-range to load. This is shorthand and is equivalent to ':' from MATLAB.
[0,-1] : The y-range
Here we have loaded the entire thing. Alternatively, you could have given a single value or a list of indices. That is, giving 0 would take the first slice, [0,100] takes the first 100 elements, and [0,2,4,6] takes the first, third, fifth, and, seventh elements.
Lazy loading had also been implemented so that q=spy.reader('q',0) would have also worked.
End of explanation
x,y = spy.get_grid()
print('The shape of x is {0} and the shape of y is {1}'.format(x.shape,y.shape))
Explanation: Note that this is ordered as (Nx,Ny). If we had wanted MATLAB style ordering (Ny,Nx), we could have used the optional argument ordering = 'matlab' (useful for some plotting). The default is ordering = 'natural' (useful because it feels right).
Loading Grids and Simulation Information
To begin, let's load in our grid. Since we aren't dealing with mapped grids, we only need vectors (the default behaviour).
End of explanation
data = spy.get_params()
print(data.Nx,data.Ny,data.Nz)
print('---')
data.display()
Explanation: Perfect, now we have our grid vectors. We can also load in grid information, such as the domain size and limits. This is stored in a class that has a method called display. These are illustrated below.
End of explanation
q = spy.reader('q', 10)
plt.figure(1)
t0 = time.clock()
plt.contour(x,y,q.T) # Transpose for plotting order
t1 = time.clock()
print('Time to plot: {0:1.2e}'.format(t1-t0))
plt.title('q');
plt.xlabel('x');
plt.ylabel('y');
plt.figure(2)
t0 = time.clock()
plt.pcolor(x,y,q.transpose()); # Regrettably, the default colormap is still jet...
t1 = time.clock()
print('Time to plot: {0:1.2e}'.format(t1-t0))
plt.colorbar()
plt.title('Height Field');
plt.xlabel('x');
plt.ylabel('y');
plt.figure(3)
t0 = time.clock()
plt.pcolormesh(x,y,q.T, cmap='darkjet') # So we made darkjet!
t1 = time.clock()
print('Time to plot: {0:1.2e}'.format(t1-t0))
plt.colorbar()
plt.title('Height Field')
plt.xlabel('x')
plt.ylabel('y')
plt.axis('tight')
plt.show()
Explanation: Plotting
We now have our grid vectors and potential vorticity loaded into memory, so it's time to try some plotting! A standard plotting library in python is matplotlib, which replicates many of MATLAB's 2D plotting functions. For example, here we have a pcolor and contour plot.
End of explanation |
7,475 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Beaming and Boosting
Due to concerns about accuracy, support for Beaming & Boosting has been disabled in the 2.2 release of PHOEBE.
It may come as surprise that support for Doppler boosting has been dropped in PHOEBE 2.2. This document details the underlying causes for that decision and explains the conditions that need to be met for boosting to be re-incorporated into PHOEBE.
Let's start by reviewing the theory behind Doppler boosting. The motion of the stars towards or away from the observer changes the amount of received flux due to three effects
Step1: Pull a set of Sun-like emergent intensities as a function of $\mu = \cos \theta$ from the Castelli and Kurucz database of model atmospheres (the necessary file can be downloaded from here)
Step2: Grab only the normal component for testing purposes
Step3: Now let's load a Johnson V passband and the transmission function $P(\lambda)$ contained within
Step4: Tesselate the wavelength interval to the range covered by the passband
Step5: Calculate $S(\lambda) P(\lambda)$ and plot it, to make sure everything so far makes sense
Step6: Now let's compute the term $\mathrm{d}(\mathrm{ln}\, I_\lambda) / \mathrm{d}(\mathrm{ln}\, \lambda)$. First we will compute $\mathrm{ln}\,\lambda$ and $\mathrm{ln}\,I_\lambda$ and plot them
Step7: Per equation above, $B(\lambda)$ is then the slope of this curve (plus 5). Herein lies the problem
Step8: It is clear that there is a pretty strong systematics here that we sweep under the rug. Thus, we need to revise the way we compute the spectral index and make it robust before we claim that we support boosting.
For fun, this is what would happen if we tried to estimate $B(\lambda)$ at each $\lambda$ | Python Code:
import phoebe
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
Explanation: Beaming and Boosting
Due to concerns about accuracy, support for Beaming & Boosting has been disabled in the 2.2 release of PHOEBE.
It may come as surprise that support for Doppler boosting has been dropped in PHOEBE 2.2. This document details the underlying causes for that decision and explains the conditions that need to be met for boosting to be re-incorporated into PHOEBE.
Let's start by reviewing the theory behind Doppler boosting. The motion of the stars towards or away from the observer changes the amount of received flux due to three effects:
the spectrum is Doppler-shifted, so the flux, being the passband-weighted integral of the spectrum, changes;
the photons' arrival rate changes due to time dilation; and
radiation is beamed in the direction of motion due to light aberration.
It turns out that the combined boosting signal can be written as:
$$ I_\lambda = I_{\lambda,0} \left( 1 - B(\lambda) \frac{v_r}c \right), $$
where $I_{\lambda,0}$ is the intrinsic (rest-frame) passband intensity, $I_\lambda$ is the boosted passband intensity, $v_r$ is radial velocity, $c$ is the speed of light and $B(\lambda)$ is the boosting index:
$$ B(\lambda) = 5 + \frac{\mathrm{d}\,\mathrm{ln}\, I_\lambda}{\mathrm{d}\,\mathrm{ln}\, \lambda}. $$
The term $\mathrm{d}(\mathrm{ln}\, I_\lambda) / \mathrm{d}(\mathrm{ln}\, \lambda)$ is called spectral index. As $I_\lambda$ depends on $\lambda$, we average it across the passband:
$$ B_\mathrm{pb} = \frac{\int_\lambda \mathcal{P}(\lambda) \mathcal S(\lambda) B(\lambda) \mathrm d\lambda}{\int_\lambda \mathcal{P}(\lambda) \mathcal S(\lambda) \mathrm d\lambda}. $$
In what follows we will code up these steps and demonstrate the inherent difficulty of realizing a robust, reliable treatment of boosting.
Import all python modules that we'll need:
End of explanation
wl = np.arange(900., 39999.501, 0.5)/1e10
with fits.open('T06000G40P00.fits') as hdu:
Imu = 1e7*hdu[0].data
Explanation: Pull a set of Sun-like emergent intensities as a function of $\mu = \cos \theta$ from the Castelli and Kurucz database of model atmospheres (the necessary file can be downloaded from here):
End of explanation
Inorm = Imu[-1,:]
Explanation: Grab only the normal component for testing purposes:
End of explanation
pb = phoebe.get_passband('Johnson:V')
Explanation: Now let's load a Johnson V passband and the transmission function $P(\lambda)$ contained within:
End of explanation
keep = (wl >= pb.ptf_table['wl'][0]) & (wl <= pb.ptf_table['wl'][-1])
Inorm = Inorm[keep]
wl = wl[keep]
Explanation: Tesselate the wavelength interval to the range covered by the passband:
End of explanation
plt.plot(wl, Inorm*pb.ptf(wl), 'b-')
plt.show()
Explanation: Calculate $S(\lambda) P(\lambda)$ and plot it, to make sure everything so far makes sense:
End of explanation
lnwl = np.log(wl)
lnI = np.log(Inorm)
plt.xlabel(r'$\mathrm{ln}\,\lambda$')
plt.ylabel(r'$\mathrm{ln}\,I_\lambda$')
plt.plot(lnwl, lnI, 'b-')
plt.show()
Explanation: Now let's compute the term $\mathrm{d}(\mathrm{ln}\, I_\lambda) / \mathrm{d}(\mathrm{ln}\, \lambda)$. First we will compute $\mathrm{ln}\,\lambda$ and $\mathrm{ln}\,I_\lambda$ and plot them:
End of explanation
envelope = np.polynomial.legendre.legfit(lnwl, lnI, 5)
continuum = np.polynomial.legendre.legval(lnwl, envelope)
diff = lnI-continuum
sigma = np.std(diff)
clipped = (diff > -sigma)
while True:
Npts = clipped.sum()
envelope = np.polynomial.legendre.legfit(lnwl[clipped], lnI[clipped], 5)
continuum = np.polynomial.legendre.legval(lnwl, envelope)
diff = lnI-continuum
clipped = clipped & (diff > -sigma)
if clipped.sum() == Npts:
break
plt.xlabel(r'$\mathrm{ln}\,\lambda$')
plt.ylabel(r'$\mathrm{ln}\,I_\lambda$')
plt.plot(lnwl, lnI, 'b-')
plt.plot(lnwl, continuum, 'r-')
plt.show()
Explanation: Per equation above, $B(\lambda)$ is then the slope of this curve (plus 5). Herein lies the problem: what part of this graph do we fit a line to? In versions 2 and 2.1, PHOEBE used a 5th order Legendre polynomial to fit the spectrum and then sigma-clipping to get to the continuum. Finally, it computed an average derivative of that Legendrian and proclaimed that $B(\lambda)$. The order of the Legendre polynomial and the values of sigma for sigma-clipping have been set ad-hoc and kept fixed for every single spectrum.
End of explanation
dlnwl = lnwl[1:]-lnwl[:-1]
dlnI = lnI[1:]-lnI[:-1]
B = dlnI/dlnwl
plt.plot(0.5*(wl[1:]+wl[:-1]), B, 'b-')
plt.show()
Explanation: It is clear that there is a pretty strong systematics here that we sweep under the rug. Thus, we need to revise the way we compute the spectral index and make it robust before we claim that we support boosting.
For fun, this is what would happen if we tried to estimate $B(\lambda)$ at each $\lambda$:
End of explanation |
7,476 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DBSCAN (Density-Based Spatial Clustering of Applications with Noise)
Find core samples of high density and expand clusters from them.
The minimum number of samples in a neighborhood for a point to be considered as a core point was set at 10 and the maximum distance between two samples within the same neighborhood was set at 0.1.
Step1: small_df=df[df.Total_Expenses<1000000]
med_df=df[df.Total_Expenses>1000000]
med_df=med_df[df.Total_Expenses<10000000]
large_df=df[df.Total_Expenses<50000000]
large_df=large_df[df.Total_Expenses>10000000]
national_df=df[df.Total_Expenses>50000000] | Python Code:
import pandas as pd
df1=pd.read_csv('team_out_1.csv')
df2=pd.read_csv('team_out_a2.csv')
df=df1.append(df2)
df.dropna(inplace=True)
df.reset_index(inplace=True,drop=True)
df=df[df.Total_Expenses>0]
df=df[df.Program_Exp<=1]
df
Explanation: DBSCAN (Density-Based Spatial Clustering of Applications with Noise)
Find core samples of high density and expand clusters from them.
The minimum number of samples in a neighborhood for a point to be considered as a core point was set at 10 and the maximum distance between two samples within the same neighborhood was set at 0.1.
End of explanation
#Getting a list of positive businesses
temp=df[df.Program_Exp>.9]
temp=temp[temp.Liabilities_To_Asset<.2]
lst_temp=list(temp['EIN'])
df.reset_index(drop=True,inplace=True)
norm_df=df.copy()
norm_df=norm_df[['Program_Exp','Liabilities_To_Asset','Working_Capital','Surplus_Margin','Total_Expenses']]
from sklearn import preprocessing
x = norm_df.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
norm_df = pd.DataFrame(x_scaled)
norm_df["Filename"]=df['Filename']
norm_df["EIN"]=df['EIN']
norm_df.columns=['Program_Exp','Liabilities_To_Asset','Working_Capital','Surplus_Margin','Total_Expenses','Filename','EIN']
norm_df.set_index('EIN',inplace=True)
norm_df
df2 = df.copy()
df2.reset_index(inplace=True, drop = True)
print(norm_df2)
Y_class_df = pd.DataFrame()
X_class_df=norm_df.loc[lst_temp]
X_class_df['Efficiency'] = 1
Y_class_df['Efficiency'] = X_class_df['Efficiency']
X_class_df.drop('Efficiency', axis=1, inplace=True)
new_df=norm_df[['Program_Exp','Liabilities_To_Asset','Working_Capital','Surplus_Margin']]
new_df.reset_index(inplace=True,drop=True)
X_class_df=X_class_df[['Program_Exp','Liabilities_To_Asset','Working_Capital','Surplus_Margin']]
# X_class_df=X_class_df.drop(X_class_df.index[2]) #OUTLIER REMOVER
X_class_df.reset_index(inplace=True,drop=True)
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import TruncatedSVD
svd = TruncatedSVD(n_components=2, n_iter=7)
X = svd.fit_transform(new_df)
db = DBSCAN(eps=0.1, min_samples=10).fit(X)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
print(n_clusters_)
outliers_index = []
for i in range(len(labels)):
if(labels[i]==-1):
outliers_index.append(i)
#print(df2.loc[i])
outliers = df2.loc[outliers_index]
import matplotlib.pyplot as plt
# Black removed and is used for noise instead.
unique_labels = set(labels)
colors = 'cyan'
for k, col in zip(unique_labels, colors):
if k == -1:
# Black used for noise.
col = 'k'
class_member_mask = (labels == k)
xy = X[class_member_mask & core_samples_mask]
plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,
markeredgecolor='k', markersize=14)
xy = X[class_member_mask & ~core_samples_mask]
plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,
markeredgecolor='k', markersize=6)
plt.title('Estimated number of clusters: %d' % n_clusters_)
plt.show()
outliers
Explanation: small_df=df[df.Total_Expenses<1000000]
med_df=df[df.Total_Expenses>1000000]
med_df=med_df[df.Total_Expenses<10000000]
large_df=df[df.Total_Expenses<50000000]
large_df=large_df[df.Total_Expenses>10000000]
national_df=df[df.Total_Expenses>50000000]
End of explanation |
7,477 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Non-parametric 1 sample cluster statistic on single trial power
This script shows how to estimate significant clusters
in time-frequency power estimates. It uses a non-parametric
statistical procedure based on permutations and cluster
level statistics.
The procedure consists of
Step1: Set parameters
Step2: Define adjacency for statistics
To compute a cluster-corrected value, we need a suitable definition
for the adjacency/adjacency of our values. So we first compute the
sensor adjacency, then combine that with a grid/lattice adjacency
assumption for the time-frequency plane
Step3: Compute statistic
Step4: View time-frequency plots | 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.time_frequency import tfr_morlet
from mne.stats import permutation_cluster_1samp_test
from mne.datasets import sample
print(__doc__)
Explanation: Non-parametric 1 sample cluster statistic on single trial power
This script shows how to estimate significant clusters
in time-frequency power estimates. It uses a non-parametric
statistical procedure based on permutations and cluster
level statistics.
The procedure consists of:
extracting epochs
compute single trial power estimates
baseline line correct the power estimates (power ratios)
compute stats to see if ratio deviates from 1.
End of explanation
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
tmin, tmax, event_id = -0.3, 0.6, 1
# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')
include = []
raw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + 2 more
# picks MEG gradiometers
picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True,
stim=False, include=include, exclude='bads')
# Load condition 1
event_id = 1
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True,
reject=dict(grad=4000e-13, eog=150e-6))
# just use right temporal sensors for speed
epochs.pick_channels(mne.read_vectorview_selection('Right-temporal'))
evoked = epochs.average()
# Factor to down-sample the temporal dimension of the TFR computed by
# tfr_morlet. Decimation occurs after frequency decomposition and can
# be used to reduce memory usage (and possibly computational time of downstream
# operations such as nonparametric statistics) if you don't need high
# spectrotemporal resolution.
decim = 5
freqs = np.arange(8, 40, 2) # define frequencies of interest
sfreq = raw.info['sfreq'] # sampling in Hz
tfr_epochs = tfr_morlet(epochs, freqs, n_cycles=4., decim=decim,
average=False, return_itc=False, n_jobs=1)
# Baseline power
tfr_epochs.apply_baseline(mode='logratio', baseline=(-.100, 0))
# Crop in time to keep only what is between 0 and 400 ms
evoked.crop(-0.1, 0.4)
tfr_epochs.crop(-0.1, 0.4)
epochs_power = tfr_epochs.data
Explanation: Set parameters
End of explanation
sensor_adjacency, ch_names = mne.channels.find_ch_adjacency(
tfr_epochs.info, 'grad')
# Subselect the channels we are actually using
use_idx = [ch_names.index(ch_name.replace(' ', ''))
for ch_name in tfr_epochs.ch_names]
sensor_adjacency = sensor_adjacency[use_idx][:, use_idx]
assert sensor_adjacency.shape == \
(len(tfr_epochs.ch_names), len(tfr_epochs.ch_names))
assert epochs_power.data.shape == (
len(epochs), len(tfr_epochs.ch_names),
len(tfr_epochs.freqs), len(tfr_epochs.times))
adjacency = mne.stats.combine_adjacency(
sensor_adjacency, len(tfr_epochs.freqs), len(tfr_epochs.times))
# our adjacency is square with each dim matching the data size
assert adjacency.shape[0] == adjacency.shape[1] == \
len(tfr_epochs.ch_names) * len(tfr_epochs.freqs) * len(tfr_epochs.times)
Explanation: Define adjacency for statistics
To compute a cluster-corrected value, we need a suitable definition
for the adjacency/adjacency of our values. So we first compute the
sensor adjacency, then combine that with a grid/lattice adjacency
assumption for the time-frequency plane:
End of explanation
threshold = 3.
n_permutations = 50 # Warning: 50 is way too small for real-world analysis.
T_obs, clusters, cluster_p_values, H0 = \
permutation_cluster_1samp_test(epochs_power, n_permutations=n_permutations,
threshold=threshold, tail=0,
adjacency=adjacency,
out_type='mask', verbose=True)
Explanation: Compute statistic
End of explanation
evoked_data = evoked.data
times = 1e3 * evoked.times
plt.figure()
plt.subplots_adjust(0.12, 0.08, 0.96, 0.94, 0.2, 0.43)
# Create new stats image with only significant clusters
T_obs_plot = np.nan * np.ones_like(T_obs)
for c, p_val in zip(clusters, cluster_p_values):
if p_val <= 0.05:
T_obs_plot[c] = T_obs[c]
# Just plot one channel's data
ch_idx, f_idx, t_idx = np.unravel_index(
np.nanargmax(np.abs(T_obs_plot)), epochs_power.shape[1:])
# ch_idx = tfr_epochs.ch_names.index('MEG 1332') # to show a specific one
vmax = np.max(np.abs(T_obs))
vmin = -vmax
plt.subplot(2, 1, 1)
plt.imshow(T_obs[ch_idx], cmap=plt.cm.gray,
extent=[times[0], times[-1], freqs[0], freqs[-1]],
aspect='auto', origin='lower', vmin=vmin, vmax=vmax)
plt.imshow(T_obs_plot[ch_idx], cmap=plt.cm.RdBu_r,
extent=[times[0], times[-1], freqs[0], freqs[-1]],
aspect='auto', origin='lower', vmin=vmin, vmax=vmax)
plt.colorbar()
plt.xlabel('Time (ms)')
plt.ylabel('Frequency (Hz)')
plt.title(f'Induced power ({tfr_epochs.ch_names[ch_idx]})')
ax2 = plt.subplot(2, 1, 2)
evoked.plot(axes=[ax2], time_unit='s')
plt.show()
Explanation: View time-frequency plots
End of explanation |
7,478 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quickstart
Step1: DataFrame Creation
A PySpark DataFrame can be created via pyspark.sql.SparkSession.createDataFrame typically by passing a list of lists, tuples, dictionaries and pyspark.sql.Rows, a pandas DataFrame and an RDD consisting of such a list.
pyspark.sql.SparkSession.createDataFrame takes the schema argument to specify the schema of the DataFrame. When it is omitted, PySpark infers the corresponding schema by taking a sample from the data.
Firstly, you can create a PySpark DataFrame from a list of rows
Step2: Create a PySpark DataFrame with an explicit schema.
Step3: Create a PySpark DataFrame from a pandas DataFrame
Step4: Create a PySpark DataFrame from an RDD consisting of a list of tuples.
Step5: The DataFrames created above all have the same results and schema.
Step6: Viewing Data
The top rows of a DataFrame can be displayed using DataFrame.show().
Step7: Alternatively, you can enable spark.sql.repl.eagerEval.enabled configuration for the eager evaluation of PySpark DataFrame in notebooks such as Jupyter. The number of rows to show can be controlled via spark.sql.repl.eagerEval.maxNumRows configuration.
Step8: The rows can also be shown vertically. This is useful when rows are too long to show horizontally.
Step9: You can see the DataFrame's schema and column names as follows
Step10: Show the summary of the DataFrame
Step11: DataFrame.collect() collects the distributed data to the driver side as the local data in Python. Note that this can throw an out-of-memory error when the dataset is too large to fit in the driver side because it collects all the data from executors to the driver side.
Step12: In order to avoid throwing an out-of-memory exception, use DataFrame.take() or DataFrame.tail().
Step13: PySpark DataFrame also provides the conversion back to a pandas DataFrame to leverage pandas API. Note that toPandas also collects all data into the driver side that can easily cause an out-of-memory-error when the data is too large to fit into the driver side.
Step14: Selecting and Accessing Data
PySpark DataFrame is lazily evaluated and simply selecting a column does not trigger the computation but it returns a Column instance.
Step15: In fact, most of column-wise operations return Columns.
Step16: These Columns can be used to select the columns from a DataFrame. For example, DataFrame.select() takes the Column instances that returns another DataFrame.
Step17: Assign new Column instance.
Step18: To select a subset of rows, use DataFrame.filter().
Step19: Applying a Function
PySpark supports various UDFs and APIs to allow users to execute Python native functions. See also the latest Pandas UDFs and Pandas Function APIs. For instance, the example below allows users to directly use the APIs in a pandas Series within Python native function.
Step20: Another example is DataFrame.mapInPandas which allows users directly use the APIs in a pandas DataFrame without any restrictions such as the result length.
Step21: Grouping Data
PySpark DataFrame also provides a way of handling grouped data by using the common approach, split-apply-combine strategy.
It groups the data by a certain condition applies a function to each group and then combines them back to the DataFrame.
Step22: Grouping and then applying the avg() function to the resulting groups.
Step23: You can also apply a Python native function against each group by using pandas API.
Step24: Co-grouping and applying a function.
Step25: Getting Data in/out
CSV is straightforward and easy to use. Parquet and ORC are efficient and compact file formats to read and write faster.
There are many other data sources available in PySpark such as JDBC, text, binaryFile, Avro, etc. See also the latest Spark SQL, DataFrames and Datasets Guide in Apache Spark documentation.
CSV
Step26: Parquet
Step27: ORC
Step28: Working with SQL
DataFrame and Spark SQL share the same execution engine so they can be interchangeably used seamlessly. For example, you can register the DataFrame as a table and run a SQL easily as below
Step29: In addition, UDFs can be registered and invoked in SQL out of the box
Step30: These SQL expressions can directly be mixed and used as PySpark columns. | Python Code:
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
Explanation: Quickstart: DataFrame
This is a short introduction and quickstart for the PySpark DataFrame API. PySpark DataFrames are lazily evaluated. They are implemented on top of RDDs. When Spark transforms data, it does not immediately compute the transformation but plans how to compute later. When actions such as collect() are explicitly called, the computation starts.
This notebook shows the basic usages of the DataFrame, geared mainly for new users. You can run the latest version of these examples by yourself in 'Live Notebook: DataFrame' at the quickstart page.
There is also other useful information in Apache Spark documentation site, see the latest version of Spark SQL and DataFrames, RDD Programming Guide, Structured Streaming Programming Guide, Spark Streaming Programming Guide and Machine Learning Library (MLlib) Guide.
PySpark applications start with initializing SparkSession which is the entry point of PySpark as below. In case of running it in PySpark shell via <code>pyspark</code> executable, the shell automatically creates the session in the variable <code>spark</code> for users.
End of explanation
from datetime import datetime, date
import pandas as pd
from pyspark.sql import Row
df = spark.createDataFrame([
Row(a=1, b=2., c='string1', d=date(2000, 1, 1), e=datetime(2000, 1, 1, 12, 0)),
Row(a=2, b=3., c='string2', d=date(2000, 2, 1), e=datetime(2000, 1, 2, 12, 0)),
Row(a=4, b=5., c='string3', d=date(2000, 3, 1), e=datetime(2000, 1, 3, 12, 0))
])
df
Explanation: DataFrame Creation
A PySpark DataFrame can be created via pyspark.sql.SparkSession.createDataFrame typically by passing a list of lists, tuples, dictionaries and pyspark.sql.Rows, a pandas DataFrame and an RDD consisting of such a list.
pyspark.sql.SparkSession.createDataFrame takes the schema argument to specify the schema of the DataFrame. When it is omitted, PySpark infers the corresponding schema by taking a sample from the data.
Firstly, you can create a PySpark DataFrame from a list of rows
End of explanation
df = spark.createDataFrame([
(1, 2., 'string1', date(2000, 1, 1), datetime(2000, 1, 1, 12, 0)),
(2, 3., 'string2', date(2000, 2, 1), datetime(2000, 1, 2, 12, 0)),
(3, 4., 'string3', date(2000, 3, 1), datetime(2000, 1, 3, 12, 0))
], schema='a long, b double, c string, d date, e timestamp')
df
Explanation: Create a PySpark DataFrame with an explicit schema.
End of explanation
pandas_df = pd.DataFrame({
'a': [1, 2, 3],
'b': [2., 3., 4.],
'c': ['string1', 'string2', 'string3'],
'd': [date(2000, 1, 1), date(2000, 2, 1), date(2000, 3, 1)],
'e': [datetime(2000, 1, 1, 12, 0), datetime(2000, 1, 2, 12, 0), datetime(2000, 1, 3, 12, 0)]
})
df = spark.createDataFrame(pandas_df)
df
Explanation: Create a PySpark DataFrame from a pandas DataFrame
End of explanation
rdd = spark.sparkContext.parallelize([
(1, 2., 'string1', date(2000, 1, 1), datetime(2000, 1, 1, 12, 0)),
(2, 3., 'string2', date(2000, 2, 1), datetime(2000, 1, 2, 12, 0)),
(3, 4., 'string3', date(2000, 3, 1), datetime(2000, 1, 3, 12, 0))
])
df = spark.createDataFrame(rdd, schema=['a', 'b', 'c', 'd', 'e'])
df
Explanation: Create a PySpark DataFrame from an RDD consisting of a list of tuples.
End of explanation
# All DataFrames above result same.
df.show()
df.printSchema()
Explanation: The DataFrames created above all have the same results and schema.
End of explanation
df.show(1)
Explanation: Viewing Data
The top rows of a DataFrame can be displayed using DataFrame.show().
End of explanation
spark.conf.set('spark.sql.repl.eagerEval.enabled', True)
df
Explanation: Alternatively, you can enable spark.sql.repl.eagerEval.enabled configuration for the eager evaluation of PySpark DataFrame in notebooks such as Jupyter. The number of rows to show can be controlled via spark.sql.repl.eagerEval.maxNumRows configuration.
End of explanation
df.show(1, vertical=True)
Explanation: The rows can also be shown vertically. This is useful when rows are too long to show horizontally.
End of explanation
df.columns
df.printSchema()
Explanation: You can see the DataFrame's schema and column names as follows:
End of explanation
df.select("a", "b", "c").describe().show()
Explanation: Show the summary of the DataFrame
End of explanation
df.collect()
Explanation: DataFrame.collect() collects the distributed data to the driver side as the local data in Python. Note that this can throw an out-of-memory error when the dataset is too large to fit in the driver side because it collects all the data from executors to the driver side.
End of explanation
df.take(1)
Explanation: In order to avoid throwing an out-of-memory exception, use DataFrame.take() or DataFrame.tail().
End of explanation
df.toPandas()
Explanation: PySpark DataFrame also provides the conversion back to a pandas DataFrame to leverage pandas API. Note that toPandas also collects all data into the driver side that can easily cause an out-of-memory-error when the data is too large to fit into the driver side.
End of explanation
df.a
Explanation: Selecting and Accessing Data
PySpark DataFrame is lazily evaluated and simply selecting a column does not trigger the computation but it returns a Column instance.
End of explanation
from pyspark.sql import Column
from pyspark.sql.functions import upper
type(df.c) == type(upper(df.c)) == type(df.c.isNull())
Explanation: In fact, most of column-wise operations return Columns.
End of explanation
df.select(df.c).show()
Explanation: These Columns can be used to select the columns from a DataFrame. For example, DataFrame.select() takes the Column instances that returns another DataFrame.
End of explanation
df.withColumn('upper_c', upper(df.c)).show()
Explanation: Assign new Column instance.
End of explanation
df.filter(df.a == 1).show()
Explanation: To select a subset of rows, use DataFrame.filter().
End of explanation
import pandas as pd
from pyspark.sql.functions import pandas_udf
@pandas_udf('long')
def pandas_plus_one(series: pd.Series) -> pd.Series:
# Simply plus one by using pandas Series.
return series + 1
df.select(pandas_plus_one(df.a)).show()
Explanation: Applying a Function
PySpark supports various UDFs and APIs to allow users to execute Python native functions. See also the latest Pandas UDFs and Pandas Function APIs. For instance, the example below allows users to directly use the APIs in a pandas Series within Python native function.
End of explanation
def pandas_filter_func(iterator):
for pandas_df in iterator:
yield pandas_df[pandas_df.a == 1]
df.mapInPandas(pandas_filter_func, schema=df.schema).show()
Explanation: Another example is DataFrame.mapInPandas which allows users directly use the APIs in a pandas DataFrame without any restrictions such as the result length.
End of explanation
df = spark.createDataFrame([
['red', 'banana', 1, 10], ['blue', 'banana', 2, 20], ['red', 'carrot', 3, 30],
['blue', 'grape', 4, 40], ['red', 'carrot', 5, 50], ['black', 'carrot', 6, 60],
['red', 'banana', 7, 70], ['red', 'grape', 8, 80]], schema=['color', 'fruit', 'v1', 'v2'])
df.show()
Explanation: Grouping Data
PySpark DataFrame also provides a way of handling grouped data by using the common approach, split-apply-combine strategy.
It groups the data by a certain condition applies a function to each group and then combines them back to the DataFrame.
End of explanation
df.groupby('color').avg().show()
Explanation: Grouping and then applying the avg() function to the resulting groups.
End of explanation
def plus_mean(pandas_df):
return pandas_df.assign(v1=pandas_df.v1 - pandas_df.v1.mean())
df.groupby('color').applyInPandas(plus_mean, schema=df.schema).show()
Explanation: You can also apply a Python native function against each group by using pandas API.
End of explanation
df1 = spark.createDataFrame(
[(20000101, 1, 1.0), (20000101, 2, 2.0), (20000102, 1, 3.0), (20000102, 2, 4.0)],
('time', 'id', 'v1'))
df2 = spark.createDataFrame(
[(20000101, 1, 'x'), (20000101, 2, 'y')],
('time', 'id', 'v2'))
def asof_join(l, r):
return pd.merge_asof(l, r, on='time', by='id')
df1.groupby('id').cogroup(df2.groupby('id')).applyInPandas(
asof_join, schema='time int, id int, v1 double, v2 string').show()
Explanation: Co-grouping and applying a function.
End of explanation
df.write.csv('foo.csv', header=True)
spark.read.csv('foo.csv', header=True).show()
Explanation: Getting Data in/out
CSV is straightforward and easy to use. Parquet and ORC are efficient and compact file formats to read and write faster.
There are many other data sources available in PySpark such as JDBC, text, binaryFile, Avro, etc. See also the latest Spark SQL, DataFrames and Datasets Guide in Apache Spark documentation.
CSV
End of explanation
df.write.parquet('bar.parquet')
spark.read.parquet('bar.parquet').show()
Explanation: Parquet
End of explanation
df.write.orc('zoo.orc')
spark.read.orc('zoo.orc').show()
Explanation: ORC
End of explanation
df.createOrReplaceTempView("tableA")
spark.sql("SELECT count(*) from tableA").show()
Explanation: Working with SQL
DataFrame and Spark SQL share the same execution engine so they can be interchangeably used seamlessly. For example, you can register the DataFrame as a table and run a SQL easily as below:
End of explanation
@pandas_udf("integer")
def add_one(s: pd.Series) -> pd.Series:
return s + 1
spark.udf.register("add_one", add_one)
spark.sql("SELECT add_one(v1) FROM tableA").show()
Explanation: In addition, UDFs can be registered and invoked in SQL out of the box:
End of explanation
from pyspark.sql.functions import expr
df.selectExpr('add_one(v1)').show()
df.select(expr('count(*)') > 0).show()
Explanation: These SQL expressions can directly be mixed and used as PySpark columns.
End of explanation |
7,479 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Importing data from LOBO-Buoy server
Objectives
Step1: NOTE
Step2: Exploring the data
Lets see what is in "data"...
Step3: Now lets disect "data" a bit... lets find the title (or "keys") of its collumns...
Step4: Lets see what is in the temperature column...
Step5: ...and in the "date" column...
Step6: ...and the indices
Step7: Plotting
Ok! Now lets start with a quick plot...
...but first a quick trick. You need to execute %matplotlib inline so that your plots appear in the Notebook.
Step8: Ok, now lets do the plot...
Step9: If we change the indices from "numbers" to "DatetimeIndex", then we can plot nicer!
Step10: Lets see what happened....
Step11: Lets plot again...
Step12: Lets make it prettier!
Putting it all together
Ok. NOw it is the time to put it all together... Note that I replaced the 'min_date' and 'max_date' arguments in the url for a couple of variables, so that we can easily change dates.
Step13: Making a function
Now it is time to make our code into a function, note that
Step14: Lets take our new function for a spin...
Step15: Some final touch-ups, like Documentation and a karg to prevent plotting...
Step16: Lets see if we can see the documentation...
Step17: One last spin without making a plot | Python Code:
# URL quering the LOBO server for data (in this case, temperature data)
URL = 'http://lobo.satlantic.com/cgi-data/nph-data.cgi?min_date=20090610&max_date=20090706&y=temperature'
Explanation: Importing data from LOBO-Buoy server
Objectives:
* Download data from LOBO server
* (if needed) transform data into a format suitable for plotting
* Plot time vs variable (e.g. temperature)
* Turn your code into function for future (easier) use
* Add docstrings and other relevant comments and documentation
Other relevant information:
LOBO's main page
"LOBOviz" data download portal
time to work...
Getting the data
From the "LOBOviz" webpage, you can select a variable (e.g. temperature) and a date range sometime during the summer.
Click "Plot data"
Right-click on the button "Download tab separtaed values" and select "Copy link address"
In python (i.e. Notebook or Spyder), "paste" the URL address in a variable
End of explanation
import pandas as pd
# Import data from LOBO server
data = pd.read_csv(URL,sep='\t')
Explanation: NOTE: You can see in the URL that the dates are included (i.e. min_date=20090610 and max_date=20090706) as well as the variable to query (i.e. y=temperature).
Now lets use "pandas" to actually dowload the data...
End of explanation
data[:10]
Explanation: Exploring the data
Lets see what is in "data"...
End of explanation
data.keys()
Explanation: Now lets disect "data" a bit... lets find the title (or "keys") of its collumns...
End of explanation
data['temperature [C]'][:10]
Explanation: Lets see what is in the temperature column...
End of explanation
data['date [AST]'][:10]
Explanation: ...and in the "date" column...
End of explanation
data.index
Explanation: ...and the indices
End of explanation
%matplotlib inline
Explanation: Plotting
Ok! Now lets start with a quick plot...
...but first a quick trick. You need to execute %matplotlib inline so that your plots appear in the Notebook.
End of explanation
#import matplotlib.pyplot as plt
# ...just a quick plot
data.plot();
Explanation: Ok, now lets do the plot...
End of explanation
# Change indices to DatetimeIndex objects
data.index = pd.DatetimeIndex(data['date [AST]'])
# Now that we made "date indices" we can drop the "date" column
data = data.drop('date [AST]',axis=1)
Explanation: If we change the indices from "numbers" to "DatetimeIndex", then we can plot nicer!
End of explanation
data.index
Explanation: Lets see what happened....
End of explanation
data.plot()
Explanation: Lets plot again...
End of explanation
import pandas as pd
import matplotlib.pyplot as plt
# Start and End dates
mindate = '20090610'
maxdate = '20090706'
# URL quering the LOBO server for data (in this case, temperature data)
URL = 'http://lobo.satlantic.com/cgi-data/nph-data.cgi?min_date='+mindate+'&max_date='+maxdate+'&y=temperature'
# Import data from LOBO server
data = pd.read_csv(URL,sep='\t')
# Change indices to DatetimeIndex objects
data.index = pd.DatetimeIndex(data['date [AST]'])
# Now that we made "date indices" we can drop the "date" column
data = data.drop('date [AST]',axis=1)
# ...a bit fancier plot
data.plot(style='-r',legend=False)
plt.title('Temperature from LOBO (Halifax, Canada)')
plt.ylabel('Temperature (oC)')
plt.xlabel('Dates')
Explanation: Lets make it prettier!
Putting it all together
Ok. NOw it is the time to put it all together... Note that I replaced the 'min_date' and 'max_date' arguments in the url for a couple of variables, so that we can easily change dates.
End of explanation
def load_temp(mindate,maxdate):
import pandas as pd
import matplotlib.pyplot as plt
# URL quering the LOBO server for data (in this case, temperature data)
URL = 'http://lobo.satlantic.com/cgi-data/nph-data.cgi?min_date='+mindate+'&max_date='+maxdate+'&y=temperature'
# Import data from LOBO server
data = pd.read_csv(URL,sep='\t')
# Change indices to DatetimeIndex objects
data.index = pd.DatetimeIndex(data['date [AST]'])
# Now that we made "date indices" we can drop the "date" column
data = data.drop('date [AST]',axis=1)
# ...a bit fancier plot
data.plot(style='-r',legend=False)
plt.title('Temperature from LOBO (Halifax, Canada)')
plt.ylabel('Temperature (oC)')
plt.xlabel('Dates')
plt.show()
return data
Explanation: Making a function
Now it is time to make our code into a function, note that:
At the begining, add: def NameOfFunction(arguments):
At the end, add: return Output
Indent contents
NOTE that we inserted mindate and maxdate in the URL string!!!
End of explanation
mydata = load_temp('20090616','20101017')
print mydata[:20]
Explanation: Lets take our new function for a spin...
End of explanation
def load_temp(mindate,maxdate,plot=True):
'''
Downloads data from LOBO and makes a plot.
Arguments:
mindate (string): Start date
maxdate (string): End date
plot (boolean): If True, it produces a plot (default=True)
Returns:
DataFrame and a plot (if `plot` argument = True)
'''
import pandas as pd
import matplotlib.pyplot as plt
# URL quering the LOBO server for data (in this case, temperature data)
URL = 'http://lobo.satlantic.com/cgi-data/nph-data.cgi?min_date='+mindate+'&max_date='+maxdate+'&y=temperature'
# Import data from LOBO server
data = pd.read_csv(URL,sep='\t')
# Change indices to DatetimeIndex objects
data.index = pd.DatetimeIndex(data['date [AST]'])
# Now that we made "date indices" we can drop the "date" column
data = data.drop('date [AST]',axis=1)
if plot==True:
# ...a bit fancier plot
data.plot(style='-r',legend=False)
plt.title('Temperature from LOBO (Halifax, Canada)')
plt.ylabel('Temperature (oC)')
plt.xlabel('Dates')
plt.show()
return data
Explanation: Some final touch-ups, like Documentation and a karg to prevent plotting...
End of explanation
load_temp?
Explanation: Lets see if we can see the documentation...
End of explanation
mydata = load_temp('20090610','20090706',plot=False)
print mydata[:10]
Explanation: One last spin without making a plot:
End of explanation |
7,480 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to on road lane detection program
Programm has image processing pipeline that support both RGB images and BGR video input.
RGB image processing consists of next steps
Step1: Next class is responsible for filtering out lanes detection area
Step2: Here is the result of getColorMask function, that turns all white and yellow objects into white ones and makes other colored objects black
Step3: The result of Canny edge detection
Step4: Result of getLaneLines transformed into lines
Then goes line grop detection, that accepts getLaneLines result as input parameter.
CoordinateSorter class does line groups detection and median line calculation for each found group.
Influence it's input parameters on 'sort' function behavior could be described with help of Gherkin language
Step5: Result of lines sorting function in Cartesian coordinate system
Step6: The result
Step7: And the result of processFrame
Step8: Video processing entry point
Step9: Constants with image/video pathes for testing, pipeline initialization | Python Code:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import pandas
import os
def getPathFor(file_path):
current_directory = %pwd
path = os.path.join(current_directory, file_path)
print("About to open file: {}\n".format(path))
return path
Explanation: Welcome to on road lane detection program
Programm has image processing pipeline that support both RGB images and BGR video input.
RGB image processing consists of next steps:
- image file reading. File expected to exist on disk
- RGB to BGR conversion
- common image processing pipeline
- processing result conversion (BGR to RGB)
- result image output
BGR video processing consists of next steps:
- video file capturing. File expected to exist on disk
- video frame processing loop:
* common image processing pipeline
* result frame output
- resources release
Image processing pipeline does:
- BGR to HSV conversion
- white and yellow colors filter, creates b/w image. Makes other colored objects black
- detection area filter. Creates new b/w image output of color filter result
- edge detection
- lines detection with help of Hough transform method (cv2.HoughLines tool)
- lanes detection with help of custom algorithm that does line groups detection and median line
calculation for each found group
- lane lines Polar coortinate to Cartesian coordinate conversion, drawing lane lines
- result image composition from initial frame and detected lane lines images
- result image returned to program for output/further operations
Colors detection on HSV image allows efficientely get rid of noise coused by shadows and road surface color artifacts. Further b/w image processing might save processor time.
As the next improvement I would extract configuration parametes into separate entity. And would use same instance of it for on-flight configuration/adjustment. It can become an interface for another system :)
Imports, compose full file path fuction
End of explanation
class DetectionAreaFilter:
def __init__(self):
self._lower_yellow = np.array([20, 0, 170], dtype=np.uint8)
self._upper_yellow = np.array([55, 255, 255], dtype=np.uint8)
self._lower_white = np.array([0, 0, 220], dtype=np.uint8)
self._upper_white = np.array([255, 25, 255], dtype=np.uint8)
self._ignore_mask_color = 255
def getColorMask(self, hsv_image):
mask_yellow = cv2.inRange(hsv_image, self._lower_yellow, self._upper_yellow)
mask_white = cv2.inRange(hsv_image, self._lower_white, self._upper_white)
mask = cv2.add(mask_white, mask_yellow)
return mask
def applyDetectionArea(self, bw_image, width_adjustment=60, height_adjustment=65):
im_height = bw_image.shape[0]
im_half_height = im_height // 2
im_width = bw_image.shape[1]
im_half_width = im_width // 2
area_left_bottom = (0, im_height)
area_left_top = (im_half_width - width_adjustment, im_half_height + height_adjustment)
area_right_top = (im_half_width + width_adjustment, im_half_height + height_adjustment)
area_right_bottom = (im_width, im_height)
detection_area = [area_left_bottom, area_left_top, area_right_top, area_right_bottom]
vertices = np.array([detection_area], dtype=np.int32)
mask = np.zeros_like(bw_image)
cv2.fillPoly(mask, vertices, self._ignore_mask_color)
masked_image = cv2.bitwise_and(bw_image, mask)
return masked_image
Explanation: Next class is responsible for filtering out lanes detection area:
End of explanation
def getEdges(image, low_threshold=50, high_threshold=150):
edges = cv2.Canny(image, low_threshold, high_threshold)
return edges
Explanation: Here is the result of getColorMask function, that turns all white and yellow objects into white ones and makes other colored objects black:
And the result of applyDetectionArea function, that creates new b/w image with applyed trapezium shaped mask out of given b/w image:
Then goes Canny edge detection:
End of explanation
def getLaneLines(edges):
deg = np.pi/180
lines = cv2.HoughLines(edges, 1, 1*deg, 40)
if lines is None:
return np.array([])
points_array = list()
for line in lines:
for rho, theta in line:
points_array.append((rho, theta))
return np.array(points_array)
Explanation: The result of Canny edge detection:
Lines detetection with help of Hough transform method
End of explanation
class CoordinateSorter:
def __init__(self, max_distance_delta, max_angle_delta, threshold):
if max_angle_delta < 0:
raise ValueError("[max_angle_delta] must be positive number")
if max_angle_delta < 0:
raise ValueError("[max_angle_delta] must be positive number")
if threshold < 1 or type(threshold) != int:
raise ValueError("[threshold] expected to be integer greater then or equal to 1")
self._max_point_distance = (max_distance_delta, max_angle_delta)
self._min_points_amount = threshold
def _sortPointsByDistance(self, points_dict):
set_list = list()
for key, value in points_dict.items():
indexes_set = set()
set_list.append(indexes_set)
indexes_set.add(key)
for inner_key, inner_value in points_dict.items():
point_distance = abs(np.subtract(value, inner_value))
if point_distance[0] <= self._max_point_distance[0] \
and point_distance[1] <= self._max_point_distance[1]:
indexes_set.add(inner_key)
return set_list
def _splitOnGroups(self, set_list_source):
sorted_source = list(set_list_source)
sorted_source.sort(key=len, reverse=True)
extremums = list()
def find_extremums(ordered_list_of_set_items):
if len(ordered_list_of_set_items) == 0:
return
first_extremum = ordered_list_of_set_items[0]
items_for_further_sorting = list()
for dot_set in ordered_list_of_set_items:
if dot_set.issubset(first_extremum):
continue
else:
if len(first_extremum.intersection(dot_set)):
first_extremum = first_extremum.union(dot_set)
else:
items_for_further_sorting.append(dot_set)
extremums.append(first_extremum)
find_extremums(items_for_further_sorting)
find_extremums(sorted_source)
filtered_extremums = filter(lambda x: len(x) >= self._min_points_amount, extremums)
return filtered_extremums
@staticmethod
def _getMedian(source_dict, key_set):
point_array = [source_dict[item] for item in key_set]
data_frame = pandas.DataFrame(data=point_array, columns=["distance", "angle"])
return data_frame["distance"].median(), data_frame["angle"].median()
def sort(self, points_array):
if len(points_array) < self._min_points_amount:
return []
points_dictionary = dict()
for index, coordinates in enumerate(points_array):
points_dictionary[index] = (int(coordinates[0]), coordinates[1])
point_set_list = self._sortPointsByDistance(points_dictionary)
point_groups = self._splitOnGroups(point_set_list)
resulting_points = [self._getMedian(points_dictionary, point_group) for point_group in point_groups]
return resulting_points
Explanation: Result of getLaneLines transformed into lines
Then goes line grop detection, that accepts getLaneLines result as input parameter.
CoordinateSorter class does line groups detection and median line calculation for each found group.
Influence it's input parameters on 'sort' function behavior could be described with help of Gherkin language:
CoordinateSorter(max_distance_delta, max_angle_delta, threshold)
Scenario: 'max_distance_delta' and 'max_angle_delta' parameters allow to control line group detection
Given: 5 lines have been given to sort
And: it is possible to create a chain 'chain_1' of lines line1, line2, line3
Where: distance between links is less (or equal) then (max_distance_delta, max_angle_delta)
And: it is possible to create a chain 'chain_2' of lines line4, line5
Where: distance between links is less (or equal) then (max_distance_delta, max_angle_delta)
And: distance between chain_1 and chain_2 edges is more than (max_distance_delta, max_angle_delta)
Then: chain_1 and chain_2 considered as two separate lines
Scenario: 'threshold' parameter allows to filter out noise lines
Given: threshold = 4, set of lines
When: sorter found 3 groups of lines
And: the first set of lines contains 10 lines, second - 5 lines
But: the third set of lines contains 3 lines
Then: the third considered as noise and will not be presented in sorting result
Resulting line is calculate as median of all lines in a group
End of explanation
def convert(rho, theta, y_min, y_max):
def create_point(y):
x = (rho - y*np.sin(theta))/np.cos(theta)
return int(x), int(y)
d1 = create_point(y_max)
d2 = create_point(y_min)
return d1, d2
def drawLines(polar_coordinates_array, image, color, line_weight = 10):
y_max = image.shape[0]
y_min = int(y_max * 2 / 3)
lines = [convert(rho, theta, y_min, y_max) for rho, theta in polar_coordinates_array]
for d1, d2 in lines:
cv2.line(image, d1, d2, color, line_weight)
Explanation: Result of lines sorting function in Cartesian coordinate system:
Drawing of lines with needed length:
End of explanation
class ImageProcessor:
def __init__(self, detection_area_filter, coordinate_sorter):
self._bgr_line_color = (0, 0, 255)
self._detection_area_filter = detection_area_filter
self._coordinate_sorter = coordinate_sorter
def processFrame(self, bgr_frame):
frame = cv2.cvtColor(bgr_frame, cv2.COLOR_BGR2HSV)
bw_color_mask = self._detection_area_filter.getColorMask(frame)
bw_area = self._detection_area_filter.applyDetectionArea(bw_color_mask)
bw_edges = getEdges(bw_area)
polar_lane_coordinates = getLaneLines(bw_edges)
average_polar_lane_coordinates = self._coordinate_sorter.sort(polar_lane_coordinates)
lines_image = np.zeros(bgr_frame.shape, dtype=np.uint8)
drawLines(average_polar_lane_coordinates, lines_image, self._bgr_line_color)
result_image = cv2.addWeighted(lines_image, 0.9, bgr_frame, 1, 0)
return result_image
def _convert_bw_2_color(self, bw_image):
return np.dstack((bw_image, bw_image, bw_image))
Explanation: The result:
The pipeline itself:
End of explanation
def showImage(file_path):
def convert(image):
return image[..., [2, 1, 0]]
image_path = getPathFor(file_path)
rgb_image = mpimg.imread(image_path)
bgr_frame = convert(rgb_image)
frame = img_processor.processFrame(bgr_frame)
rgb_frame = convert(frame)
plt.imshow(rgb_frame)
plt.show()
Explanation: And the result of processFrame:
RGB image processing entry point
End of explanation
def playVideo(file_path):
video_path = getPathFor(file_path)
video = cv2.VideoCapture(video_path)
print("About to start video playback...")
while video.isOpened():
_, bgr_frame = video.read()
if not isinstance(bgr_frame, np.ndarray):
# workaround to handle end of video stream.
break
frame = img_processor.processFrame(bgr_frame)
cv2.imshow("output", frame)
key = cv2.waitKey(1) & 0xFF
# stop video on ESC key pressed
if key == 27:
break
print("Video has been closed successfully.")
video.release()
cv2.destroyAllWindows()
Explanation: Video processing entry point
End of explanation
image1 = "input/test_images/solidWhiteCurve.jpg"
image2 = "input/test_images/solidWhiteRight.jpg"
image3 = "input/test_images/solidYellowCurve.jpg"
image4 = "input/test_images/solidYellowCurve2.jpg"
image5 = "input/test_images/solidYellowLeft.jpg"
image6 = "input/test_images/whiteCarLaneSwitch.jpg"
video1 = "input/test_videos/challenge.mp4"
video2 = "input/test_videos/solidYellowLeft.mp4"
video3 = "input/test_videos/solidWhiteRight.mp4"
detection_area_filter = DetectionAreaFilter()
max_distance_delta = 40 # max distance between lines (rho1 - rho2) in polar coordinate system
max_angle_delta = np.radians(4) # max angle between lines (theta1 - theta2) in polar coordinate system
threshold = 3 # min amount of lines in set filter
coordinate_sorter = CoordinateSorter(max_distance_delta, max_angle_delta, threshold)
img_processor = ImageProcessor(detection_area_filter, coordinate_sorter)
showImage(image4)
#playVideo(video1)
Explanation: Constants with image/video pathes for testing, pipeline initialization
End of explanation |
7,481 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
write a program to train a machine learning model using support vector machines algorithm and print the predictions
| Python Code::
from sklearn import svm
model = svm.SVC()
model.fit(X_train, y_train)
pred = model.predict(X_test)
print(pred)
|
7,482 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Indico.io sentiment score analysis
Step1: Compute average sentiment score per week
make it 0.5 if no news that week.
Step2: read bitcoin price data
Step3: add news volume data
Step4: AlchemyAPI sentiment score
Step5: Daily score analysis
Previously we only consider average weekly score. As news spread pretty fast, it is possible that its effect is occurring in shorter time. Therefore we try to plot daily score data.
Step6: Prediction
Weekly prediction first
Step7: Daily prediction | Python Code:
score_data = pd.read_csv("../data/indico_nyt_bitcoin.csv", index_col='time',
parse_dates=[0], date_parser=lambda x: datetime.datetime.strptime(x, time_format))
score_data.head()
Explanation: Indico.io sentiment score analysis
End of explanation
weekly_score = score_data.resample('w', how='mean').loc['2013':].fillna(0.5)
weekly_score.head()
weekly_score.plot()
Explanation: Compute average sentiment score per week
make it 0.5 if no news that week.
End of explanation
time_format = "%Y-%m-%dT%H:%M:%S"
data = pd.read_csv("../data/price.csv", names=['time', 'price'], index_col='time',
parse_dates=[0], date_parser=lambda x: datetime.datetime.strptime(x[:-6], time_format))
bpi = data.resample('w', how='ohlc')
bpi.index.name = 'time'
bpi = pd.DataFrame(bpi['price']['close']).loc['2013':]
bpi.head()
trend_bpi = pd.merge(weekly_score, bpi, how='right', left_index=True, right_index=True)
trend_bpi.columns = ['sentiment', 'close_price']
trend_bpi.head()
Explanation: read bitcoin price data
End of explanation
trend_bpi.plot(secondary_y='close_price')
trend_bpi.corr()
Explanation: add news volume data
End of explanation
time_format = "%Y-%m-%dT%H:%M:%SZ"
alchemy_data = pd.read_csv("../data/alchemy_nyt_bitcoin.csv"
, index_col='time',
parse_dates=[0], date_parser=lambda x: datetime.datetime.strptime(x, time_format))
alchemy_data.head()
alchemy_data.alchemy_score.plot(kind='hist')
alchemy_data.describe()
weekly_alchemy = alchemy_data.resample('w', how='mean').loc['2013':].fillna(0.0)
weekly_alchemy.head()
weekly_alchemy.plot(kind='hist')
weekly_alchemy.describe()
alchemy_bpi = pd.merge(weekly_alchemy, bpi, how='right', left_index=True, right_index=True)
alchemy_bpi.columns = ['sentiment', 'close_price']
alchemy_bpi.head()
alchemy_bpi.plot(secondary_y='close_price')
merged_data = pd.merge(alchemy_bpi, weekly_score, how='right', left_index=True, right_index=True)
merged_data.head()
merged_data.plot(secondary_y='close_price')
merged_data.corr()
Explanation: AlchemyAPI sentiment score
End of explanation
daily_alchemy = alchemy_data.resample('d', how='mean').loc['2013':].fillna(0.0)
daily_alchemy.head()
daily_price = data.resample('d', how='ohlc')
daily_price.index.name = 'time'
daily_price = pd.DataFrame(daily_price['price']['close']).loc['2013':]
daily_price.head()
daily_data = pd.merge(daily_price, daily_alchemy, how='right', left_index=True, right_index=True)
daily_data.head()
daily_data.plot(secondary_y='close')
Explanation: Daily score analysis
Previously we only consider average weekly score. As news spread pretty fast, it is possible that its effect is occurring in shorter time. Therefore we try to plot daily score data.
End of explanation
alchemy_bpi['avg_sentiment'] = pd.rolling_mean(alchemy_bpi.sentiment, 1)
alchemy_bpi.head()
alchemy_bpi['avg_shifted'] = alchemy_bpi['avg_sentiment'].shift(1)
alchemy_bpi.head()
alchemy_bpi['order']= 'NA'
alchemy_bpi['diff'] = alchemy_bpi.sentiment - alchemy_bpi.avg_shifted
alchemy_bpi.head()
## SII_diff >= diff => search interest rises this week => price rises next week
alchemy_bpi.loc[alchemy_bpi['diff'] > 0,'order'] = False
## SII_diff < diff => search interest falls this week => price falls next week
alchemy_bpi.loc[alchemy_bpi['diff'] < 0,'order'] = True
alchemy_bpi.head()
alchemy_bpi['trend'] = alchemy_bpi.close_price > alchemy_bpi.close_price.shift(1)
alchemy_bpi.head()
total_predict = alchemy_bpi[alchemy_bpi.order!='NA'].order.count()
total_correct = alchemy_bpi[alchemy_bpi.order==alchemy_bpi.trend].order.count()
print "TP+TN: %f (%d/%d)" % (total_correct/float(total_predict), total_correct, total_predict)
alchemy_bpi.corr()
Explanation: Prediction
Weekly prediction first
End of explanation
daily_data = pd.merge(daily_price, daily_alchemy, how='right', left_index=True, right_index=True)
daily_data['avg_sentiment'] = pd.rolling_mean(daily_data.alchemy_score, 1)
daily_data.head()
daily_data['avg_shifted'] = daily_data['avg_sentiment'].shift(3)
daily_data.head()
daily_data['order']= 'NA'
daily_data['diff'] = daily_data.alchemy_score - daily_data.avg_shifted
daily_data.head()
## SII_diff >= diff => search interest rises this week => price rises next week
daily_data.loc[daily_data['diff'] > 0,'order'] = True
## SII_diff < diff => search interest falls this week => price falls next week
daily_data.loc[daily_data['diff'] < 0,'order'] = False
daily_data.head()
daily_data['trend'] = daily_data.close > daily_data.close.shift(1)
daily_data.head()
total_predict = daily_data[daily_data.order!='NA'].order.count()
total_correct = daily_data[daily_data.order==daily_data.trend].order.count()
print "TP+TN: %f (%d/%d)" % (total_correct/float(total_predict), total_correct, total_predict)
Explanation: Daily prediction
End of explanation |
7,483 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Twitter Bots
A workshop by Dillon Niederhut and Juan Shishido.
Interacting with <a href="https
Step1: What you see
Step2: What you get
Step3: You have access to more than just the text.
JSON
JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript).
Sure. Think of it like Python's dict type. Keys and values, collectively referred to as items, are separated by a colon. Multiple items are separated by commas. Keys must be immutable and unique to a particular dict. Values can be of any type, including list or even another dict. Dictionaries are always surrounded by braces, {}.
In JSON, it's common practice to have nested or hierarchical dictionaries. For example, some Reddit endpoints return JSON objects that are six dictionaries deep.
So, how can you access data within a Python dict? You first need the keys. To get the keys, you must look at the data or use the .keys() method, which returns a list of the key names in an arbitrary order.
Step4: How about the values? Use the dictionary name along with the key in square brackets. We used this above to access the tweet's text. If you're interested in knowing when the tweet was created, use the following.
Step5: Note
Step6: It's a dictionary. To access any of those values, use the appropriate key.
Step7: Of course, there are no hashtags associated with this tweet, so it's just an empty list.
Step8: Authentication
Before you proceed, you'll need four pieces of information.
consumer_key
consumer_secret
access_token_key
access_token_secret
While signed in to your Twitter account, go to
Step9: We've created a Twitter account for this talk. Feel free to use the following keys and access tokens to familiarize yourself with the API. But, be aware that Twitter imposes rate limits, and that these rate limits are different for different kinds of API interactions.
Search will be rate limited at 180 queries per 15 minute window for the time being, but we may adjust that over time.
- Twitter
Search
Notice that the end point is the same as in the URL example, search/tweets.
Query
Step10: The API supports what it calls query operators, which modify the search behavior. For example, if you want to search for tweets where a particular user is mentioned, include the at-sign, @, followed by the username. To search for tweets sent to a particular user, use to
Step11: User
You can also search user timelines. Notice the change in the end point and parameter values.
Step12: Location
Step13: Language
Step14: Streaming
Step15: Posting
The other half of the game is posting.
Step16: Saving Data
Now that you know how to search for tweets, how about we save them?
Step17: Note
Step18: But you are a human that needs to eat, sleep, and be social with other humans. Luckily, most UNIX based systems have a time-based daemon called cron that will run scripts like this for you. The way that cron works is it reads in files where each line has a time followed by a job (these are called cronjobs). They looks like this
Step19: If you are using a mac (especially Mavericks or newer), Apple prefers that you use their init library, called launchd. launchd is a bit more complicated, and requires that you create an xml document that will be read by Apple's init service | Python Code:
import json
with open('data/first_tweet.json','r') as f:
a_tweet = json.loads(f.read())
Explanation: Twitter Bots
A workshop by Dillon Niederhut and Juan Shishido.
Interacting with <a href="https://twitter.com/tob_pohskrow" target="_blank">tob_pohskrow</a>.
Bots
The W's: What, why, and probably even how.
What is a bot?
A bot is a program that runs user defined tasks in an automated way.
Why would you want a bot?
For fun! For laughs. For productivity.
What can you do with a bot?
You can test code. You can use it to collect data. On Twitter, you can use a bot to post automated status updates. You can even use a bot can alert you when certain events happen (inside or outside of Twitter).
At the D-Lab, we pull training/workshop information from our calendar, generate a tweet, and post it to the @DLabAtBerkeley account. We're trying to add more functionality, such as including instructor usernames in the tweets or processing the descriptions and titles to come up with a short, descriptive summary.
A team of researchers led by Jacob Eisenstein used a bot to collect 107 million tweets, which were then used ot track the diffusion of linguistic variants across the United States.
There are lots of people doing interesting things with bots on Twitter. For inspiration, see: http://qz.com/279139/the-17-best-bots-on-twitter/.
Both of the world's most famous vocab-limited characters have Twitter accounts that reply with their catchphrases to anyone who mentions their name.
Hodor
Groot
How can you do it?
Read on.
APIs
API is shorthand for Application Programming Interface, which is in turn computer-ese for a middleman.
Think about it this way. You have a bunch of things on your computer that you want other people to be able to look at. Some of them are static documents, some of them call programs in real time, and some of them are programs themselves.
Solution 1
You publish login credentials on the internet, and let anyone log into your computer
Problems:
People will need to know how each document and program works to be able to access their data
You don't want the world looking at your browser history
Solution 2
You paste everything into HTML and publish it on the internet
Problems:
This can be information overload
Making things dynamic can be tricky
Solution 3
You create a set of methods to act as an intermediary between the people you want to help and the things you want them to have access to.
Why this is the best solution:
People only access what you want them to have, in the way that you want them to have it
People use one language to get the things they want
Why this is still not Panglossian:
You will have to explain to people how to use your middleman
What is Twitter?
Twitter is visible
Currently 8th ranked website worldwide, 7th in the US
288 million users per month
500 million tweets per day
Twitter is democratic
80% of users are on mobile devices
Support for 33 languages
American Twitter users are disproprtionately from underrepresented communities
Fun Fact: the third most-searched for term leading to Twitter, after 'Twitter' and 'CNN' is the name of a porn actress
Twitter is information
User histories
User (and tweet) location
User language
Tweet popularity
Tweet spread
Conversation chains
Twitter is antidemocratic
Mexico's government has been accused of using Twitter for false flag operations
GCHQ has a software library purportedly designed to modulate public opinion
Someone here used a Twitter bot to occupy all of State Bird Provision's table reservations
Twitter is opaque
Twitter's API does not return all tweets that match your search criteria
The sampling method is not published, and can change without notice
Location information is not necessarily provided by GPS
Twitter is spam
Two years ago, approximately 20 million Twitter accounts were advertising bots
Appoximately 1/3 of any accounts followers are not humans
Of the top ten accounts (by followers), eight are celebrities (the other two are YouTube and the current President)
A Tweet
Simple, right? 140 characters. Done.
Let's find out
End of explanation
print a_tweet['text']
Explanation: What you see
End of explanation
from pprint import pprint
pprint(a_tweet)
Explanation: What you get
End of explanation
a_tweet.keys()
Explanation: You have access to more than just the text.
JSON
JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript).
Sure. Think of it like Python's dict type. Keys and values, collectively referred to as items, are separated by a colon. Multiple items are separated by commas. Keys must be immutable and unique to a particular dict. Values can be of any type, including list or even another dict. Dictionaries are always surrounded by braces, {}.
In JSON, it's common practice to have nested or hierarchical dictionaries. For example, some Reddit endpoints return JSON objects that are six dictionaries deep.
So, how can you access data within a Python dict? You first need the keys. To get the keys, you must look at the data or use the .keys() method, which returns a list of the key names in an arbitrary order.
End of explanation
a_tweet['user'].keys()
a_tweet['created_at']
Explanation: How about the values? Use the dictionary name along with the key in square brackets. We used this above to access the tweet's text. If you're interested in knowing when the tweet was created, use the following.
End of explanation
a_tweet['entities']
Explanation: Note: This is given in UTC. The offset is shown by the +0000.
The thing about JSON data or Python dictionaries is that they can have a nested structure. What if we want access to the values associated with the entities key?
End of explanation
a_tweet['entities']['hashtags']
Explanation: It's a dictionary. To access any of those values, use the appropriate key.
End of explanation
type(a_tweet)
Explanation: Of course, there are no hashtags associated with this tweet, so it's just an empty list.
End of explanation
from TwitterAPI import TwitterAPI
consumer_key = '9cQ7SNtWsmTTfta8Gv5y8svWD'
consumer_secret = 'kjJllUPEJefFQ4Dfr6dBXDETiQaVWFXTt0zLSNMy8tY8F8IpqK'
access_token_key = '3129088320-dIfoDZOt5cIKVCFnJpS0krt3oCYPB13rk5ITavI'
access_token_secret = 'H41REM344zgKCvJenCGGsF1JbFSK8I1r1WvFrc8Fs74jg'
api = TwitterAPI(consumer_key, consumer_secret, access_token_key, access_token_secret)
Explanation: Authentication
Before you proceed, you'll need four pieces of information.
consumer_key
consumer_secret
access_token_key
access_token_secret
While signed in to your Twitter account, go to: https://apps.twitter.com/. Follow the prompts to generate your keys and access tokens. You'll need to have a phone number associated with your account.
Accessing the API
So, how do we actually access the Twitter API? Well, there are several ways. To search for something, you can use the search URL, which looks like: https://api.twitter.com/1.1/search/tweets.json?q=%40twitterapi. The q is the query parameter. You can replace it with anything you want. However, if you follow this link, you'll get an error because your request was not authenticated.
For more information on the REST APIs, end points, and terms, check out: https://dev.twitter.com/rest/public. For the Streaming APIs: https://dev.twitter.com/streaming/overview.
Instead, we'll use Jonas Geduldig's TwitterAPI module: https://github.com/geduldig/TwitterAPI. The nice thing about modules such as this one--yes, there are others--is that it handles the OAuth. TwitterAPI supports both the REST and Streaming APIs.
TwitterAPI
To authenticate, run the following code.
End of explanation
r = api.request('search/tweets', {'q':'technology'})
for item in r:
print item
Explanation: We've created a Twitter account for this talk. Feel free to use the following keys and access tokens to familiarize yourself with the API. But, be aware that Twitter imposes rate limits, and that these rate limits are different for different kinds of API interactions.
Search will be rate limited at 180 queries per 15 minute window for the time being, but we may adjust that over time.
- Twitter
Search
Notice that the end point is the same as in the URL example, search/tweets.
Query
End of explanation
end_point = 'search/tweets'
parameters = {
'q':'from:Engadget',
'count':1
}
r = api.request(end_point, parameters)
for item in r:
print item['text'] + '\n'
Explanation: The API supports what it calls query operators, which modify the search behavior. For example, if you want to search for tweets where a particular user is mentioned, include the at-sign, @, followed by the username. To search for tweets sent to a particular user, use to:username. For tweets from a particular user, from:username. For hashtags, use #hashtag.
For a complete set of options: https://dev.twitter.com/rest/public/search.
To make things clearer, let's use variables.
End of explanation
end_point = 'statuses/user_timeline'
parameters = {
'screen_name':'UCBerkeley',
'count':5
}
r = api.request(end_point, parameters)
for item in r:
print item['text']
Explanation: User
You can also search user timelines. Notice the change in the end point and parameter values.
End of explanation
end_point = 'search/tweets'
parameters = {
'q':'technology',
'geocode':'37.871667,-122.272778,5km', # UC Berkeley
'count':1
}
r = api.request(end_point, parameters)
for item in r:
print item['text']
Explanation: Location
End of explanation
end_point = 'search/tweets'
parameters = {
'q':'*',
'lang':'fr',
'count':1
}
r = api.request(end_point, parameters)
for item in r:
print item['text']
Explanation: Language
End of explanation
end_point = 'statuses/filter'
parameters = {
'q':'coding',
'locations': '-180,-90,180,90'
}
r = api.request(end_point, parameters)
tweets = r.get_iterator()
for i in range(15):
t = tweets.next()
print t['place']['full_name'] + ', ' + t['place']['country'] + ': ' + t['text'], '\n'
Explanation: Streaming
End of explanation
end_point = 'statuses/update'
parameters = {
'status':'.IPA rettiwT eht tuoba nraeL'
}
r = api.request(end_point, parameters)
print r.status_code
Explanation: Posting
The other half of the game is posting.
End of explanation
print r.text
for item in r:
filename = item['id_str'] + '.json'
with open(filename,'w') as f:
json.dump(item,f)
Explanation: Saving Data
Now that you know how to search for tweets, how about we save them?
End of explanation
import time
r = api.request('search/tweets', {'q':'accepted berkeley'})
for item in r:
username = item['user']['screen_name']
parameters = {'status':'HOORAY! @' + username}
r = api.request('statuses/update', parameters)
time.sleep(5)
print r.status_code
Explanation: Note: if you are doing a lot of these, it will be faster and easier to use a non-relational database like MongoDB
Scheduling
The real beauty of bots is that they are designed to work without interaction or oversight. Imagine a situation where you want to write a Twitter bot that replies 'HOORAY!' every time someone posts on Twitter that they were accepted to Cal. One option is to write a python script like this and call it by hand every minute.
End of explanation
# That thing after crontab is a lowercase L even though it looks like a 1
# This will execute directly through your shell, so use at your own risk
# Make sure you replace the <> with the file path
!crontab -l | { cat; echo "0 * * * * python <absolute path to>twitter_bot.py"; } | crontab -
Explanation: But you are a human that needs to eat, sleep, and be social with other humans. Luckily, most UNIX based systems have a time-based daemon called cron that will run scripts like this for you. The way that cron works is it reads in files where each line has a time followed by a job (these are called cronjobs). They looks like this:
0 * * * * python twitter_bot.py
This is telling cron to execute python twitter_bot.py at 0 seconds, every minute, every hour, every day, every year, until the end of time.
End of explanation
from TwitterAPI import TwitterAPI
import time
consumer_key = '9cQ7SNtWsmTTfta8Gv5y8svWD'
consumer_secret = 'kjJllUPEJefFQ4Dfr6dBXDETiQaVWFXTt0zLSNMy8tY8F8IpqK'
access_token_key = '3129088320-dIfoDZOt5cIKVCFnJpS0krt3oCYPB13rk5ITavI'
access_token_secret = 'H41REM344zgKCvJenCGGsF1JbFSK8I1r1WvFrc8Fs74jg'
api = TwitterAPI(consumer_key, consumer_secret, access_token_key, access_token_secret)
request_parameters = {} #Enter your search parameters here
def main():
while True: #You may want to set a condition here
r = api.request('search/tweets', request_parameters)
if r.status_code == 200:
for item in r:
if True: #You may want to set a condition here
post_parameters = {} #Enter your post parameters here
p = api.request('statuses/update', post_parameters)
print p.status
time.sleep(15)
if r.status_code == 420: #If Twitter is throttling you
break
if r.status_code == 429: #If you are exceeding the rate limit
time.sleep(60)
if __name__ == 'main':
main()
Explanation: If you are using a mac (especially Mavericks or newer), Apple prefers that you use their init library, called launchd. launchd is a bit more complicated, and requires that you create an xml document that will be read by Apple's init service:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>twitter.bot</string>
<key>ProgramArguments</key>
<array>
<string>python</string>
<string>twitter_bot.py</string>
</array>
<key>StartCalendarInterval</key>
<dict>
<key>Minute</key>
<integer>00</integer>
</dict>
</dict>
</plist>
```
We won't be messing with launchd for this workshop.
Now it is time for you to make your own twitter bot!
To get you started, here is a template in python. You should modify the search parameters and post parameters to get the bot to act the way you want.
You might find it easier to copy this out of the notebook into a python script and run it from your terminal.
End of explanation |
7,484 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Showing some of the dstoolbox features
The purpose of this notebook is to demonstrate some of the features of dstoolbox using a toy dataset that contains different categories of features.
Imports
Step1: Generate a toy dataset
Here we create a fictitious dataset of pupils with the goal of predicting their grades based on their name, age, city of birth, and body height. The dataset contains a mixture of numerical and non-numerical features. Although holding such a dataset is not a problem for a pandas DataFrames, it is difficult to integrate it seamlessly with scikit-learn.
Step2: Working with dstoolbox
This part shows how we can get this dataset to work with scikit-learn thanks to dstoolbox features.
Imports
Step3: Custom functions
Step4: Define the feature transformation step
Here we will define a special FeatureUnion that takes pandas DataFrames as input and returns pandas DataFrames as output. Within this DataFrameFeatureUnion, we will make use of several other dstoolbox features that will facilitate the integration of DataFrames with scikit-learn.
Step5: Look at the result
We promised that we would get back a pandas DataFrame, here it is
Step6: As we can see, the column names are exactly as we expected.
Full regression pipeline
We want to use those features to train an sklearn RandomForestRegressor. For good measure, we also add polynomial features to the mix and put all the ingredients into a Pipeline
Step7: As you probably noticed, we did not use a simple sklearn Pipeline. Instead, we use a dstoolbox TimedPipeline. This special pipeline works just as an sklearn Pipeline, except that it prints additional information about the time it took to step through the pipeline steps, and what shape the outcoming data has.
Step8: We immediately see that the generation of the features is the slowest step, followed by the model fit. Additionally, we see that we that the feature generation step produces 5 features, followed by 21 features after applying the polynomial fatures.
This kind of information would be tricky to get with sklearn features alone.
By the way, the printed outputs can be evaled as dicts or parsed as json's, which is useful for logging.
Step9: We can now generate a test dataset to validate our model. As the targets are completely random, we will find that our model totally overfits
Step10: Conclusion
The features from dstoolbox allowed us to integrate all processing steps into an sklearn Pipeline. Without them, we would probably have had to do a separate processing step that ingests the DataFrame's different columns and returns a numpy array, which we would pass to the proper sklearn Pipeline in a second step.
The advantage of having all steps in one pipeline is that it is easier to handle and provides us with all the niceties that come with sklearn Pipeline's, e.g. being able to pass them to ensemble models (e.g. BaggingRegressor), grid search over all parameters, changing any parameter with set_params, saving the whole pipeline in one file with pickle, etc.
Bonus
Step11: For this, we first transform the pipeline to a pydotplus graph, then visualize that graph. Btw., this also works with normal sklearn Pipelines and FeatureUnions.
Note that this requires additional packages to be installed, namely pydotplus and graphviz. Those can be installed via pip. | Python Code:
from functools import partial
import operator
import random
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import FunctionTransformer
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import Imputer
from sklearn.pipeline import Pipeline
Explanation: Showing some of the dstoolbox features
The purpose of this notebook is to demonstrate some of the features of dstoolbox using a toy dataset that contains different categories of features.
Imports
End of explanation
np.random.seed(1)
NAMES = ['Alice', 'Bob', 'Charlie', 'Dora', 'Eve', 'Fenchurch', 'Guido']
CITIES = ['London', 'Paris', 'New York', 'Berlin', 'Warsaw', 'Vancouver', 'Amsterdam', 'Rome']
AGES = [6, 7, 8, 9, 10, np.nan]
def _yield_names(n):
for _ in range(n):
yield random.choice(NAMES)
def _yield_age(n):
for _ in range(n):
yield random.choice(AGES)
def _yield_city(n):
for _ in range(n):
yield random.choice(CITIES)
def _yield_height(n):
for _ in range(n):
yield 140 + 20 * random.random()
def make_data(n):
df = pd.DataFrame({
'name': list(_yield_names(n)),
'age': list(_yield_age(n)),
'city': list(_yield_city(n)),
'height': list(_yield_height(n)),
})
target = np.array([random.randint(0, 100) for _ in range(n)])
return df, target
df, y = make_data(100)
df.head()
df.shape
y[:10]
Explanation: Generate a toy dataset
Here we create a fictitious dataset of pupils with the goal of predicting their grades based on their name, age, city of birth, and body height. The dataset contains a mixture of numerical and non-numerical features. Although holding such a dataset is not a problem for a pandas DataFrames, it is difficult to integrate it seamlessly with scikit-learn.
End of explanation
from dstoolbox.pipeline import TimedPipeline
from dstoolbox.pipeline import DataFrameFeatureUnion
from dstoolbox.pipeline import DictFeatureUnion
from dstoolbox.transformers import ItemSelector
from dstoolbox.transformers import ParallelFunctionTransformer
from dstoolbox.transformers import ToDataFrame
from dstoolbox.transformers import XLabelEncoder
Explanation: Working with dstoolbox
This part shows how we can get this dataset to work with scikit-learn thanks to dstoolbox features.
Imports
End of explanation
def word_count_e(words):
return np.expand_dims(np.array([word.count('e') for word in words]), axis=1)
def word_len(words):
return np.expand_dims(np.array([len(word) for word in words]), axis=1)
Explanation: Custom functions
End of explanation
# Use dstoolbox's DataFrameFeatureUnion, which will return a DataFrame if all intermediate
# transformation steps return either a pandas DataFrame or a pandas Series.
feature_union = DataFrameFeatureUnion([
# Now we define our feature set.
# A boolean feature, namely, whether age is below 9 years.
('age_less_than_9', Pipeline([
# ItemSelector allows us to select a specific column from the DataFrame.
# The result would 1d but sklearn transformers usually expects features to be 2d.
# Therefore, we set the force_2d argument to True.
('select_age', ItemSelector('age', force_2d=True)),
# Let's impute the NaN values.
('impute_nan', Imputer(strategy='most_frequent')),
# This FunctionTransformer will return True if age is less than 9.
('less_than_9', FunctionTransformer(partial(operator.lt, 9))),
# Finally, transform the data to a DataFrame with the name 'age_less_than_9'.
('to_df', ToDataFrame(columns=['age_less_than_9'])),
])),
# We also have city names; we want to encode those, treating them as categorical.
('city_label_encoded', Pipeline([
# We use ItemSelector again to access the city values. As it returns a Series,
# but we want a 2d array, we set force_2d to True.
('select_city', ItemSelector('city', force_2d=True)),
# dstoolbox's XLabelEncoder is similar to sklearn's LabelEncoder but works on feature data.
('encode', XLabelEncoder()),
# Again, let's transform the resuling ndarray to a pandas DataFrame.
('to_df', ToDataFrame(columns=['city_label_encoded'])),
])),
# The height feature is fine, let's just take it as it is.
# Since the returned value is already a Series object, no need to transform it further.
('raw_height', ItemSelector('height')),
# Finally, we would like to derive 2 features based on the children's names.
# First is the length of the name, second the number of the letter 'e' in the name.
('name_features', Pipeline([
('select_name', ItemSelector('name')),
('name_features', DictFeatureUnion([
# Since determining the length and number of e's is an embarassingly parallel
# task, we use dstoolbox's ParallelFunctionTransformer instead of sklearn's
# FunctionTransformer.
# Notice that we did not use lambdas here, since those cannot be pickled.
('name_length', ParallelFunctionTransformer(word_len, validate=False, n_jobs=2)),
('name_count_of_e', ParallelFunctionTransformer(word_count_e, validate=False, n_jobs=2)),
])),
# Again, transform the output into a DataFrame, this time with 2 columns.
# Since the incoming data from `DictFeatureUnion` is a dict, the column names
# will be inferred automatically from the dict's keys, i.e.
# `name_length` and `name_count_of_e`.
('to_df', ToDataFrame()),
])),
])
Explanation: Define the feature transformation step
Here we will define a special FeatureUnion that takes pandas DataFrames as input and returns pandas DataFrames as output. Within this DataFrameFeatureUnion, we will make use of several other dstoolbox features that will facilitate the integration of DataFrames with scikit-learn.
End of explanation
df_transformed = feature_union.fit_transform(df)
df_transformed.head()
Explanation: Look at the result
We promised that we would get back a pandas DataFrame, here it is:
End of explanation
pipeline = TimedPipeline([
('features', feature_union),
('polynomial', PolynomialFeatures()),
('random_forest', RandomForestRegressor(n_estimators=100)),
])
Explanation: As we can see, the column names are exactly as we expected.
Full regression pipeline
We want to use those features to train an sklearn RandomForestRegressor. For good measure, we also add polynomial features to the mix and put all the ingredients into a Pipeline:
End of explanation
pipeline.fit(df, y)
Explanation: As you probably noticed, we did not use a simple sklearn Pipeline. Instead, we use a dstoolbox TimedPipeline. This special pipeline works just as an sklearn Pipeline, except that it prints additional information about the time it took to step through the pipeline steps, and what shape the outcoming data has.
End of explanation
y_pred = pipeline.predict(df)
mean_squared_error(y, y_pred)
Explanation: We immediately see that the generation of the features is the slowest step, followed by the model fit. Additionally, we see that we that the feature generation step produces 5 features, followed by 21 features after applying the polynomial fatures.
This kind of information would be tricky to get with sklearn features alone.
By the way, the printed outputs can be evaled as dicts or parsed as json's, which is useful for logging.
End of explanation
df_test, y_test = make_data(100)
y_pred = pipeline.predict(df_test)
mean_squared_error(y_test, y_pred)
Explanation: We can now generate a test dataset to validate our model. As the targets are completely random, we will find that our model totally overfits:
End of explanation
from IPython.display import Image
from dstoolbox.visualization import make_graph
Explanation: Conclusion
The features from dstoolbox allowed us to integrate all processing steps into an sklearn Pipeline. Without them, we would probably have had to do a separate processing step that ingests the DataFrame's different columns and returns a numpy array, which we would pass to the proper sklearn Pipeline in a second step.
The advantage of having all steps in one pipeline is that it is easier to handle and provides us with all the niceties that come with sklearn Pipeline's, e.g. being able to pass them to ensemble models (e.g. BaggingRegressor), grid search over all parameters, changing any parameter with set_params, saving the whole pipeline in one file with pickle, etc.
Bonus: Visualizing pipelines
A final goody we want to demonstrate is a tool to visualize Pipelines and FeatureUnions with the help of dstoolbox.
End of explanation
graph = make_graph('my pipe', pipeline)
Image(graph.create_png())
Explanation: For this, we first transform the pipeline to a pydotplus graph, then visualize that graph. Btw., this also works with normal sklearn Pipelines and FeatureUnions.
Note that this requires additional packages to be installed, namely pydotplus and graphviz. Those can be installed via pip.
End of explanation |
7,485 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This tutorial will show you how to find the suitable habitat range for Bristlecone pine using GeoPySpark
This tutorial will focus on GeoPySpark functionality, but you can find more resources and tutorials about GeoNotebooks here.
Suitability analysis is a classic GIS case study that enables the combination of factors to return a desired result
This tutorial sets the premise that you are interested in two factors for locating Bristlecone pines
Step1: You will need to set up a spark context. To learn more about what that means take a look here
Step2: Retrieving an elevation .tif from AWS S3
Step3: Tile, reproject, pyramid
Step4: Imports for creating a TMS server capable of serving layers with custom colormaps
Step5: Display the tiles in an embedded Folium map
Step6: Classify the elevation such that values of interest (between 3,000 and 4,000 meters) return a value of 1.
Step7: Focal operation
Step8: Reclassify values such that values between 120 and 240 degrees (south) have a value of 1
Step9: Now add the values togehter to find the suitable range | Python Code:
import geopyspark as gps
from pyspark import SparkContext
Explanation: This tutorial will show you how to find the suitable habitat range for Bristlecone pine using GeoPySpark
This tutorial will focus on GeoPySpark functionality, but you can find more resources and tutorials about GeoNotebooks here.
Suitability analysis is a classic GIS case study that enables the combination of factors to return a desired result
This tutorial sets the premise that you are interested in two factors for locating Bristlecone pines:
- Located between 3,000 and 4,000 meters
- Located on a south facing slope
End of explanation
conf=gps.geopyspark_conf(appName="BristleConePine")
conf.set('spark.ui.enabled', True)
sc = SparkContext(conf = conf)
Explanation: You will need to set up a spark context. To learn more about what that means take a look here
End of explanation
elev_rdd = gps.geotiff.get(
layer_type='spatial',
uri='s3://geopyspark-demo/elevation/ca-elevation.tif')
Explanation: Retrieving an elevation .tif from AWS S3:
End of explanation
elev_tiled_rdd = elev_rdd.tile_to_layout(
layout=gps.GlobalLayout(),
target_crs=3857)
elev_pyramided_rdd = elev_tiled_rdd.pyramid().cache()
Explanation: Tile, reproject, pyramid:
End of explanation
from geopyspark.geotrellis.color import get_colors_from_matplotlib
elev_histo = elev_pyramided_rdd.get_histogram()
elev_colors = get_colors_from_matplotlib('viridis', 100)
elev_color_map = gps.ColorMap.from_histogram(elev_histo, elev_colors)
elev_tms = gps.TMS.build(elev_pyramided_rdd, elev_color_map)
elev_tms.bind('0.0.0.0')
Explanation: Imports for creating a TMS server capable of serving layers with custom colormaps
End of explanation
import folium
map_center = [37.75, -118.85]
zoom = 7
m = folium.Map(location=map_center, zoom_start=zoom)
folium.TileLayer(tiles="Stamen Terrain", overlay=False).add_to(m)
folium.TileLayer(tiles=elev_tms.url_pattern, attr="GeoPySpark", overlay=True).add_to(m)
m
Explanation: Display the tiles in an embedded Folium map:
End of explanation
# use: elev_reprojected_rdd
elev_reclass_pre = elev_tiled_rdd.reclassify({1000:2, 2000:2, 3000:2, 4000:1, 5000:2}, int)
elev_reclass_rdd = elev_reclass_pre.reclassify({1:1}, int)
elev_reclass_pyramid_rdd = elev_reclass_rdd.pyramid()
elev_reclass_histo = elev_reclass_pyramid_rdd.get_histogram()
#elev_reclass_color_map = ColorMap.from_histogram(sc, elev_reclass_histo, get_breaks(sc, 'Viridis', num_colors=100))
elev_reclass_color_map = gps.ColorMap.from_colors(
breaks =[1],
color_list = [0xff000080])
elev_reclass_tms = gps.TMS.build(elev_reclass_pyramid_rdd, elev_reclass_color_map)
elev_reclass_tms.bind('0.0.0.0')
m2 = folium.Map(location=map_center, zoom_start=zoom)
folium.TileLayer(tiles="Stamen Terrain", overlay=False).add_to(m2)
folium.TileLayer(tiles=elev_tms.url_pattern, attr='GeoPySpark', name="Elevation", overlay=True).add_to(m2)
folium.TileLayer(tiles=elev_reclass_tms.url_pattern, attr='GeoPySpark', name="High Elevation Areas", overlay=True).add_to(m2)
folium.LayerControl().add_to(m2)
m2
Explanation: Classify the elevation such that values of interest (between 3,000 and 4,000 meters) return a value of 1.
End of explanation
# square_neighborhood = Square(extent=1)
aspect_rdd = elev_tiled_rdd.focal(
gps.Operation.ASPECT,
gps.Neighborhood.SQUARE, 1)
aspect_pyramid_rdd = aspect_rdd.pyramid()
aspect_histo = aspect_pyramid_rdd.get_histogram()
aspect_color_map = gps.ColorMap.from_histogram(aspect_histo, get_colors_from_matplotlib('viridis', num_colors=256))
aspect_tms = gps.TMS.build(aspect_pyramid_rdd, aspect_color_map)
aspect_tms.bind('0.0.0.0')
m3 = folium.Map(tiles='Stamen Terrain', location=map_center, zoom_start=zoom)
folium.TileLayer(tiles=aspect_tms.url_pattern, attr='GeoPySpark', name="High Elevation Areas", overlay=True).add_to(m3)
m3
aspect_tms.unbind()
Explanation: Focal operation: aspect. To find south facing slopes
End of explanation
aspect_reclass_pre = aspect_rdd.reclassify({120:2, 240:1, 360: 2}, int)
aspect_reclass = aspect_reclass_pre.reclassify({1:1}, int)
aspect_reclass_pyramid_rdd = aspect_reclass.pyramid()
aspect_reclass_histo = aspect_reclass_pyramid_rdd.get_histogram()
aspect_reclass_color_map = gps.ColorMap.from_histogram(aspect_reclass_histo, get_colors_from_matplotlib('viridis', num_colors=256))
aspect_reclass_tms = gps.TMS.build(aspect_reclass_pyramid_rdd, aspect_reclass_color_map)
aspect_reclass_tms.bind('0.0.0.0')
m4 = folium.Map(tiles='Stamen Terrain', location=map_center, zoom_start=zoom)
folium.TileLayer(tiles=aspect_reclass_tms.url_pattern, attr='GeoPySpark', name="High Elevation Areas", overlay=True).add_to(m4)
m4
aspect_reclass_tms.unbind()
Explanation: Reclassify values such that values between 120 and 240 degrees (south) have a value of 1
End of explanation
added = elev_reclass_pyramid_rdd + aspect_reclass_pyramid_rdd
added_histo = added.get_histogram()
added_color_map = gps.ColorMap.from_histogram(added_histo, get_colors_from_matplotlib('viridis', num_colors=256))
added_tms = gps.TMS.build(added, added_color_map)
added_tms.bind('0.0.0.0')
m5 = folium.Map(tiles='Stamen Terrain', location=map_center, zoom_start=zoom)
folium.TileLayer(tiles=added_tms.url_pattern, attr='GeoPySpark', name="High Elevation Areas", overlay=True).add_to(m5)
m5
import matplotlib.pyplot as plt
%matplotlib inline
v = elev_tiled_rdd.lookup(342,787)
plt.imshow(v[0].cells[0])
Explanation: Now add the values togehter to find the suitable range:
End of explanation |
7,486 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Continuous training with TFX and Google Cloud AI Platform
Learning Objectives
Use the TFX CLI to build a TFX pipeline.
Deploy a TFX pipeline version without tuning to a hosted AI Platform Pipelines instance.
Create and monitor a TFX pipeline run using the TFX CLI.
Deploy a new TFX pipeline version with tuning enabled to a hosted AI Platform Pipelines instance.
Create and monitor another TFX pipeline run directly in the KFP UI.
In this lab, you use utilize the following tools and services to deploy and run a TFX pipeline on Google Cloud that automates the development and deployment of a TensorFlow 2.3 WideDeep Classifer to predict forest cover from cartographic data
Step1: Validate lab package version installation
Step2: Note
Step3: Note
Step4: The config.py module configures the default values for the environment specific settings and the default values for the pipeline runtime parameters.
The default values can be overwritten at compile time by providing the updated values in a set of environment variables. You will set custom environment variables later on this lab.
The pipeline.py module contains the TFX DSL defining the workflow implemented by the pipeline.
The preprocessing.py module implements the data preprocessing logic the Transform component.
The model.py module implements the training, tuning, and model building logic for the Trainer and Tuner components.
The runner.py module configures and executes KubeflowDagRunner. At compile time, the KubeflowDagRunner.run() method converts the TFX DSL into the pipeline package in the argo format for execution on your hosted AI Platform Pipelines instance.
The features.py module contains feature definitions common across preprocessing.py and model.py.
Exercise
Step5: CUSTOM_SERVICE_ACCOUNT - In the gcp console Click on the Navigation Menu. Navigate to IAM & Admin, then to Service Accounts and use the service account starting with prefix - 'tfx-tuner-caip-service-account'. This enables CloudTuner and the Google Cloud AI Platform extensions Tuner component to work together and allows for distributed and parallel tuning backed by AI Platform Vizier's hyperparameter search algorithm. Please see the lab setup README for setup instructions.
ENDPOINT - set the ENDPOINT constant to the endpoint to your AI Platform Pipelines instance. The endpoint to the AI Platform Pipelines instance can be found on the AI Platform Pipelines page in the Google Cloud Console. Open the SETTINGS for your instance and use the value of the host variable in the Connect to this Kubeflow Pipelines instance from a Python client via Kubeflow Pipelines SKD section of the SETTINGS window. The format is '...pipelines.googleusercontent.com'.
Step6: Set the compile time settings to first create a pipeline version without hyperparameter tuning
Default pipeline runtime environment values are configured in the pipeline folder config.py. You will set their values directly below
Step7: Compile your pipeline code
You can build and upload the pipeline to the AI Platform Pipelines instance in one step, using the tfx pipeline create command. The tfx pipeline create goes through the following steps
Step8: Note
Step9: Hint
Step10: To view the status of existing pipeline runs
Step11: To retrieve the status of a given run
Step12: Important
A full pipeline run without tuning enabled will take about 40 minutes to complete. You can view the run's progress using the TFX CLI commands above or in the
Exercise
Step13: Compile your pipeline code
Step14: Deploy your pipeline container to AI Platform Pipelines with the TFX CLI | Python Code:
import yaml
# Set `PATH` to include the directory containing TFX CLI and skaffold.
PATH=%env PATH
%env PATH=/home/jupyter/.local/bin:{PATH}
Explanation: Continuous training with TFX and Google Cloud AI Platform
Learning Objectives
Use the TFX CLI to build a TFX pipeline.
Deploy a TFX pipeline version without tuning to a hosted AI Platform Pipelines instance.
Create and monitor a TFX pipeline run using the TFX CLI.
Deploy a new TFX pipeline version with tuning enabled to a hosted AI Platform Pipelines instance.
Create and monitor another TFX pipeline run directly in the KFP UI.
In this lab, you use utilize the following tools and services to deploy and run a TFX pipeline on Google Cloud that automates the development and deployment of a TensorFlow 2.3 WideDeep Classifer to predict forest cover from cartographic data:
The TFX CLI utility to build and deploy a TFX pipeline.
A hosted AI Platform Pipeline instance (Kubeflow Pipelines) for TFX pipeline orchestration.
Dataflow jobs for scalable, distributed data processing for TFX components.
A AI Platform Training job for model training and flock management for parallel tuning trials.
AI Platform Prediction as a model server destination for blessed pipeline model versions.
CloudTuner and AI Platform Vizier for advanced model hyperparameter tuning using the Vizier algorithm.
You will then create and monitor pipeline runs using the TFX CLI as well as the KFP UI.
Setup
Update lab environment PATH to include TFX CLI and skaffold
End of explanation
!python -c "import tfx; print('TFX version: {}'.format(tfx.__version__))"
!python -c "import kfp; print('KFP version: {}'.format(kfp.__version__))"
Explanation: Validate lab package version installation
End of explanation
%pip install --upgrade --user tfx==0.25.0
%pip install --upgrade --user kfp==1.0.4
Explanation: Note: this lab was built and tested with the following package versions:
TFX version: 0.25.0
KFP version: 1.0.4
(Optional) If running the above command results in different package versions or you receive an import error, upgrade to the correct versions by running the cell below:
End of explanation
%cd pipeline
!ls -la
Explanation: Note: you may need to restart the kernel to pick up the correct package versions.
Validate creation of AI Platform Pipelines cluster
Navigate to AI Platform Pipelines page in the Google Cloud Console.
Note you may have already deployed an AI Pipelines instance during the Setup for the lab series. If so, you can proceed using that instance. If not:
1. Create or select an existing Kubernetes cluster (GKE) and deploy AI Platform. Make sure to select "Allow access to the following Cloud APIs https://www.googleapis.com/auth/cloud-platform" to allow for programmatic access to your pipeline by the Kubeflow SDK for the rest of the lab. Also, provide an App instance name such as "tfx" or "mlops".
Validate the deployment of your AI Platform Pipelines instance in the console before proceeding.
Review: example TFX pipeline design pattern for Google Cloud
The pipeline source code can be found in the pipeline folder.
End of explanation
# Use the following command to identify the GCS bucket for metadata and pipeline storage.
!gsutil ls
Explanation: The config.py module configures the default values for the environment specific settings and the default values for the pipeline runtime parameters.
The default values can be overwritten at compile time by providing the updated values in a set of environment variables. You will set custom environment variables later on this lab.
The pipeline.py module contains the TFX DSL defining the workflow implemented by the pipeline.
The preprocessing.py module implements the data preprocessing logic the Transform component.
The model.py module implements the training, tuning, and model building logic for the Trainer and Tuner components.
The runner.py module configures and executes KubeflowDagRunner. At compile time, the KubeflowDagRunner.run() method converts the TFX DSL into the pipeline package in the argo format for execution on your hosted AI Platform Pipelines instance.
The features.py module contains feature definitions common across preprocessing.py and model.py.
Exercise: build your pipeline with the TFX CLI
You will use TFX CLI to compile and deploy the pipeline. As explained in the previous section, the environment specific settings can be provided through a set of environment variables and embedded into the pipeline package at compile time.
Configure your environment resource settings
Update the below constants with the settings reflecting your lab environment.
GCP_REGION - the compute region for AI Platform Training, Vizier, and Prediction.
ARTIFACT_STORE - An existing GCS bucket. You can use any bucket or use the GCS bucket created during installation of AI Platform Pipelines. The default bucket name will contain the kubeflowpipelines- prefix.
End of explanation
#TODO: Set your environment resource settings here for GCP_REGION, ARTIFACT_STORE_URI, ENDPOINT, and CUSTOM_SERVICE_ACCOUNT.
GCP_REGION = 'us-central1'
ARTIFACT_STORE_URI = 'gs://dougkelly-sandbox-kubeflowpipelines-default' #Change
ENDPOINT = '6f857f6a72ef2a99-dot-us-central2.pipelines.googleusercontent.com' #Change
CUSTOM_SERVICE_ACCOUNT = 'tfx-tuner-caip-service-account@dougkelly-sandbox.iam.gserviceaccount.com' #Change
PROJECT_ID = !(gcloud config get-value core/project)
PROJECT_ID = PROJECT_ID[0]
# Set your resource settings as environment variables. These override the default values in pipeline/config.py.
%env GCP_REGION={GCP_REGION}
%env ARTIFACT_STORE_URI={ARTIFACT_STORE_URI}
%env CUSTOM_SERVICE_ACCOUNT={CUSTOM_SERVICE_ACCOUNT}
%env PROJECT_ID={PROJECT_ID}
Explanation: CUSTOM_SERVICE_ACCOUNT - In the gcp console Click on the Navigation Menu. Navigate to IAM & Admin, then to Service Accounts and use the service account starting with prefix - 'tfx-tuner-caip-service-account'. This enables CloudTuner and the Google Cloud AI Platform extensions Tuner component to work together and allows for distributed and parallel tuning backed by AI Platform Vizier's hyperparameter search algorithm. Please see the lab setup README for setup instructions.
ENDPOINT - set the ENDPOINT constant to the endpoint to your AI Platform Pipelines instance. The endpoint to the AI Platform Pipelines instance can be found on the AI Platform Pipelines page in the Google Cloud Console. Open the SETTINGS for your instance and use the value of the host variable in the Connect to this Kubeflow Pipelines instance from a Python client via Kubeflow Pipelines SKD section of the SETTINGS window. The format is '...pipelines.googleusercontent.com'.
End of explanation
PIPELINE_NAME = 'tfx_covertype_continuous_training'
MODEL_NAME = 'tfx_covertype_classifier'
DATA_ROOT_URI = 'gs://workshop-datasets/covertype/small'
CUSTOM_TFX_IMAGE = 'gcr.io/{}/{}'.format(PROJECT_ID, PIPELINE_NAME)
RUNTIME_VERSION = '2.3'
PYTHON_VERSION = '3.7'
USE_KFP_SA=False
ENABLE_TUNING=False
%env PIPELINE_NAME={PIPELINE_NAME}
%env MODEL_NAME={MODEL_NAME}
%env DATA_ROOT_URI={DATA_ROOT_URI}
%env KUBEFLOW_TFX_IMAGE={CUSTOM_TFX_IMAGE}
%env RUNTIME_VERSION={RUNTIME_VERSION}
%env PYTHON_VERIONS={PYTHON_VERSION}
%env USE_KFP_SA={USE_KFP_SA}
%env ENABLE_TUNING={ENABLE_TUNING}
Explanation: Set the compile time settings to first create a pipeline version without hyperparameter tuning
Default pipeline runtime environment values are configured in the pipeline folder config.py. You will set their values directly below:
PIPELINE_NAME - the pipeline's globally unique name. For each pipeline update, each pipeline version uploaded to KFP will be reflected on the Pipelines tab in the Pipeline name > Version name dropdown in the format PIPELINE_NAME_datetime.now().
MODEL_NAME - the pipeline's unique model output name for AI Platform Prediction. For multiple pipeline runs, each pushed blessed model will create a new version with the format 'v{}'.format(int(time.time())).
DATA_ROOT_URI - the URI for the raw lab dataset gs://workshop-datasets/covertype/small.
CUSTOM_TFX_IMAGE - the image name of your pipeline container build by skaffold and published by Cloud Build to Cloud Container Registry in the format 'gcr.io/{}/{}'.format(PROJECT_ID, PIPELINE_NAME).
RUNTIME_VERSION - the TensorFlow runtime version. This lab was built and tested using TensorFlow 2.3.
PYTHON_VERSION - the Python runtime version. This lab was built and tested using Python 3.7.
USE_KFP_SA - The pipeline can run using a security context of the GKE default node pool's service account or the service account defined in the user-gcp-sa secret of the Kubernetes namespace hosting Kubeflow Pipelines. If you want to use the user-gcp-sa service account you change the value of USE_KFP_SA to True. Note that the default AI Platform Pipelines configuration does not define the user-gcp-sa secret.
ENABLE_TUNING - boolean value indicating whether to add the Tuner component to the pipeline or use hyperparameter defaults. See the model.py and pipeline.py files for details on how this changes the pipeline topology across pipeline versions. You will create pipeline versions without and with tuning enabled in the subsequent lab exercises for comparison.
End of explanation
!tfx pipeline compile --engine kubeflow --pipeline_path runner.py
Explanation: Compile your pipeline code
You can build and upload the pipeline to the AI Platform Pipelines instance in one step, using the tfx pipeline create command. The tfx pipeline create goes through the following steps:
- (Optional) Builds the custom image to that provides a runtime environment for TFX components or uses the latest image of the installed TFX version
- Compiles the pipeline code into a pipeline package
- Uploads the pipeline package via the ENDPOINT to the hosted AI Platform instance.
As you debug the pipeline DSL, you may prefer to first use the tfx pipeline compile command, which only executes the compilation step. After the DSL compiles successfully you can use tfx pipeline create to go through all steps.
End of explanation
# TODO: Your code here to use the TFX CLI to deploy your pipeline image to AI Platform Pipelines.
!tfx pipeline create \
--pipeline_path=runner.py \
--endpoint={ENDPOINT} \
--build_target_image={CUSTOM_TFX_IMAGE}
Explanation: Note: you should see a {PIPELINE_NAME}.tar.gz file appear in your current pipeline directory.
Exercise: deploy your pipeline container to AI Platform Pipelines with TFX CLI
After the pipeline code compiles without any errors you can use the tfx pipeline create command to perform the full build and deploy the pipeline. You will deploy your compiled pipeline container hosted on Google Container Registry e.g. gcr.io/[PROJECT_ID]/tfx_covertype_continuous_training to run on AI Platform Pipelines with the TFX CLI.
End of explanation
# TODO: your code here to trigger a pipeline run with the TFX CLI
!tfx run create --pipeline_name={PIPELINE_NAME} --endpoint={ENDPOINT}
Explanation: Hint: review the TFX CLI documentation on the "pipeline group" to create your pipeline. You will need to specify the --pipeline_path to point at the pipeline DSL and runner defined locally in runner.py, --endpoint, and --build_target_image arguments using the environment variables specified above.
Note: you should see a build.yaml file in your pipeline folder created by skaffold. The TFX CLI compile triggers a custom container to be built with skaffold using the instructions in the Dockerfile.
If you need to redeploy the pipeline you can first delete the previous version using tfx pipeline delete or you can update the pipeline in-place using tfx pipeline update.
To delete the pipeline:
tfx pipeline delete --pipeline_name {PIPELINE_NAME} --endpoint {ENDPOINT}
To update the pipeline:
tfx pipeline update --pipeline_path runner.py --endpoint {ENDPOINT}
Create and monitor a pipeline run with the TFX CLI
After the pipeline has been deployed, you can trigger and monitor pipeline runs using TFX CLI.
Hint: review the TFX CLI documentation on the "run group".
End of explanation
!tfx run list --pipeline_name {PIPELINE_NAME} --endpoint {ENDPOINT}
Explanation: To view the status of existing pipeline runs:
End of explanation
RUN_ID='[YOUR RUN ID]'
!tfx run status --pipeline_name {PIPELINE_NAME} --run_id {RUN_ID} --endpoint {ENDPOINT}
Explanation: To retrieve the status of a given run:
End of explanation
ENABLE_TUNING=True
%env ENABLE_TUNING={ENABLE_TUNING}
Explanation: Important
A full pipeline run without tuning enabled will take about 40 minutes to complete. You can view the run's progress using the TFX CLI commands above or in the
Exercise: deploy a pipeline version with tuning enabled
Incorporating automatic model hyperparameter tuning into a continuous training TFX pipeline workflow enables faster experimentation, development, and deployment of a top performing model.
The previous pipeline version read from hyperparameter default values in the search space defined in _get_hyperparameters() in model.py and used these values to build a TensorFlow WideDeep Classifier model.
Let's now deploy a new pipeline version with the Tuner component added to the pipeline that calls out to the AI Platform Vizier service for distributed and parallelized hyperparameter tuning. The Tuner component "best_hyperparameters" artifact will be passed directly to your Trainer component to deploy the top performing model. Review pipeline.py to see how this environment variable changes the pipeline topology. Also, review the tuning function in model.py for configuring CloudTuner.
Note that you might not want to tune the hyperparameters every time you retrain your model due to the computational cost. Once you have used Tuner determine a good set of hyperparameters, you can remove Tuner from your pipeline and use model hyperparameters defined in your model code or use a ImporterNode to import the Tuner "best_hyperparameters"artifact from a previous Tuner run to your model Trainer.
End of explanation
!tfx pipeline compile --engine kubeflow --pipeline_path runner.py
Explanation: Compile your pipeline code
End of explanation
#TODO: your code to update your pipeline
!tfx pipeline update --pipeline_path runner.py --endpoint {ENDPOINT}
Explanation: Deploy your pipeline container to AI Platform Pipelines with the TFX CLI
End of explanation |
7,487 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wasserstein Discriminant Analysis
This example illustrate the use of WDA as proposed in [11].
[11] Flamary, R., Cuturi, M., Courty, N., & Rakotomamonjy, A. (2016).
Wasserstein Discriminant Analysis.
Step1: Generate data
Step2: Plot data
Step3: Compute Fisher Discriminant Analysis
Step4: Compute Wasserstein Discriminant Analysis
Step5: Plot 2D projections | Python Code:
# Author: Remi Flamary <remi.flamary@unice.fr>
#
# License: MIT License
import numpy as np
import matplotlib.pylab as pl
from ot.dr import wda, fda
Explanation: Wasserstein Discriminant Analysis
This example illustrate the use of WDA as proposed in [11].
[11] Flamary, R., Cuturi, M., Courty, N., & Rakotomamonjy, A. (2016).
Wasserstein Discriminant Analysis.
End of explanation
#%% parameters
n = 1000 # nb samples in source and target datasets
nz = 0.2
# generate circle dataset
t = np.random.rand(n) * 2 * np.pi
ys = np.floor((np.arange(n) * 1.0 / n * 3)) + 1
xs = np.concatenate(
(np.cos(t).reshape((-1, 1)), np.sin(t).reshape((-1, 1))), 1)
xs = xs * ys.reshape(-1, 1) + nz * np.random.randn(n, 2)
t = np.random.rand(n) * 2 * np.pi
yt = np.floor((np.arange(n) * 1.0 / n * 3)) + 1
xt = np.concatenate(
(np.cos(t).reshape((-1, 1)), np.sin(t).reshape((-1, 1))), 1)
xt = xt * yt.reshape(-1, 1) + nz * np.random.randn(n, 2)
nbnoise = 8
xs = np.hstack((xs, np.random.randn(n, nbnoise)))
xt = np.hstack((xt, np.random.randn(n, nbnoise)))
Explanation: Generate data
End of explanation
#%% plot samples
pl.figure(1, figsize=(6.4, 3.5))
pl.subplot(1, 2, 1)
pl.scatter(xt[:, 0], xt[:, 1], c=ys, marker='+', label='Source samples')
pl.legend(loc=0)
pl.title('Discriminant dimensions')
pl.subplot(1, 2, 2)
pl.scatter(xt[:, 2], xt[:, 3], c=ys, marker='+', label='Source samples')
pl.legend(loc=0)
pl.title('Other dimensions')
pl.tight_layout()
Explanation: Plot data
End of explanation
#%% Compute FDA
p = 2
Pfda, projfda = fda(xs, ys, p)
Explanation: Compute Fisher Discriminant Analysis
End of explanation
#%% Compute WDA
p = 2
reg = 1e0
k = 10
maxiter = 100
Pwda, projwda = wda(xs, ys, p, reg, k, maxiter=maxiter)
Explanation: Compute Wasserstein Discriminant Analysis
End of explanation
#%% plot samples
xsp = projfda(xs)
xtp = projfda(xt)
xspw = projwda(xs)
xtpw = projwda(xt)
pl.figure(2)
pl.subplot(2, 2, 1)
pl.scatter(xsp[:, 0], xsp[:, 1], c=ys, marker='+', label='Projected samples')
pl.legend(loc=0)
pl.title('Projected training samples FDA')
pl.subplot(2, 2, 2)
pl.scatter(xtp[:, 0], xtp[:, 1], c=ys, marker='+', label='Projected samples')
pl.legend(loc=0)
pl.title('Projected test samples FDA')
pl.subplot(2, 2, 3)
pl.scatter(xspw[:, 0], xspw[:, 1], c=ys, marker='+', label='Projected samples')
pl.legend(loc=0)
pl.title('Projected training samples WDA')
pl.subplot(2, 2, 4)
pl.scatter(xtpw[:, 0], xtpw[:, 1], c=ys, marker='+', label='Projected samples')
pl.legend(loc=0)
pl.title('Projected test samples WDA')
pl.tight_layout()
pl.show()
Explanation: Plot 2D projections
End of explanation |
7,488 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing different movie rating systems
In this notebook, I use simple statistical metrics (mean, median, standard deviation and some quantiles) to analyze different movie rating systems. I also perform a linear regression and analyse its significance.
Author
Step1: Fandango stars histogram
Step2: Metacritic (normed and rounded to the closest 0.5) histogram
Step3: Some comparison metrics for Metacritic and Fandango ratings
Step4: Major differences between Fandango and Metacritic ratings
Fandango lowest rating is 3.0 whereas Metacritic could go as low as 0.5
The rating for Fandango are rounded to the closest 0.5 point above
The mean for Fandango is higher than its median which could mean there are more large ratings
The opposite is true for Metacritic ratings
There is less variability in the Fandango ratings (0.54 std) than the Metacritic ones (0.99 std)
=> The Fandango rating system seems biased, flawed and thus of lesser value than the Metacritic one.
Scatter plot between Fandango and Metacritic ratings
Step6: Finding the 5 movies with the biggest rating differences (in absolute values)
Step7: Correlation analysis between Fandango and Metacritic ratings
Step8: => The low correlation (which is significant at an $alpha=0.05$ level) might mean that the two ratings systems are independent (this is of course just an assumption which is generally false).
This is why for the next part we will analyse a linear regression model between both.
Linear regression between the two ratings systems
Step9: Predict the Fandango rating given a Metacritic one
Step10: A scatter plot + fitted regression line
Step11: Display the residuals distribution of the fitted Fandango ratings
Step12: => The residuals doesn't seem to be drawn from a Gaussian distribution. Let's test this assumption.
Testing the normality of the residuals
Step13: => The fandango residuals are thus normal at
$alpha=0.05$ level but not at $alpha=0.01$ one.
To end out investigation, a qqplot | Python Code:
import pandas as pd
import numpy as np
import scipy.stats as sps
import matplotlib.pyplot as plt
%matplotlib inline
movies = pd.read_csv('fandango_score_comparison.csv')
movies.describe()
movies.info()
# Check the movie data structure
movies.head()
Explanation: Comparing different movie rating systems
In this notebook, I use simple statistical metrics (mean, median, standard deviation and some quantiles) to analyze different movie rating systems. I also perform a linear regression and analyse its significance.
Author: Yassine Alouini
Date: 16-5-2016
License: MIT
End of explanation
movies["Fandango_Stars"].hist(bins=[1,2,3,4,5])
Explanation: Fandango stars histogram
End of explanation
movies["Metacritic_norm_round"].hist(bins=[1,2,3,4,5])
Explanation: Metacritic (normed and rounded to the closest 0.5) histogram
End of explanation
# Mean, standard deviation, median and other quantiles
movies[["Metacritic_norm_round","Fandango_Stars"]].describe()
Explanation: Some comparison metrics for Metacritic and Fandango ratings
End of explanation
movies.plot(x='Fandango_Stars',
y='Metacritic_norm_round',
kind='scatter')
Explanation: Major differences between Fandango and Metacritic ratings
Fandango lowest rating is 3.0 whereas Metacritic could go as low as 0.5
The rating for Fandango are rounded to the closest 0.5 point above
The mean for Fandango is higher than its median which could mean there are more large ratings
The opposite is true for Metacritic ratings
There is less variability in the Fandango ratings (0.54 std) than the Metacritic ones (0.99 std)
=> The Fandango rating system seems biased, flawed and thus of lesser value than the Metacritic one.
Scatter plot between Fandango and Metacritic ratings
End of explanation
def abs_diff(row):
return np.abs(row[0] - row[1])
fm_diff = movies[["Metacritic_norm_round","Fandango_Stars"]].apply(
lambda row: abs_diff(row), axis=1)
fm_diff.sort(ascending=False)
differently_rated_movies = movies.loc[fm_diff.head().index]["FILM"]
differently_rated_movies = '\n'.join(differently_rated_movies.values)
print(The top 5 differently rated movies are: \n{0}.format(differently_rated_movies))
Explanation: Finding the 5 movies with the biggest rating differences (in absolute values)
End of explanation
x = movies["Metacritic_norm_round"]
y = movies["Fandango_Stars"]
correlation, p_value = sps.pearsonr(x, y)
correlation_message = "The correlation between Metacritic and Fandango ratings is {0} for a p-value of {1}"
print(correlation_message.format(correlation, p_value))
Explanation: Correlation analysis between Fandango and Metacritic ratings
End of explanation
slope, intercept, _, _,stderr = sps.linregress(x,y)
Explanation: => The low correlation (which is significant at an $alpha=0.05$ level) might mean that the two ratings systems are independent (this is of course just an assumption which is generally false).
This is why for the next part we will analyse a linear regression model between both.
Linear regression between the two ratings systems
End of explanation
def make_prediction(x):
return slope * x + intercept
metacritic_rating = 3.0
fandango_predicted_rating = make_prediction(metacritic_rating)
prediction_message = "The Fandango rating for a {0} Metacritic one is: {1}"
print(prediction_message.format(metacritic_rating,
fandango_predicted_rating))
Explanation: Predict the Fandango rating given a Metacritic one
End of explanation
fandango_predicted_ratings = list(map(make_prediction,
x))
plt.scatter(x, y)
plt.plot(x, fandango_predicted_ratings, color='red')
Explanation: A scatter plot + fitted regression line
End of explanation
# Construct a Gaussian curve using the mean and std of the Fandango
# residuals
np.random.seed(314159265)
min_res = fandango_ratings_residuals.min()
max_res = fandango_ratings_residuals.max()
linear_space = np.linspace(min_res, max_res,
len(fandango_ratings_residuals))
mean = fandango_ratings_residuals.mean()
std = fandango_ratings_residuals.std()
normal_residuals = sps.norm.pdf(linear_space, mean, std)
import seaborn as sns
fandango_ratings_residuals = fandango_predicted_ratings - y
def IQR(x):
return np.ediff1d(x.quantile([0.25, 0.75]))
def optimal_bins_width(x):
return 2 * IQR(x) / (len(x) ** (1/3))
def optimal_bins_number(x):
return (x.max() - x.min()) / optimal_bins_width(x)
bins = int(optimal_bins_number(fandango_ratings_residuals))
sns.distplot(fandango_ratings_residuals, bins=bins, color="r")
plt.plot(linear_space, normal_residuals)
Explanation: Display the residuals distribution of the fitted Fandango ratings
End of explanation
_, normality_p_value = sps.normaltest(fandango_ratings_residuals)
normality_p_value
Explanation: => The residuals doesn't seem to be drawn from a Gaussian distribution. Let's test this assumption.
Testing the normality of the residuals
End of explanation
sps.probplot(fandango_ratings_residuals, dist="norm", plot=plt)
plt.show()
Explanation: => The fandango residuals are thus normal at
$alpha=0.05$ level but not at $alpha=0.01$ one.
To end out investigation, a qqplot
End of explanation |
7,489 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Drawdown caused by groundwater extraction
Developed by R.A. Collenteur & M. Bakker
In this example notebook it is shown how to simulate the effect of a pumping well on the groundwater levels. We will first create a TFN model with the net recharge as the single stress used to explain the observed heads. Second, this model is extended to include the effect of a pumping well on the heads by adding another stress model. The simulated heads are compared and it can be clearly seen how the addition of the pumping well improves the simulation of the heads.
This example was also shown at the 2018 General Assembly of the European Geophysical Union
Step1: 2. Read the time series from files
All time series for this example have been prepared as csv-files, which are read using the Pandas read_csv- method. The following time series are available
Step2: 3. Create a Pastas Model
A pastas Model is created. A constant and a noisemodel are automatically added. The effect of the net groundwater recharge $R(t)$ is simulated using the ps.RechargeModel stress model. Net recharge is calculated as $R(t) = P(t) - f * E(t)$ where $f$ is a parameter that is estimated and $P(t)$ and $E(t)$ are precipitation and reference evapotranspiration, respectively.
Step3: Interpreting the results
As can be seen from the above plot, the observed heads show a clear rise whereas the simulated heads do not show this behaviour. The rise in the heads cannot be explained by an increased precipitation or a decreased evaporation over time, and it is likely another force is driving the heads upwards. Given the location of the well, we can hypothesize that the groundwater pumping caused a lowering of the heads in the beginning of the observations, which decreased when the pumping well was shut down. A next logical step is to add the effect of the pumping well and see if it improves the simulation of the head.
Add the effect of the pumping well
To simulate the effect of the pumping well a new stress model is added. The effect of the well is simulated using the ps.StressModel, which convoluted a stress with a response function. As a response function the ps.Hantush response function is used. The keyword-argument up=False is provided to tell the model this stress is supposed to have a lowering effect on the groundwater levels.
Step4: Interpreting the results
The addition of the pumping well to simulate the heads clearly improved the fit with the observed heads. It can also be seen how the pumping well stops contributing to the lowering of the head after ~2014, indicating the pumping effect of the well has dampened out. The period it takes before the historic pumping has no effect anymore can be approximated by the length of the response function for the well (e.g., len(ml.get_step_response("well"))).
Analyzing the residuals
The difference between the model with and without the pumping becomes even more clear when analyzing the model residuals. The residuals of the model without the well show a clear upward trend, whereas the model with a model does not show this trend anymore. | Python Code:
import pandas as pd
import pastas as ps
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Drawdown caused by groundwater extraction
Developed by R.A. Collenteur & M. Bakker
In this example notebook it is shown how to simulate the effect of a pumping well on the groundwater levels. We will first create a TFN model with the net recharge as the single stress used to explain the observed heads. Second, this model is extended to include the effect of a pumping well on the heads by adding another stress model. The simulated heads are compared and it can be clearly seen how the addition of the pumping well improves the simulation of the heads.
This example was also shown at the 2018 General Assembly of the European Geophysical Union:
Bakker, M., Collenteur, R., Calje, F. Schaars (2018, April) Untangling groundwater head series using time series analysis and Pastas. In EGU General Assembly 2018. https://meetingorganizer.copernicus.org/EGU2018/EGU2018-7194.pdf
End of explanation
head = pd.read_csv("data_notebook_7/head_wellex.csv", index_col="Date", parse_dates=True, squeeze=True)
rain = pd.read_csv("data_notebook_7/prec_wellex.csv", index_col="Date", parse_dates=True)
evap = pd.read_csv("data_notebook_7/evap_wellex.csv", index_col="Date", parse_dates=True)
well = pd.read_csv("data_notebook_7/well_wellex.csv", index_col="Date", parse_dates=True)
# Make a plot of all the time series
fig, ax = plt.subplots(4, 1, sharex=True, figsize=(12,5));
ax[0].plot(head, label=head.name, linestyle=" ", marker=".", markersize=2)
ax[0].legend()
ax[1].plot(rain, label="rain")
ax[1].legend()
ax[2].plot(evap, label="evap")
ax[2].legend()
ax[3].plot(well, label="well")
ax[3].legend()
plt.xlim("1995", "2018");
Explanation: 2. Read the time series from files
All time series for this example have been prepared as csv-files, which are read using the Pandas read_csv- method. The following time series are available:
heads in meters above the Dutch National Datum (NAP), irregular time steps
rain in m/d
Makkink reference evaporation in m/d
Pumping extraction rate in m$^3$/d. The pumping well stopped operating after 2012.
End of explanation
# Create the time series model
ml = ps.Model(head, name="groundwater head")
# Add the stres model for the net recharge
rm = ps.StressModel2([rain, evap], name="recharge", rfunc=ps.Gamma)
ml.add_stressmodel(rm)
ml.solve()
ml.plot()
# Let's store the simulated values to compare later
sim1 = ml.simulate()
res1 = ml.residuals()
n1 = ml.noise()
Explanation: 3. Create a Pastas Model
A pastas Model is created. A constant and a noisemodel are automatically added. The effect of the net groundwater recharge $R(t)$ is simulated using the ps.RechargeModel stress model. Net recharge is calculated as $R(t) = P(t) - f * E(t)$ where $f$ is a parameter that is estimated and $P(t)$ and $E(t)$ are precipitation and reference evapotranspiration, respectively.
End of explanation
# Add the stress model for the pumping well
sm = ps.StressModel(well, rfunc=ps.Hantush, name="well", settings="well", up=False)
ml.add_stressmodel(sm)
# Solve the model and make a plot
ml.solve()
axes = ml.plots.decomposition()
axes[0].plot(sim1) # Add the previously simulated values to the plot
Explanation: Interpreting the results
As can be seen from the above plot, the observed heads show a clear rise whereas the simulated heads do not show this behaviour. The rise in the heads cannot be explained by an increased precipitation or a decreased evaporation over time, and it is likely another force is driving the heads upwards. Given the location of the well, we can hypothesize that the groundwater pumping caused a lowering of the heads in the beginning of the observations, which decreased when the pumping well was shut down. A next logical step is to add the effect of the pumping well and see if it improves the simulation of the head.
Add the effect of the pumping well
To simulate the effect of the pumping well a new stress model is added. The effect of the well is simulated using the ps.StressModel, which convoluted a stress with a response function. As a response function the ps.Hantush response function is used. The keyword-argument up=False is provided to tell the model this stress is supposed to have a lowering effect on the groundwater levels.
End of explanation
ml.residuals().plot(figsize=(12, 4))
res1.plot()
plt.legend(["Model with well", "Model without well"])
Explanation: Interpreting the results
The addition of the pumping well to simulate the heads clearly improved the fit with the observed heads. It can also be seen how the pumping well stops contributing to the lowering of the head after ~2014, indicating the pumping effect of the well has dampened out. The period it takes before the historic pumping has no effect anymore can be approximated by the length of the response function for the well (e.g., len(ml.get_step_response("well"))).
Analyzing the residuals
The difference between the model with and without the pumping becomes even more clear when analyzing the model residuals. The residuals of the model without the well show a clear upward trend, whereas the model with a model does not show this trend anymore.
End of explanation |
7,490 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2A.ml - Clustering
Ce notebook utilise les données des vélos de Chicago Divvy Data. Il s'inspire du challenge créée pour découvrir les habitudes des habitantes de la ville City Bike. L'idée est d'explorer plusieurs algorithmes de clustering et de voire comment trafiquer les données pour les faire marcher et en tirer quelques apprentissages.
Step1: Les données
Elles ont été prétraitées selon le notebook Bike Pattern 2. Elles représentent la distribution du nombre de vélos partant (startdist) et arrivant (stopdist). On utilise le clustering pour découvrir les différents usages des habitants de Chicago avec pour intuition le fait que les habitants de Chicago utilise majoritairement les vélos pour aller et venir entre leur appartement et leur lieu de travail. Cette même idée mais à Paris est illustrée par ce billet de blog | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
Explanation: 2A.ml - Clustering
Ce notebook utilise les données des vélos de Chicago Divvy Data. Il s'inspire du challenge créée pour découvrir les habitudes des habitantes de la ville City Bike. L'idée est d'explorer plusieurs algorithmes de clustering et de voire comment trafiquer les données pour les faire marcher et en tirer quelques apprentissages.
End of explanation
from pyensae.datasource import download_data
file = download_data("features_bike_chicago.zip")
file
import pandas
features = pandas.read_csv("features_bike_chicago.txt", sep="\t", encoding="utf-8", low_memory=False, header=[0,1])
features.columns = ["station_id", "station_name", "weekday"] + list(features.columns[3:])
features.head()
Explanation: Les données
Elles ont été prétraitées selon le notebook Bike Pattern 2. Elles représentent la distribution du nombre de vélos partant (startdist) et arrivant (stopdist). On utilise le clustering pour découvrir les différents usages des habitants de Chicago avec pour intuition le fait que les habitants de Chicago utilise majoritairement les vélos pour aller et venir entre leur appartement et leur lieu de travail. Cette même idée mais à Paris est illustrée par ce billet de blog : Busy areas in Paris.
End of explanation |
7,491 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating MNE objects from data arrays
In this simple example, the creation of MNE objects from
numpy arrays is demonstrated. In the last example case, a
NEO file format is used as a source for the data.
Step1: Create arbitrary data
Step2: Create an
Step3: Create a dummy
Step4: EpochsArray
Step5: EvokedArray
Step6: Create epochs by windowing the raw data.
Step7: Create overlapping epochs using
Step8: Extracting data from NEO file | Python Code:
# Author: Jaakko Leppakangas <jaeilepp@student.jyu.fi>
#
# License: BSD (3-clause)
import numpy as np
import neo
import mne
print(__doc__)
Explanation: Creating MNE objects from data arrays
In this simple example, the creation of MNE objects from
numpy arrays is demonstrated. In the last example case, a
NEO file format is used as a source for the data.
End of explanation
sfreq = 1000 # Sampling frequency
times = np.arange(0, 10, 0.001) # Use 10000 samples (10s)
sin = np.sin(times * 10) # Multiplied by 10 for shorter cycles
cos = np.cos(times * 10)
sinX2 = sin * 2
cosX2 = cos * 2
# Numpy array of size 4 X 10000.
data = np.array([sin, cos, sinX2, cosX2])
# Definition of channel types and names.
ch_types = ['mag', 'mag', 'grad', 'grad']
ch_names = ['sin', 'cos', 'sinX2', 'cosX2']
Explanation: Create arbitrary data
End of explanation
# It is also possible to use info from another raw object.
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
Explanation: Create an :class:info <mne.Info> object.
End of explanation
raw = mne.io.RawArray(data, info)
# Scaling of the figure.
# For actual EEG/MEG data different scaling factors should be used.
scalings = {'mag': 2, 'grad': 2}
raw.plot(n_channels=4, scalings=scalings, title='Data from arrays',
show=True, block=True)
# It is also possible to auto-compute scalings
scalings = 'auto' # Could also pass a dictionary with some value == 'auto'
raw.plot(n_channels=4, scalings=scalings, title='Auto-scaled Data from arrays',
show=True, block=True)
Explanation: Create a dummy :class:mne.io.RawArray object
End of explanation
event_id = 1 # This is used to identify the events.
# First column is for the sample number.
events = np.array([[200, 0, event_id],
[1200, 0, event_id],
[2000, 0, event_id]]) # List of three arbitrary events
# Here a data set of 700 ms epochs from 2 channels is
# created from sin and cos data.
# Any data in shape (n_epochs, n_channels, n_times) can be used.
epochs_data = np.array([[sin[:700], cos[:700]],
[sin[1000:1700], cos[1000:1700]],
[sin[1800:2500], cos[1800:2500]]])
ch_names = ['sin', 'cos']
ch_types = ['mag', 'mag']
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
epochs = mne.EpochsArray(epochs_data, info=info, events=events,
event_id={'arbitrary': 1})
picks = mne.pick_types(info, meg=True, eeg=False, misc=False)
epochs.plot(picks=picks, scalings='auto', show=True, block=True)
Explanation: EpochsArray
End of explanation
nave = len(epochs_data) # Number of averaged epochs
evoked_data = np.mean(epochs_data, axis=0)
evokeds = mne.EvokedArray(evoked_data, info=info, tmin=-0.2,
comment='Arbitrary', nave=nave)
evokeds.plot(picks=picks, show=True, units={'mag': '-'},
titles={'mag': 'sin and cos averaged'}, time_unit='s')
Explanation: EvokedArray
End of explanation
# The events are spaced evenly every 1 second.
duration = 1.
# create a fixed size events array
# start=0 and stop=None by default
events = mne.make_fixed_length_events(raw, event_id, duration=duration)
print(events)
# for fixed size events no start time before and after event
tmin = 0.
tmax = 0.99 # inclusive tmax, 1 second epochs
# create :class:`Epochs <mne.Epochs>` object
epochs = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,
tmax=tmax, baseline=None, verbose=True)
epochs.plot(scalings='auto', block=True)
Explanation: Create epochs by windowing the raw data.
End of explanation
duration = 0.5
events = mne.make_fixed_length_events(raw, event_id, duration=duration)
print(events)
epochs = mne.Epochs(raw, events=events, tmin=tmin, tmax=tmax, baseline=None,
verbose=True)
epochs.plot(scalings='auto', block=True)
Explanation: Create overlapping epochs using :func:mne.make_fixed_length_events (50 %
overlap). This also roughly doubles the amount of events compared to the
previous event list.
End of explanation
# The example here uses the ExampleIO object for creating fake data.
# For actual data and different file formats, consult the NEO documentation.
reader = neo.io.ExampleIO('fakedata.nof')
bl = reader.read(lazy=False)[0]
# Get data from first (and only) segment
seg = bl.segments[0]
title = seg.file_origin
ch_names = list()
data = list()
for ai, asig in enumerate(seg.analogsignals):
# Since the data does not contain channel names, channel indices are used.
ch_names.append('Neo %02d' % (ai + 1,))
# We need the ravel() here because Neo < 0.5 gave 1D, Neo 0.5 gives
# 2D (but still a single channel).
data.append(asig.rescale('V').magnitude.ravel())
data = np.array(data, float)
sfreq = int(seg.analogsignals[0].sampling_rate.magnitude)
# By default, the channel types are assumed to be 'misc'.
info = mne.create_info(ch_names=ch_names, sfreq=sfreq)
raw = mne.io.RawArray(data, info)
raw.plot(n_channels=4, scalings={'misc': 1}, title='Data from NEO',
show=True, block=True, clipping='clamp')
Explanation: Extracting data from NEO file
End of explanation |
7,492 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
View in Colaboratory
Classifying Handwritting using Convolutional Neural Networks
In this example we are going to use PyTorch, a commonly used Deep Learning Framework to classify Handwritten Digits.
We are going to motivate the use of CNNs by quickly examining Softmax Regression and Multilayer Perceptrons, then use the LeNet5 Network Architecture, an architecture developed by Yann LeCunn in the 1990s to recognize digits on zipcodes.
Installing Dependencies
PyTorch is a python based framework and does much of the heavy lifting for us when it comes to preprocessing our data and managing the learning process.
We are going to start by installing PyTorch, importing the framework package and the other packages we are going to use
Step1: Loading Helpful Packages
First thing in any app is to include all of the dependencies for the project.
torch (PyTorch) and its specific sub-libraries - This handles all of our neural network setup, training and testing
torchvision - This is a specific sub-library for PyTorch for computer vision tasks
numpy - Generic matrix library for python
matplotlib and seaborn - graphing libraries for python
Step2: Setting up the Enviorment
We are training our networks on GPUs so we need to make sure to see the random number generator there before we begin
Step3: Loading our Data
First thing we are going to do is load our dataset.
This dataset is called MNIST and it was created by Yann Lecun as a benchmark for handwritting recognition.
As recognition systems got better, it transitioned to a way to teach people the fundimentals of image classification. The dataset consists of 60,000 training and 10,000 testing 28x28px images from 0-9 in grayscale and their labels. Because it is a common example PyTorch makes it easy to download and setup.
We want to seperate our training and testing data to prevent what is called overfitting. Overfitting is when the model starts to memorize what is in its training set and when that happens it will not be as flexible to new images. So we never want to evaluate the performace of the model on the training data. We use a set of data the network has not seen before to assess how good the network is.
Dataset Hyper Parameters
Notice there are two "Hyper Parameters", numbers that are not optimized by the model but have impact on the performace. There are more hyper parameters below but since we are right now creating our dataset we are going to start with these two
Step4: Creating the Learning Pipeline
We are going now to layout all the systems to manage training and testing our model
The Training Pipeline
First we are going to define our training pipeline. This is the order of steps in which you go though to train your model on how to complete its task.
First we start with setting the model to train mode. This allows the parameters in the model to change. This function represents 1 training epoch. An epoch is one full interation through the data set. We use the training dataset we created earlier to generate batches of data and their associated true labels.
For each batch we go through the following steps
Step5: Testing Pipeline
Next we are going to define our testing or inference pipeline. During our training we want to intermittently chech the accuracy of our model. Since we don't want to do this with data the model has already seen we will show it new data that it will not remember since we will not be doing backpropogation here. You can see that the pipeline is almost the same with the changes after the data passes through the model and loss is calculated. Here we look at the probablilites outputed by the final layer of the models and find the index of the one with the highest. Each node corressponds to its index's value (e.g. index 0 means 0). We then compare the index of what was predicted to what was expected and calcuated the accuracy.
Step6: This function controls our full training of the model. It takes in a model definition, a selected optimizer and selected loss function and then returns metrics on how the training went and as a byproduct also trains the model. As you can see the learning pipeline iterates according to the number of epochs or the number of times that you want the model to go though the full dataset
Step7: Helpful Utilities
The following function is a function to visualize the learning process, plotting the training loss, testing loss and testing accuracy over time.
Step8: This function conducts inference on a single image
Step9: This function takes an image from the testing set and runs inference on it
Step10: Implementing Sofmax Regression
Our first model of the day is going to be softmax regression. This model can be summed up as simultaneously calculating the probablity that an image is any of the 10 classes at the same time using a set of parameters that represent the importance of particular pixels in the image.
We use the function $P(y' = {1..10}) = \sigma(w^Tx + b)$ where $\sigma = \frac{e^{ \boldsymbol x}} {\sum_\limits{i \in dim \boldsymbol x} e^{\boldsymbol x_i}}$ to calculate the probablity and we use gradient decent to find the weights.
Defining the Model
Pytorch has a super easy way to define machine learning models. We create a sub class of the pytorch class torch.nn.Module listing out the layers of our model in our __init__ method and the operations between those layers in the method called forward. The torch.nn.Module super class handles the implementation of the backpropogation.
Go a head and try to fill in what you think a SoftmaxRegression Model would look like.
Here are some useful functions
Step11: Training the Model
Now that we have a model definition, we can train it on our dataset. Below you can see a couple more hyper parameters.
epochs -> The number of times we show the training dataset to the model
learning rate -> The size of the step we take each time we go through backpropogation (i.e. the $\alpha$ in $W_{t+1} = W_t - \alpha \nabla_W\mathcal L$)
momentum (Note
Step12: Now we can create an instance of our model and transfer it to the GPU (using the nn.Module.cuda method).
Now chose your optimizer, there are a bunch of choices (the most common one is Stocastic Gradient Decent, but others include ADAM, ADA and more). Take a look at http
Step13: Visualizing How Well the Training Went
Now we should have a reasonably well trained model. Lets see how the train went. Use the visualization function to plot the training loss, testing loss and testing accuracy over the course of the training.
Notice
Step14: Trying an Example on Your Trained Model
Use the classify_an_example helper function to classify an example from the testing set
Step15: Implementing Multilayer Perceptron
Next we are going to implement a mulilayer perceptron. Each layer weights the importance of the data from the previous layer, eventually terminating in the same sigmoid function to convert the representation vector of the input data into a probablity. Between each layer we now include a non-linearity or activation function, a function that allows the model to approximate non linear functions and filter data between layers.
Each layer of the MLP now looks like this $relu(w^Tx +b)$ and the full model becomes $\sigma(w^T relu(w^T relu(w^Tx + b)+ b) + b)$
Again we train this model with gradient decent
Defining the Model
Once again we are going to create a sub class of the pytorch class torch.nn.Module listing out the layers of our model in our __init__ method and the operations between those layers in the method called forward. The torch.nn.Module super class handles the implementation of the backpropogation.
Go a head and try to fill in what you think a Multilayer Perceptron Model would look like.
Here are some useful functions
Step16: Training the Model
Again we are going to set our training hyper parameters
epochs -> The number of times we show the training dataset to the model
learning rate -> The size of the step we take each time we go through backpropogation (i.e. the $\alpha$ in $W_{t+1} = W_t - \alpha \nabla_W\mathcal L$)
momentum (Note
Step17: Again create an instance of your model and transfer it to the GPU (using the nn.Module.cuda method).
Now chose your optimizer. Take a look at http
Step18: Visualizing How Well the Training Went
Now we should have a reasonably well trained model. Lets see how the train went. Use the visualization function to plot the training loss, testing loss and testing accuracy over the course of the training.
Notice
Step19: Trying an Example on Your Trained Model
Use the classify_an_example helper function to classify an example from the testing set
Step20: Implementing LeNet
Our final model of the day is going to be LeNet (LeCun 1998). LeNet uses convolution layers to learn usuful features in the image instead of relying on just pixels. Then by stacking more convolution layers on top the model begins to extra useful collections of features. This terminates in a MLP which tries to associate this high level representation of the image with the label.
Now our model looks like this $\sigma(w^T relu(w^T relu(w^T relu(w * relu( w * x + b) + b)+ b)+ b) + b)$ and again we can train this with gradient decent
Defining the Model
Once again we are going to create a sub class of the pytorch class torch.nn.Module listing out the layers of our model in our __init__ method and the operations between those layers in the method called forward. The torch.nn.Module super class handles the implementation of the backpropogation.
Go a head and try to fill in what you think a Multilayer Perceptron Model would look like.
Here are some useful functions
Step21: Training the Model
Again we are going to set our training hyper parameters
epochs -> The number of times we show the training dataset to the model
learning rate -> The size of the step we take each time we go through backpropogation (i.e. the $\alpha$ in $W_{t+1} = W_t - \alpha \nabla_W\mathcal L$)
momentum (Note
Step22: Again create an instance of your model and transfer it to the GPU (using the nn.Module.cuda method).
Now chose your optimizer. Take a look at http
Step23: Visualizing How Well the Training Went
Now we should have a reasonably well trained model. Lets see how the train went. Use the visualization function to plot the training loss, testing loss and testing accuracy over the course of the training.
Notice
Step24: Trying an Example on Your Trained Model
Use the classify_an_example helper function to classify an example from the testing set
Step25: Congratulations!
You just trained 3 different machine learning models and all of them are relatively good at detecting handwritting. There is a big world of models, tasks and strategies to explore. But one more thing before we finish this tutorial...
Limits of your model
You trained a model, it gets something like 98% accuracy on your testing dataset. But is it ready to go out into the world and classify digits?
Lets take a look at an example again...
Step26: But what if I give you this image? | Python Code:
!pip3 install http://download.pytorch.org/whl/cu80/torch-0.3.0.post4-cp36-cp36m-linux_x86_64.whl
!pip3 install torchvision
!pip3 install numpy
!pip3 install matplotlib
!pip3 install seaborn
Explanation: View in Colaboratory
Classifying Handwritting using Convolutional Neural Networks
In this example we are going to use PyTorch, a commonly used Deep Learning Framework to classify Handwritten Digits.
We are going to motivate the use of CNNs by quickly examining Softmax Regression and Multilayer Perceptrons, then use the LeNet5 Network Architecture, an architecture developed by Yann LeCunn in the 1990s to recognize digits on zipcodes.
Installing Dependencies
PyTorch is a python based framework and does much of the heavy lifting for us when it comes to preprocessing our data and managing the learning process.
We are going to start by installing PyTorch, importing the framework package and the other packages we are going to use
End of explanation
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
Explanation: Loading Helpful Packages
First thing in any app is to include all of the dependencies for the project.
torch (PyTorch) and its specific sub-libraries - This handles all of our neural network setup, training and testing
torchvision - This is a specific sub-library for PyTorch for computer vision tasks
numpy - Generic matrix library for python
matplotlib and seaborn - graphing libraries for python
End of explanation
#Enable Cuda
SEED = 1 #Seed the random wieghts on initialization
LOG_INTERVAL = 100 #How often to log training and testing info
torch.cuda.manual_seed(SEED)
Explanation: Setting up the Enviorment
We are training our networks on GPUs so we need to make sure to see the random number generator there before we begin
End of explanation
#Dataloader
#@title Batch Hyper Parameters
BATCH_SIZE = 64 #@param {type:"integer"} #Number of training images to process before updating weights
TEST_BATCH_SIZE = 1000 #@param {type:"number"} #Number of test images to process at once
kwargs = {'num_workers': 1, 'pin_memory': True}
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('/tmp/mnist/data',
train=True,
download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,),
(0.3081,))
])),
batch_size=BATCH_SIZE,
shuffle=True,
**kwargs)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('/tmp/mnist/data',
train=False,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,),
(0.3081,))
])),
batch_size=TEST_BATCH_SIZE,
shuffle=True,
**kwargs
)
Explanation: Loading our Data
First thing we are going to do is load our dataset.
This dataset is called MNIST and it was created by Yann Lecun as a benchmark for handwritting recognition.
As recognition systems got better, it transitioned to a way to teach people the fundimentals of image classification. The dataset consists of 60,000 training and 10,000 testing 28x28px images from 0-9 in grayscale and their labels. Because it is a common example PyTorch makes it easy to download and setup.
We want to seperate our training and testing data to prevent what is called overfitting. Overfitting is when the model starts to memorize what is in its training set and when that happens it will not be as flexible to new images. So we never want to evaluate the performace of the model on the training data. We use a set of data the network has not seen before to assess how good the network is.
Dataset Hyper Parameters
Notice there are two "Hyper Parameters", numbers that are not optimized by the model but have impact on the performace. There are more hyper parameters below but since we are right now creating our dataset we are going to start with these two: Batch Size and Test Batch Size. Batch Size defines how many images the model will try to classify before trying to update its weights. Since we are using Stocastic Gradient Decent (randomly sampling datapoints from the dataset instead of looking at the set in order), we can get irratic gradient behavior if we update too often with not enough information. A lot of times increasing batch size will improve accuracy of the network and the speed of training (by allowing you to take larger steps), but there is a hard limit on the size of your steps so ever increasing batch size may not be a good idea. The test batch size is less important and only defines how many instances of the model we evaluate at once.
Feel free to tweak these numbers and see how it effects the training and accuracy of your models. Make sure to shift + enter after setting them to lock the values in
Data Preprocessing
We dont usually just pass raw images to our model, since we want to reduce the varience in our dataset so distingushing images is an easier task. There are a couple common preprocessing techniques such as subtracting the mean of the dataset from each image and normalizing images.
We are going to normalize our data. Luckly pytorch makes this easy, using the transforms lambda functions. I provided the normalization values for you.
End of explanation
def train(model, optimizer, loss_func, epoch, training_history):
model.train() #Set training mode
for batch, (data, target) in enumerate(train_loader):
data, target = data.cuda(), target.cuda() #Transfer data and correct result to the GPU
data, target = Variable(data), Variable(target) #Make data and correct answers variables in the Network
optimizer.zero_grad() #zero the gradients
output = model(data) #classify the data
loss = loss_func(output, target) #calculate the loss
loss.backward() #propogate the weight updates through the network
optimizer.step()
if batch % LOG_INTERVAL == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch, batch * len(data), len(train_loader.dataset), 100. * batch / len(train_loader), loss.data[0]))
training_history.append(((len(train_loader.dataset) * epoch) + batch * len(data), loss.data[0]))
Explanation: Creating the Learning Pipeline
We are going now to layout all the systems to manage training and testing our model
The Training Pipeline
First we are going to define our training pipeline. This is the order of steps in which you go though to train your model on how to complete its task.
First we start with setting the model to train mode. This allows the parameters in the model to change. This function represents 1 training epoch. An epoch is one full interation through the data set. We use the training dataset we created earlier to generate batches of data and their associated true labels.
For each batch we go through the following steps:
Move our data to our GPU
Declare our data as Variables in the network
Zero all the gradients in the network
Run our data through the network and get the predictions
Using out chosen loss function, calculate the loss function
Calcuate the gradients $\nabla_W$ of the loss with respect to the weights at each node in the network
Update the weights in the network using $W_{t+1} = W_t - \alpha \nabla_W\mathcal L$
End of explanation
def test(model, loss_func, epoch, test_loss_history, test_accuracy_history):
model.eval()
test_loss = 0
correct = 0
for data, target in test_loader:
data, target = data.cuda(), target.cuda() #Transfer data and correct result to the GPU
data, target = Variable(data, volatile=True), Variable(target) #Make data and correct answers variables in the Network
output = model(data) #classify the data
test_loss += loss_func(output, target).data[0] #calculate loss
pred = output.data.max(1)[1] #get predictions for the batch using argmax
correct += pred.eq(target.data).cpu().sum() #total correct anwsers
test_loss /= len(test_loader)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset)))
test_loss_history.append((epoch, test_loss))
test_accuracy_history.append((epoch, 100. * correct / len(test_loader.dataset)))
Explanation: Testing Pipeline
Next we are going to define our testing or inference pipeline. During our training we want to intermittently chech the accuracy of our model. Since we don't want to do this with data the model has already seen we will show it new data that it will not remember since we will not be doing backpropogation here. You can see that the pipeline is almost the same with the changes after the data passes through the model and loss is calculated. Here we look at the probablilites outputed by the final layer of the models and find the index of the one with the highest. Each node corressponds to its index's value (e.g. index 0 means 0). We then compare the index of what was predicted to what was expected and calcuated the accuracy.
End of explanation
def learn(model, optimizer, loss_func):
training_loss = []
test_loss = []
test_accuracy = []
for e in range(EPOCHS):
train(model, optimizer, loss_func, e + 1, training_loss)
test(model, loss_func, e + 1, test_loss, test_accuracy)
return (training_loss, test_loss, test_accuracy)
Explanation: This function controls our full training of the model. It takes in a model definition, a selected optimizer and selected loss function and then returns metrics on how the training went and as a byproduct also trains the model. As you can see the learning pipeline iterates according to the number of epochs or the number of times that you want the model to go though the full dataset
End of explanation
def visualize_learning(training_loss, test_loss, test_accuracy):
f1 = plt.figure()
f2 = plt.figure()
f3 = plt.figure()
ax1 = f1.add_subplot(111)
ax2 = f2.add_subplot(111)
ax3 = f3.add_subplot(111)
training_loss_batch, training_loss_values = zip(*training_loss)
ax1.plot(training_loss_batch, training_loss_values)
ax1.set_title('Training Loss')
ax1.set_xlabel("Batch")
ax1.set_ylabel("Loss")
test_loss_epoch, test_loss_values = zip(*test_loss)
ax2.plot(test_loss_epoch, test_loss_values)
ax2.set_title("Testing Loss")
ax2.set_xlabel("Batch")
ax2.set_ylabel("Loss")
test_accuracy_epoch, test_accuracy_values = zip(*test_accuracy)
ax3.plot(test_accuracy_epoch, test_accuracy_values)
ax3.set_title("Testing Accuracy")
ax3.set_xlabel("Batch")
ax3.set_ylabel("Accuracy (%)")
plt.show()
Explanation: Helpful Utilities
The following function is a function to visualize the learning process, plotting the training loss, testing loss and testing accuracy over time.
End of explanation
def classify(model, img):
img = img.cuda()
img = Variable(img, volatile=True)
output = model(img)
return output.data.max(1)[1]
Explanation: This function conducts inference on a single image
End of explanation
def classify_an_example(model):
img = next(iter(test_loader))[0]
img_np = img.cpu().numpy()[0]
plt.imshow(img_np.reshape(28,28))
print()
print("The image is probably: {}".format(classify(model, img)[0]))
print()
Explanation: This function takes an image from the testing set and runs inference on it
End of explanation
class SoftmaxRegression(nn.Module):
def __init__(self):
super(SoftmaxRegression, self).__init__()
'''
INSERT YOUR MODEL COMPONENTS HERE
'''
def forward(self, x):
'''
LINK YOUR COMPONENTS HERE
'''
return x
Explanation: Implementing Sofmax Regression
Our first model of the day is going to be softmax regression. This model can be summed up as simultaneously calculating the probablity that an image is any of the 10 classes at the same time using a set of parameters that represent the importance of particular pixels in the image.
We use the function $P(y' = {1..10}) = \sigma(w^Tx + b)$ where $\sigma = \frac{e^{ \boldsymbol x}} {\sum_\limits{i \in dim \boldsymbol x} e^{\boldsymbol x_i}}$ to calculate the probablity and we use gradient decent to find the weights.
Defining the Model
Pytorch has a super easy way to define machine learning models. We create a sub class of the pytorch class torch.nn.Module listing out the layers of our model in our __init__ method and the operations between those layers in the method called forward. The torch.nn.Module super class handles the implementation of the backpropogation.
Go a head and try to fill in what you think a SoftmaxRegression Model would look like.
Here are some useful functions:
torch.nn.Linear -> Fully Connected Layer / Impliments $F(\boldsymbol x) = \boldsymbol w^T \boldsymbol x + \boldsymbol b$
torch.nn.Functional.softmax -> Softmax function / Implements $F(x) = \frac{e^{ \boldsymbol x}} {\sum_\limits{i \in dim \boldsymbol x} e^{\boldsymbol x_i} }$
torch.nn.Functional.log_softmax -> Log of the softmax function / Implements $F(x) = log(\frac{e^{ \boldsymbol x}} {\sum_\limits{i \in dim \boldsymbol x} e^{\boldsymbol x_i} })$
torch.Tensor.view -> allows you to reshape a Tensor (multi-dimentional vector)
End of explanation
#@title Training Hyper Parameters
EPOCHS = 10 #@param {type:"integer"} #Number of times to go through the data set
LEARNING_RATE = 0.001 #@param {type:"number"} #How far each update pushes the weights
SGD_MOMENTUM = 0.5 #@param {type:"number"} #How much it takes to change the direction of the gradient
Explanation: Training the Model
Now that we have a model definition, we can train it on our dataset. Below you can see a couple more hyper parameters.
epochs -> The number of times we show the training dataset to the model
learning rate -> The size of the step we take each time we go through backpropogation (i.e. the $\alpha$ in $W_{t+1} = W_t - \alpha \nabla_W\mathcal L$)
momentum (Note: this will only apply if you use SGD) -> We don't want to get stuck in local minima in the loss landscape so we may want to not let a particularly bad batch prevent otherwise good progress. We can redefine the parameter update procedure as $W_{t+1} = W_t - \alpha V_t$ and $V_t = \beta V_{t-1} + (1 - \beta)\nabla_W\mathcal L$ where $\beta$
is our notion of momentum
Set these values to something you think might be reasonable and see what happens. Make sure to shift+enter to lock them in.
End of explanation
sr_model = SoftmaxRegression()
sr_model.cuda()
# Change this to whatever optimizer you want to try
sr_optimizer = optim.SGD(sr_model.parameters(), lr=LEARNING_RATE, momentum=SGD_MOMENTUM)
print(sr_model)
#Change the last argument to whatever loss function you want to try
SR_TRAINING_LOSS, SR_TEST_LOSS, SR_TEST_ACCURACY = learn(sr_model, sr_optimizer, F.nll_loss) #negative loss values may be due to your final layer
Explanation: Now we can create an instance of our model and transfer it to the GPU (using the nn.Module.cuda method).
Now chose your optimizer, there are a bunch of choices (the most common one is Stocastic Gradient Decent, but others include ADAM, ADA and more). Take a look at http://pytorch.org/docs/master/optim.html#algorithms for a list of choices, but if you need a recomendation use torch.optim.SGD
Next we need to pick a loss function. This function calcaluates how far off our prediction was from the expected value. Again there are a whole bunch of options. Here is a list http://pytorch.org/docs/master/nn.html#id46
If you are not sure what to choose then use torch.nn.functional.nll_loss which is negative log likelihood loss ($L(y) = -log(y)$) a common function to use with softmax
End of explanation
visualize_learning(SR_TRAINING_LOSS, SR_TEST_LOSS, SR_TEST_ACCURACY)
Explanation: Visualizing How Well the Training Went
Now we should have a reasonably well trained model. Lets see how the train went. Use the visualization function to plot the training loss, testing loss and testing accuracy over the course of the training.
Notice: We do not measure the training accuracy, since it is not a good measure of how good the model is since we are looking for a model that has good performace on data not yet seen
We should see the training loss quickly decline then plateau.
- If you are seeing jagged training loss perhaps increase the batch size or decrease the learning rate
You should see that the testing loss more gradually reduces
- if you see the testing loss starting to go up, you are now overfitting - probably reduce the number of epochs
You should also see the testing accuracy increase at the same rate the testing loss decreases
End of explanation
classify_an_example(sr_model)
Explanation: Trying an Example on Your Trained Model
Use the classify_an_example helper function to classify an example from the testing set
End of explanation
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
'''
INSERT YOUR MODEL COMPONENTS HERE
'''
return x
def forward(self, x):
'''
LINK YOUR COMPONENTS HERE
'''
return x
Explanation: Implementing Multilayer Perceptron
Next we are going to implement a mulilayer perceptron. Each layer weights the importance of the data from the previous layer, eventually terminating in the same sigmoid function to convert the representation vector of the input data into a probablity. Between each layer we now include a non-linearity or activation function, a function that allows the model to approximate non linear functions and filter data between layers.
Each layer of the MLP now looks like this $relu(w^Tx +b)$ and the full model becomes $\sigma(w^T relu(w^T relu(w^Tx + b)+ b) + b)$
Again we train this model with gradient decent
Defining the Model
Once again we are going to create a sub class of the pytorch class torch.nn.Module listing out the layers of our model in our __init__ method and the operations between those layers in the method called forward. The torch.nn.Module super class handles the implementation of the backpropogation.
Go a head and try to fill in what you think a Multilayer Perceptron Model would look like.
Here are some useful functions:
torch.nn.Linear -> Fully Connected Layer / Impliments $F(\boldsymbol x) = \boldsymbol w^T \boldsymbol x + \boldsymbol b$
torch.nn.Functional.relu -> Rectifying Linear Unit / Implements $max(0,x)$
Other activation functions can be found here: http://pytorch.org/docs/master/nn.html#non-linear-activation-functions
torch.nn.Functional.softmax -> Softmax function / Implements $F(x) = \frac{e^{ \boldsymbol x}} {\sum_\limits{i \in dim \boldsymbol x} e^{\boldsymbol x_i} }$
torch.nn.Functional.log_softmax -> Log of the softmax function / Implements $F(x) = log(\frac{e^{ \boldsymbol x}} {\sum_\limits{i \in dim \boldsymbol x} e^{\boldsymbol x_i} })$
torch.Tensor.view -> allows you to reshape a Tensor (multi-dimentional vector)
End of explanation
#@title Training Hyper Parameters
EPOCHS = 10 #@param {type:"integer"} #Number of times to go through the data set
SGD_MOMENTUM = 0.5 #@param {type:"number"} #How much it takes to change the direction of the gradient
LEARNING_RATE = 0.001 #@param {type:"number"} #How far each update pushes the weights
Explanation: Training the Model
Again we are going to set our training hyper parameters
epochs -> The number of times we show the training dataset to the model
learning rate -> The size of the step we take each time we go through backpropogation (i.e. the $\alpha$ in $W_{t+1} = W_t - \alpha \nabla_W\mathcal L$)
momentum (Note: this will only apply if you use SGD) -> We don't want to get stuck in local minima in the loss landscape so we may want to not let a particularly bad batch prevent otherwise good progress. We can redefine the parameter update procedure as $W_{t+1} = W_t - \alpha V_t$ and $V_t = \beta V_{t-1} + (1 - \beta)\nabla_W\mathcal L$ where $\beta$
is our notion of momentum
Set these values to something you think might be reasonable and see what happens. Make sure to shift+enter to lock them in.
End of explanation
mlp_model = MLP()
mlp_model.cuda()
# Change this to whatever optimizer you want to try
mlp_optimizer = optim.SGD(mlp_model.parameters(), lr=LEARNING_RATE, momentum=SGD_MOMENTUM)
print(mlp_model)
#Change the last argument to whatever loss function you want to try
MLP_TRAINING_LOSS, MLP_TEST_LOSS, MLP_TEST_ACCURACY = learn(mlp_model, mlp_optimizer, F.nll_loss)
Explanation: Again create an instance of your model and transfer it to the GPU (using the nn.Module.cuda method).
Now chose your optimizer. Take a look at http://pytorch.org/docs/master/optim.html#algorithms for a list of choices, but if you need a recomendation use torch.optim.SGD
Next we need to pick a loss function. Here is a list http://pytorch.org/docs/master/nn.html#id46
If you are not sure what to choose then use torch.nn.functional.nll_loss which is negative log likelihood loss ($L(y) = -log(y)$) a common function to use with softmax
End of explanation
visualize_learning(MLP_TRAINING_LOSS, MLP_TEST_LOSS, MLP_TEST_ACCURACY)
Explanation: Visualizing How Well the Training Went
Now we should have a reasonably well trained model. Lets see how the train went. Use the visualization function to plot the training loss, testing loss and testing accuracy over the course of the training.
Notice: We do not measure the training accuracy, since it is not a good measure of how good the model is since we are looking for a model that has good performace on data not yet seen
We should see the training loss quickly decline then plateau.
- If you are seeing jagged training loss perhaps increase the batch size or decrease the learning rate
You should see that the testing loss more gradually reduces
- if you see the testing loss starting to go up, you are now overfitting - probably reduce the number of epochs
You should also see the testing accuracy increase at the same rate the testing loss decreases
End of explanation
classify_an_example(mlp_model)
Explanation: Trying an Example on Your Trained Model
Use the classify_an_example helper function to classify an example from the testing set
End of explanation
#Network
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
'''
INSERT YOUR MODEL COMPONENTS HERE
'''
def forward(self, x):
'''
LINK YOUR COMPONENTS HERE
'''
return x
Explanation: Implementing LeNet
Our final model of the day is going to be LeNet (LeCun 1998). LeNet uses convolution layers to learn usuful features in the image instead of relying on just pixels. Then by stacking more convolution layers on top the model begins to extra useful collections of features. This terminates in a MLP which tries to associate this high level representation of the image with the label.
Now our model looks like this $\sigma(w^T relu(w^T relu(w^T relu(w * relu( w * x + b) + b)+ b)+ b) + b)$ and again we can train this with gradient decent
Defining the Model
Once again we are going to create a sub class of the pytorch class torch.nn.Module listing out the layers of our model in our __init__ method and the operations between those layers in the method called forward. The torch.nn.Module super class handles the implementation of the backpropogation.
Go a head and try to fill in what you think a Multilayer Perceptron Model would look like.
Here are some useful functions:
torch.nn.Conv2d -> 2 Dimentional Convolution / Implements $F(\boldsymbol ) = \boldsymbol b + \sum_{k=0}^{C_{in} - 1} \boldsymbol w * \boldsymbol x$
torch.nn.Linear -> Fully Connected Layer / Impliments $F(\boldsymbol x) = \boldsymbol w^T \boldsymbol x + \boldsymbol b$
torch.nn.Functional.relu -> Rectifying Linear Unit / Implements $max(0,x)$
Other activation functions can be found here: http://pytorch.org/docs/master/nn.html#non-linear-activation-functions
torch.nn.Functional.softmax -> Softmax function / Implements $F(x) = \frac{e^{ \boldsymbol x}} {\sum_\limits{i \in dim \boldsymbol x} e^{\boldsymbol x_i} }$
torch.nn.Functional.log_softmax -> Log of the softmax function / Implements $F(x) = log(\frac{e^{ \boldsymbol x}} {\sum_\limits{i \in dim \boldsymbol x} e^{\boldsymbol x_i} })$
torch.Tensor.view -> allows you to reshape a Tensor (multi-dimentional vector)
torch.nn.Dropout2d -> randomly set a percentage of weights to randomly be set to 0 each update to prevent overfitting
End of explanation
#@title Training Hyper Parameters
EPOCHS = 5 #@param {type:"integer"} #Number of times to go through the data set
SGD_MOMENTUM = 0.5 #@param {type:"number"} #How much it takes to change the direction of the gradient
LEARNING_RATE = 0.001 #@param {type:"number"} #How far each update pushes the weights
Explanation: Training the Model
Again we are going to set our training hyper parameters
epochs -> The number of times we show the training dataset to the model
learning rate -> The size of the step we take each time we go through backpropogation (i.e. the $\alpha$ in $W_{t+1} = W_t - \alpha \nabla_W\mathcal L$)
momentum (Note: this will only apply if you use SGD) -> We don't want to get stuck in local minima in the loss landscape so we may want to not let a particularly bad batch prevent otherwise good progress. We can redefine the parameter update procedure as $W_{t+1} = W_t - \alpha V_t$ and $V_t = \beta V_{t-1} + (1 - \beta)\nabla_W\mathcal L$ where $\beta$
is our notion of momentum
Set these values to something you think might be reasonable and see what happens. Make sure to shift+enter to lock them in.
End of explanation
cnn_model = LeNet()
cnn_model.cuda()
# Change this to whatever optimizer you want to try
cnn_model_optimizer = optim.SGD(cnn_model.parameters(), lr=LEARNING_RATE, momentum=SGD_MOMENTUM)
print(cnn_model)
#Change the last argument to whatever loss function you want to try
CNN_TRAINING_LOSS, CNN_TEST_LOSS, CNN_TEST_ACCURACY = learn(cnn_model, cnn_model_optimizer, F.nll_loss)
Explanation: Again create an instance of your model and transfer it to the GPU (using the nn.Module.cuda method).
Now chose your optimizer. Take a look at http://pytorch.org/docs/master/optim.html#algorithms for a list of choices, but if you need a recomendation use torch.optim.SGD
Next we need to pick a loss function. Here is a list http://pytorch.org/docs/master/nn.html#id46
If you are not sure what to choose then use torch.nn.functional.nll_loss which is negative log likelihood loss ($L(y) = -log(y)$) a common function to use with softmax
End of explanation
visualize_learning(CNN_TRAINING_LOSS, CNN_TEST_LOSS, CNN_TEST_ACCURACY)
Explanation: Visualizing How Well the Training Went
Now we should have a reasonably well trained model. Lets see how the train went. Use the visualization function to plot the training loss, testing loss and testing accuracy over the course of the training.
Notice: We do not measure the training accuracy, since it is not a good measure of how good the model is since we are looking for a model that has good performace on data not yet seen
We should see the training loss quickly decline then plateau.
- If you are seeing jagged training loss perhaps increase the batch size or decrease the learning rate
You should see that the testing loss more gradually reduces
- if you see the testing loss starting to go up, you are now overfitting - probably reduce the number of epochs
You should also see the testing accuracy increase at the same rate the testing loss decreases
End of explanation
classify_an_example(cnn_model)
Explanation: Trying an Example on Your Trained Model
Use the classify_an_example helper function to classify an example from the testing set
End of explanation
classify_an_example(cnn_model)
Explanation: Congratulations!
You just trained 3 different machine learning models and all of them are relatively good at detecting handwritting. There is a big world of models, tasks and strategies to explore. But one more thing before we finish this tutorial...
Limits of your model
You trained a model, it gets something like 98% accuracy on your testing dataset. But is it ready to go out into the world and classify digits?
Lets take a look at an example again...
End of explanation
img, label = next(iter(test_loader))
img = img[0][0]
label = label[0]
img_transpose = img.transpose(0,1)
img_view = img_transpose.cpu().numpy()
plt.imshow(img_view.reshape(28,28))
print("It is supposed to be a " + str(label))
print("The model thinks it is a " + str(classify(cnn_model, img_transpose.unsqueeze(0).unsqueeze(0))[0]))
Explanation: But what if I give you this image?
End of explanation |
7,493 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 1 - Overfitting Sample Data
Here, we will use a simple model to overfit a set of randomly generated data points.
First, we import Numpy to hold the data, and we import Learny McLearnface.
Step1: Now, we will create the data to be overfitted. For the purposes of the example, we will create 100 700-dimensional data points, which will each be randomly assigned one of 10 classes. We will attempt to use a model to overfit this data and achieve 100% accuracy on this training set.
We will organize the data points into a single numpy array, where the rows are individual datapoints, and we will also create a separate vector of integers which give the classes for corresponding examples.
We initialize the data and its classes
Step2: Now, in order to feed the data to Learny McLearnface, we wrap it in a data dictionary with specified labels.
(Note that he validation set and training set will be the same in this case, as we are intentionally trying to overfit a training set.)
Step3: Now, we will create our model. We will use a simple fully-connected shallow network, with 500 hidden layer neurons, ReLU activations, and a softmax classifier at the end.
First, we set our initial network options in a dictionary. We will have an input dimension of 700, and we will use the Xavier scheme to initialize our parameters.
Step4: And finally, we build the network itself. With the above description, the layer architecture will be
Step5: Now that our model is created, we must train it. We use the given Trainer object to accomplish this. First, we must supply training options. These are, once again, provided in a dictionary.
We will use basic stochastic gradient descent with a learning rate of 1, no regularization, and we will train for 10 epochs.
Step6: Now we create the trainer object and give it the model, the data, and the options.
Step7: We will use the trainer's toolset to first print the accuracy of the model before training. Since the model was randomly initialized and there are 10 classes, we should expect an initial accuracy close to 10%
Step8: Since we have supplied all the requirements necessary for the trainer, we simply use the train() function to train the model. This will print status updates at the end of each epoch.
Step9: As you can see, the network overfits the data very easily, achieving a validation accuracy of 100%. For the sake of completeness, we will print the final validation accuracy of the model. | Python Code:
import numpy as np
import LearnyMcLearnface as lml
Explanation: Example 1 - Overfitting Sample Data
Here, we will use a simple model to overfit a set of randomly generated data points.
First, we import Numpy to hold the data, and we import Learny McLearnface.
End of explanation
test_data = np.random.randn(100, 700)
test_classes = np.random.randint(1, 10, 100)
Explanation: Now, we will create the data to be overfitted. For the purposes of the example, we will create 100 700-dimensional data points, which will each be randomly assigned one of 10 classes. We will attempt to use a model to overfit this data and achieve 100% accuracy on this training set.
We will organize the data points into a single numpy array, where the rows are individual datapoints, and we will also create a separate vector of integers which give the classes for corresponding examples.
We initialize the data and its classes:
End of explanation
data = {
'X_train' : test_data,
'y_train' : test_classes,
'X_val' : test_data,
'y_val' : test_classes
}
Explanation: Now, in order to feed the data to Learny McLearnface, we wrap it in a data dictionary with specified labels.
(Note that he validation set and training set will be the same in this case, as we are intentionally trying to overfit a training set.)
End of explanation
opts = {
'input_dim' : 700,
'init_scheme' : 'xavier'
}
Explanation: Now, we will create our model. We will use a simple fully-connected shallow network, with 500 hidden layer neurons, ReLU activations, and a softmax classifier at the end.
First, we set our initial network options in a dictionary. We will have an input dimension of 700, and we will use the Xavier scheme to initialize our parameters.
End of explanation
nn = lml.NeuralNetwork(opts)
nn.add_layer('Affine', {'neurons':500})
nn.add_layer('ReLU', {})
nn.add_layer('Affine', {'neurons':10})
nn.add_layer('SoftmaxLoss', {})
Explanation: And finally, we build the network itself. With the above description, the layer architecture will be:
(Affine) -> (ReLU) -> (Affine) -> (Softmax)
We create our network object, with 500 hidden layer neurons and 10 output layer neurons (which correspond to our 10 classes).
End of explanation
opts = {
'update_options' : {'update_rule' : 'sgd', 'learning_rate' : 1},
'reg_param' : 0,
'num_epochs' : 10
}
Explanation: Now that our model is created, we must train it. We use the given Trainer object to accomplish this. First, we must supply training options. These are, once again, provided in a dictionary.
We will use basic stochastic gradient descent with a learning rate of 1, no regularization, and we will train for 10 epochs.
End of explanation
trainer = lml.Trainer(nn, data, opts)
Explanation: Now we create the trainer object and give it the model, the data, and the options.
End of explanation
accuracy = trainer.accuracy(test_data, test_classes)
print('Initial model accuracy:', accuracy)
Explanation: We will use the trainer's toolset to first print the accuracy of the model before training. Since the model was randomly initialized and there are 10 classes, we should expect an initial accuracy close to 10%
End of explanation
trainer.train()
Explanation: Since we have supplied all the requirements necessary for the trainer, we simply use the train() function to train the model. This will print status updates at the end of each epoch.
End of explanation
accuracy = trainer.accuracy(test_data, test_classes)
print('Final model accuracy:', accuracy)
Explanation: As you can see, the network overfits the data very easily, achieving a validation accuracy of 100%. For the sake of completeness, we will print the final validation accuracy of the model.
End of explanation |
7,494 | Given the following text description, write Python code to implement the functionality described.
Description:
Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation
Function to check for valid subsequences ; Stores which element belongs to which subsequence ; Check for each pos if a possible subsequence exist or not ; Last member of 1 subsequence ; Last Member of 2 nd subsequence ; Check if current element can go to 2 nd subsequence ; Check if the current elements belongs to first subsequence ; If the current element does not belong to any subsequence ; Check if last digit of first subsequence is greater than pos ; If a subsequence is found , find the subsequences ; Stores the resulting subsequences ; Print the subsequence ; If no subsequence found , print - 1 ; Driver Code
| Python Code:
def findSubsequence(str ) :
n = len(str )
res =['0' for i in range(n ) ]
for pos in range(10 ) :
lst1 = '0'
flag = 1
lst2 = chr(pos + 48 )
for i in range(n ) :
if(lst2 <= str[i ] ) :
res[i ] = '2'
lst2 = str[i ]
elif(lst1 <= str[i ] ) :
res[i ] = '1'
lst1 = str[i ]
else :
flag = 0
if(lst1 > chr(pos + 48 ) ) :
flag = 0
if(flag ) :
S1 = ""
S2 = ""
for i in range(n ) :
if(res[i ] == '1' ) :
S1 += str[i ]
else :
S2 += str[i ]
print(S1 , S2 )
return
print("- 1")
if __name__== ' __main __' :
S = "040425524644"
findSubsequence(S )
S = "123456789"
findSubsequence(S )
|
7,495 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Assignment 6
Step1: Importing data
Unfortunately, the USGS does not have any data from this year available from the Feather River or its tributaries. (For this river, it only makes data available after staff hydrologists have had a chance to review it.) I was, however, able to find recent data available from a station maintained by the CA Department of Water Resources (DWR) on this website. The station is the Feather River at Gridley, which is just downstream of Oroville. However, the period of record only goes back to 1984 (in contrast to some of the USGS stations with periods of record back to the early 1900s.) The DWR data is downloadable as a CSV, in which the columns represent data collected on the hour over the 24 hours of the day, and the rows represent days in the period of record. Let's import it and begin to work with it. First, make sure the data file is saved to your computer.
Step2: Note that discharge is in units of cfs, or cubic feet per second. You'll notice that missing data has been assigned the value -9998. Below we will correct the blanks to nan and then convert the discharge data to an array using the values function in the pandas package.
Step3: Now we will embark on a sophisticated approach for removing blank values. We'll interpolate them using pandas' interpolate function, but only when half the day's data values are valid. Finally, we will add all of the hourly values to create a daily value. If there were more than 12 blanks in a day, the daily value will end up as an NaN.
So that you can see how this loop works, I suggest changing the first line to for i in range(2)
Step4: Now, let's visualize the whole period of record.
Step5: So you can see that the recent high flow coming out of the Oroville Dam, while pretty darn high, was not the highest on record. Let's now look at the data another way...
Step6: Very skewed! Notice that above, we needed to tell the histogram function only to look at those values of dailyQ that were not NaNs, otherwise we get an error.
For extreme flows, we usually want to know the average amount of time that elapses between flows of particular magnitudes. Thus, for a flood frequency cacluation, the next step is to determine the peak daily flow for the year. This is very similar to calculations we made in the precipitation tutorial, which you can find here.
One difference is that the dataset we downloaded is missing some days altogether. Rather than going back and finding the missing days (an onorous task), we are just going to use a for loop to calculate the peak value in each year.
First we need to separate the year from the single date column in the input data file. We can do this in pandas using "date-time" functions, as shown below.
Step7: So now let's go through and find the maximimum value of discharge per year.
3) Concept check
Step8: 4) Now, using the Feb 2 class Notebook as a model, develop a Weibull probability plot of the return period vs. annual peakflow value for this period of record. What is the return period of this year's storm according to this method? [1 pt]
Step9: 5) Now use the Gumbel method to produce a plot of return period vs. peak discharge. What is the return period of this year's storm according to this method? [1 pt] | Python Code:
# Import numerical tools
import numpy as np
#Import pandas for reading in and managing data
import pandas as pd
# Import pyplot for plotting
import matplotlib.pyplot as plt
#Import seaborn (useful for plotting)
import seaborn as sns
# Magic function to make matplotlib inline; other style specs must come AFTER
%matplotlib inline
%config InlineBackend.figure_formats = {'svg',}
#%config InlineBackend.figure_formats = {'png', 'retina'}
Explanation: Assignment 6: Floods
Due date: March 16
4 pts + 2 final project points
In this assignment, we will look at flow data from the Feather River just downstream of the Oroville Dam, in order to figure out the statistical frequency of the recent high-flow event.
Questions are interspersed among the "tutorial"-type material below. Please submit your assignment as an html export, and for written responses, please type them in a cell that is of type Markdown.
End of explanation
# Use pd.read_csv() to read in the data and store in a DataFrame
fname = '/Users/lglarsen/Desktop/Laurel Google Drive/Terrestrial hydrology Spr2017/Assignments/Assignment 6/FeatherRiveratGridley.csv'
df = pd.read_csv(fname)
df.head()
Explanation: Importing data
Unfortunately, the USGS does not have any data from this year available from the Feather River or its tributaries. (For this river, it only makes data available after staff hydrologists have had a chance to review it.) I was, however, able to find recent data available from a station maintained by the CA Department of Water Resources (DWR) on this website. The station is the Feather River at Gridley, which is just downstream of Oroville. However, the period of record only goes back to 1984 (in contrast to some of the USGS stations with periods of record back to the early 1900s.) The DWR data is downloadable as a CSV, in which the columns represent data collected on the hour over the 24 hours of the day, and the rows represent days in the period of record. Let's import it and begin to work with it. First, make sure the data file is saved to your computer.
End of explanation
hoursbyday = df[['0', '100', '200', '300', '400', '500', '600', '700', '800', '900', '1000', '1100', '1200', '1300', '1400', '1500', '1600', '1700', '1800', '1900', '2000', '2100', '2200', '2300']].values
Explanation: Note that discharge is in units of cfs, or cubic feet per second. You'll notice that missing data has been assigned the value -9998. Below we will correct the blanks to nan and then convert the discharge data to an array using the values function in the pandas package.
End of explanation
#First, initialize the daily discharge array
dailyQ = np.zeros(np.size(hoursbyday,0)) #This makes the daily discharge array have the same length
#as the number of rows in hoursbyday.
for i in range(np.size(hoursbyday,0)): #This means to iterate over the number of rows in hoursbyday
dayvals = hoursbyday[i,:] #Grab the row of hourly values for each day you are iterating over.
#Now we're going to pad this array with the last 12 values from the day before and the first 12 values from the day after.
#This is in case we need to get rid of blanks at the beginning or end of the day.
if i>0:
dayvals = np.append(hoursbyday[i-1,12:23], dayvals)
else: #If this is the first row, pad the values with blanks
dayvals = np.append(np.ones(12)*-9998, dayvals)
if i==np.size(hoursbyday,0)-1: #if this is the last line in the data file
dayvals = np.append(dayvals, np.ones(12)*-9998)
else: #If this is not the last row
dayvals = np.append(dayvals, hoursbyday[i+1,0:11])
#Now we interpolate the missing values.
dayvals[dayvals<0]=np.nan #Convert blanks to NaN values
pandas_dayvals = pd.Series(dayvals)#I'm converting back to a pandas object because pandas has a useful interpolate function
#Linearly interpolate across the blanks, but only if there are no more than 12 blanks in a row
pandas_dayvals = pandas_dayvals.interpolate(limit=12)
#Last, we'll convert back to a numpy array and just grab the original set of data for that day.
dayvals = pandas_dayvals[12:35].values
# print(dayvals)
#Finally, add all of the values to acquire a daily discharge.
dailyQ[i] = np.sum(dayvals)
# print(dailyQ[i])
np.size(hoursbyday,0)
Explanation: Now we will embark on a sophisticated approach for removing blank values. We'll interpolate them using pandas' interpolate function, but only when half the day's data values are valid. Finally, we will add all of the hourly values to create a daily value. If there were more than 12 blanks in a day, the daily value will end up as an NaN.
So that you can see how this loop works, I suggest changing the first line to for i in range(2): and uncommenting the two print statements at the end of the code. The two questions below require you to do this.
Concept check: In the first row of the data table, how many NaNs do you end up with after the blank interpolation procedure? Why? [1/3 pt]
Concept check: What is the big difference in the daily sum between the first and second rows of the data table? Why? [1/3 pt]
End of explanation
plt.plot(dailyQ)
plt.xlabel('Day in sequence')
plt.ylabel('Daily discharge, cfs')
Explanation: Now, let's visualize the whole period of record.
End of explanation
plt.hist(dailyQ[~np.isnan(dailyQ)],20, normed=True) #creates a 20-bin, normalized histogram.
plt.title('Daily discharge')
plt.xlabel('Discharge, cfs')
plt.ylabel('Probability density')
Explanation: So you can see that the recent high flow coming out of the Oroville Dam, while pretty darn high, was not the highest on record. Let's now look at the data another way...
End of explanation
df['year'] = pd.to_datetime(df['year-month-day'], format='%Y%m%d').dt.year #Tell pandas that
#this column is a date, and then extract just the year and save it to a new column.
year = df['year'].values #Convert this to an array
print(year)
Explanation: Very skewed! Notice that above, we needed to tell the histogram function only to look at those values of dailyQ that were not NaNs, otherwise we get an error.
For extreme flows, we usually want to know the average amount of time that elapses between flows of particular magnitudes. Thus, for a flood frequency cacluation, the next step is to determine the peak daily flow for the year. This is very similar to calculations we made in the precipitation tutorial, which you can find here.
One difference is that the dataset we downloaded is missing some days altogether. Rather than going back and finding the missing days (an onorous task), we are just going to use a for loop to calculate the peak value in each year.
First we need to separate the year from the single date column in the input data file. We can do this in pandas using "date-time" functions, as shown below.
End of explanation
these_years = np.unique(year) #This creates an array of "unique" years in the 'year' array (i.e.,
#with no repeats)
#Initialize the maximum value per year:
maxQ = np.zeros(len(these_years)-1) #One peak discharge per year. Subtracted 1 because the last
#year is a row of NaNs.
for i in range(len(these_years)-1): #Loop over unique years
these_Q = dailyQ[year==these_years[i]]
maxQ[i] = max(these_Q[~np.isnan(these_Q)])
plt.plot(these_years[0:len(these_years)-1], maxQ)
plt.hist(maxQ,10, normed=True) #creates a 10-bin, normalized histogram.
plt.title('Annual peak discharge')
plt.xlabel('Discharge, cfs')
plt.ylabel('Probability density')
Explanation: So now let's go through and find the maximimum value of discharge per year.
3) Concept check: What does the first line after the for loop below do? [1/3 pt]
End of explanation
#Code for Weibull Probability Analysis goes here
Explanation: 4) Now, using the Feb 2 class Notebook as a model, develop a Weibull probability plot of the return period vs. annual peakflow value for this period of record. What is the return period of this year's storm according to this method? [1 pt]
End of explanation
#Code for Gumbel Probability Analysis goes here
Explanation: 5) Now use the Gumbel method to produce a plot of return period vs. peak discharge. What is the return period of this year's storm according to this method? [1 pt]
End of explanation |
7,496 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Bracket Indexing and Selection
The simplest way to pick one or some elements of an array looks very similar to python lists
Step2: Broadcasting
Numpy arrays differ from a normal Python list because of their ability to broadcast
Step3: Now note the changes also occur in our original array!
Step4: Data is not copied, it's a view of the original array! This avoids memory problems!
Step5: Indexing a 2D array (matrices)
The general format is arr_2d[row][col] or arr_2d[row,col]. I recommend usually using the comma notation for clarity.
Step6: Fancy Indexing
Fancy indexing allows you to select entire rows or columns out of order,to show this, let's quickly build out a numpy array
Step7: Fancy indexing allows the following
Step8: More Indexing Help
Indexing a 2d matrix can be a bit confusing at first, especially when you start to add in step size. Try google image searching NumPy indexing to fins useful images, like this one | Python Code:
import numpy as np
#Creating sample array
arr = np.arange(0,11)
#Show
arr
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
NumPy Indexing and Selection
In this lecture we will discuss how to select elements or groups of elements from an array.
End of explanation
#Get a value at an index
arr[8]
#Get values in a range
arr[1:5]
#Get values in a range
arr[0:5]
Explanation: Bracket Indexing and Selection
The simplest way to pick one or some elements of an array looks very similar to python lists:
End of explanation
#Setting a value with index range (Broadcasting)
arr[0:5]=100
#Show
arr
# Reset array, we'll see why I had to reset in a moment
arr = np.arange(0,11)
#Show
arr
#Important notes on Slices
slice_of_arr = arr[0:6]
#Show slice
slice_of_arr
#Change Slice
slice_of_arr[:]=99
#Show Slice again
slice_of_arr
Explanation: Broadcasting
Numpy arrays differ from a normal Python list because of their ability to broadcast:
End of explanation
arr
Explanation: Now note the changes also occur in our original array!
End of explanation
#To get a copy, need to be explicit
arr_copy = arr.copy()
arr_copy
Explanation: Data is not copied, it's a view of the original array! This avoids memory problems!
End of explanation
arr_2d = np.array(([5,10,15],[20,25,30],[35,40,45]))
#Show
arr_2d
#Indexing row
arr_2d[1]
# Format is arr_2d[row][col] or arr_2d[row,col]
# Getting individual element value
arr_2d[1][0]
# Getting individual element value
arr_2d[1,0]
# 2D array slicing
#Shape (2,2) from top right corner
arr_2d[:2,1:]
#Shape bottom row
arr_2d[2]
#Shape bottom row
arr_2d[2,:]
Explanation: Indexing a 2D array (matrices)
The general format is arr_2d[row][col] or arr_2d[row,col]. I recommend usually using the comma notation for clarity.
End of explanation
#Set up matrix
arr2d = np.zeros((10,10))
#Length of array
arr_length = arr2d.shape[1]
#Set up array
for i in range(arr_length):
arr2d[i] = i
arr2d
Explanation: Fancy Indexing
Fancy indexing allows you to select entire rows or columns out of order,to show this, let's quickly build out a numpy array:
End of explanation
arr2d[[2,4,6,8]]
#Allows in any order
arr2d[[6,4,2,7]]
Explanation: Fancy indexing allows the following
End of explanation
arr = np.arange(1,11)
arr
arr > 4
bool_arr = arr>4
bool_arr
arr[bool_arr]
arr[arr>2]
x = 2
arr[arr>x]
Explanation: More Indexing Help
Indexing a 2d matrix can be a bit confusing at first, especially when you start to add in step size. Try google image searching NumPy indexing to fins useful images, like this one:
<img src= 'http://memory.osu.edu/classes/python/_images/numpy_indexing.png' width=500/>
Selection
Let's briefly go over how to use brackets for selection based off of comparison operators.
End of explanation |
7,497 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Corpora and Vector Spaces
Demonstrates transforming text into a vector space representation.
Also introduces corpus streaming and persistence to disk in various formats.
Step1: First, let’s create a small corpus of nine short documents [1]_
Step2: This is a tiny corpus of nine documents, each consisting of only a single sentence.
First, let's tokenize the documents, remove common words (using a toy stoplist)
as well as words that only appear once in the corpus
Step3: Your way of processing the documents will likely vary; here, I only split on whitespace
to tokenize, followed by lowercasing each word. In fact, I use this particular
(simplistic and inefficient) setup to mimic the experiment done in Deerwester et al.'s
original LSA article [1]_.
The ways to process documents are so varied and application- and language-dependent that I
decided to not constrain them by any interface. Instead, a document is represented
by the features extracted from it, not by its "surface" string form
Step4: Here we assigned a unique integer id to all words appearing in the corpus with the
Step5: To actually convert tokenized documents to vectors
Step6: The function
Step7: By now it should be clear that the vector feature with id=10 stands for the question "How many
times does the word graph appear in the document?" and that the answer is "zero" for
the first six documents and "one" for the remaining three.
Corpus Streaming -- One Document at a Time
Note that corpus above resides fully in memory, as a plain Python list.
In this simple example, it doesn't matter much, but just to make things clear,
let's assume there are millions of documents in the corpus. Storing all of them in RAM won't do.
Instead, let's assume the documents are stored in a file on disk, one document per line. Gensim
only requires that a corpus must be able to return one document vector at a time
Step8: The full power of Gensim comes from the fact that a corpus doesn't have to be
a list, or a NumPy array, or a Pandas dataframe, or whatever.
Gensim accepts any object that, when iterated over, successively yields
documents.
Step9: Download the sample mycorpus.txt file here <./mycorpus.txt>_. The assumption that
each document occupies one line in a single file is not important; you can mold
the __iter__ function to fit your input format, whatever it is.
Walking directories, parsing XML, accessing the network...
Just parse your input to retrieve a clean list of tokens in each document,
then convert the tokens via a dictionary to their ids and yield the resulting sparse vector inside __iter__.
Step10: Corpus is now an object. We didn't define any way to print it, so print just outputs address
of the object in memory. Not very useful. To see the constituent vectors, let's
iterate over the corpus and print each document vector (one at a time)
Step11: Although the output is the same as for the plain Python list, the corpus is now much
more memory friendly, because at most one vector resides in RAM at a time. Your
corpus can now be as large as you want.
Similarly, to construct the dictionary without loading all texts into memory
Step12: And that is all there is to it! At least as far as bag-of-words representation is concerned.
Of course, what we do with such a corpus is another question; it is not at all clear
how counting the frequency of distinct words could be useful. As it turns out, it isn't, and
we will need to apply a transformation on this simple representation first, before
we can use it to compute any meaningful document vs. document similarities.
Transformations are covered in the next tutorial
(sphx_glr_auto_examples_core_run_topics_and_transformations.py),
but before that, let's briefly turn our attention to corpus persistency.
Corpus Formats
There exist several file formats for serializing a Vector Space corpus (~sequence of vectors) to disk.
Gensim implements them via the streaming corpus interface mentioned earlier
Step13: Other formats include Joachim's SVMlight format <http
Step14: Conversely, to load a corpus iterator from a Matrix Market file
Step15: Corpus objects are streams, so typically you won't be able to print them directly
Step16: Instead, to view the contents of a corpus
Step17: or
Step18: The second way is obviously more memory-friendly, but for testing and development
purposes, nothing beats the simplicity of calling list(corpus).
To save the same Matrix Market document stream in Blei's LDA-C format,
Step19: In this way, gensim can also be used as a memory-efficient I/O format conversion tool
Step20: and from/to scipy.sparse matrices
Step21: What Next
Read about sphx_glr_auto_examples_core_run_topics_and_transformations.py.
References
For a complete reference (Want to prune the dictionary to a smaller size?
Optimize converting between corpora and NumPy/SciPy arrays?), see the apiref.
.. [1] This is the same corpus as used in
Deerwester et al. (1990) | Python Code:
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
Explanation: Corpora and Vector Spaces
Demonstrates transforming text into a vector space representation.
Also introduces corpus streaming and persistence to disk in various formats.
End of explanation
documents = [
"Human machine interface for lab abc computer applications",
"A survey of user opinion of computer system response time",
"The EPS user interface management system",
"System and human system engineering testing of EPS",
"Relation of user perceived response time to error measurement",
"The generation of random binary unordered trees",
"The intersection graph of paths in trees",
"Graph minors IV Widths of trees and well quasi ordering",
"Graph minors A survey",
]
Explanation: First, let’s create a small corpus of nine short documents [1]_:
From Strings to Vectors
This time, let's start from documents represented as strings:
End of explanation
from pprint import pprint # pretty-printer
from collections import defaultdict
# remove common words and tokenize
stoplist = set('for a of the and to in'.split())
texts = [
[word for word in document.lower().split() if word not in stoplist]
for document in documents
]
# remove words that appear only once
frequency = defaultdict(int)
for text in texts:
for token in text:
frequency[token] += 1
texts = [
[token for token in text if frequency[token] > 1]
for text in texts
]
pprint(texts)
Explanation: This is a tiny corpus of nine documents, each consisting of only a single sentence.
First, let's tokenize the documents, remove common words (using a toy stoplist)
as well as words that only appear once in the corpus:
End of explanation
from gensim import corpora
dictionary = corpora.Dictionary(texts)
dictionary.save('/tmp/deerwester.dict') # store the dictionary, for future reference
print(dictionary)
Explanation: Your way of processing the documents will likely vary; here, I only split on whitespace
to tokenize, followed by lowercasing each word. In fact, I use this particular
(simplistic and inefficient) setup to mimic the experiment done in Deerwester et al.'s
original LSA article [1]_.
The ways to process documents are so varied and application- and language-dependent that I
decided to not constrain them by any interface. Instead, a document is represented
by the features extracted from it, not by its "surface" string form: how you get to
the features is up to you. Below I describe one common, general-purpose approach (called
:dfn:bag-of-words), but keep in mind that different application domains call for
different features, and, as always, it's garbage in, garbage out <http://en.wikipedia.org/wiki/Garbage_In,_Garbage_Out>_...
To convert documents to vectors, we'll use a document representation called
bag-of-words <http://en.wikipedia.org/wiki/Bag_of_words>_. In this representation,
each document is represented by one vector where each vector element represents
a question-answer pair, in the style of:
Question: How many times does the word system appear in the document?
Answer: Once.
It is advantageous to represent the questions only by their (integer) ids. The mapping
between the questions and ids is called a dictionary:
End of explanation
print(dictionary.token2id)
Explanation: Here we assigned a unique integer id to all words appearing in the corpus with the
:class:gensim.corpora.dictionary.Dictionary class. This sweeps across the texts, collecting word counts
and relevant statistics. In the end, we see there are twelve distinct words in the
processed corpus, which means each document will be represented by twelve numbers (ie., by a 12-D vector).
To see the mapping between words and their ids:
End of explanation
new_doc = "Human computer interaction"
new_vec = dictionary.doc2bow(new_doc.lower().split())
print(new_vec) # the word "interaction" does not appear in the dictionary and is ignored
Explanation: To actually convert tokenized documents to vectors:
End of explanation
corpus = [dictionary.doc2bow(text) for text in texts]
corpora.MmCorpus.serialize('/tmp/deerwester.mm', corpus) # store to disk, for later use
print(corpus)
Explanation: The function :func:doc2bow simply counts the number of occurrences of
each distinct word, converts the word to its integer word id
and returns the result as a sparse vector. The sparse vector [(0, 1), (1, 1)]
therefore reads: in the document "Human computer interaction", the words computer
(id 0) and human (id 1) appear once; the other ten dictionary words appear (implicitly) zero times.
End of explanation
from smart_open import open # for transparently opening remote files
class MyCorpus:
def __iter__(self):
for line in open('https://radimrehurek.com/gensim/mycorpus.txt'):
# assume there's one document per line, tokens separated by whitespace
yield dictionary.doc2bow(line.lower().split())
Explanation: By now it should be clear that the vector feature with id=10 stands for the question "How many
times does the word graph appear in the document?" and that the answer is "zero" for
the first six documents and "one" for the remaining three.
Corpus Streaming -- One Document at a Time
Note that corpus above resides fully in memory, as a plain Python list.
In this simple example, it doesn't matter much, but just to make things clear,
let's assume there are millions of documents in the corpus. Storing all of them in RAM won't do.
Instead, let's assume the documents are stored in a file on disk, one document per line. Gensim
only requires that a corpus must be able to return one document vector at a time:
End of explanation
# This flexibility allows you to create your own corpus classes that stream the
# documents directly from disk, network, database, dataframes... The models
# in Gensim are implemented such that they don't require all vectors to reside
# in RAM at once. You can even create the documents on the fly!
Explanation: The full power of Gensim comes from the fact that a corpus doesn't have to be
a list, or a NumPy array, or a Pandas dataframe, or whatever.
Gensim accepts any object that, when iterated over, successively yields
documents.
End of explanation
corpus_memory_friendly = MyCorpus() # doesn't load the corpus into memory!
print(corpus_memory_friendly)
Explanation: Download the sample mycorpus.txt file here <./mycorpus.txt>_. The assumption that
each document occupies one line in a single file is not important; you can mold
the __iter__ function to fit your input format, whatever it is.
Walking directories, parsing XML, accessing the network...
Just parse your input to retrieve a clean list of tokens in each document,
then convert the tokens via a dictionary to their ids and yield the resulting sparse vector inside __iter__.
End of explanation
for vector in corpus_memory_friendly: # load one vector into memory at a time
print(vector)
Explanation: Corpus is now an object. We didn't define any way to print it, so print just outputs address
of the object in memory. Not very useful. To see the constituent vectors, let's
iterate over the corpus and print each document vector (one at a time):
End of explanation
# collect statistics about all tokens
dictionary = corpora.Dictionary(line.lower().split() for line in open('https://radimrehurek.com/gensim/mycorpus.txt'))
# remove stop words and words that appear only once
stop_ids = [
dictionary.token2id[stopword]
for stopword in stoplist
if stopword in dictionary.token2id
]
once_ids = [tokenid for tokenid, docfreq in dictionary.dfs.items() if docfreq == 1]
dictionary.filter_tokens(stop_ids + once_ids) # remove stop words and words that appear only once
dictionary.compactify() # remove gaps in id sequence after words that were removed
print(dictionary)
Explanation: Although the output is the same as for the plain Python list, the corpus is now much
more memory friendly, because at most one vector resides in RAM at a time. Your
corpus can now be as large as you want.
Similarly, to construct the dictionary without loading all texts into memory:
End of explanation
corpus = [[(1, 0.5)], []] # make one document empty, for the heck of it
corpora.MmCorpus.serialize('/tmp/corpus.mm', corpus)
Explanation: And that is all there is to it! At least as far as bag-of-words representation is concerned.
Of course, what we do with such a corpus is another question; it is not at all clear
how counting the frequency of distinct words could be useful. As it turns out, it isn't, and
we will need to apply a transformation on this simple representation first, before
we can use it to compute any meaningful document vs. document similarities.
Transformations are covered in the next tutorial
(sphx_glr_auto_examples_core_run_topics_and_transformations.py),
but before that, let's briefly turn our attention to corpus persistency.
Corpus Formats
There exist several file formats for serializing a Vector Space corpus (~sequence of vectors) to disk.
Gensim implements them via the streaming corpus interface mentioned earlier:
documents are read from (resp. stored to) disk in a lazy fashion, one document at
a time, without the whole corpus being read into main memory at once.
One of the more notable file formats is the Market Matrix format <http://math.nist.gov/MatrixMarket/formats.html>_.
To save a corpus in the Matrix Market format:
create a toy corpus of 2 documents, as a plain Python list
End of explanation
corpora.SvmLightCorpus.serialize('/tmp/corpus.svmlight', corpus)
corpora.BleiCorpus.serialize('/tmp/corpus.lda-c', corpus)
corpora.LowCorpus.serialize('/tmp/corpus.low', corpus)
Explanation: Other formats include Joachim's SVMlight format <http://svmlight.joachims.org/>,
Blei's LDA-C format <http://www.cs.princeton.edu/~blei/lda-c/> and
GibbsLDA++ format <http://gibbslda.sourceforge.net/>_.
End of explanation
corpus = corpora.MmCorpus('/tmp/corpus.mm')
Explanation: Conversely, to load a corpus iterator from a Matrix Market file:
End of explanation
print(corpus)
Explanation: Corpus objects are streams, so typically you won't be able to print them directly:
End of explanation
# one way of printing a corpus: load it entirely into memory
print(list(corpus)) # calling list() will convert any sequence to a plain Python list
Explanation: Instead, to view the contents of a corpus:
End of explanation
# another way of doing it: print one document at a time, making use of the streaming interface
for doc in corpus:
print(doc)
Explanation: or
End of explanation
corpora.BleiCorpus.serialize('/tmp/corpus.lda-c', corpus)
Explanation: The second way is obviously more memory-friendly, but for testing and development
purposes, nothing beats the simplicity of calling list(corpus).
To save the same Matrix Market document stream in Blei's LDA-C format,
End of explanation
import gensim
import numpy as np
numpy_matrix = np.random.randint(10, size=[5, 2]) # random matrix as an example
corpus = gensim.matutils.Dense2Corpus(numpy_matrix)
# numpy_matrix = gensim.matutils.corpus2dense(corpus, num_terms=number_of_corpus_features)
Explanation: In this way, gensim can also be used as a memory-efficient I/O format conversion tool:
just load a document stream using one format and immediately save it in another format.
Adding new formats is dead easy, check out the code for the SVMlight corpus
<https://github.com/piskvorky/gensim/blob/develop/gensim/corpora/svmlightcorpus.py>_ for an example.
Compatibility with NumPy and SciPy
Gensim also contains efficient utility functions <http://radimrehurek.com/gensim/matutils.html>_
to help converting from/to numpy matrices
End of explanation
import scipy.sparse
scipy_sparse_matrix = scipy.sparse.random(5, 2) # random sparse matrix as example
corpus = gensim.matutils.Sparse2Corpus(scipy_sparse_matrix)
scipy_csc_matrix = gensim.matutils.corpus2csc(corpus)
Explanation: and from/to scipy.sparse matrices
End of explanation
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('run_corpora_and_vector_spaces.png')
imgplot = plt.imshow(img)
_ = plt.axis('off')
Explanation: What Next
Read about sphx_glr_auto_examples_core_run_topics_and_transformations.py.
References
For a complete reference (Want to prune the dictionary to a smaller size?
Optimize converting between corpora and NumPy/SciPy arrays?), see the apiref.
.. [1] This is the same corpus as used in
Deerwester et al. (1990): Indexing by Latent Semantic Analysis <http://www.cs.bham.ac.uk/~pxt/IDA/lsa_ind.pdf>_, Table 2.
End of explanation |
7,498 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Risk Sharing and Moral Hazard
Step1: Risk-sharing review
A simple employment contract
Employer hires worker to perform a task that has a stochastic outcome. Project can either
Step2: Moral Hazard or Hidden Actions
or Hidden Actions model
Risk sharing vs. incentives
Stiglitz (1974), Holmstrom (1979), Grossman and Hart (1983)
Agent's private benefit from avoiding diligence or effort is B (extra disutility from high vs. low effort).
Effort is non-contractible and $B$ cannot be observed/seized. Effort-contingent contracts not possible.
Only outcone-contingent contracts can be used.
Hidden actions
Now agent's unobserved (or more to the point non-verifiable) effort levels determines success probability
Step3: If we set this up and solve it as a Lagrangean (loosely following Holmstrom, 1979) we get a condition like this | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, fixed
Explanation: Risk Sharing and Moral Hazard
End of explanation
alpha = 0.25
def u(c, alpha=alpha):
return (1/alpha)*c**alpha
def E(x,p):
return p*x[1] + (1-p)*x[0]
def EU(c, p):
return p*u(c[1]) + (1-p)*u(c[0])
def budgetc(c0, p, x):
return E(x,p)/p - ((1-p)/p)*c0
def indif(c0, p, ubar):
return (alpha*(ubar-(1-p)*u(c0))/p)**(1/alpha)
def IC(c0,p,q,B):
'''incentive compatibility line'''
return (alpha*(u(c0)+B/(p-q)))**(1/alpha)
def Bopt(p,x):
'''Bank profit maximum'''
return (alpha*EU(x,p))**(1/alpha)
def Copt(p,x):
'''Consumer utility maximum'''
return E(x,p)
x = [15,90]
p = 0.6
EU([36,36],p)
Explanation: Risk-sharing review
A simple employment contract
Employer hires worker to perform a task that has a stochastic outcome. Project can either:
- with probability $p$ succeeds to yield $X_s$
- with probability $1-p$ fails to yield $X_f < X_S$
There are two states of the world lebeled $s$ and $f$. The expected return from the project is: $E(X|p) = p \cdot X_s + (1-p) \cdot X_f $
Example
$X_s = 100$, $X_f = 0$, $p = 0.8$
$E(X|p) = 0.8 \cdot 100 + 0.2 \cdot 0 = 80 $
Risk neutral employer and risk-averse agent
Contract design problem: how to allocate claims to stochastic output between:
Principal (Employer): $(X_s-c_s, X_f-c_f)$
Agent (worker): $(c_s, c_f)$
The agent maximize the von-Neumann-Morgenstern expected utility:
$Eu(c|p) = p u(c_s) + (1-p) u(c_f)$
Monopoly Contract design Example
$$\max_{c_s,c_f} \ \ E(X|p) - E(c|p)$$
$$Eu(c|p) \ge \bar u$$
Lagrangian:
$$\mathcal{L}(c_s, c_f,\lambda) = p \cdot (X_s-c_s) + (1-p) \cdot (X_f-c_f) \
-\lambda \left( \bar u - p \cdot u(c_s) - (1-p) u(c_f) \right)$$
Monopoly FOC
for state-contingent claim in state $s$: $p \cdot \lambda \cdot u'(c_s)-p =0 $
Rearranging for $i=s,f$
$$ \frac{1}{u'(c_s)} = \lambda = \frac{1}{u'(c_f)} $$
This implies agent should be fully insured: $c_s = c_f = c^*$
substitute $c_s = c_f = c^*$ into agent participation:
If for example $u(c) = \frac{c^{\alpha}}{\alpha}$ and $\alpha=\frac{1}{2}$ then $2\sqrt{\bar c^*} = \bar u$
Monopoly contract pays worker a fixed wage determined by their reservation utility:
$c^* = \left (\frac{\bar u}{2} \right )^2$
For example if the worker ran the project without insurance:
$\bar u = 0.8 \cdot 2 \sqrt(100) + 0.2 2 \sqrt(0) = 16$ utils
The monopoly insurer offers safe contract: $c_f=c_s=64$
Firm then earns $X_s - c_s = 100 - 64 = 36$ or $X_f - c_f = 0 - 64 = -64$
For expected return of $0.8 \cdot 64 + 0.2 (-36) = 44$
Competitive Contract design
Employers compete for workers:
$$\max_{c_s, c_f} p \cdot u(c_s) + (1-p) u(c_f)$$
subject to then employer participation (zero-profit) constraint:
$$p \cdot (X_s-c_s) + (1-p) \cdot (X_f-c_f) \geq 0$$
Competitive Contract design Example
$$\mathcal{L}(c_s, c_f,\lambda) = p \cdot u(c_s) + (1-p) u(c_f) \
+\lambda \left( p \cdot (X_s-c_s) - (1-p) \cdot (X_f-c_f) \right)$$
Same FOC as above imply: $c_s = c_f$
substitute this now into employer participation to get: $c_f=c_s = E(X|p)$
In our example agent is paid $c_f=c_s = 80$
And firm earns $(X_s-c_s)=100-80 = 20$ and $(X_f-c_f)= 0 - 80 = -80$ for expected return of zero.
Competitive financing
A financial contract is modeled just like this last example (with a slight rewriting and reinterpretation of the Bank (i.e. the principal's) participation constraint).
Suppose agent has access to the same stochastic project above but can only get it started with lump sum investment $I$.
$$\max_{c_s, c_f} p \cdot u(c_s) + (1-p) u(c_f)$$
subject to then employer participation (zero-profit) constraint:
$$p \cdot (X_s-c_s) + (1-p) \cdot (X_f-c_f) \geq I(1+r)$$
Exactly the problem above only that the participation constraint includes a term to cover the opportunity cost of funding.
Lagrangian:
$$\mathcal{L}(c_s, c_f,\lambda) = p \cdot u(c_s) + (1-p) u(c_f) \
+\lambda \left( I(1+r) - p \cdot (X_s-c_s) - (1-p) \cdot (X_f-c_f) \right)$$
FOC again imply contract keeps agent's consumption steady at: $c_s = c_f = c^*$
Bank just breaks even: $E(X|p) - E(c|p) = I(1+r)$
Example: Suppose loan finance costs $I(1+r) = 70$
$E(c|p) = E(X|p) - I(1+r)$
$E(c|p) = 80 - 70 = 10$
Can think of contract as a loan with state-contingent repayments:
$X_s - c_s - I(1+r) = 100 - 10 - 70 = 20$
$X_f - c_f - I(1+r) = 0 - 10 - 70 = -80$
Bank breaks even: $0.8 \cdot 20 + 0.2 \cdot (-80) = 0$
Can extend to many states of the world:
$$E(X|e) = \sum_i {X_i \cdot f(X_i|e)}$$
End of explanation
p = 0.5
q = 0.4
cmax = 100
B = 1.5
IC(2,p,q,B)
def consume_plot(p,q,B,ic=False):
c0 = np.linspace(0.1,200,num=100)
#bank optimum
c0e = Bopt(p,x)
c1e = c0e
uebar = EU([c0e,c1e],p)
idfc = indif(c0, p, uebar)
budg = budgetc(c0, p, [c0e,c1e])
#consumer optimum
c0ee = Copt(p,x)
c1ee = c0ee
uemax = EU([c0ee,c1ee],p)
idfcmax = indif(c0, p, uemax)
zerop = budgetc(c0, p, x)
icline = IC(c0,p,q,B)
fig, ax = plt.subplots(figsize=(10,10))
if ic:
ax.plot(c0,icline)
ax.plot(c0, budg, lw=2.5)
ax.plot(c0, zerop, lw=2.5)
ax.plot(c0, idfc, lw=2.5)
#ax.plot(c0, idfcmax, lw=2.5)
ax.plot(c0,c0)
#ax.vlines(c0e,0,c2e, linestyles="dashed")
#ax.hlines(c1e,0,c1e, linestyles="dashed")
ax.plot(c0e,c1e,'ob')
ax.plot(c0ee,c1ee,'ob')
ax.plot(x[0],x[1],'ob')
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
ax.set_xlabel(r'$c_0$', fontsize=16)
ax.set_ylabel('$c_1$', fontsize=16)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid()
plt.show()
interact(consume_plot,p=fixed(0.5),q=(0.1,0.5,0.01),B=(0,3,0.1));
Explanation: Moral Hazard or Hidden Actions
or Hidden Actions model
Risk sharing vs. incentives
Stiglitz (1974), Holmstrom (1979), Grossman and Hart (1983)
Agent's private benefit from avoiding diligence or effort is B (extra disutility from high vs. low effort).
Effort is non-contractible and $B$ cannot be observed/seized. Effort-contingent contracts not possible.
Only outcone-contingent contracts can be used.
Hidden actions
Now agent's unobserved (or more to the point non-verifiable) effort levels determines success probability:
- High $e_H$ (probability of success $p$).
- Low $e_L$ (probability of success $q$).
- Can no longer offer earlier risk-sharing contract ($c=10$) as cnnot be sure success probability is $p$
Example $q=0.6$ versus $p=0.8$
- E(X|p) - E(c|p) - I(1+r) = 80-10-70 = 0 (bank breaks even)
- E(X|q) - E(c|q) - I(1+r) = 60-10-70 = -20 (bank loses money)
On the other hand full-residual claimancy contract imposes too much risk
Full residual claimant when fixed repayment $I(1+r)$
$c_s = 100-70 = 30$
$c_f = -70 = -70$
$0.8 (30) + 0.2(-70) = 24 - 14 = 10$
But this imposes a lot of risk (actually here not even defined since u(-70) is 'catastrophic')
Need to find balance between risk sharing and incentives
Incentive compatibility constraint:
$$EU(c|p) \geq EU(c|q) + B$$
In 2 outcome case can be re-arranged to:
$$u(c_1) \geq u(c_0) + \frac{B}{p-q}$$
Interactive indifference curve diagram
End of explanation
%%html
<script src="https://cdn.rawgit.com/parente/4c3e6936d0d7a46fd071/raw/65b816fb9bdd3c28b4ddf3af602bfd6015486383/code_toggle.js"></script>
Explanation: If we set this up and solve it as a Lagrangean (loosely following Holmstrom, 1979) we get a condition like this:
$$\frac{1}{u'(c_i)} = \lambda + \mu \cdot
\left [ {1-\frac{f(x_i,e_L)}{f(x_i,e_H)}} \right ] \text{ }\forall i
$$
In our two outcome case $p=f(x_1|e_H)$ and $q=f(x_1|e_L)$ and this becomes:
$$\frac{1}{u'(c_1)} = \lambda + \mu \cdot
\left [ {1-\frac{q}{p}} \right ]
$$
$$\frac{1}{u'(c_0)} = \lambda + \mu \cdot
\left [ {1-\frac{1-q}{1-p}} \right ]
$$
TODO:
- Functions to solve the two outcome cases (closed form possible, substitute IC into binding PC; or 2 FOC plus IC plus PC for $c_0, c_1, \lambda \text{ and } \mu$).
- Function to solve numerically for N outcomes (N FOCs and one participation constraint).
- discuss how sensitive to distribution
Holmstrom's sufficient statistic
$$\frac{1}{u'(c)} = \lambda + \mu \cdot
\left [ {1-\frac{f(x,y,e_L)}{f(x,y,e_H)}} \right ] \text{ }\forall i
$$
End of explanation |
7,499 | 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 Python function component tutorial
Note
Step2: Upgrade Pip
To avoid upgrading Pip in a system when running locally, check to make sure
that we're running in Colab. Local systems can of course be upgraded
separately.
Step3: Install TFX
Note
Step4: Did you restart the runtime?
If you are using Google Colab, the first time that you run the cell above, you
must restart the runtime (Runtime > Restart runtime ...). This is because of
the way that Colab loads packages.
Import packages
We import TFX and check its version.
Step6: Custom Python function components
In this section, we will create components from Python functions. We will notbe
doing any real ML problem — these simple functions are just used to illustrate
the Python function component development process.
See Python function based component
guide
for more documentation.
Create Python custom components
We begin by writing a function that generate some dummy data. This is written
to its own Python module file.
Step8: Next, we write a second component that uses the dummy data produced.
We will just calculate hash of the data and return it.
Step9: Run in-notebook with the InteractiveContext
Now, we will demonstrate usage of our new components in the TFX
InteractiveContext.
For more information on what you can do with the TFX notebook
InteractiveContext, see the in-notebook TFX Keras Component Tutorial.
Step10: Construct the InteractiveContext
Step11: Run your component interactively with context.run()
Next, we run our components interactively within the notebook with
context.run(). Our consumer component uses the outputs of the generator
component.
Step12: After execution, we can inspect the contents of the "hash" output artifact of
the consumer component on disk.
Step13: That's it, and you've now written and executed your own custom components!
Write a pipeline definition
Next, we will author a pipeline using these same components. While using the
InteractiveContext within a notebook works well for experimentation, defining
a pipeline lets you deploy your pipeline on local or remote runners for
production usage.
Here, we will demonstrate usage of the LocalDagRunner running locally on your
machine. For production execution, the Airflow or Kubeflow runners may
be more suitable.
Construct a pipeline
Step14: Run your pipeline with the LocalDagRunner
Step15: We can inspect the output artifacts generated by this pipeline execution. | 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
sys.version
Explanation: TFX Python function component tutorial
Note: We recommend running this tutorial in a Colab notebook, with no setup
required! Just click "Run in 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/python_function_component">
<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/tfx/blob/master/docs/tutorials/tfx/python_function_component.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/tfx/tree/master/docs/tutorials/tfx/python_function_component.ipynb">
<img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">View source on GitHub</a></td>
<td><a target="_blank" href="https://storage.googleapis.com/tensorflow_docs/tfx/docs/tutorials/tfx/python_function_component.ipynb">
<img width=32px src="https://www.tensorflow.org/images/download_logo_32px.png">Download notebook</a></td>
</table></div>
This notebook contains an examples on how to author and run Python function
components within the TFX InteractiveContext and in a locally-orchestrated TFX
pipeline.
For more context and information, see the Custom Python function components
page on the TFX documentation site.
Setup
We will first install TFX and import necessary modules. TFX requires Python 3.
Check the system Python version
End of explanation
try:
import colab
!pip install --upgrade pip
except:
pass
Explanation: Upgrade Pip
To avoid upgrading Pip in a system when running locally, check to make sure
that we're running in Colab. Local systems can of course be upgraded
separately.
End of explanation
!pip install -U tfx
Explanation: Install TFX
Note: In Google Colab, because of package updates, the first time you run
this cell you must restart the runtime (Runtime > Restart runtime ...).
End of explanation
# Check version
from tfx import v1 as tfx
tfx.__version__
Explanation: Did you restart the runtime?
If you are using Google Colab, the first time that you run the cell above, you
must restart the runtime (Runtime > Restart runtime ...). This is because of
the way that Colab loads packages.
Import packages
We import TFX and check its version.
End of explanation
%%writefile my_generator.py
import os
import tensorflow as tf # Used for writing files.
from tfx import v1 as tfx
# Non-public APIs, just for showcase.
from tfx.types.experimental.simple_artifacts import Dataset
@tfx.dsl.components.component
def MyGenerator(data: tfx.dsl.components.OutputArtifact[Dataset]):
Create a file with dummy data in the output artifact.
with tf.io.gfile.GFile(os.path.join(data.uri, 'data_file.txt'), 'w') as f:
f.write('Dummy data')
# Set metadata and ensure that it gets passed to downstream components.
data.set_string_custom_property('my_custom_field', 'my_custom_value')
Explanation: Custom Python function components
In this section, we will create components from Python functions. We will notbe
doing any real ML problem — these simple functions are just used to illustrate
the Python function component development process.
See Python function based component
guide
for more documentation.
Create Python custom components
We begin by writing a function that generate some dummy data. This is written
to its own Python module file.
End of explanation
%%writefile my_consumer.py
import hashlib
import os
import tensorflow as tf
from tfx import v1 as tfx
# Non-public APIs, just for showcase.
from tfx.types.experimental.simple_artifacts import Dataset
from tfx.types.standard_artifacts import String
@tfx.dsl.components.component
def MyConsumer(data: tfx.dsl.components.InputArtifact[Dataset],
hash: tfx.dsl.components.OutputArtifact[String],
algorithm: tfx.dsl.components.Parameter[str] = 'sha256'):
Reads the contents of data and calculate.
with tf.io.gfile.GFile(
os.path.join(data.uri, 'data_file.txt'), 'r') as f:
contents = f.read()
h = hashlib.new(algorithm)
h.update(tf.compat.as_bytes(contents))
hash.value = h.hexdigest()
# Read a custom property from the input artifact and set to the output.
custom_value = data.get_string_custom_property('my_custom_field')
hash.set_string_custom_property('input_custom_field', custom_value)
Explanation: Next, we write a second component that uses the dummy data produced.
We will just calculate hash of the data and return it.
End of explanation
from my_generator import MyGenerator
from my_consumer import MyConsumer
Explanation: Run in-notebook with the InteractiveContext
Now, we will demonstrate usage of our new components in the TFX
InteractiveContext.
For more information on what you can do with the TFX notebook
InteractiveContext, see the in-notebook TFX Keras Component Tutorial.
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.
from tfx.orchestration.experimental.interactive.interactive_context import InteractiveContext
context = InteractiveContext()
Explanation: Construct the InteractiveContext
End of explanation
generator = MyGenerator()
context.run(generator)
consumer = MyConsumer(
data=generator.outputs['data'],
algorithm='md5')
context.run(consumer)
Explanation: Run your component interactively with context.run()
Next, we run our components interactively within the notebook with
context.run(). Our consumer component uses the outputs of the generator
component.
End of explanation
!tail -v {consumer.outputs['hash'].get()[0].uri}
Explanation: After execution, we can inspect the contents of the "hash" output artifact of
the consumer component on disk.
End of explanation
import os
import tempfile
from tfx import v1 as tfx
# Select a persistent TFX root directory to store your output artifacts.
# For demonstration purposes only, we use a temporary directory.
PIPELINE_ROOT = tempfile.mkdtemp()
# Select a pipeline name so that multiple runs of the same logical pipeline
# can be grouped.
PIPELINE_NAME = "function-based-pipeline"
# We use a ML Metadata configuration that uses a local SQLite database in
# the pipeline root directory. Other backends for ML Metadata are available
# for production usage.
METADATA_CONNECTION_CONFIG = tfx.orchestration.metadata.sqlite_metadata_connection_config(
os.path.join(PIPELINE_ROOT, 'metadata.sqlite'))
def function_based_pipeline():
# Here, we construct our generator and consumer components in the same way.
generator = MyGenerator()
consumer = MyConsumer(
data=generator.outputs['data'],
algorithm='md5')
return tfx.dsl.Pipeline(
pipeline_name=PIPELINE_NAME,
pipeline_root=PIPELINE_ROOT,
components=[generator, consumer],
metadata_connection_config=METADATA_CONNECTION_CONFIG)
my_pipeline = function_based_pipeline()
Explanation: That's it, and you've now written and executed your own custom components!
Write a pipeline definition
Next, we will author a pipeline using these same components. While using the
InteractiveContext within a notebook works well for experimentation, defining
a pipeline lets you deploy your pipeline on local or remote runners for
production usage.
Here, we will demonstrate usage of the LocalDagRunner running locally on your
machine. For production execution, the Airflow or Kubeflow runners may
be more suitable.
Construct a pipeline
End of explanation
tfx.orchestration.LocalDagRunner().run(my_pipeline)
Explanation: Run your pipeline with the LocalDagRunner
End of explanation
!find {PIPELINE_ROOT}
Explanation: We can inspect the output artifacts generated by this pipeline execution.
End of explanation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.