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
|
---|---|---|---|---|---|
Identifier for storing these features on disk and referring to them later. | feature_list_id = 'tfidf' | _____no_output_____ | MIT | notebooks/feature-tfidf.ipynb | MinuteswithMetrics/kaggle-quora-question-pairs |
Read Data Preprocessed and tokenized questions. | tokens_train = kg.io.load(project.preprocessed_data_dir + 'tokens_lowercase_spellcheck_no_stopwords_train.pickle')
tokens_test = kg.io.load(project.preprocessed_data_dir + 'tokens_lowercase_spellcheck_no_stopwords_test.pickle')
tokens = tokens_train + tokens_test | _____no_output_____ | MIT | notebooks/feature-tfidf.ipynb | MinuteswithMetrics/kaggle-quora-question-pairs |
Extract a set of unique question texts (document corpus). | all_questions_flat = np.array(tokens).ravel()
documents = list(set(' '.join(question) for question in all_questions_flat))
del all_questions_flat | _____no_output_____ | MIT | notebooks/feature-tfidf.ipynb | MinuteswithMetrics/kaggle-quora-question-pairs |
Train TF-IDF vectorizer Create a bag-of-token-unigrams vectorizer. | vectorizer = TfidfVectorizer(
encoding='utf-8',
analyzer='word',
strip_accents='unicode',
ngram_range=(1, 1),
lowercase=True,
norm='l2',
use_idf=True,
smooth_idf=True,
sublinear_tf=True,
)
vectorizer.fit(documents)
model_filename = 'tfidf_vectorizer_{}_ngrams_{}_{}_penalty_{}.pickle'.format(
vectorizer.analyzer,
vectorizer.ngram_range[0],
vectorizer.ngram_range[1],
vectorizer.norm,
)
kg.io.save(vectorizer, project.trained_model_dir + model_filename) | _____no_output_____ | MIT | notebooks/feature-tfidf.ipynb | MinuteswithMetrics/kaggle-quora-question-pairs |
Vectorize train and test sets, compute distances | def compute_pair_distances(pair):
q1_doc = ' '.join(pair[0])
q2_doc = ' '.join(pair[1])
pair_dtm = vectorizer.transform([q1_doc, q2_doc])
q1_doc_vec = pair_dtm[0]
q2_doc_vec = pair_dtm[1]
return [
cosine_distances(q1_doc_vec, q2_doc_vec)[0][0],
euclidean_distances(q1_doc_vec, q2_doc_vec)[0][0],
]
features = kg.jobs.map_batch_parallel(
tokens,
item_mapper=compute_pair_distances,
batch_size=1000,
)
X_train = np.array(features[:len(tokens_train)], dtype='float64')
X_test = np.array(features[len(tokens_train):], dtype='float64')
print('X_train:', X_train.shape)
print('X_test: ', X_test.shape) | X_train: (404290, 2)
X_test: (2345796, 2)
| MIT | notebooks/feature-tfidf.ipynb | MinuteswithMetrics/kaggle-quora-question-pairs |
Save features | feature_names = [
'tfidf_cosine',
'tfidf_euclidean',
]
project.save_features(X_train, X_test, feature_names, feature_list_id) | _____no_output_____ | MIT | notebooks/feature-tfidf.ipynb | MinuteswithMetrics/kaggle-quora-question-pairs |
PyMC3 Examples GLM Robust Regression with Outlier Detection**A minimal reproducable example of Robust Regression with Outlier Detection using Hogg 2010 Signal vs Noise method.**+ This is a complementary approach to the Student-T robust regression as illustrated in Thomas Wiecki's notebook in the [PyMC3 documentation](http://pymc-devs.github.io/pymc3/GLM-robust/), that approach is also compared here.+ This model returns a robust estimate of linear coefficients and an indication of which datapoints (if any) are outliers.+ The likelihood evaluation is essentially a copy of eqn 17 in "Data analysis recipes: Fitting a model to data" - [Hogg 2010](http://arxiv.org/abs/1008.4686).+ The model is adapted specifically from Jake Vanderplas' [implementation](http://www.astroml.org/book_figures/chapter8/fig_outlier_rejection.html) (3rd model tested).+ The dataset is tiny and hardcoded into this Notebook. It contains errors in both the x and y, but we will deal here with only errors in y.**Note:**+ Python 3.4 project using latest available [PyMC3](https://github.com/pymc-devs/pymc3)+ Developed using [ContinuumIO Anaconda](https://www.continuum.io/downloads) distribution on a Macbook Pro 3GHz i7, 16GB RAM, OSX 10.10.5.+ During development I've found that 3 data points are always indicated as outliers, but the remaining ordering of datapoints by decreasing outlier-hood is slightly unstable between runs: the posterior surface appears to have a small number of solutions with similar probability. + Finally, if runs become unstable or Theano throws weird errors, try clearing the cache `$> theano-cache clear` and rerunning the notebook.**Package Requirements (shown as a conda-env YAML):**```$> less conda_env_pymc3_examples.ymlname: pymc3_examples channels: - defaults dependencies: - python=3.4 - ipython - ipython-notebook - ipython-qtconsole - numpy - scipy - matplotlib - pandas - seaborn - patsy - pip$> conda env create --file conda_env_pymc3_examples.yml$> source activate pymc3_examples$> pip install --process-dependency-links git+https://github.com/pymc-devs/pymc3``` Setup | %matplotlib inline
%qtconsole --colors=linux
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import optimize
import pymc3 as pm
import theano as thno
import theano.tensor as T
# configure some basic options
sns.set(style="darkgrid", palette="muted")
pd.set_option('display.notebook_repr_html', True)
plt.rcParams['figure.figsize'] = 12, 8
np.random.seed(0) | _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
Load and Prepare Data We'll use the Hogg 2010 data available at https://github.com/astroML/astroML/blob/master/astroML/datasets/hogg2010test.pyIt's a very small dataset so for convenience, it's hardcoded below | #### cut & pasted directly from the fetch_hogg2010test() function
## identical to the original dataset as hardcoded in the Hogg 2010 paper
dfhogg = pd.DataFrame(np.array([[1, 201, 592, 61, 9, -0.84],
[2, 244, 401, 25, 4, 0.31],
[3, 47, 583, 38, 11, 0.64],
[4, 287, 402, 15, 7, -0.27],
[5, 203, 495, 21, 5, -0.33],
[6, 58, 173, 15, 9, 0.67],
[7, 210, 479, 27, 4, -0.02],
[8, 202, 504, 14, 4, -0.05],
[9, 198, 510, 30, 11, -0.84],
[10, 158, 416, 16, 7, -0.69],
[11, 165, 393, 14, 5, 0.30],
[12, 201, 442, 25, 5, -0.46],
[13, 157, 317, 52, 5, -0.03],
[14, 131, 311, 16, 6, 0.50],
[15, 166, 400, 34, 6, 0.73],
[16, 160, 337, 31, 5, -0.52],
[17, 186, 423, 42, 9, 0.90],
[18, 125, 334, 26, 8, 0.40],
[19, 218, 533, 16, 6, -0.78],
[20, 146, 344, 22, 5, -0.56]]),
columns=['id','x','y','sigma_y','sigma_x','rho_xy'])
## for convenience zero-base the 'id' and use as index
dfhogg['id'] = dfhogg['id'] - 1
dfhogg.set_index('id', inplace=True)
## standardize (mean center and divide by 1 sd)
dfhoggs = (dfhogg[['x','y']] - dfhogg[['x','y']].mean(0)) / dfhogg[['x','y']].std(0)
dfhoggs['sigma_y'] = dfhogg['sigma_y'] / dfhogg['y'].std(0)
dfhoggs['sigma_x'] = dfhogg['sigma_x'] / dfhogg['x'].std(0)
## create xlims ylims for plotting
xlims = (dfhoggs['x'].min() - np.ptp(dfhoggs['x'])/5
,dfhoggs['x'].max() + np.ptp(dfhoggs['x'])/5)
ylims = (dfhoggs['y'].min() - np.ptp(dfhoggs['y'])/5
,dfhoggs['y'].max() + np.ptp(dfhoggs['y'])/5)
## scatterplot the standardized data
g = sns.FacetGrid(dfhoggs, size=8)
_ = g.map(plt.errorbar, 'x', 'y', 'sigma_y', 'sigma_x', marker="o", ls='')
_ = g.axes[0][0].set_ylim(ylims)
_ = g.axes[0][0].set_xlim(xlims)
plt.subplots_adjust(top=0.92)
_ = g.fig.suptitle('Scatterplot of Hogg 2010 dataset after standardization', fontsize=16) | _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
**Observe**: + Even judging just by eye, you can see these datapoints mostly fall on / around a straight line with positive gradient+ It looks like a few of the datapoints may be outliers from such a line ------ Create Conventional OLS Model The *linear model* is really simple and conventional:$$\bf{y} = \beta^{T} \bf{X} + \bf{\sigma}$$where: $\beta$ = coefs = $\{1, \beta_{j \in X_{j}}\}$ $\sigma$ = the measured error in $y$ in the dataset `sigma_y` Define model**NOTE:**+ We're using a simple linear OLS model with Normally distributed priors so that it behaves like a ridge regression | with pm.Model() as mdl_ols:
## Define weakly informative Normal priors to give Ridge regression
b0 = pm.Normal('b0_intercept', mu=0, sd=100)
b1 = pm.Normal('b1_slope', mu=0, sd=100)
## Define linear model
yest = b0 + b1 * dfhoggs['x']
## Use y error from dataset, convert into theano variable
sigma_y = thno.shared(np.asarray(dfhoggs['sigma_y'],
dtype=thno.config.floatX), name='sigma_y')
## Define Normal likelihood
likelihood = pm.Normal('likelihood', mu=yest, sd=sigma_y, observed=dfhoggs['y'])
| _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
Sample | with mdl_ols:
## find MAP using Powell, seems to be more robust
start_MAP = pm.find_MAP(fmin=optimize.fmin_powell, disp=True)
## take samples
traces_ols = pm.sample(2000, start=start_MAP, step=pm.NUTS(), progressbar=True) | Optimization terminated successfully.
Current function value: 145.777745
Iterations: 3
Function evaluations: 118
[-----------------100%-----------------] 2000 of 2000 complete in 0.9 sec | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
View Traces**NOTE**: I'll 'burn' the traces to only retain the final 1000 samples | _ = pm.traceplot(traces_ols[-1000:], figsize=(12,len(traces_ols.varnames)*1.5),
lines={k: v['mean'] for k, v in pm.df_summary(traces_ols[-1000:]).iterrows()}) | _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
**NOTE:** We'll illustrate this OLS fit and compare to the datapoints in the final plot ------ Create Robust Model: Student-T Method I've added this brief section in order to directly compare the Student-T based method exampled in Thomas Wiecki's notebook in the [PyMC3 documentation](http://pymc-devs.github.io/pymc3/GLM-robust/)Instead of using a Normal distribution for the likelihood, we use a Student-T, which has fatter tails. In theory this allows outliers to have a smaller mean square error in the likelihood, and thus have less influence on the regression estimation. This method does not produce inlier / outlier flags but is simpler and faster to run than the Signal Vs Noise model below, so a comparison seems worthwhile.**Note:** we'll constrain the Student-T 'degrees of freedom' parameter `nu` to be an integer, but otherwise leave it as just another stochastic to be inferred: no need for prior knowledge. Define Model | with pm.Model() as mdl_studentt:
## Define weakly informative Normal priors to give Ridge regression
b0 = pm.Normal('b0_intercept', mu=0, sd=100)
b1 = pm.Normal('b1_slope', mu=0, sd=100)
## Define linear model
yest = b0 + b1 * dfhoggs['x']
## Use y error from dataset, convert into theano variable
sigma_y = thno.shared(np.asarray(dfhoggs['sigma_y'],
dtype=thno.config.floatX), name='sigma_y')
## define prior for Student T degrees of freedom
nu = pm.DiscreteUniform('nu', lower=1, upper=100)
## Define Student T likelihood
likelihood = pm.StudentT('likelihood', mu=yest, sd=sigma_y, nu=nu
,observed=dfhoggs['y'])
| _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
Sample | with mdl_studentt:
## find MAP using Powell, seems to be more robust
start_MAP = pm.find_MAP(fmin=optimize.fmin_powell, disp=True)
## two-step sampling to allow Metropolis for nu (which is discrete)
step1 = pm.NUTS([b0, b1])
step2 = pm.Metropolis([nu])
## take samples
traces_studentt = pm.sample(2000, start=start_MAP, step=[step1, step2], progressbar=True) | Optimization terminated successfully.
Current function value: 107.488021
Iterations: 3
Function evaluations: 77
[-----------------100%-----------------] 2000 of 2000 complete in 1.0 sec | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
View Traces | _ = pm.traceplot(traces_studentt[-1000:]
,figsize=(12,len(traces_studentt.varnames)*1.5)
,lines={k: v['mean'] for k, v in pm.df_summary(traces_studentt[-1000:]).iterrows()}) | _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
**Observe:**+ Both parameters `b0` and `b1` show quite a skew to the right, possibly this is the action of a few samples regressing closer to the OLS estimate which is towards the left+ The `nu` parameter seems very happy to stick at `nu = 1`, indicating that a fat-tailed Student-T likelihood has a better fit than a thin-tailed (Normal-like) Student-T likelihood.+ The inference sampling also ran very quickly, almost as quickly as the conventional OLS**NOTE:** We'll illustrate this Student-T fit and compare to the datapoints in the final plot ------ Create Robust Model with Outliers: Hogg Method Please read the paper (Hogg 2010) and Jake Vanderplas' code for more complete information about the modelling technique.The general idea is to create a 'mixture' model whereby datapoints can be described by either the linear model (inliers) or a modified linear model with different mean and larger variance (outliers).The likelihood is evaluated over a mixture of two likelihoods, one for 'inliers', one for 'outliers'. A Bernouilli distribution is used to randomly assign datapoints in N to either the inlier or outlier groups, and we sample the model as usual to infer robust model parameters and inlier / outlier flags:$$\mathcal{logL} = \sum_{i}^{i=N} log \left[ \frac{(1 - B_{i})}{\sqrt{2 \pi \sigma_{in}^{2}}} exp \left( - \frac{(x_{i} - \mu_{in})^{2}}{2\sigma_{in}^{2}} \right) \right] + \sum_{i}^{i=N} log \left[ \frac{B_{i}}{\sqrt{2 \pi (\sigma_{in}^{2} + \sigma_{out}^{2})}} exp \left( - \frac{(x_{i}- \mu_{out})^{2}}{2(\sigma_{in}^{2} + \sigma_{out}^{2})} \right) \right]$$where: $\bf{B}$ is Bernoulli-distibuted $B_{i} \in [0_{(inlier)},1_{(outlier)}]$ Define model | def logp_signoise(yobs, is_outlier, yest_in, sigma_y_in, yest_out, sigma_y_out):
'''
Define custom loglikelihood for inliers vs outliers.
NOTE: in this particular case we don't need to use theano's @as_op
decorator because (as stated by Twiecki in conversation) that's only
required if the likelihood cannot be expressed as a theano expression.
We also now get the gradient computation for free.
'''
# likelihood for inliers
pdfs_in = T.exp(-(yobs - yest_in + 1e-4)**2 / (2 * sigma_y_in**2))
pdfs_in /= T.sqrt(2 * np.pi * sigma_y_in**2)
logL_in = T.sum(T.log(pdfs_in) * (1 - is_outlier))
# likelihood for outliers
pdfs_out = T.exp(-(yobs - yest_out + 1e-4)**2 / (2 * (sigma_y_in**2 + sigma_y_out**2)))
pdfs_out /= T.sqrt(2 * np.pi * (sigma_y_in**2 + sigma_y_out**2))
logL_out = T.sum(T.log(pdfs_out) * is_outlier)
return logL_in + logL_out
with pm.Model() as mdl_signoise:
## Define weakly informative Normal priors to give Ridge regression
b0 = pm.Normal('b0_intercept', mu=0, sd=100)
b1 = pm.Normal('b1_slope', mu=0, sd=100)
## Define linear model
yest_in = b0 + b1 * dfhoggs['x']
## Define weakly informative priors for the mean and variance of outliers
yest_out = pm.Normal('yest_out', mu=0, sd=100)
sigma_y_out = pm.HalfNormal('sigma_y_out', sd=100)
## Define Bernoulli inlier / outlier flags according to a hyperprior
## fraction of outliers, itself constrained to [0,.5] for symmetry
frac_outliers = pm.Uniform('frac_outliers', lower=0., upper=.5)
is_outlier = pm.Bernoulli('is_outlier', p=frac_outliers, shape=dfhoggs.shape[0])
## Extract observed y and sigma_y from dataset, encode as theano objects
yobs = thno.shared(np.asarray(dfhoggs['y'], dtype=thno.config.floatX), name='yobs')
sigma_y_in = thno.shared(np.asarray(dfhoggs['sigma_y']
, dtype=thno.config.floatX), name='sigma_y_in')
## Use custom likelihood using DensityDist
likelihood = pm.DensityDist('likelihood', logp_signoise,
observed={'yobs':yobs, 'is_outlier':is_outlier,
'yest_in':yest_in, 'sigma_y_in':sigma_y_in,
'yest_out':yest_out, 'sigma_y_out':sigma_y_out})
| _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
Sample | with mdl_signoise:
## two-step sampling to create Bernoulli inlier/outlier flags
step1 = pm.NUTS([frac_outliers, yest_out, sigma_y_out, b0, b1])
step2 = pm.BinaryMetropolis([is_outlier], tune_interval=100)
## find MAP using Powell, seems to be more robust
start_MAP = pm.find_MAP(fmin=optimize.fmin_powell, disp=True)
## take samples
traces_signoise = pm.sample(2000, start=start_MAP, step=[step1,step2], progressbar=True) | Optimization terminated successfully.
Current function value: 155.449990
Iterations: 3
Function evaluations: 213
[-----------------100%-----------------] 2000 of 2000 complete in 169.1 sec | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
View Traces | _ = pm.traceplot(traces_signoise[-1000:], figsize=(12,len(traces_signoise.varnames)*1.5),
lines={k: v['mean'] for k, v in pm.df_summary(traces_signoise[-1000:]).iterrows()}) | _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
**NOTE:**+ During development I've found that 3 datapoints id=[1,2,3] are always indicated as outliers, but the remaining ordering of datapoints by decreasing outlier-hood is unstable between runs: the posterior surface appears to have a small number of solutions with very similar probability.+ The NUTS sampler seems to work okay, and indeed it's a nice opportunity to demonstrate a custom likelihood which is possible to express as a theano function (thus allowing a gradient-based sampler like NUTS). However, with a more complicated dataset, I would spend time understanding this instability and potentially prefer using more samples under Metropolis-Hastings. ------ Declare Outliers and Compare Plots View ranges for inliers / outlier predictions At each step of the traces, each datapoint may be either an inlier or outlier. We hope that the datapoints spend an unequal time being one state or the other, so let's take a look at the simple count of states for each of the 20 datapoints. | outlier_melt = pd.melt(pd.DataFrame(traces_signoise['is_outlier', -1000:],
columns=['[{}]'.format(int(d)) for d in dfhoggs.index]),
var_name='datapoint_id', value_name='is_outlier')
ax0 = sns.pointplot(y='datapoint_id', x='is_outlier', data=outlier_melt,
kind='point', join=False, ci=None, size=4, aspect=2)
_ = ax0.vlines([0,1], 0, 19, ['b','r'], '--')
_ = ax0.set_xlim((-0.1,1.1))
_ = ax0.set_xticks(np.arange(0, 1.1, 0.1))
_ = ax0.set_xticklabels(['{:.0%}'.format(t) for t in np.arange(0,1.1,0.1)])
_ = ax0.yaxis.grid(True, linestyle='-', which='major', color='w', alpha=0.4)
_ = ax0.set_title('Prop. of the trace where datapoint is an outlier')
_ = ax0.set_xlabel('Prop. of the trace where is_outlier == 1') | _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
**Observe**:+ The plot above shows the number of samples in the traces in which each datapoint is marked as an outlier, expressed as a percentage.+ In particular, 3 points [1, 2, 3] spend >=95% of their time as outliers+ Contrastingly, points at the other end of the plot close to 0% are our strongest inliers.+ For comparison, the mean posterior value of `frac_outliers` is ~0.35, corresponding to roughly 7 of the 20 datapoints. You can see these 7 datapoints in the plot above, all those with a value >50% or thereabouts.+ However, only 3 of these points are outliers >=95% of the time. + See note above regarding instability between runs.The 95% cutoff we choose is subjective and arbitrary, but I prefer it for now, so let's declare these 3 to be outliers and see how it looks compared to Jake Vanderplas' outliers, which were declared in a slightly different way as points with means above 0.68. Declare outliers**Note:**+ I will declare outliers to be datapoints that have value == 1 at the 5-percentile cutoff, i.e. in the percentiles from 5 up to 100, their values are 1. + Try for yourself altering cutoff to larger values, which leads to an objective ranking of outlier-hood. | cutoff = 5
dfhoggs['outlier'] = np.percentile(traces_signoise[-1000:]['is_outlier'],cutoff, axis=0)
dfhoggs['outlier'].value_counts() | _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
Posterior Prediction Plots for OLS vs StudentT vs SignalNoise | g = sns.FacetGrid(dfhoggs, size=8, hue='outlier', hue_order=[True,False],
palette='Set1', legend_out=False)
lm = lambda x, samp: samp['b0_intercept'] + samp['b1_slope'] * x
pm.glm.plot_posterior_predictive(traces_ols[-1000:],
eval=np.linspace(-3, 3, 10), lm=lm, samples=200, color='#22CC00', alpha=.2)
pm.glm.plot_posterior_predictive(traces_studentt[-1000:], lm=lm,
eval=np.linspace(-3, 3, 10), samples=200, color='#FFA500', alpha=.5)
pm.glm.plot_posterior_predictive(traces_signoise[-1000:], lm=lm,
eval=np.linspace(-3, 3, 10), samples=200, color='#357EC7', alpha=.3)
_ = g.map(plt.errorbar, 'x', 'y', 'sigma_y', 'sigma_x', marker="o", ls='').add_legend()
_ = g.axes[0][0].annotate('OLS Fit: Green\nStudent-T Fit: Orange\nSignal Vs Noise Fit: Blue',
size='x-large', xy=(1,0), xycoords='axes fraction',
xytext=(-160,10), textcoords='offset points')
_ = g.axes[0][0].set_ylim(ylims)
_ = g.axes[0][0].set_xlim(xlims) | _____no_output_____ | Apache-2.0 | docs/notebooks/GLM-robust-with-outlier-detection.ipynb | ds7788/hello-world |
Sample plots | # load libraries
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
os.listdir() | _____no_output_____ | MIT | datascience/plots_ds_python_pandas_1.ipynb | futureseadev/hgwxx7 |
sample plot 1 | # load csv
train = pd.read_csv('restaurant-and-market-health-inspections.csv')
train.info()
train.head()
train['grade'].unique()
train.select_dtypes('object')
# plot the count of Unique Values in integer Columns
train.select_dtypes(np.int64).nunique().value_counts().sort_index().plot.bar(color = 'red',
figsize = (9, 6), edgecolor = 'c', linewidth = 2)
plt.xlabel('Number of Unique Values')
plt.ylabel('Count')
plt.title('Count of Unique Values in Integer Columns') | _____no_output_____ | MIT | datascience/plots_ds_python_pandas_1.ipynb | futureseadev/hgwxx7 |
sample 2 | # plotting different categories
from collections import OrderedDict
plt.figure(figsize = (20, 16))
plt.style.use('fivethirtyeight')
# Color mapping
colors = OrderedDict({'A': 'red', 'B': 'orange', 'C': 'blue', ' ': 'green'})
mapping = OrderedDict({'A': 'extreme', 'B': 'moderate', 'C': 'vulnerable', ' ': 'non vulnerable'})
# Iterate through the float columns
for i, col in enumerate(train.select_dtypes('int64')):
ax = plt.subplot(4, 2, i + 1)
# Iterate through the poverty levels
for level, color in colors.items():
# Plot each poverty level as a separate line
sns.kdeplot(train.loc[train['grade'] == level, col].dropna(),
ax = ax, color = color, label = mapping[level])
plt.title(f'{col.capitalize()} Distribution'); plt.xlabel(f'{col}')
plt.ylabel('Density')
plt.subplots_adjust(top = 2) | c:\py37\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
c:\py37\lib\site-packages\numpy\core\_methods.py:140: RuntimeWarning: Degrees of freedom <= 0 for slice
keepdims=keepdims)
c:\py37\lib\site-packages\numpy\core\_methods.py:132: RuntimeWarning: invalid value encountered in double_scalars
ret = ret.dtype.type(ret / rcount)
c:\py37\lib\site-packages\statsmodels\nonparametric\bandwidths.py:20: RuntimeWarning: invalid value encountered in minimum
return np.minimum(np.std(X, axis=0, ddof=1), IQR)
c:\py37\lib\site-packages\numpy\core\fromnumeric.py:83: RuntimeWarning: invalid value encountered in reduce
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
| MIT | datascience/plots_ds_python_pandas_1.ipynb | futureseadev/hgwxx7 |
Plot Categoricals | # plot two categorical variables
def plot_categoricals(x, y, data, annotate=False):
"""Plot counts of two categoricals.
Size is raw count for each grouping.
Percentages are for a given value of y."""
# Raw counts
raw_counts = pd.DataFrame(data.groupby(y)[x].value_counts(normalize = False))
raw_counts = raw_counts.rename(columns = {x: 'raw_count'})
# Calculate counts for each group of x and y
counts = pd.DataFrame(data.groupby(y)[x].value_counts(normalize = True))
# Rename the column and reset the index
counts = counts.rename(columns = {x: 'normalized_count'}).reset_index()
counts['percent'] = 100 * counts['normalized_count']
# Add the raw count
counts['raw_count'] = list(raw_counts['raw_count'])
plt.figure(figsize = (14, 10))
# Scatter plot sized by percent
plt.scatter(counts[x], counts[y], edgecolor = 'k', color = 'lightgreen',
s = 100 * np.sqrt(counts['raw_count']), marker = 'o',
alpha = 0.6, linewidth = 1.5)
if annotate:
# Annotate the plot with text
for i, row in counts.iterrows():
# Put text with appropriate offsets
plt.annotate(xy = (row[x] - (1 / counts[x].nunique()),
row[y] - (0.15 / counts[y].nunique())),
color = 'navy',
s = f"{round(row['percent'], 1)}%")
# Set tick marks
plt.yticks(counts[y].unique())
plt.xticks(counts[x].unique())
# Transform min and max to evenly space in square root domain
sqr_min = int(np.sqrt(raw_counts['raw_count'].min()))
sqr_max = int(np.sqrt(raw_counts['raw_count'].max()))
# 5 sizes for legend
msizes = list(range(sqr_min, sqr_max,
int(( sqr_max - sqr_min) / 5)))
markers = []
# Markers for legend
for size in msizes:
markers.append(plt.scatter([], [], s = 100 * size,
label = f'{int(round(np.square(size) / 100) * 100)}',
color = 'lightgreen',
alpha = 0.6, edgecolor = 'k', linewidth = 1.5))
# Legend and formatting
plt.legend(handles = markers, title = 'Counts',
labelspacing = 3, handletextpad = 2,
fontsize = 16,
loc = (1.10, 0.19))
plt.annotate(f'* Size represents raw count while % is for a given y value.',
xy = (0, 1), xycoords = 'figure points', size = 10)
# Adjust axes limits
#plt.xlim((counts[x].min() - (6 / counts[x].nunique()),
# counts[x].max() + (6 / counts[x].nunique())))
#plt.ylim((counts[y].min() - (4 / counts[y].nunique()),
# counts[y].max() + (4 / counts[y].nunique())))
plt.grid(None)
plt.xlabel(f"{x}"); plt.ylabel(f"{y}"); plt.title(f"{y} vs {x}")
# plots two categorical columns in the dataframe train
plot_categoricals('grade', 'program_status', train); | _____no_output_____ | MIT | datascience/plots_ds_python_pandas_1.ipynb | futureseadev/hgwxx7 |
Value Count Plots | # plot value counts of a column
def plot_value_counts(df, col, condition=False):
"""Plot value counts of a column, optionally with only the heads of a household"""
# apply condition here if required
if condition:
# define condition below <>
df = df.loc[df[col] == condition].copy()
plt.figure(figsize = (8, 6))
df[col].value_counts().sort_index().plot.bar(color = 'red',
edgecolor = 'g',
linewidth = 2)
plt.xlabel(f'{col}')
plt.title(f'{col} Value Counts')
plt.ylabel('Count')
plt.show()
# plot
plot_value_counts(train, 'grade')
plot_value_counts(train, 'program_status')
| _____no_output_____ | MIT | datascience/plots_ds_python_pandas_1.ipynb | futureseadev/hgwxx7 |
Demos: Lecture 4 | import pennylane as qml
import numpy as np | /opt/conda/envs/pennylane/lib/python3.8/site-packages/_distutils_hack/__init__.py:30: UserWarning: Setuptools is replacing distutils.
warnings.warn("Setuptools is replacing distutils.")
| MIT | demos/Lecture04-Demos.ipynb | annabellegrimes/CPEN-400Q |
Demo 1: `qml.ctrl` | def some_function():
qml.PauliX(wires=1)
qml.CNOT(wires=[1, 2])
qml.Hadamard(wires=2)
qml.CRX(0.3, wires=[2, 1])
dev = qml.device('default.qubit', wires=3)
@qml.qnode(dev)
def control_the_thing():
qml.Hadamard(wires=0)
qml.ctrl(some_function, control=0)()
return qml.state()
control_the_thing()
print(qml.draw(control_the_thing, expansion_strategy='device')()) | 0: ──H──╭C──╭C──╭ControlledPhaseShift(1.57)──╭C─────────╭ControlledPhaseShift(1.57)──╭C─────────╭C─────────╭C──╭C──────────╭C──╭C──────────╭┤ State
1: ─────╰X──├C──│────────────────────────────│──────────│────────────────────────────╰RZ(1.57)──╰RY(0.15)──├X──╰RY(-0.15)──├X──╰RZ(-1.57)──├┤ State
2: ─────────╰X──╰ControlledPhaseShift(1.57)──╰RX(1.57)──╰ControlledPhaseShift(1.57)────────────────────────╰C──────────────╰C──────────────╰┤ State
| MIT | demos/Lecture04-Demos.ipynb | annabellegrimes/CPEN-400Q |
Demo 2: multi-qubit measurements | dev = qml.device('default.qubit', wires=3)#, shots=10)
@qml.qnode(dev)
def something_parametrized(x, y):
qml.Hadamard(wires=0)
qml.CRX(x, wires=[0, 1])
qml.CRY(y, wires=[1, 2])
return qml.probs(wires=[0])
something_parametrized(0.1, 0.2) | _____no_output_____ | MIT | demos/Lecture04-Demos.ipynb | annabellegrimes/CPEN-400Q |
Demo 3: multi-qubit expectation values | dev = qml.device('default.qubit', wires=3)#, shots=10)
@qml.qnode(dev)
def something_parametrized(x, y):
qml.Hadamard(wires=0)
qml.CRX(x, wires=[0, 1])
qml.CRY(y, wires=[1, 2])
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2))
something_parametrized(0.3, 0.4)
dev = qml.device('default.qubit', wires=3)#, shots=10)
@qml.qnode(dev)
def something_parametrized(x, y):
qml.Hadamard(wires=0)
qml.CRX(x, wires=[0, 1])
qml.CRY(y, wires=[1, 2])
return qml.expval(qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliY(2))
something_parametrized(0.3, 0.4) | _____no_output_____ | MIT | demos/Lecture04-Demos.ipynb | annabellegrimes/CPEN-400Q |
Demo 4: superdense coding | dev = qml.device('default.qubit', wires=2, shots=1)
def create_entangled_state(wires=None):
qml.Hadamard(wires=wires[0])
qml.CNOT(wires=[wires[0], wires[1]])
@qml.qnode(dev)
def superdense_coding(b1=0, b2=0):
create_entangled_state(wires=[0, 1])
if b1 == 1:
qml.PauliZ(wires=0)
if b2 == 1:
qml.PauliX(wires=0)
qml.adjoint(create_entangled_state)(wires=[0, 1])
return qml.sample()
superdense_coding(b1=1, b2=0) | _____no_output_____ | MIT | demos/Lecture04-Demos.ipynb | annabellegrimes/CPEN-400Q |
1 - Getting Started The main application for `scikit-gstat` is variogram analysis and [Kriging](https://en.wikipedia.org/wiki/Kriging). This Tutorial will guide you through the most basic functionality of `scikit-gstat`. There are other tutorials that will explain specific methods or attributes in `scikit-gstat` in more detail. What you will learn in this tutorial* How to instantiate `Variogram` and `OrdinaryKriging`* How to read a variogram* Perform an interpolation* Most basic plotting | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pprint import pprint
plt.style.use('ggplot') | _____no_output_____ | MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
The `Variogram` and `OrdinaryKriging` classes can be loaded directly from `skgstat`. This is the name of the Python module. | from skgstat import Variogram, OrdinaryKriging | _____no_output_____ | MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
At the current version, there are some deprecated attributes and method in the `Variogram` class. They do not raise `DeprecationWarning`s, but rather print a warning message to the screen. You can suppress this warning by adding an `SKG_SUPPRESS` environment variable | %set_env SKG_SUPPRESS=true | env: SKG_SUPPRESS=true
| MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
1.1 Load data You can find a prepared example data set in the `./data` subdirectory. This example is extracted from a generated Gaussian random field. We can expect the field to be stationary and show a nice spatial dependence, because it was created that way.We can load one of the examples and have a look at the data: | data = pd.read_csv('./data/sample_sr.csv')
print("Loaded %d rows and %d columns" % data.shape)
data.head() | Loaded 200 rows and 3 columns
| MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
Get a first overview of your data by plotting the `x` and `y` coordinates and visually inspect how the `z` spread out. | fig, ax = plt.subplots(1, 1, figsize=(9, 9))
art = ax.scatter(data.x,data.y, s=50, c=data.z, cmap='plasma')
plt.colorbar(art); | _____no_output_____ | MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
We can already see a lot from here: * The small values seem to concentrate on the upper left and lower right corner* Larger values are arranged like a band from lower left to upper right corner* To me, each of these blobs seem to have a diameter of something like 30 or 40 units.* The distance between the minimum and maximum seems to be not more than 60 or 70 units.These are already very important insights. 1.2 Build a Variogram As a quick reminder, the variogram relates pair-wise separating distances of `coordinates` and relates them to the *semi-variance* of the corresponding `values` pairs. The default estimator used is the Matheron estimator:$$ \gamma (h) = \frac{1}{2N(h)} * \sum_{i=1}^{N(h)}(Z(x_i) - Z(x_{i + h}))^2 $$For more details, please refer to the [User Guide](https://mmaelicke.github.io/scikit-gstat/userguide/variogram.htmlexperimental-variograms) The `Variogram` class takes at least two arguments. The `coordinates` and the `values` observed at these locations. You should also at least set the `normalize` parameter to explicitly, as it changes it's default value in version `0.2.8` to `False`. This attribute affects only the plotting, not the variogram values.Additionally, the number of bins is set to 15, because we have fairly many observations and the default value of 10 is unnecessarily small. The `maxlag` set the maximum distance for the last bin. We know from the plot above, that more than 60 units is not really meaningful | V = Variogram(data[['x', 'y']].values, data.z.values, normalize=False, maxlag=60, n_lags=15)
fig = V.plot(show=False) | _____no_output_____ | MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
The upper subplot show the histogram for the count of point-pairs in each lag class. You can see various things here:* As expected, there is a clear spatial dependency, because semi-variance increases with distance (blue dots)* The default `spherical` variogram model is well fitted to the experimental data* The shape of the dependency is **not** captured quite well, but fair enough for this exampleThe sill of the variogram should correspond with the field variance. The field is unknown, but we can compare the sill to the *sample* variance: | print('Sample variance: %.2f Variogram sill: %.2f' % (data.z.var(), V.describe()['sill'])) | Sample variance: 1.10 Variogram sill: 1.26
| MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
The `describe` method will return the most important parameters as a dictionary. And we can simply print the variogram ob,ect to the screen, to see all parameters. | pprint(V.describe())
print(V) | spherical Variogram
-------------------
Estimator: matheron
Effective Range: 39.50
Sill: 1.26
Nugget: 0.00
| MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
1.3 Kriging The Kriging class will now use the Variogram from above to estimate the Kriging weights for each grid cell. This is done by solving a linear equation system. For an unobserved location $s_0$, we can use the distances to 5 observation points and build the system like:$$\begin{pmatrix}\gamma(s_1, s_1) & \gamma(s_1, s_2) & \gamma(s_1, s_3) & \gamma(s_1, s_4) & \gamma(s_1, s_5) & 1\\\gamma(s_2, s_1) & \gamma(s_2, s_2) & \gamma(s_2, s_3) & \gamma(s_2, s_4) & \gamma(s_2, s_5) & 1\\\gamma(s_3, s_1) & \gamma(s_3, s_2) & \gamma(s_3, s_3) & \gamma(s_3, s_4) & \gamma(s_3, s_5) & 1\\\gamma(s_4, s_1) & \gamma(s_4, s_2) & \gamma(s_4, s_3) & \gamma(s_4, s_4) & \gamma(s_4, s_5) & 1\\\gamma(s_5, s_1) & \gamma(s_5, s_2) & \gamma(s_5, s_3) & \gamma(s_5, s_4) & \gamma(s_5, s_5) & 1\\1 & 1 & 1 & 1 & 1 & 0 \\\end{pmatrix} *\begin{bmatrix}\lambda_1 \\\lambda_2 \\\lambda_3 \\\lambda_4 \\\lambda_5 \\\mu \\\end{bmatrix} =\begin{pmatrix}\gamma(s_0, s_1) \\\gamma(s_0, s_2) \\\gamma(s_0, s_3) \\\gamma(s_0, s_4) \\\gamma(s_0, s_5) \\1 \\\end{pmatrix}$$For more information, please refer to the [User Guide](https://mmaelicke.github.io/scikit-gstat/userguide/kriging.htmlkriging-equation-system) Consequently, the `OrdinaryKriging` class needs a `Variogram` object as a mandatory attribute. Two very important optional attributes are `min_points` and `max_points`. They will limit the size of the Kriging equation system. As we have 200 observations, we can require at least 5 neighbors within the range. More than 15 will only unnecessarily slow down the computation. The `mode='exact'` attribute will advise the class to build and solve the system above for each location. | ok = OrdinaryKriging(V, min_points=5, max_points=15, mode='exact') | _____no_output_____ | MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
The `transform` method will apply the interpolation for passed arrays of coordinates. It requires each dimension as a single 1D array. We can easily build a meshgrid of 100x100 coordinates and pass them to the interpolator. To recieve a 2D result, we can simply reshape the result. The Kriging error will be available as the `sigma` attribute of the interpolator. | # build the target grid
xx, yy = np.mgrid[0:99:100j, 0:99:100j]
field = ok.transform(xx.flatten(), yy.flatten()).reshape(xx.shape)
s2 = ok.sigma.reshape(xx.shape) | _____no_output_____ | MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
And finally, we can plot the result. | fig, axes = plt.subplots(1, 2, figsize=(16, 8))
art = axes[0].matshow(field.T, origin='lower', cmap='plasma')
axes[0].set_title('Interpolation')
axes[0].plot(data.x, data.y, '+k')
axes[0].set_xlim((0,100))
axes[0].set_ylim((0,100))
plt.colorbar(art, ax=axes[0])
art = axes[1].matshow(s2.T, origin='lower', cmap='YlGn_r')
axes[1].set_title('Kriging Error')
plt.colorbar(art, ax=axes[1])
axes[1].plot(data.x, data.y, '+w')
axes[1].set_xlim((0,100))
axes[1].set_ylim((0,100)); | _____no_output_____ | MIT | docs/tutorials/01_getting_started.ipynb | rhugonnet/scikit-gstat |
KNN | import pickle
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import StratifiedShuffleSplit
#資料劃分
x_train, x_test, y_train, y_test = train_test_split(feature, answer, test_size=0.3, random_state=9)
#參數區間
param_grid = {'n_neighbors':[1, 2, 3, 4, 5]}
#交叉驗證
cv = StratifiedShuffleSplit(n_splits=2, test_size=0.3, random_state=12)
grid = GridSearchCV(KNeighborsClassifier(n_neighbors = 5), param_grid, cv=cv, verbose=10, n_jobs=-1) #n_jobs為平行運算的數量
grid.fit(x_train, y_train)
grid_predictions = grid.predict(x_test)
#儲存
file = open('model_KNN.pickle', 'wb')
pickle.dump(grid, file)
file.close()
#最佳參數
print(grid.best_params_)
#預測結果
#print(grid_predictions)
#混淆矩陣
print(confusion_matrix(y_test, grid_predictions))
#分類結果
print(classification_report(y_test, grid_predictions)) | {'n_neighbors': 5}
[[6164 75 373 345 0]
[ 71 6402 356 352 0]
[ 351 360 8975 105 0]
[ 368 397 123 8683 0]
[ 5 5 7 25 1]]
precision recall f1-score support
0 0.89 0.89 0.89 6957
1 0.88 0.89 0.89 7181
2 0.91 0.92 0.91 9791
3 0.91 0.91 0.91 9571
4 1.00 0.02 0.05 43
accuracy 0.90 33543
macro avg 0.92 0.72 0.73 33543
weighted avg 0.90 0.90 0.90 33543
| MIT | MLGame/games/snake/ml/train.py.ipynb | Liuian/1092_INTRODUCTION-TO-MACHINE-LEARNING-AND-ITS-APPLICATION-TO-GAMING |
Bayesian Regression Using NumPyroIn this tutorial, we will explore how to do bayesian regression in NumPyro, using a simple example adapted from Statistical Rethinking [[1](References)]. In particular, we would like to explore the following: - Write a simple model using the `sample` NumPyro primitive. - Run inference using MCMC in NumPyro, in particular, using the No U-Turn Sampler (NUTS) to get a posterior distribution over our regression parameters of interest. - Learn about utilities such as `initialize_model` that are useful for running HMC. - Learn how we can use effect-handlers in NumPyro to generate execution traces, condition on sample sites, seed models with RNG seeds, etc., and use this to implement various utilities that will be useful for MCMC. e.g. computing model log likelihood, generating empirical distribution over the posterior predictive, etc. Tutorial Outline:1. [Dataset](Dataset)2. [Regression Model to Predict Divorce Rate](Regression-Model-to-Predict-Divorce-Rate) - [Model-1: Predictor-Marriage Rate](Model-1:-Predictor---Marriage-Rate) - [Posterior Distribution over the Regression Parameters](Posterior-Distribution-over-the-Regression-Parameters) - [Posterior Predictive Distribution](Posterior-Predictive-Distribution) - [Model Log Likelihood](Model-Log-Likelihood) - [Model-2: Predictor-Median Age of Marriage](Model-2:-Predictor---Median-Age-of-Marriage) - [Model-3: Predictor-Marriage Rate and Median Age of Marriage](Model-3:-Predictor---Marriage-Rate-and-Median-Age-of-Marriage) - [Divorce Rate Residuals by State](Divorce-Rate-Residuals-by-State)3. [Regression Model with Measurement Error](Regression-Model-with-Measurement-Error) - [Effect of Incorporating Measurement Noise on Residuals](Effect-of-Incorporating-Measurement-Noise-on-Residuals)4. [References](References) | %reset -s -f
import jax
import jax.numpy as np
from jax import random, vmap
from jax.config import config; config.update("jax_platform_name", "cpu")
from jax.scipy.special import logsumexp
import matplotlib
import matplotlib.pyplot as plt
import numpy as onp
import pandas as pd
import seaborn as sns
from numpyro.diagnostics import hpdi
import numpyro.distributions as dist
from numpyro.handlers import sample, seed, substitute, trace
from numpyro.hmc_util import initialize_model
from numpyro.mcmc import mcmc
%matplotlib inline
plt.style.use('bmh')
plt.rcParams.update({'font.size': 16,
'xtick.labelsize': 14,
'ytick.labelsize': 14,
'axes.titlesize': 'large',
'axes.labelsize': 'medium'}) | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
DatasetFor this example, we will use the `WaffleDivorce` dataset from Chapter 05, Statistical Rethinking [[1](References)]. The dataset contains divorce rates in each of the 50 states in the USA, along with predictors such as population, median age of marriage, whether it is a Southern state and, curiously, number of Waffle Houses. | DATASET_URL = 'https://raw.githubusercontent.com/rmcelreath/rethinking/master/data/WaffleDivorce.csv'
dset = pd.read_csv(DATASET_URL, sep=';')
dset | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
Let us plot the pair-wise relationship amongst the main variables in the dataset, using `seaborn.pairplot`. | vars = ['Population', 'MedianAgeMarriage', 'Marriage', 'WaffleHouses', 'South', 'Divorce']
sns.pairplot(dset, x_vars=vars, y_vars=vars, palette='husl'); | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
From the plots above, we can clearly observe that there is a relationship between divorce rates and marriage rates in a state (as might be expected), and also between divorce rates and median age of marriage. There is also a weak relationship between number of Waffle Houses and divorce rates, which is not obvious from the plot above, but will be clearer if we regress `Divorce` against `WaffleHouse` and plot the results. This is an example of a spurious association. We do not expect the number of Waffle Houses in a state to affect the divorce rate, but it is likely correlated with other factors that have an effect on the divorce rate. We will not delve into this spurious association in this tutorial, but the interested reader is encouraged to read Chapters 5 and 6 of [[1](References)] which explores the problem of causal association in the presence of multiple predictors. For simplicity, we will primarily focus on marriage rate and the median age of marriage as our predictors for divorce rate throughout the remaining tutorial. | sns.regplot('WaffleHouses', 'Divorce', dset); | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
Regression Model to Predict Divorce RateLet us now write a regressionn model in *NumPyro* to predict the divorce rate as a linear function of marriage rate and median age of marriage in each of the states. First, note that our predictor variables have somewhat different scales. It is a good practice to standardize our predictors and response variables to mean `0` and standard deviation `1`, which should result in faster inference. Refer to this [note](https://mc-stan.org/docs/2_19/stan-users-guide/standardizing-predictors-and-outputs.html) in the Stan manual for more details. | dset['AgeScaled'] = (dset.MedianAgeMarriage - onp.mean(dset.MedianAgeMarriage)) / onp.std(dset.MedianAgeMarriage)
dset['MarriageScaled'] = (dset.Marriage - onp.mean(dset.Marriage)) / onp.std(dset.Marriage)
dset['DivorceScaled'] = (dset.Divorce - onp.mean(dset.Divorce)) / onp.std(dset.Divorce) | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
We write the NumPyro model as follows. While the code should largely be self-explanatory, take note of the following: - In NumPyro, model code is any Python callable that can accept arguments and keywords. For HMC which we will be using for this tutorial, these arguments and keywords cannot change during model execution. This is convenient for passing in numpy arrays, or boolean arguments that might affect the execution path. - In addition to regular Python statements, the model code also contains primitives like `sample`. These primitives can be interpreted with various side-effects by effect handlers used by inference algorithms in NumPyro. For more on effect handlers, refer to [[3](References)], [[4](References)]. For now, just remember that a `sample` statement makes this a stochastic function by sampling from some distribution of interest. - The reason why we have kept our predictors as optional keyword arguments is to be able to reuse the same model as we vary the set of predictors. Likewise, the reason why the response variable is optional is that we would like to reuse this model to sample from the posterior predictive distribution. See the [section](Posterior-Predictive-Distribution) on plotting the posterior predictive distribution, as an example. | def model(marriage=None, age=None, divorce=None):
a = sample('a', dist.Normal(0., 0.2))
M, A = 0., 0.
if marriage is not None:
bM = sample('bM', dist.Normal(0., 0.5))
M = bM * marriage
if age is not None:
bA = sample('bA', dist.Normal(0., 0.5))
A = bA * age
sigma = sample('sigma', dist.Exponential(1.))
mu = a + M + A
sample('obs', dist.Normal(mu, sigma), obs=divorce) | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
Model 1: Predictor - Marriage RateWe first try to model the divorce rate as depending on a single variable, marriage rate. As mentioned above, we can use the same `model` code as earlier, but only pass values for `marriage` and `divorce` keyword arguments. We will use the No U-Turn Sampler (see [[5](References)] for more details on the NUTS algorithm) to run inference on this simple model.Note the following requirements for running HMC and NUTS in NumPyro: - The Hamiltonian Monte Carlo (or, the NUTS) implementation in Pyro takes in a potential energy function. This is the negative log joint density for the model. - The verlet integrator in HMC (or, NUTS) returns sample values simulated using Hamiltonian dynamics in the unconstrained space. As such, continuous variables with bounded support need to be transformed into unconstrained space using bijective transforms. We also need to transform these samples back to their constrained support before returning these values to the user. Thankfully, all of this is handled on the backend for us. Let us go through the steps one by one. - JAX uses functional PRNGs. Unlike other languages / frameworks which maintain a global random state, in JAX, every call to a sampler requires an [explicit PRNGKey](https://github.com/google/jaxrandom-numbers-are-different). We will split our initial random seed for subsequent operations, so that we do not accidentally reuse the same seed. - The function [initialize_model](https://numpyro.readthedocs.io/en/latest/mcmc.htmlnumpyro.hmc_util.initialize_model) takes a model along with model arguments (and keyword arguments), and returns a tuple of initial parameters, potential energy function, and constrain function. The initial parameters are used to initiate the MCMC chain, the potential energy function is a callable that when given unconstrained sample values returns the potential energy at these sample values. This is used by the verlet integrator in HMC. Lastly, `constrain_fn` is a callable that transforms the unconstrained samples returned by HMC/NUTS to sample values that lie within the constrained support. - Finally, we use the [mcmc](https://numpyro.readthedocs.io/en/latest/mcmc.htmlnumpyro.mcmc.mcmc) function to run inference using the default `NUTS` sampler. Note that to run vanilla HMC, all you need to do is to pass `algo='HMC'` as argument to `mcmc` instead. This is a convenience utility that does all of the following: - Runs warmup - adapts steps size and mass matrix. - Uses the sample from the warmup phase to start MCMC. - Return samples from the posterior distribution and print diagnostic information. | # Start from this source of randomness. We will split keys for subsequent operations.
rng = random.PRNGKey(0)
rng_, rng = random.split(rng)
# Initialize the model.
init_params, potential_fn, constrain_fn = initialize_model(rng_, model,
marriage=dset.MarriageScaled.values,
divorce=dset.DivorceScaled.values)
num_warmup, num_samples = 1000, 2000
# Run NUTS.
samples_1 = mcmc(num_warmup, num_samples, init_params,
potential_fn=potential_fn,
trajectory_length=10,
constrain_fn=constrain_fn) | warmup: 100%|██████████| 1000/1000 [00:12<00:00, 78.24it/s, 1 steps of size 6.99e-01. acc. prob=0.79]
sample: 100%|██████████| 2000/2000 [00:03<00:00, 515.37it/s, 3 steps of size 6.99e-01. acc. prob=0.88]
| MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
Posterior Distribution over the Regression ParametersWe notice that the progress bar gives us online statistics on the acceptance probability, step size and number of steps taken per sample while running NUTS. In particular, during warmup, we adapt the step size and mass matrix to achieve a certain target acceptance probability (0.8, by default). We were able to successfully adapt our step size to achieve this target in the warmup phase.During warmup, the aim is to adapt or learn values for hyper-parameters such as step size and mass matrix (the HMC algorithm is very sensitive to these hyper-parameters), and to reach the typical set (see [[6](References)] for more details). If there are any issues in the model specification, it might be reflected in low acceptance probabilities or very high number of steps. We use the sample from the end of the warmup phase to seed the MCMC chain (denoted by the second `sample` progress bar) from which we generate the desired number of samples from our target distribution.At the end of inference, NumPyro prints the mean, std and 90% CI values for each of the latent parameters. Note that since we standardized our predictors and response variable, we would expect the intercept to have mean 0, as can be seen here. It also prints other convergence diagnostics on the latent parameters in the model, including [effective sample size](https://numpyro.readthedocs.io/en/latest/diagnostics.htmlnumpyro.diagnostics.effective_sample_size) and the [gelman rubin diagnostic](https://numpyro.readthedocs.io/en/latest/diagnostics.htmlnumpyro.diagnostics.gelman_rubin) ($\hat{R}$). The value for these diagnostics indicates that the chain has converged to the target distribution. In our case, the "target distribution" is the posterior distribution over the latent parameters that we are interested in. Note that this is often worth verifying with multiple chains on more complicated models. In the end, `samples_1` is a collection (in our case, a `dict` since `init_samples` was a `dict`) containing samples from the posterior distribution for each of the latent parameters in the model.To look at our regression fit, let us plot the regression line using our posterior estimates for the regression parameters, along with the 90% Credibility Interval (CI). Note that the [hpdi](https://numpyro.readthedocs.io/en/latest/diagnostics.htmlnumpyro.diagnostics.hpdi) function in NumPyro's diagnostics module can be used to compute CI. In the functions below, note that the collected samples from the posterior are all along the leading axis.We can see from the plot, that the CI broadens towards the tails where values of the predictor variables are sparse, as can be expected. | def plot_regression(x, y_mean, y_hpdi):
# Sort values for plotting by x axis
idx = np.argsort(x)
marriage = x[idx]
mean = y_mean[idx]
hpdi = y_hpdi[:, idx]
divorce = dset.DivorceScaled.values[idx]
# Plot
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 6))
ax.plot(marriage, mean)
ax.plot(marriage, divorce, 'o')
ax.fill_between(marriage, hpdi[0], hpdi[1], alpha=0.3, interpolate=True)
return ax
# Compute empirical posterior distribution over mu
posterior_mu = np.expand_dims(samples_1['a'], -1) + \
np.expand_dims(samples_1['bM'], -1) * dset.MarriageScaled.values
mean_mu = np.mean(posterior_mu, axis=0)
hpdi_mu = hpdi(posterior_mu, 0.9)
ax = plot_regression(dset.MarriageScaled.values, mean_mu, hpdi_mu)
ax.set(xlabel='Marriage rate', ylabel='Divorce rate', title='Regression line with 90% CI'); | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
Posterior Predictive DistributionLet us now look at the posterior predictive distribution to see how our predictive distribution looks with respect to the observed divorce rates. To get samples from the posterior predictive distribution, we need to run the model by substituting the latent parameters with samples from the posterior. This sounds complicated, but this can be easily achieved by using effect handlers from the [handlers module](https://numpyro.readthedocs.io/en/latest/handlers.html).In particular, note the use of the `substitute`, `seed` and `trace` effect handlers in the `predict` function. - The `seed` effect-handler is used to wrap a stochastic function with an initial `PRNGKey` seed. When a sample statement inside the model is called, it uses the existing seed to sample from a distribution but this effect-handler also splits the existing key to ensure that future `sample` calls in the model use the newly split key instead. This is to prevent us from having to explicitly pass in a `PRNGKey` to each `sample` statement. - The `substitute` effect handler simply substitutes the value for the site name present in the `post_samples` dict instead of sampling from the distribution, which can be useful for conditioning sample sites to certain values. - The `trace` effect handler runs the model and records the execution trace within an `OrderedDict`. This trace object contains execution metadata that is useful for computing quantities such as the log joint density. It should be clear now that the `predict` function simply runs the model by substituting the latent parameters with samples from the posterior (generated by the `mcmc` function) to generate predictions, which are samples from the posterior predictive distribution. Note the use of JAX's auto-vectorization transform called [vmap](https://github.com/google/jaxauto-vectorization-with-vmap) to vectorize predictions. If we didn't use `vmap`, we would have to use a native for loop which for each sample which is much slower. Each draw from the posterior can be used to get predictions over all the 50 states. When we vectorize this over all the samples from the posterior using `vmap`, we will get a `predictions_1` array of shape `(num_samples, 50)`. We can then compute the mean and 90% CI of these samples to plot the posterior predictive distribution. | def predict(rng, post_samples, model, *args, **kwargs):
model = substitute(seed(model, rng), post_samples)
model_trace = trace(model).get_trace(*args, **kwargs)
return model_trace['obs']['value']
# vectorize predictions via vmap
predict_fn = vmap(lambda rng, samples: predict(rng, samples, model, marriage=dset.MarriageScaled.values))
rng, rng_ = random.split(rng)
predictions_1 = predict_fn(random.split(rng_, num_samples), samples_1)
mean_pred = np.mean(predictions_1, axis=0)
hpdi_pred = hpdi(predictions_1, 0.9)
ax = plot_regression(dset.MarriageScaled.values, mean_pred, hpdi_pred)
ax.set(xlabel='Marriage rate', ylabel='Divorce rate', title='Predictions with 90% CI'); | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
We will use the same `plot_regression` function as earlier. We notice that our CI for the predictive distribution is much broader as compared to the last plot due to the additional noise introduced by the `sigma` parameter. Note that most data points lie well within the 90% CI, which indicates a good fit. Model Log LikelihoodLikewise, making use of effect-handlers and `vmap`, we can also compute the log likelihood for this model given the dataset. | def log_lk(rng, params, model, *args, **kwargs):
model = substitute(seed(model, rng), params)
model_trace = trace(model).get_trace(*args, **kwargs)
obs_node = model_trace['obs']
return np.sum(obs_node['fn'].log_prob(obs_node['value']))
def expected_log_likelihood(rng, params, model, *args, **kwargs):
n = list(params.values())[0].shape[0]
log_lk_fn = vmap(lambda rng, params: log_lk(rng, params, model, *args, **kwargs))
log_lk_vals = log_lk_fn(random.split(rng, n), params)
return logsumexp(log_lk_vals) - np.log(n)
rng, rng_ = random.split(rng)
print('Log likelihood: {}'.format(expected_log_likelihood(rng_,
samples_1,
model,
marriage=dset.MarriageScaled.values,
divorce=dset.DivorceScaled.values))) | Log likelihood: -68.14618682861328
| MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
Model 2: Predictor - Median Age of MarriageWe will now model the divorce rate as a function of the median age of marriage. The computations are mostly a reproduction of what we did for Model 1. Notice the following: - Divorce rate is inversely related to the age of marriage. Hence states where the median age of marriage is low will likely have a higher divorce rate. - We get a higher log likelihood of -60.92 as compared to -68.15 with Model 2, indicating that median age of marriage is likely a much better predictor of divorce rate. | rng, rng_ = random.split(rng)
init_params, potential_fn, constrain_fn = initialize_model(rng_, model,
age=dset.AgeScaled.values,
divorce=dset.DivorceScaled.values)
samples_2 = mcmc(num_warmup, num_samples, init_params,
potential_fn=potential_fn,
trajectory_length=10,
constrain_fn=constrain_fn)
posterior_mu = np.expand_dims(samples_2['a'], -1) + \
np.expand_dims(samples_2['bA'], -1) * dset.AgeScaled.values
mean_mu = np.mean(posterior_mu, axis=0)
hpdi_mu = hpdi(posterior_mu, 0.9)
ax = plot_regression(dset.AgeScaled.values, mean_mu, hpdi_mu)
ax.set(xlabel='Median marriage age', ylabel='Divorce rate', title='Regression line with 90% CI');
rng, rng_ = random.split(rng)
predict_fn = vmap(lambda rng, samples: predict(rng, samples, model, age=dset.AgeScaled.values))
predictions_2 = predict_fn(random.split(rng_, num_samples), samples_2)
mean_pred = np.mean(predictions_2, axis=0)
hpdi_pred = hpdi(predictions_2, 0.9)
ax = plot_regression(dset.AgeScaled.values, mean_pred, hpdi_pred)
ax.set(xlabel='Median Age', ylabel='Divorce rate', title='Predictions with 90% CI');
rng, rng_ = random.split(rng)
print('Log likelihood: {}'.format(expected_log_likelihood(rng_,
samples_2,
model,
age=dset.AgeScaled.values,
divorce=dset.DivorceScaled.values))) | Log likelihood: -60.926387786865234
| MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
Model 3: Predictor - Marriage Rate and Median Age of MarriageFinally, we will also model divorce rate as depending on both marriage rate as well as the median age of marriage. Note that there is no increase in the model's log likelihood over Model 2 which likely indicates that the marginal information from marriage rate in predicting divorce rate is low when the median age of marriage is already known. | rng, rng_ = random.split(rng)
init_params, potential_fn, constrain_fn = initialize_model(rng_, model,
marriage=dset.MarriageScaled.values,
age=dset.AgeScaled.values,
divorce=dset.DivorceScaled.values)
samples_3 = mcmc(num_warmup, num_samples, init_params,
potential_fn=potential_fn,
trajectory_length=10,
constrain_fn=constrain_fn)
rng, rng_ = random.split(rng)
print('Log likelihood: {}'.format(expected_log_likelihood(rng_,
samples_3,
model,
marriage=dset.MarriageScaled.values,
age=dset.AgeScaled.values,
divorce=dset.DivorceScaled.values))) | Log likelihood: -61.04328918457031
| MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
Divorce Rate Residuals by StateThe regression plots above shows that the observed divorce rates for many states differs considerably from the mean regression line. To dig deeper into how the last model (Model 3) under-predicts or over-predicts for each of the states, we will plot the posterior predictive and residuals (`Observed divorce rate - Predicted divorce rate`) for each of the states. | # Predictions for Model 3.
rng, rng_ = random.split(rng)
predict_fn = vmap(lambda rng, samples: predict(rng, samples, model,
marriage=dset.MarriageScaled.values,
age=dset.AgeScaled.values))
predictions_3 = predict_fn(random.split(rng_, num_samples), samples_3)
y = np.arange(50)
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12, 16))
pred_mean = np.mean(predictions_3, axis=0)
pred_hpdi = hpdi(predictions_3, 0.9)
residuals_3 = dset.DivorceScaled.values - predictions_3
residuals_mean = np.mean(residuals_3, axis=0)
residuals_hpdi = hpdi(residuals_3, 0.9)
idx = np.argsort(residuals_mean)
# Plot posterior predictive
ax[0].plot(np.zeros(50), y, '--')
ax[0].errorbar(pred_mean[idx], y, xerr=pred_hpdi[1, idx] - pred_mean[idx],
marker='o', ms=5, mew=4, ls='none', alpha=0.8)
ax[0].plot(dset.DivorceScaled.values[idx], y, marker='o',
ls='none', color='gray', alpha=0.5)
ax[0].set(xlabel='Posterior Predictive', ylabel='State', title='Posterior Predictive with 90% CI')
ax[0].set_yticks(y)
ax[0].set_yticklabels(dset.Loc.values[idx], fontsize=10);
# Plot residuals
residuals_3 = dset.DivorceScaled.values - predictions_3
residuals_mean = np.mean(residuals_3, axis=0)
residuals_hpdi = hpdi(residuals_3, 0.9)
err = residuals_hpdi[1] - residuals_mean
ax[1].plot(np.zeros(50), y, '--')
ax[1].errorbar(residuals_mean[idx], y, xerr=err[idx],
marker='o', ms=5, mew=4, ls='none', alpha=0.8)
ax[1].set(xlabel='Residuals', ylabel='State', title='Residuals with 90% CI')
ax[1].set_yticks(y)
ax[1].set_yticklabels(dset.Loc.values[idx], fontsize=10); | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
The plot on the left shows the mean predictions with 90% CI for each of the states using Model 3. The gray markers indicate the actual observed divorce rates. The right plot shows the residuals for each of the states, and both these plots are sorted by the residuals, i.e. at the bottom, we are looking at states where the model predictions are higher than the observed rates, whereas at the top, the reverse is true.Overall, the model fit seems good because most observed data points like within a 90% CI around the mean predictions. However, notice how the model over-predicts by a large margin for states like Idaho (bottom left), and on the other end under-predicts for states like Maine (top right). This is likely indicative of other factors that we are missing out in our model that affect divorce rate across different states. Even ignoring other socio-political variables, one such factor that we have not yet modeled is the measurement noise given by `Divorce SE` in the dataset. We will explore this in the next section. Regression Model with Measurement ErrorNote that in our previous models, each data point influences the regression line equally. Is this well justified? We will build on the previous model to incorporate measurement error given by `Divorce SE` variable in the dataset. Incorporating measurement noise will be useful in ensuring that observations that have higher confidence (i.e. lower measurement noise) have a greater impact on the regression line. On the other hand, this will also help us better model outliers with high measurement errors. For more details on modeling errors due to measurement noise, refer to Chapter 15 of [[1](References)].To do this, we will reuse Model 3, with the only change that the final observed value has a measurement error given by `divorce_sd` (notice that this has to be standardized since the `divorce` variable itself has been standardized to mean 0 and std 1). | def model_se(marriage, age, divorce_sd, divorce=None):
a = sample('a', dist.Normal(0., 0.2))
bM = sample('bM', dist.Normal(0., 0.5))
M = bM * marriage
bA = sample('bA', dist.Normal(0., 0.5))
A = bA * age
sigma = sample('sigma', dist.Exponential(1.))
mu = a + M + A
divorce_rate = sample('divorce_rate', dist.Normal(mu, sigma))
sample('obs', dist.Normal(divorce_rate, divorce_sd), obs=divorce)
rng, rng_ = random.split(rng)
# Standardize
dset['DivorceScaledSD'] = dset['Divorce SE'] / np.std(dset.Divorce.values)
init_params, potential_fn, constrain_fn = initialize_model(rng_, model_se,
marriage=dset.MarriageScaled.values,
age=dset.AgeScaled.values,
divorce_sd=dset.DivorceScaledSD.values,
divorce=dset.DivorceScaled.values)
samples_4 = mcmc(num_warmup=1000,
num_samples=3000,
init_params=init_params,
potential_fn=potential_fn,
trajectory_length=10,
target_accept_prob=0.9,
constrain_fn=constrain_fn) | warmup: 100%|██████████| 1000/1000 [00:19<00:00, 50.19it/s, 15 steps of size 2.16e-01. acc. prob=0.89]
sample: 100%|██████████| 3000/3000 [00:06<00:00, 442.19it/s, 15 steps of size 2.16e-01. acc. prob=0.94]
| MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
Effect of Incorporating Measurement Noise on ResidualsNotice that our values for the regression coefficients is very similar to Model 3. However, introducing measurement noise allows us to more closely match our predictive distributions to the observed values. We can see this if we plot the residuals as earlier. | rng, rng_ = random.split(rng)
predict_fn = vmap(lambda rng, samples: predict(rng, samples, model_se,
marriage=dset.MarriageScaled.values,
age=dset.AgeScaled.values,
divorce_sd=dset.DivorceScaledSD.values))
predictions_4 = predict_fn(random.split(rng_, 3000), samples_4)
sd = dset.DivorceScaledSD.values
residuals_4 = dset.DivorceScaled.values - predictions_4
residuals_mean = np.mean(residuals_4, axis=0)
residuals_hpdi = hpdi(residuals_4, 0.9)
err = residuals_hpdi[1] - residuals_mean
idx = np.argsort(residuals_mean)
y = np.arange(50)
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 16))
# Plot Residuals
ax.plot(np.zeros(50), y, '--')
ax.errorbar(residuals_mean[idx], y, xerr=err[idx],
marker='o', ms=5, mew=4, ls='none', alpha=0.4)
# Plot SD
ax.errorbar(residuals_mean[idx], y, xerr=sd[idx],
ls='none')
# Plot earlier mean residual
ax.plot(np.mean(dset.DivorceScaled.values - predictions_3, 0)[idx], y,
ls='none', marker='o', ms=5, color='gray', alpha=0.8)
ax.set(xlabel='Residuals', ylabel='State', title='Residuals with 90% CI')
ax.set_yticks(y)
ax.set_yticklabels(dset.Loc.values[idx], fontsize=10); | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
The plot above shows the residuals for each of the states, along with the measurement noise given by inner error bar. The gray dots are the mean residuals from our earlier Model 3. Notice how having an additional degree of freedom to model the measurement noise has shrunk the residuals. In particular, for Idaho and Maine, our predictions are now much closer to the observed values after incorporating measurement noise in the model.To better see how measurement noise affects the movement of the regression line, let us plot the residuals with respect to the measurement noise. | fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 6))
x = dset.DivorceScaledSD.values
y1 = np.mean(residuals_3, 0)
y2 = np.mean(residuals_4, 0)
ax.plot(x, y1, ls='none', marker='o')
ax.plot(x, y2, ls='none', marker='o')
for i, (j, k) in enumerate(zip(y1, y2)):
ax.plot([x[i], x[i]], [j, k], '--', color='gray');
ax.set(xlabel='Measurement Noise', ylabel='Residual', title='Mean residuals (Model 4: red, Model 3: blue)'); | _____no_output_____ | MIT | notebooks/source/bayesian_regression.ipynb | Anthonymcqueen21/numpyro |
Mutation analysis1. Calculate the mutation rate (number of mutations/number of unique sequences) 2. Consider only the sequences between 2000 and 20203. Write the different files (Year : Mutation rate) | from google.colab import drive
drive.mount('/content/gdrive')
%cd 'gdrive/MyDrive/Machine Learning/coronavirus/analysis'
!ls
import os
import pandas as pd
import numpy as np
#List all the directory names
dir_name = os.listdir('./H1N_H9N')
for name in dir_name:
df = pd.read_csv('./H1N_H9N/' + name)
#Select only sequence between 2000 and 2020
start_date = '2000-01-01'
end_date = '2020-12-31'
df = df[(df['Date'] >= start_date)]
df = df[(df['Date'] < end_date)]
#Create another column called year to select the number of unique sequence and number of mutations
df['year'] = pd.to_datetime(df['Date']).dt.year
start = 2000
length = 20
i = 0
with open('output_{}.txt'.format(name[:-4]), 'a') as output:
output.write('Year Mutation Rate\n')
while i <= length:
specific_year = df[(df['year'] == start + i)]
#Calculate the number of mutations
num_mutations = np.float64(specific_year['year'].count())
#Calculate the number of unique sequence
num_unique = np.float64(specific_year['Accession ID'].nunique())
#Calculate the mutation rate
if num_unique != 0:
mutation_rate = num_mutations/num_unique
else:
mutation_rate = 0
output.write('{} {}\n'.format(start + i, mutation_rate))
i += 1
| _____no_output_____ | MIT | analysis/Mutation_analysis.ipynb | chuducthang77/coronavirus |
Table of Contents 0.0.1 Cover Slide 10.0.2 Cover Slide 21 Headline Slide2 Preprocessing3 Headline Subslide4 Fragment4.0.1 Divider5 Markdown Examples5.0.0.1 Text6 Headline Subslide6.0.0.1 Code7 Python example7.0.0.1 Code8 Headline Subslide8.0.0.1 Lists9 Headline Subslide9.0.0.1 Lists10 Headline Subslide10.0.0.1 Blockquotes10.0.0.2 inline code11 Table12 Images13 Links13.0.1 Q&A Slide | # Add all necessary imports here
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.reload_library()
plt.style.use("ggplot") | _____no_output_____ | MIT | reports/Presentations/Presentation_241117/timing_presentation.ipynb | EstevaoVieira/spikelearn |
Cover Slide 1 | <image>
<section data-background="img/cover.jpg" data-state="img-transparent no-title-footer">
<div class="intro-body">
<div class="intro_h1"><h1>Title</h1></div>
<h3>Subtitle of the Presentation</h3>
<p><strong><span class="a">Speaker 1</span></strong> <span class="b"></span> <span>Job Title</span></p>
<p><strong><span class="a">Speaker 2</span></strong> <span class="b"></span> <span>Job Title</span></p>
<p> </p>
<p> </p>
</div>
</section>
</image> | _____no_output_____ | MIT | reports/Presentations/Presentation_241117/timing_presentation.ipynb | EstevaoVieira/spikelearn |
Cover Slide 2 | <image>
<section data-state="no-title-footer">
<div class="intro_h1"><h1>Title</h1></div>
<h3>Subtitle of the Presentation</h3>
<p><strong><span class="a">Speaker 1</span></strong> <span class="b"></span> <span>Job Title</span></p>
<p><strong><span class="a">Speaker 2</span></strong> <span class="b"></span> <span>Job Title</span></p>
<p> </p>
<p> </p>
</section>
</image> | _____no_output_____ | MIT | reports/Presentations/Presentation_241117/timing_presentation.ipynb | EstevaoVieira/spikelearn |
Headline Slide Preprocessing       | def f(x):
"""a docstring"""
return x**2 | _____no_output_____ | MIT | reports/Presentations/Presentation_241117/timing_presentation.ipynb | EstevaoVieira/spikelearn |
Headline Subslide | plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show() | _____no_output_____ | MIT | reports/Presentations/Presentation_241117/timing_presentation.ipynb | EstevaoVieira/spikelearn |
FragmentPress the right arrow. - I am a Fragement - I am another one Divider | <image>
</section>
<section data-background="#F27C3A" data-state="no-title-footer">
<div class="divider_h1">
<h1>Divider</h1>
</div>
</section>
</image> | _____no_output_____ | MIT | reports/Presentations/Presentation_241117/timing_presentation.ipynb | EstevaoVieira/spikelearn |
Markdown Examples TextIt's very easy to make some words **bold** and other words *italic* with Markdown. You can even [link to Google!](http://google.com) Headline Subslide Code```javascriptvar s = "JavaScript syntax highlighting";alert(s);``` ```pythons = "Python syntax highlighting"print s``` ```No language indicated, so no syntax highlighting. But let's throw in a tag.``` Python example Code```python This program adds up integers in the command lineimport systry: total = sum(int(arg) for arg in sys.argv[1:]) print 'sum =', totalexcept ValueError: print 'Please supply integer arguments'``` Headline Subslide ListsSometimes you want numbered lists:1. Item 12. Item 23. Item 3 * Item 3a * Item 3b Headline Subslide ListsSometimes you want bullet points:* Item 1* Item 2 * Item 2a * Item 2b* This is a long long long long long long long long long long long long long long long long long long long long long long long long long list Headline Subslide BlockquotesAs Kanye West said:> We're living the future so> the present is our past. inline codeI think you should use an`` element here instead. Table| Tables | Are | Cool || ------------- |:-------------:| -----:|| col 3 is | right-aligned | $1600 || col 2 is | centered | $12 || zebra stripes | are neat | $1 | ImagesIf you want to embed images, this is how you do it: Links- https://guides.github.com/features/mastering-markdown/- https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet Q&A Slide | <image>
</section>
<section data-background="#0093C9" data-state="no-title-footer">
<div class="divider_h1">
<h1>Questions???</h1>
</div>
</section>
</image> | _____no_output_____ | MIT | reports/Presentations/Presentation_241117/timing_presentation.ipynb | EstevaoVieira/spikelearn |
test: 30% train-val 70%To simulate noisy label acquisition, assume a labeler quality p. then use a random we first hide the labels of all examples for each dataset. At the point in an experiment when a label is acquired, we generate a label according to the labeler quality p: we assign the example's original label with the probability p and the opposite value with the probability 1−p. For each worker, the original true label was assigned to each instance with the probability p, and the opposite value was assigned with the probability 1−𝑝. In our experiments, the labeling quality p of each worker was generated randomly from a uniform distribution on the interval (0.3, 0.9)After obtaining the labels, we construct the training set to induce a classifier. The classifier is evaluated on the test set (with the true labels). Each experiment is repeated 10 times with a different random data partition, and average results are reported. procedure1. generate a random p for each labeler2. generate a random number from a random variable for each instance and if the value is bigger than p, then assign the true label, but if its smaller than p then assign the opposite of true label for that worker 3. train a network for these noisy labels for each labeler 4. repeate this 10 times to be able to measure ethe uncertainty and average accuracy. When it is necessary, we convert the target to binary- for thyroid we keep the negative class and integrate the other three classes into positive; - for splice, we integrate classes IE and EI; - for waveform, we integrate classes 1 and 2.) | %reload_ext autoreload
%autoreload 2
import sys, os, wget
sys.path.append('../../')
import pandas as pd
import numpy as np
import load_data
import ipywidgets
from IPython.display import display
args = {'options': ['read', 'download'],
'label': 'read',
'description': 'mode:' ,
'orientation': 'vertical',
'disabled': False,
'button_style': '',
'layout': {'width': 'max-content'},
'tooltips': ['reading the dataset', 'downloading the dataset'],
}
dataset_mode = ipywidgets.ToggleButtons( **args )
display(dataset_mode)
dataset = ipywidgets.Dropdown( options = [ ('1. kr-vs-kp' ,'kr-vs-kp'),
('2. mushroom' ,'mushroom'),
('3. sick' ,'sick'),
('4. spambase' ,'spambase'),
('5. tic-tac-toe' ,'tic-tac-toe'),
('6. splice' ,'splice'),
('7. thyroid' ,'thyroid'),
('8. waveform' ,'waveform'),
('9. biodeg' ,'biodeg'),
('10. horse-colic','horse-colic'),
('11. ionosphere' ,'ionosphere'),
('12. vote' ,'vote')],
value = 'horse-colic')
@ipywidgets.interact(WHICH_DATASET = dataset)
def read_data(WHICH_DATASET):
if WHICH_DATASET in ['splice','vote','thyroid']:
print('dataset does not exist')
else:
global data, feature_columns
data, feature_columns = load_data.aim1_3_read_download_UCI_database( WHICH_DATASET = WHICH_DATASET,
mode = dataset_mode.value)
print(data['train'].head(3) , '\ntrain shape:',data['train'].shape , '\ntest shape:',data['test'].shape)
data, feature_columns = load_data.aim1_3_read_download_UCI_database(WHICH_DATASET='biodeg', mode='read')
data
data, feature_columns = load_data.aim1_3_read_download_UCI_database(WHICH_DATASET='horse-colic', mode='read_raw')
data['train']
pd.read_csv('/groups/jjrodrig/projects/datasets/uci_multilabeler_aim1_3/UCI_horse-colic/horse-colic.data',delimiter=' ', index_col=None) | _____no_output_____ | Apache-2.0 | examples_artin/applied_to_other_datasets.ipynb | artinmajdi/crowd-kit |
guide for ipywidgetssource: | widgets.FloatRangeSlider(
value=[5, 7.5],
min=0,
max=10.0,
step=0.1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.1f',
)
b = widgets.BoundedFloatText(
value=7.5,
min=0,
max=10.0,
step=0.1,
description='Text:',
disabled=False
)
b
b.value
a = widgets.ToggleButton(
value=False,
description='Run',
button_style='', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Description',
icon='check')
a
a.value
c = widgets.Checkbox(
value=False,
description='this',
disabled=False,
indent=False
)
c
c.value
widgets.Valid(
value=True,
description='Status:',
)
d = widgets.Dropdown(
options=[('One', 1), ('Two', 2), ('Three', 3)],
value=2,
description='Number:')
d.value
widgets.RadioButtons(
options=['pepperoni', 'pineapple', 'anchovies'],
# value='pineapple', # Defaults to 'pineapple'
# layout={'width': 'max-content'}, # If the items' names are long
description='Pizza topping:',
disabled=False
)
widgets.Box(
[
widgets.Label(value='Pizza topping with a very long label:'),
widgets.RadioButtons(
options=[
'pepperoni',
'pineapple',
'anchovies',
'and the long name tha'
],
layout={'width': 'max-content'}
)
]
)
widgets.Select(
options=['Linux', 'Windows', 'OSX'],
value='OSX',
# rows=10,
description='OS:',
disabled=False
)
widgets.ToggleButtons(
options=['Slow', 'Regular', 'Fast'],
description='Speed:',
disabled=False,
button_style='', # 'success', 'info', 'warning', 'danger' or ''
tooltips=['Description of slow', 'Description of regular', 'Description of fast'],
icons=['check'] * 3
)
a = widgets.ColorPicker(
concise=False,
description='Pick a color',
value='blue',
disabled=False
)
a
widgets.FileUpload(
accept='', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf'
multiple=False # True to accept multiple files upload else False
)
from IPython.display import display
def func3(a,b,c):
display((a+b)^c)
w = interactive(func3, a=ipywidgets.IntSlider(min=10, max=50, value=25, step=2),
b=ipywidgets.IntSlider(min=10, max=50, value=25, step=2),
c=ipywidgets.IntSlider(min=10, max=50, value=25, step=2) )
display(w) | _____no_output_____ | Apache-2.0 | examples_artin/applied_to_other_datasets.ipynb | artinmajdi/crowd-kit |
XGBoost Cloud Prediction - Iris ClassificationInvoke SageMaker Prediction Service | # Acquire a realtime endpoint
endpoint_name = 'xgboost-iris-v1'
predictor = sagemaker.predictor.Predictor (endpoint_name=endpoint_name)
predictor.serializer = CSVSerializer()
# Test predictive quality against data in validation file
df_all = pd.read_csv('iris_validation.csv',
names=['encoded_class','sepal_length','sepal_width','petal_length','petal_width'])
df_all.head()
df_all.columns
# Need to pass an array to the prediction
# can pass a numpy array or a list of values [[19,1],[20,1]]
# arr_test = df_all.as_matrix(['sepal_length', 'sepal_width', 'petal_length','petal_width'])
arr_test = df_all[['sepal_length', 'sepal_width', 'petal_length','petal_width']].values
type(arr_test)
arr_test.shape
arr_test[:5]
result = predictor.predict(arr_test[:2])
arr_test.shape
result
# For large number of predictions, we can split the input data and
# Query the prediction service.
# array_split is convenient to specify how many splits are needed
predictions = []
for arr in np.array_split(arr_test,10):
result = predictor.predict(arr)
result = result.decode("utf-8")
result = result.split(',')
print (arr.shape)
predictions += [int(float(r)) for r in result]
len(predictions)
predictions[:5]
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])
df_all['class'] = le.inverse_transform(df_all.encoded_class)
df_all['predicted_class']=le.inverse_transform(predictions)
df_all.head()
print('Confusion matrix - Actual versus Predicted')
pd.crosstab(df_all['class'], df_all['predicted_class'])
import sklearn.metrics as metrics
print(metrics.classification_report(df_all['class'], df_all['predicted_class'])) | _____no_output_____ | Apache-2.0 | 5 Xgboost/IrisClassification/xgboost_cloud_prediction_template.ipynb | jaypeeml/AWSSagemaker |
宣告- 只能存不重複的元素- 因為是無序的,所以每次編譯後的順序都會不同 | a = {1, 2, 3, 2, 4, 5, 2}
b = set([1, 2, 3, 2, 4, 5, 2])
print(a, type(a))
print(b, type(b))
s1.add(5)
print(s1)
s1.add(5)
print(s1)
s1.remove(5)
print(s1)
# 因為找不到,所以會報錯
#s1.remove(8)
#print(s1)
a = '1234512'
print(set(a))
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
print('交集:', s1 & s2)
print('聯集:', s1 | s2)
print('對稱差集:', s1 ^ s2)
print('差集1:', s1 - s2)
print('差集2:', s2 - s1) | 交集: {3, 4}
聯集: {1, 2, 3, 4, 5, 6}
對稱差集: {1, 2, 5, 6}
差集1: {1, 2}
差集2: {5, 6}
| MIT | Python/[Python] Set.ipynb | ZongSingHuang/Data-Scientist-Tokyo |
Image annotations for a batch of samplesUsing this notebook, cardiologists are able to quickly view and annotate MRI images for a batch of samples. These annotated images become the training data for the next round of modeling. Setup This notebook assumes Terra is running custom Docker image ghcr.io/broadinstitute/ml4h/ml4h_terra:20211101_143643. ml4h is running custom Docker image gcr.io/broad-ml4cvd/deeplearning:tf2-latest-gpu.  | # TODO(deflaux): remove this cell after gcr.io/broad-ml4cvd/deeplearning:tf2-latest-gpu has this preinstalled.
from ml4h.runtime_data_defines import determine_runtime
from ml4h.runtime_data_defines import Runtime
if Runtime.ML4H_VM == determine_runtime():
!pip3 install --user ipycanvas==0.7.0 ipyannotations==0.2.1
!jupyter nbextension install --user --py ipycanvas
!jupyter nbextension enable --user --py ipycanvas
# Be sure to restart the kernel if pip installs anything.
# Also, shift-reload the browser page after the notebook extension installation.
from ipyannotations import BoxAnnotator, PointAnnotator, PolygonAnnotator
from ml4h.visualization_tools.annotation_storage import BigQueryAnnotationStorage
from ml4h.visualization_tools.batch_image_annotations import BatchImageAnnotator
import pandas as pd
import tensorflow as tf
%%javascript
// Display cell outputs to full height (no vertical scroll bar)
IPython.OutputArea.auto_scroll_threshold = 9999;
pd.set_option('display.max_colwidth', -1)
BIG_QUERY_ANNOTATIONS_STORAGE = BigQueryAnnotationStorage('uk-biobank-sek-data.ml_results.annotations') | _____no_output_____ | BSD-3-Clause | notebooks/review_results/image_annotations.ipynb | deflaux/ml4h |
Define the batch of samples to annotate Edit the CSV file path below, if needed, to either a local file or one in Cloud Storage. | #---[ EDIT AND RUN THIS CELL TO READ FROM A LOCAL FILE OR A FILE IN CLOUD STORAGE ]---
SAMPLE_BATCH_FILE = None
if SAMPLE_BATCH_FILE:
samples_df = pd.read_csv(tf.io.gfile.GFile(SAMPLE_BATCH_FILE))
else:
# Normally these would all be the same or similar TMAP. We are using different ones here just to make it
# more obvious in this demo that we are processing different samples.
samples_df = pd.DataFrame(
columns=BatchImageAnnotator.EXPECTED_COLUMN_NAMES,
data=[
[1655349, 'cine_lax_3ch_192', 25, 'gs://ml4cvd/deflaux/ukbb_tensors/'],
[1655349, 't2_flair_sag_p2_1mm_fs_ellip_pf78_1', 50, 'gs://ml4cvd/deflaux/ukbb_tensors/'],
[1655349, 'cine_lax_4ch_192', 25, 'gs://ml4cvd/deflaux/ukbb_tensors/'],
[1655349, 't2_flair_sag_p2_1mm_fs_ellip_pf78_2', 50, 'gs://ml4cvd/deflaux/ukbb_tensors/'],
[2403657, 'cine_lax_3ch_192', 25, 'gs://ml4cvd/deflaux/ukbb_tensors/'],
])
samples_df.shape
samples_df.head(n = 10) | _____no_output_____ | BSD-3-Clause | notebooks/review_results/image_annotations.ipynb | deflaux/ml4h |
Annotate the batch! Annotate with pointsUse points to annotate landmarks within the images. | # Note: a zoom level of 1.0 displays the tensor as-is. For higher zoom levels, this code currently
# use the PIL library to scale the image.
annotator = BatchImageAnnotator(samples=samples_df,
zoom=2.0,
annotation_categories=['region_of_interest'],
annotation_storage=BIG_QUERY_ANNOTATIONS_STORAGE,
annotator=PointAnnotator)
annotator.annotate_images() | _____no_output_____ | BSD-3-Clause | notebooks/review_results/image_annotations.ipynb | deflaux/ml4h |
Annotate with polygonsUse polygons to annotate arbitrarily shaped regions within the images. | # Note: a zoom level of 1.0 displays the tensor as-is. For higher zoom levels, this code currently
# use the PIL library to scale the image.
annotator = BatchImageAnnotator(samples=samples_df,
zoom=2.0,
annotation_categories=['region_of_interest'],
annotation_storage=BIG_QUERY_ANNOTATIONS_STORAGE,
annotator=PolygonAnnotator)
annotator.annotate_images() | _____no_output_____ | BSD-3-Clause | notebooks/review_results/image_annotations.ipynb | deflaux/ml4h |
Annotate with rectanglesUse rectangles to annotate rectangular regions within the image. | # Note: a zoom level of 1.0 displays the tensor as-is. For higher zoom levels, this code currently
# use the PIL library to scale the image.
annotator = BatchImageAnnotator(samples=samples_df,
zoom=2.0,
annotation_categories=['region_of_interest'],
annotation_storage=BIG_QUERY_ANNOTATIONS_STORAGE,
annotator=BoxAnnotator)
annotator.annotate_images() | _____no_output_____ | BSD-3-Clause | notebooks/review_results/image_annotations.ipynb | deflaux/ml4h |
View the stored annotations | annotator.view_recent_submissions(count=10) | _____no_output_____ | BSD-3-Clause | notebooks/review_results/image_annotations.ipynb | deflaux/ml4h |
Provenance | import datetime
print(datetime.datetime.now())
%%bash
pip3 freeze | _____no_output_____ | BSD-3-Clause | notebooks/review_results/image_annotations.ipynb | deflaux/ml4h |
'ewm' series is the most stationary out of all the series. Hence we model on 'ewm' | from pandas.tools.plotting import autocorrelation_plot
autocorrelation_plot(ewm)
from statsmodels.tsa.arima_model import ARIMA
model = ARIMA(ewm, order = (15, 1, 0))
model_fit = model.fit(disp = 0)
plt.plot(model_fit.fittedvalues)
logpred_diff = pd.Series(model_fit.fittedvalues, index = ewm.index)
logpred_cumsum = logpred_diff.cumsum()
logpred = pd.Series(ewm.iloc[0], index = ewm.index)
logpred = logpred.add(logpred_cumsum, fill_value = 0)
logpred.head()
ewm.head()
pred = np.exp(logpred)
pred.head()
violence.head()
plt.plot(pred, label = 'Prediction')
plt.plot(violence, label = 'Expected')
plt.legend(loc = 'best')
violence.tail()
dates = [pd.Timestamp('2018-05-31'), pd.Timestamp('2018-06-30'), pd.Timestamp('2018-07-31'), pd.Timestamp('2018-08-31'), pd.Timestamp('2018-09-30')]
forecast = pd.Series(model_fit.forecast(steps = 5)[0], dates)
forecast = np.exp(forecast)
forecast.head()
plt.plot(forecast, label = 'Forecast')
plt.title("Forecast for the next Five Months")
plt.legend(loc = 'best')
autocorrelation_plot(violence)
model = ARIMA(violence.astype(float), order = (10,1,0))
model_fit = model.fit(disp = 0)
plt.plot(model_fit.fittedvalues)
model_fit.fittedvalues.head()
violence.head()
forecast = pd.Series(model_fit.forecast(steps = 5)[0], dates)
forecast
plt.plot(forecast)
plt.title("Forecasted") | _____no_output_____ | MIT | Gun Violence.ipynb | itsmepiyush2/Effects-of-Gun-Violence-forecast |
Testing the functionalities of MetaTuner on bcancer dataset | from mango import MetaTuner
# Define different classifiers
from scipy.stats import uniform
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score
data = datasets.load_breast_cancer()
X = data.data
Y = data.target | _____no_output_____ | Apache-2.0 | benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb | jashanmeet-collab/mango |
XGBoost | from xgboost import XGBClassifier
param_dict_xgboost = {"learning_rate": uniform(0, 1),
"gamma": uniform(0, 5),
"max_depth": range(1, 16),
"n_estimators": range(1, 4),
"booster":['gbtree','gblinear','dart']
}
X_xgboost = X
Y_xgboost = Y
# import warnings
# warnings.filterwarnings('ignore')
def objective_xgboost(args_list):
global X_xgboost, Y_xgboost
results = []
for hyper_par in args_list:
#clf = XGBClassifier(**hyper_par)
clf = XGBClassifier(verbosity = 0, random_state = 0)
#clf = XGBClassifier()
clf.set_params(**hyper_par)
result = cross_val_score(clf, X_xgboost, Y_xgboost, scoring='accuracy', cv=3).mean()
results.append(result)
return results | _____no_output_____ | Apache-2.0 | benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb | jashanmeet-collab/mango |
KNN | param_dict_knn = {"n_neighbors": range(1, 101),
'algorithm' : ['auto', 'ball_tree', 'kd_tree', 'brute']
}
X_knn = X
Y_knn = Y
def objective_knn(args_list):
global X_knn,Y_knn
results = []
for hyper_par in args_list:
clf = KNeighborsClassifier()
clf.set_params(**hyper_par)
result = cross_val_score(clf, X_knn, Y_knn, scoring='accuracy', cv=3).mean()
results.append(result)
return results | _____no_output_____ | Apache-2.0 | benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb | jashanmeet-collab/mango |
SVM | from mango.domain.distribution import loguniform
from sklearn import svm
param_dict_svm = {"gamma": uniform(0.1, 4),
"C": loguniform(-7, 10)}
X_svm = X
Y_svm = Y
def objective_svm(args_list):
global X_svm,Y_svm
#print('SVM:',args_list)
results = []
for hyper_par in args_list:
clf = svm.SVC(random_state = 0)
clf.set_params(**hyper_par)
result = cross_val_score(clf, X_svm, Y_svm, scoring='accuracy', cv= 3).mean()
results.append(result)
return results | _____no_output_____ | Apache-2.0 | benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb | jashanmeet-collab/mango |
Decision Tree | from sklearn.tree import DecisionTreeClassifier
param_dict_dtree = {
"max_features": ['auto', 'sqrt', 'log2'],
"max_depth": range(1,21),
"splitter":['best','random'],
"criterion":['gini','entropy']
}
X_dtree = X
Y_dtree = Y
print(X_dtree.shape, Y_dtree.shape)
def objective_dtree(args_list):
global X_dtree,Y_dtree
results = []
for hyper_par in args_list:
clf = DecisionTreeClassifier(random_state = 0)
clf.set_params(**hyper_par)
result = cross_val_score(clf, X_dtree, Y_dtree, scoring='accuracy', cv=3).mean()
results.append(result)
return results
param_space_list = [param_dict_knn, param_dict_svm, param_dict_dtree, param_dict_xgboost]
objective_list = [objective_knn, objective_svm, objective_dtree, objective_xgboost]
metatuner = MetaTuner(param_space_list, objective_list)
results = metatuner.run()
# see the keys results of evaluations
for k in results:
print(k)
print('best_objective:',results['best_objective'])
print('best_params:',results['best_params'])
print('best_objective_fid:',results['best_objective_fid'])
#order of function evaluation, initial order is random
print(results['objective_fid'])
# See the evaluation order of function values
print(results['objective_values']) | [0.9016522788452613, 0.9016244314489928, 0.6264204028589994, 0.6274204028589994, 0.924412884062007, 0.924403601596584, 0.9208948296667595, 0.9402394876079088, 0.91914972616727, 0.8700083542188805, 0.9208948296667595, 0.8893158822983386, 0.9384665367121507, 0.8752900770444629, 0.7431913116123643, 0.924403601596584, 0.8840248770073332, 0.9173767752715122, 0.9208948296667595, 0.9156595191682911, 0.924412884062007, 0.9420124385036667, 0.9261579875614964, 0.9103777963427087, 0.9261951174231876, 0.6274204028589994, 0.9050960735171261, 0.933194096351991]
| Apache-2.0 | benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb | jashanmeet-collab/mango |
A simple chart of function evaluations | def count_elements(seq):
"""Tally elements from `seq`."""
hist = {}
for i in seq:
hist[i] = hist.get(i, 0) + 1
return hist
def ascii_histogram(seq):
"""A horizontal frequency-table/histogram plot."""
counted = count_elements(seq)
for k in sorted(counted):
print('{0:5d} {1}'.format(k, '+' * counted[k]))
ascii_histogram(results['objective_fid']) | 0 ++++
1 +++
2 ++++++++++++
3 +++++++++
| Apache-2.0 | benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb | jashanmeet-collab/mango |
May be possible to entangle all ions with global pulse with multiple tones. | from numpy import *
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from Error_dist import func_str
# 10-ion test
N = 11
x = arange(1, N)
y = x
def func(x, a, b, c, d, e):
return (a / x ** 0.5 + b / x ** 0.7 + c / x ** 1 + d / x ** 1.5 + e / x ** 2)
# Assume entangling strengt\ scales as 1 / d ^ r where 0.5 < r < 3
def func_log(x, a, b, c, d, e):
return - log(a / x ** 0.5 + b / x ** 0.7 + c / x ** 1 + d / x ** 1.5 + e / x ** 2)
popt, pcov = curve_fit(func_log, x, y)
x_cont = linspace(1, N, 1000)
y_cont = func_log(x_cont, *popt)
print(f'Function: {func_str(func_log)}')
plt.plot(x, y, 'bo')
plt.plot(x_cont, y_cont, 'r')
plt.show()
print(f"Parameters: {popt}")
def func(x, a, b, c, d, e):
return (a / x ** 0.5 + b / x ** 0.7 + c / x ** 1 + d / x ** 1.5 + e / x ** 2)
# Assume entangling strengt\ scales as 1 / d ^ r where 0.5 < r < 3
def func_log(x, a, b, c, d, e):
return - log(func(x, a, b, c, d, e))
N_start = 21
N = 30
x = arange(N_start, N)
y = exp(-x)
popt, pcov = curve_fit(func, x, y)
x_disc = arange(25, N+2)
y_disc = exp(-x_disc)
L = len(x_disc)
x_cont = linspace(25, N+3, 1000)
y_cont = func(x_cont, *popt)
x = arange(1, N)
y = exp(-x)
print(f'Function: {func_str(func)}')
plt.plot(x_disc, y_disc, 'bo')
plt.plot(x_cont, y_cont, 'r')
# plt.ylim([y_disc[L-1] * 0.9, y_disc[0] * 1.1])
# plt.ylim([y_disc[L-1] * 0.9, y_disc[0] * 0.01])
plt.show()
print(f"Parameters (normalized by {popt[0]}): {popt / popt[0]}")
# print(f"Covariance: {pcov}")
N = 20
x = linspace(1, N, 300)
plt.plot(x, func1(x, *popt))
x_dots = arange(1, N)
plt.plot(x_dots, exp(-x_dots), 'ro')
plt.ylim([-0.01, 0.5])
| _____no_output_____ | Apache-2.0 | Global beam test.ipynb | jlfly12/qrsim |
**4장 – 모델 훈련** _이 노트북은 4장에 있는 모든 샘플 코드와 연습문제 해답을 가지고 있습니다._ 구글 코랩에서 실행하기 설정 먼저 몇 개의 모듈을 임포트합니다. 맷플롯립 그래프를 인라인으로 출력하도록 만들고 그림을 저장하는 함수를 준비합니다. 또한 파이썬 버전이 3.5 이상인지 확인합니다(파이썬 2.x에서도 동작하지만 곧 지원이 중단되므로 파이썬 3을 사용하는 것이 좋습니다). 사이킷런 버전이 0.20 이상인지도 확인합니다. | # 파이썬 ≥3.5 필수
import sys
assert sys.version_info >= (3, 5)
# 사이킷런 ≥0.20 필수
import sklearn
assert sklearn.__version__ >= "0.20"
# 공통 모듈 임포트
import numpy as np
import os
# 노트북 실행 결과를 동일하게 유지하기 위해
np.random.seed(42)
# 깔끔한 그래프 출력을 위해
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)
# 그림을 저장할 위치
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "training_linear_models"
IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID)
os.makedirs(IMAGES_PATH, exist_ok=True)
def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
print("그림 저장:", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(path, format=fig_extension, dpi=resolution) | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
선형 회귀 | import numpy as np
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
plt.plot(X, y, "b.")
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.axis([0, 2, 0, 15])
save_fig("generated_data_plot")
plt.show() | 그림 저장: generated_data_plot
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
**식 4-4: 정규 방정식**$\hat{\boldsymbol{\theta}} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}$ | X_b = np.c_[np.ones((100, 1)), X] # 모든 샘플에 x0 = 1을 추가합니다.
theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)
theta_best | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
$\hat{y} = \mathbf{X} \boldsymbol{\hat{\theta}}$ | X_new = np.array([[0], [2]])
X_new_b = np.c_[np.ones((2, 1)), X_new] # 모든 샘플에 x0 = 1을 추가합니다.
y_predict = X_new_b.dot(theta_best)
y_predict
plt.plot(X_new, y_predict, "r-")
plt.plot(X, y, "b.")
plt.axis([0, 2, 0, 15])
plt.show() | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
책에 있는 그림은 범례와 축 레이블이 있는 그래프입니다: | plt.plot(X_new, y_predict, "r-", linewidth=2, label="Predictions")
plt.plot(X, y, "b.")
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.legend(loc="upper left", fontsize=14)
plt.axis([0, 2, 0, 15])
save_fig("linear_model_predictions_plot")
plt.show()
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)
lin_reg.intercept_, lin_reg.coef_
lin_reg.predict(X_new) | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
`LinearRegression` 클래스는 `scipy.linalg.lstsq()` 함수("least squares"의 약자)를 사용하므로 이 함수를 직접 사용할 수 있습니다: | # 싸이파이 lstsq() 함수를 사용하려면 scipy.linalg.lstsq(X_b, y)와 같이 씁니다.
theta_best_svd, residuals, rank, s = np.linalg.lstsq(X_b, y, rcond=1e-6)
theta_best_svd | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
이 함수는 $\mathbf{X}^+\mathbf{y}$을 계산합니다. $\mathbf{X}^{+}$는 $\mathbf{X}$의 _유사역행렬_ (pseudoinverse)입니다(Moore–Penrose 유사역행렬입니다). `np.linalg.pinv()`을 사용해서 유사역행렬을 직접 계산할 수 있습니다: $\boldsymbol{\hat{\theta}} = \mathbf{X}^{-1}\hat{y}$ | np.linalg.pinv(X_b).dot(y) | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
경사 하강법 배치 경사 하강법 **식 4-6: 비용 함수의 그레이디언트 벡터**$\dfrac{\partial}{\partial \boldsymbol{\theta}} \text{MSE}(\boldsymbol{\theta}) = \dfrac{2}{m} \mathbf{X}^T (\mathbf{X} \boldsymbol{\theta} - \mathbf{y})$**식 4-7: 경사 하강법의 스텝**$\boldsymbol{\theta}^{(\text{next step})} = \boldsymbol{\theta} - \eta \dfrac{\partial}{\partial \boldsymbol{\theta}} \text{MSE}(\boldsymbol{\theta})$ | eta = 0.1 # 학습률
n_iterations = 1000
m = 100
theta = np.random.randn(2,1) # 랜덤 초기화
for iteration in range(n_iterations):
gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
theta = theta - eta * gradients
theta
X_new_b.dot(theta)
theta_path_bgd = []
def plot_gradient_descent(theta, eta, theta_path=None):
m = len(X_b)
plt.plot(X, y, "b.")
n_iterations = 1000
for iteration in range(n_iterations):
if iteration < 10:
y_predict = X_new_b.dot(theta)
style = "b-" if iteration > 0 else "r--"
plt.plot(X_new, y_predict, style)
gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
theta = theta - eta * gradients
if theta_path is not None:
theta_path.append(theta)
plt.xlabel("$x_1$", fontsize=18)
plt.axis([0, 2, 0, 15])
plt.title(r"$\eta = {}$".format(eta), fontsize=16)
np.random.seed(42)
theta = np.random.randn(2,1) # random initialization
plt.figure(figsize=(10,4))
plt.subplot(131); plot_gradient_descent(theta, eta=0.02)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.subplot(132); plot_gradient_descent(theta, eta=0.1, theta_path=theta_path_bgd)
plt.subplot(133); plot_gradient_descent(theta, eta=0.5)
save_fig("gradient_descent_plot")
plt.show() | 그림 저장: gradient_descent_plot
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
확률적 경사 하강법 | theta_path_sgd = []
m = len(X_b)
np.random.seed(42)
n_epochs = 50
t0, t1 = 5, 50 # 학습 스케줄 하이퍼파라미터
def learning_schedule(t):
return t0 / (t + t1)
theta = np.random.randn(2,1) # 랜덤 초기화
for epoch in range(n_epochs):
for i in range(m):
if epoch == 0 and i < 20: # 책에는 없음
y_predict = X_new_b.dot(theta) # 책에는 없음
style = "b-" if i > 0 else "r--" # 책에는 없음
plt.plot(X_new, y_predict, style) # 책에는 없음
random_index = np.random.randint(m)
xi = X_b[random_index:random_index+1]
yi = y[random_index:random_index+1]
gradients = 2 * xi.T.dot(xi.dot(theta) - yi)
eta = learning_schedule(epoch * m + i)
theta = theta - eta * gradients
theta_path_sgd.append(theta) # 책에는 없음
plt.plot(X, y, "b.") # 책에는 없음
plt.xlabel("$x_1$", fontsize=18) # 책에는 없음
plt.ylabel("$y$", rotation=0, fontsize=18) # 책에는 없음
plt.axis([0, 2, 0, 15]) # 책에는 없음
save_fig("sgd_plot") # 책에는 없음
plt.show() # 책에는 없음
theta
from sklearn.linear_model import SGDRegressor
sgd_reg = SGDRegressor(max_iter=1000, tol=1e-3, penalty=None, eta0=0.1, random_state=42)
sgd_reg.fit(X, y.ravel())
sgd_reg.intercept_, sgd_reg.coef_ | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
미니배치 경사 하강법 | theta_path_mgd = []
n_iterations = 50
minibatch_size = 20
np.random.seed(42)
theta = np.random.randn(2,1) # 랜덤 초기화
t0, t1 = 200, 1000
def learning_schedule(t):
return t0 / (t + t1)
t = 0
for epoch in range(n_iterations):
shuffled_indices = np.random.permutation(m)
X_b_shuffled = X_b[shuffled_indices]
y_shuffled = y[shuffled_indices]
for i in range(0, m, minibatch_size):
t += 1
xi = X_b_shuffled[i:i+minibatch_size]
yi = y_shuffled[i:i+minibatch_size]
gradients = 2/minibatch_size * xi.T.dot(xi.dot(theta) - yi)
eta = learning_schedule(t)
theta = theta - eta * gradients
theta_path_mgd.append(theta)
theta
theta_path_bgd = np.array(theta_path_bgd)
theta_path_sgd = np.array(theta_path_sgd)
theta_path_mgd = np.array(theta_path_mgd)
plt.figure(figsize=(7,4))
plt.plot(theta_path_sgd[:, 0], theta_path_sgd[:, 1], "r-s", linewidth=1, label="Stochastic")
plt.plot(theta_path_mgd[:, 0], theta_path_mgd[:, 1], "g-+", linewidth=2, label="Mini-batch")
plt.plot(theta_path_bgd[:, 0], theta_path_bgd[:, 1], "b-o", linewidth=3, label="Batch")
plt.legend(loc="upper left", fontsize=16)
plt.xlabel(r"$\theta_0$", fontsize=20)
plt.ylabel(r"$\theta_1$ ", fontsize=20, rotation=0)
plt.axis([2.5, 4.5, 2.3, 3.9])
save_fig("gradient_descent_paths_plot")
plt.show() | 그림 저장: gradient_descent_paths_plot
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
다항 회귀 | import numpy as np
import numpy.random as rnd
np.random.seed(42)
m = 100
X = 6 * np.random.rand(m, 1) - 3
y = 0.5 * X**2 + X + 2 + np.random.randn(m, 1)
plt.plot(X, y, "b.")
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.axis([-3, 3, 0, 10])
save_fig("quadratic_data_plot")
plt.show()
from sklearn.preprocessing import PolynomialFeatures
poly_features = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly_features.fit_transform(X)
X[0]
X_poly[0]
lin_reg = LinearRegression()
lin_reg.fit(X_poly, y)
lin_reg.intercept_, lin_reg.coef_
X_new=np.linspace(-3, 3, 100).reshape(100, 1)
X_new_poly = poly_features.transform(X_new)
y_new = lin_reg.predict(X_new_poly)
plt.plot(X, y, "b.")
plt.plot(X_new, y_new, "r-", linewidth=2, label="Predictions")
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.legend(loc="upper left", fontsize=14)
plt.axis([-3, 3, 0, 10])
save_fig("quadratic_predictions_plot")
plt.show()
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
for style, width, degree in (("g-", 1, 300), ("b--", 2, 2), ("r-+", 2, 1)):
polybig_features = PolynomialFeatures(degree=degree, include_bias=False)
std_scaler = StandardScaler()
lin_reg = LinearRegression()
polynomial_regression = Pipeline([
("poly_features", polybig_features),
("std_scaler", std_scaler),
("lin_reg", lin_reg),
])
polynomial_regression.fit(X, y)
y_newbig = polynomial_regression.predict(X_new)
plt.plot(X_new, y_newbig, style, label=str(degree), linewidth=width)
plt.plot(X, y, "b.", linewidth=3)
plt.legend(loc="upper left")
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.axis([-3, 3, 0, 10])
save_fig("high_degree_polynomials_plot")
plt.show() | 그림 저장: high_degree_polynomials_plot
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
학습 곡선 | from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
def plot_learning_curves(model, X, y):
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=10)
train_errors, val_errors = [], []
for m in range(1, len(X_train) + 1):
model.fit(X_train[:m], y_train[:m])
y_train_predict = model.predict(X_train[:m])
y_val_predict = model.predict(X_val)
train_errors.append(mean_squared_error(y_train[:m], y_train_predict))
val_errors.append(mean_squared_error(y_val, y_val_predict))
plt.plot(np.sqrt(train_errors), "r-+", linewidth=2, label="train")
plt.plot(np.sqrt(val_errors), "b-", linewidth=3, label="val")
plt.legend(loc="upper right", fontsize=14) # 책에는 없음
plt.xlabel("Training set size", fontsize=14) # 책에는 없음
plt.ylabel("RMSE", fontsize=14) # 책에는 없음
lin_reg = LinearRegression()
plot_learning_curves(lin_reg, X, y)
plt.axis([0, 80, 0, 3]) # 책에는 없음
save_fig("underfitting_learning_curves_plot") # 책에는 없음
plt.show() # 책에는 없음
from sklearn.pipeline import Pipeline
polynomial_regression = Pipeline([
("poly_features", PolynomialFeatures(degree=10, include_bias=False)),
("lin_reg", LinearRegression()),
])
plot_learning_curves(polynomial_regression, X, y)
plt.axis([0, 80, 0, 3]) # 책에는 없음
save_fig("learning_curves_plot") # 책에는 없음
plt.show() # 책에는 없음 | 그림 저장: learning_curves_plot
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
규제가 있는 선형 모델 릿지 회귀 | np.random.seed(42)
m = 20
X = 3 * np.random.rand(m, 1)
y = 1 + 0.5 * X + np.random.randn(m, 1) / 1.5
X_new = np.linspace(0, 3, 100).reshape(100, 1) | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
**식 4-8: 릿지 회귀의 비용 함수**$J(\boldsymbol{\theta}) = \text{MSE}(\boldsymbol{\theta}) + \alpha \dfrac{1}{2}\sum\limits_{i=1}^{n}{\theta_i}^2$ | from sklearn.linear_model import Ridge
ridge_reg = Ridge(alpha=1, solver="cholesky", random_state=42)
ridge_reg.fit(X, y)
ridge_reg.predict([[1.5]])
ridge_reg = Ridge(alpha=1, solver="sag", random_state=42)
ridge_reg.fit(X, y)
ridge_reg.predict([[1.5]])
from sklearn.linear_model import Ridge
def plot_model(model_class, polynomial, alphas, **model_kargs):
for alpha, style in zip(alphas, ("b-", "g--", "r:")):
model = model_class(alpha, **model_kargs) if alpha > 0 else LinearRegression()
if polynomial:
model = Pipeline([
("poly_features", PolynomialFeatures(degree=10, include_bias=False)),
("std_scaler", StandardScaler()),
("regul_reg", model),
])
model.fit(X, y)
y_new_regul = model.predict(X_new)
lw = 2 if alpha > 0 else 1
plt.plot(X_new, y_new_regul, style, linewidth=lw, label=r"$\alpha = {}$".format(alpha))
plt.plot(X, y, "b.", linewidth=3)
plt.legend(loc="upper left", fontsize=15)
plt.xlabel("$x_1$", fontsize=18)
plt.axis([0, 3, 0, 4])
plt.figure(figsize=(8,4))
plt.subplot(121)
plot_model(Ridge, polynomial=False, alphas=(0, 10, 100), random_state=42)
plt.ylabel("$y$", rotation=0, fontsize=18)
plt.subplot(122)
plot_model(Ridge, polynomial=True, alphas=(0, 10**-5, 1), random_state=42)
save_fig("ridge_regression_plot")
plt.show() | 그림 저장: ridge_regression_plot
| Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
**노트**: 향후 버전이 바뀌더라도 동일한 결과를 만들기 위해 사이킷런 0.21 버전의 기본값인 `max_iter=1000`과 `tol=1e-3`으로 지정합니다. | sgd_reg = SGDRegressor(penalty="l2", max_iter=1000, tol=1e-3, random_state=42)
sgd_reg.fit(X, y.ravel())
sgd_reg.predict([[1.5]]) | _____no_output_____ | Apache-2.0 | 04_training_linear_models.ipynb | probationer070/handson-ml2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.