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 <name> 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 <br> 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.