markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
これをconcrete_functionにラップします。 | inception_func = wrap_frozen_graph(
graph_def, inputs='input:0',
outputs='InceptionV1/InceptionV1/Mixed_3b/Branch_1/Conv2d_0a_1x1/Relu:0') | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
入力としてテンソルを渡します。 | input_img = tf.ones([1,224,224,3], dtype=tf.float32)
inception_func(input_img).shape | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
Estimator
Estimator でトレーニングする
Estimator は TensorFlow 2.0 でサポートされています。
Estimator を使用する際には、TensorFlow 1.x. からのinput_fn()、tf.estimator.TrainSpec、tf.estimator.EvalSpecを使用できます。
ここに train と evaluate specs を伴う input_fn を使用する例があります。
input_fn と train/eval specs を作成する | # Define the estimator's input_fn
def input_fn():
datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True)
mnist_train, mnist_test = datasets['train'], datasets['test']
BUFFER_SIZE = 10000
BATCH_SIZE = 64
def scale(image, label):
image = tf.cast(image, tf.float32)
image /= 255
... | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
Keras モデル定義を使用する
TensorFlow 2.x で Estimator を構築する方法には、いくつかの違いがあります。
モデルは Keras を使用して定義することを推奨します。次にtf.keras.estimator.model_to_estimatorユーティリティを使用して、モデルを Estimator に変更します。次のコードは Estimator を作成してトレーニングする際に、このユーティリティをどのように使用するかを示します。 | def make_model():
return tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.02),
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.... | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
注意 : Keras で重み付きメトリクスを作成し、model_to_estimatorを使用してそれらを Estimator API で重み付きメトリクスを変換することはサポートされません。それらのメトリクスは、add_metrics関数を使用して Estimator 仕様で直接作成する必要があります。
カスタム model_fn を使用する
保守する必要がある既存のカスタム Estimator model_fn を持つ場合には、model_fnを変換して Keras モデルを使用できるようにすることが可能です。
しかしながら、互換性の理由から、カスタムmodel_fnは依然として1.x スタイルのグラフモードで動作します。これは... | def my_model_fn(features, labels, mode):
model = make_model()
optimizer = tf.compat.v1.train.AdamOptimizer()
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
training = (mode == tf.estimator.ModeKeys.TRAIN)
predictions = model(features, training=training)
if mode == tf.estimator.ModeK... | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
TensorFlow 2.x シンボルでmodel_fnをカスタマイズする
TensorFlow 1.x シンボルをすべて削除し、カスタムmodel_fn をネイティブの TensorFlow 2.x にアップグレードする場合は、オプティマイザとメトリクスをtf.keras.optimizersとtf.keras.metricsにアップグレードする必要があります。
カスタムmodel_fnでは、上記の変更に加えて、さらにアップグレードを行う必要があります。
v1.train.Optimizer の代わりに tf.keras.optimizers を使用します。
損失が呼び出し可能(関数など)な場合は、Optimizer.minim... | def my_model_fn(features, labels, mode):
model = make_model()
training = (mode == tf.estimator.ModeKeys.TRAIN)
loss_obj = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
predictions = model(features, training=training)
# Get both the unconditional losses (the None part)
# and the input-con... | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
事前作成された Estimator
tf.estimator.DNN*、tf.estimator.Linear*、 tf.estimator.DNNLinearCombined*のファミリーに含まれる事前作成された Estimator は、依然として TensorFlow 2.0 API でもサポートされていますが、一部の引数が変更されています。
input_layer_partitioner: v2 で削除されました。
loss_reduction: tf.compat.v1.losses.Reductionの代わりにtf.keras.losses.Reductionに更新されました。デフォルト値もtf.compat.v1.lo... | ! curl -O https://raw.githubusercontent.com/tensorflow/estimator/master/tensorflow_estimator/python/estimator/tools/checkpoint_converter.py | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
ツールにはヘルプが組み込まれています。 | ! python checkpoint_converter.py -h | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
<a id="tensorshape"></a>
TensorShape
このクラスはtf.compat.v1.Dimensionオブジェクトの代わりにintを保持することにより単純化されました。従って、.value()を呼び出してintを取得する必要はありません。
個々のtf.compat.v1.Dimensionオブジェクトは依然としてtf.TensorShape.dimsからアクセス可能です。
以下に TensorFlow 1.x と TensorFlow 2.x 間の違いを示します。 | # Create a shape and choose an index
i = 0
shape = tf.TensorShape([16, None, 256])
shape | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
TensorFlow 1.x で次を使っていた場合:
python
value = shape[i].value
Then do this in TensorFlow 2.x: | value = shape[i]
value | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
TensorFlow 1.x で次を使っていた場合:
python
for dim in shape: value = dim.value print(value)
TensorFlow 2.0 では次のようにします: | for value in shape:
print(value) | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
TensorFlow 1.x で次を使っていた場合(またはその他の次元のメソッドを使用していた場合):
python
dim = shape[i] dim.assert_is_compatible_with(other_dim)
TensorFlow 2.0 では次のようにします: | other_dim = 16
Dimension = tf.compat.v1.Dimension
if shape.rank is None:
dim = Dimension(None)
else:
dim = shape.dims[i]
dim.is_compatible_with(other_dim) # or any other dimension method
shape = tf.TensorShape(None)
if shape:
dim = shape.dims[i]
dim.is_compatible_with(other_dim) # or any other dimension meth... | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
tf.TensorShape のブール型の値は、階数がわかっている場合は Trueで、そうでない場合はFalseです。 | print(bool(tf.TensorShape([]))) # Scalar
print(bool(tf.TensorShape([0]))) # 0-length vector
print(bool(tf.TensorShape([1]))) # 1-length vector
print(bool(tf.TensorShape([None]))) # Unknown-length vector
print(bool(tf.TensorShape([1, 10, 100]))) # 3D tensor
print(bool(tf.TensorShape([None, None, None... | site/ja/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
Part 1: A toy example
Setup
Let's consider a toy 'neural network' consisting of two 'neurons' that map an input $x$ to an output $z$:
$$
y = f(w_1 x + b_1)
$$
$$
z = f(w_2 y + b_2)
$$
Here, $y$ is a vector (i.e. we have many 'hidden neurons'):
<img src="img/sketch.png" alt="sketch" width="200" align="middle"/>
For the ... | num_hidden = 5 # number of hidden neurons
x_linspace = np.linspace(0, 1, 100) # some input values
# A placeholder for the input (batch size unknown)
x = tf.placeholder(tf.float32, [None, 1], name='x')
# Our hidden neurons
w1 = tf.Variable(tf.random_normal([1, num_hidden], stddev=.1), name='w1... | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
Let's have a look | def target_funct(x):
return 4*(x - 0.5)**2 # our target function
# return 0.5*np.sin(4*np.pi*x) + 0.5 # another target function
# Plot network output against target function
plt.plot(x_linspace, z_out, label='NETWORK')
plt.plot(x_linspace, target_funct(x_linspace), label='TARGET')
plt.legend() | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
Backprop
Now we want to optimize. To do so, we need the derivatives of the loss $L = [z - t(x)]^2$ wrt. the parameters $w_1, b_1, w_2, b_2$. Let's start with the bias of our output neuron $z = f(w_2 y + b_2)$:
$$
\frac{dL}{db_2} = \frac{\partial L}{\partial z}\frac{dz}{db_2} = \frac{\partial L}{\partial z} f^\prime(w_2... | learning_rate = 1e-2 # learning rate
epochs = int(3e3) # number of epochs
batch_size = 128 # batch size
# target and loss
target = tf.placeholder(tf.float32, [None, 1], name='target')
loss = tf.reduce_mean(tf.square(z - target))
# optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
... | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
Loss | plt.plot(loss_storage, label='LOSS')
plt.legend(loc=0) | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
Let's have a look | plt.plot(x_linspace, z_out, label='NETWORK')
plt.plot(x_linspace, target_funct(x_linspace), label='TARGET')
plt.legend(loc=0) | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
Part 2: MNIST - what else? | # clear the tensorflow graph
tf.reset_default_graph() | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
Setup
Essentially, we use the same architecture as above. Differences:
* $28 \times 28 = 784$ inputs instead of a single one
* $10$ output neurons for the ten digits
* $300$ hidden neurons
* relu (hidden) and softmax (output) nonlinearity
* We use another optimizer
* We use another loss function (cross entropy)
Basical... | # tensorflow.examples.tutorials.mnist is deprecated
# Because it is useful we just suppress the warnings...
old_tf_verbosity = tf.logging.get_verbosity()
tf.logging.set_verbosity(tf.logging.ERROR)
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
... | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
Building the model | # input placeholder - for 28 x 28 pixels = 784
x = tf.placeholder(tf.float32, [None, 784])
# label placeholder - 10 digits
y = tf.placeholder(tf.float32, [None, 10])
# hidden layer
w1 = tf.Variable(tf.random_normal([784, 300], stddev=0.03), name='w1')
b1 = tf.Variable(tf.random_normal([300]), name='b1')
hidden_out = t... | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
Setting up the optimization | learning_rate = 0.5
# loss function
y_clipped = tf.clip_by_value(y_, 1e-10, 0.9999999) # needed for logarithm
cross_entropy = -tf.reduce_mean(tf.reduce_sum(
y * tf.log(y_clipped) + (1 - y) * tf.log(1 - y_clipped), axis=1))
# optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
tra... | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
Running it | epochs = 10
batch_size = 128
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
total_batch = int(len(mnist.train.labels) / batch_size)
loss_storage = np.empty(epochs)
for epoch in range(epochs):
avg_loss = 0.
for i in range(total_batch):
batch_x, batch_y... | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
Let's have a look | plt.plot(loss_storage, label='LOSS')
plt.legend(loc=0)
print("Final accuracy: {:.1f}%".format(100*final_acc)) | session11_Tensorflow/TensorFlow by example.ipynb | INM-6/Python-Module-of-the-Week | mit |
First, we will create a simple model structure | nlay, nrow, ncol = 10, 10, 10
perlen = np.zeros((10), dtype=np.float) + 10
nper = len(perlen)
ibound = np.ones((nlay,nrow,ncol), dtype=np.int)
botm = np.arange(-1,-11,-1)
top = 0. | examples/Notebooks/flopy3_multi-component_SSM.ipynb | mrustl/flopy | bsd-3-clause |
Create the MODFLOW packages | model_ws = 'data'
modelname = 'ssmex'
mf = modflow.Modflow(modelname, model_ws=model_ws)
dis = modflow.ModflowDis(mf, nlay=nlay, nrow=nrow, ncol=ncol,
perlen=perlen, nper=nper, botm=botm, top=top,
steady=False)
bas = modflow.ModflowBas(mf, ibound=ibound, strt=top)
lpf... | examples/Notebooks/flopy3_multi-component_SSM.ipynb | mrustl/flopy | bsd-3-clause |
We'll track the cell locations for the SSM data using the MODFLOW boundary conditions.
Get a dictionary (dict) that has the SSM itype for each of the boundary types. | itype = mt3d.Mt3dSsm.itype_dict()
print(itype)
print(mt3d.Mt3dSsm.get_default_dtype())
ssm_data = {} | examples/Notebooks/flopy3_multi-component_SSM.ipynb | mrustl/flopy | bsd-3-clause |
Add a general head boundary (ghb). The general head boundary head (bhead) is 0.1 for the first 5 stress periods with a component 1 (comp_1) concentration of 1.0 and a component 2 (comp_2) concentration of 100.0. Then bhead is increased to 0.25 and comp_1 concentration is reduced to 0.5 and comp_2 concentration is inc... | ghb_data = {}
print(modflow.ModflowGhb.get_default_dtype())
ghb_data[0] = [(4, 4, 4, 0.1, 1.5)]
ssm_data[0] = [(4, 4, 4, 1.0, itype['GHB'], 1.0, 100.0)]
ghb_data[5] = [(4, 4, 4, 0.25, 1.5)]
ssm_data[5] = [(4, 4, 4, 0.5, itype['GHB'], 0.5, 200.0)]
for k in range(nlay):
for i in range(nrow):
ghb_data[0].appe... | examples/Notebooks/flopy3_multi-component_SSM.ipynb | mrustl/flopy | bsd-3-clause |
Add an injection well. The injection rate (flux) is 10.0 with a comp_1 concentration of 10.0 and a comp_2 concentration of 0.0 for all stress periods. WARNING: since we changed the SSM data in stress period 6, we need to add the well to the ssm_data for stress period 6. | wel_data = {}
print(modflow.ModflowWel.get_default_dtype())
wel_data[0] = [(0, 4, 8, 10.0)]
ssm_data[0].append((0, 4, 8, 10.0, itype['WEL'], 10.0, 0.0))
ssm_data[5].append((0, 4, 8, 10.0, itype['WEL'], 10.0, 0.0)) | examples/Notebooks/flopy3_multi-component_SSM.ipynb | mrustl/flopy | bsd-3-clause |
Add the GHB and WEL packages to the mf MODFLOW object instance. | ghb = modflow.ModflowGhb(mf, stress_period_data=ghb_data)
wel = modflow.ModflowWel(mf, stress_period_data=wel_data) | examples/Notebooks/flopy3_multi-component_SSM.ipynb | mrustl/flopy | bsd-3-clause |
Create the MT3DMS packages | mt = mt3d.Mt3dms(modflowmodel=mf, modelname=modelname, model_ws=model_ws)
btn = mt3d.Mt3dBtn(mt, sconc=0, ncomp=2, sconc2=50.0)
adv = mt3d.Mt3dAdv(mt)
ssm = mt3d.Mt3dSsm(mt, stress_period_data=ssm_data)
gcg = mt3d.Mt3dGcg(mt) | examples/Notebooks/flopy3_multi-component_SSM.ipynb | mrustl/flopy | bsd-3-clause |
Let's verify that stress_period_data has the right dtype | print(ssm.stress_period_data.dtype) | examples/Notebooks/flopy3_multi-component_SSM.ipynb | mrustl/flopy | bsd-3-clause |
Create the SEAWAT packages | swt = seawat.Seawat(modflowmodel=mf, mt3dmodel=mt,
modelname=modelname, namefile_ext='nam_swt', model_ws=model_ws)
vdf = seawat.SeawatVdf(swt, mtdnconc=0, iwtable=0, indense=-1)
mf.write_input()
mt.write_input()
swt.write_input() | examples/Notebooks/flopy3_multi-component_SSM.ipynb | mrustl/flopy | bsd-3-clause |
And finally, modify the vdf package to fix indense. | fname = modelname + '.vdf'
f = open(os.path.join(model_ws, fname),'r')
lines = f.readlines()
f.close()
f = open(os.path.join(model_ws, fname),'w')
for line in lines:
f.write(line)
for kper in range(nper):
f.write("-1\n")
f.close()
| examples/Notebooks/flopy3_multi-component_SSM.ipynb | mrustl/flopy | bsd-3-clause |
Restart the kernel (Kernel > Restart kernel > Restart).
Re-run the above cell and proceed further.
Note: Please ignore any incompatibility warnings and errors.
Install TFDV
This will pull in all the dependencies, which will take a minute. Please ignore the warnings or errors regarding incompatible dependency versions. | import pandas as pd
import tensorflow_data_validation as tfdv
import sys
import warnings
warnings.filterwarnings('ignore')
print('Installing TensorFlow Data Validation')
!pip install -q tensorflow_data_validation[visualization] | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Load the Files
We will download our dataset from Google Cloud Storage. | import os
import tempfile, urllib, zipfile
# Set up some globals for our file paths
BASE_DIR = tempfile.mkdtemp()
DATA_DIR = os.path.join(BASE_DIR, 'data')
OUTPUT_DIR = os.path.join(BASE_DIR, 'chicago_taxi_output')
TRAIN_DATA = os.path.join(DATA_DIR, 'train', 'data.csv')
EVAL_DATA = os.path.join(DATA_DIR, 'eval', 'dat... | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Check the version | import tensorflow_data_validation as tfdv
print('TFDV version: {}'.format(tfdv.version.__version__)) | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Compute and visualize statistics
First we'll use tfdv.generate_statistics_from_csv to compute statistics for our training data. (ignore the snappy warnings)
TFDV can compute descriptive statistics that provide a quick overview of the data in terms of the features that are present and the shapes of their value distribut... | # Compute data statistics from CSV files.
# TODO: Your code goes here
| courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Now let's use tfdv.visualize_statistics, which uses Facets to create a succinct visualization of our training data:
Notice that numeric features and categorical features are visualized separately, and that charts are displayed showing the distributions for each feature.
Notice that features with missing or zero values... | # Visualize the input statistics using Facets.
# TODO: Your code goes here
| courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Infer a schema
Now let's use tfdv.infer_schema to create a schema for our data. A schema defines constraints for the data that are relevant for ML. Example constraints include the data type of each feature, whether it's numerical or categorical, or the frequency of its presence in the data. For categorical features t... | # Infers schema from the input statistics.
# TODO: Your code goes here
tfdv.display_schema(schema=schema) | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Check evaluation data for errors
So far we've only been looking at the training data. It's important that our evaluation data is consistent with our training data, including that it uses the same schema. It's also important that the evaluation data includes examples of roughly the same ranges of values for our numeri... | # Compute stats for evaluation data
eval_stats = tfdv.generate_statistics_from_csv(data_location=EVAL_DATA)
# Compare evaluation data with training data
tfdv.visualize_statistics(lhs_statistics=eval_stats, rhs_statistics=train_stats,
lhs_name='EVAL_DATASET', rhs_name='TRAIN_DATASET') | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Check for evaluation anomalies
Does our evaluation dataset match the schema from our training dataset? This is especially important for categorical features, where we want to identify the range of acceptable values.
Key Point: What would happen if we tried to evaluate using data with categorical feature values that we... | # Check eval data for errors by validating the eval data stats using the previously inferred schema.
# TODO: Your code goes here
tfdv.display_anomalies(anomalies) | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Fix evaluation anomalies in the schema
Oops! It looks like we have some new values for company in our evaluation data, that we didn't have in our training data. We also have a new value for payment_type. These should be considered anomalies, but what we decide to do about them depends on our domain knowledge of the ... | # Relax the minimum fraction of values that must come from the domain for feature company.
company = tfdv.get_feature(schema, 'company')
company.distribution_constraints.min_domain_mass = 0.9
# Add new value to the domain of feature payment_type.
payment_type_domain = tfdv.get_domain(schema, 'payment_type')
payment_ty... | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Hey, look at that! We verified that the training and evaluation data are now consistent! Thanks TFDV ;)
Schema Environments
We also split off a 'serving' dataset for this example, so we should check that too. By default all datasets in a pipeline should use the same schema, but there are often exceptions. For exampl... | serving_stats = tfdv.generate_statistics_from_csv(SERVING_DATA)
serving_anomalies = tfdv.validate_statistics(serving_stats, schema)
tfdv.display_anomalies(serving_anomalies) | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
We'll deal with the tips feature below. We also have an INT value in our trip seconds, where our schema expected a FLOAT. By making us aware of that difference, TFDV helps uncover inconsistencies in the way the data is generated for training and serving. It's very easy to be unaware of problems like that until model p... | options = tfdv.StatsOptions(schema=schema, infer_type_from_schema=True)
serving_stats = tfdv.generate_statistics_from_csv(SERVING_DATA, stats_options=options)
serving_anomalies = tfdv.validate_statistics(serving_stats, schema)
tfdv.display_anomalies(serving_anomalies) | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Now we just have the tips feature (which is our label) showing up as an anomaly ('Column dropped'). Of course we don't expect to have labels in our serving data, so let's tell TFDV to ignore that. | # All features are by default in both TRAINING and SERVING environments.
schema.default_environment.append('TRAINING')
schema.default_environment.append('SERVING')
# Specify that 'tips' feature is not in SERVING environment.
tfdv.get_feature(schema, 'tips').not_in_environment.append('SERVING')
serving_anomalies_with_... | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Check for drift and skew
In addition to checking whether a dataset conforms to the expectations set in the schema, TFDV also provides functionalities to detect drift and skew. TFDV performs this check by comparing the statistics of the different datasets based on the drift/skew comparators specified in the schema.
Dri... | # Add skew comparator for 'payment_type' feature.
payment_type = tfdv.get_feature(schema, 'payment_type')
payment_type.skew_comparator.infinity_norm.threshold = 0.01
# Add drift comparator for 'company' feature.
company=tfdv.get_feature(schema, 'company')
company.drift_comparator.infinity_norm.threshold = 0.001
# TOD... | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
In this example we do see some drift, but it is well below the threshold that we've set.
Freeze the schema
Now that the schema has been reviewed and curated, we will store it in a file to reflect its "frozen" state. | from tensorflow.python.lib.io import file_io
from google.protobuf import text_format
file_io.recursive_create_dir(OUTPUT_DIR)
schema_file = os.path.join(OUTPUT_DIR, 'schema.pbtxt')
tfdv.write_schema_text(schema, schema_file)
!cat {schema_file} | courses/machine_learning/deepdive2/production_ml/labs/tfdv_advanced_taxi.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Getting the data ready for work
If the data is in GSLIB format you can use the function pygslib.gslib.read_gslib_file(filename) to import the data into a Pandas DataFrame. | #get the data in gslib format into a pandas Dataframe
cluster= pygslib.gslib.read_gslib_file('../data/cluster.dat')
true= pygslib.gslib.read_gslib_file('../data/true.dat')
true['Declustering Weight'] = 1
| pygslib/Ipython_templates/qqplt_html.ipynb | opengeostat/pygslib | mit |
QQ-Plot | npoints = len(cluster['Primary'])
true['Declustering Weight'] = 1
#using declustering wight
parameters_qpplt = {
# gslib parameters for qq-pp calculation
'qqorpp': 0, # integer (Optional, default 0, Q-Q plot). Q-Q plot (qqorpp=0); P-P plot (qqorpp=1)
#'npts' : None, # integer (Optional, default min len... | pygslib/Ipython_templates/qqplt_html.ipynb | opengeostat/pygslib | mit |
Число вариантов быстро растёт. Для строки "a x 10", парсер переберёт 89 разборов. Для "a x 20" — 979 и потратит заметное количество времени.
При работе с естественным русским языком, мы построянно сталкиваемся с неоднозначными грамматиками. Например, список из трёх взысканий по арбиражному делу: "5 тыс. р. штраф пени 3... | class TooManyStates(Exception): pass
def capped(method):
def wrap(self, column, *args):
before = len(column.states)
method(self, column, *args)
after = len(column.states)
self.states += (after - before)
if self.cap and self.states > self.cap:
raise TooManyState... | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Порядок аргументов в or_ имеет значение
Когда разборов больше одного, парсер возвращает самый левый вариант: | A = or_(
rule('a'),
rule('a', 'a')
)
B = A.repeatable()
parser = Parser(B)
match = parser.match('a a a')
match.tree.as_dot | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Переставим местами a a и a, результат поменяется: | A = or_(
rule('a', 'a'),
rule('a')
)
B = A.repeatable()
parser = Parser(B)
match = parser.match('a a a')
match.tree.as_dot | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
На практике это важно. В примере со взыскиниями грамматика:
PENALTY -> MONEY TYPE | TYPE MONEY | MONEY | TYPE
Левый разбор, не то, что ожидалось:
(5 тыс. р. штраф) (пени 3 тыс. р.) (необоснованного обогащения)`
Переставим аргументы:
PENALTY -> MONEY TYPE | TYPE | TYPE MONEY | MONEY
Получим:
(5 тыс. р. штраф) (пе... | from yargy.tokenizer import (
Tokenizer,
MorphTokenizer,
EOL
)
# Стандартный токенизатор. Удаляем правило для переводом строк.
# Обычно токены с '\n' только мешаются.
TOKENIZER = MorphTokenizer().remove_types(EOL)
class IdTokenizer(Tokenizer):
def __init__(self, tokenizer):
self.tokenizer = ... | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
ValueError: no .interpretation(...) for root rule
Есть два правила, хотим найти факты, где сработало одно из них: | from yargy.interpretation import fact
F = fact('F', ['a'])
G = fact('G', ['b'])
A = rule('a').interpretation(F.a).interpretation(F)
B = rule('b').interpretation(G.b).interpretation(G)
C = or_(A, B)
parser = Parser(C)
match = parser.match('a')
# match.fact ValueError | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Ожидаем F(a='a'), получаем ValueError: no .interpretation(...) for root rule. На вершине-корне нет пометки контруктора факта: | C.as_dot | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Создадим прокси-факт: | Proxy = fact('Proxy', ['value'])
C = or_(A, B).interpretation(Proxy.value).interpretation(Proxy)
display(C.as_dot)
parser = Parser(C)
match = parser.match('a')
match.fact.value
| docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
TypeError: mixed types
Набор аргументов or_ бывает двух видов:
1. Все предикаты, тогда результат — предикат
2. Все rule, тогда результат — rule
Иногда правило состоит из одного предиката, передаём его в or_, получаем ошибку: | from yargy.predicates import caseless
A = rule('a')
B = caseless('b')
# or_(A, B) # TypeError: mixed types: [<class 'yargy.rule.constructors.Rule'>, <class 'yargy.predicates.bank.eq'>] | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Явно завернём предикат в rule: | B = rule(caseless('b'))
C = or_(A, B) | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Машинное обучение и Yargy
Есть текст размеченный BIO-тегами: | text = '15 апреля в Симферополе Леонид Рожков ...'
tags = 'B I O B B I O'.split() | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Parser принимает необязательный аргумент tagger: Parser(RULE, tagger=Tagger). Tagger принимает и возвращает список токенов. Добавим внешнюю разметку tags в токены. Используем предикат tag, извлечём сущности: | from yargy.tagger import Tagger
from yargy.predicates import tag
class Tagger(Tagger):
# Все возможные теги. Используется при инициализации предиката tag.
# Если пользователь создаст tag('FOO'), будет ошибка
tags = {'B', 'I', 'O'}
def __call__(self, tokens):
for token, tag in zip(tokens, tags... | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Пропустить часть текста
Есть текст "взыскать 5 тыс. р. штрафа, а также пени и неустойку". Нужно выделить 3 взыскания "5 тыс. р. штраф", "пени", "неустойка", пропустить подстроки ", а также", "и". Запустить парсер 2 раза: сначала выделим взыскания, удалим лишние токены, запустим парсер ещё раз: | from yargy.pipelines import morph_pipeline
text = 'взыскать 5 тыс. р. штрафа, а также пени и неустойку'
tokens = list(TOKENIZER(text))
PAYMENT = morph_pipeline([
'5 тыс. р. штраф',
'пени',
'неустойка'
])
parser = Parser(PAYMENT, tokenizer=ID_TOKENIZER)
matches = parser.findall(tokens)
spans = [_.span fo... | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Генерация правил
В Yargy все правила описываются на языке Python. Создадим функцию, которая генерирует правило. Например, правило для текста в скобочка и кавычках: | from yargy import not_
from yargy.predicates import eq
def bounded(start, stop):
return rule(
eq(start),
not_(eq(stop)).repeatable(),
eq(stop)
)
BOUNDED = or_(
bounded('[', ']'),
bounded('«', '»')
)
parser = Parser(BOUNDED)
matches = parser.findall('[a b] {c d} «e f»')
for ma... | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Правило — аналог join в Python: | from yargy.predicates import in_
def joined(ITEM, SEP):
return rule(
ITEM,
rule(
SEP,
ITEM
).repeatable().optional()
)
SEP = in_(',;')
JOINED = joined(BOUNDED, SEP)
parser = Parser(JOINED)
match = parser.match('[a b], [c d], [e f g]') | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Правило для BIO-разметки: | def bio(type):
return rule(
tag('B-%s' % type),
tag('I-%s' % type).repeatable().optional()
)
PER = bio('PER')
LOC = bio('LOC')
text = '15 апреля в Симферополе Леонид Рожков ...'
tags = 'B-DATE I-DATE O B-LOC B-PER I-PER O'.split()
class Tagger(Tagger):
tags = {'B-PER', 'I-PER', 'B-LOC'... | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Генерация pipeline
Создадим pipeline из словаря пар "полное название", "сокращение": | from yargy.pipelines import (
morph_pipeline,
pipeline
)
from yargy import interpretation as interp
TYPES = [
('Общество с ограниченной ответственностью', 'ООО'),
('Акционерное общество', 'АО'),
('Страховая компания', 'СК'),
('Строительная компания', 'СК')
]
TYPE = or_(
morph_pipeline([
... | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Наследование fact
fact создаёт Python-класс, отнаследуемся, добавим методы и атрибуты. Например, есть ссылка на статьи "ст. 15-17 п.1", результат список объектов Ref(art=15, punkt=1), Ref(art=16, punkt=1), ...: | from collections import namedtuple
from yargy.predicates import type
Ref_ = namedtuple(
'Ref',
['art', 'punkt']
)
Art = fact(
'Art',
['start', 'stop']
)
class Art(Art):
def range(self):
if self.stop:
return range(self.start, self.stop + 1)
else:
return [s... | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Есть периоды "1917-1918г.", "21 век", приведём их к единому формату: Period(1917, 1919), Period(2000, 2100). | Period_ = namedtuple('Period', ['start', 'stop'])
Year = fact(
'Year',
['value']
)
class Year(Year):
@property
def normalized(self):
return Period_(self.value, self.value + 1)
YearRange = fact(
'YearRange',
['start', 'stop']
)
class YearRange(YearRange):
@property
def normali... | docs/cookbook.ipynb | bureaucratic-labs/yargy | mit |
Sorting
Q1. Sort x along the second axis. | x = np.array([[1,4],[3,1]])
out = np.sort(x, axis=1)
x.sort(axis=1)
assert np.array_equal(out, x)
print out | numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Q2. Sort pairs of surnames and first names and return their indices. (first by surname, then by name). | surnames = ('Hertz', 'Galilei', 'Hertz')
first_names = ('Heinrich', 'Galileo', 'Gustav')
print np.lexsort((first_names, surnames)) | numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Q3. Get the indices that would sort x along the second axis. | x = np.array([[1,4],[3,1]])
out = np.argsort(x, axis=1)
print out | numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Q4. Create an array such that its fifth element would be the same as the element of sorted x, and it divide other elements by their value. | x = np.random.permutation(10)
print "x =", x
print "\nCheck the fifth element of this new array is 5, the first four elements are all smaller than 5, and 6th through the end are bigger than 5\n",
out = np.partition(x, 5)
x.partition(5) # in-place equivalent
assert np.array_equal(x, out)
print out
| numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Q5. Create the indices of an array such that its third element would be the same as the element of sorted x, and it divide other elements by their value. | x = np.random.permutation(10)
print "x =", x
partitioned = np.partition(x, 3)
indices = np.argpartition(x, 3)
print "partitioned =", partitioned
print "indices =", partitioned
assert np.array_equiv(x[indices], partitioned) | numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Searching
Q6. Get the maximum and minimum values and their indices of x along the second axis. | x = np.random.permutation(10).reshape(2, 5)
print "x =", x
print "maximum values =", np.max(x, 1)
print "max indices =", np.argmax(x, 1)
print "minimum values =", np.min(x, 1)
print "min indices =", np.argmin(x, 1)
| numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Q7. Get the maximum and minimum values and their indices of x along the second axis, ignoring NaNs. | x = np.array([[np.nan, 4], [3, 2]])
print "maximum values ignoring NaNs =", np.nanmax(x, 1)
print "max indices =", np.nanargmax(x, 1)
print "minimum values ignoring NaNs =", np.nanmin(x, 1)
print "min indices =", np.nanargmin(x, 1) | numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Q8. Get the values and indices of the elements that are bigger than 2 in x. | x = np.array([[1, 2, 3], [1, 3, 5]])
print "Values bigger than 2 =", x[x>2]
print "Their indices are ", np.nonzero(x > 2)
assert np.array_equiv(x[x>2], x[np.nonzero(x > 2)])
assert np.array_equiv(x[x>2], np.extract(x > 2, x)) | numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Q9. Get the indices of the elements that are bigger than 2 in the flattend x. | x = np.array([[1, 2, 3], [1, 3, 5]])
print np.flatnonzero(x)
assert np.array_equiv(np.flatnonzero(x), x.ravel().nonzero()) | numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Q10. Check the elements of x and return 0 if it is less than 0, otherwise the element itself. | x = np.arange(-5, 4).reshape(3, 3)
print np.where(x <0, 0, x) | numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Q11. Get the indices where elements of y should be inserted to x to maintain order. | x = [1, 3, 5, 7, 9]
y = [0, 4, 2, 6]
np.searchsorted(x, y) | numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
Counting
Q12. Get the number of nonzero elements in x. | x = [[0,1,7,0,0],[3,0,0,2,19]]
print np.count_nonzero(x)
assert np.count_nonzero(x) == len(x[x!=0]) | numpy/numpy_exercises_from_kyubyong/Sorting_searching_and_counting_Solutions.ipynb | mohanprasath/Course-Work | gpl-3.0 |
ConsIndShockModel assumes that income has a permanent component $p$ which is subject to "permanent" shocks:
$\log p_{t+1} = \log p_{t} + \log \psi_{t+1}$
Many papers in the literature instead examine models in which shocks merely have some persistence,
$\log p_{t+1} = \gamma \log p_{t} + \log \psi_{t+1}$
where if $0 < ... | # This cell defines a dictionary to make an instance of "explicit permanent income" consumer.
GenIncDictionary = {
"CRRA": 2.0, # Coefficient of relative risk aversion
"Rfree": 1.03, # Interest factor on assets
"DiscFac": 0.96, # Inter... | examples/GenIncProcessModel/GenIncProcessModel.ipynb | econ-ark/HARK | apache-2.0 |
Let's now create an instance of the type of consumer we are interested in and solve this agent's problem with an infinite horizon (cycles=0). | # Make and solve an example "explicit permanent income" consumer with idiosyncratic shocks
ExplicitExample = IndShockExplicitPermIncConsumerType(**GenIncDictionary)
print('Here, the lowest percentile is ' + str(GenIncDictionary['pLvlPctiles'][0]*100))
print('and the highest perc... | examples/GenIncProcessModel/GenIncProcessModel.ipynb | econ-ark/HARK | apache-2.0 |
In the cell below, we generate a plot of the consumption function for explicit permanent income consumer at different income levels. | # Plot the consumption function at various permanent income levels.
print('Consumption function by pLvl for explicit permanent income consumer:')
pLvlGrid = ExplicitExample.pLvlGrid[0]
mLvlGrid = np.linspace(0,20,300)
for p in pLvlGrid:
M_temp = mLvlGrid + ExplicitExample.solution[0].mLvlMin(p)
C = ExplicitExam... | examples/GenIncProcessModel/GenIncProcessModel.ipynb | econ-ark/HARK | apache-2.0 |
Permanent income normalized
An alternative model is to normalize it by dividing all variables by permanent income $p_t$ and solve the model again. | # Make and solve an example of normalized model
NormalizedExample = IndShockConsumerType(**GenIncDictionary, verbose=0)
NormalizedExample.solve()
# Compare the normalized problem with and without explicit permanent income and plot the consumption functions
print('Normalized consumption function by pLvl for explicit pe... | examples/GenIncProcessModel/GenIncProcessModel.ipynb | econ-ark/HARK | apache-2.0 |
The figures above show that the normalized consumption function for the "explicit permanent income" consumer is almost identical for every permanent income level (and the same as the normalized problem's $\texttt{cFunc}$), but is less accurate due to extrapolation outside the bounds of $\texttt{pLvlGrid}$.
The "explic... | # Plot the value function at various permanent income levels
if ExplicitExample.vFuncBool:
pGrid = np.linspace(0.1,3.0,24)
M = np.linspace(0.001,5,300)
for p in pGrid:
M_temp = M+ExplicitExample.solution[0].mLvlMin(p)
C = ExplicitExample.solution[0].vFunc(M_temp,p*np.ones_like(M_temp))
... | examples/GenIncProcessModel/GenIncProcessModel.ipynb | econ-ark/HARK | apache-2.0 |
2. Persistent income shock consumer
Class to solve consumption-saving models with idiosyncratic shocks to income in which shocks are persistent and transitory. This model extends ConsGenIndShockModel by allowing (log) persistent income to follow an AR(1) process.
The agent's problem can be written in Bellman form as:
\... | # Make a dictionary for the "persistent idiosyncratic shocks" model
PrstIncCorr = 0.98 # Serial correlation coefficient for persistent income
persistent_shocks = copy(GenIncDictionary)
persistent_shocks['PrstIncCorr'] = PrstIncCorr | examples/GenIncProcessModel/GenIncProcessModel.ipynb | econ-ark/HARK | apache-2.0 |
The PersistentShockConsumerType class solves the problem of a consumer facing idiosyncratic shocks to his persistent and transitory income, and for which the (log) persistent income follows an AR1 process rather than random walk. | # Make and solve an example of "persistent idisyncratic shocks" consumer
PersistentExample = PersistentShockConsumerType(**persistent_shocks)
PersistentExample.solve()
# Plot the consumption function at various levels of persistent income pLvl
print('Consumption function by persistent income level pLvl for a consumer ... | examples/GenIncProcessModel/GenIncProcessModel.ipynb | econ-ark/HARK | apache-2.0 |
モデルの平均化
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/addons/tutorials/average_optimizers_callback"><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/git... | !pip install -U tensorflow-addons
import tensorflow as tf
import tensorflow_addons as tfa
import numpy as np
import os | site/ja/addons/tutorials/average_optimizers_callback.ipynb | tensorflow/docs-l10n | apache-2.0 |
モデルを構築する | def create_model(opt):
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimi... | site/ja/addons/tutorials/average_optimizers_callback.ipynb | tensorflow/docs-l10n | apache-2.0 |
データセットを準備する | #Load Fashion MNIST dataset
train, test = tf.keras.datasets.fashion_mnist.load_data()
images, labels = train
images = images/255.0
labels = labels.astype(np.int32)
fmnist_train_ds = tf.data.Dataset.from_tensor_slices((images, labels))
fmnist_train_ds = fmnist_train_ds.shuffle(5000).batch(32)
test_images, test_labels... | site/ja/addons/tutorials/average_optimizers_callback.ipynb | tensorflow/docs-l10n | apache-2.0 |
ここでは、次の 3 つのオプティマイザを比較してみます。
ラップされていない SGD
移動平均を適用した SGD
確率的重み平均を適用した SGD
同じモデルを使用してパフォーマンスを見てみましょう。 | #Optimizers
sgd = tf.keras.optimizers.SGD(0.01)
moving_avg_sgd = tfa.optimizers.MovingAverage(sgd)
stocastic_avg_sgd = tfa.optimizers.SWA(sgd) | site/ja/addons/tutorials/average_optimizers_callback.ipynb | tensorflow/docs-l10n | apache-2.0 |
MovingAverageオプティマイザとStocasticAverageオプティマイザは、どちらもModelAverageCheckpointを使用します。 | #Callback
checkpoint_path = "./training/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_dir,
save_weights_only=True,
verbose=1)
... | site/ja/addons/tutorials/average_optimizers_callback.ipynb | tensorflow/docs-l10n | apache-2.0 |
モデルをトレーニングする
Vanilla SGD オプティマイザ | #Build Model
model = create_model(sgd)
#Train the network
model.fit(fmnist_train_ds, epochs=5, callbacks=[cp_callback])
#Evalute results
model.load_weights(checkpoint_dir)
loss, accuracy = model.evaluate(test_images, test_labels, batch_size=32, verbose=2)
print("Loss :", loss)
print("Accuracy :", accuracy) | site/ja/addons/tutorials/average_optimizers_callback.ipynb | tensorflow/docs-l10n | apache-2.0 |
移動平均 SGD | #Build Model
model = create_model(moving_avg_sgd)
#Train the network
model.fit(fmnist_train_ds, epochs=5, callbacks=[avg_callback])
#Evalute results
model.load_weights(checkpoint_dir)
loss, accuracy = model.evaluate(test_images, test_labels, batch_size=32, verbose=2)
print("Loss :", loss)
print("Accuracy :", accuracy... | site/ja/addons/tutorials/average_optimizers_callback.ipynb | tensorflow/docs-l10n | apache-2.0 |
確率的重み平均 SGD | #Build Model
model = create_model(stocastic_avg_sgd)
#Train the network
model.fit(fmnist_train_ds, epochs=5, callbacks=[avg_callback])
#Evalute results
model.load_weights(checkpoint_dir)
loss, accuracy = model.evaluate(test_images, test_labels, batch_size=32, verbose=2)
print("Loss :", loss)
print("Accuracy :", accur... | site/ja/addons/tutorials/average_optimizers_callback.ipynb | tensorflow/docs-l10n | apache-2.0 |
Hierarchical Non-Linear Regression Models in PyMC3: Part II
This is a follow up to a previous post, extending to the case where we have nonlinear responces.
First, some data | colors = ['r', 'g', 'b']
N_cars = 3
N_sightings = 10
idxs = np.array([0, 0, 0, 1, 1, 1, 1, 1, 2, 2])
a_val = 45
mu_b_val = 0.1
sigma_b_val = 3
mu_c_val = 0.5
sigma_c_val = 0.5
b = np.random.normal(mu_b_val, sigma_b_val, N_cars)
c = np.random.normal(mu_c_val, sigma_c_val, N_cars)
xobs = np.random.uniform(0, 10, N_sigh... | _notebooks/2015-12-03-Hierarchical-NonLinear-Regression-Models-In-PyMC3.ipynb | ga7g08/ga7g08.github.io | mit |
The clever bit:
In the following code we flatten the data, but create a set of indexes which maps the responces to the respondant. For example if our data data consisted of 2 repondants, with 3 responces from the first and 2 from the second, then the data above would be:
xobs_stacked = [[1.1, 2.2, 4.5],
... | with pm.Model() as hierarchical_model:
# hyperparameters
mu_b = pm.Normal('mu_b', mu=0., sd=100)
sigma_b = pm.Uniform('sigma_b', lower=0, upper=100)
mu_c = pm.Normal('mu_c', mu=0., sd=100)
sigma_c = pm.Uniform('sigma_c', lower=0, upper=100)
# Common effects
a = pm.Normal('a', mu=45, sd=100,... | _notebooks/2015-12-03-Hierarchical-NonLinear-Regression-Models-In-PyMC3.ipynb | ga7g08/ga7g08.github.io | mit |
Now we generate samples using the Metropolis algorithm. Note that in some of the linked examples they initiate the MCMC chains with a MLE. I found that this degraded the performance, but I don't have the time to figure out why at the moment. | nsamples = 40000
nburn = 10000
with hierarchical_model:
step = pm.Metropolis()
hierarchical_trace = pm.sample(nsamples, step, progressbar=True) | _notebooks/2015-12-03-Hierarchical-NonLinear-Regression-Models-In-PyMC3.ipynb | ga7g08/ga7g08.github.io | mit |
Now let's use the handy traceplot to inspect the chains and the posteriors having discarded the first half of the samples. | pm.traceplot(hierarchical_trace[30000:],
vars=['mu_b', 'mu_c', 'a', 'eps'],
#lines={'mu_b': mu_b_val, 'sigma_b': sigma_b_val}
)
plt.show() | _notebooks/2015-12-03-Hierarchical-NonLinear-Regression-Models-In-PyMC3.ipynb | ga7g08/ga7g08.github.io | mit |
The posterior distributions (in blue) can be compared with vertical (red) lines indicating the "true" values used to generate the data. This shows that we have not fully captured the features of the model, but compared to the diffuse prior we have learnt a great deal. Note that in generating the data $\epsilon$ was eff... | s['b']
npp = 5
repeats = 100
fig, ax = plt.subplots(figsize=(10, 10))
xfit = np.linspace(-1, 10, 100)
for i in range(N_cars):
for j in range(repeats):
s = hierarchical_trace[np.random.randint(nburn, nsamples)]
yfit = s['a'] + s['b'][i] * xfit+ s['c'][i] * xfit**2
ax.plot(xfit, yfit, "-",... | _notebooks/2015-12-03-Hierarchical-NonLinear-Regression-Models-In-PyMC3.ipynb | ga7g08/ga7g08.github.io | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.