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 |
|---|---|---|---|---|---|
Of course, I purposely inserted numerous errors into this data set to demonstrate some of the many possible scenarios you may face while tidying your data.The general takeaways here should be:* Make sure your data is encoded properly* Make sure your data falls within the expected range, and use domain knowledge wheneve... | # We know that we should only have three classes
assert len(iris_data_clean['class'].unique()) == 3
# We know that sepal lengths for 'Iris-versicolor' should never be below 2.5 cm
assert iris_data_clean.loc[iris_data_clean['class'] == 'Iris-versicolor', 'sepal_length_cm'].min() >= 2.5
# We know that our data set should... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
And so on. If any of these expectations are violated, then our analysis immediately stops and we have to return to the tidying stage. Data Cleanup & Wrangling > 80% time spent in Data Science Step 4: Exploratory analysis[[ go back to the top ]](Table-of-contents)Now after spending entirely too much time tidying our d... | sb.pairplot(iris_data_clean)
; | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Our data is normally distributed for the most part, which is great news if we plan on using any modeling methods that assume the data is normally distributed.There's something strange going on with the petal measurements. Maybe it's something to do with the different `Iris` types. Let's color code the data by the class... | sb.pairplot(iris_data_clean, hue='class')
; | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Sure enough, the strange distribution of the petal measurements exist because of the different species. This is actually great news for our classification task since it means that the petal measurements will make it easy to distinguish between `Iris-setosa` and the other `Iris` types.Distinguishing `Iris-versicolor` an... | plt.figure(figsize=(10, 10))
for column_index, column in enumerate(iris_data_clean.columns):
if column == 'class':
continue
plt.subplot(2, 2, column_index + 1)
sb.violinplot(x='class', y=column, data=iris_data_clean) | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Enough flirting with the data. Let's get to modeling. Step 5: Classification[[ go back to the top ]](Table-of-contents)Wow, all this work and we *still* haven't modeled the data!As tiresome as it can be, tidying and exploring our data is a vital component to any data analysis. If we had jumped straight to the modeling... | iris_data_clean = pd.read_csv('../data/iris-data-clean.csv')
# We're using all four measurements as inputs
# Note that scikit-learn expects each entry to be a list of values, e.g.,
# [ [val1, val2, val3],
# [val1, val2, val3],
# ... ]
# such that our input data set is represented as a list of lists
# We can extra... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Now our data is ready to be split. | from sklearn.model_selection import train_test_split
all_inputs[:3]
iris_data_clean.head(3)
all_labels[:3]
# Here we split our data into training and testing data
(training_inputs,
testing_inputs,
training_classes,
testing_classes) = train_test_split(all_inputs, all_labels, test_size=0.25, random_state=1)
training_... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
With our data split, we can start fitting models to our data. Our company's Head of Data is all about decision tree classifiers, so let's start with one of those.Decision tree classifiers are incredibly simple in theory. In their simplest form, decision tree classifiers ask a series of Yes/No questions about the data —... | from sklearn.tree import DecisionTreeClassifier
# Create the classifier
decision_tree_classifier = DecisionTreeClassifier()
# Train the classifier on the training set
decision_tree_classifier.fit(training_inputs, training_classes)
# Validate the classifier on the testing set using classification accuracy
decision_tr... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Heck yeah! Our model achieves 97% classification accuracy without much effort.However, there's a catch: Depending on how our training and testing set was sampled, our model can achieve anywhere from 80% to 100% accuracy: | import matplotlib.pyplot as plt
# here we randomly split data 1000 times in differrent training and test sets
model_accuracies = []
for repetition in range(1000):
(training_inputs,
testing_inputs,
training_classes,
testing_classes) = train_test_split(all_inputs, all_labels, test_size=0.25)
... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
It's obviously a problem that our model performs quite differently depending on the subset of the data it's trained on. This phenomenon is known as **overfitting**: The model is learning to classify the training set so well that it doesn't generalize and perform well on data it hasn't seen before. Cross-validation[[ go... | # new text
import numpy as np
from sklearn.model_selection import StratifiedKFold
def plot_cv(cv, features, labels):
masks = []
for train, test in cv.split(features, labels):
mask = np.zeros(len(labels), dtype=bool)
mask[test] = 1
masks.append(mask)
plt.figure(figsize=(15, 15))... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
You'll notice that we used **Stratified *k*-fold cross-validation** in the code above. Stratified *k*-fold keeps the class proportions the same across all of the folds, which is vital for maintaining a representative subset of our data set. (e.g., so we don't have 100% `Iris setosa` entries in one of the folds.)We can ... | from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_score
decision_tree_classifier = DecisionTreeClassifier()
# cross_val_score returns a list of the scores, which we can visualize
# to get a reasonable estimate of our classifier's performance
cv_scores = cross_val_score(... | Entropy for column: 0 4.9947332367061925
Entropy for column: 1 4.994187360273029
Entropy for column: 2 4.88306851089088
Entropy for column: 3 4.76945055275522
| MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Now we have a much more consistent rating of our classifier's general classification accuracy. Parameter tuning[[ go back to the top ]](Table-of-contents)Every Machine Learning model comes with a variety of parameters to tune, and these parameters can be vitally important to the performance of our classifier. For examp... | decision_tree_classifier = DecisionTreeClassifier(max_depth=1)
cv_scores = cross_val_score(decision_tree_classifier, all_inputs, all_labels, cv=10)
plt.hist(cv_scores)
plt.title('Average score: {}'.format(np.mean(cv_scores)))
; | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
the classification accuracy falls tremendously.Therefore, we need to find a systematic method to discover the best parameters for our model and data set.The most common method for model parameter tuning is **Grid Search**. The idea behind Grid Search is simple: explore a range of parameters and find the best-performing... | from sklearn.model_selection import GridSearchCV
decision_tree_classifier = DecisionTreeClassifier()
parameter_grid = {'max_depth': [1, 2, 3, 4, 5],
'max_features': [1, 2, 3, 4]}
cross_validation = StratifiedKFold(n_splits=10)
grid_search = GridSearchCV(decision_tree_classifier,
... | Best score: 0.9664429530201343
Best parameters: {'max_depth': 3, 'max_features': 2}
| MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Now let's visualize the grid search to see how the parameters interact. | grid_search.cv_results_['mean_test_score']
grid_visualization = grid_search.cv_results_['mean_test_score']
grid_visualization.shape = (5, 4)
sb.heatmap(grid_visualization, cmap='Reds', annot=True)
plt.xticks(np.arange(4) + 0.5, grid_search.param_grid['max_features'])
plt.yticks(np.arange(5) + 0.5, grid_search.param_gri... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Now we have a better sense of the parameter space: We know that we need a `max_depth` of at least 2 to allow the decision tree to make more than a one-off decision.`max_features` doesn't really seem to make a big difference here as long as we have 2 of them, which makes sense since our data set has only 4 features and ... | decision_tree_classifier = DecisionTreeClassifier()
parameter_grid = {'criterion': ['gini', 'entropy'],
'splitter': ['best', 'random'],
'max_depth': [1, 2, 3, 4, 5],
'max_features': [1, 2, 3, 4]}
cross_validation = StratifiedKFold(n_splits=10)
grid_search = GridS... | Best score: 0.9664429530201343
Best parameters: {'criterion': 'gini', 'max_depth': 3, 'max_features': 3, 'splitter': 'best'}
| MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Now we can take the best classifier from the Grid Search and use that: | decision_tree_classifier = grid_search.best_estimator_
decision_tree_classifier | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
We can even visualize the decision tree with [GraphViz](http://www.graphviz.org/) to see how it's making the classifications: | import sklearn.tree as tree
from sklearn.externals.six import StringIO
with open('iris_dtc.dot', 'w') as out_file:
out_file = tree.export_graphviz(decision_tree_classifier, out_file=out_file) | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
(This classifier may look familiar from earlier in the notebook.)Alright! We finally have our demo classifier. Let's create some visuals of its performance so we have something to show our company's Head of Data. | dt_scores = cross_val_score(decision_tree_classifier, all_inputs, all_labels, cv=10)
sb.boxplot(dt_scores)
sb.stripplot(dt_scores, jitter=True, color='black')
; | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Hmmm... that's a little boring by itself though. How about we compare another classifier to see how they perform?We already know from previous projects that Random Forest classifiers usually work better than individual decision trees. A common problem that decision trees face is that they're prone to overfitting: They ... | from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestClassifier
random_forest_classifier = RandomForestClassifier()
parameter_grid = {'n_estimators': [10, 25, 50, 100],
'criterion': ['gini', 'entropy'],
'max_features': [1, 2, 3, 4]}
cross_va... | Best score: 0.9664429530201343
Best parameters: {'criterion': 'gini', 'max_features': 3, 'n_estimators': 25}
| MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Now we can compare their performance: | random_forest_classifier = grid_search.best_estimator_
rf_df = pd.DataFrame({'accuracy': cross_val_score(random_forest_classifier, all_inputs, all_labels, cv=10),
'classifier': ['Random Forest'] * 10})
dt_df = pd.DataFrame({'accuracy': cross_val_score(decision_tree_classifier, all_inputs, all_la... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
How about that? They both seem to perform about the same on this data set. This is probably because of the limitations of our data set: We have only 4 features to make the classification, and Random Forest classifiers excel when there's hundreds of possible features to look at. In other words, there wasn't much room fo... | !pip install watermark
%load_ext watermark
pd.show_versions()
%watermark -a 'RCS_April_2019' -nmv --packages numpy,pandas,sklearn,matplotlib,seaborn | RCS_April_2019 Wed Apr 17 2019
CPython 3.7.3
IPython 7.4.0
numpy 1.16.2
pandas 0.24.2
sklearn 0.20.3
matplotlib 3.0.3
seaborn 0.9.0
compiler : MSC v.1915 64 bit (AMD64)
system : Windows
release : 10
machine : AMD64
processor : Intel64 Family 6 Model 158 Stepping 10, GenuineIntel
CPU cores : 12
interpr... | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Finally, let's extract the core of our work from Steps 1-5 and turn it into a single pipeline. | %matplotlib inline
import pandas as pd
import seaborn as sb
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, cross_val_score
# We can jump directly to working with the clean data because we saved our cleaned data set
iris_data_clean = pd.read_csv('../data/iris-d... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Example 2: Sensitivity analysis on a NetLogo model with SALibThis notebook provides a more advanced example of interaction between NetLogo and a Python environment, using the SALib library (Herman & Usher, 2017; available through the pip package manager) to sample and analyze a suitable experimental design for a Sobol... | #Ensuring compliance of code with both python2 and python3
from __future__ import division, print_function
try:
from itertools import izip as zip
except ImportError: # will be 3.x series
pass
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
impor... | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
SALib relies on a problem definition dictionary which contains the number of input parameters to sample, their names (which should here correspond to a NetLogo global variable), and the sampling bounds. Documentation for SALib can be found at https://salib.readthedocs.io/en/latest/. | problem = {
'num_vars': 6,
'names': ['random-seed',
'grass-regrowth-time',
'sheep-gain-from-food',
'wolf-gain-from-food',
'sheep-reproduce',
'wolf-reproduce'],
'bounds': [[1, 100000],
[20., 40.],
[2., 8.],
[16.,... | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
We start by instantiating the wolf-sheep predation example model, specifying the _gui=False_ flag to run in headless mode. | netlogo = pyNetLogo.NetLogoLink(gui=False)
netlogo.load_model(r'Wolf Sheep Predation_v6.nlogo') | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
The SALib sampler will automatically generate an appropriate number of samples for Sobol analysis. To calculate first-order, second-order and total sensitivity indices, this gives a sample size of _n*(2p+2)_, where _p_ is the number of input parameters, and _n_ is a baseline sample size which should be large enough to ... | n = 1000
param_values = saltelli.sample(problem, n, calc_second_order=True) | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
The sampler generates an input array of shape (_n*(2p+2)_, _p_) with rows for each experiment and columns for each input parameter. | param_values.shape | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
Assuming we are interested in the mean number of sheep and wolf agents over a timeframe of 100 ticks, we first create an empty dataframe to store the results. | results = pd.DataFrame(columns=['Avg. sheep', 'Avg. wolves']) | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
We then simulate the model over the 14000 experiments, reading input parameters from the param_values array generated by SALib. The repeat_report command is used to track the outcomes of interest over time. To later compare performance with the ipyparallel implementation of the analysis, we also keep track of the elaps... | import time
t0=time.time()
for run in range(param_values.shape[0]):
#Set the input parameters
for i, name in enumerate(problem['names']):
if name == 'random-seed':
#The NetLogo random seed requires a different syntax
netlogo.command('random-seed {}'.format(param_values[run... | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
The "to_csv" dataframe method provides a simple way of saving the results to disk.Pandas supports several more advanced storage options, such as serialization with msgpack, or hierarchical HDF5 storage. | results.to_csv('Sobol_sequential.csv')
results = pd.read_csv('Sobol_sequential.csv', header=0, index_col=0)
results.head(5) | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
We can then proceed with the analysis, first using a histogram to visualize output distributions for each outcome: | sns.set_style('white')
sns.set_context('talk')
fig, ax = plt.subplots(1,len(results.columns), sharey=True)
for i, n in enumerate(results.columns):
ax[i].hist(results[n], 20)
ax[i].set_xlabel(n)
ax[0].set_ylabel('Counts')
fig.set_size_inches(10,4)
fig.subplots_adjust(wspace=0.1)
#plt.savefig('JASSS figures/SA... | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
Bivariate scatter plots can be useful to visualize relationships between each input parameter and the outputs. Taking the outcome for the average sheep count as an example, we obtain the following, using the scipy library to calculate the Pearson correlation coefficient (r) for each parameter: | %matplotlib
import scipy
nrow=2
ncol=3
fig, ax = plt.subplots(nrow, ncol, sharey=True)
sns.set_context('talk')
y = results['Avg. sheep']
for i, a in enumerate(ax.flatten()):
x = param_values[:,i]
sns.regplot(x, y, ax=a, ci=None, color='k',scatter_kws={'alpha':0.2, 's':4, 'color':'gray'})
pearson = scipy.s... | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
This indicates a positive relationship between the "sheep-gain-from-food" parameter and the mean sheep count, and negative relationships for the "wolf-gain-from-food" and "wolf-reproduce" parameters.We can then use SALib to calculate first-order (S1), second-order (S2) and total (ST) Sobol indices, to estimate each inp... | Si = sobol.analyze(problem, results['Avg. sheep'].values, calc_second_order=True, print_to_console=False) | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
As a simple example, we first select and visualize the first-order and total indices for each input, converting the dictionary returned by SALib to a dataframe. | Si_filter = {k:Si[k] for k in ['ST','ST_conf','S1','S1_conf']}
Si_df = pd.DataFrame(Si_filter, index=problem['names'])
Si_df
sns.set_style('white')
fig, ax = plt.subplots(1)
indices = Si_df[['S1','ST']]
err = Si_df[['S1_conf','ST_conf']]
indices.plot.bar(yerr=err.values.T,ax=ax)
fig.set_size_inches(8,4)
#plt.savefig... | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
The "sheep-gain-from-food" parameter has the highest ST index, indicating that it contributes over 50% of output variance when accounting for interactions with other parameters. However, it can be noted that the confidence bounds are overly broad due to the small _n_ value used for sampling, so that a larger sample wou... | import itertools
from math import pi
def normalize(x, xmin, xmax):
return (x-xmin)/(xmax-xmin)
def plot_circles(ax, locs, names, max_s, stats, smax, smin, fc, ec, lw,
zorder):
s = np.asarray([stats[name] for name in names])
s = 0.01 + max_s * np.sqrt(normalize(s, smin, smax))
... | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
In this case, the sheep-gain-from-food variable has strong interactions with the wolf-gain-from-food and sheep-reproduce inputs in particular. The size of the ST and S1 circles correspond to the normalized variable importances. Finally, the kill_workspace() function shuts down the NetLogo instance. | netlogo.kill_workspace() | _____no_output_____ | BSD-3-Clause | docs/source/_docs/pyNetLogo demo - SALib sequential.ipynb | jasonrwang/pyNetLogo |
1. Visualize The 10 Most Slow Players | most_slow_Players = players_time[players_time["seconds_added_per_point"] > 0].sort_values(by="seconds_added_per_point", ascending=False).head(10)
most_slow_Players
sns.set(style="darkgrid")
plt.figure(figsize = (10,5))
ax= sns.barplot(x="seconds_added_per_point", y="player", data=most_slow_Players)
ax.set_title("TOP 10... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
2. Visualize The 10 Most Fast Players | most_fast_Players = players_time[players_time["seconds_added_per_point"] < 0].sort_values(by="seconds_added_per_point").head(10)
most_fast_Players
sns.set(style="darkgrid")
plt.figure(figsize = (10,5))
ax= sns.barplot(x="seconds_added_per_point", y="player", data=most_fast_Players)
ax.set_title("TOP 10 MOST FAST PLAYER... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
3. Visualize The Time Of The Big 3 | big_three_time = players_time[(players_time["player"] == "Novak Djokovic") | (players_time["player"] == "Roger Federer") | (players_time["player"] == "Rafael Nadal")]
big_three_time
sns.set(style="darkgrid")
plt.figure(figsize = (10,5))
ax= sns.barplot(x="seconds_added_per_point", y="player", data=big_three_time)
ax.se... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
4. Figure Out The Top 10 Surfaces That Take The Longest Time | longest_time_surfaces = events_time[events_time["seconds_added_per_point"] > 0].sort_values(by="seconds_added_per_point", ascending=False).head(10)
longest_time_surfaces
sns.set(style="darkgrid")
plt.figure(figsize = (10,5))
ax= sns.barplot(x="seconds_added_per_point", y="tournament", hue="surface", data=longest_time_s... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
5. Figure Out The Top 10 Surfaces That Take The Shortest Time | shortest_time_surfaces = events_time[events_time["seconds_added_per_point"] < 0].sort_values(by="seconds_added_per_point").head(10)
shortest_time_surfaces
sns.set(style="darkgrid")
plt.figure(figsize = (10,5))
ax = sns.barplot(x="seconds_added_per_point", y="tournament", hue="surface", data=shortest_time_surfaces)
ax.s... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
6. Figure Out How The Time For The Clay Surface Has Progressed Throughout The Years | years = events_time[~events_time["years"].str.contains("-")]
sorted_years_clay = years[years["surface"] == "Clay"].sort_values(by="years")
sorted_years_clay
sns.set(style="darkgrid")
plt.figure(figsize = (10,5))
ax= sns.lineplot(x="years", y="seconds_added_per_point", hue="surface", data=sorted_years_clay)
ax.set_title... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
7. Figure Out How The Time For The Hard Surface Has Progressed Throughout The Years | sorted_years_hard = years[years["surface"] == "Hard"].sort_values(by="years")
sns.set(style="darkgrid")
plt.figure(figsize = (10,5))
ax= sns.lineplot(x="years", y="seconds_added_per_point", hue="surface", data=sorted_years_hard)
ax.set_title("PROGRESSION OF TIME FOR THE HARD SURFACE THROUGHOUT THE YEARS", fontsize=17)
... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
8. Figure Out How The Time For The Carpet Surface Has Progressed Throughout The Years | sorted_years_carpet = years[years["surface"] == "Carpet"].sort_values(by="years")
sns.set(style="darkgrid")
plt.figure(figsize = (10,5))
ax= sns.lineplot(x="years", y="seconds_added_per_point", hue="surface", data=sorted_years_carpet)
ax.set_title("PROGRESSION OF TIME FOR THE CARPET SURFACE THROUGHOUT THE YEARS", fonts... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
9. Figure Out How The Time For The Grass Surface Has Progressed Throughout The Years | sorted_years_grass = events_time[events_time["surface"] == "Grass"].sort_values(by="years").head(5)
sns.set(style="darkgrid")
plt.figure(figsize = (10,5))
ax= sns.lineplot(x="years", y="seconds_added_per_point", hue="surface", data=sorted_years_grass)
ax.set_title("PROGRESSION OF TIME FOR THE GRASS SURFACE THROUGHOUT T... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
10. Figure Out The Person Who Took The Most Time Serving In 2015 | serve_time
serve_time_visualization = serve_time.groupby("server")["seconds_before_next_point"].agg("sum")
serve_time_visualization
serve_time_visual_data = serve_time_visualization.reset_index()
serve_time_visual_data
serve_time_visual_sorted = serve_time_visual_data.sort_values(by="seconds_before_next_point", ascendi... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
BIG THREE TOTAL SERVING TIME IN 2015 | big_three_total_serving_time = serve_time_visual_sorted[(serve_time_visual_sorted["server"] == "Roger Federer") | (serve_time_visual_sorted["server"] == "Rafael Nadal") | (serve_time_visual_sorted["server"] == "Novak Djokovic")]
big_three_total_serving_time
sns.set(style="darkgrid")
plt.figure(figsize = (10,5))
ax = sn... | _____no_output_____ | MIT | Tennis_Time_Data_Visualization.ipynb | Tinzyl/Tennis_Time_Data_Visualization |
Data | PATH = Path('/home/giles/Downloads/fastai_data/salt/')
MASKS_FN = 'train_masks.csv'
META_FN = 'metadata.csv'
masks_csv = pd.read_csv(PATH/MASKS_FN)
meta_csv = pd.read_csv(PATH/META_FN)
def show_img(im, figsize=None, ax=None, alpha=None):
if not ax: fig,ax = plt.subplots(figsize=figsize)
ax.imshow(im, alpha=alph... | _____no_output_____ | Apache-2.0 | notebooks/old/Salt_9-resne34-with-highLR-derper.ipynb | GilesStrong/Kaggle_TGS-Salt |
TRAIN_DN = 'train'MASKS_DN = 'train_masks_png'sz = 128bs = 64nw = 16 | class MatchedFilesDataset(FilesDataset):
def __init__(self, fnames, y, transform, path):
self.y=y
assert(len(fnames)==len(y))
super().__init__(fnames, transform, path)
def get_y(self, i): return open_image(os.path.join(self.path, self.y[i]))
def get_c(self): return 0
x_names = np.arr... | _____no_output_____ | Apache-2.0 | notebooks/old/Salt_9-resne34-with-highLR-derper.ipynb | GilesStrong/Kaggle_TGS-Salt |
Simple upsample | f = resnet34
cut,lr_cut = model_meta[f]
def get_base():
layers = cut_model(f(True), cut)
return nn.Sequential(*layers)
def dice(pred, targs):
pred = (pred>0.5).float()
return 2. * (pred*targs).sum() / (pred+targs).sum() | _____no_output_____ | Apache-2.0 | notebooks/old/Salt_9-resne34-with-highLR-derper.ipynb | GilesStrong/Kaggle_TGS-Salt |
U-net (ish) | class SaveFeatures():
features=None
def __init__(self, m): self.hook = m.register_forward_hook(self.hook_fn)
def hook_fn(self, module, input, output): self.features = output
def remove(self): self.hook.remove()
class UnetBlock(nn.Module):
def __init__(self, up_in, x_in, n_out):
super().__ini... | _____no_output_____ | Apache-2.0 | notebooks/old/Salt_9-resne34-with-highLR-derper.ipynb | GilesStrong/Kaggle_TGS-Salt |
64x64 | sz=64
bs=64
tfms = tfms_from_model(resnet34, sz, crop_type=CropType.NO, tfm_y=TfmType.CLASS, aug_tfms=aug_tfms)
datasets = ImageData.get_ds(MatchedFilesDataset, (trn_x,trn_y), (val_x,val_y), tfms, path=PATH)
md = ImageData(PATH, datasets, bs, num_workers=16, classes=None)
denorm = md.trn_ds.denorm
m_base = get_base()
m... | _____no_output_____ | Apache-2.0 | notebooks/old/Salt_9-resne34-with-highLR-derper.ipynb | GilesStrong/Kaggle_TGS-Salt |
128x128 | sz=128
bs=64
tfms = tfms_from_model(resnet34, sz, crop_type=CropType.NO, tfm_y=TfmType.CLASS, aug_tfms=aug_tfms)
datasets = ImageData.get_ds(MatchedFilesDataset, (trn_x,trn_y), (val_x,val_y), tfms, path=PATH)
md = ImageData(PATH, datasets, bs, num_workers=16, classes=None)
denorm = md.trn_ds.denorm
m_base = get_base()
... | _____no_output_____ | Apache-2.0 | notebooks/old/Salt_9-resne34-with-highLR-derper.ipynb | GilesStrong/Kaggle_TGS-Salt |
Test on original validation | x_names_orig = np.array(glob(f'{PATH}/train/*'))
y_names_orig = np.array(glob(f'{PATH}/train_masks/*'))
val_idxs_orig = list(range(800))
((val_x_orig,trn_x_orig),(val_y_orig,trn_y_orig)) = split_by_idx(val_idxs_orig, x_names_orig, y_names_orig)
sz=128
bs=64
tfms = tfms_from_model(resnet34, sz, crop_type=CropType.NO, tf... | _____no_output_____ | Apache-2.0 | notebooks/old/Salt_9-resne34-with-highLR-derper.ipynb | GilesStrong/Kaggle_TGS-Salt |
Optimise threshold | # src: https://www.kaggle.com/aglotero/another-iou-metric
def iou_metric(y_true_in, y_pred_in, print_table=False):
labels = y_true_in
y_pred = y_pred_in
true_objects = 2
pred_objects = 2
intersection = np.histogram2d(labels.flatten(), y_pred.flatten(), bins=(true_objects, pred_objects))[0]
... | _____no_output_____ | Apache-2.0 | notebooks/old/Salt_9-resne34-with-highLR-derper.ipynb | GilesStrong/Kaggle_TGS-Salt |
Run on test | (PATH/'test-128').mkdir(exist_ok=True)
def resize_img(fn):
Image.open(fn).resize((128,128)).save((fn.parent.parent)/'test-128'/fn.name)
files = list((PATH/'test').iterdir())
with ThreadPoolExecutor(8) as e: e.map(resize_img, files)
testData = np.array(glob(f'{PATH}/test-128/*'))
class TestFilesDataset(FilesDataset... | _____no_output_____ | Apache-2.0 | notebooks/old/Salt_9-resne34-with-highLR-derper.ipynb | GilesStrong/Kaggle_TGS-Salt |
AWS Elastic Kubernetes Service (EKS) Deep MNISTIn this example we will deploy a tensorflow MNIST model in Amazon Web Services' Elastic Kubernetes Service (EKS).This tutorial will break down in the following sections:1) Train a tensorflow model to predict mnist locally2) Containerise the tensorflow model with our docke... | from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
import tensorflow as tf
if __name__ == '__main__':
x = tf.placeholder(tf.float32, [None,784], name="x")
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
... | Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
0.9194
| Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
2) Containerise the tensorflow model with our docker utility First you need to make sure that you have added the .s2i/environment configuration file in this folder with the following content: | !cat .s2i/environment | MODEL_NAME=DeepMnist
API_TYPE=REST
SERVICE_TYPE=MODEL
PERSISTENCE=0
| Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Now we can build a docker image named "deep-mnist" with the tag 0.1 | !s2i build . seldonio/seldon-core-s2i-python36:1.5.0-dev deep-mnist:0.1 | ---> Installing application source...
---> Installing dependencies ...
Looking in links: /whl
Requirement already satisfied: tensorflow>=1.12.0 in /usr/local/lib/python3.6/site-packages (from -r requirements.txt (line 1)) (1.13.1)
Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/sit... | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
3) Send some data to the docker model to test itWe first run the docker image we just created as a container called "mnist_predictor" | !docker run --name "mnist_predictor" -d --rm -p 5000:5000 deep-mnist:0.1 | 5157ab4f516bd0dea11b159780f31121e9fb41df6394e0d6d631e6e0d572463b
| Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Send some random features that conform to the contract | import matplotlib.pyplot as plt
# This is the variable that was initialised at the beginning of the file
i = [0]
x = mnist.test.images[i]
y = mnist.test.labels[i]
plt.imshow(x.reshape((28, 28)), cmap='gray')
plt.show()
print("Expected label: ", np.sum(range(0,10) * y), ". One hot encoding: ", y)
from seldon_core.seldon... | mnist_predictor
| Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
4) Install and configure AWS tools to interact with AWS First we install the awscli | !pip install awscli --upgrade --user | Collecting awscli
Using cached https://files.pythonhosted.org/packages/f6/45/259a98719e7c7defc9be4cc00fbfb7ccf699fbd1f74455d8347d0ab0a1df/awscli-1.16.163-py2.py3-none-any.whl
Collecting colorama<=0.3.9,>=0.2.5 (from awscli)
Using cached https://files.pythonhosted.org/packages/db/c8/7dcf9dbcb22429512708fe3a547f8b610... | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Configure aws so it can talk to your server (if you are getting issues, make sure you have the permmissions to create clusters) | %%bash
# You must make sure that the access key and secret are changed
aws configure << END_OF_INPUTS
YOUR_ACCESS_KEY
YOUR_ACCESS_SECRET
us-west-2
json
END_OF_INPUTS | AWS Access Key ID [****************SF4A]: AWS Secret Access Key [****************WLHu]: Default region name [eu-west-1]: Default output format [json]: | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Install EKCTL*IMPORTANT*: These instructions are for linuxPlease follow the official installation of ekctl at: https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html | !curl --silent --location "https://github.com/weaveworks/eksctl/releases/download/latest_release/eksctl_$(uname -s)_amd64.tar.gz" | tar xz
!chmod 755 ./eksctl
!./eksctl version | [36m[ℹ] version.Info{BuiltAt:"", GitCommit:"", GitTag:"0.1.32"}
[0m | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
5) Use the AWS tools to create and setup EKS cluster with SeldonIn this example we will create a cluster with 2 nodes, with a minimum of 1 and a max of 3. You can tweak this accordingly.If you want to check the status of the deployment you can go to AWS CloudFormation or to the EKS dashboard.It will take 10-15 minutes... | %%bash
./eksctl create cluster \
--name demo-eks-cluster \
--region us-west-2 \
--nodes 2 | Process is interrupted.
| Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Configure local kubectl We want to now configure our local Kubectl so we can actually reach the cluster we've just created | !aws eks --region us-west-2 update-kubeconfig --name demo-eks-cluster | Updated context arn:aws:eks:eu-west-1:271049282727:cluster/deepmnist in /home/alejandro/.kube/config
| Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
And we can check if the context has been added to kubectl config (contexts are basically the different k8s cluster connections)You should be able to see the context as "...aws:eks:eu-west-1:27...". If it's not activated you can activate that context with kubectlt config set-context | !kubectl config get-contexts | CURRENT NAME CLUSTER AUTHINFO NAMESPACE
* arn:aws:eks:eu-west-1:271049282727:cluster/deepmnist arn:aws:eks:eu-west-1:271049282727:cluster/deepmnist arn:aws:eks:eu-... | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Setup Seldon CoreUse the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlSetup-Cluster) with [Ambassador Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlAmbassador) and [Install Seldon Core](https://doc... | !aws ecr create-repository --repository-name seldon-repository --region us-west-2 | {
"repository": {
"repositoryArn": "arn:aws:ecr:us-west-2:271049282727:repository/seldon-repository",
"registryId": "271049282727",
"repositoryName": "seldon-repository",
"repositoryUri": "271049282727.dkr.ecr.us-west-2.amazonaws.com/seldon-repository",
"createdAt": 155853579... | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Now prepare docker imageWe need to first tag the docker image before we can push it | %%bash
export AWS_ACCOUNT_ID=""
export AWS_REGION="us-west-2"
if [ -z "$AWS_ACCOUNT_ID" ]; then
echo "ERROR: Please provide a value for the AWS variables"
exit 1
fi
docker tag deep-mnist:0.1 "$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/seldon-repository" | _____no_output_____ | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
We now login to aws through docker so we can access the repository | !`aws ecr get-login --no-include-email --region us-west-2` | WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /home/alejandro/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store
Login Succeeded
| Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
And push the imageMake sure you add your AWS Account ID | %%bash
export AWS_ACCOUNT_ID=""
export AWS_REGION="us-west-2"
if [ -z "$AWS_ACCOUNT_ID" ]; then
echo "ERROR: Please provide a value for the AWS variables"
exit 1
fi
docker push "$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/seldon-repository" | The push refers to repository [271049282727.dkr.ecr.us-west-2.amazonaws.com/seldon-repository]
f7d0d000c138: Preparing
987f3f1afb00: Preparing
00d16a381c47: Preparing
bb01f50d544a: Preparing
fcb82c6941b5: Preparing
67290e35c458: Preparing
b813745f5bb3: Preparing
ffecb18e9f0b: Preparing
f50f856f49fa: Preparing
80b43ad4a... | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Running the ModelWe will now run the model.Let's first have a look at the file we'll be using to trigger the model: | !cat deep_mnist.json | {
"apiVersion": "machinelearning.seldon.io/v1alpha2",
"kind": "SeldonDeployment",
"metadata": {
"labels": {
"app": "seldon"
},
"name": "deep-mnist"
},
"spec": {
"annotations": {
"project_name": "Tensorflow MNIST",
"deployment_versio... | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Now let's trigger seldon to run the model.We basically have a yaml file, where we want to replace the value "REPLACE_FOR_IMAGE_AND_TAG" for the image you pushed | %%bash
export AWS_ACCOUNT_ID=""
export AWS_REGION="us-west-2"
if [ -z "$AWS_ACCOUNT_ID" ]; then
echo "ERROR: Please provide a value for the AWS variables"
exit 1
fi
sed 's|REPLACE_FOR_IMAGE_AND_TAG|'"$AWS_ACCOUNT_ID"'.dkr.ecr.'"$AWS_REGION"'.amazonaws.com/seldon-repository|g' deep_mnist.json | kubectl apply -f... | error: unable to recognize "STDIN": Get https://461835FD3FF52848655C8F09FBF5EEAA.yl4.us-west-2.eks.amazonaws.com/api?timeout=32s: dial tcp: lookup 461835FD3FF52848655C8F09FBF5EEAA.yl4.us-west-2.eks.amazonaws.com on 1.1.1.1:53: no such host
| Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
And let's check that it's been created.You should see an image called "deep-mnist-single-model...".We'll wait until STATUS changes from "ContainerCreating" to "Running" | !kubectl get pods | NAME READY STATUS RESTARTS AGE
ambassador-5475779f98-7bhcw 1/1 Running 0 21m
ambassador-5475779f98-986g5 1/1 Running 0 21m
ambassador-5475779f98-zcd28 1/1 Running 0 ... | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Test the modelNow we can test the model, let's first find out what is the URL that we'll have to use: | !kubectl get svc ambassador -o jsonpath='{.status.loadBalancer.ingress[0].hostname}' | a68bbac487ca611e988060247f81f4c1-707754258.us-west-2.elb.amazonaws.com | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
We'll use a random example from our dataset | import matplotlib.pyplot as plt
# This is the variable that was initialised at the beginning of the file
i = [0]
x = mnist.test.images[i]
y = mnist.test.labels[i]
plt.imshow(x.reshape((28, 28)), cmap='gray')
plt.show()
print("Expected label: ", np.sum(range(0,10) * y), ". One hot encoding: ", y) | _____no_output_____ | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
We can now add the URL above to send our request: | from seldon_core.seldon_client import SeldonClient
import math
import numpy as np
host = "a68bbac487ca611e988060247f81f4c1-707754258.us-west-2.elb.amazonaws.com"
port = "80" # Make sure you use the port above
batch = x
payload_type = "ndarray"
sc = SeldonClient(
gateway="ambassador",
ambassador_endpoint=host... | Success:True message:
Request:
data {
names: "text"
ndarray {
values {
list_value {
values {
number_value: 0.0
}
values {
number_value: 0.0
}
values {
number_value: 0.0
}
values {
number_value: 0.0
}
... | Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
Let's visualise the probability for each labelIt seems that it correctly predicted the number 7 | for proba, label in zip(client_prediction.response.data.ndarray.values[0].list_value.ListFields()[0][1], range(0,10)):
print(f"LABEL {label}:\t {proba.number_value*100:6.4f} %") | LABEL 0: 0.0068 %
LABEL 1: 0.0000 %
LABEL 2: 0.0085 %
LABEL 3: 0.3409 %
LABEL 4: 0.0002 %
LABEL 5: 0.0020 %
LABEL 6: 0.0000 %
LABEL 7: 99.5371 %
LABEL 8: 0.0026 %
LABEL 9: 0.1019 %
| Apache-2.0 | examples/models/aws_eks_deep_mnist/aws_eks_deep_mnist.ipynb | welcomemandeep/seldon-core |
**Introduction to TinyAutoML**---TinyAutoML is a Machine Learning Python3.9 library thought as an extension of Scikit-Learn. It builds an adaptable and auto-tuned pipeline to handle binary classification tasks.In a few words, your data goes through 2 main preprocessing steps. The first one is scaling and NonStationnar... | %pip install TinyAutoML==0.2.3.3
from TinyAutoML.Models import *
from TinyAutoML import MetaPipeline | _____no_output_____ | MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
MetaModelsMetaModels inherit from the MetaModel Abstract Class. They all implement ensemble methods and therefore are based on EstimatorPools.When training EstimatorPools, you are faced with a choice : doing parameterTuning on entire pipelines with the estimators on the top or training the estimators using the same p... | best_model = MetaPipeline(BestModel(comprehensiveSearch = False, parameterTuning = False)) | _____no_output_____ | MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
2- OneRulerForAll : implements Stacking using a RandomForestClassifier by default. The user is free to use another classifier using the ruler arguments | orfa_model = MetaPipeline(OneRulerForAll(comprehensiveSearch=False, parameterTuning=False)) | _____no_output_____ | MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
3- DemocraticModel : implements Soft and Hard voting models through the voting argument | democratic_model = MetaPipeline(DemocraticModel(comprehensiveSearch=False, parameterTuning=False, voting='soft')) | _____no_output_____ | MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
As of release v0.2.3.2 (13/04/2022) there are 5 models on which these MetaModels rely in the EstimatorPool:- Random Forest Classifier- Logistic Regression- Gaussian Naive Bayes- Linear Discriminant Analysis- XGBoost***We'll use the breast_cancer dataset from sklearn as an example: | import pandas as pd
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
X = pd.DataFrame(data=cancer.data, columns=cancer.feature_names)
y = cancer.target
cut = int(len(y) * 0.8)
X_train, X_test = X[:cut], X[cut:]
y_train, y_test = y[:cut], y[cut:] | _____no_output_____ | MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
Let's train a BestModel first and reuse its Pool for the other MetaModels | best_model.fit(X_train,y_train) | INFO:root:Training models
INFO:root:The best estimator is random forest classifier with a cross-validation accuracy (in Sample) of 1.0
| MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
We can now extract the pool | pool = best_model.get_pool() | _____no_output_____ | MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
And use it when fitting the other MetaModels to skip the fitting of the underlying models: | orfa_model.fit(X_train,y_train,pool=pool)
democratic_model.fit(X_train,y_train,pool=pool) | INFO:root:Training models...
INFO:root:Training models...
| MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
Great ! Let's look at the results with the sk_learn classification report : | orfa_model.classification_report(X_test,y_test) | precision recall f1-score support
0 0.96 1.00 0.98 26
1 1.00 0.99 0.99 88
accuracy 0.99 114
macro avg 0.98 0.99 0.99 114
weighted avg 0.99 0.99 0.99 ... | MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
Looking good! What about the ROC Curve ? | democratic_model.roc_curve(X_test,y_test) | _____no_output_____ | MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
Let's see how the estimators of the pool are doing individually: | best_model.get_scores(X_test,y_test) | _____no_output_____ | MIT | introduction-to-Tiny-AutoML.ipynb | thomktz/TinyAutoML |
Computer Vision Nanodegree Project: Image Captioning---In this notebook, you will train your CNN-RNN model. You are welcome and encouraged to try out many different architectures and hyperparameters when searching for a good model.This does have the potential to make the project quite messy! Before submitting your p... | import nltk
nltk.download('punkt')
import torch
import torch.nn as nn
from torchvision import transforms
import sys
sys.path.append('/opt/cocoapi/PythonAPI')
from pycocotools.coco import COCO
from data_loader import get_loader
from model import EncoderCNN, DecoderRNN
import math
## TODO #1: Select appropriate values... | Vocabulary successfully loaded from vocab.pkl file!
loading annotations into memory...
Done (t=1.07s)
creating index...
| MIT | 2_Training.ipynb | siddsrivastava/Image-captionin |
Step 2: Train your ModelOnce you have executed the code cell in **Step 1**, the training procedure below should run without issue. It is completely fine to leave the code cell below as-is without modifications to train your model. However, if you would like to modify the code used to train the model below, you must ... | import torch.utils.data as data
import numpy as np
import os
import requests
import time
# Open the training log file.
f = open(log_file, 'w')
old_time = time.time()
response = requests.request("GET",
"http://metadata.google.internal/computeMetadata/v1/instance/attributes/keep_alive_token... | Epoch [1/3], Step [100/6471], Loss: 4.2137, Perplexity: 67.6088
Epoch [1/3], Step [200/6471], Loss: 3.9313, Perplexity: 50.97528
Epoch [1/3], Step [300/6471], Loss: 3.5978, Perplexity: 36.5175
Epoch [1/3], Step [400/6471], Loss: 3.6794, Perplexity: 39.6219
Epoch [1/3], Step [500/6471], Loss: 3.0714, Perplexity: 21.5712... | MIT | 2_Training.ipynb | siddsrivastava/Image-captionin |
Step 3: (Optional) Validate your ModelTo assess potential overfitting, one approach is to assess performance on a validation set. If you decide to do this **optional** task, you are required to first complete all of the steps in the next notebook in the sequence (**3_Inference.ipynb**); as part of that notebook, you ... | # (Optional) TODO: Validate your model. | _____no_output_____ | MIT | 2_Training.ipynb | siddsrivastava/Image-captionin |
Mount google drive to colab | from google.colab import drive
drive.mount("/content/drive") | Mounted at /content/drive
| MIT | Models/CNN_best.ipynb | DataMas/Deep-Learning-Image-Classification |
Import libraries | import os
import random
import numpy as np
import shutil
import time
from PIL import Image, ImageOps
import cv2
import pandas as pd
import math
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
import tensorflow as tf
from keras import models
from keras import layers
from keras import... | _____no_output_____ | MIT | Models/CNN_best.ipynb | DataMas/Deep-Learning-Image-Classification |
Initialize basic working directories | directory = "drive/MyDrive/Datasets/Sign digits/Dataset"
trainDir = "train"
testDir = "test"
os.chdir(directory) | _____no_output_____ | MIT | Models/CNN_best.ipynb | DataMas/Deep-Learning-Image-Classification |
Augmented dataframes | augDir = "augmented/"
classNames_train = os.listdir(augDir+'train/')
classNames_test = os.listdir(augDir+'test/')
classes_train = []
data_train = []
paths_train = []
classes_test = []
data_test = []
paths_test = []
classes_val = []
data_val = []
paths_val = []
for className in range(0,10):
temp_train = os.listdi... | _____no_output_____ | MIT | Models/CNN_best.ipynb | DataMas/Deep-Learning-Image-Classification |
Решаем задачу логистической регрессии и l1-регуляризацией:$$F(w) = - \frac{1}{N}\sum\limits_{i=1}^Ny_i\ln(\sigma_w(x_i)) + (1 - y_i)\ln(1 - \sigma_w(x_i)) + \lambda\|w\|_1,$$где $\lambda$ -- параметр регуляризации.Задачу решаем проксимальным градиентным методом. Убедимся сначала, что при $\lambda = 0$ наше решение совп... | orac = make_oracle('a1a.txt', penalty='l1', reg=0)
orac1 = make_oracle('a1a.txt')
x, y = load_svmlight_file('a1a.txt', zero_based=False)
m = x[0].shape[1] + 1
w0 = np.zeros((m, 1))
optimizer = OptimizeLassoProximal()
optimizer1 = OptimizeGD()
point = optimizer(orac, w0)
point1 = optimizer1(orac1, w0, NesterovLineSearch... | _____no_output_____ | Apache-2.0 | HW_exam/.ipynb_checkpoints/Exam_Prazdnichnykh-checkpoint.ipynb | AntonPrazdnichnykh/HSE.optimization |
Изучим скорость сходимости метода на датасете a1a.txt ($\lambda = 0.001$) | def convergence_plot(xs, ys, xlabel, title=None):
plt.figure(figsize = (12, 3))
plt.xlabel(xlabel)
plt.ylabel('F(w_{k+1} - F(w_k)')
plt.plot(xs, ys)
plt.yscale('log')
if title:
plt.title(title)
plt.tight_layout()
plt.show()
orac = make_oracle('a1a.txt', penalty='l1', reg=0.0... | _____no_output_____ | Apache-2.0 | HW_exam/.ipynb_checkpoints/Exam_Prazdnichnykh-checkpoint.ipynb | AntonPrazdnichnykh/HSE.optimization |
Заметим, что было использовано условие остановки $F(w_{k+1}) - F(w_k) \leq tol = 10^{-16}$. Из математических соображений кажется, что это ок, так как в вещественных числах сходимость последовательности равносильна её фундаментальности. Я также пытался использовать в качестве условия остановки $\|\nabla_w f(w_k)\|_2^2 ... | def plot(x, ys, ylabel, legend=False):
plt.figure(figsize = (12, 3))
plt.xlabel("lambda")
plt.ylabel(ylabel)
plt.plot(x, ys, 'o')
plt.xscale('log')
if legend:
plt.legend()
plt.tight_layout()
plt.show()
lambdas = [10**(-i) for i in range... | _____no_output_____ | Apache-2.0 | HW_exam/.ipynb_checkpoints/Exam_Prazdnichnykh-checkpoint.ipynb | AntonPrazdnichnykh/HSE.optimization |
Видно, что параметр регуляризации практически не влияет на скорость сходимости (она всегда линейная), но количество итераций метода падает с увеличением параметра регуляризации. Так же из последнего графика делаем ожидаемый вывод, что число ненулевых компонент в решении уменьшается с ростом параметра регуляризации Пост... | def value_plot(xs, ys, xlabel, title=None):
plt.figure(figsize = (12, 3))
plt.xlabel(xlabel)
plt.ylabel('F(w_k)')
plt.plot(xs, ys)
# plt.yscale('log')
if title:
plt.title(title)
plt.tight_layout()
plt.show()
orac = make_oracle('a1a.txt', penalty='l1', reg=0.001)
point = optimizer... | _____no_output_____ | Apache-2.0 | HW_exam/.ipynb_checkpoints/Exam_Prazdnichnykh-checkpoint.ipynb | AntonPrazdnichnykh/HSE.optimization |
Для подтверждения сделаных выводов проверим их ещё на breast-cancer_scale датасете. Проверка равносильности GD + Nesterov и Proximal + $\lambda = 0$: | orac = make_oracle('breast-cancer_scale.txt', penalty='l1', reg=0)
orac1 = make_oracle('breast-cancer_scale.txt')
x, y = load_svmlight_file('breast-cancer_scale.txt', zero_based=False)
m = x[0].shape[1] + 1
w0 = np.zeros((m, 1))
optimizer = OptimizeLassoProximal()
optimizer1 = OptimizeGD()
point = optimizer(orac, w0)
p... | 0.0001461093710795336
| Apache-2.0 | HW_exam/.ipynb_checkpoints/Exam_Prazdnichnykh-checkpoint.ipynb | AntonPrazdnichnykh/HSE.optimization |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.