markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Let's run a tournament, playing each plan against every other, and returning a list of `[(plan, mean_game_points),...]`. I will also define `show` to pretty-print these results and display a histogram:
def tournament(plans): "Play each plan against each other; return a sorted list of [(plan: mean_points)]" rankdict = {A: mean_points(A, plans) for A in plans} return Counter(rankdict).most_common() def mean_points(A, opponents): "Mean points for A playing against all opponents (but not against itself)...
Top 10 of 1202 plans: ( 0, 3, 4, 7, 16, 24, 4, 34, 4, 4) 85.6% ( 5, 7, 9, 11, 15, 21, 25, 2, 2, 3) 84.1% ( 3, 5, 8, 10, 13, 1, 26, 30, 2, 2) 83.3% ( 2, 2, 6, 12, 2, 18, 24, 30, 2, 2) 83.3% ( 2, 8, 2, 2, 10, 18, 26, 26, 3, 3) 83.2% ( 3, 6, 7, 9, 11, 2, 27, 31, 2, 2) 83.2% ( 1, 1, ...
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
It looks like there are a few really bad plans in there. Let's just keep the top 1000 plans (out of 1202), and re-run the rankings:
plans = {A for (A, _) in rankings[:1000]} rankings = tournament(plans) show(rankings)
Top 10 of 1000 plans: ( 0, 3, 4, 7, 16, 24, 4, 34, 4, 4) 87.4% ( 5, 5, 5, 5, 5, 5, 27, 30, 6, 7) 84.8% ( 5, 5, 5, 5, 5, 5, 30, 30, 5, 5) 84.2% ( 3, 3, 5, 5, 7, 7, 30, 30, 5, 5) 84.1% ( 1, 2, 3, 4, 6, 16, 25, 33, 4, 6) 82.5% ( 2, 2, 2, 5, 5, 26, 26, 26, 3, 3) 82.4% ( 1, 1, ...
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
The top 10 plans are still winning over 80%, and the top plan remains `(0, 3, 4, 7, 16, 24, 4, 34, 4, 4)`. This is an interesting plan: it places most of the soldiers on castles 4+5+6+8, which totals only 23 points, so it needs to pick up 5 more points from the other castles (that have mostly 4 soldiers attacking each ...
def plotter(plans, X=range(41)): X = list(X) def mean_reward(c, s): return mean(reward(s, p[c], c+1) for p in plans) for c in range(10): plt.plot(X, [mean_reward(c, s) for s in X], '.-') plt.xlabel('Number of soldiers (on each of the ten castles)') plt.ylabel('Expected points won') plt.g...
_____no_output_____
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
For example, this says that for castle 10 (the orange line at top), there is a big gain in expected return as we increase from 0 to 4 soldiers, and after that the gains are relatively less steep. This plot is interesting, but I can't see how to directly read off a best plan from it. HillclimbingInstead I'll see if I ca...
def hillclimb(A, plans=plans, steps=1000): "Try to improve Plan A, repeat `steps` times; return new plan and total." m = mean_points(A, plans) for _ in range(steps): B = mutate(A) m, A = max((m, A), (mean_points(B, plans), B)) return A, m def mutate(plan): "Retur...
_____no_output_____
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
Let's see how well this works. Remember, the best plan so far had a score of `87.4%`. Can we improve on that?
hillclimb((0, 3, 4, 7, 16, 24, 4, 34, 4, 4))
_____no_output_____
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
We got an improvement. Let's see what happens if we start with other plans:
hillclimb((10, 10, 10, 10, 10, 10, 10, 10, 10, 10)) hillclimb((0, 1, 2, 3, 4, 18, 18, 18, 18, 18)) hillclimb((2, 3, 5, 5, 5, 20, 20, 20, 10, 10)) hillclimb((0, 0, 5, 5, 25, 3, 25, 3, 31, 3))
_____no_output_____
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
What if we hillclimb 20 times longer?
hillclimb((0, 3, 4, 7, 16, 24, 4, 34, 4, 4), steps=20000)
_____no_output_____
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
Opponent modellingTo have a chance of winning the second round of this contest, we have to predict what the other entries will be like. Nobody knows for sure, but I can hypothesize that the entries will be slightly better than the first round, and try to approximate that by hillclimbing from each of the first-round pl...
def hillclimbers(plans, steps=100): "Return a sorted list of [(improved_plan, mean_points), ...]" pairs = {hillclimb(plan, plans, steps) for plan in plans} return sorted(pairs, key=lambda pair: pair[1], reverse=True) # For example: hillclimbers({(26, 5, 5, 5, 6, 7, 26, 0, 0, 0), (25, 0, 0, 0,...
_____no_output_____
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
I will define `plans2` (and `rankings2`) to be my estimate of the entries for round 2:
%time rankings2 = hillclimbers(plans) plans2 = {A for (A, _) in rankings2} show(rankings2)
CPU times: user 6min 11s, sys: 3.21 s, total: 6min 14s Wall time: 6min 17s Top 10 of 1000 plans: ( 1, 4, 5, 15, 6, 21, 3, 31, 3, 11) 90.8% ( 0, 3, 5, 14, 7, 21, 3, 30, 4, 13) 90.6% ( 0, 4, 6, 15, 9, 21, 4, 31, 5, 5) 90.2% ( 2, 4, 3, 13, 5, 22, 3, 32, 4, 12) 90.1% ( 0, 3, 5, 15, 8, 21, 4, 32...
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
Even though we only took 100 steps, the `plans2` plans are greatly improved: Almost all of them defeat 75% or more of the first-round `plans`. The top 10 plans are all very similar, targeting castles 4+6+8+10 (for 28 points), but reserving 20 or soldiers to spread among the other castles. Let's look more carefully at ...
for (p, m) in rankings2[::40] + [rankings2[-1]]: print(pplan(p), pct(m))
( 1, 4, 5, 15, 6, 21, 3, 31, 3, 11) 90.8% ( 0, 6, 3, 13, 3, 22, 2, 32, 4, 15) 88.9% ( 1, 3, 6, 13, 9, 22, 1, 30, 4, 11) 88.3% ( 2, 2, 1, 13, 3, 21, 2, 32, 3, 21) 87.9% ( 0, 2, 5, 5, 15, 2, 28, 31, 5, 7) 87.6% ( 2, 2, 4, 14, 9, 1, 27, 30, 6, 5) 87.3% ( 3, 2, 3, 12, 3, 28, 3, 32,...
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
We see a wider variety in plans as we go farther down the rankings. Now for the plot:
plotter(plans2)
_____no_output_____
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
We see that many castles (e.g. 9 (green), 8 (blue), 7 (black), 6 (yellowish)) have two plateaus. Castle 7 (black) has a plateau at 3.5 points for 6 to 20 soldiers (suggesting that 6 soldiers is a good investment and 20 soldiers a bad investment), and then another plateau at 7 points for everything above 30 soldiers.Now...
%time rankings3 = hillclimbers(plans2) show(rankings3)
CPU times: user 5min 40s, sys: 1 s, total: 5min 41s Wall time: 5min 42s Top 10 of 1000 plans: ( 3, 8, 10, 18, 21, 3, 5, 6, 10, 16) 99.9% ( 1, 9, 10, 17, 21, 6, 4, 6, 9, 17) 99.9% ( 1, 8, 10, 18, 21, 4, 4, 6, 11, 17) 99.9% ( 0, 10, 10, 17, 20, 4, 5, 6, 7, 21) 99.9% ( 2, 11, 1, 16, 18, 7, 6, 6, ...
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
We can try even harder to improve the champ:
champ, _ = rankings3[0] hillclimb(champ, plans2, 10000)
_____no_output_____
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
Here are some champion plans from previous runs of this notebook:
champs = { (0, 1, 3, 16, 20, 3, 4, 5, 32, 16), (0, 1, 9, 16, 15, 24, 5, 5, 8, 17), (0, 1, 9, 16, 16, 24, 5, 5, 7, 17), (0, 2, 9, 16, 15, 24, 5, 5, 8, 16), (0, 2, 9, 16, 15, 25, 5, 4, 7, 17), (0, 3, 4, 7, 16, 24, 4, 34, 4, 4), (0, 3, 5, 6, 20, 4, 4, 33, 8, 17), (0, 4, 5, 7, 20, 4, 4, 33, 7, 16), (0, 4, 6, 7, 19...
_____no_output_____
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
We can evaluate each of them against the original `plans`, against the improved `plans2`, against their fellow champs, and against all of those put together:
def μ(plan, plans): return pct(mean_points(plan,plans)) all = plans | plans2 | champs print('Plan plans plans2 champs all') for p in sorted(champs, key=lambda p: -mean_points(p, all)): print(pplan(p), μ(p, plans), μ(p, plans2), μ(p, champs), μ(p, all))
Plan plans plans2 champs all ( 0, 5, 7, 3, 18, 4, 4, 34, 8, 17) 85.5% 96.0% 68.5% 90.2% ( 0, 4, 6, 7, 19, 4, 4, 31, 8, 17) 84.7% 95.0% 63.0% 89.2% ( 0, 1, 3, 16, 20, 3, 4, 5, 32, 16) 85.6% 95.2% 31.5% 89.0% ( 0, 3, 5, 6, 20, 4, 4, 33, 8, 17) 84.1...
MIT
ipynb/Riddler Battle Royale.ipynb
mikiec84/pytudes
Individual EDA- Separate the states into 4 regions: Western, southern, eastern and northern.- Filter data based on assigned regions and explore with support from visualization- North East and South is the main focus in this EDA.___ Data Filtering
import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt # Add scripts module's directory to sys.path import sys, os sys.path.append(os.path.join(os.getcwd(),"..")) from scripts import project_functions as pf # Load 4 parts of raw data on State Names state_df = pf.load_and_process_m...
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
___ Initial inspectionLet's have a general of the data set for each region. North East region
n_df.head(10) n_df.shape
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
For the North East, we see that there are **more than 1 million collected record** and **5 variable for each observation**.
n_df.columns
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
Indeed, we have 5 variables for each observation. **The state column is not important since we care only about regions.**
n_df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1077888 entries, 0 to 1077887 Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Name 1077888 non-null object 1 Year 1077888 non-null int64 2 Gender 1077888 non-null object 3 State 10778...
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
We see Year and Count are 64-bit integers type while other columns are categorial types.
n_df.describe(include=[object]).T
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
For categorial data:- We see that there are 3 categorical variable in the dataframe with other 2 numerical variable (Year and Count)- Here, we can see that are 15817 unique names in this region- There are 11 states recorded that equal to total number of states in this region. This means all states participates in this ...
n_df.describe().T
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
Summary on numerical values do not give any useful information.
n_df["Year"].unique()
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
The data set span from 1910 to 2014 without any missing years.
len(n_df.loc[n_df["Count"]<=0])
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
This shows that we do not have negative values for names'count. South region
s_df.head(10) s_df.shape
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
For the South, we see that there are **more than 2 million collected record** and **5 variable for each observation**.
# We have 5 variables for each observation s_df.columns
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
This is similar to that of North East region.
s_df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 2173021 entries, 0 to 2173020 Data columns (total 5 columns): # Column Dtype --- ------ ----- 0 Name object 1 Year int64 2 Gender object 3 State object 4 Count int64 dtypes: int64(2), object(3) memory usage: 82.9+ MB
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
The type of each column is also similar to that of North East dataset.
s_df.describe(include=[object]).T
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
For categorial data:- We see that there are 3 categorical variable in the dataframe with other 2 numerical variable (Year and Count)- Here, we can see that are 20860 unique names in this region- There are 17 states recorded that equal to total number of states in this region. This means all states participates in this ...
s_df.describe().T
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
Summary on numerical values do not give any useful information.
s_df.loc[s_df["Count"]<=0]
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
This shows that we do not have negative values for names'count.
s_df["Year"].unique()
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
The data set also spans from 1910 to 2014 without gaps! ___ Analysis Top 5 of all times in South and North We start by aggregating sum of counts of every name in each region for all years.
# Define processing function def get_top5_all_time(data=None): if data is None: return data return (data.groupby(by="Name") .aggregate("sum") .drop(columns=["Year"]) # We do not analyze with time .reset_index() .sort_values(by="Count", ascending=Fa...
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
The code works properly to return top 5 all times in these two regions. Now, we can build plots. In this case, for counting the number of occurence for each discrete entry, bar plots is ideal.
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12,7), sharex=True) # Check similarity between 2 regions sns.set_theme(context="notebook", style="ticks", font_scale=1.3) def get_top5_all_time(data, ax, region): plot = sns.barplot(y="Name", x="Count", data=data, or...
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
Observations- We can see that top 5 in these 2 regions are quite similar with the appearance of **James, William, Robert and John**. The difference is that **Michael** is in top 5 in the North East while **Mary** is in the top 5 in the South.- All names in top 5 list in both region pass the mark of **1 million** coun...
# Function for filter data based on gender def get_top5_gender(data, region, gender): return (data.loc[data["Gender"] == gender] .groupby(by="Name") .agg(np.sum) .sort_values(by="Count", ascending=False) .head() .dro...
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
Now, we can plot. In this case, we will will bar plot to indicate counts and FacetGrid as way to categorize plot based on region and gender.
# Settings sns.set_theme(style="ticks", font_scale=1.3) fig,ax= plt.subplots(1,2, figsize=(12,7), sharex=True) def draw_gender_plot(axes, data_list, result_axes=None): if result_axes is None: result_axes = list() for i in range(len(ax)): data = data_list[i] ax_ij = sns.barplot(x="Count"...
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
Observation- Interestingly, two regions have the same names in the top 5 male names all times. This might result from the fact that these two regions are close to each other.- However, the pattern is different. In the **North East**, **John is most occuring name** with over 1.5 million counts. In the **South**, **Jame...
fig, ax = plt.subplots(1,2, figsize=(12,7), sharex=True) draw_gender_plot(ax,[top5_female_n,top5_female_s]) # Configure figure object sns.despine() fig.tight_layout(pad=2.7) fig.suptitle("Top 5 female names of all times in North East and South Region") plt.show()
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
Observations- Even more interesting, the top 5 female names see Mary at top for both region. **Mary's count is almost double that of other names in the list.**- The two list seems similar with the appearance of Mary, Patricia, Elizabeth. Unlike male top 5, **this list differs by 2 names between two region**. In the N...
def get_proportion_df(data, region): p_df = (data.pivot_table(index="Year", columns="Name", values="Count", aggfunc="sum") .fillna(0) ) y = data.groupby(by="Year").sum() for year in range(1910...
_____no_output_____
MIT
analysis/Jamie/milestones2_EDA.ipynb
data301-2020-winter2/course-project-group_1039
PyTorch Training and Serving in SageMaker "Script Mode"Script mode is a training script format for PyTorch that lets you execute any PyTorch training script in SageMaker with minimal modification. The [SageMaker Python SDK](https://github.com/aws/sagemaker-python-sdk) handles transferring your script to a SageMaker tr...
!pip install sagemaker --upgrade --ignore-installed --no-cache --user !pip install torch==1.3.1 torchvision==0.4.2 --upgrade --ignore-installed --no-cache --user
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Forcing `pillow==6.2.1` due to https://discuss.pytorch.org/t/cannot-import-name-pillow-version-from-pil/66096
!pip uninstall -y pillow !pip install pillow==6.2.1 --upgrade --ignore-installed --no-cache --user
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Restart the Kernel to Recognize New Dependencies Above
from IPython.display import display_html display_html("<script>Jupyter.notebook.kernel.restart()</script>", raw=True) !pip3 list
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Create the SageMaker Session
import os import sagemaker from sagemaker import get_execution_role sagemaker_session = sagemaker.Session()
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Setup the Service Execution Role and RegionGet IAM role arn used to give training and hosting access to your data. See the documentation for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the `sagemaker.get_execution_role()` with a the ap...
role = get_execution_role() print('RoleARN: {}\n'.format(role)) region = sagemaker_session.boto_session.region_name print('Region: {}'.format(region))
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Training Data Copy the Training Data to Your Notebook Disk
local_data_path = './data' from torchvision import datasets, transforms normalization_mean = 0.1307 normalization_std = 0.3081 # download the dataset # this will not only download data to ./mnist folder, but also load and transform (normalize) them datasets.MNIST(local_data_path, download=True, transform=transforms.C...
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Upload the Data to S3 for Distributed Training Across Many WorkersWe are going to use the `sagemaker.Session.upload_data` function to upload our datasets to an S3 location. The return value inputs identifies the location -- we will use later when we start the training job.This is S3 bucket and prefix that you want to ...
bucket = sagemaker_session.default_bucket() data_prefix = 'sagemaker/pytorch-mnist/data' training_data_uri = sagemaker_session.upload_data(path=local_data_path, bucket=bucket, key_prefix=data_prefix) print('Input spec (S3 path): {}'.format(training_data_uri)) !aws s3 ls --recursive {training_data_uri}
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Train Training ScriptThe `mnist_pytorch.py` script provides all the code we need for training and hosting a SageMaker model (`model_fn` function to load a model).The training script is very similar to a training script you might run outside of SageMaker, but you can access useful properties about the training environm...
!ls ./src/mnist_pytorch.py
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
You can add custom Python modules to the `src/requirements.txt` file. They will automatically be installed - and made available to your training script.
!cat ./src/requirements.txt
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Train with SageMaker `PyTorch` EstimatorThe `PyTorch` class allows us to run our training function as a training job on SageMaker infrastructure. We need to configure it with our training script, an IAM role, the number of training instances, the training instance type, and hyperparameters. In this case we are going...
from sagemaker.pytorch import PyTorch import time model_output_path = 's3://{}/sagemaker/pytorch-mnist/training-runs'.format(bucket) mnist_estimator = PyTorch( entry_point='mnist_pytorch.py', source_dir='./src', output_path=model_output_path, rol...
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Attach to a training job to monitor the logs._Note: Each instance in the training job (2 in this example) will appear as a different color in the logs. 1 color per instance._
mnist_estimator = PyTorch.attach(training_job_name=training_job_name)
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Option 1: Perform Batch Predictions Directly in the Notebook Use PyTorch Core to load the model from `model_output_path`
!aws --region {region} s3 ls --recursive {model_output_path}/{training_job_name}/output/ !aws --region {region} s3 cp {model_output_path}/{training_job_name}/output/model.tar.gz ./model/model.tar.gz !ls ./model !tar -xzvf ./model/model.tar.gz -C ./model # Based on https://github.com/pytorch/examples/blob/master/mnist/m...
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Option 2: Create a SageMaker Endpoint and Perform REST-based Predictions Deploy the Trained Model to a SageMaker Endpoint (Approx. 10 mins)After training, we use the `PyTorch` estimator object to build and deploy a `PyTorchPredictor`. This creates a Sagemaker Endpoint -- a hosted prediction service that we can use t...
predictor = mnist_estimator.deploy(initial_instance_count=1, instance_type='ml.c5.2xlarge')
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Invoke the EndpointWe can now use this predictor to classify hand-written digits. Drawing into the image box loads the pixel data into a `data` variable in this notebook, which we can then pass to the `predictor`.
from IPython.display import HTML HTML(open("input.html").read())
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
The value of `data` is retrieved from the HTML above.
print(data) import numpy as np image = np.array([data], dtype=np.float32) response = predictor.predict(image) prediction = response.argmax(axis=1)[0] print(prediction)
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
(Optional) Cleanup EndpointAfter you have finished with this example, remember to delete the prediction endpoint to release the instance(s) associated with it
sagemaker.Session().delete_endpoint(predictor.endpoint)
_____no_output_____
Apache-2.0
07_train/archive/extras/pytorch/pytorch_mnist.ipynb
MarcusFra/workshop
Train a Plane Detection Model from Voxel51 DatasetThis notebook trains a plane detection model using transfer learning. Depending on the label used, it can just detect a plane or it can try to detect the model of the plane.A pre-trained model is used as a starting point. This means that fewer example images are needed...
training_name="881images-efficientdet-d0-model" # The name for the model. All of the different directories will be based on this label_field = "detections" # The field from the V51 Samples around which will be used for the Labels for training. dataset_name = "jsm-test-dataset" # The name of the V51 dataset that will b...
Reading package lists... Done Building dependency tree Reading state information... Done protobuf-compiler is already the newest version (3.0.0-9.1ubuntu1). libgl1-mesa-glx is already the newest version (20.0.8-0ubuntu1~18.04.1). wget is already the newest version (1.19.4-1ubuntu2.2). 0 upgraded, 0 newly install...
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Download and Install TF ModelsThe TF Object Detection API is available here: https://github.com/tensorflow/models
import os import pathlib # Clone the tensorflow models repository if it doesn't already exist if "models" in pathlib.Path.cwd().parts: while "models" in pathlib.Path.cwd().parts: os.chdir('..') elif not pathlib.Path('models').exists(): # pull v2.5.0 of tensorflow models to make deterministic !git clone --...
_____no_output_____
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Export the Training and Val Dataset from Voxel 51
import fiftyone as fo import math dataset = fo.load_dataset(dataset_name)
_____no_output_____
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Explore the dataset contentHere are some basic stats on the Voxel51 dataset you are going to build training the model on. An example of the samples is also printed out. In the Sample, make sure the *label_field* you selected has some detections in it.
print("\t\tDataset\n-----------------------------------") view = dataset.match_tags("training").shuffle(seed=51) # You can add additional things to the query to further refine it. eg .match_tags("good_box") print(view) print("\n\n\tExample Sample\n-----------------------------------") print(view.first())
Dataset ----------------------------------- Dataset: jsm-test-dataset Media type: image Num samples: 881 Tags: ['capture-3-29', 'capture-3-30', 'capture-5-13', 'training'] Sample fields: id: fiftyone.core.fields.ObjectIdField filepath: fiftyone.core.fields.StringField...
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Export the dataset into TFRecordsThe selected dataset samples will be exported to TensorFlow Records (TFRecords). They will be split between Training and Validation. The ratio can be adjusted below. You only need to do this once to build the dataset. If you run this a second time with the same **model_name** additiona...
# The Dataset or DatasetView to export sample_len = len(view) val_len = math.floor(sample_len * 0.2) train_len = math.floor(sample_len * 0.8) print("Total: {} Val: {} Train: {}".format(sample_len,val_len,train_len)) val_view = view.take(val_len) train_view = view.skip(val_len).take(train_len) # Export the dataset val_v...
Total: 881 Val: 176 Train: 704 100% |█████████████████| 176/176 [4.1s elapsed, 0s remaining, 52.9 samples/s] 100% |█████████████████| 704/704 [13.2s elapsed, 0s remaining, 54.4 samples/s]
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Create a file with the Labels for the objectsThe TF2 Object Detection API looks for a map of the labels used and a corresponding Id. You can build a list of the unique classnames by itterating the dataset. You can also just hardcode it if there only a few.
def convert_classes(classes, start=1): msg = StringIntLabelMap() for id, name in enumerate(classes, start=start): msg.item.append(StringIntLabelMapItem(id=id, name=name)) text = str(text_format.MessageToBytes(msg, as_utf8=True), 'utf-8') return text # If labelfield is a classification class_nam...
item { name: "plane" id: 1 }
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Download a pretrained Model & default ConfigA list of the models can be found here: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.mdThe configs are here: https://raw.githubusercontent.com/tensorflow/models/master/research/object_detection/configs/tf2/
#download pretrained weights %mkdir /tf/models/research/deploy/ %cd /tf/models/research/deploy/ import tarfile download_tar = 'http://download.tensorflow.org/models/object_detection/tf2/20200711/' + pretrained_checkpoint !wget {download_tar} tar = tarfile.open(pretrained_checkpoint) tar.extractall() tar.close() #downl...
/tf/models/research/deploy --2021-07-08 20:52:50-- https://raw.githubusercontent.com/tensorflow/models/master/research/object_detection/configs/tf2/ssd_efficientdet_d0_512x512_coco17_tpu-8.config Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.110.133, 185.199.111.133, ... C...
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Build the Config for trainingThe default config for the model being trained needs to be updated with the correct parameters and paths to the data. This just adds some standard settings, you may need to do some additional tuning if the training is not working well.
# Gets the total number of classes from the Label Map def get_num_classes(pbtxt_fname): from object_detection.utils import label_map_util label_map = label_map_util.load_labelmap(pbtxt_fname) categories = label_map_util.convert_label_map_to_categories( label_map, max_num_classes=90, use_display_nam...
working with 1 classes
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
You may need to adjust the learning rate section below. The number used here are from the EfficentDet config. I noticed that this learning rate worked well for the small bounding boxes I was using when planes were at a high altitude. You can try increasing it if the planes take up more of the image. If the initial loss...
# write custom configuration file by slotting our dataset, model checkpoint, and training parameters into the base pipeline file import re %cd /tf/models/research/deploy print('writing custom configuration file') with open(pipeline_fname) as f: s = f.read() with open('pipeline_file.config', 'w') as f: #...
# SSD with EfficientNet-b0 + BiFPN feature extractor, # shared box predictor and focal loss (a.k.a EfficientDet-d0). # See EfficientDet, Tan et al, https://arxiv.org/abs/1911.09070 # See Lin et al, https://arxiv.org/abs/1708.02002 # Trained on COCO, initialized from an EfficientNet-b0 checkpoint. # # Train on TP...
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Train Custom TF2 Object DetectorThis step will launch the TF2 Object Detection training. It can take a while to start-up. If you get an error about not finding the GPU, try shutting down the Jupyter kernel and restarting it.While it is running, it should print out the Current Loss and which Step it is on.* pipeline_fi...
# 2:48 PM ET Tuesday, May 25, 2021 !python /tf/models/research/object_detection/model_main_tf2.py \ --pipeline_config_path={pipeline_file} \ --model_dir={model_dir} \ --alsologtostderr \ --num_train_steps={num_steps} \ --sample_1_of_n_eval_examples=1 \ --num_eval_steps={num_eval_steps}
2021-07-08 20:53:56.154660: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudart.so.11.0 2021-07-08 20:53:59.234024: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcuda.so.1 2021-07-08 20:53:59.259096: I ten...
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Evaluate trained modelAfter the model has finished training, try running it against some data to see if it atleast works.
import matplotlib import matplotlib.pyplot as plt import io, os, glob import scipy.misc import numpy as np from six import BytesIO from PIL import Image, ImageDraw, ImageFont import tensorflow as tf from object_detection.utils import label_map_util from object_detection.utils import config_util from object_detectio...
_____no_output_____
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Load model from a training checkpointSelect a checkpoint index from above
# generally you want to put the last ckpt index from training in here checkpoint_index=41 # recover our saved model pipeline_config = pipeline_file checkpoint = model_dir + "ckpt-" + str(checkpoint_index) configs = config_util.get_configs_from_pipeline_file(pipeline_config) model_config = configs['model'] detection_m...
_____no_output_____
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Export the modelWhen you have a working model, use the TF2 Object Detection API to export it to a saved model. Export a Saved Model that uses Image Tensors
image_tensor_model_export_dir = model_export_dir + "image_tensor_saved_model" print(image_tensor_model_export_dir) !python /tf/models/research/object_detection/exporter_main_v2.py \ --input_type image_tensor \ --trained_checkpoint_dir={model_dir} \ --pipeline_config_path={pipeline_file} \ --output_direc...
2021-06-28 23:00:37.233618: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudart.so.11.0 2021-06-28 23:00:39.839076: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcuda.so.1 2021-06-28 23:00:39.864436: I ten...
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Export a Saved Model that uses TF Examples
# Ignore for now - we do not need to use the TF Example approach. #tf_example_model_export_dir = model_export_dir + "tf_example_saved_model" #!python /tf/models/research/object_detection/exporter_main_v2.py \ # --input_type=tf_example \ # --trained_checkpoint_dir={model_dir} \ # --pipeline_config_path={pipeli...
_____no_output_____
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Export a TFLite compatible modelRemeber that only Detection models that use SSDs are supported
!python /tf/models/research/object_detection/export_tflite_graph_tf2.py \ --pipeline_config_path={pipeline_file} \ --trained_checkpoint_dir={model_dir} \ --output_directory={model_export_dir}tflite-compatible # I think we skip this step... #! tflite_convert \ # --saved_model_dir="{model_export_dir}tflite-com...
_____no_output_____
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Export a TensorJS compatible modelFrom: https://www.tensorflow.org/js/tutorials/conversion/import_saved_model
!pip install tensorflowjs ! tensorflowjs_converter \ --input_format=tf_saved_model \ {model_export_dir}image_tensor_saved_model/saved_model \ {model_export_dir}web_model !saved_model_cli show --dir /tf/models/research/deploy/ssd_mobilenet_v2_320x320_coco17_tpu-8/saved_model --all
_____no_output_____
Apache-2.0
ml-model/notebooks/Train Plane Detection Model.ipynb
wiseman/SkyScan
Python Homework 1 - The challengeTake the python challenge found on www.pythonchallenge.com/.You will copy this notebook. Rename it as:YOURLASTNAME-FIRSTINITIAL-python-challenge-xx-Sept-2017with your name replacing your last name and first initial and the xx replaced by the date you started or submitted.Do the first ...
#http://www.pythonchallenge.com/pc/def/0.html print(2**38) print(pow(2,38)) #http://www.pythonchallenge.com/pc/def/map.html
274877906944 274877906944
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 2 I changed the URL to "http://www.pythonchallenge.com/pc/def/274877906944.html" which redirected to "http://www.pythonchallenge.com/pc/def/map.html". This challenge has a picture with letters on i and a text below it. It can be seen that the letters on the right are two characters after the ...
#http://www.pythonchallenge.com/pc/def/274877906944.html #http://www.pythonchallenge.com/pc/def/map.html import string inp="abcdefghijklmnopqrstuvwxyz" outp="cdefghijklmnopqrstuvwxyzab" trans=str.maketrans(inp, outp) strg = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq ...
i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url. ocr
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 3 I then changed the URL to "http://www.pythonchallenge.com/pc/def/ocr.html". This challenge shows a picture of a book and it says to recognize the characters, giving a clue to check the page source. When I checked it, I found big block of characters in the page source which I thought should...
#http://www.pythonchallenge.com/pc/def/ocr.html import urllib.request url_ocr = urllib.request.urlopen("http://www.pythonchallenge.com/pc/def/ocr.html").read().decode() #print(url_ocr) import re content = re.findall("<!--(.*?)-->", url_ocr, re.S)[-1] #findall() matches all occurrences of a pattern ...
['e', 'q', 'u', 'a', 'l', 'i', 't', 'y']
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 4 Then, I changed the URL to "http://www.pythonchallenge.com/pc/def/equality.html" and there is text which says "One small letter, surrounded by EXACTLY three big bodyguards on each of its sides". I checked the page source to find any other clues and there is a big block of text, just as prev...
#http://www.pythonchallenge.com/pc/def/equality.html import urllib.request url_eq = urllib.request.urlopen("http://www.pythonchallenge.com/pc/def/equality.html").read().decode() import re data = re.findall("<!--(.*?)-->", url_eq, re.S)[-1] #findall() matches all occurrences of a pattern ...
['l', 'i', 'n', 'k', 'e', 'd', 'l', 'i', 's', 't'] linkedlist
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 5 For the next challenge, I changed the URL to "http://www.pythonchallenge.com/pc/def/linkedlist.html" but it showed text "linkedlist.php". So, I changed the URL to "http://www.pythonchallenge.com/pc/def/linkedlist.php". When I checked the page source, it has "urllib may help. DON'T TRY ALL N...
#http://www.pythonchallenge.com/pc/def/linkedlist.php import urllib import re url_ll = ("http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s") num="12345" #num=16044/2 while num!="": data = urllib.request.urlopen(url_ll % num).read().decode() #print(data) num = "".join(re.findall("and the nex...
Came to an End and the next nothing is 25357 and the next nothing is 89879 and the next nothing is 80119 and the next nothing is 50290 and the next nothing is 9297 and the next nothing is 30571 and the next nothing is 7414 and the next nothing is 30978 and the next nothing is 16408 and the next nothing is 80109 and the...
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 6 For the next challenge, I changed the URL to "http://www.pythonchallenge.com/pc/def/peak.html" which showed a picture of a hill with the text “pronounce it”. When I checked the page source, it showed some text "peak hell sounds familiar ?" and a file named "banner.p" which again took me to ...
#http://www.pythonchallenge.com/pc/def/peak.html import urllib.request url_ban = urllib.request.urlopen("http://www.pythonchallenge.com/pc/def/banner.p") import pickle data = pickle.load(url_ban) #Reads a pickled object representation from the open file object given in the constructor, and return the reconstituted o...
##### ##### #### #### #### ...
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 7 For the next challenge, I changed the URL to "http://www.pythonchallenge.com/pc/def/channel.html" and it showed a picture of a zipper and I felt it is something related to zip files. When I checked page source, it showed some text. I changed the URl to ".zip" and got a file with a lot of te...
#http://www.pythonchallenge.com/pc/def/channel.html import urllib import zipfile import re url_ll = "http://www.pythonchallenge.com/pc/def/channel.html" zf = zipfile.ZipFile("channel.zip", 'r') print(zf.read("readme.txt").decode()) num = "90052" comments = "" while num != "" : data = zf.read(num + ".txt").decode...
welcome to my zipped list. hint1: start from 90052 hint2: answer is inside the zip Collect the comments. **************************************************************** **************************************************************** ** ** ** OO OO X...
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 8 For the next challenge, I tried URL "http://www.pythonchallenge.com/pc/def/hockey.html" but it gave a text saying "it's in the air. look at the letters". Then, I tried "http://www.pythonchallenge.com/pc/def/oxygen.html". It gave a picture in which the center of the picture was grey scaled f...
#http://www.pythonchallenge.com/pc/def/oxygen.html import urllib.request from PIL import Image import requests from io import BytesIO url = "http://www.pythonchallenge.com/pc/def/oxygen.png" img_oxy = requests.get(url) img = Image.open(BytesIO(img_oxy.content)) width,height = img.size print(width) print(height) #fo...
629 95 smart guy, you made it. the next level is [105, 110, 116, 101, 103, 114, 105, 116, 121]pe_integrity
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 9 For the next challenge, I changed the URL to "http://www.pythonchallenge.com/pc/def/integrity.html" which showed a picture of a bee with text "Where is the missing link?". It seemed the bee is clickable and when clicked, it asked for a a userame and password.Also, when I checked page source...
#http://www.pythonchallenge.com/pc/def/integrity.html import bz2 usr = b"BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084" pwd = b"BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03$ \x00!\x9ah3M\x13<]\xc9\x14\xe1BBP\x91\xf08" print(bz2.BZ2Decompressor().decompress(us...
b'huge' b'file'
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 10 For this challenge, I gave username and password previously obtained which took me to URL "http://www.pythonchallenge.com/pc/return/good.html". It has a picture of a stem with black dots. It seemed like we need to connect the dots to get the answer. Looking at page source, my intuition is ...
#http://www.pythonchallenge.com/pc/return/good.html from PIL import Image, ImageDraw first=[ 146,399,163,403,170,393,169,391,166,386,170,381,170,371,170,355,169,346,167,335,170,329,170,320,170, 310,171,301,173,290,178,289,182,287,188,286,190,286,192,291,194,296,195,305,194,307,191,312,190,316, 190,321,192,331,193,338...
_____no_output_____
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 11 For the next challenge, I tried URL "http://www.pythonchallenge.com/pc/return/bull.html" and it showed a picture of a bull. In text below it says ‘len(a[30]) = ?’. When I clicked the bull, which is clickable, a new page shoed a sequence ‘a = [1, 11, 21, 1211, 111221,..]'. When I googled th...
#http://www.pythonchallenge.com/pc/return/bull.html from itertools import groupby def lookandsay(n): return (''.join(str(len(list(g))) + k for k,g in groupby(n))) n='1' for i in range(30): print("Term", i,"--", n) n = lookandsay(n) type(n) len(n) #http://www.pythonchallenge.com/pc/retur...
Term 0 -- 1 Term 1 -- 11 Term 2 -- 21 Term 3 -- 1211 Term 4 -- 111221 Term 5 -- 312211 Term 6 -- 13112221 Term 7 -- 1113213211 Term 8 -- 31131211131221 Term 9 -- 13211311123113112211 Term 10 -- 11131221133112132113212221 Term 11 -- 3113112221232112111312211312113211 Term 12 -- 132113213211121312211231131122211311122113...
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 12 For the next challenge, I tried URL "http://www.pythonchallenge.com/pc/return/5808.html" and it showed a blurry picture with page title 'odd even'. When I checked page source, there is nothing much except cave.jpg, which when clicked got to the same image. I tried searching '"cave in pytho...
#http://www.pythonchallenge.com/pc/return/5808.html import urllib.request from PIL import Image from io import StringIO #url = 'http://www.pythonchallenge.com/pc/return/cave.jpg' #img_cav = urllib.request.urlopen(url).read() #img = Image.open(StringIO.StringIO(img_cav)) im = Image.open('cave.jpg') im.size w, h = im....
_____no_output_____
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 13 For the next challenge, I tried URL "http://www.pythonchallenge.com/pc/return/evil.html" and it showed a picture of a man dealing with cards. When I checked page source, there is a link which redirected me to the URL "http://www.pythonchallenge.com/pc/return/evil1.jpg". When I changed the ...
#http://www.pythonchallenge.com/pc/return/evil.html import requests from PIL import Image #url_evl = "http://www.pythonchallenge.com/pc/return/evil2.gfx" #un, pw = 'huge', 'file' #d = requests.get(url_evl, auth=(un, pw)).content #print(d) data = open("evil2.gfx", "rb").read() #print(data) for i in range(0,5): o...
_____no_output_____
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 14 For the next challenge, I tried URL "http://www.pythonchallenge.com/pc/return/disproportional.html" and it gave an image with numbers on phone and text "phone that evil". The number "5" is clickable and it took me to URL "http://www.pythonchallenge.com/pc/phonebook.php" which is XML file.O...
#http://www.pythonchallenge.com/pc/return/disproportional.html url_evl = "http://www.pythonchallenge.com/pc/return/evil4.jpg" un, pw = 'huge', 'file' d = requests.get(url_evl, auth=(un, pw)).content print(d) import xmlrpc.client url_pb = 'http://www.pythonchallenge.com/pc/phonebook.php' with xmlrpc.client.ServerProx...
b'Bert is evil! go back!\n' ['phone', 'system.listMethods', 'system.methodHelp', 'system.methodSignature', 'system.multicall', 'system.getCapabilities'] Returns the phone of a person [['string', 'string']] 555-ITALY
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 15 For the next challenge, I tried URL "http://www.pythonchallenge.com/pc/return/italy.html" and it gave an image of a roll in spiral form and other square image with vertical lines. The pagetitle is "walk around". When I checked the page source, it has a link to "http://www.pythonchallenge.c...
#http://www.pythonchallenge.com/pc/return/italy.html #http://www.pythonchallenge.com/pc/return/uzi.html
_____no_output_____
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 16 For this challenge, I had to see the URL of the previous challenge. For the next challenge, I tried URL "http://www.pythonchallenge.com/pc/return/uzi.html" and it gave an image with calendar with year 1_6 and January 26th rounded, which is a Monday. Also, when I checked the page source, th...
#http://www.pythonchallenge.com/pc/return/uzi.html import datetime import calendar for year in range(1006, 2000, 10): if calendar.isleap(year) and datetime.date(year, 1, 26).weekday() == 0: print(year) #http://www.pythonchallenge.com/pc/return/mozart.html
1176 1356 1576 1756 1976
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Python challenge question 17
#http://www.pythonchallenge.com/pc/return/mozart.html
_____no_output_____
MIT
Homeworks/Homework1/VANGUMALLI-D-python-challenge-04-sept-2017.ipynb
DineshVangumalli/big-data-python-class
Testing a 1D case
from scipy.interpolate import interp1d from scipy.optimize import bisect # 4th-order Runge-Kutta def rk4(x, t, h, f): # x is coordinates (as a vector) # h is timestep # f(x) is a function that returns the derivative # "Slopes" k1 = f(x, t) k2 = f(x + k1*h/2, t + h/2) k3 = f(x + k...
_____no_output_____
MIT
notebooks/1D_test.ipynb
nordam/Discontinuities
Run a quick test to verify that results don't look crazy
# Problem properties X0 = 50 Tmax = 10 dt = 0.01 # Interpolation points xc = np.linspace(0, 100, 1001) # kind of interpolation #kind = 'linear' kind = 'quadratic' #kind = 'cubic' fig = plt.figure(figsize = (9, 5)) # Positive derivative interpolator = interp1d(xc, 1.2 + np.sin(2*np.pi*xc), kind = kind) f = lambda x...
_____no_output_____
MIT
notebooks/1D_test.ipynb
nordam/Discontinuities
Run convergence test
X0 = 0 Tmax = 10 # Interopolation points xc = np.linspace(0, 100, 1001) # kind of interpolation kind = 'linear' #kind = 'quadratic' #kind = 'cubic' # create interpolator, and wrap with lambda to get f(x, t) interpolator = interp1d(xc, 2 + np.sin(2*np.pi*xc), kind = kind) f = lambda x, t: interpolator(x) # Referenc...
_____no_output_____
MIT
notebooks/1D_test.ipynb
nordam/Discontinuities
SSD512 Training正しく学習できたらこんな感じ[SSD300 "07+12" training summary](https://github.com/pierluigiferrari/ssd_keras/blob/master/training_summaries/ssd300_pascal_07%2B12_training_summary.md)
from tensorflow.python.keras.optimizers import Adam, SGD from tensorflow.python.keras.callbacks import ModelCheckpoint, LearningRateScheduler, TerminateOnNaN, CSVLogger from tensorflow.python.keras import backend as K from tensorflow.python.keras.models import load_model from math import ceil import numpy as np from ma...
_____no_output_____
Apache-2.0
ssd512_training _2.ipynb
hidekazu300/ssd_512_2
0. Make annotation data
datasize = 10 Make_PicXML(sample_filename = 'sample/home' , save_pic_filename = 'DATASET/JPEGImages', save_xml_filename = 'DATASET/Annotations', robust = 0 , datasize = datasize ) Make_txt( save_file = 'DATASET', datasize = datasize , percent = 0.2 )
_____no_output_____
Apache-2.0
ssd512_training _2.ipynb
hidekazu300/ssd_512_2
1. Set the model configuration parametersパラメーターを設定する。 2. Build or load the model初めてであれば2.1を、2回目の学習以降は2.2を実行。両方はだめ 2.1 Create a new model and load trained VGG-16 weights into it (or trained SSD weights)If you want to create a new SSD300 model, this is the relevant section for you. If you want to load a previously sav...
""" # TODO: Set the path to the `.h5` file of the model to be loaded. model_path = 'path/to/trained/model.h5' # We need to create an SSDLoss object in order to pass that to the model loader. ssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0) K.clear_session() # Clear previous models from memory. model = load_model(model...
_____no_output_____
Apache-2.0
ssd512_training _2.ipynb
hidekazu300/ssd_512_2
3. Set up the data generators for the trainingThe code cells below set up the data generators for the training and validation datasets to train the model. The settings below reproduce the original SSD training on Pascal VOC 2007 `trainval` plus 2012 `trainval` and validation on Pascal VOC 2007 `test`.The only thing yo...
# 1: Instantiate two `DataGenerator` objects: One for training, one for validation. # Optional: If you have enough memory, consider loading the images into memory for the reasons explained above. train_dataset = DataGenerator(load_images_into_memory=False, hdf5_dataset_path=None) val_dataset = DataGenerator(load_imag...
_____no_output_____
Apache-2.0
ssd512_training _2.ipynb
hidekazu300/ssd_512_2
4. Set the remaining training parametersWe've already chosen an optimizer and set the batch size above, now let's set the remaining training parameters. I'll set one epoch to consist of 1,000 training steps. The next code cell defines a learning rate schedule that replicates the learning rate schedule of the original ...
# Define a learning rate schedule. def lr_schedule(epoch): if epoch < 80: return 0.001 elif epoch < 100: return 0.0001 else: return 0.00001 # Define model callbacks. # TODO: Set the filepath under which you want to save the model. model_checkpoint = ModelCheckpoint(filepath='traine...
_____no_output_____
Apache-2.0
ssd512_training _2.ipynb
hidekazu300/ssd_512_2
5. Train In order to reproduce the training of the "07+12" model mentioned above, at 1,000 training steps per epoch you'd have to train for 120 epochs. That is going to take really long though, so you might not want to do all 120 epochs in one go and instead train only for a few epochs at a time. You can find a summar...
# If you're resuming a previous training, set `initial_epoch` and `final_epoch` accordingly. initial_epoch = 0 final_epoch = 120 steps_per_epoch = 1000 history = model.fit_generator(generator=train_generator, steps_per_epoch=steps_per_epoch, epochs=fina...
_____no_output_____
Apache-2.0
ssd512_training _2.ipynb
hidekazu300/ssd_512_2
6. Make predictionsNow let's make some predictions on the validation dataset with the trained model. For convenience we'll use the validation generator that we've already set up above. Feel free to change the batch size.You can set the `shuffle` option to `False` if you would like to check the model's progress on the ...
# 1: Set the generator for the predictions. predict_generator = val_dataset.generate(batch_size=1, shuffle=True, transformations=[convert_to_3_channels, resize], ...
_____no_output_____
Apache-2.0
ssd512_training _2.ipynb
hidekazu300/ssd_512_2
Now let's decode the raw predictions in `y_pred`.Had we created the model in 'inference' or 'inference_fast' mode, then the model's final layer would be a `DecodeDetections` layer and `y_pred` would already contain the decoded predictions, but since we created the model in 'training' mode, the model outputs raw predict...
# 4: Decode the raw predictions in `y_pred`. y_pred_decoded = decode_detections(y_pred, confidence_thresh=0.5, iou_threshold=0.4, top_k=200, normalize_coords=normalize_coords, ...
_____no_output_____
Apache-2.0
ssd512_training _2.ipynb
hidekazu300/ssd_512_2
We made the predictions on the resized images, but we'd like to visualize the outcome on the original input images, so we'll convert the coordinates accordingly. Don't worry about that opaque `apply_inverse_transforms()` function below, in this simple case it just aplies `(* original_image_size / resized_image_size)` t...
# 5: Convert the predictions for the original image. y_pred_decoded_inv = apply_inverse_transforms(y_pred_decoded, batch_inverse_transforms) np.set_printoptions(precision=2, suppress=True, linewidth=90) print("Predicted boxes:\n") print(' class conf xmin ymin xmax ymax') print(y_pred_decoded_inv[i])
_____no_output_____
Apache-2.0
ssd512_training _2.ipynb
hidekazu300/ssd_512_2
Finally, let's draw the predicted boxes onto the image. Each predicted box says its confidence next to the category name. The ground truth boxes are also drawn onto the image in green for comparison.
# 5: Draw the predicted boxes onto the image # Set the colors for the bounding boxes colors = plt.cm.hsv(np.linspace(0, 1, n_classes+1)).tolist() classes = ['1m','2m','3m','4m','5m','6m','7m','8m','9m','1p','2p','3p','4p','5p','6p', '7p','8p','9p','1s','2s','3s','4s','5s','6s','7s','8s','9s', 'ea...
_____no_output_____
Apache-2.0
ssd512_training _2.ipynb
hidekazu300/ssd_512_2
Build a machine learning workflow using Step Functions and SageMaker1. [Introduction](Introduction)1. [Setup](Setup)1. [Build a machine learning workflow](Build-a-machine-learning-workflow) IntroductionThis notebook describes using the AWS Step Functions Data Science SDK to create and manage workflows. The Step Funct...
%%sh pip -q install --upgrade stepfunctions
_____no_output_____
Apache-2.0
step-functions-data-science-sdk/machine_learning_workflow_abalone/machine_learning_workflow_abalone.ipynb
juliensimon/amazon-sagemaker-examples
Setup Add a policy to your SageMaker role in IAM**If you are running this notebook on an Amazon SageMaker notebook instance**, the IAM role assumed by your notebook instance needs permission to create and run workflows in AWS Step Functions. To provide this permission to the role, do the following.1. Open the Amazon [...
import sagemaker # SageMaker Execution Role # You can use sagemaker.get_execution_role() if running inside sagemaker's notebook instance sagemaker_execution_role = sagemaker.get_execution_role() #Replace with ARN if not in an AWS SageMaker notebook # paste the StepFunctionsWorkflowExecutionRole ARN from above workflo...
_____no_output_____
Apache-2.0
step-functions-data-science-sdk/machine_learning_workflow_abalone/machine_learning_workflow_abalone.ipynb
juliensimon/amazon-sagemaker-examples