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
Evaluating Model against Test Set
# YOU CAN SAFELY IGNORE WARNINGS HERE! # THIS WILL NOT AFFECT YOUR FORECAST, IT'S JUST SOMETHING STATSMODELS NEEDS TO UPDATE UPON NEXT RELEASE. test_predictions = fitted_model.forecast(36).rename('HW Forecast') test_predictions train_data['Thousands of Passengers'].plot(legend=True,label='TRAIN') test_data['Thousands o...
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
Evaluation Metrics
from sklearn.metrics import mean_squared_error,mean_absolute_error mean_absolute_error(test_data,test_predictions) mean_squared_error(test_data,test_predictions) np.sqrt(mean_squared_error(test_data,test_predictions)) test_data.describe()
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
Forecasting into Future
final_model = ExponentialSmoothing(df['Thousands of Passengers'],trend='mul',seasonal='mul',seasonal_periods=12).fit() forecast_predictions = final_model.forecast(36) df['Thousands of Passengers'].plot(figsize=(12,8)) forecast_predictions.plot();
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
StationarityTime series data is said to be stationary if it does not exhibit trends or seasonality. That is, the mean, variance and covariance should be the same for any segment of the series, and are not functions of time.The file samples.csv contains made-up datasets that illustrate stationary and non-stationary dat...
df2 = pd.read_csv('../Data/samples.csv',index_col=0,parse_dates=True) df2.head() df2['a'].plot(ylim=[0,100],title="STATIONARY DATA").autoscale(axis='x',tight=True); df2['b'].plot(ylim=[0,100],title="NON-STATIONARY DATA").autoscale(axis='x',tight=True); df2['c'].plot(ylim=[0,10000],title="MORE NON-STATIONARY DATA").auto...
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
In an upcoming section we'll learn how to test for stationarity. Differencing First Order DifferencingNon-stationary data can be made to look stationary through differencing. A simple method called first order differencing calculates the difference between consecutive observations.    $y^{\prime}_t...
# Calculate the first difference of the non-stationary dataset "b" df2['d1b'] = df2['b'] - df2['b'].shift(1) df2[['b','d1b']].head()
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
Notice that differencing eliminates one or more rows of data from the beginning of the series.
df2['d1b'].plot(title="FIRST ORDER DIFFERENCE").autoscale(axis='x',tight=True);
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
An easier way to perform differencing on a pandas Series or DataFrame is to use the built-in .diff() method:
df2['d1b'] = df2['b'].diff() df2['d1b'].plot(title="FIRST ORDER DIFFERENCE").autoscale(axis='x',tight=True);
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
Forecasting on first order differenced dataWhen forecasting with first order differences, the predicted values have to be added back in to the original values in order to obtain an appropriate forecast.Let's say that the next five forecasted values after applying some model to df['d1b'] are [7,-2,5,-1,12]. We need to ...
# For our example we need to build a forecast series from scratch # First determine the most recent date in the training set, to know where the forecast set should start df2[['b']].tail(3) # Next set a DateTime index for the forecast set that extends 5 periods into the future idx = pd.date_range('1960-01-01', periods=5...
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
The idea behind an inverse transformation is to start with the most recent value from the training set, and to add a cumulative sum of Fcast values to build the new forecast set. For this we'll use the pandas .cumsum() function which does the reverse of .diff()
z['forecast']=df2['b'].iloc[-1] + z['Fcast'].cumsum() z df2['b'].plot(figsize=(12,5), title="FORECAST").autoscale(axis='x',tight=True) z['forecast'].plot();
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
Second order differencingSometimes the first difference is not enough to attain stationarity, particularly if the trend is not linear. We can difference the already differenced values again to obtain a second order set of values.    $\begin{split}y_{t}^{\prime\prime} &= y_{t}^{\prime} - y_{t-1}^{\p...
# First we'll look at the first order difference of dataset "c" df2['d1c'] = df2['c'].diff() df2['d1c'].plot(title="FIRST ORDER DIFFERENCE").autoscale(axis='x',tight=True);
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
Now let's apply a second order difference to dataset "c".
# We can do this from the original time series in one step df2['d2c'] = df2['c'].diff().diff() df2[['c','d1c','d2c']].head() df2['d2c'].plot(title="SECOND ORDER DIFFERENCE").autoscale(axis='x',tight=True);
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
NOTE: This is different from df2['c'].diff(2), which would provide a first order difference spaced 2 lags apart.We'll use this technique later to address seasonality. Forecasting on second order differenced dataAs before, the prediction values have to be added back in to obtain an appropriate forecast.To invert the se...
# For our example we need to build a forecast series from scratch idx = pd.date_range('1960-01-01', periods=5, freq='MS') z = pd.DataFrame([7,-2,5,-1,12],index=idx,columns=['Fcast']) z
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
One way to invert a 2nd order transformation is to follow the formula above:
forecast = [] # Capture the two most recent values from the training set v2,v1 = df2['c'].iloc[-2:] # Apply the formula for i in z['Fcast']: newval = i + 2*v1 - v2 forecast.append(newval) v2,v1 = v1,newval z['forecast']=forecast z
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
Another, perhaps more straightforward method is to create a first difference set from the second, then build the forecast set from the first difference. We'll again use the pandas .cumsum() function which does the reverse of .diff()
# Add the most recent first difference from the training set to the Fcast cumulative sum z['firstdiff'] = (df2['c'].iloc[-1]-df2['c'].iloc[-2]) + z['Fcast'].cumsum() # Now build the forecast values from the first difference set z['forecast'] = df2['c'].iloc[-1] + z['firstdiff'].cumsum() z[['Fcast','firstdiff','foreca...
_____no_output_____
MIT
tsa/jose/TSA_COURSE_NOTEBOOKS/06-General-Forecasting-Models/00-Introduction-to-Forecasting-Revised.ipynb
juspreet51/ml_templates
Create dataset
patient = HIVPatient(clipping=False,logscale=False) FQI_buffer = Buffer(50000) for j in tqdm(range(30)): s = patient.reset(mode="unhealthy") for i in range(200): a = np.random.choice(4) s_, r, d, _ = patient.step(a) FQI_buffer.append(s,a,r,s_,d) s = s_
100%|██████████| 30/30 [08:28<00:00, 16.96s/it]
MIT
Paul/Paul.ipynb
Fiona55/hiv_experiment
FQI
from sklearn.ensemble import RandomForestRegressor from typing import Optional,List, Callable from sklearn.base import BaseEstimator def estimator_factory(*args, **kwargs): return RandomForestRegressor(*args, **kwargs) def update(memory : Buffer, gamma : float = 0.98, estimator : Optional[BaseEstimator] ...
_____no_output_____
MIT
Paul/Paul.ipynb
Fiona55/hiv_experiment
Premier entraînement !
estimator = None for _ in tqdm(range(100)): estimator = update(FQI_buffer,estimator=estimator)
0%| | 0/100 [00:00<?, ?it/s]/tmp/ipykernel_1097/1251894869.py:38: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel(). estimator.fit(data,target) 1%| | 1/100 [00:03<06:22, 3.86s/it]/tmp/ipykern...
MIT
Paul/Paul.ipynb
Fiona55/hiv_experiment
Deuxième entraînement
for j in tqdm(range(30)): s = patient.reset(mode="unhealthy") for step in range(200): if np.random.random()<0.15: action = np.random.choice(4) else: if estimator is not None: greedy = np.zeros((4,2)) for a in range(4): ...
100%|██████████| 100/100 [00:00<00:00, 56096.08it/s]
MIT
Paul/Paul.ipynb
Fiona55/hiv_experiment
Affichons les résultats
s = patient.reset(mode="unhealthy") T1,T2,T1_,T2_,V,E = np.zeros(200), np.zeros(200), np.zeros(200), np.zeros(200), np.zeros(200), np.zeros(200) actions = [] for step in tqdm(range(200)): T1[step], T2[step], T1_[step], T2_[step], V[step], E[step] = s greedy = np.zeros((4,2)) for a in range(4): ...
100%|██████████| 200/200 [00:59<00:00, 3.37it/s]
MIT
Paul/Paul.ipynb
Fiona55/hiv_experiment
Post traitement
actions plt.plot(np.log10(E)) plt.plot(np.log10(T1)) FQI_buffer.get() np.array(FQI_buffer.actions).shape _, _, rewards, _, _ = FQI_buffer.get()
_____no_output_____
MIT
Paul/Paul.ipynb
Fiona55/hiv_experiment
Generative models - variational auto-encoders Author: Philippe Esling (esling@ircam.fr)In this course we will cover1. A [quick recap](recap) on simple probability concepts (and in TensorFlow)2. A formal introduction to [Variational Auto-Encoders](vae) (VAEs)3. An explanation of the [implementation](implem) of VAEs4. S...
import tensorflow_probability as tfp import matplotlib.pyplot as plt import numpy as np import seaborn as sns
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Probability distributions Discrete distributionsLet $\mathbf{x}$ be a discrete random variable with range $R_{X}=\{x_1,\cdots,x_n\}$ (finite or countably infinite). The function\begin{equation} p_{X}(x_{i})=p(X=x_{i}), \forall i\in\{1,\cdots,n\}\end{equation}is called the probability mass function (PMF) of $X$.Henc...
bernoulli = tfp.distributions.Bernoulli(probs=0.5) samples = bernoulli.sample(10000) sns.distplot(samples) plt.title("Samples from a Bernoulli (coin toss)") plt.show()
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
However, we can also _sample_ from the distribution to have individual values of a single throw. In that case, we obtain a series of separate events that _follow_ the distribution
vals = ['heads', 'tails'] samples = bernoulli.sample(10) for s in samples: print('Coin is tossed on ' + vals[s])
Coin is tossed on heads Coin is tossed on heads Coin is tossed on tails Coin is tossed on heads Coin is tossed on heads Coin is tossed on tails Coin is tossed on tails Coin is tossed on heads Coin is tossed on tails Coin is tossed on tails
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Continuous distributionsThe same ideas apply to _continuous_ random variables, which can model for instance the height of human beings. If we try to guess the height of someone that we do not know, there is a higher probability that this person will be around 1m70, instead of 20cm or 3m. For the rest of this course, w...
normal = tfp.distributions.Normal(loc=0., scale=1.) samples = normal.sample(10000) sns.distplot(samples) plt.title("Samples from a standard Normal") plt.show()
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Comparing distributions (KL divergence)$\newcommand{\R}{\mathbb{R}}\newcommand{\bb}[1]{\mathbf{1}}\newcommand{\bx}{\bb{x}}\newcommand{\by}{\bb{y}}\newcommand{\bz}{\bb{z}}\newcommand{\KL}[2]{\mathcal{D}_{\text{KL}}\left[1 \| 2\right]}$Originally defined in the field of information theory, the _Kullback-Leibler (KL) div...
import tensorflow as tf from sklearn.metrics import accuracy_score, precision_score, recall_score from sklearn.model_selection import train_test_split from tensorflow.keras import layers, losses from tensorflow.keras.datasets import fashion_mnist from tensorflow.keras.models import Model class AE(Model): def __ini...
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
In order to move to a probabilistic version, we need to add the latent space sampling mechanism, and change the behavior of our `call` function. This process is implemented in the following `VAE` class.Note that we purposedly rely on an implementation of the `encode` function where the `encoder` first produces an inter...
class VAE(AE): def __init__(self, encoder, decoder, encoding_dims, latent_dims): super(VAE, self).__init__(encoder, decoder, encoding_dims) self.latent_dims = latent_dims self.mu = layers.Dense(self.latent_dims, activation='relu') self.sigma = layers.Dense(self.latent_dims, acti...
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Now the interesting aspect of VAEs is that we can define any parametric function as `encoder` and `decoder`, as long as we can optimize them. Here, we will rely on simple feed-forward neural networks, but these can be largely more complex (with limitations that we will discuss later in the tutorial).
def construct_encoder_decoder(nin, n_latent = 16, n_hidden = 512, n_classes = 1): # Encoder network encoder = tf.keras.Sequential([ layers.Flatten(), layers.Dense(n_hidden, activation='relu'), layers.Dense(n_hidden, activation='relu'), layers.Dense(n_hidden, activation='r...
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Evaluating the errorIn the definition of the `VAE` class, we directly included the computation of the $D_{KL}$ term to regularize our latent space. However, remember that the complete loss of equation (4) also contains a *reconstruction loss* which compares our reconstructed output to the original data. While there ar...
optimizer = tf.keras.optimizers.Adam(1e-4) def compute_loss(model, x): x_tilde, kl_div = model(x) cross_ent = tf.nn.sigmoid_cross_entropy_with_logits(logits=x_tilde, labels=x) logpx_z = -tf.reduce_sum(cross_ent, axis=[1, 2]) return -tf.reduce_mean(logpx_z + kl_div) @tf.function def train_step(model, x...
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Optimizing a VAE on a real datasetFor this tutorial, we are going to take a quick shot at a real-life problem by trying to train our VAEs on the `FashionMNIST` dataset. This dataset can be natively used in PyTorch by relying on the `torchvision.datasets` classes as follows
# Load (and eventually download) the dataset (x_train, _), (x_test, _) = fashion_mnist.load_data() # Normalize the dataset in the [0, 1] range] x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255.
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
The `FashionMNIST` dataset is composed of simple 28x28 black and white images of different items of clothings (such as shoes, bags, pants and shirts). We put a simple function here to display one batch of the test set (note that we keep a fixed batch from the test set in order to evaluate the different variations that ...
def plot_batch(batch, nslices=8): # Create one big image for plot img = np.zeros(((batch.shape[1] + 1) * nslices, (batch.shape[2] + 1) * nslices)) for b in range(batch.shape[0]): row = int(b / nslices); col = int(b % nslices) r_p = row * batch.shape[1] + row; c_p = col * batch.shape[2] + col...
(10000, 28, 28)
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Now based on our proposed implementation, the optimization aspects are defined in a very usual way
# Using Bernoulli or Multinomial loss num_classes = 1 # Number of hidden and latent n_hidden = 512 n_latent = 2 # Compute input dimensionality nin = fixed_batch.shape[1] * fixed_batch.shape[2] # Construct encoder and decoder encoder, decoder = construct_encoder_decoder(nin, n_hidden = n_hidden, n_latent = n_latent, n_c...
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Now all that is left to do is train the model. We define here a `train_vae` function that we will reuse along the future implementations and variations of VAEs and flows. Note that this function is set to run for only a very few number of `epochs` and also most importantly, *only considers a subsample of the full datas...
def generate_and_save_images(model, epoch, test_sample): predictions, _ = model(test_sample) fig = plt.figure(figsize=(4, 4)) for i in range(predictions.shape[0]): plt.subplot(4, 4, i + 1) plt.imshow(predictions[i, :, :], cmap='gray') plt.axis('off') # tight_layout minimizes the ...
Epoch: 1, Test set ELBO: nan
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Evaluating generative modelsIn order to evaluate our upcoming generative models, we will rely on the computation of the Negative Log-Likelihood. This code for the following `evaluate_nll_bpd` is inspired by the [Sylvester flow repository](https://github.com/riannevdberg/sylvester-flows)
from scipy.special import logsumexp def evaluate_nll_bpd(data_loader, model, batch = 500, R = 5): # Set of likelihood tests likelihood_test = [] # Go through dataset for batch_idx, (x, _) in enumerate(data_loader): for j in range(x.shape[0]): a = [] for r in range(0, R):...
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Now we can evaluate our VAE model more formally as follows.
# Plot final loss plt.figure() plt.plot(losses_kld[:, 0].numpy()); # Evaluate log-likelihood and bits per dim nll, _ = evaluate_nll_bpd(test_loader, model) print('Negative Log-Likelihood : ' + str(nll))
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Limitations of VAEs - (**exercise**)Although VAEs are extremely powerful tools, they still have some limitations. Here we list the three most important and known limitations (all of them are still debated and topics of active research). 1. **Blurry reconstructions.** As can be witnessed directly in the results of the ...
def construct_encoder_decoder_complex(nin, n_latent = 16, n_hidden = 512, n_params = 0, n_classes = 1): # Encoder network encoder = ... # Decoder network decoder = ... return encoder, decoder
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Preventing posterior collapse with Wasserstein-VAE-MMD (InfoVAE)As we discussed earlier, the reason behind posterior collapse mostly relates to the KL divergence criterion (a nice intuitive explanation can be found [here](https://ermongroup.github.io/blog/a-tutorial-on-mmd-variational-autoencoders/). This can be mitig...
def compute_kernel(x, y): return ... def compute_mmd(x, y): return ... class InfoVAEMMD(VAE): def __init__(self, encoder, decoder): super(InfoVAEMMD, self).__init__(encoder, decoder) def latent(self, x, z_params): return ...
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Putting it all togetherHere we combine all these ideas (except for the MMD, which is not adequate as the flow definition already regularizes the latent space without the KL divergence) to perform a more advanced optimization of the dataset. Hence, we will rely on the complex encoder and decoder with gated convolutions...
# Size of latent space n_latent = 16 # Number of hidden units n_hidden = 256 # Rely on Bernoulli or multinomial num_classes = 128 # Construct encoder and decoder encoder, decoder = ... # Create VAE or (InfoVAEMMD - WAE) model model_flow_p = ... # Create optimizer algorithm optimizer = ... # Add learning rate scheduler ...
_____no_output_____
MIT
documents/atiam_ml/05b_probabilistic_machine_learning.ipynb
esling/esling.github.io
Tutorial 3 - Boosting Search via Symmetry Breaking, Implied Constraints, Randomisation, and Restarts revisit the exact parameters so that restars work) **Please do not read untill you fully finish the first 2 tutorials**Congratulations! you are now level one constraint programmer: you know the basics on how to model ...
from config import setup setup()
_____no_output_____
CC-BY-3.0
teaching/2021-2022/5-cp/Tutorial3.ipynb
siala/siala.github.io
Golomb rulerYour goal is to place $N$ marks on a ruler, such that no two marks are at the same distance and the total length of the ruler (the position of the last mark) is minimized. Golomb ruler of order 4 and length 6. This ruler is both optimal and perfect.Golomb ruler can be used in information theory to ...
### WARNING : This block takes a lot of time to execute # A lot of configurations try for instance
_____no_output_____
CC-BY-3.0
teaching/2021-2022/5-cp/Tutorial3.ipynb
siala/siala.github.io
This notebook uses PRAW to pull the subreddits posted in of reddit users in antiwork
#Imports import praw import pandas as pd import datetime as dt import csv import prawcore.exceptions
_____no_output_____
MIT
src/other-subreddits/Reddit_UComment_Subs.ipynb
alu13/Antiwork_Analysis
We import the file of all usernames in antiwork, then loop through their posts and the subsequent subreddits.
df = pd.read_csv ('user_stats.csv') reddit = praw.Reddit(client_id='blb2ZuNkAGWKyPJr_ruqOw', client_secret='9IYM0Ba4kJQBKKP9H9ZTVkkDgtrSsQ', user_agent='6471_Project') #number of observations size = df.shape[0] print("total users within Anti-Work Subreddit ", size) #Users...
_____no_output_____
MIT
src/other-subreddits/Reddit_UComment_Subs.ipynb
alu13/Antiwork_Analysis
Univariate Analysis Target Variable
train['is_promoted'].value_counts(normalize=True) # Around 91% trainee have promoted # Unbalanced dataset
_____no_output_____
MIT
Gbm-tuning-best-from-50-to-53.ipynb
sid24rane/Promotion-OR-Not
Categorical Independent Variables
plt.figure(1) plt.subplot(221) train['department'].value_counts(normalize=True).plot.bar(figsize=(20,10), title= 'Department') plt.subplot(222) train['awards_won?'].value_counts(normalize=True).plot.bar(title= 'Awards won') plt.subplot(223) train['education'].value_counts(normalize=True).plot.bar(title= 'Education') ...
_____no_output_____
MIT
Gbm-tuning-best-from-50-to-53.ipynb
sid24rane/Promotion-OR-Not
Numerical Independent Variables
sns.distplot(train['age']); # Most of the trainee are in the age range of 20-30 and 40-50 sns.distplot(train['length_of_service']); sns.distplot(train['avg_training_score']);
_____no_output_____
MIT
Gbm-tuning-best-from-50-to-53.ipynb
sid24rane/Promotion-OR-Not
Bivariate Analysis
# Correlation between numerical variables matrix = train.corr() f, ax = plt.subplots(figsize=(9, 6)) sns.heatmap(matrix, vmax=.8, square=True, cmap="BuPu"); # Not much correlation between the variables # program_id vs is_pass plt.figure(figsize=(12,4)) sns.barplot(train['department'], train['is_promoted']) plt.figure(f...
_____no_output_____
MIT
Gbm-tuning-best-from-50-to-53.ipynb
sid24rane/Promotion-OR-Not
Missing Values Treatment
# Check the number of missing values in each variable train.isnull().sum() # age and trainee_engagement_rating variables have missing values in it. test = pd.read_csv('test.csv') test.drop('employee_id',inplace=True,axis = 1) test.head() test['education'].fillna('other',inplace=True) test['previous_year_rating'].fillna...
_____no_output_____
MIT
Gbm-tuning-best-from-50-to-53.ipynb
sid24rane/Promotion-OR-Not
Logistic Regression
train.head() # Save target variable in separate dataset X = train.drop('is_promoted',axis=1) y = train.is_promoted test.head() # Apply dummies to the dataset X=pd.get_dummies(X) test=pd.get_dummies(test) from sklearn.ensemble import GradientBoostingClassifier from sklearn import cross_validation, metrics #Additional ...
_____no_output_____
MIT
Gbm-tuning-best-from-50-to-53.ipynb
sid24rane/Promotion-OR-Not
[View in Colaboratory](https://colab.research.google.com/github/3catz/DeepLearning-NLP/blob/master/Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb) TIME SERIES FORECASTING -- using Empirical Mode Decomposition with Fully Convolutional Networks for One-step ahead forec...
!pip install pyhht !pip install PeakUtils from sklearn.preprocessing import MinMaxScaler, RobustScaler from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score #import pandas_datareader.data as web from pandas import Series from pandas import DataFrame from pandas import concat import...
_____no_output_____
MIT
Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb
3catz/DeepLearning-NLP
Utilities: series to supervised
def series_to_supervised(data, n_in, n_out, dropnan=True): n_vars = 1 if type(data) is list else data.shape[1] df = DataFrame(data) cols, names = list(), list() # input sequence (t-n, ... t-1) for i in range(n_in, 0, -1): cols.append(df.shift(i)) names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)] #...
_____no_output_____
MIT
Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb
3catz/DeepLearning-NLP
Loading Data
from google.colab import files files.upload() import numpy as np data = np.fromfile("yourfilehere.dat", sep = "\n") print(data) len(data) import numpy as np data = np.genfromtxt("FLYahooop_IRX.csv", delimiter = ","); data = np.asarray(data); data.shape #Plot of Time Series from scipy.interpolate import interp...
(9000,)
MIT
Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb
3catz/DeepLearning-NLP
Empirical Mode DecompositionFrom Yang et. al (2015), a summary: **Empirical mode decomposition (EMD)** technique to decompose the nonstationary signal into a series of intrinsic mode functions (IMFs) [9–11]. This ability makes HHT competitive in processing various composite signals [12–14]. With HHT, complex signals ca...
from pyhht.emd import EMD from pyhht.visualization import plot_imfs decomposer1 = EMD(in_sample, maxiter = 10000) imfs1 = decomposer1.decompose() print("There are a total of %s IMFs" % len(imfs1)) #Plot the IMFs, from highest frequency to lowest. The last one should be a monotonic trend function. It is known as the ...
_____no_output_____
MIT
Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb
3catz/DeepLearning-NLP
Creating Datasets *Raw Data, using a certian number of lags; most of my experimentation has beeen with either 10 or 20.
in_sample = in_sample.reshape(-1,1); print(in_sample.shape) lookback = 10 data_f = series_to_supervised(in_sample, n_in = lookback, n_out = 1, dropnan = True) print(data_f.shape) data_f = np.asarray(data_f) Xr = data_f[:,:-1] Y = data_f[:,-1] print(Xr.shape, Y.shape)
(8990, 11) (8990, 10) (8990,)
MIT
Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb
3catz/DeepLearning-NLP
Use the IMFs--which are time series of equal length as the original signal, as features for convolutional/recurrent network.
imfs1.shape imfs1 = np.transpose(imfs1, (1,0)); imfs1.shape imf_df = series_to_supervised(imfs1, n_in = lookback, n_out = 1, dropnan = True) imf_df = np.expand_dims(imf_df, axis = 1) print(imf_df.shape) imf_df = np.reshape(imf_df, (imf_df.shape[0], (lookback +1), imfs1.shape[-1])) print(imf_df.shape) targets = imf_df...
(990, 11) (990, 1, 10) (990,)
MIT
Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb
3catz/DeepLearning-NLP
Partial autocorrelation If you were doing SARIMA analysis, you would want to know if this series is autoregressive and to what extent. this helps when calculating a good lag for prediction, that is, how many past values you need to accurately predict a future value.
from statsmodels.graphics.tsaplots import plot_acf from statsmodels.graphics.tsaplots import plot_pacf fig, axes = plt.subplots(2, figsize=(20,6)) fig1 = plot_acf(scaled_data,lags = 60, ax = axes[0]) fig2 = plot_pacf(scaled_data, lags = 100, ax = axes[1]) plt.show()
/usr/local/lib/python3.6/dist-packages/statsmodels/compat/pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead. from pandas.core import datetools
MIT
Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb
3catz/DeepLearning-NLP
Network Architecture and Model fitting
from keras.layers.advanced_activations import * from keras.regularizers import l1, l2 from sklearn.metrics import r2_score import keras.backend as K from keras.layers import ConvLSTM2D from keras.layers import LeakyReLU np.random.seed(2018) #inputs are (1, 20) and outputs are #(1 time step,17 features) def convs(x, n...
__________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_30 (InputLayer) ...
MIT
Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb
3catz/DeepLearning-NLP
preds = model.predict(testX, batch_size = 1) summed = np.sum(preds, axis = -1); print(summed.shape) test_preds = summed[:,0] plt.plot(test_preds)
(990, 1)
MIT
Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb
3catz/DeepLearning-NLP
R2 analysisIn statistics, the coefficient of determination, denoted R2 or r2 and pronounced "R squared", is the proportion of the variance in the dependent variable that is predictable from the independent variable(s).It is a statistic used in the context of statistical models whose main purpose is either the predicti...
print("Final R2 Score is: {}".format(r2_score(testY, test_preds))) fig = plt.figure(figsize = (20,6)) fig = plt.plot(test_preds, label = "PREDICTIONS") fig = plt.plot(testY, label = "TRUE DATA") plt.xlim([0,990]) plt.legend() plt.show() plt.clf() plt.cla() plt.close()
Final R2 Score is: 0.9888552530780896
MIT
Time_Series_Forecasting_with_EMD_and_Fully_Convolutional_Neural_Networks_on_the_IRX_data_set.ipynb
3catz/DeepLearning-NLP
Finetuning a pretrained QuartzNet on TIMITusing [thunder-speech](https://github.com/scart97/thunder-speech) I talk more about this project [here on Twitter](https://twitter.com/Irmuzy/status/1529087355377836032)
# hide !pip install thunder-speech wandb
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
Cloning the repository that contains `.csv`'s with processed labels and filepaths, courtesy of my coursemates.
!git clone https://github.com/mizoru/pronunciation-trainer.git
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
Getting the data and the imports ready
from kaggle import api api.dataset_download_files('mfekadu/darpa-timit-acousticphonetic-continuous-speech') import zipfile archive = zipfile.ZipFile('darpa-timit-acousticphonetic-continuous-speech.zip') archive.extractall()
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
This dataset is going to be used as noise
api.dataset_download_files('chrisfilo/urbansound8k') import zipfile archive = zipfile.ZipFile('urbansound8k.zip') archive.extractall('data') import thunder from thunder.callbacks import FinetuneEncoderDecoder from thunder.finetune import FinetuneCTCModule from thunder.data.dataset import BaseSpeechDataset from thunder....
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
Setting up Dataset and DataModule for trainingThe commented out code is the transforms I tried.
class TimitDataset(BaseSpeechDataset): def __init__( self, items: Sequence, force_mono: bool = True, sample_rate: int = 16000, time_stretch = None, volume = None, pitch = None, noise_files = None # 0.2, 0.2, 2 ): super().__init__(items, force_mono, sam...
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
Getting the tokens from the data
whole = '.'.join([t for t in labels.Transcription]) tokens = list(set(whole.split('.'))) len(tokens) def dot_tokenizer(s:str): return s.split('.')
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
Adapting pretrained weights
model = FinetuneCTCModule(QuartznetCheckpoint.QuartzNet15x5Base_En, decoder_class = conv1d_decoder, tokens = tokens, text_kwargs={'custom_tokenizer_function':dot_tokenizer})
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
These next five cells import the weights of the decoder from a trained models and adapt them into the new decoder.`correspondences` is a dictionary that assigns every token in the new decoder the corresponding token in the trained decoder to take the model parameters from.
correspnodences = {'s': 's', 'n': 'n', 'dʒ': 'j', 'd̚': 'd', 'w': 'w', 'b': 'b', 'g': 'g', 'm': 'm', 'l̩': 'l', 'f': 'f', 'l': 'l', 'j': 'y', 'k': 'k', 'eɪ': 'a', 'p̚': 'p', 'm̩': 'm', 'r': 'r', 't': 't', 'h': 'h', 'aʊ': 'o', 'n̩': 'n', 'i': 'e', 'b̚': 'b', 'p': 'p', ...
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
These `vocab` dictionaries give the function `adapt_into_new_decoder` the indices in the weight matrix of the decoder for the corresponding tokens.
old_vocab = checkpoint_model.text_transform.vocab.itos old_vocab = {k:v for (v, k) in enumerate(old_vocab)} new_vocab = {k:v for (v, k) in enumerate(model.text_transform.vocab.itos)} model.decoder = adapt_into_new_decoder(checkpoint_model.decoder, old_vocab, new_vocab, correspnodences) del checkpoint_model
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
Training
import wandb from pytorch_lightning.loggers import WandbLogger wandb_logger = WandbLogger(project='pronunciation-trainer', name='transform-thunder')
wandb: Currently logged in as: mizoru. Use `wandb login --relogin` to force relogin
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
Setting a higher `encoder_initial_lr_div` led to less overfitting.
trainer = pl.Trainer( gpus=-1, # Use all gpus max_epochs=30, callbacks=[FinetuneEncoderDecoder(unfreeze_encoder_at_epoch=15, encoder_initial_lr_div=100)], logger = wandb_logger ) trainer.fit(model = model, datamodule=dm) trainer.validate(model = model, datamodule=dm)
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
let's save our model for inference
model.to_torchscript("QuartzNet_thunderspeech.pt") wandb.save('QuartzNet_thunderspeech.pt', policy='now') wandb.finish()
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
Getting predictions for the app
loader = AudioFileLoader(sample_rate=16000) natives = pd.read_csv('pronunciation-trainer/natives.csv')
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
I came up with a small list of words that learners might struggle with differentiating.
subset = ["thin", "thing", "think", "fit", "feet", "bald", "bold", "food", "foot", "death", "deaf", "worm", "warm"] subset_df = natives[natives.replica.isin(subset)]
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
This dataset contains audio for single words.
!wget https://lingualibre.org/datasets/Q22-eng-English.zip import zipfile archive = zipfile.ZipFile('Q22-eng-English.zip') archive.extractall()
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
I get the raw prediction tensors and then convert them into the format I need.
model.eval() predicts = [] for i in range(len(subset_df)): path = str(Path('Q22-eng-English') / '/'.join(subset_df.path.iloc[i].split('/')[2:])) # print(path) try: audio = loader(path) predicts.append(model(audio, torch.tensor(audio.shape[0] * [audio.shape[-1]], device=audio.device))) except Exception: ...
_____no_output_____
Apache-2.0
_notebooks/2022-05-24-thunder-speech-pronunciation-trainer.ipynb
mizoru/blog
nome = 'Guilherme Pereira' print(f'Meu nome é {nome}')
Meu nome é Guilherme Pereira
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Exercício: Modelo de Linguagem (Bengio 2003) - MLP + Embeddings Neste exercício iremos treinar uma rede neural simples para prever a proxima palavra de um texto, data as palavras anteriores como entrada. Esta tarefa é chamada de "Modelagem da Língua".Este dataset já possui um tamanho razoável e é bem provável que voc...
# iremos utilizar a biblioteca dos transformers para ter acesso ao tokenizador do BERT. !pip install transformers
Collecting transformers Downloading transformers-4.19.2-py3-none-any.whl (4.2 MB)  |████████████████████████████████| 4.2 MB 5.2 MB/s [?25hRequirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.7/dist-packages (from transformers) (4.64.0) Requirement already satisfied: importlib-metadata in /usr...
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Importação dos pacotes
import collections import itertools import functools import math import random import torch import torch.nn as nn import numpy as np from torch.utils.data import DataLoader from tqdm import tqdm_notebook # Check which GPU we are using !nvidia-smi if torch.cuda.is_available(): dev = "cuda:0" else: dev = "cpu" ...
Using cuda:0
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Implementação do MyDataset
from typing import List def tokenize(text: str, tokenizer): return tokenizer(text, return_tensors=None, add_special_tokens=False).input_ids class MyDataset(): def __init__(self, texts: List[str], tokenizer, context_size: int): # Escreva seu código aqui self.tokens, self.target = [], [] ...
_____no_output_____
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Teste se sua implementação do MyDataset está correta
from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained("neuralmind/bert-base-portuguese-cased") dummy_texts = ['Eu gosto de correr', 'Ela gosta muito de comer pizza'] dummy_dataset = MyDataset(texts=dummy_texts, tokenizer=tokenizer, context_size=3) dummy_loader = DataLoader(dummy_dataset, b...
_____no_output_____
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Carregamento do dataset Iremos usar uma pequena amostra do dataset [BrWaC](https://www.inf.ufrgs.br/pln/wiki/index.php?title=BrWaC) para treinar e avaliar nosso modelo de linguagem.
!wget -nc https://storage.googleapis.com/unicamp-dl/ia025a_2022s1/aula7/sample_brwac.txt # Load datasets context_size = 9 valid_examples = 100 test_examples = 100 texts = open('sample_brwac.txt').readlines() # print('Truncating for debugging purposes.') # texts = texts[:500] training_texts = texts[:-(valid_example...
_____no_output_____
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Teste o modelo com um exemplo
model = LanguageModel( vocab_size=tokenizer.vocab_size, context_size=context_size, embedding_dim=64, hidden_size=128, ).to(device) sample_train, _ = next(iter(DataLoader(training_dataset))) sample_train_gpu = sample_train.to(device) model(sample_train_gpu).shape num_params = sum(p.numel() for p in mode...
Number of model parameters: 6180096
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Assert da Perplexidade
random.seed(123) np.random.seed(123) torch.manual_seed(123) def perplexity(logits, target): """ Computes the perplexity. Args: logits: a FloatTensor of shape (batch_size, vocab_size) target: a LongTensor of shape (batch_size,) Returns: A float corresponding to the perplexity....
my perplexity: 30139 correct initial perplexity: 29794 Passou o no assert da perplexidade
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Laço de Treinamento e Validação
max_examples = 200_000_000 eval_every_steps = 5000 lr = 3.5e-5 batch_size = 1024 model = LanguageModel( vocab_size=tokenizer.vocab_size, context_size=context_size, embedding_dim=128, hidden_size=256, ).to(device) train_loader = DataLoader(training_dataset, batch_size=batch_size, shuffle=True, drop_la...
0 steps; 0 examples so far; train ppl: 29804.25, valid ppl: 29721.71 5000 steps; 5120000 examples so far; train ppl: 1493.07, valid ppl: 1092.24 10000 steps; 10240000 examples so far; train ppl: 931.18, valid ppl: 815.84 15000 steps; 15360000 examples so far; train ppl: 741.66, valid ppl: 680.47 20000 steps; 20480000 e...
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Avaliação final no dataset de testeBonus: o modelo com menor perplexidade no dataset de testes ganhará 0.5 ponto na nota final.
test_loader = DataLoader(test_dataset, batch_size=64) with torch.no_grad(): test_ppl = np.exp(np.average([ validation_step(input.to(device), target.to(device)) for input, target in test_loader ])) print(f'test perplexity: {test_ppl}')
test perplexity: 171.63801942647711
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Teste seu modelo com uma sentençaEscolha uma sentença gerada pelo modelo que ache interessante.
prompt = 'Eu estou sozinho, sinto muita falta da minha namorada' max_output_tokens = 10 for _ in range(max_output_tokens): input_ids = tokenize(text=prompt, tokenizer=tokenizer) input_ids_truncated = input_ids[-context_size:] # Usamos apenas os últimos <context_size> tokens como entrada para o modelo. log...
_____no_output_____
MIT
ex07/Guilherme_Pereira/Aula_7_Guilherme_Pereira.ipynb
fabiormazza/IA025_2022S1
Network Training Includes
# mass includes import os, sys, warnings import ipdb import torch as t import torchnet as tnt from tqdm.notebook import tqdm # add paths for all sub-folders paths = [root for root, dirs, files in os.walk('.')] for item in paths: sys.path.append(item) from ipynb.fs.full.config import r2rNetConf from ipynb.fs.full....
_____no_output_____
MIT
train-r2rNet.ipynb
YCL92/deepSelfie
Initialization
# for debugging only %pdb off warnings.filterwarnings('ignore') # choose GPU if available os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = '0' device = t.device('cuda' if t.cuda.is_available() else 'cpu') # define model opt = r2rNetConf() model = r2rNet().to(device) # load pre-trai...
_____no_output_____
MIT
train-r2rNet.ipynb
YCL92/deepSelfie
Validation
def validate(): # set to evaluation mode model.eval() psnr = 0.0 for (raw_patch, srgb_patch, cam_wb) in val_loader: with t.no_grad(): # copy to device raw_patch = raw_patch.to(device) srgb_patch = srgb_patch.to(device) rggb_patch = toRGGB(srgb_pat...
_____no_output_____
MIT
train-r2rNet.ipynb
YCL92/deepSelfie
Training entry
for epoch in tqdm(range(last_epoch, opt.max_epoch), desc='epoch', total=opt.max_epoch - last_epoch): # reset meter and update learning rate loss_meter.reset() scheduler.step() for (raw_patch, srgb_patch, cam_wb) in train_loader: # reset gradient optim...
_____no_output_____
MIT
train-r2rNet.ipynb
YCL92/deepSelfie
This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). Challenge Notebook Problem: Implement breadth-first traversal on a binary tree.* [Constraints](Constraints)* [Test Cases](Test-Cases)* [Al...
# %load ../bst/bst.py class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None self.parent = None def __repr__(self): return str(self.data) class Bst(object): def __init__(self, root=None): self.root = root de...
_____no_output_____
Apache-2.0
graphs_trees/tree_bfs/bfs_challenge.ipynb
hanbf/interactive-coding-challenges
Unit Test
%run ../utils/results.py # %load test_bfs.py from nose.tools import assert_equal class TestBfs(object): def __init__(self): self.results = Results() def test_bfs(self): bst = BstBfs(Node(5)) bst.insert(2) bst.insert(8) bst.insert(1) bst.insert(3) bst.b...
Success: test_bfs
Apache-2.0
graphs_trees/tree_bfs/bfs_challenge.ipynb
hanbf/interactive-coding-challenges
Spatial merge census and precinct dataThis notebook will join precincts with census data. Spatial unit of analysis is the precinct. The aim is to join census data to each precinct. The problem is the precinct and block group boundaries don't match up. So, calculate census values for each precinct this way:For eac...
%matplotlib inline from geopandas import GeoDataFrame, read_file from geopandas.tools import overlay import pandas as pd import spatial_processing_functions as spf #import importlib #importlib.reload(spf)
_____no_output_____
BSD-3-Clause
vote_analysis/precincts-join-census.ipynb
lrayle/sf-voting
SF voting precincts. Boundaries are updated every ten years, and become active two years after the census. We have 1992, 2002, and 2012. years = ['1990','2000','2010','2009','2014']1990 census data -> 1992 precinct + 1990 bg (missing)2000, 2009 census data -> 2002 precincts + 2000 bgs2010, 2014 census data -> 2012 pre...
bgXprec = dict.fromkeys(['bg2000pre1992', 'bg2000pre2002', 'bg2010pre2012']) for yr_key in bgXprec.keys(): bgs = spf.load_bg_shp(yr_key[2:6]) precincts = spf.load_prec_shp(yr_key[9:13]) precincts = spf.reproject_prec(precincts) bgXprec[yr_key] = spf.merge_precinct_bg(precincts,bgs,yr_key) #yr_ke...
_____no_output_____
BSD-3-Clause
vote_analysis/precincts-join-census.ipynb
lrayle/sf-voting
Merge with census data
# We'll need the following combinations of censusXprecinct #ce2000pre1992, ce2000pre2002, ce2007pre2002, ce2012pre2012 <- for census data #'bg2000pre1992', 'bg2000pre2002', 'bg2010pre2012' <- for block groups # dictionary for matching correct year. # (although we don't actually need 1990 data. ) census2bg_year = {...
ce2000pre2002 586 precincts before 586 precincts after Sum >1.1 or <.97: precname 2009 0.968559 Name: prop_area, dtype: float64 saved as census_by_precinct_ce2000pre2002.csv ce2007pre2002 586 precincts before 586 precincts after Sum >1.1 or <.97: precname 2009 0.968559 Name: prop_area, dtype: float64 saved ...
BSD-3-Clause
vote_analysis/precincts-join-census.ipynb
lrayle/sf-voting
Let's check out the precincts that don't total 1.0.. something may be wrong. Precinct 2009(2002) is on the SF border and has 931 registered voters. The 5 precincts(1992) with weird results are all on the southern SF border. These that are on the border probably don't add up to 1.0 because the boundaries are slightly di...
# look for other missing data. # can't find any other missing data here. for yr_key in census_data_by_precinct.keys(): print(len(census_data_by_precinct[yr_key][pd.isnull(census_data_by_precinct[yr_key]['med_inc_wgt'])]))
0 0 0 0
BSD-3-Clause
vote_analysis/precincts-join-census.ipynb
lrayle/sf-voting
Extract RGB values from imageThere are broadly three steps to find the dominant colors in an image:Extract RGB values into three lists.Perform k-means clustering on scaled RGB values.Display the colors of cluster centers.To extract RGB values, we use the imread() function of the image class of matplotlib. Empty lists,...
import matplotlib.image as img r = [] g = [] b = [] # Read batman image batman_image = img.imread('datasets/batman.jpg') print(batman_image.shape) for row in batman_image: for temp_r, temp_g, temp_b in row: r.append(temp_r) g.append(temp_g) b.append(temp_b) batman_df = pd.DataFrame({'red...
_____no_output_____
MIT
courses/cluster_analysis/cluster_analysis2.ipynb
albertoarenas/datacamp
How many dominant colors?We have loaded the following image using the imread() function of the image class of matplotlib.The RGB values are stored in a data frame, batman_df. The RGB values have been standardized used the whiten() function, stored in columns, scaled_red, scaled_blue and scaled_green.Construct an elbow...
from scipy.cluster.vq import kmeans, vq distortions = [] num_clusters = range(1, 7) # Create a list of distortions from the kmeans function for i in num_clusters: cluster_centers, distortion = kmeans(batman_df[['scaled_red', 'scaled_green', 'scaled_blue']], i) distortions.append(distortion) # Create a data f...
_____no_output_____
MIT
courses/cluster_analysis/cluster_analysis2.ipynb
albertoarenas/datacamp
RESULT: Notice that there are three distinct colors present in the image, which is supported by the elbow plot. Display dominant colorsWe have loaded the following image using the imread() function of the image class of matplotlib.To display the dominant colors, convert the colors of the cluster centers to their raw ...
colors = [] cluster_centers, distortion = kmeans(batman_df[['scaled_red', 'scaled_green', 'scaled_blue']], 3) # Get standard deviations of each color r_std, g_std, b_std = batman_df[['red', 'green', 'blue']].std() display(r_std, g_std, g_std) for cluster_center in cluster_centers: scaled_r, scaled_g, scaled_b = ...
_____no_output_____
MIT
courses/cluster_analysis/cluster_analysis2.ipynb
albertoarenas/datacamp
COMP90051 Workshop 3 Logistic regression***In this workshop we'll be implementing L2-regularised logistic regression using `scipy` and `numpy`. Our key objectives are:* to become familiar with the optimisation problem that sits behind L2-regularised logistic regression;* to apply polynomial basis expansion and recogni...
%matplotlib inline import numpy as np import matplotlib.pyplot as plt
_____no_output_____
MIT
Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb
infinityglow/Unimelb-CS-Subjects
1. Binary classification dataLet's begin by generating some binary classification data.To make it easy for us to visualise the results, we'll stick to a two-dimensional feature space.
from sklearn.datasets import make_circles X, Y = make_circles(n_samples=300, noise=0.1, factor=0.7, random_state=90051) plt.plot(X[Y==0,0], X[Y==0,1], 'o', label = "y=0") plt.plot(X[Y==1,0], X[Y==1,1], 's', label = "y=1") plt.legend() plt.xlabel("$x_0$") plt.ylabel("$x_1$") plt.show()
_____no_output_____
MIT
Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb
infinityglow/Unimelb-CS-Subjects
**Question:** What's interesting about this data? Do you think logistic regression will perform well?**Answer:** *This question is answered in section 3.* In preparation for fitting and evaluating a logistic regression model, we randomly partition the data into train/test sets. We use the `train_test_split` function fr...
from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, random_state=90051) print("Training set has {} instances. Test set has {} instances.".format(X_train.shape[0], X_test.shape[0]))
Training set has 201 instances. Test set has 99 instances.
MIT
Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb
infinityglow/Unimelb-CS-Subjects