markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
A first simple example Let's start from a simple example: We create a new class that subclasses keras.Model. We just override the method train_step(self, data). We return a dictionary mapping metric names (including the loss) to their current value. The input argument data is what gets passed to fit as training data:...
class CustomModel(keras.Model): def train_step(self, data): # Unpack the data. Its structure depends on your model and # on what you pass to `fit()`. x, y = data with tf.GradientTape() as tape: y_pred = self(x, training=True) # Forward pass # Compute the los...
site/en-snapshot/guide/keras/customizing_what_happens_in_fit.ipynb
tensorflow/docs-l10n
apache-2.0
Let's try this out:
import numpy as np # Construct and compile an instance of CustomModel inputs = keras.Input(shape=(32,)) outputs = keras.layers.Dense(1)(inputs) model = CustomModel(inputs, outputs) model.compile(optimizer="adam", loss="mse", metrics=["mae"]) # Just use `fit` as usual x = np.random.random((1000, 32)) y = np.random.ran...
site/en-snapshot/guide/keras/customizing_what_happens_in_fit.ipynb
tensorflow/docs-l10n
apache-2.0
Going lower-level Naturally, you could just skip passing a loss function in compile(), and instead do everything manually in train_step. Likewise for metrics. Here's a lower-level example, that only uses compile() to configure the optimizer: We start by creating Metric instances to track our loss and a MAE score. We i...
loss_tracker = keras.metrics.Mean(name="loss") mae_metric = keras.metrics.MeanAbsoluteError(name="mae") class CustomModel(keras.Model): def train_step(self, data): x, y = data with tf.GradientTape() as tape: y_pred = self(x, training=True) # Forward pass # Compute our own...
site/en-snapshot/guide/keras/customizing_what_happens_in_fit.ipynb
tensorflow/docs-l10n
apache-2.0
Supporting sample_weight & class_weight You may have noticed that our first basic example didn't make any mention of sample weighting. If you want to support the fit() arguments sample_weight and class_weight, you'd simply do the following: Unpack sample_weight from the data argument Pass it to compiled_loss & compile...
class CustomModel(keras.Model): def train_step(self, data): # Unpack the data. Its structure depends on your model and # on what you pass to `fit()`. if len(data) == 3: x, y, sample_weight = data else: sample_weight = None x, y = data with...
site/en-snapshot/guide/keras/customizing_what_happens_in_fit.ipynb
tensorflow/docs-l10n
apache-2.0
Providing your own evaluation step What if you want to do the same for calls to model.evaluate()? Then you would override test_step in exactly the same way. Here's what it looks like:
class CustomModel(keras.Model): def test_step(self, data): # Unpack the data x, y = data # Compute predictions y_pred = self(x, training=False) # Updates the metrics tracking the loss self.compiled_loss(y, y_pred, regularization_losses=self.losses) # Update th...
site/en-snapshot/guide/keras/customizing_what_happens_in_fit.ipynb
tensorflow/docs-l10n
apache-2.0
Wrapping up: an end-to-end GAN example Let's walk through an end-to-end example that leverages everything you just learned. Let's consider: A generator network meant to generate 28x28x1 images. A discriminator network meant to classify 28x28x1 images into two classes ("fake" and "real"). One optimizer for each. A loss...
from tensorflow.keras import layers # Create the discriminator discriminator = keras.Sequential( [ keras.Input(shape=(28, 28, 1)), layers.Conv2D(64, (3, 3), strides=(2, 2), padding="same"), layers.LeakyReLU(alpha=0.2), layers.Conv2D(128, (3, 3), strides=(2, 2), padding="same"), ...
site/en-snapshot/guide/keras/customizing_what_happens_in_fit.ipynb
tensorflow/docs-l10n
apache-2.0
Here's a feature-complete GAN class, overriding compile() to use its own signature, and implementing the entire GAN algorithm in 17 lines in train_step:
class GAN(keras.Model): def __init__(self, discriminator, generator, latent_dim): super(GAN, self).__init__() self.discriminator = discriminator self.generator = generator self.latent_dim = latent_dim def compile(self, d_optimizer, g_optimizer, loss_fn): super(GAN, self)...
site/en-snapshot/guide/keras/customizing_what_happens_in_fit.ipynb
tensorflow/docs-l10n
apache-2.0
Let's test-drive it:
# Prepare the dataset. We use both the training & test MNIST digits. batch_size = 64 (x_train, _), (x_test, _) = keras.datasets.mnist.load_data() all_digits = np.concatenate([x_train, x_test]) all_digits = all_digits.astype("float32") / 255.0 all_digits = np.reshape(all_digits, (-1, 28, 28, 1)) dataset = tf.data.Datase...
site/en-snapshot/guide/keras/customizing_what_happens_in_fit.ipynb
tensorflow/docs-l10n
apache-2.0
ํ™œ์šฉ ์˜ˆ์ œ
interval_point(0, 1, 0.5) interval_point(3, 2, 0.2)
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
ํ•ด์•ผ ํ•  ์ผ 1 (5์ ) ์œ„ ์ฝ”๋“œ๋ฅผ if ์กฐ๊ฑด๋ฌธ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋„๋ก ์ˆ˜์ •ํ•˜๊ณ ์ž ํ•œ๋‹ค. ์•„๋ž˜ ์ฝ”๋“œ์˜ ๋นˆ์นธ (A)๋ฅผ ์ฑ„์›Œ๋ผ. def interval_point_no_if(a, b, x): return (A) ๋ฌธ์ œ 2 ์•„๋ž˜ ์ฝ”๋“œ๋Š” ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ๋ฅผ ๋Œ€๋น„ํ•˜์—ฌ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•œ ์ฝ”๋“œ์ด๋‹ค.
while True: try: x = float(raw_input("Please type a new number: ")) inverse = 1.0 / x print("The inverse of {} is {}.".format(x, inverse)) break except ValueError: print("You should have given either an int or a float") except ZeroDivisionError: print("The inp...
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
ํ•ด์•ผ ํ•  ์ผ 2 (10์ ) ์•„๋ž˜ ์ฝ”๋“œ๊ฐ€ ํ•˜๋Š” ์ผ์„ ์„ค๋ช…ํ•˜๊ณ  ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ์˜ˆ์™ธ๋“ค์„ ๋‚˜์—ดํ•˜๋ฉฐ, ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ์–ด๋–ป๊ฒŒ ํ•˜๋Š”์ง€ ์„ค๋ช…ํ•˜๋ผ. ๋ฌธ์ œ 3 ์ฝค๋งˆ(',')๋กœ ๊ตฌ๋ถ„๋œ ๋ฌธ์ž๋“ค์ด ์ €์žฅ๋˜์–ด ์žˆ๋Š” ํŒŒ์ผ์„ csv(comma separated value) ํŒŒ์ผ์ด๋ผ ๋ถ€๋ฅธ๋‹ค. ์ˆซ์ž๋“ค๋กœ๋งŒ ๊ตฌ์„ฑ๋œ csv ํŒŒ์ผ์„ ์ธ์ž๋กœ ๋ฐ›์•„์„œ ๊ฐ ์ค„๋ณ„๋กœ ํฌํ•จ๋œ ์ˆซ์ž๋“ค๊ณผ ์ˆซ์ž๋“ค์˜ ํ•ฉ์„ ๊ณ„์‚ฐํ•˜์—ฌ ๋ณด์—ฌ์ฃผ๋Š” ํ•จ์ˆ˜ print_line_sum_of_file๊ณผ ๊ด€๋ จ๋œ ๋ฌธ์ œ์ด๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด test.txt ํŒŒ์ผ์— ์•„๋ž˜ ๋‚ด์šฉ์ด ๋“ค์–ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๋ฉด ์•„๋ž˜์˜ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์™€์•ผ ํ•œ๋‹ค. 1,3,5,8 0,4,7 1,18 In [...
f = open("test.txt", 'w') f.write("1,3,5,8\n0,4,7\n1,18") f.close()
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
๋˜ํ•œ print_line_sum_of_file์„ ์˜ˆ๋ฅผ ๋“ค์–ด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.
def print_line_sum_of_file(filename): g = open("test.txt", 'r') h = g.readlines() g.close() for line in h: sum = 0 k = line.strip().split(',') for i in range(len(k)): if i < len(k) -1: print(k[i] + " +"), else: print(k[...
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
์œ„ ํ•จ์ˆ˜๋ฅผ ์ด์ „์— ์ž‘์„ฑํ•œ ์˜ˆ์ œ ํŒŒ์ผ์— ์ ์šฉํ•˜๋ฉด ์˜ˆ์ƒ๋œ ๊ฒฐ๊ณผ๊ณผ ๋‚˜์˜จ๋‹ค.
print_line_sum_of_file("test.txt")
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
ํ•ด์•ผ ํ•  ์ผ 3 (5์ ) ๊ทธ๋Ÿฐ๋ฐ ์œ„์™€ ๊ฐ™์ด ์ •์˜ํ•˜๋ฉด ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๋ฌธ์ž์—ด์ด ํฌํ•จ๋˜์–ด ์žˆ์„ ๊ฒฝ์šฐ ValueError๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. ValuError๊ฐ€ ์–ด๋””์—์„œ ๋ฐœ์ƒํ•˜๋Š”์ง€ ๋‹ตํ•˜๋ผ. ํ•ด์•ผ ํ•  ์ผ 4 (10์ ) ์ด์ œ ๋ฐ์ดํ„ฐ ํŒŒ์ผ์— ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๋ฌธ์ž์—ด์ด ํฌํ•จ๋˜์–ด ์žˆ์„ ๊ฒฝ์šฐ๋„ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ๋„๋ก print_line_sum_of_file๋ฅผ ์ˆ˜์ •ํ•ด์•ผ ํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๋ฌธ์ž๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ๋Š” ๋‹จ์–ด๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ๋‹จ์–ด์˜ ๊ธธ์ด๋ฅผ ๋ง์…ˆ์— ์ถ”๊ฐ€ํ•˜๋„๋ก ํ•ด๋ณด์ž. ์˜ˆ์ œ: test.txt ํŒŒ์ผ์— ์•„๋ž˜ ๋‚ด์šฉ์ด ๋“ค์–ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๋ฉด ์•„๋ž˜ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์™€์•ผ ํ•œ๋‹ค. 1,3,5,8 1,cat4,7 co2...
def linear_1(a, b): return a + b def linear_2(a, b): return a * 2 + b
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
๋™์ผํ•œ ๋ฐฉ์‹์„ ๋ฐ˜๋ณตํ•˜๋ฉด ์ž„์˜์˜ ์ž์—ฐ์ˆ˜ n์— ๋Œ€ํ•ด linear_n ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ฆ‰, linear_n(a, b) = a * n + b ์ด ๋งŒ์กฑ๋˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋ฌดํ•œํžˆ ๋งŽ์ด ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ๊ทธ๋Ÿฐ ํ•จ์ˆ˜๋“ค์„ ์œ„์™€๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ์ •์˜ํ•˜๋Š” ๊ฒƒ์€ ๋งค์šฐ ๋น„ํšจ์œจ์ ์ด๋‹ค. ํ•œ ๊ฐ€์ง€ ๋Œ€์•ˆ์€ ๋ณ€์ˆ˜๋ฅผ ํ•˜๋‚˜ ๋” ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ์ด๋‹ค.
def linear_gen(n, a, b): return a * n + b
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
์œ„์™€ ๊ฐ™์ด linear_gen ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•œ ๋‹ค์Œ์— ํŠน์ • n์— ๋Œ€ํ•ด linear_n ์ด ํ•„์š”ํ•˜๋‹ค๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ๊ฐ„๋‹จํ•˜๊ฒŒ ์ •์˜ํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด n = 10์ธ ๊ฒฝ์šฐ์ด๋‹ค.
def linear_10(a, b): return linear_gen(10, a, b)
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
ํ•ด์•ผ ํ•  ์ผ 5 (10์ ) ๊ทธ๋Ÿฐ๋ฐ ์ด ๋ฐฉ์‹์€ ํŠน์ • linear_n์„ ์‚ฌ์šฉํ•˜๊ณ ์ž ํ•  ๋•Œ๋งˆ๋‹ค def ํ‚ค์›Œ๋“œ๋ฅผ ์ด์šฉํ•˜์—ฌ ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•ด์•ผ ํ•˜๋Š” ๋‹จ์ ์ด ์žˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ๊ณ ๊ณ„ํ•จ์ˆ˜๋ฅผ ํ™œ์šฉํ•˜๋ฉด def ํ‚ค์›Œ๋“œ๋ฅผ ํ•œ ๋ฒˆ๋งŒ ์‚ฌ์šฉํ•ด๋„ ๋ชจ๋“  ์ˆ˜ n์— ๋Œ€ํ•ด linear_n ํ•จ์ˆ˜๋ฅผ ํ•„์š”ํ•  ๋•Œ๋งˆ๋‹ค ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์•„๋ž˜ ๋“ฑ์‹์ด ๋งŒ์กฑ์‹œํ‚ค๋Š” ๊ณ ๊ณ„ํ•จ์ˆ˜ linear_high๋ฅผ ์ •์˜ํ•  ์ˆ˜ ์žˆ๋‹ค. linear_10(3, 5) = linear_high(10)(3, 5) linear_15(2, 7) = linear_high(15)(2, 7) ์•„๋ž˜ ์ฝ”๋“œ๊ฐ€ ์œ„ ๋“ฑ์‹์„ ๋งŒ์กฑ์‹œํ‚ค๋„๋ก ๋นˆ์ž๋ฆฌ (A)์™€ (B...
names = ["Koh", "Kang", "Park", "Kwon", "Lee", "Yi", "Kim", "Jin"]
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
K๋กœ ์‹œ์ž‘ํ•˜๋Š” ์ด๋ฆ„์œผ๋กœ๋งŒ ๊ตฌ์„ฑ๋œ ๋ฆฌ์ŠคํŠธ๋Š” ํŒŒ์ด์ฌ ๋‚ด์žฅํ•จ์ˆ˜ filter๋ฅผ ์ด์šฉํ•˜์—ฌ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.
def StartsWithK(s): return s[0] == 'K' K_names = filter(StartsWithK, names) K_names
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
ํ•ด์•ผ ํ•  ์ผ 7 (15์ ) filter ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด์„œ ๋™์ผํ•œ ๊ธฐ๋Šฅ์„ ์ˆ˜ํ–‰ํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๊ณ ์ž ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋นˆ์นธ (A), (B), (C)๋ฅผ ์ฑ„์›Œ๋ผ. K_names = [] for name in names: if (A) : (B) else: (C) ํ•ด์•ผ ํ•  ์ผ 8 (5์ ) K๋กœ ์‹œ์ž‘ํ•˜๋Š” ์ด๋ฆ„๋งŒ์œผ๋กœ ๊ตฌ์„ฑ๋œ ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ธ€์ž ์ˆœ์„œ์˜ __์—ญ์ˆœ__์œผ๋กœ ์ •๋ ฌํ•˜๊ณ ์ž ํ•œ๋‹ค. ์•„๋ž˜ ์ฝ”๋“œ๊ฐ€ ๋ฆฌ์ŠคํŠธ ๊ด€๋ จ ํŠน์ • ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋„๋ก ๋นˆ ์ž๋ฆฌ (D)๋ฅผ ์ฑ„์›Œ๋ผ. K_names.(D) ๋ฌธ์ œ 7 ํŒŒ์ด์ฌ ๋‚ด์žฅํ•จ์ˆ˜ map์˜ ๊ธฐ...
map(lambda x : x ** 2, range(5))
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
map ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฐฉ์‹์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
def list_square(num): L = [] for i in range(num): L.append(i ** 2) return L list_square(5)
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
ํ•ด์•ผ ํ•  ์ผ 9 (10์ ) list_square ํ•จ์ˆ˜์™€ ๋™์ผํ•œ ๊ธฐ๋Šฅ์„ ์ˆ˜ํ–‰ํ•˜๋Š” ํ•จ์ˆ˜ list_square_comp ํ•จ์ˆ˜๋ฅผ ๋ฆฌ์ŠคํŠธ ์กฐ๊ฑด์ œ์‹œ๋ฒ•์„ ํ™œ์šฉํ•˜์—ฌ ์•„๋ž˜์ฒ˜๋Ÿผ ๊ตฌํ˜„ํ•˜๊ณ ์ž ํ•œ๋‹ค. ๋นˆ์ž๋ฆฌ (A)๋ฅผ ์ฑ„์›Œ๋ผ. def list_square_comp(num): return (A) ๋ฌธ์ œ 8 ๋‹ค์„ฏ ๊ฐœ์˜ ๋„์‹œ๋ช…๊ณผ ๊ฐ ๋„์‹œ์˜ ์ธ๊ตฌ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ๋‘ ๊ฐœ์˜ ๋ฆฌ์ŠคํŠธ๊ฐ€ ์•„๋ž˜์ฒ˜๋Ÿผ ์žˆ๋‹ค.
cities = ['A', 'B', 'C', 'D', 'E'] populations = [20, 30, 140, 80, 25]
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
๋„์‹œ์ด๋ฆ„๊ณผ ์ธ๊ตฌ์ˆ˜๋ฅผ ์Œ์œผ๋กœ ๊ฐ–๋Š” ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค.
city_pop = [] for i in range(len(cities)): city_pop.append((cities[i], populations[i])) city_pop
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
city_pop๋ฅผ ์ด์šฉํ•˜์—ฌ ์˜ˆ๋ฅผ ๋“ค์–ด C ๋„์‹œ์˜ ์ธ๊ตฌ์ˆ˜๋ฅผ ํ™•์ธํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
city_pop[2][1]
ref_materials/exams/2015/midterm.ipynb
liganega/Gongsu-DataSci
gpl-3.0
Una vez hecho esto ya deberiamos tener disponible la cell magic para ser usada:
%%tutor --lang python3 a = 1 b = 2 def add(x, y): return x + y c = add(a, b)
tutormagic.ipynb
Pybonacci/notebooks
bsd-2-clause
Ahora un ejemplo con javascript:
%%tutor --lang javascript var a = 1; var b = 1; console.log(a + b);
tutormagic.ipynb
Pybonacci/notebooks
bsd-2-clause
Macro Basics A Macro command begins with a percent sign (% similar to the %sql magic command) and can be found anywhere within a %sql line or %%sql block. Macros must be separated from other text in the SQL with a space. To define a macro, the %%sql macro &lt;name&gt; command is used. The body of the macro is found in...
%%sql macro emptable select * from employee
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
The name of the macro follows the %%sql macro command and is case sensitive. To use the macro, we can place it anywhere in the %sql block. This first example uses it by itself.
%sql %emptable
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
The actual SQL that is generated is not shown by default. If you do want to see the SQL that gets generated, you can use the -e (echo) option to display the final SQL statement. The following example will display the generated SQL. Note that the echo setting is only used to display results for the current cell that is ...
%%sql -e %emptable
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Since we can use the %emptable anywhere in our SQL, we can add additional commands around it. In this example we add some logic to the select statement.
%%sql %emptable where empno = '000010'
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Macros can also have parameters supplied to them. The parameters are included after the name of the macro. Here is a simple macro which will use the first parameter as the name of the column we want returned from the EMPLOYEE table.
%%sql macro emptable SELECT {1} FROM EMPLOYEE
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
This example illustrates two concepts. The MACRO command will replace any existing macro with the same name. Since we already have an emptable macro, the macro body will be replaced with this code. In addition, macros only exist for the duration of your notebook. If you create another Jupyter notebook, it will not cont...
%%sql %emptable(lastname)
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
The remainder of this notebook will explore the advanced features of macros. Macro Parameters Macros can have up to 9 parameters supplied to them. The parameters are numbered from 1 to 9, left to right in the argument list for the macro. For instance, the following macro has 5 paramters: %emptable(lastname,firstnme,sal...
%%sql macro emptable display on SELECT {1},{2},{3},{4} FROM EMPLOYEE WHERE EMPNO = '{5}'
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Note that the EMPNO field is a character field in the EMPLOYEE table. Even though the employee number was supplied as a string, the quotes are not included in the parameter. The macro places quotes around the parameter {5} so that it is properly used in the SQL statement. The other feature of this macro is that the dis...
%sql %emptable(lastname,firstnme,salary,bonus,'000010')
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
We can modify the macro to assume that the parameters will include the quotes in the string.
%%sql macro emptable SELECT {1},{2},{3},{4} FROM EMPLOYEE WHERE EMPNO = {5}
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
We just have to make sure that the quotes are part of the parameter now.
%sql -e %emptable(lastname,firstnme,salary,bonus,"'000010'")
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
We could use the square brackets as an alternative way of passing the parameter.
%sql -e %emptable(lastname,firstnme,salary,bonus,['000010'])
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Parameters can also be named in a macro. To name an input value, the macro needs to use the format: field=value For instance, the following macro call will have 2 numbered parameters and one named parameter: %showemp(firstnme,lastname,logic="WHERE EMPNO='000010'") From within the macro the parameter count would be 2 an...
%%sql macro showemp SELECT {1},{2} FROM EMPLOYEE {logic} %sql %showemp(firstnme,lastname,logic="WHERE EMPNO='000010'") %sql %showemp(firstnme,logic="WHERE EMPNO='000010'",lastname)
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Named parameters are useful when there are many options within the macro and you don't want to keep track of which position it is in. In addition, if you have a variable number of parameters, you should use named parameters for the fixed (required) parameters and numbered parameters for the optional ones. Macro Coding ...
%%sql macro showdisplay SELECT * FROM EMPLOYEE FETCH FIRST ROW ONLY
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Using the -e flag will display the final SQL that is run.
%sql -e %showdisplay
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
If we remove the -e option, the final SQL will not be shown.
%sql %showdisplay
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Exit Command The exit command will terminate the processing within a macro and not run the generated SQL. You would use this when a condition is not met within the macro (like a missing parameter).
%%sql macro showexit echo This message gets shown SELECT * FROM EMPLOYEE FETCH FIRST ROW ONLY exit echo This message does not get shown
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
The macro that was defined will not show the second statement, nor will it execute the SQL that was defined in the macro body.
%sql %showexit
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Echo Command As you already noticed in the previous example, the echo command will display information on the screen. Any text following the command will have variables substituted and then displayed with a green box surrounding it. The following code illustates the use of the command.
%%sql macro showecho echo Here is a message echo Two lines are shown
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
The echo command will show each line as a separate box.
%sql %showecho
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
If you want to have a message go across multiple lines use the &lt;br&gt; to start a new line.
%%sql macro showecho echo Here is a paragraph. <br> And a final paragraph. %sql %showecho
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Var Command The var (variable) command sets a macro variable to a value. A variable is referred to in the macro script using curly braces {name}. By default the arguments that are used in the macro call are assigned the variable names {1} to {9}. If you use a named argument (option="value") in the macro call, a variabl...
%%sql macro initialize var $hello Hello There var hello You won't see this %%sql macro runit echo The value of hello is *{hello}* echo {$hello}
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Calling runit will display the variable that was set in the first macro.
%sql %initialize %sql %runit
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
A variable can be converted to uppercase by placing the ^ beside the variable name or number.
%%sql macro runit echo The first parameter is {^1} %sql %runit(Hello There)
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
The string following the variable name can include quotes and these will not be removed. Only quotes that are supplied in a parameter to a macro will have the quotes removed.
%%sql macro runit var hello This is a long string without quotes var hello2 'This is a long string with quotes' echo {hello} <br> {hello2} %sql %runit
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
When passing parameters to a macro, the program will automatically create variables based on whether they are positional parameters (1, 2, ..., n) or named parameters. The following macro will be used to show how parameters are passed to the routine.
%%sql macro showvar echo parm1={1} <br>parm2={2} <br>message={message}
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Calling the macro will show how the variable names get assigned and used.
%sql %showvar(parameter 1, another parameter,message="Hello World")
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
If you pass an empty value (or if a variable does not exist), a "null" value will be shown.
%sql %showvar(1,,message="Hello World")
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
An empty string also returns a null value.
%sql %showvar(1,2,message="")
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Finally, any string that is supplied to the macro will not include the quotes in the variable. The Hello World string will not have quotes when it is displayed:
%sql %showvar(1,2,message="Hello World")
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
You need to supply the quotes in the script or macro when using variables since quotes are stripped from any strings that are supplied.
%%sql macro showvar echo parm1={1} <br>parm2={2} <br>message='{message}' %sql %showvar(1,2,message="Hello World")
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
The count of the total number of parameters passed is found in the {argc} variable. You can use this variable to decide whether or not the user has supplied the proper number of arguments or change which code should be executed.
%%sql macro showvar echo The number of unnamed parameters is {argc}. The where clause is *{where}*.
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Unnamed parameters are included in the count of arguments while named parameters are ignored.
%sql %showvar(1,2,option=nothing,3,4,where=)
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
If/Else/Endif Command If you need to add conditional logic to your macro then you should use the if/else/endif commands. The format of the if statement is: if variable condition value statements else statements endif The else portion is optional, but the block must be closed with the endif command. If statements ...
%%sql macro showif if {argc} = 0 echo No parameters supplied if {option} <> null echo The optional parameter option was set: {option} endif else if {argc} = "1" echo One parameter was supplied else echo More than one parameter was supplied: {argc} endif endif
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Running the previous macro with no parameters will check to see if the option keyword was used.
%sql %showif
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Now include the optional parameter.
%sql %showif(option="Yes there is an option")
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Finally, issue the macro with multiple parameters.
%sql %showif(Here,are,a,number,of,parameters)
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
One additional option is available for variable substitution. If the first character of the variable name or parameter number is the ^ symbol, it will uppercase the entire string.
%%sql macro showif if {option} <> null echo The optional parameter option was set: {^option} endif %sql %showif(option="Yes there is an option")
Db2 Jupyter Macros.ipynb
DB2-Samples/db2jupyter
apache-2.0
Lorsqu'on dรฉcrit n'importe quel algorithme, on รฉvoque toujours son coรปt, souvent une formule de ce style : $$O(n^u(\ln_2 n)^v)$$ $u$ et $v$ sont des entiers. $v$ est souvent soit 0, soit 1. Mais d'oรน vient ce logarithme ? Le premier algorithme auquel on pense et dont le coรปt correspond au cas $u=0$ et $v=1$ est la rech...
from pyquickhelper.helpgen import NbImage NbImage("images/dicho.png")
_doc/notebooks/1a/recherche_dichotomique.ipynb
sdpython/ensae_teaching_cs
mit
Version itรฉrative
def recherche_dichotomique(element, liste_triee): a = 0 b = len(liste_triee)-1 m = (a+b)//2 while a < b : if liste_triee[m] == element: return m elif liste_triee[m] > element: b = m-1 else : a = m+1 m = (a+b)//2 return a li = [0, 4...
_doc/notebooks/1a/recherche_dichotomique.ipynb
sdpython/ensae_teaching_cs
mit
Version rรฉcursive
def recherche_dichotomique_recursive( element, liste_triee, a = 0, b = -1 ): if a == b : return a if b == -1 : b = len(liste_triee)-1 m = (a+b)//2 if liste_triee[m] == element: return m elif liste_triee[m] > element: return recherche_dichotomique_recursive(element, ...
_doc/notebooks/1a/recherche_dichotomique.ipynb
sdpython/ensae_teaching_cs
mit
Version rรฉcursive 2 L'ajout des parametrรจs a et b peut paraรฎtre un peu lourd. Voici une troisiรจme implรฉmentation en Python (toujours rรฉcursive) :
def recherche_dichotomique_recursive2(element, liste_triee): if len(liste_triee)==1 : return 0 m = len(liste_triee)//2 if liste_triee[m] == element: return m elif liste_triee[m] > element: return recherche_dichotomique_recursive2(element, liste_triee[:m]) else : retur...
_doc/notebooks/1a/recherche_dichotomique.ipynb
sdpython/ensae_teaching_cs
mit
Read Expression data using pandas. Notice that pandas can read URLs (!), not just files on your computer!
csv = "https://media.githubusercontent.com/media/olgabot/macosko2015/" \ "master/data/05_make_rentina_subsets_for_teaching/big_clusters_expression.csv" expression = pd.read_csv(csv, index_col=0) print(expression.shape) expression.head()
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Exercise 1 Now use pd.read_csv to read the csv file of the cell metadata
csv = "https://media.githubusercontent.com/media/olgabot/macosko2015/" \ "master/data/05_make_rentina_subsets_for_teaching/big_clusters_cell_metadata.csv" # YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
csv = "https://media.githubusercontent.com/media/olgabot/macosko2015/" \ "master/data/05_make_rentina_subsets_for_teaching/big_clusters_cell_metadata.csv" cell_metadata = pd.read_csv(csv, index_col=0) print(cell_metadata.shape) cell_metadata.head()
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
To correlate columns of dataframes in pandas, you use the function .corr. Let's look at the documentation of .corr Is the default method Pearson or Spearman correlation? Can you correlate between rows, or only between columns?
expression.corr?
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Since .corr only correlates between columns, we need to transpose our dataframe. Here's a little animation of matrix transposition from Wikipedia: Exercise 2 Transpose the expression matrix so the cells are the columns, which makes it easy to calculate correlations. How do you transpose a dataframe in pandas? (hint: g...
# YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
expression_t = expression.T print(expression_t.shape) expression_t.head()
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Exercise 3 Use .corr to calculate the Spearman correlation of the transposed expression dataframe. Make sure to print the shape, and show the head of the resulting dataframe.
# YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
expression_corr = expression_t.corr(method='spearman') print(expression_corr.shape) expression_corr.head()
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Pro tip: if your matrix is really big, here's a trick to make spearman correlations faster Remember that spearman correlation is equal to performing pearson correlation on the ranks? Well, that's exactly what's happening inside the .corr(method='spearman') function! Every time it's calculating spearman, it's converting...
expression_t.rank?
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Notice we can specify axis=1 or axis=0, but what does that really mean? Was this ascending along rows, or ascending along columns? To figure this out, let's use a small, simple dataframe:
df = pd.DataFrame([[5, 6, 7], [5, 6, 7], [5, 6, 7]]) df
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Exercise 4 Try axis=0 when using rank on this df
# YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
df.rank(axis=0)
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Did that make ranks ascending along columns or along rows? Exercise 5 Now try axis=1 when using rank on this df
# YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
df.rank(axis=1)
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Did that make ranks ascending along columns or along rows? Exercise 6 To get the gene (row) ranks for each cell (column), do we want axis=1 or axis=0? Perform .rank on the transposed expression matrix (expression_t), print the shape of the resulting ranks, and show the head() of it.
# YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
ranks = expression_t.rank(axis=0) print(ranks.shape) ranks.head()
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Exercise 6 Now that you're armed with all this information, we'll calculate the ranks. While you're at it, let's compare the time it takes to run ("runtime") of .corr(method="pearson") on the ranks matrix vs .corr(method="spearman") on the expression matrix. Perform pearson correlation on the ranks Check that it is eq...
# YOUR CODE HERE # YOUR CODE HERE # YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
%timeit expression_t.corr(method='spearman') %timeit ranks.corr(method='pearson') ranks_corr = ranks.corr(method='pearson') print(ranks_corr.shape) ranks_corr.head()
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Use inequality to see if any points are not the same. If this is equal to zero, then we know that they are ALL the same.
(ranks_corr != expression_corr).sum().sum()
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
This is a flip of checking for equality, which is a little trickier because then you have to know exactly how many items are in the matrix. Since we have a 300x300 matrix, that multiplication is a little easier to do in your head and know that you got the right answer.
(ranks_corr == expression_corr).sum().sum()
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Make a heatmap!! Now we are ready to make a clustered heatmap! We'll use seaborn's sns.clustermap. Let's read the documentation for sns.clustermap. What is the default distance metric and linkage method?
sns.clustermap?
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Exercise 7 Now run sns.clustermap on either the ranks or expression correlation matrices, since they are equal :)
# YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
sns.clustermap(expression_corr)
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
How can we add the colors labeling the rows and columns? Check the documentation for sns.clustermap again: Exercise 8
# YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
sns.clustermap?
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Since I am not a color design expert, I defer to color design experts in choosing my color palettes. One such expert is Cynthia Brewer, who made a ColorBrewer (hah!) list of color maps for both increasing quantity (shades), and for categories (differing colors). As a reference, I like using this demo of every ColorBrew...
palette = sns.color_palette('Accent', n_colors=3) palette
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Huh that's a bunch of weird numbers. What do they mean? Turns out it's a value from 0 to 1 representing the red, green, and blue (RGB) color channels that computers understand. But I'm not a computer .... what am I supposed to do?? Turns out, seaborn also has a very convenient function called palplot to plot the entire...
sns.palplot(palette)
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Exercise 9 Get the color palette for the "Set2" colormap and specify that you want 6 colors (read the documentation of sns.color_palette) Plot the color palette
# YOUR CODE HERE # YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
set2 = sns.color_palette('Set2', n_colors=6) sns.palplot(set2)
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
If you are more advanced and want access to more colormaps, I recommend checking out palettable. Assign colors to clusters To set a specific color to each cluster, we'll need to see the unique clusters here. For an individual column (called a "Series" in pandas-speak), how can we get only the unique items? Exercise 10 ...
# YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
cluster_ids_unique = cell_metadata['cluster_celltype_with_id'].unique() cluster_ids_unique
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Detour: zip and dict To map colors to each cluster name, we need to talk about some built-in functions in Python, called zip and dict For this next part, we'll use the built-in function zip which is very useful. It acts like a zipper (like for clothes) to glue together the pairs of items in two lists:
english = ["hello", "goodbye", "no", "yes", "please", "thank you",] spanish = ["hola", "adios", "no", "si", "por favor", "gracias"] zip(english, spanish)
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
To be memory efficient, this doesn't show us what's inside right away. To look inside a zip object, we can use list:
list(zip(english, spanish))
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit
Exercise 11 What happened to "please" and "thank you" from english? Make another list, called spanish2, that contains the Spanish words for "please" and "thank you" (again, google knows everything), then call zip on english and spanish2. Don't forget to use list on them!
# YOUR CODE HERE
notebooks/1.4_make_clustered_heatmap.ipynb
olgabot/cshl-singlecell-2017
mit