markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values | hash
stringlengths 32
32
|
---|---|---|---|---|---|
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 | 0f4b89bde498d8548c465ec570d74e16 |
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],
[0, 0, 1, 3]])):
"""
A helper function for repetitive
pieces of code.
Creates a dataset, where target depends on
`unobserved`, but `unobserved` is not
included as a feature. Independent features
can be passed as `given_exogenous` as well as
be drawn from Gaussian distribution.
Target is generated as linear combination of
features and their interactions in the
following manner. Order features as below:
unobserved variable, treatment indicator,
given exogenous features, drawn exogenous
features. Then the (i, i)-th element of
`weights_matrix` defines coefficient of
the i-th feature, whereas the (i, j)-th
element of `weights_matrix` (where i != j)
defines coefficient of interaction between
the i-th and j-th features.
@type unobserved: numpy.ndarray
@type treatment: numpy.ndarray
@type given_exogenous: numpy.ndarray
@type n_exogenous_to_draw: int
@type weights_matrix: numpy.ndarray
@rtype: tuple(numpy.ndarray)
"""
if unobserved.shape != treatment.shape:
raise ValueError("`unobserved` and `treatment` are not aligned.")
if (given_exogenous is not None and
unobserved.shape[0] != given_exogenous.shape[0]):
raise ValueError("`unobserved` and `given_exogenous` are not " +
"aligned. Try to transpose `given_exogenous`.")
if weights_matrix.shape[0] != weights_matrix.shape[1]:
raise ValueError("Matrix of weights is not square.")
if not np.array_equal(weights_matrix, weights_matrix.T):
raise ValueError("Matrix of weigths is not symmetric.")
len_of_given = given_exogenous.shape[1] if given_exogenous is not None else 0
if 2 + len_of_given + n_exogenous_to_draw != weights_matrix.shape[0]:
raise ValueError("Number of weights is not equal to that of features.")
drawn_features = []
for i in range(n_exogenous_to_draw):
current_feature = np.random.normal(size=unobserved.shape[0])
drawn_features.append(current_feature)
if given_exogenous is None:
features = np.vstack([unobserved, treatment] + drawn_features).T
else:
features = np.vstack([unobserved, treatment, given_exogenous.T] +
drawn_features).T
target = np.dot(features, weights_matrix.diagonal())
indices = list(range(weights_matrix.shape[0]))
interactions = [weights_matrix[i, j] * features[:, i] * features[:, j]
for i, j in combinations(indices, 2)]
target = np.sum(np.vstack([target] + interactions), axis=0)
return features[:, 1:], target
learning_X, learning_y = synthesize_dataset(unobserved, treatment) | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit | bf124d0cd786d899ec17d9b458c0194c |
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,
no_treatment_X[:, 1:], 0) | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit | 3debf2278cd235d7e8381b2095cd8d92 |
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 | 7022a2d088a403439f88b9bf979a8ac4 |
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
all routines related to grid search.
@type X_train: numpy.ndarray
@type y_train: numpy.ndarray
@type rgr: any sklearn regressor
@type grid_params: dict
@type kf: any sklearn folds
@type scoring: str
@rtype: sklearn regressor
"""
grid_search_cv = GridSearchCV(rgr, grid_params, cv=kf,
scoring=scoring)
grid_search_cv.fit(X_train, y_train)
print("Best CV mean score: {}".format(grid_search_cv.best_score_))
means = grid_search_cv.cv_results_['mean_test_score']
stds = grid_search_cv.cv_results_['std_test_score']
print("Detailed results:")
for mean, std, params in zip(means, stds,
grid_search_cv.cv_results_['params']):
print("%0.3f (+/-%0.03f) for %r" % (mean, 2 * std, params))
return grid_search_cv.best_estimator_
rgr = LinearRegression()
grid_params = {'fit_intercept': [True, False]}
kf = KFold(n_splits=5, shuffle=True, random_state=361) | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit | f4382c144f98afc58c85efe6b8ddc2c5 |
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 | cbf343b7e6fd10ca9d9ee87036c4b333 |
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 interpretation can not be used for a model without intercept). | 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 | 7d9781facfe700186241d12e01f88e27 |
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 | 0868135f7ae5b8db744c28c7ee096b57 |
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 | e8101818ea41af0654ac56b793861b26 |
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(full_treatment_y_hat, full_treatment_y)
ax_two.set_title("Simulation of treatment")
ax_two.set_xlabel("Predicted values")
ax_two.set_ylabel("True values")
_ = ax_two.grid() | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit | c0268ead2a9a4b8322740ca5c73c9fdc |
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 creation. Similarly, in case of full treatment, for items with unobserved feature equal to 0, predictions are higher than true values and the differences are close to the abovementioned coefficient too.
Finally, let us simulate a wrong decision that the manager can make. Suppose that treatment costs one dollar per item and every unit increase in the target variable leads to creation of value that is equal to one dollar too. | 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 | 12bb7583ff4fd33011efce54858f5f70 |
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_improvement | endogeneity/treatment_effect_with_selection_on_unobservables.ipynb | Nikolay-Lysenko/presentations | mit | ada5f704dc7ecf766d336d608b5cd176 |
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 'Ingredient({0}, {1}, {2}, {3})'.format(self.name, self.carbs, self.protein, self.fat)
def get_nutrition(self):
"""Returns the nutritional information for the ingredient"""
return (self.carbs, self.protein, self.fat)
class Recipe(object):
"""The Recipe object containing the ingredients"""
def __init__(self, name, ingredients):
self.name = name
self.ingredients = ingredients
def get_nutrition(self):
"""Returns the nutritional information for the recipe"""
nutrition = [0, 0, 0]
for amount, ingredient in self.ingredients:
nutrition[0] += amount * ingredient.carbs
nutrition[1] += amount * ingredient.protein
nutrition[2] += amount * ingredient.fat
return nutrition
bread = Recipe('Bread', [(820, Ingredient('Flour', 0.77, 0.10, 0.01)),
(30, Ingredient('Oil', 0, 0, 1)),
(36, Ingredient('Sugar', 1, 0, 0)),
(7, Ingredient('Yeast', 0.3125, 0.5, 0.0625)),
(560, Ingredient('Water', 0, 0, 0))])
print(bread.ingredients)
# Should be roughly [(820, Ingredient(Flour, 0.77, 0.1, 0.01)), (30, Ingredient(Oil, 0, 0, 1)),
# (36, Ingredient(Sugar, 1, 0, 0)), (7, Ingredient(Yeast, 0.3125, 0.5, 0.0625)), (560, Ingredient(Water, 0, 0, 0))]
print(bread.nutrition)
#Should be roughly {'carbs': 669.5875, 'protein': 85.5, 'fat': 38.6375} the order is not important
#Points to note:
# - The different call to Ingredient, you can use isinstance or type to change the
# behaviour depending on the arguments supplied
# - Cholesterol as an extra nutrient, your implementation should accept any nutrient
# - Use of Recipe (bread) as an ingredient
basic_french_toast = Recipe('Basic French Toast', [(300, Ingredient('Egg', {'carbs': 0.0077, 'protein': 0.1258,
'fat': 0.0994, 'cholesterol': 0.00423})),
(0.25, bread)])
print(basic_french_toast.ingredients)
# Should be roughly:
# [(300, Ingredient(Egg, 0.0077, 0.1258, 0.0994)), (0.25, Recipe(Bread, [(820, Ingredient(Flour, 0.77, 0.1, 0.01)),
# (30, Ingredient(Oil, 0, 0, 1)), (36, Ingredient(Sugar, 1, 0, 0)), (7, Ingredient(Yeast, 0.3125, 0.5, 0.0625)),
# (560, Ingredient(Water, 0, 0, 0))]))]
# Note the formatting for the Recipe object, a __repr__ method will be needed
print(basic_french_toast.nutrition)
# Should be roughly {'protein': 59.115, 'carbs': 169.706875, 'cholesterol': 1.2690000000000001, 'fat': 39.479375000000005}
# The order is not important | Wk05/Wk05-OOP-Public-interface.ipynb | briennakh/BIOF509 | mit | e23302a9160579e4c3beaefa64ac69f5 |
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/docs-l10n/blob/master/site/ja/guide/estimator.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab で実行</a> </td>
<td> <a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/guide/estimator.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub でソースを表示</a> </td>
<td> <a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/guide/estimator.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">ノートブックをダウンロード</a> </td>
</table>
警告: 新しいコードには Estimators は推奨されません。Estimators は v1.Session スタイルのコードを実行しますが、これは正しく記述するのはより難しく、特に TF 2 コードと組み合わせると予期しない動作をする可能性があります。Estimators は、互換性保証の対象となりますが、セキュリティの脆弱性以外の修正は行われません。詳細については、移行ガイドを参照してください。
このドキュメントでは、tf.estimator という高位 TensorFlow API を紹介します。Estimator は以下のアクションをカプセル化します。
トレーニング
評価
予測
配信向けエクスポート
TensorFlow は、事前に作成された複数の Estimator を実装します。カスタムの Estimator は依然としてサポートされていますが、主に下位互換性の対策としてサポートされているため、新しいコードでは、カスタム Estimator を使用してはいけません。事前に作成された Estimator とカスタム Estimator はすべて、tf.estimator.Estimator クラスに基づくクラスです。
簡単な例については、Estimator チュートリアルを試してください。API デザインの概要については、ホワイトペーパーをご覧ください。
セットアップ | !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 | fab2d2528d99c1baa957fc86a6ea1bcf |
メリット
tf.keras.Model と同様に、estimator はモデルレベルの抽象です。tf.estimator は、tf.keras 向けに現在開発段階にある以下の機能を提供しています。
パラメーターサーバーベースのトレーニング
TFX の完全統合
Estimator の機能
Estimator には以下のメリットがあります。
Estimator ベースのモデルは、モデルを変更することなくローカルホストまたは分散マルチサーバー環境で実行できます。さらに、モデルをコーディングし直すことなく、CPU、GPU、または TPU で実行できます。
Estimator では、次を実行する方法とタイミングを制御する安全な分散型トレーニングループを使用できます。
データの読み込み
例外の処理
チェックポイントファイルの作成と障害からの復旧
TensorBoard 用のサマリーの保存
Estimator を使ってアプリケーションを記述する場合、データ入力パイプラインとモデルを分離する必要があります。分離することで、異なるデータセットを伴う実験を単純化することができます。
事前作成済み Estimator を使用する
既成の Estimator を使うと、基本の TensorFlow API より非常に高い概念レベルで作業することができます。Estimator がすべての「配管作業」を処理してくれるため、計算グラフやセッションの作成などに気を回す必要がありません。さらに、事前作成済みの Estimator では、コード変更を最小限に抑えて多様なモデルアーキテクチャを使った実験を行えます。たとえば tf.estimator.DNNClassifier は、密度の高いフィードフォワードのニューラルネットワークに基づく分類モデルをトレーニングする事前作成済みの Estimator クラスです。
事前作成済み Estimator に依存する TensorFlow プログラムは、通常、次の 4 つのステップで構成されています。
1. 入力関数を作成する
たとえば、トレーニングセットをインポートする関数とテストセットをインポートする関数を作成する場合、Estimator は入力が次の 2 つのオブジェクトのペアとしてフォーマットされていることを期待します。
特徴名のキーと対応する特徴データを含むテンソル(または SparseTensors)の値で構成されるディクショナリ
1 つ以上のラベルを含むテンソル
input_fn は上記のフォーマットのペアを生成する tf.data.Dataset を返します。
たとえば、次のコードは Titanic データセットの train.csv ファイルから tf.data.Dataset を構築します。 | 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)
.prefetch(tf.data.AUTOTUNE))
return titanic_batches | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 | df07d1e42d9b528a48c5f1fda8d7b2a5 |
input_fn は、tf.Graph で実行し、グラフテンソルを含む (features_dics, labels) ペアを直接返すこともできますが、定数を返すといった単純なケースではない場合に、エラーが発生しやすくなります。
2. 特徴量カラムを定義する
tf.feature_column は、特徴量名、その型、およびすべての入力前処理を特定します。
たとえば、次のスニペットは 3 つの特徴量カラムを作成します。
最初の特徴量カラムは、浮動小数点数の入力として直接 age 特徴量を使用します。
2 つ目の特徴量カラムは、カテゴリカル入力として class 特徴量を使用します。
3 つ目の特徴量カラムは、カテゴリカル入力として embark_town を使用しますが、オプションを列挙する必要がないように、またオプション数を設定するために、hashing trick を使用します。
詳細については、特徴量カラムのチュートリアルをご覧ください。 | 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 | 0f8d9ea53272fbc9547723054d845747 |
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 | 6eccea8cfb505a190562687702156de8 |
詳細については、線形分類器のチュートリアルをご覧ください。
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 | 1c2f832100c836b9a1cd9bcb71fb3f99 |
事前作成済み Estimator のメリット
事前作成済み Estimator は、次のようなベストプラクティスをエンコードするため、さまざまなメリットがあります。
さまざまな部分の計算グラフをどこで実行するかを決定し、単一のマシンまたはクラスタに戦略を実装するためのベストプラクティス。
イベント(要約)の書き込みと普遍的に役立つ要約のベストプラクティス。
事前作成済み Estimator を使用しない場合は、上記の特徴量を独自に実装する必要があります。
カスタム Estimator
事前作成済みかカスタムかに関係なく、すべての Estimator の中核は、モデル関数の model_fn にあります。これは、トレーニング、評価、および予測に使用するグラフを構築するメソッドです。事前作成済み Estimator を使用する場合は、モデル関数はすでに実装されていますが、カスタム Estimator を使用する場合は、モデル関数を自分で記述する必要があります。
注意: カスタム model_fn は 1.x スタイルのグラフモードでそのまま実行します。つまり、Eager execution はなく、依存関係の自動制御もないため、tf.estimator からカスタム model_fn に移行する必要があります。代替の API は tf.keras と tf.distribute です。トレーニングの一部に Estimator を使用する必要がある場合は、tf.keras.estimator.model_to_estimator コンバータを使用して keras.Model から Estimator を作成する必要があります。
Keras モデルから Estimator を作成する
tf.keras.estimator.model_to_estimator を使用して、既存の Keras モデルを Estimator に変換できます。モデルコードを最新の状態に変更したくても、トレーニングパイプラインに Estimator が必要な場合に役立ちます。
Keras MobileNet V2 モデルをインスタンス化し、トレーニングに使用する optimizer、loss、および metrics とともにモデルをコンパイルします。 | 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_model.compile(
optimizer='adam',
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy']) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 | 85b34b0d538a839c6eb7774db3ebb6b2 |
コンパイルされた 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 | 3057a8c54c0be877a31146c808049c1b |
派生した 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)
train_data = data['train']
train_data = train_data.map(preprocess).shuffle(500).batch(batch_size)
return train_data | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 | fd5a39eaa4207b60bd9527b38d41e266 |
トレーニングするには、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 | 677de698f32551bb8e965e47b5fa56ac |
同様に、評価するには、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 | a17e017ca5b1c6ceebd68a0529fbd5a2 |
詳細については、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):
super(Net, self).__init__()
self.l1 = tf.keras.layers.Dense(5)
def call(self, x):
return self.l1(x)
def model_fn(features, labels, mode):
net = Net()
opt = tf.keras.optimizers.Adam(0.1)
ckpt = tf.train.Checkpoint(step=tf_compat.train.get_global_step(),
optimizer=opt, net=net)
with tf.GradientTape() as tape:
output = net(features['x'])
loss = tf.reduce_mean(tf.abs(output - features['y']))
variables = net.trainable_variables
gradients = tape.gradient(loss, variables)
return tf.estimator.EstimatorSpec(
mode,
loss=loss,
train_op=tf.group(opt.apply_gradients(zip(gradients, variables)),
ckpt.step.assign_add(1)),
# Tell the Estimator to save "ckpt" in an object-based format.
scaffold=tf_compat.train.Scaffold(saver=ckpt))
tf.keras.backend.clear_session()
est = tf.estimator.Estimator(model_fn, './tf_estimator_example/')
est.train(toy_dataset, steps=10) | site/ja/guide/estimator.ipynb | tensorflow/docs-l10n | apache-2.0 | 4de7ec7c2450597f17f81e5f9a014e6c |
その後、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 | 39c0ee9c940c7125b56c2e849b4c9ed0 |
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 | 4e756acd59ff7ccff5e3817e612b3720 |
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 | 05d98f99af99503dc926dfbf41d64724 |
また、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 | b55dc7d977a6f6e89565460df94262dc |
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 を使用している場合は、コードを少し変更するだけで、分散型トレーニングに変更することができます。これにより、Estimator ユーザーは複数の GPU と複数のワーカーだけでなく、TPU でも同期分散型トレーニングを実行できるようになりましたが、Estimator でのこのサポートには制限があります。詳細については、以下に示す「現在、何がサポートされていますか」セクションをご覧ください。
Estimator での tf.distribute.Strategy の使用は、Keras の事例とわずかに異なります。strategy.scope を使用する代わりに、ストラテジーオブジェクトを Estimator の RunConfig に渡します。
詳細については、分散型トレーニングガイドをご覧ください。
次は、事前に作成された Estimator LinearRegressor と MirroredStrategy を使ってこの動作を示すコードスニペットです。 | 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 | 2fb5095a4b6c7ee5ccc8503547da7806 |
ここでは、事前に作成された 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 | b72b3a4c61a166dd1d7b722547f82766 |
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-Friendly Application for MEG/EEG Analysis.
Computational Intelligence and Neuroscience, vol. 2011, Article ID
879716, 13 pages, 2011. doi:10.1155/2011/879716 | # 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(__doc__) | 0.16/_downloads/plot_brainstorm_phantom_elekta.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause | b623d7d69e1a737e4c637a6a72d14210 |
$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 | 77c68d7c0909a63eec1e5ac6718f0914 |
$\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 | 4dad2cac7a0ecc20d6fea9effe77f03e |
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", outdir="/tmp", diploid=True) | newdocs/API-analysis/cookbook-construct-ipcoal.ipynb | dereneaton/ipyrad | gpl-3.0 | 1b1d392ba6a2a2b0de8072f5c1775fa6 |
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 | 06f5f9a418eb00f75d2811b5408f3bd7 |
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 | f2c1bc8c2e8a65e807b2ca875a85e9fc |
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 | e47ed3b5d89994ac075d7e29799f3a3b |
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 | 1ccce37e77719999f03a81725c8c2014 |
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 | 8a781332ac486b800451fc083cdf8b07 |
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 | a7a7de0872fb34ba0b677a2306fc4818 |
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 | 9f1a64b6753018423646029aa6abcc04 |
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, this requires to load the integration package. | 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 | e8c2e81a255d93795f56df0f0a3bba40 |
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 | 8511379f426e97cc80aa9977f8bbf294 |
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 likelihood function has no (simple) analytical normalisation anymore, i.e. we directly do the numerical approach. | 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 | 406a350644e773586f070c710cdaf2ec |
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 | 523c777b6ea7029e10c2566337621ce1 |
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 affects the result. | # 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_posterior(theta, x):
a , b = theta
# construct and the log of the posterior
return 1. | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause | 471075db5bf382516f94583432d58fc5 |
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 | 9383c2574387f1021e95dbd7ce48df1b |
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 | f31791c5910d457ec73e5a08602dbe58 |
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 | 93c182af0023aa1273d946365b1c0e73 |
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 array
i_sort = np.argsort(L)[::-1]
i_unsort = np.argsort(i_sort)
L_cumsum = L[i_sort].cumsum()
L_cumsum /= L_cumsum[-1]
xbins = 0.5 * (xbins[1:] + xbins[:-1])
ybins = 0.5 * (ybins[1:] + ybins[:-1])
return xbins, ybins, L_cumsum[i_unsort].reshape(shape)
#xbins, ybins, sigma = compute_sigma_level(emcee_trace[0], emcee_trace[1])
#plt.contour(xbins, ybins, sigma.T, levels=[0.683, 0.955])
#plt.plot(emcee_trace[0], emcee_trace[1], ',k', alpha=0.1) | tutorials/analysis-stats/Tutorial.ipynb | gammapy/PyGamma15 | bsd-3-clause | 0f879c4c3ddf6485b561b20e06e0b70a |
欢迎来到线性回归项目
若项目中的题目有困难没完成也没关系,我们鼓励你带着问题提交项目,评审人会给予你诸多帮助。
所有选做题都可以不做,不影响项目通过。如果你做了,那么项目评审会帮你批改,也会因为选做部分做错而判定为不通过。
其中非代码题可以提交手写后扫描的 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 | 14e3dd962143753b9402a590cc9ab338 |
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 | 8afe8736f2f75096d8714c6cee659fb9 |
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 | a45605f56b7ac25bc399d1c651505d87 |
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 | 62c61587b4d02ba640d23cd68976013e |
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]
for j in range(colB):
colb = BT[j]
element = sum([rowa[x]*colb[x] for x in range(colA)])
result[i][j] = element
return result
# 运行以下代码测试你的 matxMultiply 函数
%run -i -e test.py LinearRegressionTestCase.test_matxMultiply | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit | a26d1763a5fe6c365c5ba735d2284eca |
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} \
... \
b_{n} \
\end{bmatrix}$
返回 $ Ab = \begin{bmatrix}
a_{11} & a_{12} & ... & a_{1n} & b_{1}\
a_{21} & a_{22} & ... & a_{2n} & b_{2}\
a_{31} & a_{22} & ... & a_{3n} & b_{3}\
... & ... & ... & ...& ...\
a_{n1} & a_{n2} & ... & a_{nn} & b_{n} \end{bmatrix}$ | # 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
# 运行以下代码测试你的 augmentMatrix 函数
%run -i -e test.py LinearRegressionTestCase.test_augmentMatrix | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit | 4ddad0c268def53816e8fe80574ad94a |
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是非法输入,要求 raise ValueError
# 直接修改参数矩阵,无返回值
def scaleRow(M, r, scale):
if scale == 0:
raise ValueError
colM = shape(M)[1]
for i in range(colM):
M[r][i] *= scale
pass
# 运行以下代码测试你的 scaleRow 函数
%run -i -e test.py LinearRegressionTestCase.test_scaleRow
# TODO r1 <--- r1 + r2*scale
# 直接修改参数矩阵,无返回值
def addScaledRow(M, r1, r2, scale):
colM = shape(M)[1]
for i in range(colM):
M[r1][i] += M[r2][i]*scale
pass
# 运行以下代码测试你的 addScaledRow 函数
%run -i -e test.py LinearRegressionTestCase.test_addScaledRow | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit | 41f77bfc1e41e5c5023dd44581a3d702 |
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
多次使用第三个行变换,将列c的其他元素消为0
步骤4 返回Ab的最后一列
注: 我们并没有按照常规方法先把矩阵转化为行阶梯形矩阵,再转换为化简行阶梯形矩阵,而是一步到位。如果你熟悉常规方法的话,可以思考一下两者的等价性。
2.3.2 算法推演
为了充分了解Gaussian Jordan消元法的计算流程,请根据Gaussian Jordan消元法,分别手动推演矩阵A为可逆矩阵,矩阵A为奇异矩阵两种情况。
推演示例
$Ab = \begin{bmatrix}
-7 & 5 & -1 & 1\
1 & -3 & -8 & 1\
-10 & -2 & 9 & 1\end{bmatrix}$
$ --> $
$\begin{bmatrix}
1 & \frac{1}{5} & -\frac{9}{10} & -\frac{1}{10}\
0 & -\frac{16}{5} & -\frac{71}{10} & \frac{11}{10}\
0 & \frac{32}{5} & -\frac{73}{10} & \frac{3}{10}\end{bmatrix}$
$ --> $
$\begin{bmatrix}
1 & 0 & -\frac{43}{64} & -\frac{7}{64}\
0 & 1 & -\frac{73}{64} & \frac{3}{64}\
0 & 0 & -\frac{43}{4} & \frac{5}{4}\end{bmatrix}$
$ --> $
$\begin{bmatrix}
1 & 0 & 0 & -\frac{3}{16}\
0 & 1 & 0 & -\frac{59}{688}\
0 & 0 & 1 & -\frac{5}{43}\end{bmatrix}$
推演有以下要求:
展示每一列的消元结果, 比如3*3的矩阵, 需要写三步
用分数来表示
分数不能再约分
我们已经给出了latex的语法,你只要把零改成你要的数字(或分数)即可
检查你的答案, 可以用这个, 或者后面通过单元测试后的gj_Solve
你可以用python的 fractions 模块辅助你的约分
以下开始你的尝试吧! | # 不要修改这里!
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 | 364d05f1ad884c2298839c608519639b |
请按照算法的步骤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}$
$ --> \begin{bmatrix}
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \end{bmatrix}$
$...$ | # 不要修改这里!
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 | 00c2b6a766618670b2c03640fe98faac |
请按照算法的步骤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}$
$ --> \begin{bmatrix}
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \
0 & 0 & 0 & 0 \end{bmatrix}$
$...$
2.3.3 实现 Gaussian Jordan 消元法 | # 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, epsilon = 1.0e-16):
def max_idx(list):
if max(list)<=epsilon:
raise ValueError
return 0 if len(list)<=0 else list.index(max(list))
if not shape(A)[0] == shape(b)[0]:
return None
Ab = augmentMatrix(A, b)
for i in range(shape(A)[1]):
col_i = [abs(Ab[row_num][i]) for row_num in range(i, shape(Ab)[0])]
try:
idx = max_idx(col_i) + i
swapRows(Ab, i, idx)
scaleRow(Ab, i, 1.0/Ab[i][i])
for j in range(shape(Ab)[0]):
if j != i:
addScaledRow(Ab, j, i, Fraction(-Ab[j][i]))
except ValueError:
return None
result = [[0] * 1 for row in range(shape(Ab)[0])]
for i in range(shape(Ab)[0]):
result[i][0]=Ab[i][-1]
return result
# 运行以下代码测试你的 gj_Solve 函数
%run -i -e test.py LinearRegressionTestCase.test_gj_Solve | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit | f81d57a280d21966005a9816e8c61dc9 |
(选做) 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 的某一列是其他列的线性组合
TODO 证明:
3 线性回归
3.1 随机生成样本点 | # 不要修改这里!
# 运行一次就够了!
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 | bee0a3e36e2b3949507b556f061598f9 |
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 | cd7d716fc5d065e4abc636aeea889db6 |
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 | 52a58663f363bfb9076321ae10b9fe67 |
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}MSE$, 所以 $E$ 取到最小值时,$MSE$ 也取到最小值。要找到 $E$ 的最小值,即要找到 $m, b$ 使得 $E$ 相对于 $m$, $E$ 相对于 $b$ 的偏导数等于0.
因此我们要解下面的方程组。
$$
\begin{cases}
\displaystyle
\frac{\partial E}{\partial m} =0 \
\
\displaystyle
\frac{\partial E}{\partial b} =0 \
\end{cases}
$$
3.3.1 计算目标函数相对于参数的导数
首先我们计算两个式子左边的值
证明/计算:
$$
\frac{\partial E}{\partial m} = \sum_{i=1}^{n}{-x_i(y_i - mx_i - b)}
$$
$$
\frac{\partial E}{\partial b} = \sum_{i=1}^{n}{-(y_i - mx_i - b)}
$$
TODO 证明:
3.3.2 实例推演
现在我们有了一个二元二次方程组
$$
\begin{cases}
\displaystyle
\sum_{i=1}^{n}{-x_i(y_i - mx_i - b)} =0 \
\
\displaystyle
\sum_{i=1}^{n}{-(y_i - mx_i - b)} =0 \
\end{cases}
$$
为了加强理解,我们用一个实际例子演练。
我们要用三个点 $(1,1), (2,2), (3,2)$ 来拟合一条直线 y = m*x + b, 请写出
目标函数 $E$,
二元二次方程组,
并求解最优参数 $m, b$
TODO 写出目标函数,方程组和最优参数
3.3.3 将方程组写成矩阵形式
我们的二元二次方程组可以用更简洁的矩阵形式表达,将方程组写成矩阵形式更有利于我们使用 Gaussian Jordan 消元法求解。
请证明
$$
\begin{bmatrix}
\frac{\partial E}{\partial m} \
\frac{\partial E}{\partial b}
\end{bmatrix} = X^TXh - X^TY
$$
其中向量 $Y$, 矩阵 $X$ 和 向量 $h$ 分别为 :
$$
Y = \begin{bmatrix}
y_1 \
y_2 \
... \
y_n
\end{bmatrix}
,
X = \begin{bmatrix}
x_1 & 1 \
x_2 & 1\
... & ...\
x_n & 1 \
\end{bmatrix},
h = \begin{bmatrix}
m \
b \
\end{bmatrix}
$$
TODO 证明:
至此我们知道,通过求解方程 $X^TXh = X^TY$ 来找到最优参数。这个方程十分重要,他有一个名字叫做 Normal Equation,也有直观的几何意义。你可以在 子空间投影 和 投影矩阵与最小二乘 看到更多关于这个方程的内容。
3.4 求解 $X^TXh = X^TY$
在3.3 中,我们知道线性回归问题等价于求解 $X^TXh = X^TY$ (如果你选择不做3.3,就勇敢的相信吧,哈哈) | # 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)
m2,b2 = linearRegression(X,Y)
assert isinstance(m2,float),"m is not a float"
assert isinstance(b2,float),"b is not a float"
print(m2,b2) | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit | 445596f2ddeb9da1696099b27e052c5f |
你求得的回归结果是什么?
请使用运行以下代码将它画出来。 | # 请不要修改下面的代码
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 | 243c8b9930850c6c840ed6b885ece313 |
你求得的回归结果对当前数据集的MSE是多少? | print(calculateMSE(X,Y,m2,b2)) | 3LinearAlgebra/project3/linear_regression_project.ipynb | famunity/deep-learning-term1 | mit | e55c965d6aa090b40a59a8531f768e33 |
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 | 367ced0bec85c79196e476c3067a419e |
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 | 3bfac6304044ba25e6db8a841bf9b12c |
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 | fe8a77a7a43e64a5851f6d8b76dd15a4 |
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 path. | 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 | b6d0dc21823377c3df74581f1bd797f3 |
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 | 860b11f34c44c238a753723e5d94fd4a |
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 | 412156de6bbb37947f206e7f70514a90 |
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 blocked.
Block Tables to Produce a Candidate Set of Tuple Pairs
First, define a blackbox function | 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_split) - 1]
# check if the cities match
if x_city != y_city:
return True
else:
return False
# Instantiate blackbox blocker
bb = em.BlackBoxBlocker()
# Set the black box function
bb.set_black_box_function(address_address_function)
C = bb.block_tables(A, B, l_output_attrs=['name', 'address'], r_output_attrs=['name', 'address'])
C | notebooks/guides/step_wise_em_guides/Performing Blocking Using Blackbox Blocker.ipynb | anhaidgroup/py_entitymatching | bsd-3-clause | a12b16ff48e01cfc35bd5f97f11db29e |
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
else:
return False
# Instantiate blackbox blocker
bb = em.BlackBoxBlocker()
# Set the black box function
bb.set_black_box_function(name_name_function)
D = bb.block_candset(C)
D | notebooks/guides/step_wise_em_guides/Performing Blocking Using Blackbox Blocker.ipynb | anhaidgroup/py_entitymatching | bsd-3-clause | e25e1dee448729a5171a60da50bba94e |
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_split) - 1]
# check if the cities match
if x_city != y_city:
return True
else:
return False
# Instantiate blackabox blocker
bb = em.BlackBoxBlocker()
# Set the blackbox function
bb.set_black_box_function(address_address_function)
A.ix[[0]]
B.ix[[0]]
status = bb.block_tuples(A.ix[0], B.ix[0])
print(status) | notebooks/guides/step_wise_em_guides/Performing Blocking Using Blackbox Blocker.ipynb | anhaidgroup/py_entitymatching | bsd-3-clause | dc4deb957bd51b261d9524c9e7c9f84b |
式(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.solve(x_matrix, f_matrix)
return a_matrix
# lagrange()で求めた補間多項式と、元の点列をプロットしてみる
# 与えられた点列のリスト
points = [[1, 1], [2, 2], [3, 1], [4, 1], [5, 3]]
# ラグランジュの補間多項式の係数行列を求める
a_matrix = lagrange(points)
# 係数行列を多項式に変換
func_lagrange = make_polynomial(a_matrix)
# 0から8まで、0.1刻みでxとfの値のセットを求める
x_list = np.arange(0, 8, 0.1)
f_list = func_lagrange(x_list)
# プロットする
points_on_func(points, x_list, f_list) | chapter2/Chapter2.ipynb | myuuuuun/NumericalCalculation | mit | d4ad6669b6e4f701c5259f49132b15d0 |
式(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][0])
Li *= points[i][1]
L += Li
f_list.append(L)
return f_list
points = [[1, 1], [2, 2], [3, 1], [4, 1], [5, 3]]
a_matrix = lagrange2(points, np.arange(0, 8, 0.1))
points_on_func(points, np.arange(0, 8, 0.1), a_matrix) | chapter2/Chapter2.ipynb | myuuuuun/NumericalCalculation | mit | 743a734e622bf409a150a7a4f765b42f |
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, counts the number of points that fall in each bin, and then visualizes the results in an intuitive manner.
For example, let's create some data that is drawn from two normal distributions: | 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 | 0bab5e6e147e3673712b78f626744773 |
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 | feda9d3994a576a6b301877cfc198a41 |
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 histogram function: | 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 | ba441d48c1ea556cc27e4f82a1169b15 |
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 interpretation of the data!
Consider this example: | 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.6]):
ax[i].hist(x, bins=bins + offset, density=True)
ax[i].plot(x, np.full_like(x, -0.01), '|k',
markeredgewidth=1) | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit | cc6646b08b224e4ced5dd8bf57a99ec9 |
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 histograms confer?
And how might we improve on this?
Stepping back, we can think of a histogram as a stack of blocks, where we stack one block within each bin on top of each point in the dataset.
Let's view this directly: | 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(-0.2, 8) | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit | 8251b3785bae757a69d517bb4eb15629 |
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 here.
But what if, instead of stacking the blocks aligned with the bins, we were to stack the blocks aligned with the points they represent?
If we do this, the blocks won't be aligned, but we can add their contributions at each location along the x-axis to find the result.
Let's try this: | 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 | d2aeb3d474f09d13e2bac3b31ed63e20 |
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 each location with a smooth function, like a Gaussian.
Let's use a standard normal curve at each point instead of a block: | 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 | ddbf22c610758c86d90ee96e0c90d5af |
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 density estimation in one dimension: the first uses a so-called "tophat" kernel and the second uses a Gaussian kernel.
We'll now look at kernel density estimation in more detail.
Kernel Density Estimation in Practice
The free parameters of kernel density estimation are the kernel, which specifies the shape of the distribution placed at each point, and the kernel bandwidth, which controls the size of the kernel at each point.
In practice, there are many kernels you might use for a kernel density estimation: in particular, the Scikit-Learn KDE implementation supports one of six kernels, which you can read about in Scikit-Learn's Density Estimation documentation.
While there are several versions of kernel density estimation implemented in Python (notably in the SciPy and StatsModels packages), I prefer to use Scikit-Learn's version because of its efficiency and flexibility.
It is implemented in the sklearn.neighbors.KernelDensity estimator, which handles KDE in multiple dimensions with one of six kernels and one of a couple dozen distance metrics.
Because KDE can be fairly computationally intensive, the Scikit-Learn estimator uses a tree-based algorithm under the hood and can trade off computation time for accuracy using the atol (absolute tolerance) and rtol (relative tolerance) parameters.
The kernel bandwidth, which is a free parameter, can be determined using Scikit-Learn's standard cross validation tools as we will soon see.
Let's first show a simple example of replicating the above plot using the Scikit-Learn KernelDensity estimator: | 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, np.full_like(x, -0.01), '|k', markeredgewidth=1)
plt.ylim(-0.02, 0.22) | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit | 9876d8f4284bfa2514f4ee7ab077a918 |
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 a bandwidth leads to a high-variance estimate (i.e., over-fitting), where the presence or absence of a single point makes a large difference. Too wide a bandwidth leads to a high-bias estimate (i.e., under-fitting) where the structure in the data is washed out by the wide kernel.
There is a long history in statistics of methods to quickly estimate the best bandwidth based on rather stringent assumptions about the data: if you look up the KDE implementations in the SciPy and StatsModels packages, for example, you will see implementations based on some of these rules.
In machine learning contexts, we've seen that such hyperparameter tuning often is done empirically via a cross-validation approach.
With this in mind, the KernelDensity estimator in Scikit-Learn is designed such that it can be used directly within the Scikit-Learn's standard grid search tools.
Here we will use GridSearchCV to optimize the bandwidth for the preceding dataset.
Because we are looking at such a small dataset, we will use leave-one-out cross-validation, which minimizes the reduction in training set size for each cross-validation trial: | 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 | be28c93a8117a6056c74f85897045afd |
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 | 6ace1a44f304fa46c93b01d0466217df |
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 visualization library (see Visualization With Seaborn), KDE is built in and automatically used to help visualize points in one and two dimensions.
Here we will look at a slightly more sophisticated use of KDE for visualization of distributions.
We will make use of some geographic data that can be loaded with Scikit-Learn: the geographic distributions of recorded observations of two South American mammals, Bradypus variegatus (the Brown-throated Sloth) and Microryzomys minutus (the Forest Small Rice Rat).
With Scikit-Learn, we can fetch this data as follows: | 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
latlon = np.vstack([data.train['dd lat'],
data.train['dd long']]).T
species = np.array([d.decode('ascii').startswith('micro')
for d in data.train['species']], dtype='int') | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit | 0616ce06e892ab646b46149e4f1bdb78 |
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_toolkits.basemap import Basemap
from sklearn.datasets.species_distributions import construct_grids
xgrid, ygrid = construct_grids(data)
# plot coastlines with basemap
m = Basemap(projection='cyl', resolution='c',
llcrnrlat=ygrid.min(), urcrnrlat=ygrid.max(),
llcrnrlon=xgrid.min(), urcrnrlon=xgrid.max())
m.drawmapboundary(fill_color='#DDEEFF')
m.fillcontinents(color='#FFEEDD')
m.drawcoastlines(color='gray', zorder=2)
m.drawcountries(color='gray', zorder=2)
# plot locations
m.scatter(latlon[:, 1], latlon[:, 0], zorder=3,
c=species, cmap='rainbow', latlon=True); | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit | a934f7c0295e20c5a4fe7754dd59ceaa |
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 way: as a smooth indication of density on the map.
Because the coordinate system here lies on a spherical surface rather than a flat plane, we will use the haversine distance metric, which will correctly represent distances on a curved surface.
There is a bit of boilerplate code here (one of the disadvantages of the Basemap toolkit) but the meaning of each code block should be clear: | # 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.subplots_adjust(left=0.05, right=0.95, wspace=0.05)
species_names = ['Bradypus Variegatus', 'Microryzomys Minutus']
cmaps = ['Purples', 'Reds']
for i, axi in enumerate(ax):
axi.set_title(species_names[i])
# plot coastlines with basemap
m = Basemap(projection='cyl', llcrnrlat=Y.min(),
urcrnrlat=Y.max(), llcrnrlon=X.min(),
urcrnrlon=X.max(), resolution='c', ax=axi)
m.drawmapboundary(fill_color='#DDEEFF')
m.drawcoastlines()
m.drawcountries()
# construct a spherical kernel density estimate of the distribution
kde = KernelDensity(bandwidth=0.03, metric='haversine')
kde.fit(np.radians(latlon[species == i]))
# evaluate only on the land: -9999 indicates ocean
Z = np.full(land_mask.shape[0], -9999.0)
Z[land_mask] = np.exp(kde.score_samples(xy))
Z = Z.reshape(X.shape)
# plot contours of the density
levels = np.linspace(0, Z.max(), 25)
axi.contourf(X, Y, Z, levels=levels, cmap=cmaps[i]) | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit | 36fcc28fc3ebc878084fe8850e25ca32 |
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 architecture to create a custom estimator.
In In Depth: Naive Bayes Classification, we took a look at naive Bayesian classification, in which we created a simple generative model for each class, and used these models to build a fast classifier.
For Gaussian naive Bayes, the generative model is a simple axis-aligned Gaussian.
With a density estimation algorithm like KDE, we can remove the "naive" element and perform the same classification with a more sophisticated generative model for each class.
It's still Bayesian classification, but it's no longer naive.
The general approach for generative classification is this:
Split the training data by label.
For each set, fit a KDE to obtain a generative model of the data.
This allows you for any observation $x$ and label $y$ to compute a likelihood $P(x~|~y)$.
From the number of examples of each class in the training set, compute the class prior, $P(y)$.
For an unknown point $x$, the posterior probability for each class is $P(y~|~x) \propto P(x~|~y)P(y)$.
The class which maximizes this posterior is the label assigned to the point.
The algorithm is straightforward and intuitive to understand; the more difficult piece is couching it within the Scikit-Learn framework in order to make use of the grid search and cross-validation architecture.
This is the code that implements the algorithm within the Scikit-Learn framework; we will step through it following the code block: | 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 to KernelDensity
"""
def __init__(self, bandwidth=1.0, kernel='gaussian'):
self.bandwidth = bandwidth
self.kernel = kernel
def fit(self, X, y):
self.classes_ = np.sort(np.unique(y))
training_sets = [X[y == yi] for yi in self.classes_]
self.models_ = [KernelDensity(bandwidth=self.bandwidth,
kernel=self.kernel).fit(Xi)
for Xi in training_sets]
self.logpriors_ = [np.log(Xi.shape[0] / X.shape[0])
for Xi in training_sets]
return self
def predict_proba(self, X):
logprobs = np.array([model.score_samples(X)
for model in self.models_]).T
result = np.exp(logprobs + self.logpriors_)
return result / result.sum(1, keepdims=True)
def predict(self, X):
return self.classes_[np.argmax(self.predict_proba(X), 1)] | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit | 139658b87ce4d4949c3f571d580bc4f9 |
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 kernel bandwidth within each class
kernel : str
the kernel name, passed to KernelDensity
"""
```
Each estimator in Scikit-Learn is a class, and it is most convenient for this class to inherit from the BaseEstimator class as well as the appropriate mixin, which provides standard functionality.
For example, among other things, here the BaseEstimator contains the logic necessary to clone/copy an estimator for use in a cross-validation procedure, and ClassifierMixin defines a default score() method used by such routines.
We also provide a doc string, which will be captured by IPython's help functionality (see Help and Documentation in IPython).
Next comes the class initialization method:
python
def __init__(self, bandwidth=1.0, kernel='gaussian'):
self.bandwidth = bandwidth
self.kernel = kernel
This is the actual code that is executed when the object is instantiated with KDEClassifier().
In Scikit-Learn, it is important that initialization contains no operations other than assigning the passed values by name to self.
This is due to the logic contained in BaseEstimator required for cloning and modifying estimators for cross-validation, grid search, and other functions.
Similarly, all arguments to __init__ should be explicit: i.e. *args or **kwargs should be avoided, as they will not be correctly handled within cross-validation routines.
Next comes the fit() method, where we handle training data:
python
def fit(self, X, y):
self.classes_ = np.sort(np.unique(y))
training_sets = [X[y == yi] for yi in self.classes_]
self.models_ = [KernelDensity(bandwidth=self.bandwidth,
kernel=self.kernel).fit(Xi)
for Xi in training_sets]
self.logpriors_ = [np.log(Xi.shape[0] / X.shape[0])
for Xi in training_sets]
return self
Here we find the unique classes in the training data, train a KernelDensity model for each class, and compute the class priors based on the number of input samples.
Finally, fit() should always return self so that we can chain commands. For example:
python
label = model.fit(X, y).predict(X)
Notice that each persistent result of the fit is stored with a trailing underscore (e.g., self.logpriors_).
This is a convention used in Scikit-Learn so that you can quickly scan the members of an estimator (using IPython's tab completion) and see exactly which members are fit to training data.
Finally, we have the logic for predicting labels on new data:
```python
def predict_proba(self, X):
logprobs = np.vstack([model.score_samples(X)
for model in self.models_]).T
result = np.exp(logprobs + self.logpriors_)
return result / result.sum(1, keepdims=True)
def predict(self, X):
return self.classes_[np.argmax(self.predict_proba(X), 1)]
`
Because this is a probabilistic classifier, we first implementpredict_proba()which returns an array of class probabilities of shape[n_samples, n_classes].
Entry[i, j]of this array is the posterior probability that sampleiis a member of classj``, computed by multiplying the likelihood by the class prior and normalizing.
Finally, the predict() method uses these probabilities and simply returns the class with the largest probability.
Using our custom estimator
Let's try this custom estimator on a problem we have seen before: the classification of hand-written digits.
Here we will load the digits, and compute the cross-validation score for a range of candidate bandwidths using the GridSearchCV meta-estimator (refer back to Hyperparameters and Model Validation): | 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_scores_]
scores = grid.cv_results_['mean_test_score'] | present/mcc2/PythonDataScienceHandbook/05.13-Kernel-Density-Estimation.ipynb | csaladenes/csaladenes.github.io | mit | bb08fe076461dca86352d5b273967305 |
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 | 62d2ea774f9ff71752fc35ec0f7efdb0 |
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 | bb81f452e311459b7106d74002181308 |
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 | 8a87d92ee663e6275d62ca64a4ffd2bd |
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 | f8e04f77e184ddc54f98cf43b507935c |
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 Series.sample() function for this: | 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 | 165eebb1ff1d46d550093ea788511098 |
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 | c1bfd2fa470a3d94043660953dcc8392 |
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, 10.5)) | blog/unbiased_variance_estimator.ipynb | mortada/notebooks | apache-2.0 | a8e30248e30498e933e145c3c3658394 |
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 | 920099f7158ce5f667415bf230206817 |