markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Now here's the slope function:
def slope_func1(state, t, system): """Compute derivatives of the state. state: position, velocity t: time system: System object containing g, rho, C_d, area, and mass returns: derivatives of y and v """ y, v = state M, g = system.M, system.g a_drag = drag_f...
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
As always, let's test the slope function with the initial params.
slope_func1(system.init, 0, system)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
We'll need an event function to stop the simulation when we get to the end of the cord.
def event_func(state, t, system): """Run until y=-L. state: position, velocity t: time system: System object containing g, rho, C_d, area, and mass returns: difference between y and -L """ y, v = state return y + system.L
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
We can test it with the initial conditions.
event_func(system.init, 0, system)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
And then run the simulation.
results, details = run_ode_solver(system, slope_func1, events=event_func) details.message
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Here's how long it takes to drop 25 meters.
t_final = get_last_label(results)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Here's the plot of position as a function of time.
def plot_position(results, **options): plot(results.y, **options) decorate(xlabel='Time (s)', ylabel='Position (m)') plot_position(results)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
We can use min to find the lowest point:
min(results.y)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Here's velocity as a function of time:
def plot_velocity(results): plot(results.v, color='C1', label='v') decorate(xlabel='Time (s)', ylabel='Velocity (m/s)') plot_velocity(results)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Velocity when we reach the end of the cord.
min(results.v)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Although we compute acceleration inside the slope function, we don't get acceleration as a result from run_ode_solver. We can approximate it by computing the numerical derivative of v:
a = gradient(results.v) plot(a) decorate(xlabel='Time (s)', ylabel='Acceleration (m/$s^2$)')
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
The maximum downward acceleration, as a factor of g
max_acceleration = max(abs(a)) * m/s**2 / params.g
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Using Equation (1) from Heck, Uylings, and Kędzierska, we can compute the peak acceleration due to interaction with the cord, neglecting drag.
def max_acceleration(system): mu = system.mu return 1 + mu * (4+mu) / 8 max_acceleration(system)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
If you set C_d=0, the simulated acceleration approaches the theoretical result, although you might have to reduce max_step to get a good numerical estimate. Sweeping cord weight Now let's see how velocity at the crossover point depends on the weight of the cord.
def sweep_m_cord(m_cord_array, params): sweep = SweepSeries() for m_cord in m_cord_array: system = make_system(Params(params, m_cord=m_cord)) results, details = run_ode_solver(system, slope_func1, events=event_func) min_velocity = min(results.v) * m/s sweep[m_cord.magnitude] = m...
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Here's what it looks like. As expected, a heavier cord gets the jumper going faster. There's a hitch near 25 kg that seems to be due to numerical error.
plot(sweep) decorate(xlabel='Mass of cord (kg)', ylabel='Fastest downward velocity (m/s)')
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Phase 2 Once the jumper falls past the length of the cord, acceleration due to energy transfer from the cord stops abruptly. As the cord stretches, it starts to exert a spring force. So let's simulate this second phase. spring_force computes the force of the cord on the jumper:
def spring_force(y, system): """Computes the force of the bungee cord on the jumper: y: height of the jumper Uses these variables from system: y_attach: height of the attachment point L: resting length of the cord k: spring constant of the cord returns: force in N """ ...
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
The spring force is 0 until the cord is fully extended. When it is extended 1 m, the spring force is 40 N.
spring_force(-25*m, system) spring_force(-26*m, system)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
The slope function for Phase 2 includes the spring force, and drops the acceleration due to the cord.
def slope_func2(state, t, system): """Compute derivatives of the state. state: position, velocity t: time system: System object containing g, rho, C_d, area, and mass returns: derivatives of y and v """ y, v = state M, g = system.M, system.g a_drag = drag_f...
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
I'll run Phase 1 again so we can get the final state.
system1 = make_system(params) event_func.direction=-1 results1, details1 = run_ode_solver(system1, slope_func1, events=event_func) print(details1.message)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Now I need the final time, position, and velocity from Phase 1.
t_final = get_last_label(results1) init2 = results1.row[t_final]
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
And that gives me the starting conditions for Phase 2.
system2 = System(system1, t_0=t_final, init=init2)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Here's how we run Phase 2, setting the direction of the event function so it doesn't stop the simulation immediately.
event_func.direction=+1 results2, details2 = run_ode_solver(system2, slope_func2, events=event_func) print(details2.message) t_final = get_last_label(results2)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
We can plot the results on the same axes.
plot_position(results1, label='Phase 1') plot_position(results2, label='Phase 2')
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
And get the lowest position from Phase 2.
min(results2.y)
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
To see how big the effect of the cord is, I'll collect the previous code in a function.
def simulate_system2(params): system1 = make_system(params) event_func.direction=-1 results1, details1 = run_ode_solver(system1, slope_func1, events=event_func) t_final = get_last_label(results1) init2 = results1.row[t_final] system2 = System(system1, t_0=t_final, init=init2) resu...
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Now we can run both phases and get the results in a single TimeFrame.
results = simulate_system2(params); plot_position(results) params_no_cord = Params(params, m_cord=1*kg) results_no_cord = simulate_system2(params_no_cord); plot_position(results, label='m_cord = 75 kg') plot_position(results_no_cord, label='m_cord = 1 kg') savefig('figs/jump.png') min(results_no_cord.y) diff = mi...
notebooks/jump2.ipynb
AllenDowney/ModSimPy
mit
Categorical Variables
import pandas as pd df = pd.DataFrame({'salary': [103, 89, 142, 54, 63, 219], 'boro': ['Manhatten', 'Queens', 'Manhatten', 'Brooklyn', 'Brooklyn', 'Bronx']}) df pd.get_dummies(df) df = pd.DataFrame({'salary': [103, 89, 142, 54, 63, 219], 'boro': [0, 1, 0, 2, 2, 3]}) df pd.get_du...
Teaching Materials/Machine Learning/ml-training-intro/notebooks/04 - Preprocessing.ipynb
astro4dev/OAD-Data-Science-Toolkit
gpl-3.0
Exercise Apply dummy encoding and scaling to the "adult" dataset consisting of income data from the census. Bonus: visualize the data.
data = pd.read_csv("adult.csv", index_col=0) # %load solutions/load_adult.py
Teaching Materials/Machine Learning/ml-training-intro/notebooks/04 - Preprocessing.ipynb
astro4dev/OAD-Data-Science-Toolkit
gpl-3.0
Composing a pipeline from reusable, pre-built, and lightweight components This tutorial describes how to build a Kubeflow pipeline from reusable, pre-built, and lightweight components. The following provides a summary of the steps involved in creating and using a reusable component: Write the program that contains you...
import kfp import kfp.gcp as gcp import kfp.dsl as dsl import kfp.compiler as compiler import kfp.components as comp import datetime import kubernetes as k8s # Required Parameters PROJECT_ID='<ADD GCP PROJECT HERE>' GCS_BUCKET='gs://<ADD STORAGE LOCATION HERE>'
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Create client If you run this notebook outside of a Kubeflow cluster, run the following command: - host: The URL of your Kubeflow Pipelines instance, for example "https://&lt;your-deployment&gt;.endpoints.&lt;your-project&gt;.cloud.goog/pipeline" - client_id: The client ID used by Identity-Aware Proxy - other_client_id...
# Optional Parameters, but required for running outside Kubeflow cluster # The host for 'AI Platform Pipelines' ends with 'pipelines.googleusercontent.com' # The host for pipeline endpoint of 'full Kubeflow deployment' ends with '/pipeline' # Examples are: # https://7c021d0340d296aa-dot-us-central2.pipelines.googleuse...
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Build reusable components Writing the program code The following cell creates a file app.py that contains a Python script. The script downloads MNIST dataset, trains a Neural Network based classification model, writes the training log and exports the trained model to Google Cloud Storage. Your component can create outp...
%%bash # Create folders if they don't exist. mkdir -p tmp/reuse_components_pipeline/mnist_training # Create the Python file that lists GCS blobs. cat > ./tmp/reuse_components_pipeline/mnist_training/app.py <<HERE import argparse from datetime import datetime import tensorflow as tf parser = argparse.ArgumentParser()...
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Create a Docker container Create your own container image that includes your program. Creating a Dockerfile Now create a container that runs the script. Start by creating a Dockerfile. A Dockerfile contains the instructions to assemble a Docker image. The FROM statement specifies the Base Image from which you are buil...
%%bash # Create Dockerfile. # AI platform only support tensorflow 1.14 cat > ./tmp/reuse_components_pipeline/mnist_training/Dockerfile <<EOF FROM tensorflow/tensorflow:1.14.0-py3 WORKDIR /app COPY . /app EOF
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Build docker image Now that we have created our Dockerfile for creating our Docker image. Then we need to build the image and push to a registry to host the image. There are three possible options: - Use the kfp.containers.build_image_from_working_dir to build the image and push to the Container Registry (GCR). This re...
IMAGE_NAME="mnist_training_kf_pipeline" TAG="latest" # "v_$(date +%Y%m%d_%H%M%S)" GCR_IMAGE="gcr.io/{PROJECT_ID}/{IMAGE_NAME}:{TAG}".format( PROJECT_ID=PROJECT_ID, IMAGE_NAME=IMAGE_NAME, TAG=TAG ) APP_FOLDER='./tmp/reuse_components_pipeline/mnist_training/' # In the following, for the purpose of demonstr...
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
If you want to use docker to build the image Run the following in a cell ```bash %%bash -s "{PROJECT_ID}" IMAGE_NAME="mnist_training_kf_pipeline" TAG="latest" # "v_$(date +%Y%m%d_%H%M%S)" Create script to build docker image and push it. cat > ./tmp/components/mnist_training/build_image.sh <<HERE PROJECT_ID="${1}" IMAGE...
image_name = GCR_IMAGE
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Writing your component definition file To create a component from your containerized program, you must write a component specification in YAML that describes the component for the Kubeflow Pipelines system. For the complete definition of a Kubeflow Pipelines component, see the component specification. However, for this...
%%bash -s "{image_name}" GCR_IMAGE="${1}" echo ${GCR_IMAGE} # Create Yaml # the image uri should be changed according to the above docker image push output cat > mnist_pipeline_component.yaml <<HERE name: Mnist training description: Train a mnist model and save to GCS inputs: - name: model_path description: 'P...
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Define deployment operation on AI Platform
mlengine_deploy_op = comp.load_component_from_url( 'https://raw.githubusercontent.com/kubeflow/pipelines/1.4.0/components/gcp/ml_engine/deploy/component.yaml') def deploy( project_id, model_uri, model_id, runtime_version, python_version): return mlengine_deploy_op( model_uri=mo...
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Kubeflow serving deployment component as an option. Note that, the deployed Endppoint URI is not availabe as output of this component. ```python kubeflow_deploy_op = comp.load_component_from_url( 'https://raw.githubusercontent.com/kubeflow/pipelines/1.4.0/components/gcp/ml_engine/deploy/component.yaml') def deploy_...
def deployment_test(project_id: str, model_name: str, version: str) -> str: model_name = model_name.split("/")[-1] version = version.split("/")[-1] import googleapiclient.discovery def predict(project, model, data, version=None): """Run predictions on a list of instances. Args: ...
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Create your workflow as a Python function Define your pipeline as a Python function. @kfp.dsl.pipeline is a required decoration, and must include name and description properties. Then compile the pipeline function. After the compilation is completed, a pipeline file is created.
# Define the pipeline @dsl.pipeline( name='Mnist pipeline', description='A toy pipeline that performs mnist model training.' ) def mnist_reuse_component_deploy_pipeline( project_id: str = PROJECT_ID, model_path: str = 'mnist_model', bucket: str = GCS_BUCKET ): train_task = mnist_train_op( ...
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Submit a pipeline run
pipeline_func = mnist_reuse_component_deploy_pipeline experiment_name = 'minist_kubeflow' arguments = {"model_path":"mnist_model", "bucket":GCS_BUCKET} run_name = pipeline_func.__name__ + ' run' # Submit pipeline directly from pipeline function run_result = client.create_run_from_pipeline_func(pipeline...
courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Sebastian Raschka
import time print('Last updated: %s' %time.strftime('%d/%m/%Y'))
notebooks/bubble_sort.ipynb
babraham123/script-runner
mit
Sorting Algorithms Overview
import platform import multiprocessing def print_sysinfo(): print('\nPython version :', platform.python_version()) print('compiler :', platform.python_compiler()) print('\nsystem :', platform.system()) print('release :', platform.release()) print('machine :', ...
notebooks/bubble_sort.ipynb
babraham123/script-runner
mit
Bubble sort [back to top] Quick note about Bubble sort I don't want to get into the details about sorting algorithms here, but there is a great report "Sorting in the Presence of Branch Prediction and Caches - Fast Sorting on Modern Computers" written by Paul Biggar and David Gregg, where they describe and analyze elem...
print_sysinfo()
notebooks/bubble_sort.ipynb
babraham123/script-runner
mit
Bubble sort implemented in (C)Python
def python_bubblesort(a_list): """ Bubblesort in Python for list objects (sorts in place).""" length = len(a_list) for i in range(length): for j in range(1, length): if a_list[j] < a_list[j-1]: a_list[j-1], a_list[j] = a_list[j], a_list[j-1] return a_list
notebooks/bubble_sort.ipynb
babraham123/script-runner
mit
<br> Below is a improved version that quits early if no further swap is needed.
def python_bubblesort_improved(a_list): """ Bubblesort in Python for list objects (sorts in place).""" length = len(a_list) swapped = 1 for i in range(length): if swapped: swapped = 0 for ele in range(length-i-1): if a_list[ele] > a_list[ele + 1]: ...
notebooks/bubble_sort.ipynb
babraham123/script-runner
mit
Verifying that all implementations work correctly
import random import copy random.seed(4354353) l = [random.randint(1,1000) for num in range(1, 1000)] l_sorted = sorted(l) for f in [python_bubblesort, python_bubblesort_improved]: assert(l_sorted == f(copy.copy(l))) print('Bubblesort works correctly')
notebooks/bubble_sort.ipynb
babraham123/script-runner
mit
Performance comparison
# small list l_small = [random.randint(1,100) for num in range(1, 100)] l_small_cp = copy.copy(l_small) %timeit python_bubblesort(l_small) %timeit python_bubblesort_improved(l_small_cp) # larger list l_small = [random.randint(1,10000) for num in range(1, 10000)] l_small_cp = copy.copy(l_small) %timeit python_bubbl...
notebooks/bubble_sort.ipynb
babraham123/script-runner
mit
Does our model obey the theory?
sm.stats.durbin_watson(arma_mod30.resid) fig = plt.figure(figsize=(12,4)) ax = fig.add_subplot(111) ax = plt.plot(arma_mod30.resid) resid = arma_mod30.resid stats.normaltest(resid) fig = plt.figure(figsize=(12,4)) ax = fig.add_subplot(111) fig = qqplot(resid, line='q', ax=ax, fit=True) fig = plt.figure(figsize=(12...
v0.13.1/examples/notebooks/generated/statespace_arma_0.ipynb
statsmodels/statsmodels.github.io
bsd-3-clause
Create random values for x in interval [0,1)
random.seed(98103) n = 30 x = graphlab.SArray([random.random() for i in range(n)]).sort()
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Compute y
y = x.apply(lambda x: math.sin(4*x))
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Add random Gaussian noise to y
random.seed(1) e = graphlab.SArray([random.gauss(0,1.0/3.0) for i in range(n)]) y = y + e
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Put data into an SFrame to manipulate later
data = graphlab.SFrame({'X1':x,'Y':y}) data
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Create a function to plot the data, since we'll do it many times
def plot_data(data): plt.plot(data['X1'],data['Y'],'k.') plt.xlabel('x') plt.ylabel('y') plot_data(data)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Define some useful polynomial regression functions Define a function to create our features for a polynomial regression model of any degree:
def polynomial_features(data, deg): data_copy=data.copy() for i in range(1,deg): data_copy['X'+str(i+1)]=data_copy['X'+str(i)]*data_copy['X1'] return data_copy
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Define a function to fit a polynomial linear regression model of degree "deg" to the data in "data":
def polynomial_regression(data, deg): model = graphlab.linear_regression.create(polynomial_features(data,deg), target='Y', l2_penalty=0.,l1_penalty=0., validation_set=None,verbose=False) return model
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Define function to plot data and predictions made, since we are going to use it many times.
def plot_poly_predictions(data, model): plot_data(data) # Get the degree of the polynomial deg = len(model.coefficients['value'])-1 # Create 200 points in the x axis and compute the predicted value for each point x_pred = graphlab.SFrame({'X1':[i/200.0 for i in range(200)]}) y_pred = model...
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Create a function that prints the polynomial coefficients in a pretty way :)
def print_coefficients(model): # Get the degree of the polynomial deg = len(model.coefficients['value'])-1 # Get learned parameters as a list w = list(model.coefficients['value']) # Numpy has a nifty function to print out polynomials in a pretty way # (We'll use it, but it needs the parame...
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Fit a degree-2 polynomial Fit our degree-2 polynomial to the data generated above:
model = polynomial_regression(data, deg=2)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Inspect learned parameters
print_coefficients(model)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Form and plot our predictions along a grid of x values:
plot_poly_predictions(data,model)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Fit a degree-4 polynomial
model = polynomial_regression(data, deg=4) print_coefficients(model) plot_poly_predictions(data,model)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Fit a degree-16 polynomial
model = polynomial_regression(data, deg=16) print_coefficients(model)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Woah!!!! Those coefficients are crazy! On the order of 10^6.
plot_poly_predictions(data,model)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Above: Fit looks pretty wild, too. Here's a clear example of how overfitting is associated with very large magnitude estimated coefficients. # # Ridge Regression Ridge regression aims to avoid overfitting by adding a cost to the RSS term of standard least squares that depends on the 2-norm of the coefficients $\|w...
def polynomial_ridge_regression(data, deg, l2_penalty): model = graphlab.linear_regression.create(polynomial_features(data,deg), target='Y', l2_penalty=l2_penalty, validation_set=None,verbose=False) return model
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Perform a ridge fit of a degree-16 polynomial using a very small penalty strength
model = polynomial_ridge_regression(data, deg=16, l2_penalty=1e-25) print_coefficients(model) plot_poly_predictions(data,model)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Perform a ridge fit of a degree-16 polynomial using a very large penalty strength
model = polynomial_ridge_regression(data, deg=16, l2_penalty=100) print_coefficients(model) plot_poly_predictions(data,model)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Let's look at fits for a sequence of increasing lambda values
for l2_penalty in [1e-25, 1e-10, 1e-6, 1e-3, 1e0,1e2]: model = polynomial_ridge_regression(data, deg=16, l2_penalty=l2_penalty) print 'lambda = %.2e' % l2_penalty print_coefficients(model) print '\n' plt.figure() plot_poly_predictions(data,model) plt.title('Ridge, lambda = %.2e' % l2_penalty...
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Perform a ridge fit of a degree-16 polynomial using a "good" penalty strength We will learn about cross validation later in this course as a way to select a good value of the tuning parameter (penalty strength) lambda. Here, we consider "leave one out" (LOO) cross validation, which one can show approximates average me...
# LOO cross validation -- return the average MSE def loo(data, deg, l2_penalty_values): # Create polynomial features polynomial_features(data, deg) # Create as many folds for cross validatation as number of data points num_folds = len(data) folds = graphlab.cross_validation.KFold(data,num_folds...
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Run LOO cross validation for "num" values of lambda, on a log scale
l2_penalty_values = numpy.logspace(-4, 10, num=10) l2_penalty_mse,best_l2_penalty = loo(data, 16, l2_penalty_values)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Plot results of estimating LOO for each value of lambda
plt.plot(l2_penalty_values,l2_penalty_mse,'k-') plt.xlabel('$\L2_penalty$') plt.ylabel('LOO cross validation error') plt.xscale('log') plt.yscale('log')
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Find the value of lambda, $\lambda_{\mathrm{CV}}$, that minimizes the LOO cross validation error, and plot resulting fit
best_l2_penalty model = polynomial_ridge_regression(data, deg=16, l2_penalty=best_l2_penalty) print_coefficients(model) plot_poly_predictions(data,model)
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Lasso Regression Lasso regression jointly shrinks coefficients to avoid overfitting, and implicitly performs feature selection by setting some coefficients exactly to 0 for sufficiently large penalty strength lambda (here called "L1_penalty"). In particular, lasso takes the RSS term of standard least squares and adds ...
def polynomial_lasso_regression(data, deg, l1_penalty): model = graphlab.linear_regression.create(polynomial_features(data,deg), target='Y', l2_penalty=0., l1_penalty=l1_penalty, ...
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Explore the lasso solution as a function of a few different penalty strengths We refer to lambda in the lasso case below as "l1_penalty"
for l1_penalty in [0.0001, 0.01, 0.1, 10]: model = polynomial_lasso_regression(data, deg=16, l1_penalty=l1_penalty) print 'l1_penalty = %e' % l1_penalty print 'number of nonzeros = %d' % (model.coefficients['value']).nnz() print_coefficients(model) print '\n' plt.figure() plot_poly_predictio...
Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb
dkirkby/astroml-study
mit
Remap MEG channel types In this example, MEG data are remapped from one channel type to another. This is useful to: - visualize combined magnetometers and gradiometers as magnetometers or gradiometers. - run statistics from both magnetometers and gradiometers while working with a single type of channels.
# Author: Mainak Jas <mainak.jas@telecom-paristech.fr> # License: BSD-3-Clause import mne from mne.datasets import sample print(__doc__) # read the evoked data_path = sample.data_path() meg_path = data_path / 'MEG' / 'sample' fname = meg_path / 'sample_audvis-ave.fif' evoked = mne.read_evokeds(fname, condition='Lef...
stable/_downloads/709b65f447b790ec915e9d00176f0746/virtual_evoked.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
First, let's call remap gradiometers to magnometers, and plot the original and remapped topomaps of the magnetometers.
# go from grad + mag to mag and plot original mag virt_evoked = evoked.as_type('mag') evoked.plot_topomap(ch_type='mag', title='mag (original)', time_unit='s') # plot interpolated grad + mag virt_evoked.plot_topomap(ch_type='mag', time_unit='s', title='mag (interpolated from mag + grad)')
stable/_downloads/709b65f447b790ec915e9d00176f0746/virtual_evoked.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Now, we remap magnometers to gradiometers, and plot the original and remapped topomaps of the gradiometers
# go from grad + mag to grad and plot original grad virt_evoked = evoked.as_type('grad') evoked.plot_topomap(ch_type='grad', title='grad (original)', time_unit='s') # plot interpolated grad + mag virt_evoked.plot_topomap(ch_type='grad', time_unit='s', title='grad (interpolated from mag + grad)...
stable/_downloads/709b65f447b790ec915e9d00176f0746/virtual_evoked.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Import NGC 2516 low-mass star data.
ngc2516 = np.genfromtxt('data/ngc2516_Christophe_v3.dat') # data for this study from J&J (2012) irwin07 = np.genfromtxt('data/irwin2007.phot') # data from Irwin+ (2007) jeffr01 = np.genfromtxt('data/jeff_2001.tsv', delimiter=';', comments='#') # data from Jeffries+ (2001)...
Projects/ngc2516_spots/ngc2516_vs_pleiades.ipynb
gfeiden/Notebook
mit
Jackson et al. (2009) recommend a small correction to I-band magnitudes from Irwin et al. (2007) to place them on the same photometric scale as Jeffries et al. (2001), which they deem to be "better calibrated." Jackson & Jeffries (2012) suggest that the tabulated data (on Vizier) has been transformed to the "better cal...
irwinVI = (irwin07[:, 7] - irwin07[:, 8])*(1.0 - 0.153) + 0.300 irwin07[:, 8] = (1.0 - 0.0076)*irwin07[:, 8] + 0.080 irwin07[:, 7] = irwinVI + irwin07[:, 8]
Projects/ngc2516_spots/ngc2516_vs_pleiades.ipynb
gfeiden/Notebook
mit
~~Note that it is not immediately clear whether this correction should be applied to photometric data cataloged by Jackson & Jeffries (2012).~~ Reading through Irwin et al. (2007) and Jackson & Jeffries (2012), it appears that the transformations are largely performed to transform the Irwin+ photometric system (Johnson...
pleiades_s07 = np.genfromtxt('../pleiades_colors/data/Stauffer_Pleiades_litPhot.txt', usecols=(2, 3, 5, 6, 8, 9, 13, 14, 15)) pleiades_k14 = np.genfromtxt('../pleiades_colors/data/Kamai_Pleiades_cmd.dat', usecols=(0, 1, 2, 3, 4, 5)) iso_emp_k14 = np.genfromtxt('../pleiades_colors/data/Kamai_Pleiades_emp.iso') # empiri...
Projects/ngc2516_spots/ngc2516_vs_pleiades.ipynb
gfeiden/Notebook
mit
Adopt literature values for reddening, neglecting differential reddening across the Pleiades.
pl_dis = 5.61 pl_ebv = 0.034 pl_evi = 1.25*pl_ebv pl_evk = 2.78*pl_ebv pl_eik = pl_evk - pl_evi pl_av = 3.12*pl_ebv ng_dis = 7.95 ng_ebv = 0.12 ng_evi = 1.25*ng_ebv ng_evk = 2.78*ng_ebv ng_eik = ng_evk - ng_evi ng_av = 3.12*ng_ebv
Projects/ngc2516_spots/ngc2516_vs_pleiades.ipynb
gfeiden/Notebook
mit
Overlay the CMDs for each cluster, corrected for reddening and distance.
fig, ax = plt.subplots(1, 2, figsize=(12., 8.), sharex=True, sharey=True) for axis in ax: axis.grid(True) axis.tick_params(which='major', axis='both', length=15., labelsize=16.) axis.set_ylim(12., 5.) axis.set_xlim(0.5, 3.0) axis.set_xlabel('$(V - I_C)$', fontsize=20.) ax[0].set_ylabel('$M_V$', fo...
Projects/ngc2516_spots/ngc2516_vs_pleiades.ipynb
gfeiden/Notebook
mit
While the Stauffer et al (2007) and Jackson et al. (2009) samples lie a bit redward of the median sequence in the Jeffries et al. (2001), the former two samples compare well against the empirical cluster sequence (shown as a red dashed line; Kamai et al. 2014) from the Pleiades in a $M_V/(V-I_C)$ CMD. What about $M_V/...
fig, ax = plt.subplots(1, 2, figsize=(12., 8.), sharey=True) for axis in ax: axis.grid(True) axis.tick_params(which='major', axis='both', length=15., labelsize=16.) axis.set_ylim(12., 5.) ax[0].set_xlim(1.0, 6.0) ax[0].set_xlabel('$(V - K)$', fontsize=20.) ax[0].set_ylabel('$M_V$', fontsize=20.) # in...
Projects/ngc2516_spots/ngc2516_vs_pleiades.ipynb
gfeiden/Notebook
mit
While data in the $M_V/(V-I_C)$ CMD appears to be bluer for early M-dwarf stars and redder for later M-dwarf stars, we find that M-dwarfs in NGC 2516 appear to be generally bluer than low-mass stars in the Pleiades. An interesting implication is that empirical isochornes based on the Pleiades or NGC 2516 may not relia...
fig, ax = plt.subplots(1, 1, figsize=(6., 8.)) ax.grid(True) ax.tick_params(which='major', axis='both', length=15., labelsize=16.) ax.set_xlim(-0.5, 2.0) ax.set_ylim( 0.0, 2.5) ax.set_ylabel('$(V - I_C)$', fontsize=20.) ax.set_xlabel('$(B - V)$', fontsize=20.) ax.plot(jeffr01[:,4] - ng_ebv, jeffr01[:,5] - ng_evi, ...
Projects/ngc2516_spots/ngc2516_vs_pleiades.ipynb
gfeiden/Notebook
mit
The empirical isochrone from Kamai et al. (2014) agrees well with photometric data for NGC 2516, with both corrected for differential extinction. There may be some small disagreements at various locations along the sequence, but the morphology of the empirical isochrone is broadly consistent with NGC 2516. However, sta...
tmp_data = np.genfromtxt('data/irwin2007.phot') # re-load Irwin et al. (2007) data into new array
Projects/ngc2516_spots/ngc2516_vs_pleiades.ipynb
gfeiden/Notebook
mit
Now, applying transformation from Bessell (1979), which states that
old_vmi = tmp_data[:, 7] - tmp_data[:, 8] new_vmi = old_vmi*0.835 - 0.130 fig, ax = plt.subplots(1, 1, figsize=(6., 8.)) ax.grid(True) ax.tick_params(which='major', axis='both', length=15., labelsize=16.) ax.set_xlim(2.0, 3.0) ax.set_ylim(22., 16.) ax.set_xlabel('$(V - I_C)$', fontsize=20.) ax.set_ylabel('$M_V$', fon...
Projects/ngc2516_spots/ngc2516_vs_pleiades.ipynb
gfeiden/Notebook
mit
Visualize the Data
import matplotlib.pyplot as plt %matplotlib inline # obtain one batch of training images dataiter = iter(train_loader) images, labels = dataiter.next() images = images.numpy() # get one image from the batch img = np.squeeze(images[0]) fig = plt.figure(figsize = (5,5)) ax = fig.add_subplot(111) ax.imshow(img, cm...
DEEP LEARNING/Pytorch from scratch/TODO/Autoencoders/linear-autoencoder/Simple_Autoencoder_Solution.ipynb
Diyago/Machine-Learning-scripts
apache-2.0
Linear Autoencoder We'll train an autoencoder with these images by flattening them into 784 length vectors. The images from this dataset are already normalized such that the values are between 0 and 1. Let's start by building a simple autoencoder. The encoder and decoder should be made of one linear layer. The units th...
import torch.nn as nn import torch.nn.functional as F # define the NN architecture class Autoencoder(nn.Module): def __init__(self, encoding_dim): super(Autoencoder, self).__init__() ## encoder ## # linear layer (784 -> encoding_dim) self.fc1 = nn.Linear(28 * 28, encoding_dim) ...
DEEP LEARNING/Pytorch from scratch/TODO/Autoencoders/linear-autoencoder/Simple_Autoencoder_Solution.ipynb
Diyago/Machine-Learning-scripts
apache-2.0
Training Here I'll write a bit of code to train the network. I'm not too interested in validation here, so I'll just monitor the training loss and the test loss afterwards. We are not concerned with labels in this case, just images, which we can get from the train_loader. Because we're comparing pixel values in input ...
# specify loss function criterion = nn.MSELoss() # specify loss function optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # number of epochs to train the model n_epochs = 20 for epoch in range(1, n_epochs+1): # monitor training loss train_loss = 0.0 ################### # train the mode...
DEEP LEARNING/Pytorch from scratch/TODO/Autoencoders/linear-autoencoder/Simple_Autoencoder_Solution.ipynb
Diyago/Machine-Learning-scripts
apache-2.0
Checking out the results Below I've plotted some of the test images along with their reconstructions. For the most part these look pretty good except for some blurriness in some parts.
# obtain one batch of test images dataiter = iter(test_loader) images, labels = dataiter.next() images_flatten = images.view(images.size(0), -1) # get sample outputs output = model(images_flatten) # prep images for display images = images.numpy() # output is resized into a batch of images output = output.view(batch_s...
DEEP LEARNING/Pytorch from scratch/TODO/Autoencoders/linear-autoencoder/Simple_Autoencoder_Solution.ipynb
Diyago/Machine-Learning-scripts
apache-2.0
c) set rebound.units:
sim.units = ('yr', 'AU', 'Msun') print("G = {0}.".format(sim.G))
ipython_examples/Units.ipynb
dtamayo/rebound
gpl-3.0
When you set the units, REBOUND converts G to the appropriate value for the units passed (must pass exactly 3 units for mass length and time, but they can be in any order). Note that if you are interested in high precision, you have to be quite particular about the exact units. As an aside, the reason why G differs ...
sim.add('Earth') ps = sim.particles import math print("v = {0}".format(math.sqrt(ps[0].vx**2 + ps[0].vy**2 + ps[0].vz**2)))
ipython_examples/Units.ipynb
dtamayo/rebound
gpl-3.0
we see that the velocity is correctly set to approximately $2\pi$ AU/yr. If you'd like to enter the initial conditions in one set of units, and then use a different set for the simulation, you can use the sim.convert_particle_units function, which converts both the initial conditions and G. Since we added Earth above,...
sim = rebound.Simulation() sim.units = ('m', 's', 'kg') sim.add(m=1.99e30) sim.add(m=5.97e24,a=1.5e11) sim.convert_particle_units('AU', 'yr', 'Msun') sim.status()
ipython_examples/Units.ipynb
dtamayo/rebound
gpl-3.0
We first set the units to SI, added (approximate values for) the Sun and Earth in these units, and switched to AU, yr, $M_\odot$. You can see that the particle states were converted correctly--the Sun has a mass of about 1, and the Earth has a distance of about 1. Note that when you pass orbital elements to sim.add, y...
sim = rebound.Simulation() print("G = {0}".format(sim.G)) sim.add(m=1.99e30) sim.add(m=5.97e24,a=1.5e11) sim.status()
ipython_examples/Units.ipynb
dtamayo/rebound
gpl-3.0
1st Step: Construct Computational Graph Question 1: Prepare the input variables (x,y_label) of the computational graph Hint: You may use the function tf.placeholder()
# computational graph inputs batch_size = 100 d = train_data.shape[1] nc = 10 x = tf.placeholder(tf.float32,[batch_size,d]); print('x=',x,x.get_shape()) y_label = tf.placeholder(tf.float32,[batch_size,nc]); print('y_label=',y_label,y_label.get_shape())
algorithms/04_sol_tensorflow.ipynb
mdeff/ntds_2016
mit
Question 2: Prepare the variables (W,b) of the computational graph Hint: You may use the function tf.Variable(), tf.truncated_normal()
# computational graph variables initial = tf.truncated_normal([d,nc], stddev=0.1); W = tf.Variable(initial); print('W=',W.get_shape()) b = tf.Variable(tf.zeros([nc],tf.float32)); print('b=',b.get_shape())
algorithms/04_sol_tensorflow.ipynb
mdeff/ntds_2016
mit
Question 3: Compute the classifier such that $$ y=softmax(Wx +b) $$ Hint: You may use the function tf.matmul(), tf.nn.softmax()
# Construct CG / output value y = tf.matmul(x, W); print('y1=',y,y.get_shape()) y += b; print('y2=',y,y.get_shape()) y = tf.nn.softmax(y); print('y3=',y,y.get_shape())
algorithms/04_sol_tensorflow.ipynb
mdeff/ntds_2016
mit
Question 4: Construct the loss of the computational graph such that $$ loss = cross\ entropy(y_{label},y) = mean_{all\ data} \ \sum_{all\ classes} -\ y_{label}.\log(y) $$ Hint: You may use the function tf.Variable(), tf.truncated_normal()
# Loss cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_label * tf.log(y), 1))
algorithms/04_sol_tensorflow.ipynb
mdeff/ntds_2016
mit
Question 5: Construct the L2 regularization of (W,b) to the computational graph such that $$ R(W) = \|W\|_2^2\ R(b) = \|b\|_2^2 $$ Hint: You may use the function tf.nn.l2_loss()
reg_loss = tf.nn.l2_loss(W) reg_loss += tf.nn.l2_loss(b)
algorithms/04_sol_tensorflow.ipynb
mdeff/ntds_2016
mit
Question 6: Form the total loss $$ total\ loss = cross\ entropy(y_{label},y) + reg_par* (R(W) + R(b)) $$
reg_par = 1e-3 total_loss = cross_entropy + reg_par* reg_loss
algorithms/04_sol_tensorflow.ipynb
mdeff/ntds_2016
mit
Question 7: Perform optimization of the total loss for learning weight variables of the computational graph Hint: You may use the function tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)
# Update CG variables / backward pass train_step = tf.train.GradientDescentOptimizer(0.25).minimize(total_loss)
algorithms/04_sol_tensorflow.ipynb
mdeff/ntds_2016
mit
Question 8: Evaluate the accuracy Hint: You may use the function tf.equal(tf.argmax(y,1), tf.argmax(y_label,1)) and tf.reduce_mean()
# Accuracy correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_label,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
algorithms/04_sol_tensorflow.ipynb
mdeff/ntds_2016
mit