markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Synthetic Dataset Generation
Let us generate an unobserved parameter and an indicator of treatment such that they are highly correlated. | unobserved = np.hstack((np.ones(10000), np.zeros(10000)))
treatment = np.hstack((np.ones(9000), np.zeros(10000), np.ones(1000)))
np.corrcoef(unobserved, treatment) | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
Now create historical dataset that is used for learning predictive model. | def synthesize_dataset(unobserved, treatment,
given_exogenous=None, n_exogenous_to_draw=2,
weights_matrix=np.array([[5, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 2, 1],
... | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
Now create two datasets for simulation where the only difference between them is that in the first one treatment is absent and in the second one treatment is assigned to all items. | unobserved = np.hstack((np.ones(2500), np.zeros(2500)))
no_treatment = np.zeros(5000)
full_treatment = np.ones(5000)
no_treatment_X, no_treatment_y = synthesize_dataset(unobserved, no_treatment)
full_treatment_X, full_treatment_y = synthesize_dataset(unobserved, full_treatment,
... | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
Look at the data that are used for simulation. | no_treatment_X[:5, :]
full_treatment_X[:5, :]
no_treatment_y[:5]
full_treatment_y[:5] | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
Good Model... | X_train, X_test, y_train, y_test = train_test_split(learning_X, learning_y,
random_state=361)
X_train.shape, X_test.shape, y_train.shape, y_test.shape
def tune_inform(X_train, y_train, rgr, grid_params, kf, scoring):
"""
Just a helper function that combines
... | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
Let us use coefficient of determination as a scorer rather than MSE. Actually, they are linearly dependent: $R^2 = 1 - \frac{MSE}{\mathrm{Var}(y)}$, but coefficient of determination is easier to interpret. | rgr = tune_inform(X_train, y_train, rgr, grid_params, kf, 'r2')
y_hat = rgr.predict(X_test)
r2_score(y_test, y_hat) | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
Although true relationship is non-linear, predictive power of linear regression is good. This is indicated by close to 1 coefficient of determination. Since the winner is model with intercept, its score can be interpreted as follows — the model explains almost all variance of the target around its mean (note that such ... | rgr = XGBRegressor()
grid_params = {'n_estimators': [50, 100, 200, 300],
'max_depth': [3, 5],
'subsample': [0.8, 1]}
kf = KFold(n_splits=5, shuffle=True, random_state=361)
rgr = tune_inform(X_train, y_train, rgr, grid_params, kf, 'r2') | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
It looks like almost all combinations of hyperparameters result in error that is close to irreducible error caused by mismatches between the indicator of treatment and the omitted variable. | y_hat = rgr.predict(X_test)
r2_score(y_test, y_hat) | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
The score is even closer to 1 than in case of linear model. Decent result deceptively motivates to think that all important variables are included in the model.
...and Poor Simulation | no_treatment_y_hat = rgr.predict(no_treatment_X)
r2_score(no_treatment_y, no_treatment_y_hat)
full_treatment_y_hat = rgr.predict(full_treatment_X)
r2_score(full_treatment_y, full_treatment_y_hat) | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
And now scores are not perfect, are they? | fig = plt.figure(figsize=(14, 7))
ax_one = fig.add_subplot(121)
ax_one.scatter(no_treatment_y_hat, no_treatment_y)
ax_one.set_title("Simulation of absence of treatment")
ax_one.set_xlabel("Predicted values")
ax_one.set_ylabel("True values")
ax_one.grid()
ax_two = fig.add_subplot(122, sharey=ax_one)
ax_two.scatter(ful... | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
It can be seen that effect of treatment is overestimated. In case of absence of treatment, for items with unobserved feature equal to 1, predictions are significantly less than true values. To be more precise, the differences are close to coefficient near unobserved feature in weights_matrix passed to the dataset creat... | estimated_effects = full_treatment_y_hat - no_treatment_y_hat
true_effects = full_treatment_y - no_treatment_y
np.min(estimated_effects) | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
The model recommends to treat all items. What happens if all of them are treated? | cost_of_one_treatment = 1
estimated_net_improvement = (np.sum(estimated_effects) -
cost_of_one_treatment * estimated_effects.shape[0])
estimated_net_improvement
true_net_improvement = (np.sum(true_effects) -
cost_of_one_treatment * true_effects.shape[0])
true_net_i... | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit |
Assignments
Modify the Ingredient and Recipe classes so that the following code works. | class Ingredient(object):
"""The ingredient object that contains nutritional information"""
def __init__(self, name, carbs, protein, fat):
self.name = name
self.carbs = carbs
self.protein = protein
self.fat = fat
def __repr__(self):
return 'Ingredie... | Wk05/Wk05-OOP-Public-interface.ipynb | briennakh/BIOF509 | mit |
Estimator
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https://www.tensorflow.org/guide/estimator"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a> </td>
<td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow... | !pip install -U tensorflow_datasets
import tempfile
import os
import tensorflow as tf
import tensorflow_datasets as tfds | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
メリット
tf.keras.Model と同様に、estimator はモデルレベルの抽象です。tf.estimator は、tf.keras 向けに現在開発段階にある以下の機能を提供しています。
パラメーターサーバーベースのトレーニング
TFX の完全統合
Estimator の機能
Estimator には以下のメリットがあります。
Estimator ベースのモデルは、モデルを変更することなくローカルホストまたは分散マルチサーバー環境で実行できます。さらに、モデルをコーディングし直すことなく、CPU、GPU、または TPU で実行できます。
Estimator では、次を実行する方法とタイミングを制御する安全な分散型トレ... | def train_input_fn():
titanic_file = tf.keras.utils.get_file("train.csv", "https://storage.googleapis.com/tf-datasets/titanic/train.csv")
titanic = tf.data.experimental.make_csv_dataset(
titanic_file, batch_size=32,
label_name="survived")
titanic_batches = (
titanic.cache().repeat().shuffle(500)... | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
input_fn は、tf.Graph で実行し、グラフテンソルを含む (features_dics, labels) ペアを直接返すこともできますが、定数を返すといった単純なケースではない場合に、エラーが発生しやすくなります。
2. 特徴量カラムを定義する
tf.feature_column は、特徴量名、その型、およびすべての入力前処理を特定します。
たとえば、次のスニペットは 3 つの特徴量カラムを作成します。
最初の特徴量カラムは、浮動小数点数の入力として直接 age 特徴量を使用します。
2 つ目の特徴量カラムは、カテゴリカル入力として class 特徴量を使用します。
3 つ目の特徴量カラムは、カテゴリカル入力として ... | age = tf.feature_column.numeric_column('age')
cls = tf.feature_column.categorical_column_with_vocabulary_list('class', ['First', 'Second', 'Third'])
embark = tf.feature_column.categorical_column_with_hash_bucket('embark_town', 32) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
3. 関連する事前作成済み Estimator をインスタンス化する
LinearClassifier という事前作成済み Estimator のインスタンス化の例を次に示します。 | model_dir = tempfile.mkdtemp()
model = tf.estimator.LinearClassifier(
model_dir=model_dir,
feature_columns=[embark, cls, age],
n_classes=2
) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
詳細については、線形分類器のチュートリアルをご覧ください。
4. トレーニング、評価、または推論メソッドを呼び出す
すべての Estimator には、train、evaluate、および predict メソッドがあります。 | model = model.train(input_fn=train_input_fn, steps=100)
result = model.evaluate(train_input_fn, steps=10)
for key, value in result.items():
print(key, ":", value)
for pred in model.predict(train_input_fn):
for key, value in pred.items():
print(key, ":", value)
break | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
事前作成済み Estimator のメリット
事前作成済み Estimator は、次のようなベストプラクティスをエンコードするため、さまざまなメリットがあります。
さまざまな部分の計算グラフをどこで実行するかを決定し、単一のマシンまたはクラスタに戦略を実装するためのベストプラクティス。
イベント(要約)の書き込みと普遍的に役立つ要約のベストプラクティス。
事前作成済み Estimator を使用しない場合は、上記の特徴量を独自に実装する必要があります。
カスタム Estimator
事前作成済みかカスタムかに関係なく、すべての Estimator の中核は、モデル関数の model_fn にあります。これは、トレーニング、評価... | keras_mobilenet_v2 = tf.keras.applications.MobileNetV2(
input_shape=(160, 160, 3), include_top=False)
keras_mobilenet_v2.trainable = False
estimator_model = tf.keras.Sequential([
keras_mobilenet_v2,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(1)
])
# Compile the model
estimator_mod... | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
コンパイルされた Keras モデルから Estimator を作成します。Keras モデルの初期化状態が、作成した Estimator に維持されます。 | est_mobilenet_v2 = tf.keras.estimator.model_to_estimator(keras_model=estimator_model) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
派生した Estimator をほかの Estimator と同じように扱います。 | IMG_SIZE = 160 # All images will be resized to 160x160
def preprocess(image, label):
image = tf.cast(image, tf.float32)
image = (image/127.5) - 1
image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))
return image, label
def train_input_fn(batch_size):
data = tfds.load('cats_vs_dogs', as_supervised=True)
t... | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
トレーニングするには、Estimator の train 関数を呼び出します。 | est_mobilenet_v2.train(input_fn=lambda: train_input_fn(32), steps=50) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
同様に、評価するには、Estimator の evaluate 関数を呼び出します。 | est_mobilenet_v2.evaluate(input_fn=lambda: train_input_fn(32), steps=10) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
詳細については、tf.keras.estimator.model_to_estimator のドキュメントを参照してください。
Estimator でオブジェクトベースのチェックポイントを保存する
Estimator はデフォルトで、チェックポイントガイドで説明したオブジェクトグラフではなく、変数名でチェックポイントを保存します。tf.train.Checkpoint は名前ベースのチェックポイントを読み取りますが、モデルの一部を Estimator の model_fn の外側に移動すると変数名が変わることがあります。上位互換性においては、オブジェクトベースのチェックポイントを保存すると、Estimator の内側でモデルをトレー... | import tensorflow.compat.v1 as tf_compat
def toy_dataset():
inputs = tf.range(10.)[:, None]
labels = inputs * 5. + tf.range(5.)[None, :]
return tf.data.Dataset.from_tensor_slices(
dict(x=inputs, y=labels)).repeat().batch(2)
class Net(tf.keras.Model):
"""A simple linear model."""
def __init__(self):
... | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
その後、tf.train.Checkpoint は Estimator のチェックポイントをその model_dir から読み込むことができます。 | opt = tf.keras.optimizers.Adam(0.1)
net = Net()
ckpt = tf.train.Checkpoint(
step=tf.Variable(1, dtype=tf.int64), optimizer=opt, net=net)
ckpt.restore(tf.train.latest_checkpoint('./tf_estimator_example/'))
ckpt.step.numpy() # From est.train(..., steps=10) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
Estimator の SavedModel
Estimator は、tf.Estimator.export_saved_model によって SavedModel をエクスポートします。 | input_column = tf.feature_column.numeric_column("x")
estimator = tf.estimator.LinearClassifier(feature_columns=[input_column])
def input_fn():
return tf.data.Dataset.from_tensor_slices(
({"x": [1., 2., 3., 4.]}, [1, 1, 0, 0])).repeat(200).shuffle(64).batch(16)
estimator.train(input_fn) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
Estimator を保存するには、serving_input_receiver を作成する必要があります。この関数は、SavedModel が受け取る生データを解析する tf.Graph の一部を構築します。
tf.estimator.export モジュールには、これらの receivers を構築するための関数が含まれています。
次のコードは、feature_columns に基づき、tf-serving と合わせて使用されることの多いシリアル化された tf.Example プロトコルバッファを受け入れるレシーバーを構築します。 | tmpdir = tempfile.mkdtemp()
serving_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(
tf.feature_column.make_parse_example_spec([input_column]))
estimator_base_path = os.path.join(tmpdir, 'from_estimator')
estimator_path = estimator.export_saved_model(estimator_base_path, serving_input_fn) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
また、Python からモデルを読み込んで実行することも可能です。 | imported = tf.saved_model.load(estimator_path)
def predict(x):
example = tf.train.Example()
example.features.feature["x"].float_list.value.extend([x])
return imported.signatures["predict"](
examples=tf.constant([example.SerializeToString()]))
print(predict(1.5))
print(predict(3.5)) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
tf.estimator.export.build_raw_serving_input_receiver_fn を使用すると、tf.train.Example の代わりに生のテンソルを取る入力関数を作成することができます。
Estimator を使った tf.distribute.Strategy の使用(制限サポート)
tf.estimator は、もともと非同期パラメーターサーバー手法をサポートしていた分散型トレーニング TensorFlow API です。tf.estimator は現在では tf.distribute.Strategy をサポートするようになっています。tf.estimator を使用している場合は、コードを... | mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
ここでは、事前に作成された Estimator が使用されていますが、同じコードはカスタム Estimator でも動作します。train_distribute はトレーニングの分散方法を判定し、eval_distribute は評価の分散方法を判定します。この点も、トレーニングと評価に同じストラテジーを使用する Keras と異なるところです。
入力関数を使用して、この Estimator をトレーニングし、評価することができます。 | def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 |
Brainstorm Elekta phantom dataset tutorial
Here we compute the evoked from raw for the Brainstorm Elekta phantom
tutorial dataset. For comparison, see [1]_ and:
http://neuroimage.usc.edu/brainstorm/Tutorials/PhantomElekta
References
.. [1] Tadel F, Baillet S, Mosher JC, Pantazis D, Leahy RM.
Brainstorm: A User-... | # Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import find_events, fit_dipole
from mne.datasets.brainstorm import bst_phantom_elekta
from mne.io import read_raw_fif
from mayavi import mlab
print(... | 0.16/_downloads/plot_brainstorm_phantom_elekta.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
$f_{1}(c,p) = \dfrac{1}{2}r_{c}c^{2}+\dfrac{1}{4}u_{c}c^{4}+\dfrac{1}{6}v_{c}c^{6}+\dfrac{1}{2}r_{p}p^{2}-\gamma cp-Ep$ | f1 = (1/2)*r_c*c**2+(1/4)*u_c*c**4+(1/6)*v_c*c**6-E*p+(1/2)*r_p*p**2-gamma*c*p | Smectic/SimplePol.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
$\dfrac{\partial f_{1}(c,p)}{\partial p} = 0 = $ | pmin = solve(f1.diff(c),p)[0]
pmin
E_cp = solve(f1.diff(p),E)[0]
E_cp
expand(E_cp.subs(p,pmin)) | Smectic/SimplePol.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
Simulate example data | # network model
tree = toytree.rtree.unittree(7, treeheight=3e6, seed=123)
tree.draw(ts='o', admixture_edges=(3, 2));
# simulation model with admixture and missing data
model = ipcoal.Model(tree, Ne=1e4, nsamples=4, admixture_edges=(3, 2, 0.5, 0.1))
model.sim_snps(250)
model.write_snps_to_hdf5(name="test-construct", o... | newdocs/API-analysis/cookbook-construct-ipcoal.ipynb | dereneaton/ipyrad | gpl-3.0 |
Input data file | # the path to your HDF5 formatted snps file
SNPS = "/tmp/test-construct.snps.hdf5" | newdocs/API-analysis/cookbook-construct-ipcoal.ipynb | dereneaton/ipyrad | gpl-3.0 |
Filter missing data and convert to genotype frequencies | # apply filtering to the SNPs file
tool = ipa.snps_extracter(data=SNPS, imap=IMAP, minmap={i:2 for i in IMAP})
tool.parse_genos_from_hdf5();
# convert SNP data to genotype frequencies
df = tool.get_population_geno_frequency()
df.head() | newdocs/API-analysis/cookbook-construct-ipcoal.ipynb | dereneaton/ipyrad | gpl-3.0 |
Write data to file | # write to a file
df.to_csv("/tmp/freqs.csv") | newdocs/API-analysis/cookbook-construct-ipcoal.ipynb | dereneaton/ipyrad | gpl-3.0 |
Generate a dataset to be fitted | np.random.seed(42)
y = np.random.random(10000)
x = 1./np.sqrt(y)
plt.hist(x, bins=100, range=(1,10), histtype='stepfilled',color='blue')
plt.yscale('log') | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
Maximum likelihood fit of a simple power law
First define the negative-log likelihood function for a density proportional to x**(-a) the range 1 < x < infinity | def nllp(a)
# here define the function
return 1. | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
Then minimize it using iminuit | import iminuit
# minp = iminuit.Minuit(nllp,a= ?,error_a=?, errordef=?)
# minp.migrad() | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
Error analysis
First determine the parabolic errors using hesse() and then do a parameter scan using minos() to determine the 68% confidence level errors. | # minp.hesse()
# minp.minos()
# minp.draw_profile('a') | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
Use of an un-normalised PDF
The above example shall be modified such that the normalisation of the likelihood function, which so far was determined analytically, now is determined numerically in the fit. This is the more realistic case, since in many case no (simple) analytical normalisation exists. As a first step, th... | from scipy.integrate import quad
def pdfpn(x, a):
return x**(-a)
def pdfpn_norm(a):
# here insert the calculation of the normalisation as a function of a
return 1.
def nllpn(a):
# calculate and return the proper negative-log likelihood function
return 1. | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
Then do the same minimization steps as before. | # minpn = iminuit.Minuit(nllpn, a=?, error_a=?, errordef=?)
# minpn.migrad() | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
Extend the fit model by an exponential cutoff
The exponential cutoff is implemented by exp(-bbx), i.e. exponential growth is not allowed for real valued parameters b. The implications of this ansatz shall be discussed when looking at the solution. After that, the example can be modified to use exp(-b*x).
Here the like... | def pdfcn(x, a, b):
return x**(-a)*np.exp(-b*b*x)
def pdfcn_norm(a, b):
# determine the normalization
return 1.
def nllcn(a, b):
# calculate an return the negative-log likelihood function
return 1. | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
As before, use Minuit for minimisation and error analysis, but now in two dimensions. Study parabolic errors and minos errors, the latter both for the single variables and for both together. | # mincn = iminuit.Minuit(nllcn, a=?, b=?, error_a=?, error_b=?, errordef=?)
# mincn.migrad()
# mincn.hesse()
# mincn.minos()
# mincn.draw_profile('a')
# mincn.draw_profile('b')
# mincn.draw_contour('a','b') | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
emcee requires as input the log-likelihood of the posterior in the parameters a and b. In the following it is composed of the log-of the prior and the log-likelihood of the data. Initially use a simple uniform prior in a and b with the constraint b>0. Afterwards one can play with the prior to see how strongly it affect... | # Define the posterior.
# for clarity the prior and likelihood are separated
# emcee requires log-posterior
def log_prior(theta):
a, b = theta
if b < 0:
return -np.inf # log(0)
else:
return 0.
def log_likelihood(theta, x):
a, b = theta
return np.sum(-a*np.log(x) - b*b*x)
def log... | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
run the MCMC (and time it using IPython's %time magic | #sampler = emcee.EnsembleSampler(nwalkers, ndim, log_posterior, args=[x])
#%time sampler.run_mcmc(starting_guesses, nsteps)
#print("done") | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
sampler.chain is of shape (nwalkers, nsteps, ndim). Before analysis throw-out the burn-in points and reshape. | #emcee_trace = sampler.chain[:, nburn:, :].reshape(-1, ndim).T
#len(emcee_trace[0]) | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
Analyse the results. Plot the projected (marginalized) posteriors for the parameters a and b and also the joinyt density as sampled by the MCMC. | # plt.hist(emcee_trace[0], 100, range=(?,?) , histtype='stepfilled', color='cyan')
# plt.hist(emcee_trace[1], 100, range=(?,?) , histtype='stepfilled', color='cyan')
# plt.plot(emcee_trace[0],emcee_trace[1],',k') | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
As a final step, generate 2-dim bayesian confidence level contours containing 68.3% and 95.5% probability content. For that define a convenient plot functions and use them. Overlay the contours with the scatter plot. | def compute_sigma_level(trace1, trace2, nbins=20):
"""From a set of traces, bin by number of standard deviations"""
L, xbins, ybins = np.histogram2d(trace1, trace2, nbins)
L[L == 0] = 1E-16
logL = np.log(L)
shape = L.shape
L = L.ravel()
# obtain the indices to sort and unsort the flattened... | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause |
欢迎来到线性回归项目
若项目中的题目有困难没完成也没关系,我们鼓励你带着问题提交项目,评审人会给予你诸多帮助。
所有选做题都可以不做,不影响项目通过。如果你做了,那么项目评审会帮你批改,也会因为选做部分做错而判定为不通过。
其中非代码题可以提交手写后扫描的 pdf 文件,或使用 Latex 在文档中直接回答。
1 矩阵运算
1.1 创建一个 4*4 的单位矩阵 | # 这个项目设计来帮你熟悉 python list 和线性代数
# 你不能调用任何NumPy以及相关的科学计算库来完成作业
# 本项目要求矩阵统一使用二维列表表示,如下:
A = [[1,2,3],
[2,3,3],
[1,2,5]]
B = [[1,2,3,5],
[2,3,3,5],
[1,2,5,1]]
# 向量也用二维列表表示
C = [[1],
[2],
[3]]
#TODO 创建一个 4*4 单位矩阵
I = [[1,0,0,0],
[0,1,0,0],
[0,0,1,0],
[0,0,0,1]] | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
1.2 返回矩阵的行数和列数 | # 运行以下代码测试你的 shape 函数
%run -i -e test.py LinearRegressionTestCase.test_shape
# TODO 返回矩阵的行数和列数
def shape(M):
return len(M),len(M[0]) | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
1.3 每个元素四舍五入到特定小数数位 | # TODO 每个元素四舍五入到特定小数数位
# 直接修改参数矩阵,无返回值
def matxRound(M, decPts=4):
row, col = shape(M)
for i in range(row):
for j in range(col):
M[i][j]=round(M[i][j],decPts)
pass
# 运行以下代码测试你的 matxRound 函数
%run -i -e test.py LinearRegressionTestCase.test_matxRound | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
1.4 计算矩阵的转置 | # TODO 计算矩阵的转置
def transpose(M):
row, col = shape(M)
MT = []
for i in range(col):
MT.append([x[i] for x in M])
return MT
# 运行以下代码测试你的 transpose 函数
%run -i -e test.py LinearRegressionTestCase.test_transpose | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
1.5 计算矩阵乘法 AB | # TODO 计算矩阵乘法 AB,如果无法相乘则raise ValueError
def matxMultiply(A, B):
rowA, colA = shape(A)
rowB, colB = shape(B)
if not colA == rowB:
raise ValueError
# result would be rowA x colB
result = [[0] * colB for row in range(rowA)]
BT = transpose(B)
for i in range(rowA):
rowa = A[i]
... | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
2 Gaussign Jordan 消元法
2.1 构造增广矩阵
$ A = \begin{bmatrix}
a_{11} & a_{12} & ... & a_{1n}\
a_{21} & a_{22} & ... & a_{2n}\
a_{31} & a_{22} & ... & a_{3n}\
... & ... & ... & ...\
a_{n1} & a_{n2} & ... & a_{nn}\
\end{bmatrix} , b = \begin{bmatrix}
b_{1} \
b_{2} \
b_{3} \
... | # TODO 构造增广矩阵,假设A,b行数相同
def augmentMatrix(A, b):
# result would be rowA x (colA+colb)
rowA, colA = shape(A)
result = [[0] * (colA+1) for row in range(rowA)]
for i in range(rowA):
for j in range(colA):
result[i][j] = A[i][j]
result[i][colA] = b[i][0]
return result
# 运行以下代... | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
2.2 初等行变换
交换两行
把某行乘以一个非零常数
把某行加上另一行的若干倍: | # TODO r1 <---> r2
# 直接修改参数矩阵,无返回值
def swapRows(M, r1, r2):
colM = shape(M)[1]
for i in range(colM):
tmp = M[r1][i]
M[r1][i] = M[r2][i]
M[r2][i] = tmp
pass
# 运行以下代码测试你的 swapRows 函数
%run -i -e test.py LinearRegressionTestCase.test_swapRows
# TODO r1 <--- r1 * scale
# scale为0是非法输入,要求... | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
2.3 Gaussian Jordan 消元法求解 Ax = b
2.3.1 算法
步骤1 检查A,b是否行数相同
步骤2 构造增广矩阵Ab
步骤3 逐列转换Ab为化简行阶梯形矩阵 中文维基链接
对于Ab的每一列(最后一列除外)
当前列为列c
寻找列c中 对角线以及对角线以下所有元素(行 c~N)的绝对值的最大值
如果绝对值最大值为0
那么A为奇异矩阵,返回None (你可以在选做问题2.4中证明为什么这里A一定是奇异矩阵)
否则
使用第一个行变换,将绝对值最大值所在行交换到对角线元素所在行(行c)
使用第二个行变换,将列c的对角线元素缩放为1
... | # 不要修改这里!
from helper import *
A = generateMatrix(3,seed,singular=False)
b = np.ones(shape=(3,1),dtype=int) # it doesn't matter
Ab = augmentMatrix(A.tolist(),b.tolist()) # 请确保你的增广矩阵已经写好了
printInMatrixFormat(Ab,padding=3,truncating=0) | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
请按照算法的步骤3,逐步推演可逆矩阵的变换。
在下面列出每一次循环体执行之后的增广矩阵。
要求:
1. 做分数运算
2. 使用\frac{n}{m}来渲染分数,如下:
- $\frac{n}{m}$
- $-\frac{a}{b}$
$ Ab = \begin{bmatrix}
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \end{bmatrix}$
$ --> \begin{bmatrix}
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \end{bmatrix}$
$ --> \beg... | # 不要修改这里!
A = generateMatrix(3,seed,singular=True)
b = np.ones(shape=(3,1),dtype=int)
Ab = augmentMatrix(A.tolist(),b.tolist()) # 请确保你的增广矩阵已经写好了
printInMatrixFormat(Ab,padding=3,truncating=0) | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
请按照算法的步骤3,逐步推演奇异矩阵的变换。
在下面列出每一次循环体执行之后的增广矩阵。
要求:
1. 做分数运算
2. 使用\frac{n}{m}来渲染分数,如下:
- $\frac{n}{m}$
- $-\frac{a}{b}$
$ Ab = \begin{bmatrix}
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \end{bmatrix}$
$ --> \begin{bmatrix}
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \end{bmatrix}$
$ --> \beg... | # TODO 实现 Gaussain Jordan 方法求解 Ax = b
""" Gaussian Jordan 方法求解 Ax = b.
参数
A: 方阵
b: 列向量
decPts: 四舍五入位数,默认为4
epsilon: 判读是否为0的阈值,默认 1.0e-16
返回列向量 x 使得 Ax = b
返回None,如果 A,b 高度不同
返回None,如果 A 为奇异矩阵
"""
from fractions import Fraction
def gj_Solve(A, b, decPts=4, epsi... | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
(选做) 2.4 算法正确判断了奇异矩阵:
在算法的步骤3 中,如果发现某一列对角线和对角线以下所有元素都为0,那么则断定这个矩阵为奇异矩阵。
我们用正式的语言描述这个命题,并证明为真。
证明下面的命题:
如果方阵 A 可以被分为4个部分:
$ A = \begin{bmatrix}
I & X \
Z & Y \
\end{bmatrix} , \text{其中 I 为单位矩阵,Z 为全0矩阵,Y 的第一列全0}$,
那么A为奇异矩阵。
提示:从多种角度都可以完成证明
- 考虑矩阵 Y 和 矩阵 A 的秩
- 考虑矩阵 Y 和 矩阵 A 的行列式
- 考虑矩阵 A 的某一列是其他列的线性组合
TOD... | # 不要修改这里!
# 运行一次就够了!
from helper import *
from matplotlib import pyplot as plt
%matplotlib inline
X,Y = generatePoints(seed,num=100)
## 可视化
plt.xlim((-5,5))
plt.xlabel('x',fontsize=18)
plt.ylabel('y',fontsize=18)
plt.scatter(X,Y,c='b')
plt.show() | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
3.2 拟合一条直线
3.2.1 猜测一条直线 | #TODO 请选择最适合的直线 y = mx + b
m1 = 3.2
b1 = 7.2
# 不要修改这里!
plt.xlim((-5,5))
x_vals = plt.axes().get_xlim()
y_vals = [m1*x+b1 for x in x_vals]
plt.plot(x_vals, y_vals, '-', color='r')
plt.xlabel('x',fontsize=18)
plt.ylabel('y',fontsize=18)
plt.scatter(X,Y,c='b')
plt.show() | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
3.2.2 计算平均平方误差 (MSE)
我们要编程计算所选直线的平均平方误差(MSE), 即数据集中每个点到直线的Y方向距离的平方的平均数,表达式如下:
$$
MSE = \frac{1}{n}\sum_{i=1}^{n}{(y_i - mx_i - b)^2}
$$ | # TODO 实现以下函数并输出所选直线的MSE
def calculateMSE(X,Y,m,b):
list_ = ([(val[1]-val[0]*m-b)**2 for val in zip(X,Y)])
return sum(list_)/len(list_)
print(calculateMSE(X,Y,m1,b1)) | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
3.2.3 调整参数 $m, b$ 来获得最小的平方平均误差
你可以调整3.2.1中的参数 $m1,b1$ 让蓝点均匀覆盖在红线周围,然后微调 $m1, b1$ 让MSE最小。
3.3 (选做) 找到参数 $m, b$ 使得平方平均误差最小
这一部分需要简单的微积分知识( $ (x^2)' = 2x $ )。因为这是一个线性代数项目,所以设为选做。
刚刚我们手动调节参数,尝试找到最小的平方平均误差。下面我们要精确得求解 $m, b$ 使得平方平均误差最小。
定义目标函数 $E$ 为
$$
E = \frac{1}{2}\sum_{i=1}^{n}{(y_i - mx_i - b)^2}
$$
因为 $E = \frac{n}{2}... | # TODO 实现线性回归
'''
参数:X, Y 存储着一一对应的横坐标与纵坐标的两个一维数组
返回:m,b 浮点数
'''
def linearRegression(X,Y):
MX = [[val,1] for val in X]
MXT = transpose(MX)
result_left = matxMultiply(MXT,MX)
MY = [[val] for val in Y]
result_right = matxMultiply(MXT,MY)
[[m],[b]]=gj_Solve(result_left,result_right)
return (m,b... | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
你求得的回归结果是什么?
请使用运行以下代码将它画出来。 | # 请不要修改下面的代码
x1,x2 = -5,5
y1,y2 = x1*m2+b2, x2*m2+b2
plt.xlim((-5,5))
plt.xlabel('x',fontsize=18)
plt.ylabel('y',fontsize=18)
plt.scatter(X,Y,c='b')
plt.plot((x1,x2),(y1,y2),'r')
plt.title('y = {m:.4f}x + {b:.4f}'.format(m=m2,b=b2))
plt.show() | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
你求得的回归结果对当前数据集的MSE是多少? | print(calculateMSE(X,Y,m2,b2)) | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit |
First, we'll download and parse a BEL document from the Human Brain Pharmacome project describing the 2018 paper from Boland et al., "Promoting the clearance of neurotoxic proteins in neurodegenerative disorders of ageing". | url = 'https://raw.githubusercontent.com/pharmacome/conib/master/hbp_knowledge/tau/boland2018.bel' | notebooks/Compiling a BEL Document.ipynb | pybel/pybel | mit |
A BEL document can be downloaded and parsed from a URL using pybel.from_bel_script_url. Keep in mind, the first time we load a given BEL document, various BEL resources that are referenced in the document must be cached. Be patient - this can take up to ten minutes. | boland_2018_graph = pybel.from_bel_script_url(url, manager=manager)
pybel.to_database(boland_2018_graph, manager=manager) | notebooks/Compiling a BEL Document.ipynb | pybel/pybel | mit |
The graph is loaded into an instance of the pybel.BELGraph class. We can use the pybel.BELGraph.summarize() to print a brief summary of the graph. | boland_2018_graph.summarize() | notebooks/Compiling a BEL Document.ipynb | pybel/pybel | mit |
Next, we'll open and parse a BEL document from the Human Brain Pharmacome project describing the 2018 paper from Cabellero et al., "Interplay of pathogenic forms of human tau with different autophagic pathways". This example uses urlretrieve() to download the file locally to demonstrate how to load from a local file pa... | url = 'https://raw.githubusercontent.com/pharmacome/conib/master/hbp_knowledge/tau/caballero2018.bel'
path = os.path.join(DESKTOP_PATH, 'caballero2018.bel')
if not os.path.exists(path):
urlretrieve(url, path) | notebooks/Compiling a BEL Document.ipynb | pybel/pybel | mit |
A BEL document can also be parsed from a path to a file using pybel.from_bel_script. Like before, we will summarize the graph after parsing it. | cabellero_2018_graph = pybel.from_bel_script(path, manager=manager)
cabellero_2018_graph.summarize()
pybel.to_database(cabellero_2018_graph, manager=manager) | notebooks/Compiling a BEL Document.ipynb | pybel/pybel | mit |
We can combine two or more graphs in a list using pybel.union. | combined_graph = pybel.union([boland_2018_graph, cabellero_2018_graph])
combined_graph.summarize() | notebooks/Compiling a BEL Document.ipynb | pybel/pybel | mit |
Different Ways to Block Using Blackbox Based Blocker
There are three different ways to do overlap blocking:
Block two tables to produce a candidate set of tuple pairs.
Block a candidate set of tuple pairs to typically produce a reduced candidate set of tuple pairs.
Block two tuples to check if a tuple pair would get b... | def address_address_function(x, y):
# x, y will be of type pandas series
# get name attribute
x_address = x['address']
y_address = y['address']
# get the city
x_split, y_split = x_address.split(','), y_address.split(',')
x_city = x_split[len(x_split) - 1]
y_city = y_split[len(y_spli... | notebooks/guides/step_wise_em_guides/Performing Blocking Using Blackbox Blocker.ipynb | anhaidgroup/py_entitymatching | bsd-3-clause |
Block Candidate Set
First, define a blackbox function | def name_name_function(x, y):
# x, y will be of type pandas series
# get name attribute
x_name = x['name']
y_name = y['name']
# get last names
x_name = x_name.split(' ')[1]
y_name = y_name.split(' ')[1]
# check if last names match
if x_name != y_name:
return True
els... | notebooks/guides/step_wise_em_guides/Performing Blocking Using Blackbox Blocker.ipynb | anhaidgroup/py_entitymatching | bsd-3-clause |
Block Two tuples To Check If a Tuple Pair Would Get Blocked
First, define the black box function first | def address_address_function(x, y):
# x, y will be of type pandas series
# get name attribute
x_address = x['address']
y_address = y['address']
# get the city
x_split, y_split = x_address.split(','), y_address.split(',')
x_city = x_split[len(x_split) - 1]
y_city = y_split[len(y_spli... | notebooks/guides/step_wise_em_guides/Performing Blocking Using Blackbox Blocker.ipynb | anhaidgroup/py_entitymatching | bsd-3-clause |
式(2.5)の実装
n+1個の点列を入力し、逆行列を解いて、補間多項式を求め、n次補間多項式の係数行列[a_0, a_1, ..., a_n]を返す
INPUT
points: n+1個の点列[[x_0, f_0], [x_1, f_1], ..., [x_n, f_n]]
OUTPUT
n次補間多項式の係数行列[a_0, a_1, ..., a_n]を返す | def lagrange(points):
# 次元数
dim = len(points) - 1
# matrix Xをもとめる(ヴァンデルモンドの行列式)
x_matrix = np.array([[pow(point[0], j) for j in range(dim + 1)] for point in points])
# matrix Fをもとめる
f_matrix = np.array([point[1] for point in points])
# 線形方程式 X * A = F を解く
a_matrix = np.linalg.solv... | chapter2/Chapter2.ipynb | myuuuuun/NumericalCalculation | mit |
式(2.7)の実装
補間多項式を変形した式から、逆行列の計算をすることなく、ラグランジュの補間多項式を求める
ただし、今回は補間多項式の係数行列を返すのではなく、具体的なxの値のリストに対して、補間値のリストを生成して返す
INPUT
points: 与えられた点列を入力
x_list: 補間値を求めたいxのリストを入力
OUTPUT
f_list: x_listの各要素に対する補間値のリスト | def lagrange2(points, x_list=np.arange(-5, 5, 0.1)):
dim = len(points) - 1
f_list = []
for x in x_list:
L = 0
for i in range(dim + 1):
Li = 1
for j in range(dim + 1):
if j != i:
Li *= (x - points[j][0]) / (points[i][0] - points[j][... | chapter2/Chapter2.ipynb | myuuuuun/NumericalCalculation | mit |
Motivating KDE: Histograms
As already discussed, a density estimator is an algorithm which seeks to model the probability distribution that generated a dataset.
For one dimensional data, you are probably already familiar with one simple density estimator: the histogram.
A histogram divides the data into discrete bins, ... | def make_data(N, f=0.3, rseed=1):
rand = np.random.RandomState(rseed)
x = rand.randn(N)
x[int(f * N):] += 5
return x
x = make_data(1000) | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
We have previously seen that the standard count-based histogram can be created with the plt.hist() function.
By specifying the normed parameter of the histogram, we end up with a normalized histogram where the height of the bins does not reflect counts, but instead reflects probability density: | hist = plt.hist(x, bins=30, density=True) | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
Notice that for equal binning, this normalization simply changes the scale on the y-axis, leaving the relative heights essentially the same as in a histogram built from counts.
This normalization is chosen so that the total area under the histogram is equal to 1, as we can confirm by looking at the output of the histog... | density, bins, patches = hist
widths = bins[1:] - bins[:-1]
(density * widths).sum() | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
One of the issues with using a histogram as a density estimator is that the choice of bin size and location can lead to representations that have qualitatively different features.
For example, if we look at a version of this data with only 20 points, the choice of how to draw the bins can lead to an entirely different ... | x = make_data(20)
bins = np.linspace(-5, 10, 10)
fig, ax = plt.subplots(1, 2, figsize=(12, 4),
sharex=True, sharey=True,
subplot_kw={'xlim':(-4, 9),
'ylim':(-0.02, 0.3)})
fig.subplots_adjust(wspace=0.05)
for i, offset in enumerate([0.0, 0... | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
On the left, the histogram makes clear that this is a bimodal distribution.
On the right, we see a unimodal distribution with a long tail.
Without seeing the preceding code, you would probably not guess that these two histograms were built from the same data: with that in mind, how can you trust the intuition that hist... | fig, ax = plt.subplots()
bins = np.arange(-3, 8)
ax.plot(x, np.full_like(x, -0.1), '|k',
markeredgewidth=1)
for count, edge in zip(*np.histogram(x, bins)):
for i in range(count):
ax.add_patch(plt.Rectangle((edge, i), 1, 1,
alpha=0.5))
ax.set_xlim(-4, 8)
ax.set_ylim... | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
The problem with our two binnings stems from the fact that the height of the block stack often reflects not on the actual density of points nearby, but on coincidences of how the bins align with the data points.
This mis-alignment between points and their blocks is a potential cause of the poor histogram results seen h... | x_d = np.linspace(-4, 8, 2000)
density = sum((abs(xi - x_d) < 0.5) for xi in x)
plt.fill_between(x_d, density, alpha=0.5)
plt.plot(x, np.full_like(x, -0.1), '|k', markeredgewidth=1)
plt.axis([-4, 8, -0.2, 8]); | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
The result looks a bit messy, but is a much more robust reflection of the actual data characteristics than is the standard histogram.
Still, the rough edges are not aesthetically pleasing, nor are they reflective of any true properties of the data.
In order to smooth them out, we might decide to replace the blocks at e... | from scipy.stats import norm
x_d = np.linspace(-4, 8, 1000)
density = sum(norm(xi).pdf(x_d) for xi in x)
plt.fill_between(x_d, density, alpha=0.5)
plt.plot(x, np.full_like(x, -0.1), '|k', markeredgewidth=1)
plt.axis([-4, 8, -0.2, 5]); | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
This smoothed-out plot, with a Gaussian distribution contributed at the location of each input point, gives a much more accurate idea of the shape of the data distribution, and one which has much less variance (i.e., changes much less in response to differences in sampling).
These last two plots are examples of kernel ... | from sklearn.neighbors import KernelDensity
# instantiate and fit the KDE model
kde = KernelDensity(bandwidth=1.0, kernel='gaussian')
kde.fit(x[:, None])
# score_samples returns the log of the probability density
logprob = kde.score_samples(x_d[:, None])
plt.fill_between(x_d, np.exp(logprob), alpha=0.5)
plt.plot(x, ... | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
The result here is normalized such that the area under the curve is equal to 1.
Selecting the bandwidth via cross-validation
The choice of bandwidth within KDE is extremely important to finding a suitable density estimate, and is the knob that controls the bias–variance trade-off in the estimate of density: too narrow ... | from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import LeaveOneOut
bandwidths = 10 ** np.linspace(-1, 1, 100)
grid = GridSearchCV(KernelDensity(kernel='gaussian'),
{'bandwidth': bandwidths},
cv=LeaveOneOut())
grid.fit(x[:, None]); | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
Now we can find the choice of bandwidth which maximizes the score (which in this case defaults to the log-likelihood): | grid.best_params_ | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
The optimal bandwidth happens to be very close to what we used in the example plot earlier, where the bandwidth was 1.0 (i.e., the default width of scipy.stats.norm).
Example: KDE on a Sphere
Perhaps the most common use of KDE is in graphically representing distributions of points.
For example, in the Seaborn visualiza... | from sklearn.datasets import fetch_species_distributions
# this step might fail based on permssions and network access
# if in Docker, specify --network=host
# if in docker-compose specify version 3.4 and build -> network: host
data = fetch_species_distributions()
# Get matrices/arrays of species IDs and locations
la... | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
With this data loaded, we can use the Basemap toolkit (mentioned previously in Geographic Data with Basemap) to plot the observed locations of these two species on the map of South America. | # !conda install -c conda-forge basemap-data-hires -y
# RESTART KERNEL
#Hack to fix missing PROJ4 env var
import os
import conda
conda_file_dir = conda.__file__
conda_dir = conda_file_dir.split('lib')[0]
proj_lib = os.path.join(os.path.join(conda_dir, 'share'), 'proj')
os.environ["PROJ_LIB"] = proj_lib
from mpl_too... | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
Unfortunately, this doesn't give a very good idea of the density of the species, because points in the species range may overlap one another.
You may not realize it by looking at this plot, but there are over 1,600 points shown here!
Let's use kernel density estimation to show this distribution in a more interpretable ... | # Set up the data grid for the contour plot
X, Y = np.meshgrid(xgrid[::5], ygrid[::5][::-1])
land_reference = data.coverages[6][::5, ::5]
land_mask = (land_reference > -9999).ravel()
xy = np.vstack([Y.ravel(), X.ravel()]).T
xy = np.radians(xy[land_mask])
# Create two side-by-side plots
fig, ax = plt.subplots(1, 2)
fig... | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
Compared to the simple scatter plot we initially used, this visualization paints a much clearer picture of the geographical distribution of observations of these two species.
Example: Not-So-Naive Bayes
This example looks at Bayesian generative classification with KDE, and demonstrates how to use the Scikit-Learn archi... | from sklearn.base import BaseEstimator, ClassifierMixin
class KDEClassifier(BaseEstimator, ClassifierMixin):
"""Bayesian generative classification based on KDE
Parameters
----------
bandwidth : float
the kernel bandwidth within each class
kernel : str
the kernel name, passed t... | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
The anatomy of a custom estimator
Let's step through this code and discuss the essential features:
```python
from sklearn.base import BaseEstimator, ClassifierMixin
class KDEClassifier(BaseEstimator, ClassifierMixin):
"""Bayesian generative classification based on KDE
Parameters
----------
bandwidth : float
the... | from sklearn.datasets import load_digits
from sklearn.model_selection import GridSearchCV
digits = load_digits()
bandwidths = 10 ** np.linspace(0, 2, 100)
grid = GridSearchCV(KDEClassifier(), {'bandwidth': bandwidths})
grid.fit(digits.data, digits.target)
# scores = [val.mean_validation_score for val in grid.grid_sc... | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
Next we can plot the cross-validation score as a function of bandwidth: | plt.semilogx(bandwidths, scores)
plt.xlabel('bandwidth')
plt.ylabel('accuracy')
plt.title('KDE Model Performance')
print(grid.best_params_)
print('accuracy =', grid.best_score_) | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
We see that this not-so-naive Bayesian classifier reaches a cross-validation accuracy of just over 96%; this is compared to around 80% for the naive Bayesian classification: | from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import cross_val_score
cross_val_score(GaussianNB(), digits.data, digits.target).mean() | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit |
We can easily calculate the population mean and population variance: | population.mean()
((population - population.mean()) ** 2).sum() / N | blog/unbiased_variance_estimator.ipynb | mortada/notebooks | apache-2.0 |
Note that we are dividing by $N$ in the variance calculation, also that in numpy or pandas this is the same as simply using the method var with ddof=0 | population.var(ddof=0) | blog/unbiased_variance_estimator.ipynb | mortada/notebooks | apache-2.0 |
where ddof=0 means to divide by $N$, and ddof=1 means to divide by $N - 1$.
Simulation
As usual in statistics, the population parameters are often unknown. But we can estimate them by drawing samples from the population. Here we are drawing a random sample of size $30$. As of version 0.16.1, pandas has a convenient Ser... | samples = {}
n = 30 # size of each sample
num_samples = 500 # we are drawing 500 samples, each with size n
for i in range(num_samples):
samples[i] = population.sample(n).reset_index(drop=True)
samples = pd.DataFrame(samples)
samples.T.tail() | blog/unbiased_variance_estimator.ipynb | mortada/notebooks | apache-2.0 |
As we expect, if we average all the sample means we can see that the it is a good estimate for the true population mean: | df = pd.DataFrame({'estimated mean': pd.expanding_mean(samples.mean()),
'actual population mean': pd.Series(population.mean(), index=samples.columns)})
df.plot(ylim=(4.5, 6.5)) | blog/unbiased_variance_estimator.ipynb | mortada/notebooks | apache-2.0 |
Now let's compare the results we would get by using the biased estimator (dividing by $n$) and the unbiased estimator (dividing by $n-1$) | df = pd.DataFrame({'biased var estimate (divide by n)': pd.expanding_mean(samples.var(ddof=0)),
'unbiased var estimate (divide by n - 1)': pd.expanding_mean(samples.var(ddof=1)),
'actual population var': pd.Series(population.var(ddof=0), index=samples.columns)})
df.plot(ylim=(6.5, ... | blog/unbiased_variance_estimator.ipynb | mortada/notebooks | apache-2.0 |
With an ordinary dictionary, I would need to check if they key exists. If it doesn't I need to initialize it with a value. For instrutional purposes I will call the int() function which will return the default value for an integer which is 0. | # This won't work because I haven't initialized keys
summed = dict()
for row in data:
key, value = row # destructure the tuple
summed[key] = summed[key] + value | python-tutorials/defaultdict.ipynb | Pinafore/ds-hw | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.