markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
<a id="keras_metric_names"></a>
์ผ๋ผ์ค ์งํ ์ด๋ฆ
ํ
์ํ๋ก 2.0์์ ์ผ๋ผ์ค ๋ชจ๋ธ์ ์งํ ์ด๋ฆ์ ๋ ์ผ๊ด์ฑ์๊ฒ ์ฒ๋ฆฌํฉ๋๋ค.
์งํ๋ฅผ ๋ฌธ์์ด๋ก ์ ๋ฌํ๋ฉด ์ ํํ ๊ฐ์ ๋ฌธ์์ด์ด ์งํ์ name์ผ๋ก ์ฌ์ฉ๋ฉ๋๋ค. model.fit ๋ฉ์๋๊ฐ ๋ฐํํ๋ ํ์คํ ๋ฆฌ(history) ๊ฐ์ฒด์ keras.callbacks๋ก ์ ๋ฌํ๋ ๋ก๊ทธ์ ๋ํ๋๋ ์ด๋ฆ์ด ์งํ๋ก ์ ๋ฌํ ๋ฌธ์์ด์ด ๋ฉ๋๋ค. | model.compile(
optimizer = tf.keras.optimizers.Adam(0.001),
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics = ['acc', 'accuracy', tf.keras.metrics.SparseCategoricalAccuracy(name="my_accuracy")])
history = model.fit(train_data)
history.history.keys() | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ด์ ๋ฒ์ ์ ์ด์ ๋ค๋ฅด๊ฒ metrics=["accuracy"]๋ฅผ ์ ๋ฌํ๋ฉด dict_keys(['loss', 'acc'])๊ฐ ๋ฉ๋๋ค.
์ผ๋ผ์ค ์ตํฐ๋ง์ด์
v1.train.AdamOptimizer๋ v1.train.GradientDescentOptimizer ๊ฐ์ v1.train์ ์๋ ์ตํฐ๋ง์ด์ ๋ tf.keras.optimizers์ ์๋ ๊ฒ๊ณผ ๋์ผํฉ๋๋ค.
v1.train์ keras.optimizers๋ก ๋ฐ๊พธ๊ธฐ
๋ค์์ ์ตํฐ๋ง์ด์ ๋ฅผ ๋ฐ๊ฟ ๋ ์ ๋
ํด์ผ ํ ๋ด์ฉ์
๋๋ค:
์ตํฐ๋ง์ด์ ๋ฅผ ์
๊ทธ๋ ์ด๋ํ๋ฉด ์์ ์ฒดํฌํฌ์ธํธ์ ํธํ์ด๋์ง ์์ ์ ์์ต๋๋ค.
์
์ค๋ก ๋งค๊ฐ๋ณ์ ๊ธฐ๋ณธ๊ฐ์ ๋ชจ๋... | def wrap_frozen_graph(graph_def, inputs, outputs):
def _imports_graph_def():
tf.compat.v1.import_graph_def(graph_def, name="")
wrapped_import = tf.compat.v1.wrap_function(_imports_graph_def, [])
import_graph = wrapped_import.graph
return wrapped_import.prune(
tf.nest.map_structure(import_graph.as_grap... | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
์๋ฅผ ๋ค์ด 2016๋
Inception v1์ ๋๊ฒฐ๋ ๊ทธ๋ํ์
๋๋ค: | path = tf.keras.utils.get_file(
'inception_v1_2016_08_28_frozen.pb',
'http://storage.googleapis.com/download.tensorflow.org/models/inception_v1_2016_08_28_frozen.pb.tar.gz',
untar=True) | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
tf.GraphDef๋ฅผ ๋ก๋ํฉ๋๋ค: | graph_def = tf.compat.v1.GraphDef()
loaded = graph_def.ParseFromString(open(path,'rb').read()) | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
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/ko/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/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ถ์ ๊ธฐ
์ถ์ ๊ธฐ๋ก ํ๋ จํ๊ธฐ
ํ
์ํ๋ก 2.0์ ์ถ์ ๊ธฐ(estimator)๋ฅผ ์ง์ํฉ๋๋ค.
์ถ์ ๊ธฐ๋ฅผ ์ฌ์ฉํ ๋ ํ
์ํ๋ก 1.x์ input_fn(), tf.estimator.TrainSpec, tf.estimator.EvalSpec๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค.
๋ค์์ input_fn์ ์ฌ์ฉํ์ฌ ํ๋ จ๊ณผ ํ๊ฐ๋ฅผ ์ํํ๋ ์์
๋๋ค.
input_fn๊ณผ ํ๋ จ/ํ๊ฐ ์คํ ๋ง๋ค๊ธฐ | # ์ถ์ ๊ธฐ 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
return i... | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ผ๋ผ์ค ๋ชจ๋ธ ์ ์ ์ฌ์ฉํ๊ธฐ
ํ
์ํ๋ก 2.0์์ ์ถ์ ๊ธฐ๋ฅผ ๊ตฌ์ฑํ๋ ๋ฐฉ๋ฒ์ ์กฐ๊ธ ๋ค๋ฆ
๋๋ค.
์ผ๋ผ์ค๋ฅผ ์ฌ์ฉํ์ฌ ๋ชจ๋ธ์ ์ ์ํ๋ ๊ฒ์ ๊ถ์ฅํฉ๋๋ค. ๊ทธ ๋ค์ tf.keras.model_to_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/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋
ธํธ: ์ผ๋ผ์ค์์๋ ๊ฐ์ค์น๊ฐ ์ ์ฉ๋ ์งํ๋ฅผ ์ง์ํ์ง ์์ต๋๋ค. model_to_estimator๋ฅผ ์ฌ์ฉํด ์ถ์ ๊ธฐ API์ ๊ฐ์ค ์งํ๋ก ๋ณ๊ฒฝํ ์ ์์ต๋๋ค. add_metrics ํจ์๋ฅผ ์ฌ์ฉํด ์ถ์ ๊ธฐ ์คํ(spec)์ ์ง์ ์ด๋ฐ ์งํ๋ฅผ ๋ง๋ค์ด์ผ ํฉ๋๋ค.
์ฌ์ฉ์ ์ ์ model_fn ์ฌ์ฉํ๊ธฐ
๊ธฐ์กด์ ์์ฑํ ์ฌ์ฉ์ ์ ์ ์ถ์ ๊ธฐ model_fn์ ์ ์งํด์ผ ํ๋ค๋ฉด ์ด model_fn์ ์ผ๋ผ์ค ๋ชจ๋ธ๋ก ๋ฐ๊ฟ ์ ์์ต๋๋ค.
๊ทธ๋ฌ๋ ํธํ์ฑ ๋๋ฌธ์ ์ฌ์ฉ์ ์ ์ model_fn์ 1.x ์คํ์ผ์ ๊ทธ๋ํ ๋ชจ๋๋ก ์คํ๋ ๊ฒ์
๋๋ค. ์ฆ ์ฆ์ ์คํ๊ณผ ์์กด์ฑ ์๋ ์ ์ด๊ฐ ์๋ค๋ ๋ป์
๋๋ค.
<a ... | 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/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
TF 2.0์ผ๋ก ์ฌ์ฉ์ ์ ์ model_fn ๋ง๋ค๊ธฐ
์ฌ์ฉ์ ์ ์ model_fn์์ TF 1.x API๋ฅผ ๋ชจ๋ ์ ๊ฑฐํ๊ณ TF 2.0์ผ๋ก ์
๊ทธ๋ ์ด๋ํ๋ ค๋ฉด ์ตํฐ๋ง์ด์ ์ ์งํ๋ฅผ tf.keras.optimizers์ tf.keras.metrics๋ก ์
๋ฐ์ดํธํด์ผ ํฉ๋๋ค.
์์์ ์ธ๊ธํ ์ต์ํ์ ๋ณ๊ฒฝ์ธ์๋ ์ฌ์ฉ์ ์ ์ model_fn์์ ์
๊ทธ๋ ์ด๋ํด์ผ ํ ๊ฒ์ด ์์ต๋๋ค:
v1.train.Optimizer ๋์ ์ tf.keras.optimizers์ ์ฌ์ฉํ์ธ์.
tf.keras.optimizers์ ๋ชจ๋ธ์ trainable_variables์ ๋ช
์์ ์ผ๋ก ์ ๋ฌํ์ธ์.
train_... | 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)
# ์กฐ๊ฑด์ด ์๋ ์์ค(None ๋ถ๋ถ)๊ณผ
# ์
๋ ฅ ์กฐ๊ฑด์ด ์๋ ์์ค(features ๋ถ๋ถ)์ ์ป์ต๋๋ค.
reg_losses ... | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
ํ๋ฆฌ๋ฉ์ด๋ ์ถ์ ๊ธฐ
tf.estimator.DNN*, tf.estimator.Linear*, tf.estimator.DNNLinearCombined* ๋ชจ๋ ์๋์ ์๋ ํ๋ฆฌ๋ฉ์ด๋ ์ถ์ ๊ธฐ(premade estimator)๋ ๊ณ์ ํ
์ํ๋ก 2.0 API๋ฅผ ์ง์ํฉ๋๋ค. ํ์ง๋ง ์ผ๋ถ ๋งค๊ฐ๋ณ์๊ฐ ๋ฐ๋์์ต๋๋ค:
input_layer_partitioner: 2.0์์ ์ญ์ ๋์์ต๋๋ค.
loss_reduction: tf.compat.v1.losses.Reduction ๋์ ์ tf.keras.losses.Reduction๋ก ์
๋ฐ์ดํธํฉ๋๋ค. ๊ธฐ๋ณธ๊ฐ์ด tf.compat.v1.losses.... | ! curl -O https://raw.githubusercontent.com/tensorflow/estimator/master/tensorflow_estimator/python/estimator/tools/checkpoint_converter.py | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ด ์คํฌ๋ฆฝํธ๋ ๋์๋ง์ ์ ๊ณตํฉ๋๋ค: | ! python checkpoint_converter.py -h | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
TensorShape
์ด ํด๋์ค๋ tf.compat.v1.Dimension ๊ฐ์ฒด ๋์ ์ int ๊ฐ์ ๊ฐ์ง๋๋ก ๋จ์ํ๋์์ต๋๋ค. ๋ฐ๋ผ์ int ๊ฐ์ ์ป๊ธฐ ์ํด .value() ๋ฉ์๋๋ฅผ ํธ์ถํ ํ์๊ฐ ์์ต๋๋ค.
์ฌ์ ํ ๊ฐ๋ณ tf.compat.v1.Dimension ๊ฐ์ฒด๋ tf.TensorShape.dims๋ก ์ฐธ์กฐํ ์ ์์ต๋๋ค.
๋ค์ ์ฝ๋๋ ํ
์ํ๋ก 1.x์ ํ
์ํ๋ก 2.0์ ์ฐจ์ด์ ์ ๋ณด์ฌ์ค๋๋ค. | # TensorShape ๊ฐ์ฒด๋ฅผ ๋ง๋ค๊ณ ์ธ๋ฑ์ค๋ฅผ ์ฐธ์กฐํฉ๋๋ค.
i = 0
shape = tf.TensorShape([16, None, 256])
shape | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
TF 1.x์์๋ ๋ค์๊ณผ ๊ฐ์ด ์ฌ์ฉํฉ๋๋ค:
python
value = shape[i].value
TF 2.0์์๋ ๋ค์๊ณผ ๊ฐ์ด ์ฌ์ฉํฉ๋๋ค: | value = shape[i]
value | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
TF 1.x์์๋ ๋ค์๊ณผ ๊ฐ์ด ์ฌ์ฉํฉ๋๋ค:
python
for dim in shape:
value = dim.value
print(value)
TF 2.0์์๋ ๋ค์๊ณผ ๊ฐ์ด ์ฌ์ฉํฉ๋๋ค: | for value in shape:
print(value) | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
TF 1.x์์๋ ๋ค์๊ณผ ๊ฐ์ด ์ฌ์ฉํฉ๋๋ค(๋ค๋ฅธ Dimension ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ๋๋):
python
dim = shape[i]
dim.assert_is_compatible_with(other_dim)
TF 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) # ๋ค๋ฅธ Dimension ๋ฉ์๋๋ ๋์ผ
shape = tf.TensorShape(None)
if shape:
dim = shape.dims[i]
dim.is_compatible_with(other_dim) # ๋ค๋ฅธ Dimension ๋ฉ์๋๋ ๋์ผ | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ญํฌ(rank)๋ฅผ ์ ์ ์๋ค๋ฉด tf.TensorShape์ ๋ถ๋ฆฌ์ธ ๊ฐ์ True๊ฐ ๋ฉ๋๋ค. ๊ทธ๋ ์ง ์์ผ๋ฉด False์
๋๋ค. | print(bool(tf.TensorShape([]))) # ์ค์นผ๋ผ
print(bool(tf.TensorShape([0]))) # ๊ธธ์ด 0์ธ ๋ฒกํฐ
print(bool(tf.TensorShape([1]))) # ๊ธธ์ด 1์ธ ๋ฒกํฐ
print(bool(tf.TensorShape([None]))) # ๊ธธ์ด๋ฅผ ์ ์ ์๋ ๋ฒกํฐ
print(bool(tf.TensorShape([1, 10, 100]))) # 3D ํ
์
print(bool(tf.TensorShape([None, None, None]))) # ํฌ๊ธฐ๋ฅผ ๋ชจ๋ฅด๋ 3D ํ
์
print()
... | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
You can install the latest pre-release version using pip install --pre --upgrade bigdl-orca. | # Install latest pre-release version of BigDL Orca
# Installing BigDL Orca from pip will automatically install pyspark, bigdl, and their dependencies.
!pip install --pre --upgrade bigdl-orca
# Install python dependencies
!pip install torch==1.7.1 torchvision==0.8.2
!pip install six cloudpickle
!pip install jep==3.9.0 | python/orca/colab-notebook/quickstart/pytorch_lenet_mnist.ipynb | intel-analytics/BigDL | apache-2.0 |
Next, fit and evaluate using the Estimator. | from bigdl.orca.learn.trigger import EveryEpoch
est.fit(data=train_loader, epochs=1, validation_data=test_loader,
checkpoint_trigger=EveryEpoch()) | python/orca/colab-notebook/quickstart/pytorch_lenet_mnist.ipynb | intel-analytics/BigDL | apache-2.0 |
We'll plot all the prices at Adj Close using matplotlib, a python 2D plotting library that is Matlab flavored. We use Adjusted Close because it is commonly used for historical pricing, and accounts for all corporate actions such as stock splits, dividends/distributions and rights offerings. This happens to be our exact... | %matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from matplotlib import style
style.use('fivethirtyeight')
spy['Adj Close'].plot(figsize=(20,10))
ax = plt.subplot()
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: '${:,.0f}'.format(x))) # Y axis dollarsymbols
plt.... | Lumpsum_vs_DCA.ipynb | Elucidation/lumpsum_vs_dca | apache-2.0 |
Great, looks similar to the SPY chart from before. Notice how due to historical pricing, the effect of including things like dividend yields increases to total return over the years. We can easily see the the bubble and crash around 2007-2009, as well as the long bull market up since then. Also we can see in the last c... | value_price = spy['Adj Close'][-1] # The final value of our stock
initial_investment = 10000 # Our initial investment of $10k
num_stocks_bought = initial_investment / spy['Adj Close']
lumpsum = num_stocks_bought * value_price
lumpsum.name = 'Lump Sum'
lumpsum.plot(figsize=(20,10))
ax = plt.subplot()
ax.yaxis.set_majo... | Lumpsum_vs_DCA.ipynb | Elucidation/lumpsum_vs_dca | apache-2.0 |
Cool! Pandas makes it really easy to manipulate data with datetime indices. Looking at the chart we see that if we'd bought right at the bottom of the 2007-2009 crash our \$10,000 would be worth ~ $32,500. If only we had a time machine... | print("Lump sum: Investing on the 1 - Best day, 2 - Worst day in past, 3 - Worst day in all")
print("1 - Investing $10,000 on {} would be worth ${:,.2f} today.".format(lumpsum.idxmax().strftime('%b %d, %Y'), lumpsum.max()))
print("2 - Investing $10,000 on {} would be worth ${:,.2f} today.".format(lumpsum[:-1000].idxmin... | Lumpsum_vs_DCA.ipynb | Elucidation/lumpsum_vs_dca | apache-2.0 |
What's nice to note as well is that even if we'd invested at the worst possible time, peak of the bubble in 2007, on Oct 9th, we'd still have come out net positive at \$14,593 today. The worst time to invest so far turns out to be more recent, on July 20th of 2015. This is because not only was the market down, but it's... | def doDCA(investment, start_date):
# Get 12 investment dates in 30 day increments starting from start date
investment_dates_all = pd.date_range(start_date,periods=12,freq='30D')
# Remove those dates beyond our known data range
investment_dates = investment_dates_all[investment_dates_all < spy.index[-1]]... | Lumpsum_vs_DCA.ipynb | Elucidation/lumpsum_vs_dca | apache-2.0 |
Surprisingly straightforward, good job Pandas. Let's plot it similar to how we did with lump sum. The x axis is the date at which we start dollar cost averaging (and then continue for the next 360 days in 30 day increments from that date). The y axis is the final value of our investment today. | dca.plot(figsize=(20,10))
ax = plt.subplot()
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: '${:,.0f}'.format(x))) # Y axis dollarsymbols
plt.title('Dollar Cost Averaging - Value today of $10,000 invested on date')
plt.xlabel('')
plt.ylabel('Investment Value ($)'); | Lumpsum_vs_DCA.ipynb | Elucidation/lumpsum_vs_dca | apache-2.0 |
Interesting! DCA looks way really smooth and the graph is really high up, so it must be better right!? Wait, no, the Y axis is different, in fact it's highest high is around \$28,000 in comparison to the lump sums \$32,500. Let's look at the ideal/worst investment dates for DCA, I include the lump sum from before as we... | print("Lump sum")
print(" Crash - Investing $10,000 on {} would be worth ${:,.2f} today.".format(lumpsum.idxmax().strftime('%b %d, %Y'), lumpsum.max()))
print("Bubble - Investing $10,000 on {} would be worth ${:,.2f} today.".format(lumpsum[:-1500].idxmin().strftime('%b %d, %Y'), lumpsum[:-1500].min()))
print("Recent - ... | Lumpsum_vs_DCA.ipynb | Elucidation/lumpsum_vs_dca | apache-2.0 |
Looking at dollar cost averaging, the best day to start dollar cost averaging was July 12, 2002, when we were still recovering from the 'tech crashs. The worst day to start was around the peak of the 2007 bubble on Jan 26, 2007, and the absolute worst would have been to start last year on Jan 20, 2015.
We can already s... | # Difference between lump sum and DCA
diff = (lumpsum - dca)
diff.name = 'Difference (Lump Sum - DCA)'
fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True, figsize=(20,15))
# SPY Actual
spy['Adj Close'].plot(ax=ax1)
ax1.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: '${:,.0f}'.format(x))) # Y axis in dollars... | Lumpsum_vs_DCA.ipynb | Elucidation/lumpsum_vs_dca | apache-2.0 |
Before we start comparing, definitely take note of the middle chart, where the initial investment of \$10k is. Notice that if we had invested using either strategy, and at any point before 2 years ago, no matter which bubble or crash, we'd have made some pretty huge returns on our investments, double and tripling at so... | print("Lump sum returns more than DCA %.1f%% of all the days" % (100*sum(diff>0)/len(diff)))
print("DCA returns more than Lump sum %.1f%% of all the days" % (100*sum(diff<0)/len(diff)))
| Lumpsum_vs_DCA.ipynb | Elucidation/lumpsum_vs_dca | apache-2.0 |
Remarkable! So 66.3% of the time lump sum results in a higher final investment value over our monthly dollar cost averaging strategy. Almost dead on to the claims of 66% by the investopedia article I'd read.
But maybe this isn't the whole story, perhaps the lump sum returned a little better than DCA most of the time, b... | print("Mean difference: Average dollar improvement lump sum returns vs. dca: ${:,.2f}".format(sum(diff) / len(diff)))
print("Mean difference when lump sum > dca: ${:,.2f}".format(sum(diff[diff>0]) / sum(diff>0)))
print("Mean difference when dca > lump sum: ${:,.2f}".format(sum(-diff[diff<0]) / sum(diff<0))) | Lumpsum_vs_DCA.ipynb | Elucidation/lumpsum_vs_dca | apache-2.0 |
Training examples
Training examples are defined through the Imageset class of TRIOSlib. The class defines a list of tuples with pairs of input and desired output image paths, and an (optional) binary image mask (see http://trioslib.sourceforge.net/index.html for more details). In this case, we use a training set with t... | train_imgs = trios.Imageset.read('images/train_images.set')
for i in range(len(train_imgs)):
print("sample %d:" % (i + 1))
print("\t input: %s" % train_imgs[i][0])
print("\t desired output: %s" % train_imgs[i][1])
print("\t mask: %s\n" % train_imgs[i][2])
print("The first pair of input and ouput exampl... | cnn_trioslib.ipynb | fjulca-aguilar/DeepTRIOS | gpl-3.0 |
Training
We define a CNN architecture through the CNN_TFClassifier class. The classifier requires the input image shape and number of outputs for initialization. We define the input shape according to the patches extracted from the images, in this example, 11x11, and use a single sigmoid output unit for binary classif... | patch_side = 19
num_outputs = 1
win = np.ones((patch_side, patch_side), np.uint8)
cnn_classifier = CNN_TFClassifier((patch_side, patch_side, 1), num_outputs, num_epochs=10, model_dir='cnn_text_segmentation')
op_tf = trios.WOperator(win, TFClassifier(cnn_classifier), RAWFeatureExtractor, batch=True)
op_tf.train(train_i... | cnn_trioslib.ipynb | fjulca-aguilar/DeepTRIOS | gpl-3.0 |
Applying the operator to a new image | test_img = sp.ndimage.imread('images/veja11.sh50.png', mode='L')
out_img = op_tf.apply(test_img, test_img)
fig = plt.figure(2, figsize=(15,15))
fig.add_subplot(121)
plt.imshow(test_img, cmap=cm.gray)
plt.title('Input')
fig.add_subplot(122)
plt.imshow(out_img, cmap=cm.gray)
plt.title('CNN output')
| cnn_trioslib.ipynb | fjulca-aguilar/DeepTRIOS | gpl-3.0 |
Download and process data
In this section we'll:
* Download the wine quality data directly from UCI Machine Learning
* Read it into a Pandas dataframe and preview it
* Split the data and labels into train and test sets | !wget 'http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv'
data = pd.read_csv('winequality-white.csv', index_col=False, delimiter=';')
data = shuffle(data, random_state=4)
data.head()
labels = data['quality']
print(labels.value_counts())
data = data.drop(columns=['quality']... | keras_sklearn_compare_caip_e2e.ipynb | PAIR-code/what-if-tool | apache-2.0 |
Train tf.keras model
In this section we'll:
Build a regression model using tf.keras to predict a wine's quality score
Train the model
Add a layer to the model to prepare it for serving | # This is the size of the array we'll be feeding into our model for each wine example
input_size = len(train_data.iloc[0])
print(input_size)
model = Sequential()
model.add(Dense(200, input_shape=(input_size,), activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(25, activation='relu'))
model.add... | keras_sklearn_compare_caip_e2e.ipynb | PAIR-code/what-if-tool | apache-2.0 |
Deploy keras model to Cloud AI Platform
In this section we'll:
* Set up some global variables for our GCP project
* Add a serving layer to our model so we can deploy it on Cloud AI Platform
* Run the deploy command to deploy our model
* Generate a test prediction on our deployed model | # Update these to your own GCP project + model names
GCP_PROJECT = 'your_gcp_project'
KERAS_MODEL_BUCKET = 'gs://your_storage_bucket'
KERAS_VERSION_NAME = 'v1'
# Add the serving input layer below in order to serve our model on AI Platform
class ServingInput(tf.keras.layers.Layer):
# the important detail in this boil... | keras_sklearn_compare_caip_e2e.ipynb | PAIR-code/what-if-tool | apache-2.0 |
Build and train Scikit learn model
In this section we'll:
* Train a regression model using Scikit Learn
* Save the model to a local file using pickle | SKLEARN_VERSION_NAME = 'v1'
SKLEARN_MODEL_BUCKET = 'gs://sklearn_model_bucket'
scikit_model = LinearRegression().fit(train_data.values, train_labels.values)
# Export the model to a local file using pickle
pickle.dump(scikit_model, open('model.pkl', 'wb')) | keras_sklearn_compare_caip_e2e.ipynb | PAIR-code/what-if-tool | apache-2.0 |
Deploy Scikit model to CAIP
In this section we'll:
* Copy our saved model file to Cloud Storage
* Run the gcloud command to deploy our model
* Generate a prediction on our deployed model | # Copy the saved model to Cloud Storage
!gsutil cp ./model.pkl gs://wine_sklearn/model.pkl
# Create a new model in our project, you only need to run this once
!gcloud ai-platform models create sklearn_wine
!gcloud beta ai-platform versions create $SKLEARN_VERSION_NAME --model=sklearn_wine \
--origin=$SKLEARN_MODEL_BU... | keras_sklearn_compare_caip_e2e.ipynb | PAIR-code/what-if-tool | apache-2.0 |
Compare tf.keras and Scikit models with the What-if Tool
Now we're ready for the What-if Tool! In this section we'll:
* Create an array of our test examples with their ground truth values. The What-if Tool works best when we send the actual values for each example input.
* Instantiate the What-if Tool using the set_com... | # Create np array of test examples + their ground truth labels
test_examples = np.hstack((test_data[:200].values,test_labels[:200].values.reshape(-1,1)))
print(test_examples.shape)
# Create a What-if Tool visualization, it may take a minute to load
# See the cell below this for exploration ideas
# We use `set_predict... | keras_sklearn_compare_caip_e2e.ipynb | PAIR-code/what-if-tool | apache-2.0 |
Projections
Bipartite graphs can be projected down to one of the projections. For example, we can generate a person-person graph from the person-crime graph, by declaring that two nodes that share a crime node are in fact joined by an edge.
Exercise
Find the bipartite projection function in the NetworkX bipartite modu... | person_nodes =
pG =
list(pG.nodes(data=True))[0:5] | archive/6-bipartite-graphs-student.ipynb | ericmjl/Network-Analysis-Made-Simple | mit |
Exercise
Try visualizing the person-person crime network by using a Circos plot. Ensure that the nodes are grouped by gender and then by number of connections. (5 min.)
Again, recapping the Circos Plot API:
python
c = CircosPlot(graph_object, node_color='metadata_key1', node_grouping='metadata_key2', node_order='metada... | for n, d in pG.nodes(data=True):
____________________
c = CircosPlot(______, node_color=_________, node_grouping=_________, node_order=__________)
_________
plt.savefig('images/crime-person.png', dpi=300) | archive/6-bipartite-graphs-student.ipynb | ericmjl/Network-Analysis-Made-Simple | mit |
Exercise
Use a similar logic to extract crime links. (2 min.) | crime_nodes = _________
cG = _____________ # cG stands for "crime graph" | archive/6-bipartite-graphs-student.ipynb | ericmjl/Network-Analysis-Made-Simple | mit |
Exercise
Can you plot how the crimes are connected, using a Circos plot? Try ordering it by number of connections. (5 min.) | for n in cG.nodes():
___________
c = CircosPlot(___________)
___________
plt.savefig('images/crime-crime.png', dpi=300) | archive/6-bipartite-graphs-student.ipynb | ericmjl/Network-Analysis-Made-Simple | mit |
Exercise
NetworkX also implements centrality measures for bipartite graphs, which allows you to obtain their metrics without first converting to a particular projection. This is useful for exploratory data analysis.
Try the following challenges, referring to the API documentation to help you:
Which crimes have the mo... | # Degree Centrality
bpdc = _______________________
sorted(___________, key=lambda x: ___, reverse=True) | archive/6-bipartite-graphs-student.ipynb | ericmjl/Network-Analysis-Made-Simple | mit |
Using the Meta-Dataset Data Pipeline
This notebook shows how to use meta_datasetโs input pipeline to sample data for the Meta-Dataset benchmark. There are two main ways in which data is sampled:
1. episodic: Returns N-way classification episodes, which contain a support (training) set and a query (test) set. The numbe... | #@title Imports and Utility Functions
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from collections import Counter
import gin
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from meta_dataset.data import config
from me... | Intro_to_Metadataset.ipynb | google-research/meta-dataset | apache-2.0 |
Primers
Download your data and process it as explained in link. Set BASE_PATH pointing the processed tf-records ($RECORDS in the conversion instructions).
meta_dataset supports many different setting for sampling data. We use gin-config to control default parameters of our functions. You can go to default gin file we ... | # 1
BASE_PATH = '/path/to/records'
GIN_FILE_PATH = 'meta_dataset/learn/gin/setups/data_config.gin'
# 2
gin.parse_config_file(GIN_FILE_PATH)
# 3
# Comment out to disable eager execution.
tf.enable_eager_execution()
# 4
def iterate_dataset(dataset, n):
if not tf.executing_eagerly():
iterator = dataset.make_one_shot... | Intro_to_Metadataset.ipynb | google-research/meta-dataset | apache-2.0 |
Reading datasets
In order to sample data, we need to read the dataset_spec files for each dataset. Following snippet reads those files into a list. | ALL_DATASETS = ['aircraft', 'cu_birds', 'dtd', 'fungi', 'ilsvrc_2012',
'omniglot', 'quickdraw', 'vgg_flower']
all_dataset_specs = []
for dataset_name in ALL_DATASETS:
dataset_records_path = os.path.join(BASE_PATH, dataset_name)
dataset_spec = dataset_spec_lib.load_dataset_spec(dataset_records_path)... | Intro_to_Metadataset.ipynb | google-research/meta-dataset | apache-2.0 |
(1) Episodic Mode
meta_dataset uses tf.data.Dataset API and it takes one call to pipeline.make_multisource_episode_pipeline(). We loaded or defined most of the variables used during this call above. The remaining parameters are explained below:
use_bilevel_ontology_list: This is a list of booleans indicating whether ... | use_bilevel_ontology_list = [False]*len(ALL_DATASETS)
use_dag_ontology_list = [False]*len(ALL_DATASETS)
# Enable ontology aware sampling for Omniglot and ImageNet.
use_bilevel_ontology_list[5] = True
use_dag_ontology_list[4] = True
variable_ways_shots = config.EpisodeDescriptionConfig(
num_query=None, num_support=... | Intro_to_Metadataset.ipynb | google-research/meta-dataset | apache-2.0 |
Using Dataset
The episodic dataset consist in a tuple of the form (Episode, data source ID). The data source ID is an integer Tensor containing a value in the range [0, len(all_dataset_specs) - 1]
signifying which of the datasets of the multisource pipeline the given episode
came from. Episodes consist of support and ... | # 1
idx, (episode, source_id) = next(iterate_dataset(dataset_episodic, 1))
print('Got an episode from dataset:', all_dataset_specs[source_id].name)
# 2
for t, name in zip(episode,
['support_images', 'support_labels', 'support_class_ids',
'query_images', 'query_labels', 'query_cla... | Intro_to_Metadataset.ipynb | google-research/meta-dataset | apache-2.0 |
Visualizing Episodes
Let's visualize the episodes.
Support and query set for each episode plotted sequentially. Set N_EPISODES to control number of episodes visualized.
Each episode is sampled from a single dataset and include N different classes. Each class might have different number of samples in support set, wher... | # 1
N_EPISODES=2
# 2, 3
for idx, (episode, source_id) in iterate_dataset(dataset_episodic, N_EPISODES):
print('Episode id: %d from source %s' % (idx, all_dataset_specs[source_id].name))
episode = [a.numpy() for a in episode]
plot_episode(support_images=episode[0], support_class_ids=episode[2],
quer... | Intro_to_Metadataset.ipynb | google-research/meta-dataset | apache-2.0 |
(2) Batch Mode
Second mode that meta_dataset library provides is the batch mode, where one can sample batches from the list of datasets in a non-episodic manner and use it to train baseline models. There are couple things to note here:
Each batch is sampled from a different dataset.
ADD_DATASET_OFFSET controls whethe... | BATCH_SIZE = 16
ADD_DATASET_OFFSET = True
dataset_batch = pipeline.make_multisource_batch_pipeline(
dataset_spec_list=all_dataset_specs, batch_size=BATCH_SIZE, split=SPLIT,
image_size=84, add_dataset_offset=ADD_DATASET_OFFSET,
shuffle_buffer_size=1000)
for idx, ((images, labels), source_id) in iterate_dat... | Intro_to_Metadataset.ipynb | google-research/meta-dataset | apache-2.0 |
(3) Fixing Ways and Shots
meta_dataset library provides option to set number of classes/samples per episode. There are 3 main flags you can set.
NUM_WAYS: Fixes the # classes per episode. We would still get variable number of samples per class in the support set.
NUM_SUPPORT: Fixes # samples per class in the support ... | #1
NUM_WAYS = 8
NUM_SUPPORT = 3
NUM_QUERY = 5
fixed_ways_shots = config.EpisodeDescriptionConfig(
num_ways=NUM_WAYS, num_support=NUM_SUPPORT, num_query=NUM_QUERY)
#2
use_bilevel_ontology_list = [False]*len(ALL_DATASETS)
use_dag_ontology_list = [False]*len(ALL_DATASETS)
quickdraw_spec = [all_dataset_specs[6]]
#3
da... | Intro_to_Metadataset.ipynb | google-research/meta-dataset | apache-2.0 |
(4) Using Meta-dataset with PyTorch
As mentioned above it is super easy to consume meta_dataset as NumPy arrays. This also enables easy integration into other popular deep learning frameworks like PyTorch. TensorFlow code processes the data and passes it to PyTorch, ready to be consumed. Since the data loader and proce... | import torch
# 1
to_torch_labels = lambda a: torch.from_numpy(a.numpy()).long()
to_torch_imgs = lambda a: torch.from_numpy(np.transpose(a.numpy(), (0, 3, 1, 2)))
# 2
def data_loader(n_batches):
for i, (e, _) in enumerate(dataset_episodic):
if i == n_batches:
break
yield (to_torch_imgs(e[0]), to_torch_la... | Intro_to_Metadataset.ipynb | google-research/meta-dataset | apache-2.0 |
Add to the function to allow amplitude to be varied and aadd in an additional slider to vary both f and a
may want to limit ylim | interact(pltsin, f=(1, 10, 0.2), x = (1, 10, 0.2))
def pltsina(f, a):
plt.plot(x, a*sin(2*pi*x*f))
plt.ylim(-10.5, 10.5)
interact(pltsina, f=(1, 10, 0.2), a = (1, 10, 0.2))
| Basemap-final.ipynb | WillRhB/PythonLesssons | mit |
Climate data | f=Dataset ('ncep-data/air.sig995.2013.nc') # get individual data set out of the right folder
air = f.variables['air'] # get variable
plt.imshow(air[0,:,:]) # display first timestep
# Create function to browse through the days
def sh(time):
plt.imshow(air[time,:,:])
# Now make it interactive
interact(sh, tim... | Basemap-final.ipynb | WillRhB/PythonLesssons | mit |
Plotting some live (ish) earthquake data...
Download the data first: http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_week.csv
This will download a file locally- move it into your working directory. Alternatively, use the historic dataset provided in this repo. | #Check the first few lats and longs
import csv
# Open the earthquake data file.
filename = '1.0_week.csv'
# Create empty lists for the latitudes and longitudes.
lats, lons, mags = [], [], []
# Read through the entire file, skip the first line,
# and pull out just the lats and lons.
with open(filename) as f:
# ... | Basemap-final.ipynb | WillRhB/PythonLesssons | mit |
This is great but one cool enhancement would be to make the size of the point represent the magnitude of the earthquake.
Here's one way to do it:
Read the magnitudes into a list along with their respective lat and long
Loop through the list, plotting one point at a time
As the magnitudes start at 1.0, you can just use ... | x,y | Basemap-final.ipynb | WillRhB/PythonLesssons | mit |
doc2vec | %load_ext autoreload
%autoreload 2
import word2vec
word2vec.doc2vec('/Users/drodriguez/Downloads/alldata.txt', '/Users/drodriguez/Downloads/vectors.bin', cbow=0, size=100, window=10, negative=5, hs=0, sample='1e-4', threads=12, iter_=20, min_count=1, verbose=True) | examples/doc2vec.ipynb | chivalrousS/word2vec | apache-2.0 |
Predictions
Is possible to load the vectors using the same wordvectors class as a regular word2vec binary file. | %load_ext autoreload
%autoreload 2
import word2vec
model = word2vec.load('/Users/drodriguez/Downloads/vectors.bin')
model.vectors.shape | examples/doc2vec.ipynb | chivalrousS/word2vec | apache-2.0 |
We can ask for similarity words or documents on document 1 | indexes, metrics = model.cosine('_*1')
model.generate_response(indexes, metrics).tolist() | examples/doc2vec.ipynb | chivalrousS/word2vec | apache-2.0 |
For each publically available version of EXIOBASE pymrio provides a specific parser.
All exiobase parser work with the zip archive (as downloaded from the exiobase webpage) or the extracted data.
To parse EXIOBASE 1 use: | exio1 = pymrio.parse_exiobase1(path='/tmp/mrios/exio1/zip/121016_EXIOBASE_pxp_ita_44_regions_coeff_txt.zip') | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
The parameter 'path' needs to point to either the folder with the extracted EXIOBASE1 files for the downloaded zip archive.
Similarly, EXIOBASE 2 can be parsed by: | exio2 = pymrio.parse_exiobase2(path='/tmp/mrios/exio2/zip/mrIOT_PxP_ita_coefficient_version2.2.2.zip',
charact=True, popvector='exio2') | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
The additional parameter 'charact' specifies if the characterization matrix provided with EXIOBASE 2 should be used. This can be specified with True or False; in addition, a custom one can be provided. In the latter case, pass the full path to the custom characterisatio file to 'charact'.
The parameter 'popvector' allo... | exio3 = pymrio.parse_exiobase3(path='/tmp/mrios/exio3/zip/exiobase3.4_iot_2009_pxp.zip') | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
Currently, no characterization or population vectors are provided for EXIOBASE 3.
For the rest of the tutorial, we use exio2; deleting exio1 and exio3 to free some memory: | del exio1
del exio3 | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
Exploring EXIOBASE
After parsing a EXIOBASE version, the handling of the database is the same as for any IO.
Here we use the parsed EXIOBASE2 to explore some characteristics of the EXIBOASE system.
After reading the raw files, metadata about EXIOBASE can be accessed within the meta field: | exio2.meta | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
Custom points can be added to the history in the meta record. For example: | exio2.meta.note("First test run of EXIOBASE 2")
exio2.meta | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
To check for sectors, regions and extensions: | exio2.get_sectors()
exio2.get_regions()
list(exio2.get_extensions()) | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
Calculating the system and extension results
The following command checks for missing parts in the system and calculates them. In case of the parsed EXIOBASE this includes A, L, multipliers M, footprint accounts, .. | exio2.calc_all() | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
Exploring the results | import matplotlib.pyplot as plt
plt.figure(figsize=(15,15))
plt.imshow(exio2.A, vmax=1E-3)
plt.xlabel('Countries - sectors')
plt.ylabel('Countries - sectors')
plt.show() | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
The available impact data can be checked with: | list(exio2.impact.get_rows()) | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
And to get for example the footprint of a specific impact do: | print(exio2.impact.unit.loc['global warming (GWP100)'])
exio2.impact.D_cba_reg.loc['global warming (GWP100)'] | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
Visualizing the data | with plt.style.context('ggplot'):
exio2.impact.plot_account(['global warming (GWP100)'], figsize=(15,10))
plt.show() | doc/source/notebooks/working_with_exiobase.ipynb | konstantinstadler/pymrio | gpl-3.0 |
Chapter 16 - The BART model of risk taking
16.1 The BART model
Balloon Analogue Risk Task (BART: Lejuez et al., 2002): Every trial in this task starts by showing a balloon representing a small monetary value. The subject can then either transfer the money to a virtual bank account, or choose to pump, which adds a small... | p = .15 # (Belief of) bursting probability
ntrials = 90 # Number of trials for the BART
Data = pd.read_csv('data/GeorgeSober.txt', sep='\t')
# Data.head()
cash = np.asarray(Data['cash']!=0, dtype=int)
npumps = np.asarray(Data['pumps'], dtype=int)
options = cash + npumps
d = np.full([ntrials,30], np.nan)
k = np.fu... | CaseStudies/TheBARTModelofRiskTaking.ipynb | junpenglao/Bayesian-Cognitive-Modeling-in-Pymc3 | gpl-3.0 |
16.2 A hierarchical extension of the BART model
$$ \mu_{\gamma^{+}} \sim \text{Uniform}(0,10) $$
$$ \sigma_{\gamma^{+}} \sim \text{Uniform}(0,10) $$
$$ \mu_{\beta} \sim \text{Uniform}(0,10) $$
$$ \sigma_{\beta} \sim \text{Uniform}(0,10) $$
$$ \gamma^{+}i \sim \text{Gaussian}(\mu{\gamma^{+}}, 1/\sigma_{\gamma^{+}}^2) $$... | p = .15 # (Belief of) bursting probability
ntrials = 90 # Number of trials for the BART
Ncond = 3
dall = np.full([Ncond,ntrials,30], np.nan)
options = np.zeros((Ncond,ntrials))
kall = np.full([Ncond,ntrials,30], np.nan)
npumps_ = np.zeros((Ncond,ntrials))
for icondi in range(Ncond):
if icondi == 0:
Dat... | CaseStudies/TheBARTModelofRiskTaking.ipynb | junpenglao/Bayesian-Cognitive-Modeling-in-Pymc3 | gpl-3.0 |
Interact with SVG display
SVG is a simple way of drawing vector graphics in the browser. Here is a simple example of how SVG can be used to draw a circle in the Notebook: | s = """
<svg width="100" height="100">
<circle cx="50" cy="50" r="20" fill="aquamarine" />
</svg>
"""
S = SVG(s)
display(S) | assignments/assignment06/InteractEx05.ipynb | nproctor/phys202-2015-work | mit |
Write a function named draw_circle that draws a circle using SVG. Your function should take the parameters of the circle as function arguments and have defaults as shown. You will have to write the raw SVG code as a Python string and then use the IPython.display.SVG object and IPython.display.display function. | def draw_circle(width=100, height=100, cx=25, cy=25, r=5, fill='red'):
"""Draw an SVG circle.
Parameters
----------
width : int
The width of the svg drawing area in px.
height : int
The height of the svg drawing area in px.
cx : int
The x position of the center of th... | assignments/assignment06/InteractEx05.ipynb | nproctor/phys202-2015-work | mit |
ๆณจๆ๏ผ่ฟ้ๅฆๆไฝฟ็จnp.allclose็่ฏไผ่ฟไธไบassert๏ผไบๅฎไธ๏ผไป
ไป
ๆฏๅฐๆฐ็ป็dtypeไปfloat64ๅๆfloat32ใ็ฒพๅบฆๅฐฑไผไธ้ๅพๅค๏ผๆฏ็ซๅท็งฏๆถๅๅฐ็่ฟ็ฎๅคชๅค | @nb.jit(nopython=True)
def jit_conv_kernel2(x, w, rs, n, n_channels, height, width, n_filters, filter_height, filter_width, out_h, out_w):
for i in range(n):
for j in range(out_h):
for p in range(out_w):
for q in range(n_filters):
for r in range(n_channels):
... | Notebooks/numba/zh-cn/CNN.ipynb | carefree0910/MachineLearning | mit |
ๅฏไปฅ็ๅฐ๏ผไฝฟ็จjitๅไฝฟ็จ็บฏnumpy่ฟ่ก็ผ็จ็ๅพๅคงไธ็นไธๅๅฐฑๆฏ๏ผไธ่ฆ็ๆง็จfor๏ผไบๅฎไธไธ่ฌๆฅ่ฏด๏ผไปฃ็ โ้ฟๅพ่ถๅ Cโใ้ๅบฆๅฐฑไผ่ถๅฟซ | def max_pool_kernel(x, rs, *args):
n, n_channels, pool_height, pool_width, out_h, out_w = args
for i in range(n):
for j in range(n_channels):
for p in range(out_h):
for q in range(out_w):
window = x[i, j, p:p+pool_height, q:q+pool_width]
... | Notebooks/numba/zh-cn/CNN.ipynb | carefree0910/MachineLearning | mit |
Confirmation that the sensors are sensitive to airflow.
The outlier sensor (:F8) is still there. The spike at 18:20 is probably from me holding it while wondering about heat disappation. One of the WiFi drop-out issues got fixed (and another discovered).
Applying the same guestimated correction to the outlier sensor fr... | downsampled_f['5C:CF:7F:33:F7:F8'] += 5.0
downsampled_f.plot(); | temperature/FoamCoreExperiment.ipynb | davewsmith/notebooks | mit |
Vertex AI: Vertex AI Migration: Custom Scikit-Learn model with pre-built training container
<table align="left">
<td>
<a href="https://colab.research.google.com/github/GoogleCloudPlatform/ai-platform-samples/blob/master/vertex-ai-samples/tree/master/notebooks/official/migration/UJ10%20Vertex%20SDK%20Custom%20Scik... | import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Set pre-built containers
Set the pre-built Docker container image for training and prediction.
For the latest list, see Pre-built containers for training.
For the latest list, see Pre-built containers for prediction. | TRAIN_VERSION = "scikit-learn-cpu.0-23"
DEPLOY_VERSION = "sklearn-cpu.0-23"
TRAIN_IMAGE = "gcr.io/cloud-aiplatform/training/{}:latest".format(TRAIN_VERSION)
DEPLOY_IMAGE = "gcr.io/cloud-aiplatform/prediction/{}:latest".format(DEPLOY_VERSION) | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Examine the training package
Package layout
Before you start the training, you will look at how a Python package is assembled for a custom training job. When unarchived, the package contains the following directory/file layout.
PKG-INFO
README.md
setup.cfg
setup.py
trainer
__init__.py
task.py
The files setup.cfg and ... | # Make folder for Python training script
! rm -rf custom
! mkdir custom
# Add package information
! touch custom/README.md
setup_cfg = "[egg_info]\n\ntag_build =\n\ntag_date = 0"
! echo "$setup_cfg" > custom/setup.cfg
setup_py = "import setuptools\n\nsetuptools.setup(\n\n install_requires=[\n\n 'tensorflow... | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Store training script on your Cloud Storage bucket
Next, you package the training folder into a compressed tar ball, and then store it in your Cloud Storage bucket. | ! rm -f custom.tar custom.tar.gz
! tar cvf custom.tar custom
! gzip custom.tar
! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_census.tar.gz | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Train a model
training.create-python-pre-built-container
Create and run custom training job
To train a custom model, you perform two steps: 1) create a custom training job, and 2) run the job.
Create custom training job
A custom training job is created with the CustomTrainingJob class, with the following parameters:
d... | job = aip.CustomTrainingJob(
display_name="census_" + TIMESTAMP,
script_path="custom/trainer/task.py",
container_uri=TRAIN_IMAGE,
requirements=["gcsfs==0.7.1", "tensorflow-datasets==4.4"],
)
print(job) | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
general.import-model
Upload the model
Next, upload your model to a Model resource using Model.upload() method, with the following parameters:
display_name: The human readable name for the Model resource.
artifact: The Cloud Storage location of the trained model artifacts.
serving_container_image_uri: The serving conta... | model = aip.Model.upload(
display_name="census_" + TIMESTAMP,
artifact_uri=MODEL_DIR,
serving_container_image_uri=DEPLOY_IMAGE,
sync=False,
)
model.wait() | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
INFO:google.cloud.aiplatform.models:Creating Model
INFO:google.cloud.aiplatform.models:Create Model backing LRO: projects/759209241365/locations/us-central1/models/925164267982815232/operations/3458372263047331840
INFO:google.cloud.aiplatform.models:Model created. Resource name: projects/759209241365/lo... | INSTANCES = [
[
25,
"Private",
226802,
"11th",
7,
"Never-married",
"Machine-op-inspct",
"Own-child",
"Black",
"Male",
0,
0,
40,
"United-States",
],
[
38,
"Private",
89814,
... | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Make the batch input file
Now make a batch input file, which you will store in your local Cloud Storage bucket. Each instance in the prediction request is a list of the form:
[ [ content_1], [content_2] ]
content: The feature values of the test item as a list. | import json
import tensorflow as tf
gcs_input_uri = BUCKET_NAME + "/" + "test.jsonl"
with tf.io.gfile.GFile(gcs_input_uri, "w") as f:
for i in INSTANCES:
f.write(json.dumps(i) + "\n")
! gsutil cat $gcs_input_uri | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Make the batch prediction request
Now that your Model resource is trained, you can make a batch prediction by invoking the batch_predict() method, with the following parameters:
job_display_name: The human readable name for the batch prediction job.
gcs_source: A list of one or more batch request input files.
gcs_dest... | MIN_NODES = 1
MAX_NODES = 1
batch_predict_job = model.batch_predict(
job_display_name="census_" + TIMESTAMP,
gcs_source=gcs_input_uri,
gcs_destination_prefix=BUCKET_NAME,
instances_format="jsonl",
predictions_format="jsonl",
model_parameters=None,
machine_type=DEPLOY_COMPUTE,
starting_r... | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example Output:
{'instance': [25, 'Private', 226802, '11th', 7, 'Never-married', 'Machine-op-inspct', 'Own-child', 'Black', 'Male', 0, 0, 40, 'United-States'], 'prediction': False}
Make online predictions
predictions.deploy-model-api
Deploy the model
Next, deploy your model for online prediction. To deploy the model, ... | DEPLOYED_NAME = "census-" + TIMESTAMP
TRAFFIC_SPLIT = {"0": 100}
MIN_NODES = 1
MAX_NODES = 1
endpoint = model.deploy(
deployed_model_display_name=DEPLOYED_NAME,
traffic_split=TRAFFIC_SPLIT,
machine_type=DEPLOY_COMPUTE,
min_replica_count=MIN_NODES,
max_replica_count=MAX_NODES,
) | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
INFO:google.cloud.aiplatform.models:Creating Endpoint
INFO:google.cloud.aiplatform.models:Create Endpoint backing LRO: projects/759209241365/locations/us-central1/endpoints/4867177336350441472/operations/4087251132693348352
INFO:google.cloud.aiplatform.models:Endpoint created. Resource name: projects/75... | INSTANCE = [
25,
"Private",
226802,
"11th",
7,
"Never-married",
"Machine-op-inspct",
"Own-child",
"Black",
"Male",
0,
0,
40,
"United-States",
] | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
Prediction(predictions=[False], deployed_model_id='7220545636163125248', explanations=None)
Undeploy the model
When you are done doing predictions, you undeploy the model from the Endpoint resouce. This deprovisions all compute resources and ends billing for the deployed model. | endpoint.undeploy_all() | notebooks/official/migration/UJ10 Vertex SDK Custom Scikit-Learn with pre-built training container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Target Configuration
The target configuration is used to describe and configure your test environment.
You can find more details in examples/utils/testenv_example.ipynb. | # Setup target configuration
my_conf = {
# Target platform and board
"platform" : 'linux',
"board" : 'juno',
"host" : '192.168.0.1',
# Folder where all the results will be collected
"results_dir" : "EnergyMeter_AEP",
# Define devlib modules to load
"modules" : ["cpufre... | ipynb/examples/energy_meter/EnergyMeter_AEP.ipynb | arnoldlu/lisa | apache-2.0 |
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/graphics/blob/master/tensorflow_graphics/projects/radiance_fields/tiny_nerf.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
... | %pip install tensorflow_graphics
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras.layers as layers
import tensorflow_graphics.projects.radiance_fields.data_loaders as data_loaders
import tensorflow_graphics.projects.radiance_fields.utils as utils
import tensorflow_graphics.rendering.cam... | tensorflow_graphics/projects/radiance_fields/TFG_tiny_nerf.ipynb | tensorflow/graphics | apache-2.0 |
Please download the data from the original repository. In this tutorial we experimented with the synthetic data (lego, ship, boat, etc) that can be found here. Then, you can either point to them locally (if you run a custom kernel) or upload them to the google colab. | DATASET_DIR = '/content/nerf_synthetic/'
#@title Parameters
batch_size = 10 #@param {type:"integer"}
n_posenc_freq = 6 #@param {type:"integer"}
learning_rate = 0.0005 #@param {type:"number"}
n_filters = 256 #@param {type:"integer"}
num_epochs = 100 #@param {type:"integer"}
n_rays = 512 #@param {type:"integer"}
near... | tensorflow_graphics/projects/radiance_fields/TFG_tiny_nerf.ipynb | tensorflow/graphics | apache-2.0 |
Training a NeRF network | #@title Load the lego dataset { form-width: "350px" }
dataset, height, width = data_loaders.load_synthetic_nerf_dataset(
dataset_dir=DATASET_DIR,
dataset_name='lego',
split='train',
scale=0.125,
batch_size=batch_size)
#@title Prepare the NeRF model and optimizer { form-width: "350px" }
input_dim ... | tensorflow_graphics/projects/radiance_fields/TFG_tiny_nerf.ipynb | tensorflow/graphics | apache-2.0 |
Testing | # @title Load the test data
test_dataset, height, width = data_loaders.load_synthetic_nerf_dataset(
dataset_dir=DATASET_DIR,
dataset_name='lego',
split='val',
scale=0.125,
batch_size=1,
shuffle=False)
for testimg, focal, principal_point, transform_matrix in test_dataset.take(1):
testimg = te... | tensorflow_graphics/projects/radiance_fields/TFG_tiny_nerf.ipynb | tensorflow/graphics | apache-2.0 |
MSTL applied to a toy dataset
Create a toy dataset with multiple seasonalities
We create a time series with hourly frequency that has a daily and weekly seasonality which follow a sine wave. We demonstrate a more real world example later in the notebook. | t = np.arange(1, 1000)
daily_seasonality = 5 * np.sin(2 * np.pi * t / 24)
weekly_seasonality = 10 * np.sin(2 * np.pi * t / (24 * 7))
trend = 0.0001 * t**2
y = trend + daily_seasonality + weekly_seasonality + np.random.randn(len(t))
ts = pd.date_range(start="2020-01-01", freq="H", periods=len(t))
df = pd.DataFrame(data=... | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
Let's plot the time series | df["y"].plot(figsize=[10, 5]) | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
Decompose the toy dataset with MSTL
Let's use MSTL to decompose the time series into a trend component, daily and weekly seasonal component, and residual component. | mstl = MSTL(df["y"], periods=[24, 24 * 7])
res = mstl.fit() | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
If the input is a pandas dataframe then the output for the seasonal component is a dataframe. The period for each component is reflect in the column names. | res.seasonal.head()
ax = res.plot() | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
We see that the hourly and weekly seasonal components have been extracted.
Any of the STL parameters other than period and seasonal (as they are set by periods and windows in MSTL) can also be set by passing arg:value pairs as a dictionary to stl_kwargs (we will show that in an example now).
Here we show that we can st... | mstl = MSTL(
df,
periods=[24, 24 * 7], # The periods and windows must be the same length and will correspond to one another.
windows=[101, 101], # Setting this large along with `seasonal_deg=0` will force the seasonality to be periodic.
iterate=3,
stl_kwargs={
"trend":1001, # Setti... | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
MSTL applied to electricity demand dataset
Prepare the data
We will use the Victoria electricity demand dataset found here:
https://github.com/tidyverts/tsibbledata/tree/master/data-raw/vic_elec. This dataset is used in the original MSTL paper [1]. It is the total electricity demand at a half hourly granularity for th... | url = "https://raw.githubusercontent.com/tidyverts/tsibbledata/master/data-raw/vic_elec/VIC2015/demand.csv"
df = pd.read_csv(url)
df.head() | examples/notebooks/mstl_decomposition.ipynb | bashtage/statsmodels | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.