Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
8,500 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Содержание<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Переменные" data-toc-modified-id="Переменные-1">Переменные</a></span></li><li><span><a href="#Параллельное-присваивание" data-toc-modified-id="Параллельное-присваивание-2">Параллельное присваивание</a></span></li><li><span><a href="#Ввод-вывод" data-toc-modified-id="Ввод-вывод-3">Ввод-вывод</a></span></li><li><span><a href="#Арифметические-операции" data-toc-modified-id="Арифметические-операции-4">Арифметические операции</a></span></li><li><span><a href="#Арифметические-выражения" data-toc-modified-id="Арифметические-выражения-5">Арифметические выражения</a></span></li><li><span><a href="#Преобразование-типов" data-toc-modified-id="Преобразование-типов-6">Преобразование типов</a></span></li></ul></div>
Переменные, выражения и простой ввод-вывод
Переменные
Как и в любом другом языке программирования, в Python есть переменные. Присвоить переменной значение можно так
Step1: Вы могли заметить, что мы нигде не объявили тип переменных a, b и c. В Python этого делать не надо. Язык сам выберет тип по значению, которое вы положили в переменную. Для переменной a это тип int (целое число). Для b — str (строка). Для c — float (вещественное число).
В ближайшем будущем вы скорее всего познакомитесь с такими типами
Step2: Параллельное присваивание
В Python можно присвоит значения сразу нескольким переменным
Step3: При этом Python сначала вычисляет все значения справа, а потом уже присваивает вычисленные значения переменным слева
Step4: Это позволяет, например, поменять значения двух переменных в одну строку
Step5: Ввод-вывод
Как вы уже видели, для вывода на экран в Python есть функция print. Ей можно передавать несколько значений через запятую — они будут выведены в одной строке через пробел
Step6: Для ввода с клавиатуры есть функция input. Она считывает одну строку целиком
Step7: Ага, что-то пошло не так! Мы получили 23 вместо 5. Так произошло, потому что input() возращает строку (str), а не число (int). Чтобы это исправить нам надо явно преобразовать результат функции input() к типу int.
Step8: Так-то лучше
Step9: Эту ошибку можно перевести с английского так
Step10: Вещественное деление всегда даёт вещественное число (float) в результате, независимо от аргументов (если делитель не 0)
Step11: Результат целочисленного деления — это результат вещественного деления, округлённый до ближайшего меньшего целого
Step12: Остаток от деления — это то что осталось от числа после целочисленного деления.
Если c = a // b, то a можно представить в виде a = c * b + r. В этом случае r — это остаток от деления.
Пример
Step13: Возведение a в степень b — это перемножение a на само себя b раз. В математике обозначается как $a^b$.
Step14: Возведение в степень работает для вещественных a и отрицательных b. Число в отрицательной степени — это единица делённое на то же число в положительной степени
Step15: Давайте посмотрим что получится, если возвести в большую степень целое число
Step16: В отличии от C++ или Pascal, Python правильно считает результат, даже если в результате получается очень большое число.
А что если возвести вещественное число в большую степень?
Step17: Запись вида <число>e<степень> — это другой способ записать $\text{<число>} \cdot 10^\text{<степень>}$. То есть
Step18: В школе вам, наверное, рассказывали, что квадратный корень нельзя извлекать из отрицательных чисел. С++ и Pascal при попытке сделать это выдадут ошибку. Давайте посмотрим, что сделает Python
Step19: В общем, это не совсем правда. Извлекать квадратный корень из отрицательных чисел, всё-таки, можно, но в результате получится не вещественное, а так называемое комплексное число. Если вы получили страшную такую штуку в своей программе, скорее всего ваш код взял корень из отрицательного числа, а значит вам надо искать в нём ошибку. В ближайшее время вам нет необходимости что-то знать про комплексные числа.
Арифметические выражения
Естественно, как и во многих других языках программирования, вы можете составлять большие выражения из переменных, чисел, арифметических операций и скобок. Например
Step20: В примере выше переменной c присвоено значение выражения
$$\frac{a^2 + b \cdot 3}{9 - b \text{ mod } (a + 1)}$$
При отсутствии скобок арфиметические операции в выражении вычисляются в порядке приоритета (см. таблицу выше). Сначала выполняются операции с приоритетом 1, потом с приоритетом 2 и т.д. При одинаковом приоритете вычисление происходит слева направо. Вы можете использовать скобки, чтобы менять порядок вычисления.
Step21: Преобразование типов
Если у вас есть значение одного типа, то вы можете преобразовать его к другому типу, вызвав функцию с таким же именем
Step22: Больше примеров | Python Code:
a = 5
b = "Hello, LKSH"
c = 5.0
print(a)
print(b)
print(c)
Explanation: <h1>Содержание<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Переменные" data-toc-modified-id="Переменные-1">Переменные</a></span></li><li><span><a href="#Параллельное-присваивание" data-toc-modified-id="Параллельное-присваивание-2">Параллельное присваивание</a></span></li><li><span><a href="#Ввод-вывод" data-toc-modified-id="Ввод-вывод-3">Ввод-вывод</a></span></li><li><span><a href="#Арифметические-операции" data-toc-modified-id="Арифметические-операции-4">Арифметические операции</a></span></li><li><span><a href="#Арифметические-выражения" data-toc-modified-id="Арифметические-выражения-5">Арифметические выражения</a></span></li><li><span><a href="#Преобразование-типов" data-toc-modified-id="Преобразование-типов-6">Преобразование типов</a></span></li></ul></div>
Переменные, выражения и простой ввод-вывод
Переменные
Как и в любом другом языке программирования, в Python есть переменные. Присвоить переменной значение можно так:
End of explanation
a = 5.0
s = "LKSH students are awesome =^_^="
print(type(a))
print(type(b))
Explanation: Вы могли заметить, что мы нигде не объявили тип переменных a, b и c. В Python этого делать не надо. Язык сам выберет тип по значению, которое вы положили в переменную. Для переменной a это тип int (целое число). Для b — str (строка). Для c — float (вещественное число).
В ближайшем будущем вы скорее всего познакомитесь с такими типами:
| Тип | Python | Аналог в C++ | Аналог в Pascal |
| --- | --- | --- | --- |
| Целое число | int | int | Integer |
| Вещественное число | float | double | Double |
| Строка | str | std::string | String |
| Логический | bool | bool | Boolean |
| Массив | list | std::vector<> | Array |
| Множество | set | std::set<> | нет |
| Словарь | dict | std::map<> | нет |
Тип переменной можно узнать с помощью функции type:
End of explanation
a, b = 3, 5
print(a)
print(b)
Explanation: Параллельное присваивание
В Python можно присвоит значения сразу нескольким переменным:
End of explanation
a = 3
b = 5
a, b = b, a + b
print(a)
print(b)
Explanation: При этом Python сначала вычисляет все значения справа, а потом уже присваивает вычисленные значения переменным слева:
End of explanation
a = "apple"
b = "banana"
a, b = b, a
print(a)
print(b)
Explanation: Это позволяет, например, поменять значения двух переменных в одну строку:
End of explanation
a = 2
b = 3
print(a, "+", b, "=", a + b)
Explanation: Ввод-вывод
Как вы уже видели, для вывода на экран в Python есть функция print. Ей можно передавать несколько значений через запятую — они будут выведены в одной строке через пробел:
End of explanation
a = input()
b = input()
print(a + b)
Explanation: Для ввода с клавиатуры есть функция input. Она считывает одну строку целиком:
End of explanation
a = int(input())
b = int(input())
print(a + b)
Explanation: Ага, что-то пошло не так! Мы получили 23 вместо 5. Так произошло, потому что input() возращает строку (str), а не число (int). Чтобы это исправить нам надо явно преобразовать результат функции input() к типу int.
End of explanation
a = int(input)
b = int(input)
print(a + b)
Explanation: Так-то лучше :)
Частая ошибка — забыть внутренние скобки после функции input. Давайте посмотрим, что в этом случае произойдёт:
End of explanation
print(11 + 7, 11 - 7, 11 * 7, (2 + 9) * (12 - 5))
Explanation: Эту ошибку можно перевести с английского так:
ОшибкаТипа: аргумент функции int() должен быть строкой, последовательностью байтов или числом, а не функцией
Теперь вы знаете что делать, если получите такую ошибку ;)
Арифметические операции
Давайте научимся складывать, умножать, вычитать и производить другие операции с целыми (тип int) или вещественными (тип float) числами. Стоит понимать, что целое число и вещественное число — это совсем разные вещи для компьютера.
Список основных бинарных (требующих 2 переменных) арифметических действий, которые вам понадобятся:
| Действие | Обозначение в Python | Аналог в C++ | Аналог в Pascal | Приоритет |
| --- | --- | --- | --- | --- |
| Сложение | a + b | a + b | a + b | 3 |
| Вычитание | a - b | a - b | a - b | 3 |
| Умножение | a * b | a * b | a * b | 2 |
| Вещественное деление | a / b | a / b | a / b | 2 |
| Целочисленное деление (с округлением вниз) | a // b | a / b | a div b | 2 |
| Остаток от деления | a % b | a % b | a mod b | 2 |
| Возведение в степень | a ** b | pow(a, b) | power(a, b) | 1 |
Сложение, вычитание и умножение работают точно также, как и в других языках:
End of explanation
print(12 / 8, 12 / 4, 12 / -7)
Explanation: Вещественное деление всегда даёт вещественное число (float) в результате, независимо от аргументов (если делитель не 0):
End of explanation
print(12 // 8, 12 // 4, 12 // -7)
Explanation: Результат целочисленного деления — это результат вещественного деления, округлённый до ближайшего меньшего целого:
End of explanation
print(12 % 8, 12 % 4, 12 % -7)
Explanation: Остаток от деления — это то что осталось от числа после целочисленного деления.
Если c = a // b, то a можно представить в виде a = c * b + r. В этом случае r — это остаток от деления.
Пример: a = 20, b = 8, c = a // b = 2. Тогда a = c * b + r превратится в 20 = 2 * 8 + 4. Остаток от деления — 4.
End of explanation
print(5 ** 2, 2 ** 4, 13 ** 0)
Explanation: Возведение a в степень b — это перемножение a на само себя b раз. В математике обозначается как $a^b$.
End of explanation
print(2.5 ** 2, 2 ** -3)
Explanation: Возведение в степень работает для вещественных a и отрицательных b. Число в отрицательной степени — это единица делённое на то же число в положительной степени: $a^{-b} = \frac{1}{a^b}$
End of explanation
print(5 ** 100)
Explanation: Давайте посмотрим что получится, если возвести в большую степень целое число:
End of explanation
print(5.0 ** 100)
Explanation: В отличии от C++ или Pascal, Python правильно считает результат, даже если в результате получается очень большое число.
А что если возвести вещественное число в большую степень?
End of explanation
print(2 ** 0.5, 9 ** 0.5)
Explanation: Запись вида <число>e<степень> — это другой способ записать $\text{<число>} \cdot 10^\text{<степень>}$. То есть:
$$\text{7.888609052210118e+69} = 7.888609052210118 \cdot 10^{69}$$
а это то же самое, что и 7888609052210118000000000000000000000000000000000000000000000000000000.
Этот результат не настолько точен, как предыдущий. Так происходит потому, что для хранения каждого вещественного числа Python использует фиксированное количество памяти, а значит может хранить число только с ограниченной точностью.
Возведение в степень также работает и для вещественной степени. Например $\sqrt{a} = a^\frac{1}{2} = a^{0.5}$
End of explanation
print((-4) ** 0.5)
Explanation: В школе вам, наверное, рассказывали, что квадратный корень нельзя извлекать из отрицательных чисел. С++ и Pascal при попытке сделать это выдадут ошибку. Давайте посмотрим, что сделает Python:
End of explanation
a = 4
b = 11
c = (a ** 2 + b * 3) / (9 - b % (a + 1))
print(c)
Explanation: В общем, это не совсем правда. Извлекать квадратный корень из отрицательных чисел, всё-таки, можно, но в результате получится не вещественное, а так называемое комплексное число. Если вы получили страшную такую штуку в своей программе, скорее всего ваш код взял корень из отрицательного числа, а значит вам надо искать в нём ошибку. В ближайшее время вам нет необходимости что-то знать про комплексные числа.
Арифметические выражения
Естественно, как и во многих других языках программирования, вы можете составлять большие выражения из переменных, чисел, арифметических операций и скобок. Например:
End of explanation
print(2 * 2 + 2)
print(2 * (2 + 2))
Explanation: В примере выше переменной c присвоено значение выражения
$$\frac{a^2 + b \cdot 3}{9 - b \text{ mod } (a + 1)}$$
При отсутствии скобок арфиметические операции в выражении вычисляются в порядке приоритета (см. таблицу выше). Сначала выполняются операции с приоритетом 1, потом с приоритетом 2 и т.д. При одинаковом приоритете вычисление происходит слева направо. Вы можете использовать скобки, чтобы менять порядок вычисления.
End of explanation
a = "-15"
print(a, int(a), float(a))
Explanation: Преобразование типов
Если у вас есть значение одного типа, то вы можете преобразовать его к другому типу, вызвав функцию с таким же именем:
End of explanation
# a_int, b_float, c_str - это просто имена переменных.
# Они так названы, чтобы было проще разобраться, где какое значение лежит.
a_int = 3
b_float = 5.0
c_str = "10"
print(a_int, b_float, c_str)
# При попытке сложить без преобразования мы получили бы ошибку, потому что Python
# не умеет складывать числа со строками.
print("a_int + int(c_str) =", a_int + int(c_str))
print("str(a_int) + str(b_float) =", str(a_int) + str(b_float))
print("float(c_str) =", float(c_str))
Explanation: Больше примеров:
End of explanation |
8,501 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this tutorial, you will learn what a categorical variable is, along with three approaches for handling this type of data.
Introduction
A categorical variable takes only a limited number of values.
Consider a survey that asks how often you eat breakfast and provides four options
Step1: We take a peek at the training data with the head() method below.
Step2: Next, we obtain a list of all of the categorical variables in the training data.
We do this by checking the data type (or dtype) of each column. The object dtype indicates a column has text (there are other things it could theoretically be, but that's unimportant for our purposes). For this dataset, the columns with text indicate categorical variables.
Step3: Define Function to Measure Quality of Each Approach
We define a function score_dataset() to compare the three different approaches to dealing with categorical variables. This function reports the mean absolute error (MAE) from a random forest model. In general, we want the MAE to be as low as possible!
Step4: Score from Approach 1 (Drop Categorical Variables)
We drop the object columns with the select_dtypes() method.
Step5: Score from Approach 2 (Ordinal Encoding)
Scikit-learn has a OrdinalEncoder class that can be used to get ordinal encodings. We loop over the categorical variables and apply the ordinal encoder separately to each column.
Step6: In the code cell above, for each column, we randomly assign each unique value to a different integer. This is a common approach that is simpler than providing custom labels; however, we can expect an additional boost in performance if we provide better-informed labels for all ordinal variables.
Score from Approach 3 (One-Hot Encoding)
We use the OneHotEncoder class from scikit-learn to get one-hot encodings. There are a number of parameters that can be used to customize its behavior.
- We set handle_unknown='ignore' to avoid errors when the validation data contains classes that aren't represented in the training data, and
- setting sparse=False ensures that the encoded columns are returned as a numpy array (instead of a sparse matrix).
To use the encoder, we supply only the categorical columns that we want to be one-hot encoded. For instance, to encode the training data, we supply X_train[object_cols]. (object_cols in the code cell below is a list of the column names with categorical data, and so X_train[object_cols] contains all of the categorical data in the training set.) | Python Code:
#$HIDE$
import pandas as pd
from sklearn.model_selection import train_test_split
# Read the data
data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv')
# Separate target from predictors
y = data.Price
X = data.drop(['Price'], axis=1)
# Divide data into training and validation subsets
X_train_full, X_valid_full, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2,
random_state=0)
# Drop columns with missing values (simplest approach)
cols_with_missing = [col for col in X_train_full.columns if X_train_full[col].isnull().any()]
X_train_full.drop(cols_with_missing, axis=1, inplace=True)
X_valid_full.drop(cols_with_missing, axis=1, inplace=True)
# "Cardinality" means the number of unique values in a column
# Select categorical columns with relatively low cardinality (convenient but arbitrary)
low_cardinality_cols = [cname for cname in X_train_full.columns if X_train_full[cname].nunique() < 10 and
X_train_full[cname].dtype == "object"]
# Select numerical columns
numerical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].dtype in ['int64', 'float64']]
# Keep selected columns only
my_cols = low_cardinality_cols + numerical_cols
X_train = X_train_full[my_cols].copy()
X_valid = X_valid_full[my_cols].copy()
Explanation: In this tutorial, you will learn what a categorical variable is, along with three approaches for handling this type of data.
Introduction
A categorical variable takes only a limited number of values.
Consider a survey that asks how often you eat breakfast and provides four options: "Never", "Rarely", "Most days", or "Every day". In this case, the data is categorical, because responses fall into a fixed set of categories.
If people responded to a survey about which what brand of car they owned, the responses would fall into categories like "Honda", "Toyota", and "Ford". In this case, the data is also categorical.
You will get an error if you try to plug these variables into most machine learning models in Python without preprocessing them first. In this tutorial, we'll compare three approaches that you can use to prepare your categorical data.
Three Approaches
1) Drop Categorical Variables
The easiest approach to dealing with categorical variables is to simply remove them from the dataset. This approach will only work well if the columns did not contain useful information.
2) Ordinal Encoding
Ordinal encoding assigns each unique value to a different integer.
This approach assumes an ordering of the categories: "Never" (0) < "Rarely" (1) < "Most days" (2) < "Every day" (3).
This assumption makes sense in this example, because there is an indisputable ranking to the categories. Not all categorical variables have a clear ordering in the values, but we refer to those that do as ordinal variables. For tree-based models (like decision trees and random forests), you can expect ordinal encoding to work well with ordinal variables.
3) One-Hot Encoding
One-hot encoding creates new columns indicating the presence (or absence) of each possible value in the original data. To understand this, we'll work through an example.
In the original dataset, "Color" is a categorical variable with three categories: "Red", "Yellow", and "Green". The corresponding one-hot encoding contains one column for each possible value, and one row for each row in the original dataset. Wherever the original value was "Red", we put a 1 in the "Red" column; if the original value was "Yellow", we put a 1 in the "Yellow" column, and so on.
In contrast to ordinal encoding, one-hot encoding does not assume an ordering of the categories. Thus, you can expect this approach to work particularly well if there is no clear ordering in the categorical data (e.g., "Red" is neither more nor less than "Yellow"). We refer to categorical variables without an intrinsic ranking as nominal variables.
One-hot encoding generally does not perform well if the categorical variable takes on a large number of values (i.e., you generally won't use it for variables taking more than 15 different values).
Example
As in the previous tutorial, we will work with the Melbourne Housing dataset.
We won't focus on the data loading step. Instead, you can imagine you are at a point where you already have the training and validation data in X_train, X_valid, y_train, and y_valid.
End of explanation
X_train.head()
Explanation: We take a peek at the training data with the head() method below.
End of explanation
# Get list of categorical variables
s = (X_train.dtypes == 'object')
object_cols = list(s[s].index)
print("Categorical variables:")
print(object_cols)
Explanation: Next, we obtain a list of all of the categorical variables in the training data.
We do this by checking the data type (or dtype) of each column. The object dtype indicates a column has text (there are other things it could theoretically be, but that's unimportant for our purposes). For this dataset, the columns with text indicate categorical variables.
End of explanation
#$HIDE$
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
# Function for comparing different approaches
def score_dataset(X_train, X_valid, y_train, y_valid):
model = RandomForestRegressor(n_estimators=100, random_state=0)
model.fit(X_train, y_train)
preds = model.predict(X_valid)
return mean_absolute_error(y_valid, preds)
Explanation: Define Function to Measure Quality of Each Approach
We define a function score_dataset() to compare the three different approaches to dealing with categorical variables. This function reports the mean absolute error (MAE) from a random forest model. In general, we want the MAE to be as low as possible!
End of explanation
drop_X_train = X_train.select_dtypes(exclude=['object'])
drop_X_valid = X_valid.select_dtypes(exclude=['object'])
print("MAE from Approach 1 (Drop categorical variables):")
print(score_dataset(drop_X_train, drop_X_valid, y_train, y_valid))
Explanation: Score from Approach 1 (Drop Categorical Variables)
We drop the object columns with the select_dtypes() method.
End of explanation
from sklearn.preprocessing import OrdinalEncoder
# Make copy to avoid changing original data
label_X_train = X_train.copy()
label_X_valid = X_valid.copy()
# Apply ordinal encoder to each column with categorical data
ordinal_encoder = OrdinalEncoder()
label_X_train[object_cols] = ordinal_encoder.fit_transform(X_train[object_cols])
label_X_valid[object_cols] = ordinal_encoder.transform(X_valid[object_cols])
print("MAE from Approach 2 (Ordinal Encoding):")
print(score_dataset(label_X_train, label_X_valid, y_train, y_valid))
Explanation: Score from Approach 2 (Ordinal Encoding)
Scikit-learn has a OrdinalEncoder class that can be used to get ordinal encodings. We loop over the categorical variables and apply the ordinal encoder separately to each column.
End of explanation
from sklearn.preprocessing import OneHotEncoder
# Apply one-hot encoder to each column with categorical data
OH_encoder = OneHotEncoder(handle_unknown='ignore', sparse=False)
OH_cols_train = pd.DataFrame(OH_encoder.fit_transform(X_train[object_cols]))
OH_cols_valid = pd.DataFrame(OH_encoder.transform(X_valid[object_cols]))
# One-hot encoding removed index; put it back
OH_cols_train.index = X_train.index
OH_cols_valid.index = X_valid.index
# Remove categorical columns (will replace with one-hot encoding)
num_X_train = X_train.drop(object_cols, axis=1)
num_X_valid = X_valid.drop(object_cols, axis=1)
# Add one-hot encoded columns to numerical features
OH_X_train = pd.concat([num_X_train, OH_cols_train], axis=1)
OH_X_valid = pd.concat([num_X_valid, OH_cols_valid], axis=1)
print("MAE from Approach 3 (One-Hot Encoding):")
print(score_dataset(OH_X_train, OH_X_valid, y_train, y_valid))
Explanation: In the code cell above, for each column, we randomly assign each unique value to a different integer. This is a common approach that is simpler than providing custom labels; however, we can expect an additional boost in performance if we provide better-informed labels for all ordinal variables.
Score from Approach 3 (One-Hot Encoding)
We use the OneHotEncoder class from scikit-learn to get one-hot encodings. There are a number of parameters that can be used to customize its behavior.
- We set handle_unknown='ignore' to avoid errors when the validation data contains classes that aren't represented in the training data, and
- setting sparse=False ensures that the encoded columns are returned as a numpy array (instead of a sparse matrix).
To use the encoder, we supply only the categorical columns that we want to be one-hot encoded. For instance, to encode the training data, we supply X_train[object_cols]. (object_cols in the code cell below is a list of the column names with categorical data, and so X_train[object_cols] contains all of the categorical data in the training set.)
End of explanation |
8,502 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: This results in a constant distance of $\delta x$ between all grid points in the $x$ dimension. Using central differences, we can numerically approximate the derivative for a given point $x_i$
Step2: To give our Python function a test run, we will now do some imports and generate the input data for the initial conditions of our metal sheet with a few very hot points. We'll also make two plots, one after a thousand time steps, and a second plot after another two thousand time steps. Do note that the plots are using different ranges for the colors. Also, executing the following cell may take a little while.
Step3: We can now use this initial condition to solve the diffusion problem and plot the results.
Step4: Now let's take a quick look at the execution time of our diffuse function. Before we do, we also copy the current state of the metal sheet to be able to restart the computation from this state.
Step6: Computing on the GPU
The next step in this tutorial is to implement a GPU kernel that will allow us to run our problem on the GPU. We store the kernel code in a Python string, because we can directly compile and run the kernel from Python. In this tutorial, we'll use the CUDA programming model to implement our kernels.
If you prefer OpenCL over CUDA, don't worry. Everything in this tutorial
applies as much to OpenCL as it does to CUDA. But we will use CUDA for our
examples, and CUDA terminology in the text.
Step7: The above CUDA kernel parallelizes the work such that every grid point will be processed by a different CUDA thread. Therefore, the kernel is executed by a 2D grid of threads, which are grouped together into 2D thread blocks. The specific thread block dimensions we choose are not important for the result of the computation in this kernel. But as we will see will later, they will have an impact on performance.
In this kernel we are using two, currently undefined, compile-time constants for block_size_x and block_size_y, because we will auto tune these parameters later. It is often needed for performance to fix the thread block dimensions at compile time, because the compiler can unroll loops that iterate using the block size, or because you need to allocate shared memory using the thread block dimensions.
The next bit of Python code initializes PyCuda, and makes preparations so that we can call the CUDA kernel to do the computation on the GPU as we did earlier in Python.
Step8: The above code is a bit of boilerplate we need to compile a kernel using PyCuda. We've also, for the moment, fixed the thread block dimensions at 16 by 16. These dimensions serve as our initial guess for what a good performing pair of thread block dimensions could look like.
Now that we've setup everything, let's see how long the computation would take using the GPU.
Step9: That should already be a lot faster than our previous Python implementation, but we can do much better if we optimize our GPU kernel. And that is exactly what the rest of this tutorial is about!
Also, if you think the Python boilerplate code to call a GPU kernel was a bit messy, we've got good news for you! From now on, we'll only use the Kernel Tuner to compile and benchmark GPU kernels, which we can do with much cleaner Python code.
Auto-Tuning with the Kernel Tuner
Remember that previously we've set the thread block dimensions to 16 by 16. But how do we actually know if that is the best performing setting? That is where auto-tuning comes into play. Basically, it is very difficult to provide an answer through performance modeling and as such, we'd rather use the Kernel Tuner to compile and benchmark all possible kernel configurations.
But before we continue, we'll increase the problem size, because the GPU is very likely underutilized.
Step10: The above code block has generated new initial conditions and a new string that contains our CUDA kernel using our new domain size.
To call the Kernel Tuner, we have to specify the tunable parameters, in our case block_size_x and block_size_y. For this purpose, we'll create an ordered dictionary to store the tunable parameters. The keys will be the name of the tunable parameter, and the corresponding value is the list of possible values for the parameter. For the purpose of this tutorial, we'll use a small number of commonly used values for the thread block dimensions, but feel free to try more!
Step11: We also have to tell the Kernel Tuner about the argument list of our CUDA kernel. Because the Kernel Tuner will be calling the CUDA kernel and measure its execution time. For this purpose we create a list in Python, that corresponds with the argument list of the diffuse_kernel CUDA function. This list will only be used as input to the kernel during tuning. The objects in the list should be Numpy arrays or scalars.
Because you can specify the arguments as Numpy arrays, the Kernel Tuner will take care of allocating GPU memory and copying the data to the GPU.
Step12: We're almost ready to call the Kernel Tuner, we just need to set how large the problem is we are currently working on by setting a problem_size. The Kernel Tuner knows about thread block dimensions, which it expects to be called block_size_x, block_size_y, and/or block_size_z. From these and the problem_size, the Kernel Tuner will compute the appropiate grid dimensions on the fly.
Step13: And that's everything the Kernel Tuner needs to know to be able to start tuning our kernel. Let's give it a try by executing the next code block!
Step15: Note that the Kernel Tuner prints a lot of useful information. To ensure you'll be able to tell what was measured in this run the Kernel Tuner always prints the GPU or OpenCL Device name that is being used, as well as the name of the kernel.
After that every line contains the combination of parameters and the time that was measured during benchmarking. The time that is being printed is in milliseconds and is obtained by averaging the execution time of 7 runs of the kernel. Finally, as a matter of convenience, the Kernel Tuner also prints the best performing combination of tunable parameters. However, later on in this tutorial we'll explain how to analyze and store the tuning results using Python.
Looking at the results printed above, the difference in performance between the different kernel configurations may seem very little. However, on our hardware, the performance of this kernel already varies in the order of 10%. Which of course can build up to large differences in the execution time if the kernel is to be executed thousands of times. We can also see that the performance of the best configuration in this set is 5% better than our initially guessed thread block dimensions of 16 by 16.
In addtion, you may notice that not all possible combinations of values for block_size_x and block_size_y are among the results. For example, 128x32 is not among the results. This is because some configuration require more threads per thread block than allowed on our GPU. The Kernel Tuner checks the limitations of your GPU at runtime and automatically skips over configurations that use too many threads per block. It will also do this for kernels that cannot be compiled because they use too much shared memory. And likewise for kernels that use too many registers to be launched at runtime. If you'd like to know about which configurations were skipped automatically you can pass the optional parameter verbose=True to tune_kernel.
However, knowing the best performing combination of tunable parameters becomes even more important when we start to further optimize our CUDA kernel. In the next section, we'll add a simple code optimization and show how this affects performance.
Using shared memory
Shared memory, is a special type of the memory available in CUDA. Shared memory can be used by threads within the same thread block to exchange and share values. It is in fact, one of the very few ways for threads to communicate on the GPU.
The idea is that we'll try improve the performance of our kernel by using shared memory as a software controlled cache. There are already caches on the GPU, but most GPUs only cache accesses to global memory in L2. Shared memory is closer to the multiprocessors where the thread blocks are executed, comparable to an L1 cache.
However, because there are also hardware caches, the performance improvement from this step is expected to not be that great. The more fine-grained control that we get by using a software managed cache, rather than a hardware implemented cache, comes at the cost of some instruction overhead. In fact, performance is quite likely to degrade a little. However, this intermediate step is necessary for the next optimization step we have in mind.
Step16: We can now tune this new kernel using the kernel tuner
Step18: Tiling GPU Code
One very useful code optimization is called tiling, sometimes also called thread-block-merge. You can look at it in this way, currently we have many thread blocks that together work on the entire domain. If we were to use only half of the number of thread blocks, every thread block would need to double the amount of work it performs to cover the entire domain. However, the threads may be able to reuse part of the data and computation that is required to process a single output element for every element beyond the first.
This is a code optimization because effectively we are reducing the total number of instructions executed by all threads in all thread blocks. So in a way, were are condensing the total instruction stream while keeping the all the really necessary compute instructions. More importantly, we are increasing data reuse, where previously these values would have been reused from the cache or in the worst-case from GPU memory.
We can apply tiling in both the x and y-dimensions. This also introduces two new tunable parameters, namely the tiling factor in x and y, which we will call tile_size_x and tile_size_y.
This is what the new kernel looks like
Step19: We can tune our tiled kernel by adding the two new tunable parameters to our dictionary tune_params.
We also need to somehow tell the Kernel Tuner to use fewer thread blocks to launch kernels with tile_size_x or tile_size_y larger than one. For this purpose the Kernel Tuner's tune_kernel function supports two optional arguments, called grid_div_x and grid_div_y. These are the grid divisor lists, which are lists of strings containing all the tunable parameters that divide a certain grid dimension. So far, we have been using the default settings for these, in which case the Kernel Tuner only uses the block_size_x and block_size_y tunable parameters to divide the problem_size.
Note that the Kernel Tuner will replace the values of the tunable parameters inside the strings and use the product of the parameters in the grid divisor list to compute the grid dimension rounded up. You can even use arithmetic operations, inside these strings as they will be evaluated. As such, we could have used ["block_size_x*tile_size_x"] to get the same result.
We are now ready to call the Kernel Tuner again and tune our tiled kernel. Let's execute the following code block, note that it may take a while as the number of kernel configurations that the Kernel Tuner will try has just been increased with a factor of 9!
Step20: We can see that the number of kernel configurations tried by the Kernel Tuner is growing rather quickly. Also, the best performing configuration quite a bit faster than the best kernel before we started optimizing. On our GTX Titan X, the execution time went from 0.72 ms to 0.53 ms, a performance improvement of 26%!
Note that the thread block dimensions for this kernel configuration are also different. Without optimizations the best performing kernel used a thread block of 32x2, after we've added tiling the best performing kernel uses thread blocks of size 64x4, which is four times as many threads! Also the amount of work increased with tiling factors 2 in the x-direction and 4 in the y-direction, increasing the amount of work per thread block by a factor of 8. The difference in the area processed per thread block between the naive and the tiled kernel is a factor 32.
However, there are actually several kernel configurations that come close. The following Python code prints all instances with an execution time within 5% of the best performing configuration.
Using the best parameters in a production run
Now that we have determined which parameters are the best for our problems we can use them to simulate the heat diffusion problem. There are several ways to do so depending on the host language you wish to use.
Python run
To use the optimized parameters in a python run, we simply have to modify the kernel code to specify which value to use for the block and tile size. There are of course many different ways to achieve this. In simple cases on can define a dictionary of values and replace the string block_size_i and tile_size_j by their values.
Step21: We also need to determine the size of the grid
Step22: We can then transfer the data initial condition on the two gpu arrays as well as compile the code and get the function we want to use.
Step23: We now just have to use the kernel with these optimized parameters to run the simulation
Step25: C run
If you wish to incorporate the optimized parameters in the kernel and use it in a C run you can use ifndef statement at the begining of the kerenel as demonstrated in the psedo code below. | Python Code:
nx = 1024
ny = 1024
Explanation: Tutorial: From physics to tuned GPU kernels
This tutorial is designed to show you the whole process starting from modeling a physical process to a Python implementation to creating optimized and auto-tuned GPU application using Kernel Tuner.
In this tutorial, we will use diffusion as an example application.
We start with modeling the physical process of diffusion, for which we create a simple numerical implementation in Python. Then we create a CUDA kernel that performs the same computation, but on the GPU. Once we have a CUDA kernel, we start using the Kernel Tuner for auto-tuning our GPU application. And finally, we'll introduce a few code optimizations to our CUDA kernel that will improve performance, but also add more parameters to tune on using the Kernel Tuner.
<div class="alert alert-info">
**Note:** If you are reading this tutorial on the Kernel Tuner's documentation pages, note that you can actually run this tutorial as a Jupyter Notebook. Just clone the Kernel Tuner's [GitHub repository](http://github.com/benvanwerkhoven/kernel_tuner). Install the Kernel Tuner and Jupyter Notebooks and you're ready to go! You can start the tutorial by typing "jupyter notebook" in the "kernel_tuner/tutorial" directory.
</div>
Diffusion
Put simply, diffusion is the redistribution of something from a region of high concentration to a region of low concentration without bulk motion. The concept of diffusion is widely used in many fields, including physics, chemistry, biology, and many more.
Suppose that we take a metal sheet, in which the temperature is exactly equal to one degree everywhere in the sheet.
Now if we were to heat a number of points on the sheet to a very high temperature, say a thousand degrees, in an instant by some method. We could see the heat diffuse from these hotspots to the cooler areas. We are assuming that the metal does not melt. In addition, we will ignore any heat loss from radiation or other causes in this example.
We can use the diffusion equation to model how the heat diffuses through our metal sheet:
\begin{equation}
\frac{\partial u}{\partial t}= D \left( \frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2} \right)
\end{equation}
Where $x$ and $y$ represent the spatial descretization of our 2D domain, $u$ is the quantity that is being diffused, $t$ is the descretization in time, and the constant $D$ determines how fast the diffusion takes place.
In this example, we will assume a very simple descretization of our problem. We assume that our 2D domain has $nx$ equi-distant grid points in the x-direction and $ny$ equi-distant grid points in the y-direction. Be sure to execute every cell as you read through this document, by selecting it and pressing shift+enter.
End of explanation
def diffuse(field, dt=0.225):
field[1:nx-1,1:ny-1] = field[1:nx-1,1:ny-1] + dt * (
field[1:nx-1,2:ny]+field[2:nx,1:ny-1]-4*field[1:nx-1,1:ny-1]+
field[0:nx-2,1:ny-1]+field[1:nx-1,0:ny-2] )
return field
Explanation: This results in a constant distance of $\delta x$ between all grid points in the $x$ dimension. Using central differences, we can numerically approximate the derivative for a given point $x_i$:
\begin{equation}
\left. \frac{\partial^2 u}{\partial x^2} \right|{x{i}} \approx \frac{u_{x_{i+1}}-2u_{{x_i}}+u_{x_{i-1}}}{(\delta x)^2}
\end{equation}
We do the same for the partial derivative in $y$:
\begin{equation}
\left. \frac{\partial^2 u}{\partial y^2} \right|{y{i}} \approx \frac{u_{y_{i+1}}-2u_{y_{i}}+u_{y_{i-1}}}{(\delta y)^2}
\end{equation}
If we combine the above equations, we can obtain a numerical estimation for the temperature field of our metal sheet in the next time step, using $\delta t$ as the time between time steps. But before we do, we also simplify the expression a little bit, because we'll assume that $\delta x$ and $\delta y$ are always equal to 1.
\begin{equation}
u'{x,y} = u{x,y} + \delta t \times \left( \left( u_{x_{i+1},y}-2u_{{x_i},y}+u_{x_{i-1},y} \right) + \left( u_{x,y_{i+1}}-2u_{x,y_{i}}+u_{x,y_{i-1}} \right) \right)
\end{equation}
In this formula $u'_{x,y}$ refers to the temperature field at the time $t + \delta t$. As a final step, we further simplify this equation to:
\begin{equation}
u'{x,y} = u{x,y} + \delta t \times \left( u_{x,y_{i+1}}+u_{x_{i+1},y}-4u_{{x_i},y}+u_{x_{i-1},y}+u_{x,y_{i-1}} \right)
\end{equation}
Python implementation
We can create a Python function that implements the numerical approximation defined in the above equation. For simplicity we'll use the assumption of a free boundary condition.
End of explanation
import numpy
#setup initial conditions
def get_initial_conditions(nx, ny):
field = numpy.ones((ny, nx)).astype(numpy.float32)
field[numpy.random.randint(0,nx,size=10), numpy.random.randint(0,ny,size=10)] = 1e3
return field
field = get_initial_conditions(nx, ny)
Explanation: To give our Python function a test run, we will now do some imports and generate the input data for the initial conditions of our metal sheet with a few very hot points. We'll also make two plots, one after a thousand time steps, and a second plot after another two thousand time steps. Do note that the plots are using different ranges for the colors. Also, executing the following cell may take a little while.
End of explanation
from matplotlib import pyplot
%matplotlib inline
#run the diffuse function a 1000 times and another 2000 times and make plots
fig, (ax1, ax2) = pyplot.subplots(1,2)
cpu=numpy.copy(field)
for i in range(1000):
cpu = diffuse(cpu)
ax1.imshow(cpu)
for i in range(2000):
cpu = diffuse(cpu)
ax2.imshow(cpu)
Explanation: We can now use this initial condition to solve the diffusion problem and plot the results.
End of explanation
#run another 1000 steps of the diffuse function and measure the time
from time import time
start = time()
cpu=numpy.copy(field)
for i in range(1000):
cpu = diffuse(cpu)
end = time()
print("1000 steps of diffuse on a %d x %d grid took" %(nx,ny), (end-start)*1000.0, "ms")
pyplot.imshow(cpu)
Explanation: Now let's take a quick look at the execution time of our diffuse function. Before we do, we also copy the current state of the metal sheet to be able to restart the computation from this state.
End of explanation
def get_kernel_string(nx, ny):
return
#define nx %d
#define ny %d
#define dt 0.225f
__global__ void diffuse_kernel(float *u_new, float *u) {
int x = blockIdx.x * block_size_x + threadIdx.x;
int y = blockIdx.y * block_size_y + threadIdx.y;
if (x>0 && x<nx-1 && y>0 && y<ny-1) {
u_new[y*nx+x] = u[y*nx+x] + dt * (
u[(y+1)*nx+x]+u[y*nx+x+1]-4.0f*u[y*nx+x]+u[y*nx+x-1]+u[(y-1)*nx+x]);
}
}
% (nx, ny)
kernel_string = get_kernel_string(nx, ny)
Explanation: Computing on the GPU
The next step in this tutorial is to implement a GPU kernel that will allow us to run our problem on the GPU. We store the kernel code in a Python string, because we can directly compile and run the kernel from Python. In this tutorial, we'll use the CUDA programming model to implement our kernels.
If you prefer OpenCL over CUDA, don't worry. Everything in this tutorial
applies as much to OpenCL as it does to CUDA. But we will use CUDA for our
examples, and CUDA terminology in the text.
End of explanation
from pycuda import driver, compiler, gpuarray, tools
import pycuda.autoinit
from time import time
#allocate GPU memory
u_old = gpuarray.to_gpu(field)
u_new = gpuarray.to_gpu(field)
#setup thread block dimensions and compile the kernel
threads = (16,16,1)
grid = (int(nx/16), int(ny/16), 1)
block_size_string = "#define block_size_x 16\n#define block_size_y 16\n"
mod = compiler.SourceModule(block_size_string+kernel_string)
diffuse_kernel = mod.get_function("diffuse_kernel")
Explanation: The above CUDA kernel parallelizes the work such that every grid point will be processed by a different CUDA thread. Therefore, the kernel is executed by a 2D grid of threads, which are grouped together into 2D thread blocks. The specific thread block dimensions we choose are not important for the result of the computation in this kernel. But as we will see will later, they will have an impact on performance.
In this kernel we are using two, currently undefined, compile-time constants for block_size_x and block_size_y, because we will auto tune these parameters later. It is often needed for performance to fix the thread block dimensions at compile time, because the compiler can unroll loops that iterate using the block size, or because you need to allocate shared memory using the thread block dimensions.
The next bit of Python code initializes PyCuda, and makes preparations so that we can call the CUDA kernel to do the computation on the GPU as we did earlier in Python.
End of explanation
#call the GPU kernel a 1000 times and measure performance
t0 = time()
for i in range(500):
diffuse_kernel(u_new, u_old, block=threads, grid=grid)
diffuse_kernel(u_old, u_new, block=threads, grid=grid)
driver.Context.synchronize()
print("1000 steps of diffuse ona %d x %d grid took" %(nx,ny), (time()-t0)*1000, "ms.")
#copy the result from the GPU to Python for plotting
gpu_result = u_old.get()
fig, (ax1, ax2) = pyplot.subplots(1,2)
ax1.imshow(gpu_result)
ax1.set_title("GPU Result")
ax2.imshow(cpu)
ax2.set_title("Python Result")
Explanation: The above code is a bit of boilerplate we need to compile a kernel using PyCuda. We've also, for the moment, fixed the thread block dimensions at 16 by 16. These dimensions serve as our initial guess for what a good performing pair of thread block dimensions could look like.
Now that we've setup everything, let's see how long the computation would take using the GPU.
End of explanation
nx = 4096
ny = 4096
field = get_initial_conditions(nx, ny)
kernel_string = get_kernel_string(nx, ny)
Explanation: That should already be a lot faster than our previous Python implementation, but we can do much better if we optimize our GPU kernel. And that is exactly what the rest of this tutorial is about!
Also, if you think the Python boilerplate code to call a GPU kernel was a bit messy, we've got good news for you! From now on, we'll only use the Kernel Tuner to compile and benchmark GPU kernels, which we can do with much cleaner Python code.
Auto-Tuning with the Kernel Tuner
Remember that previously we've set the thread block dimensions to 16 by 16. But how do we actually know if that is the best performing setting? That is where auto-tuning comes into play. Basically, it is very difficult to provide an answer through performance modeling and as such, we'd rather use the Kernel Tuner to compile and benchmark all possible kernel configurations.
But before we continue, we'll increase the problem size, because the GPU is very likely underutilized.
End of explanation
from collections import OrderedDict
tune_params = OrderedDict()
tune_params["block_size_x"] = [16, 32, 48, 64, 128]
tune_params["block_size_y"] = [2, 4, 8, 16, 32]
Explanation: The above code block has generated new initial conditions and a new string that contains our CUDA kernel using our new domain size.
To call the Kernel Tuner, we have to specify the tunable parameters, in our case block_size_x and block_size_y. For this purpose, we'll create an ordered dictionary to store the tunable parameters. The keys will be the name of the tunable parameter, and the corresponding value is the list of possible values for the parameter. For the purpose of this tutorial, we'll use a small number of commonly used values for the thread block dimensions, but feel free to try more!
End of explanation
args = [field, field]
Explanation: We also have to tell the Kernel Tuner about the argument list of our CUDA kernel. Because the Kernel Tuner will be calling the CUDA kernel and measure its execution time. For this purpose we create a list in Python, that corresponds with the argument list of the diffuse_kernel CUDA function. This list will only be used as input to the kernel during tuning. The objects in the list should be Numpy arrays or scalars.
Because you can specify the arguments as Numpy arrays, the Kernel Tuner will take care of allocating GPU memory and copying the data to the GPU.
End of explanation
problem_size = (nx, ny)
Explanation: We're almost ready to call the Kernel Tuner, we just need to set how large the problem is we are currently working on by setting a problem_size. The Kernel Tuner knows about thread block dimensions, which it expects to be called block_size_x, block_size_y, and/or block_size_z. From these and the problem_size, the Kernel Tuner will compute the appropiate grid dimensions on the fly.
End of explanation
from kernel_tuner import tune_kernel
result = tune_kernel("diffuse_kernel", kernel_string, problem_size, args, tune_params)
Explanation: And that's everything the Kernel Tuner needs to know to be able to start tuning our kernel. Let's give it a try by executing the next code block!
End of explanation
kernel_string_shared =
#define nx %d
#define ny %d
#define dt 0.225f
__global__ void diffuse_kernel(float *u_new, float *u) {
int tx = threadIdx.x;
int ty = threadIdx.y;
int bx = blockIdx.x * block_size_x;
int by = blockIdx.y * block_size_y;
__shared__ float sh_u[block_size_y+2][block_size_x+2];
#pragma unroll
for (int i = ty; i<block_size_y+2; i+=block_size_y) {
#pragma unroll
for (int j = tx; j<block_size_x+2; j+=block_size_x) {
int y = by+i-1;
int x = bx+j-1;
if (x>=0 && x<nx && y>=0 && y<ny) {
sh_u[i][j] = u[y*nx+x];
}
}
}
__syncthreads();
int x = bx+tx;
int y = by+ty;
if (x>0 && x<nx-1 && y>0 && y<ny-1) {
int i = ty+1;
int j = tx+1;
u_new[y*nx+x] = sh_u[i][j] + dt * (
sh_u[i+1][j] + sh_u[i][j+1] -4.0f * sh_u[i][j] +
sh_u[i][j-1] + sh_u[i-1][j] );
}
}
% (nx, ny)
Explanation: Note that the Kernel Tuner prints a lot of useful information. To ensure you'll be able to tell what was measured in this run the Kernel Tuner always prints the GPU or OpenCL Device name that is being used, as well as the name of the kernel.
After that every line contains the combination of parameters and the time that was measured during benchmarking. The time that is being printed is in milliseconds and is obtained by averaging the execution time of 7 runs of the kernel. Finally, as a matter of convenience, the Kernel Tuner also prints the best performing combination of tunable parameters. However, later on in this tutorial we'll explain how to analyze and store the tuning results using Python.
Looking at the results printed above, the difference in performance between the different kernel configurations may seem very little. However, on our hardware, the performance of this kernel already varies in the order of 10%. Which of course can build up to large differences in the execution time if the kernel is to be executed thousands of times. We can also see that the performance of the best configuration in this set is 5% better than our initially guessed thread block dimensions of 16 by 16.
In addtion, you may notice that not all possible combinations of values for block_size_x and block_size_y are among the results. For example, 128x32 is not among the results. This is because some configuration require more threads per thread block than allowed on our GPU. The Kernel Tuner checks the limitations of your GPU at runtime and automatically skips over configurations that use too many threads per block. It will also do this for kernels that cannot be compiled because they use too much shared memory. And likewise for kernels that use too many registers to be launched at runtime. If you'd like to know about which configurations were skipped automatically you can pass the optional parameter verbose=True to tune_kernel.
However, knowing the best performing combination of tunable parameters becomes even more important when we start to further optimize our CUDA kernel. In the next section, we'll add a simple code optimization and show how this affects performance.
Using shared memory
Shared memory, is a special type of the memory available in CUDA. Shared memory can be used by threads within the same thread block to exchange and share values. It is in fact, one of the very few ways for threads to communicate on the GPU.
The idea is that we'll try improve the performance of our kernel by using shared memory as a software controlled cache. There are already caches on the GPU, but most GPUs only cache accesses to global memory in L2. Shared memory is closer to the multiprocessors where the thread blocks are executed, comparable to an L1 cache.
However, because there are also hardware caches, the performance improvement from this step is expected to not be that great. The more fine-grained control that we get by using a software managed cache, rather than a hardware implemented cache, comes at the cost of some instruction overhead. In fact, performance is quite likely to degrade a little. However, this intermediate step is necessary for the next optimization step we have in mind.
End of explanation
result = tune_kernel("diffuse_kernel", kernel_string_shared, problem_size, args, tune_params)
Explanation: We can now tune this new kernel using the kernel tuner
End of explanation
kernel_string_tiled =
#define nx %d
#define ny %d
#define dt 0.225f
__global__ void diffuse_kernel(float *u_new, float *u) {
int tx = threadIdx.x;
int ty = threadIdx.y;
int bx = blockIdx.x * block_size_x * tile_size_x;
int by = blockIdx.y * block_size_y * tile_size_y;
__shared__ float sh_u[block_size_y*tile_size_y+2][block_size_x*tile_size_x+2];
#pragma unroll
for (int i = ty; i<block_size_y*tile_size_y+2; i+=block_size_y) {
#pragma unroll
for (int j = tx; j<block_size_x*tile_size_x+2; j+=block_size_x) {
int y = by+i-1;
int x = bx+j-1;
if (x>=0 && x<nx && y>=0 && y<ny) {
sh_u[i][j] = u[y*nx+x];
}
}
}
__syncthreads();
#pragma unroll
for (int tj=0; tj<tile_size_y; tj++) {
int i = ty+tj*block_size_y+1;
int y = by + ty + tj*block_size_y;
#pragma unroll
for (int ti=0; ti<tile_size_x; ti++) {
int j = tx+ti*block_size_x+1;
int x = bx + tx + ti*block_size_x;
if (x>0 && x<nx-1 && y>0 && y<ny-1) {
u_new[y*nx+x] = sh_u[i][j] + dt * (
sh_u[i+1][j] + sh_u[i][j+1] -4.0f * sh_u[i][j] +
sh_u[i][j-1] + sh_u[i-1][j] );
}
}
}
}
% (nx, ny)
Explanation: Tiling GPU Code
One very useful code optimization is called tiling, sometimes also called thread-block-merge. You can look at it in this way, currently we have many thread blocks that together work on the entire domain. If we were to use only half of the number of thread blocks, every thread block would need to double the amount of work it performs to cover the entire domain. However, the threads may be able to reuse part of the data and computation that is required to process a single output element for every element beyond the first.
This is a code optimization because effectively we are reducing the total number of instructions executed by all threads in all thread blocks. So in a way, were are condensing the total instruction stream while keeping the all the really necessary compute instructions. More importantly, we are increasing data reuse, where previously these values would have been reused from the cache or in the worst-case from GPU memory.
We can apply tiling in both the x and y-dimensions. This also introduces two new tunable parameters, namely the tiling factor in x and y, which we will call tile_size_x and tile_size_y.
This is what the new kernel looks like:
End of explanation
tune_params["tile_size_x"] = [1,2,4] #add tile_size_x to the tune_params
tune_params["tile_size_y"] = [1,2,4] #add tile_size_y to the tune_params
grid_div_x = ["block_size_x", "tile_size_x"] #tile_size_x impacts grid dimensions
grid_div_y = ["block_size_y", "tile_size_y"] #tile_size_y impacts grid dimensions
result = tune_kernel("diffuse_kernel", kernel_string_tiled, problem_size, args,
tune_params, grid_div_x=grid_div_x, grid_div_y=grid_div_y)
Explanation: We can tune our tiled kernel by adding the two new tunable parameters to our dictionary tune_params.
We also need to somehow tell the Kernel Tuner to use fewer thread blocks to launch kernels with tile_size_x or tile_size_y larger than one. For this purpose the Kernel Tuner's tune_kernel function supports two optional arguments, called grid_div_x and grid_div_y. These are the grid divisor lists, which are lists of strings containing all the tunable parameters that divide a certain grid dimension. So far, we have been using the default settings for these, in which case the Kernel Tuner only uses the block_size_x and block_size_y tunable parameters to divide the problem_size.
Note that the Kernel Tuner will replace the values of the tunable parameters inside the strings and use the product of the parameters in the grid divisor list to compute the grid dimension rounded up. You can even use arithmetic operations, inside these strings as they will be evaluated. As such, we could have used ["block_size_x*tile_size_x"] to get the same result.
We are now ready to call the Kernel Tuner again and tune our tiled kernel. Let's execute the following code block, note that it may take a while as the number of kernel configurations that the Kernel Tuner will try has just been increased with a factor of 9!
End of explanation
import pycuda.autoinit
# define the optimal parameters
size = [nx,ny,1]
threads = [128,4,1]
# create a dict of fixed parameters
fixed_params = OrderedDict()
fixed_params['block_size_x'] = threads[0]
fixed_params['block_size_y'] = threads[1]
# select the kernel to use
kernel_string = kernel_string_shared
# replace the block/tile size
for k,v in fixed_params.items():
kernel_string = kernel_string.replace(k,str(v))
Explanation: We can see that the number of kernel configurations tried by the Kernel Tuner is growing rather quickly. Also, the best performing configuration quite a bit faster than the best kernel before we started optimizing. On our GTX Titan X, the execution time went from 0.72 ms to 0.53 ms, a performance improvement of 26%!
Note that the thread block dimensions for this kernel configuration are also different. Without optimizations the best performing kernel used a thread block of 32x2, after we've added tiling the best performing kernel uses thread blocks of size 64x4, which is four times as many threads! Also the amount of work increased with tiling factors 2 in the x-direction and 4 in the y-direction, increasing the amount of work per thread block by a factor of 8. The difference in the area processed per thread block between the naive and the tiled kernel is a factor 32.
However, there are actually several kernel configurations that come close. The following Python code prints all instances with an execution time within 5% of the best performing configuration.
Using the best parameters in a production run
Now that we have determined which parameters are the best for our problems we can use them to simulate the heat diffusion problem. There are several ways to do so depending on the host language you wish to use.
Python run
To use the optimized parameters in a python run, we simply have to modify the kernel code to specify which value to use for the block and tile size. There are of course many different ways to achieve this. In simple cases on can define a dictionary of values and replace the string block_size_i and tile_size_j by their values.
End of explanation
# for regular and shared kernel
grid = [int(numpy.ceil(n/t)) for t,n in zip(threads,size)]
Explanation: We also need to determine the size of the grid
End of explanation
#allocate GPU memory
u_old = gpuarray.to_gpu(field)
u_new = gpuarray.to_gpu(field)
# compile the kernel
mod = compiler.SourceModule(kernel_string)
diffuse_kernel = mod.get_function("diffuse_kernel")
Explanation: We can then transfer the data initial condition on the two gpu arrays as well as compile the code and get the function we want to use.
End of explanation
#call the GPU kernel a 1000 times and measure performance
t0 = time()
for i in range(500):
diffuse_kernel(u_new, u_old, block=tuple(threads), grid=tuple(grid))
diffuse_kernel(u_old, u_new, block=tuple(threads), grid=tuple(grid))
driver.Context.synchronize()
print("1000 steps of diffuse on a %d x %d grid took" %(nx,ny), (time()-t0)*1000, "ms.")
#copy the result from the GPU to Python for plotting
gpu_result = u_old.get()
pyplot.imshow(gpu_result)
Explanation: We now just have to use the kernel with these optimized parameters to run the simulation
End of explanation
kernel_string =
#ifndef block_size_x
#define block_size_x <insert optimal value>
#endif
#ifndef block_size_y
#define block_size_y <insert optimal value>
#endif
#define nx %d
#define ny %d
#define dt 0.225f
__global__ void diffuse_kernel(float *u_new, float *u) {
......
}
}
% (nx, ny)
Explanation: C run
If you wish to incorporate the optimized parameters in the kernel and use it in a C run you can use ifndef statement at the begining of the kerenel as demonstrated in the psedo code below.
End of explanation |
8,503 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with Numpy, we'll be using TFLearn, a high-level library built on top of TensorFlow. TFLearn makes it simpler to build networks just by defining the layers. It takes care of most of the details for you.
We'll start off by importing all the modules we'll need, then load and prepare the data.
Step1: Preparing the data
Following along with Andrew, our goal here is to convert our reviews into word vectors. The word vectors will have elements representing words in the total vocabulary. If the second position represents the word 'the', for each review we'll count up the number of times 'the' appears in the text and set the second position to that count. I'll show you examples as we build the input data from the reviews data. Check out Andrew's notebook and video for more about this.
Read the data
Use the pandas library to read the reviews and postive/negative labels from comma-separated files. The data we're using has already been preprocessed a bit and we know it uses only lower case characters. If we were working from raw data, where we didn't know it was all lower case, we would want to add a step here to convert it. That's so we treat different variations of the same word, like The, the, and THE, all the same way.
Step2: Counting word frequency
To start off we'll need to count how often each word appears in the data. We'll use this count to create a vocabulary we'll use to encode the review data. This resulting count is known as a bag of words. We'll use it to select our vocabulary and build the word vectors. You should have seen how to do this in Andrew's lesson. Try to implement it here using the Counter class.
Exercise
Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in the vocabulary are rarely used so they will have little effect on our predictions. Below, we'll sort vocab by the count value and keep the 10000 most frequent words.
Step4: What's the last word in our vocabulary? We can use this to judge if 10000 is too few. If the last word is pretty common, we probably need to keep more words.
Step5: The last word in our vocabulary shows up in 30 reviews out of 25000. I think it's fair to say this is a tiny proportion of reviews. We are probably fine with this number of words.
Note
Step6: Text to vector function
Now we can write a function that converts a some text to a word vector. The function will take a string of words as input and return a vector with the words counted up. Here's the general algorithm to do this
Step7: If you do this right, the following code should return
```
text_to_vector('The tea is for a party to celebrate '
'the movie so she has no time for a cake')[
Step8: Now, run through our entire review data set and convert each review to a word vector.
Step9: Train, Validation, Test sets
Now that we have the word_vectors, we're ready to split our data into train, validation, and test sets. Remember that we train on the train data, use the validation data to set the hyperparameters, and at the very end measure the network performance on the test data. Here we're using the function to_categorical from TFLearn to reshape the target data so that we'll have two output units and can classify with a softmax activation function. We actually won't be creating the validation set here, TFLearn will do that for us later.
Step10: Building the network
TFLearn lets you build the network by defining the layers.
Input layer
For the input layer, you just need to tell it how many units you have. For example,
net = tflearn.input_data([None, 100])
would create a network with 100 input units. The first element in the list, None in this case, sets the batch size. Setting it to None here leaves it at the default batch size.
The number of inputs to your network needs to match the size of your data. For this example, we're using 10000 element long vectors to encode our input data, so we need 10000 input units.
Adding layers
To add new hidden layers, you use
net = tflearn.fully_connected(net, n_units, activation='ReLU')
This adds a fully connected layer where every unit in the previous layer is connected to every unit in this layer. The first argument net is the network you created in the tflearn.input_data call. It's telling the network to use the output of the previous layer as the input to this layer. You can set the number of units in the layer with n_units, and set the activation function with the activation keyword. You can keep adding layers to your network by repeated calling net = tflearn.fully_connected(net, n_units).
Output layer
The last layer you add is used as the output layer. Therefore, you need to set the number of units to match the target data. In this case we are predicting two classes, positive or negative sentiment. You also need to set the activation function so it's appropriate for your model. Again, we're trying to predict if some input data belongs to one of two classes, so we should use softmax.
net = tflearn.fully_connected(net, 2, activation='softmax')
Training
To set how you train the network, use
net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy')
Again, this is passing in the network you've been building. The keywords
Step11: Intializing the model
Next we need to call the build_model() function to actually build the model. In my solution I haven't included any arguments to the function, but you can add arguments so you can change parameters in the model if you want.
Note
Step12: Training the network
Now that we've constructed the network, saved as the variable model, we can fit it to the data. Here we use the model.fit method. You pass in the training features trainX and the training targets trainY. Below I set validation_set=0.1 which reserves 10% of the data set as the validation set. You can also set the batch size and number of epochs with the batch_size and n_epoch keywords, respectively. Below is the code to fit our the network to our word vectors.
You can rerun model.fit to train the network further if you think you can increase the validation accuracy. Remember, all hyperparameter adjustments must be done using the validation set. Only use the test set after you're completely done training the network.
Step13: Testing
After you're satisified with your hyperparameters, you can run the network on the test set to measure its performance. Remember, only do this after finalizing the hyperparameters.
Step14: Try out your own text! | Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
Explanation: Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with Numpy, we'll be using TFLearn, a high-level library built on top of TensorFlow. TFLearn makes it simpler to build networks just by defining the layers. It takes care of most of the details for you.
We'll start off by importing all the modules we'll need, then load and prepare the data.
End of explanation
reviews = pd.read_csv('reviews.txt', header=None)
labels = pd.read_csv('labels.txt', header=None)
Explanation: Preparing the data
Following along with Andrew, our goal here is to convert our reviews into word vectors. The word vectors will have elements representing words in the total vocabulary. If the second position represents the word 'the', for each review we'll count up the number of times 'the' appears in the text and set the second position to that count. I'll show you examples as we build the input data from the reviews data. Check out Andrew's notebook and video for more about this.
Read the data
Use the pandas library to read the reviews and postive/negative labels from comma-separated files. The data we're using has already been preprocessed a bit and we know it uses only lower case characters. If we were working from raw data, where we didn't know it was all lower case, we would want to add a step here to convert it. That's so we treat different variations of the same word, like The, the, and THE, all the same way.
End of explanation
from collections import Counter
total_counts = Counter()# bag of words here
for _, row in reviews.iterrows():
total_counts.update(row[0].split(' '))
print("Total words in data set: ", len(total_counts))
Explanation: Counting word frequency
To start off we'll need to count how often each word appears in the data. We'll use this count to create a vocabulary we'll use to encode the review data. This resulting count is known as a bag of words. We'll use it to select our vocabulary and build the word vectors. You should have seen how to do this in Andrew's lesson. Try to implement it here using the Counter class.
Exercise: Create the bag of words from the reviews data and assign it to total_counts. The reviews are stores in the reviews Pandas DataFrame. If you want the reviews as a Numpy array, use reviews.values. You can iterate through the rows in the DataFrame with for idx, row in reviews.iterrows(): (documentation). When you break up the reviews into words, use .split(' ') instead of .split() so your results match ours.
End of explanation
vocab = sorted(total_counts, key=total_counts.get, reverse=True)[:10000]
print(vocab[:60])
Explanation: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in the vocabulary are rarely used so they will have little effect on our predictions. Below, we'll sort vocab by the count value and keep the 10000 most frequent words.
End of explanation
print(vocab[-1], ': ', total_counts[vocab[-1]])
Explanation: What's the last word in our vocabulary? We can use this to judge if 10000 is too few. If the last word is pretty common, we probably need to keep more words.
End of explanation
word2idx = {word:i for i, word in enumerate(vocab)}## create the word-to-index dictionary here
len(word2idx)
Explanation: The last word in our vocabulary shows up in 30 reviews out of 25000. I think it's fair to say this is a tiny proportion of reviews. We are probably fine with this number of words.
Note: When you run, you may see a different word from the one shown above, but it will also have the value 30. That's because there are many words tied for that number of counts, and the Counter class does not guarantee which one will be returned in the case of a tie.
Now for each review in the data, we'll make a word vector. First we need to make a mapping of word to index, pretty easy to do with a dictionary comprehension.
Exercise: Create a dictionary called word2idx that maps each word in the vocabulary to an index. The first word in vocab has index 0, the second word has index 1, and so on.
End of explanation
def text_to_vector(text):
word_vector = np.zeros(len(vocab), dtype=np.int_)
for word in text.split(' '):
idx = word2idx.get(word, None)
if idx is not None:
word_vector[idx] += 1
return np.array(word_vector)
Explanation: Text to vector function
Now we can write a function that converts a some text to a word vector. The function will take a string of words as input and return a vector with the words counted up. Here's the general algorithm to do this:
Initialize the word vector with np.zeros, it should be the length of the vocabulary.
Split the input string of text into a list of words with .split(' '). Again, if you call .split() instead, you'll get slightly different results than what we show here.
For each word in that list, increment the element in the index associated with that word, which you get from word2idx.
Note: Since all words aren't in the vocab dictionary, you'll get a key error if you run into one of those words. You can use the .get method of the word2idx dictionary to specify a default returned value when you make a key error. For example, word2idx.get(word, None) returns None if word doesn't exist in the dictionary.
End of explanation
text_to_vector('The tea is for a party to celebrate '
'the movie so she has no time for a cake')[:65]
Explanation: If you do this right, the following code should return
```
text_to_vector('The tea is for a party to celebrate '
'the movie so she has no time for a cake')[:65]
array([0, 1, 0, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0])
```
End of explanation
word_vectors = np.zeros((len(reviews), len(vocab)), dtype=np.int_)
for ii, (_, text) in enumerate(reviews.iterrows()):
word_vectors[ii] = text_to_vector(text[0])
# Printing out the first 5 word vectors
word_vectors[:5, :23]
Explanation: Now, run through our entire review data set and convert each review to a word vector.
End of explanation
Y = (labels=='positive').astype(np.int_)
records = len(labels)
shuffle = np.arange(records)
np.random.shuffle(shuffle)
test_fraction = 0.9
train_split, test_split = shuffle[:int(records*test_fraction)], shuffle[int(records*test_fraction):]
trainX, trainY = word_vectors[train_split,:], to_categorical(Y.values[train_split].T[0], 2)
testX, testY = word_vectors[test_split,:], to_categorical(Y.values[test_split].T[0], 2)
trainX.shape
Y.values[train_split].T[0]
trainY
testY
Explanation: Train, Validation, Test sets
Now that we have the word_vectors, we're ready to split our data into train, validation, and test sets. Remember that we train on the train data, use the validation data to set the hyperparameters, and at the very end measure the network performance on the test data. Here we're using the function to_categorical from TFLearn to reshape the target data so that we'll have two output units and can classify with a softmax activation function. We actually won't be creating the validation set here, TFLearn will do that for us later.
End of explanation
# Network building
def build_model():
# This resets all parameters and variables, leave this here
tf.reset_default_graph()
#### Your code ####
# inputs
net = tflearn.input_data([None, 10000])
# hidden layers
net = tflearn.fully_connected(net, 150, activation='ReLU')
net = tflearn.fully_connected(net, 20, activation='ReLU')
# output layer
net = tflearn.fully_connected(net, 2, activation='softmax')
net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy')
model = tflearn.DNN(net)
return model
Explanation: Building the network
TFLearn lets you build the network by defining the layers.
Input layer
For the input layer, you just need to tell it how many units you have. For example,
net = tflearn.input_data([None, 100])
would create a network with 100 input units. The first element in the list, None in this case, sets the batch size. Setting it to None here leaves it at the default batch size.
The number of inputs to your network needs to match the size of your data. For this example, we're using 10000 element long vectors to encode our input data, so we need 10000 input units.
Adding layers
To add new hidden layers, you use
net = tflearn.fully_connected(net, n_units, activation='ReLU')
This adds a fully connected layer where every unit in the previous layer is connected to every unit in this layer. The first argument net is the network you created in the tflearn.input_data call. It's telling the network to use the output of the previous layer as the input to this layer. You can set the number of units in the layer with n_units, and set the activation function with the activation keyword. You can keep adding layers to your network by repeated calling net = tflearn.fully_connected(net, n_units).
Output layer
The last layer you add is used as the output layer. Therefore, you need to set the number of units to match the target data. In this case we are predicting two classes, positive or negative sentiment. You also need to set the activation function so it's appropriate for your model. Again, we're trying to predict if some input data belongs to one of two classes, so we should use softmax.
net = tflearn.fully_connected(net, 2, activation='softmax')
Training
To set how you train the network, use
net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy')
Again, this is passing in the network you've been building. The keywords:
optimizer sets the training method, here stochastic gradient descent
learning_rate is the learning rate
loss determines how the network error is calculated. In this example, with the categorical cross-entropy.
Finally you put all this together to create the model with tflearn.DNN(net). So it ends up looking something like
net = tflearn.input_data([None, 10]) # Input
net = tflearn.fully_connected(net, 5, activation='ReLU') # Hidden
net = tflearn.fully_connected(net, 2, activation='softmax') # Output
net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy')
model = tflearn.DNN(net)
Exercise: Below in the build_model() function, you'll put together the network using TFLearn. You get to choose how many layers to use, how many hidden units, etc.
End of explanation
model = build_model()
Explanation: Intializing the model
Next we need to call the build_model() function to actually build the model. In my solution I haven't included any arguments to the function, but you can add arguments so you can change parameters in the model if you want.
Note: You might get a bunch of warnings here. TFLearn uses a lot of deprecated code in TensorFlow. Hopefully it gets updated to the new TensorFlow version soon.
End of explanation
# Training
model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=200, n_epoch=10)
Explanation: Training the network
Now that we've constructed the network, saved as the variable model, we can fit it to the data. Here we use the model.fit method. You pass in the training features trainX and the training targets trainY. Below I set validation_set=0.1 which reserves 10% of the data set as the validation set. You can also set the batch size and number of epochs with the batch_size and n_epoch keywords, respectively. Below is the code to fit our the network to our word vectors.
You can rerun model.fit to train the network further if you think you can increase the validation accuracy. Remember, all hyperparameter adjustments must be done using the validation set. Only use the test set after you're completely done training the network.
End of explanation
predictions = (np.array(model.predict(testX))[:,0] >= 0.5).astype(np.int_)
test_accuracy = np.mean(predictions == testY[:,0], axis=0)
print("Test accuracy: ", test_accuracy)
Explanation: Testing
After you're satisified with your hyperparameters, you can run the network on the test set to measure its performance. Remember, only do this after finalizing the hyperparameters.
End of explanation
# Helper function that uses your model to predict sentiment
def test_sentence(sentence):
positive_prob = model.predict([text_to_vector(sentence.lower())])[0][1]
print('Sentence: {}'.format(sentence))
print('P(positive) = {:.3f} :'.format(positive_prob),
'Positive' if positive_prob > 0.5 else 'Negative')
sentence = "Moonlight is by far the best movie of 2016."
test_sentence(sentence)
print(model.predict([text_to_vector(sentence.lower())]))
sentence = "It's amazing anyone could be talented enough to make something this spectacularly awful"
test_sentence(sentence)
print(model.predict([text_to_vector(sentence.lower())]))
Explanation: Try out your own text!
End of explanation |
8,504 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
QuickStart
Step1: For a PoppyErgoJr
Step2: Get robot current status
Step3: Turn on/off the compliancy of a motor
Step4: Go to the zero position
Step5: Make a simple dance movement
On a single motor
Step6: On multiple motors
Step7: Wrap it inside a function for convenience
Step8: Using goto position instead | Python Code:
from poppy.creatures import PoppyErgo
ergo = PoppyErgo()
Explanation: QuickStart: Playing with a Poppy Ergo (or a PoppyErgoJr)
This notebook is still work in progress! Feedbacks are welcomed!
In this tutorial we will show how to get started with your PoppyErgo creature. You can use a PoppyErgoJr instead.
<img src="https://raw.githubusercontent.com/poppy-project/poppy-ergo-jr/master/doc/img/poppy-ergo-jr.jpg" alt="Poppy Ergo Jr" style="height: 500px;"/>
To run the code in this notebook, you will need:
* a poppy ergo creature (or a Jr)
* the pypot library
* the poppy-ergo library (or use the poppy-ergo-jr library instead)
You can install those libraries with the pip tool (see here if you don't know how to run this):
```bash
pip install pypot poppy-ergo
```
Connect to your robot
For a PoppyErgo:
End of explanation
from poppy.creatures import PoppyErgoJr
ergo = PoppyErgoJr()
Explanation: For a PoppyErgoJr:
End of explanation
ergo
ergo.m2
ergo.m2.present_position
ergo.m2.present_temperature
for m in ergo.motors:
print 'Motor "{}" current position = {}'.format(m.name, m.present_position)
Explanation: Get robot current status
End of explanation
ergo.m3.compliant
ergo.m6.compliant = False
Explanation: Turn on/off the compliancy of a motor
End of explanation
ergo.m6.goal_position = 0.
for m in ergo.motors:
m.compliant = False
# Goes to the position 0 in 2s
m.goto_position(0, 2)
# You can also change the maximum speed of the motors
# Warning! Goto position also change the maximum speed.
for m in ergo.motors:
m.moving_speed = 50
Explanation: Go to the zero position
End of explanation
import time
ergo.m4.goal_position = 30
time.sleep(1.)
ergo.m4.goal_position = -30
Explanation: Make a simple dance movement
On a single motor:
End of explanation
ergo.m4.goal_position = 30
ergo.m5.goal_position = 20
ergo.m6.goal_position = -20
time.sleep(1.)
ergo.m4.goal_position = -30
ergo.m5.goal_position = -20
ergo.m6.goal_position = 20
Explanation: On multiple motors:
End of explanation
def dance():
ergo.m4.goal_position = 30
ergo.m5.goal_position = 20
ergo.m6.goal_position = -20
time.sleep(1.)
ergo.m4.goal_position = -30
ergo.m5.goal_position = -20
ergo.m6.goal_position = 20
time.sleep(1.)
dance()
for _ in range(4):
dance()
Explanation: Wrap it inside a function for convenience:
End of explanation
def dance2():
ergo.goto_position({'m4': 30, 'm5': 20, 'm6': -20}, 1., wait=True)
ergo.goto_position({'m4': -30, 'm5': -20, 'm6': 20}, 1., wait=True)
for _ in range(4):
dance2()
Explanation: Using goto position instead:
End of explanation |
8,505 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST using Distributed Keras
Joeri Hermans (Technical Student, IT-DB-SAS, CERN)
Departement of Knowledge Engineering
Maastricht University, The Netherlands
Step1: In this notebook we will show you how to process the MNIST dataset using Distributed Keras. As in the workflow notebook, we will guide you through the complete machine learning pipeline.
Preparation
To get started, we first load all the required imports. Please make sure you installed dist-keras, and seaborn. Furthermore, we assume that you have access to an installation which provides Apache Spark.
Before you start this notebook, place the MNIST dataset (which is provided in this repository) on HDFS. Or in the case HDFS is not available, place it on the local filesystem. But make sure the path to the file is identical for all computing nodes.
Step2: In the following cell, adapt the parameters to fit your personal requirements.
Step3: As shown in the output of the cell above, we see that every pixel is associated with a seperate column. In order to ensure compatibility with Apache Spark, we vectorize the columns, and add the resulting vectors as a seperate column. However, in order to achieve this, we first need a list of the required columns. This is shown in the cell below.
Step4: Once we have a list of columns names, we can pass this to Spark's VectorAssembler. This VectorAssembler will take a list of features, vectorize them, and place them in a column defined in outputCol.
Step5: Once we have the inputs for our Neural Network (features column) after applying the VectorAssembler, we should also define the outputs. Since we are dealing with a classification task, the output of our Neural Network should be a one-hot encoded vector with 10 elements. For this, we provide a OneHotTransformer which accomplish this exact task.
Step6: MNIST
MNIST is a dataset of handwritten digits. Every image is a 28 by 28 pixel grayscale image. This means that every pixel has a value between 0 and 255. Some examples of instances within this dataset are shown in the cells below.
Step7: Normalization
In this Section, we will normalize the feature vectors between the 0 and 1 range.
Step8: Convolutions
In order to make the dense vectors compatible with convolution operations in Keras, we add another column which contains the matrix form of these images. We provide a utility class (MatrixTransformer), which helps you with this.
Step9: Model Development
Multilayer Perceptron
Step10: Convolutional network
Step11: Evaluation
We define a utility function which will compute the accuracy for us.
Step12: Training
Step13: DOWNPOUR (Multilayer Perceptron)
Step14: ADAG (MultiLayer Perceptron)
Step15: EASGD (MultiLayer Perceptron)
Step16: DOWNPOUR (Convolutional network)
Step17: ADAG (Convolutional network)
Step18: EASGD (Convolutional network) | Python Code:
!(date +%d\ %B\ %G)
Explanation: MNIST using Distributed Keras
Joeri Hermans (Technical Student, IT-DB-SAS, CERN)
Departement of Knowledge Engineering
Maastricht University, The Netherlands
End of explanation
%matplotlib inline
import numpy as np
import seaborn as sns
from keras.optimizers import *
from keras.models import Sequential
from keras.layers.core import *
from keras.layers.convolutional import *
from pyspark import SparkContext
from pyspark import SparkConf
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
from pyspark.ml.feature import StandardScaler
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.feature import OneHotEncoder
from pyspark.ml.feature import MinMaxScaler
from pyspark.ml.feature import StringIndexer
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from distkeras.trainers import *
from distkeras.predictors import *
from distkeras.transformers import *
from distkeras.evaluators import *
from distkeras.utils import *
Explanation: In this notebook we will show you how to process the MNIST dataset using Distributed Keras. As in the workflow notebook, we will guide you through the complete machine learning pipeline.
Preparation
To get started, we first load all the required imports. Please make sure you installed dist-keras, and seaborn. Furthermore, we assume that you have access to an installation which provides Apache Spark.
Before you start this notebook, place the MNIST dataset (which is provided in this repository) on HDFS. Or in the case HDFS is not available, place it on the local filesystem. But make sure the path to the file is identical for all computing nodes.
End of explanation
# Modify these variables according to your needs.
application_name = "Distributed Keras MNIST Notebook"
using_spark_2 = False
local = False
path_train = "data/mnist_train.csv"
path_test = "data/mnist_test.csv"
if local:
# Tell master to use local resources.
master = "local[*]"
num_processes = 3
num_executors = 1
else:
# Tell master to use YARN.
master = "yarn-client"
num_executors = 20
num_processes = 1
# This variable is derived from the number of cores and executors, and will be used to assign the number of model trainers.
num_workers = num_executors * num_processes
print("Number of desired executors: " + `num_executors`)
print("Number of desired processes / executor: " + `num_processes`)
print("Total number of workers: " + `num_workers`)
import os
# Use the DataBricks CSV reader, this has some nice functionality regarding invalid values.
os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages com.databricks:spark-csv_2.10:1.4.0 pyspark-shell'
conf = SparkConf()
conf.set("spark.app.name", application_name)
conf.set("spark.master", master)
conf.set("spark.executor.cores", `num_processes`)
conf.set("spark.executor.instances", `num_executors`)
conf.set("spark.executor.memory", "4g")
conf.set("spark.locality.wait", "0")
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
# Check if the user is running Spark 2.0 +
if using_spark_2:
sc = SparkSession.builder.config(conf=conf) \
.appName(application_name) \
.getOrCreate()
else:
# Create the Spark context.
sc = SparkContext(conf=conf)
# Add the missing imports
from pyspark import SQLContext
sqlContext = SQLContext(sc)
# Check if we are using Spark 2.0
if using_spark_2:
reader = sc
else:
reader = sqlContext
# Read the training dataset.
raw_dataset_train = reader.read.format('com.databricks.spark.csv') \
.options(header='true', inferSchema='true') \
.load(path_train)
# Read the testing dataset.
raw_dataset_test = reader.read.format('com.databricks.spark.csv') \
.options(header='true', inferSchema='true') \
.load(path_test)
Explanation: In the following cell, adapt the parameters to fit your personal requirements.
End of explanation
# First, we would like to extract the desired features from the raw dataset.
# We do this by constructing a list with all desired columns.
# This is identical for the test set.
features = raw_dataset_train.columns
features.remove('label')
Explanation: As shown in the output of the cell above, we see that every pixel is associated with a seperate column. In order to ensure compatibility with Apache Spark, we vectorize the columns, and add the resulting vectors as a seperate column. However, in order to achieve this, we first need a list of the required columns. This is shown in the cell below.
End of explanation
# Next, we use Spark's VectorAssembler to "assemble" (create) a vector of all desired features.
# http://spark.apache.org/docs/latest/ml-features.html#vectorassembler
vector_assembler = VectorAssembler(inputCols=features, outputCol="features")
# This transformer will take all columns specified in features, and create an additional column "features" which will contain all the desired features aggregated into a single vector.
dataset_train = vector_assembler.transform(raw_dataset_train)
dataset_test = vector_assembler.transform(raw_dataset_test)
Explanation: Once we have a list of columns names, we can pass this to Spark's VectorAssembler. This VectorAssembler will take a list of features, vectorize them, and place them in a column defined in outputCol.
End of explanation
# Define the number of output classes.
nb_classes = 10
encoder = OneHotTransformer(nb_classes, input_col="label", output_col="label_encoded")
dataset_train = encoder.transform(dataset_train)
dataset_test = encoder.transform(dataset_test)
Explanation: Once we have the inputs for our Neural Network (features column) after applying the VectorAssembler, we should also define the outputs. Since we are dealing with a classification task, the output of our Neural Network should be a one-hot encoded vector with 10 elements. For this, we provide a OneHotTransformer which accomplish this exact task.
End of explanation
def show_instances(column):
global dataset
num_instances = 6 # Number of instances you would like to draw.
x_dimension = 3 # Number of images to draw on the x-axis.
y_dimension = 2 # Number of images to draw on the y-axis.
# Fetch 3 different instance from the dataset.
instances = dataset_train.select(column).take(num_instances)
# Process the instances.
for i in range(0, num_instances):
instance = instances[i]
instance = instance[column].toArray().reshape((28, 28))
instances[i] = instance
# Draw the sampled instances.
fig, axn = plt.subplots(y_dimension, x_dimension, sharex=True, sharey=True)
num_axn = len(axn.flat)
for i in range(0, num_axn):
ax = axn.flat[i]
h = sns.heatmap(instances[i], ax=ax)
h.set_yticks([])
h.set_xticks([])
show_instances("features")
Explanation: MNIST
MNIST is a dataset of handwritten digits. Every image is a 28 by 28 pixel grayscale image. This means that every pixel has a value between 0 and 255. Some examples of instances within this dataset are shown in the cells below.
End of explanation
# Clear the dataset in the case you ran this cell before.
dataset_train = dataset_train.select("features", "label", "label_encoded")
dataset_test = dataset_test.select("features", "label", "label_encoded")
# Allocate a MinMaxTransformer using Distributed Keras.
# o_min -> original_minimum
# n_min -> new_minimum
transformer = MinMaxTransformer(n_min=0.0, n_max=1.0, \
o_min=0.0, o_max=250.0, \
input_col="features", \
output_col="features_normalized")
# Transform the dataset.
dataset_train = transformer.transform(dataset_train)
dataset_test = transformer.transform(dataset_test)
show_instances("features_normalized")
Explanation: Normalization
In this Section, we will normalize the feature vectors between the 0 and 1 range.
End of explanation
reshape_transformer = ReshapeTransformer("features_normalized", "matrix", (28, 28, 1))
dataset_train = reshape_transformer.transform(dataset_train)
dataset_test = reshape_transformer.transform(dataset_test)
Explanation: Convolutions
In order to make the dense vectors compatible with convolution operations in Keras, we add another column which contains the matrix form of these images. We provide a utility class (MatrixTransformer), which helps you with this.
End of explanation
mlp = Sequential()
mlp.add(Dense(1000, input_shape=(784,)))
mlp.add(Activation('relu'))
mlp.add(Dense(250))
mlp.add(Activation('relu'))
mlp.add(Dense(10))
mlp.add(Activation('softmax'))
mlp.summary()
optimizer_mlp = 'adam'
loss_mlp = 'categorical_crossentropy'
Explanation: Model Development
Multilayer Perceptron
End of explanation
# Taken from Keras MNIST example.
# Declare model parameters.
img_rows, img_cols = 28, 28
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)
input_shape = (img_rows, img_cols, 1)
# Construct the model.
convnet = Sequential()
convnet.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
border_mode='valid',
input_shape=input_shape))
convnet.add(Activation('relu'))
convnet.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
convnet.add(Activation('relu'))
convnet.add(MaxPooling2D(pool_size=pool_size))
convnet.add(Flatten())
convnet.add(Dense(225))
convnet.add(Activation('relu'))
convnet.add(Dense(nb_classes))
convnet.add(Activation('softmax'))
convnet.summary()
optimizer_convnet = 'adam'
loss_convnet = 'categorical_crossentropy'
Explanation: Convolutional network
End of explanation
def evaluate_accuracy(model, test_set, features="features_normalized_dense"):
evaluator = AccuracyEvaluator(prediction_col="prediction_index", label_col="label")
predictor = ModelPredictor(keras_model=model, features_col=features)
transformer = LabelIndexTransformer(output_dim=nb_classes)
test_set = test_set.select(features, "label")
test_set = predictor.predict(test_set)
test_set = transformer.transform(test_set)
score = evaluator.evaluate(test_set)
return score
Explanation: Evaluation
We define a utility function which will compute the accuracy for us.
End of explanation
dataset_train.printSchema()
dataset_train = dataset_train.select("features_normalized", "matrix","label", "label_encoded")
dataset_test = dataset_test.select("features_normalized", "matrix","label", "label_encoded")
dense_transformer = DenseTransformer(input_col="features_normalized", output_col="features_normalized_dense")
dataset_train = dense_transformer.transform(dataset_train)
dataset_test = dense_transformer.transform(dataset_test)
dataset_train.repartition(num_workers)
dataset_test.repartition(num_workers)
# Assing the training and test set.
training_set = dataset_train.repartition(num_workers)
test_set = dataset_test.repartition(num_workers)
# Cache them.
training_set.cache()
test_set.cache()
print(training_set.count())
Explanation: Training
End of explanation
trainer = DOWNPOUR(keras_model=mlp, worker_optimizer=optimizer_mlp, loss=loss_mlp, num_workers=num_workers,
batch_size=4, communication_window=5, num_epoch=1,
features_col="features_normalized_dense", label_col="label_encoded")
trained_model = trainer.train(training_set)
print("Training time: " + str(trainer.get_training_time()))
print("Accuracy: " + str(evaluate_accuracy(trained_model, test_set)))
trainer.parameter_server.num_updates
Explanation: DOWNPOUR (Multilayer Perceptron)
End of explanation
trainer = ADAG(keras_model=mlp, worker_optimizer=optimizer_mlp, loss=loss_mlp, num_workers=num_workers,
batch_size=4, communication_window=15, num_epoch=1,
features_col="features_normalized_dense", label_col="label_encoded")
trained_model = trainer.train(training_set)
print("Training time: " + str(trainer.get_training_time()))
print("Accuracy: " + str(evaluate_accuracy(trained_model, test_set)))
trainer.parameter_server.num_updates
Explanation: ADAG (MultiLayer Perceptron)
End of explanation
trainer = AEASGD(keras_model=mlp, worker_optimizer=optimizer_mlp, loss=loss_mlp, num_workers=num_workers,
batch_size=4, communication_window=35, num_epoch=1, features_col="features_normalized_dense",
label_col="label_encoded")
trained_model = trainer.train(training_set)
print("Training time: " + str(trainer.get_training_time()))
print("Accuracy: " + str(evaluate_accuracy(trained_model, test_set)))
trainer.parameter_server.num_updates
Explanation: EASGD (MultiLayer Perceptron)
End of explanation
trainer = DOWNPOUR(keras_model=convnet, worker_optimizer=optimizer_convnet, loss=loss_convnet,
num_workers=num_workers, batch_size=4, communication_window=5,
num_epoch=1, features_col="matrix", label_col="label_encoded")
trainer.set_parallelism_factor(1)
trained_model = trainer.train(training_set)
print("Training time: " + str(trainer.get_training_time()))
print("Accuracy: " + str(evaluate_accuracy(trained_model, test_set, "matrix")))
trainer.parameter_server.num_updates
Explanation: DOWNPOUR (Convolutional network)
End of explanation
trainer = ADAG(keras_model=convnet, worker_optimizer=optimizer_convnet, loss=loss_convnet,
num_workers=num_workers, batch_size=15, communication_window=5, num_epoch=1,
features_col="matrix", label_col="label_encoded")
trainer.set_parallelism_factor(1)
trained_model = trainer.train(training_set)
print("Training time: " + str(trainer.get_training_time()))
print("Accuracy: " + str(evaluate_accuracy(trained_model, test_set, "matrix")))
trainer.parameter_server.num_updates
Explanation: ADAG (Convolutional network)
End of explanation
trainer = AEASGD(keras_model=convnet, worker_optimizer=optimizer_convnet, loss=loss_convnet,
num_workers=num_workers, batch_size=35, communication_window=32, num_epoch=1,
features_col="matrix", label_col="label_encoded")
trained_model = trainer.train(training_set)
print("Training time: " + str(trainer.get_training_time()))
print("Accuracy: " + str(evaluate_accuracy(trained_model, test_set, "matrix")))
trainer.parameter_server.num_updates
Explanation: EASGD (Convolutional network)
End of explanation |
8,506 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Goal
We want to build a model $h_\theta(s) \rightarrow a^$ which predicts the mode $a^$ of some target distribution, for which we have unnormalized log-probabilities, $y$.
Stated another way, we want to find an appropriate loss L s.t. it is tractable to solve
$$
\text{argmin}\theta \sum\limits{i=1}^N L(\pi(a_i \mid h_\theta(s_i)), y_i)
$$
where $\theta$ are model parameters, $h$ is a model that depends on context $s$ and outputs the mode of $\pi$, and $\pi(a \mid \text{mode})$ is the predicted probability of action $a$. $y$ is information about the target distribution. We want the mode of $\pi$ to correspond to areas where $y$ is maximized.
Candidate
$$
L(a, h_\theta(s), y) = \left\lvert -\lvert h_\theta(s) - a\rvert^p - y \right\rvert^{1/p}
$$
where $p$ is close to 0.
Step2: Generalize the loss above to
$$
L(a, h_\theta(s), y) = \left\lvert -\lvert h_\theta(s) - a\rvert^p - y \right\rvert^{q}
$$
where $q = 1/p$. Bringing $p$ arbitrarily close to 0 converges to the non-differentiable $L^0$ loss. Choosing $p=0.1$ seems to be small enough for practable purposes. | Python Code:
#@title Default title text
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Explanation: Copyright 2020 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
End of explanation
import numpy as np
import tensorflow.compat.v2 as tf
import matplotlib.pyplot as plt
tf.enable_v2_behavior()
n = 20
lower, upper = -2, 2
modes_x, modes_y = zip(*[ # (x, y)
(-1., -20),
(0.0, -20),
(1., -20),
])
x = np.concatenate((modes_x, np.random.uniform(lower, upper, size=n-len(modes_x))))
y = np.random.uniform(-1000, -300, size=n)
y[:len(modes_x)] = modes_y
y /= np.max(np.abs(y))
plt.scatter(x, y)
plt.show()
Explanation: Goal
We want to build a model $h_\theta(s) \rightarrow a^$ which predicts the mode $a^$ of some target distribution, for which we have unnormalized log-probabilities, $y$.
Stated another way, we want to find an appropriate loss L s.t. it is tractable to solve
$$
\text{argmin}\theta \sum\limits{i=1}^N L(\pi(a_i \mid h_\theta(s_i)), y_i)
$$
where $\theta$ are model parameters, $h$ is a model that depends on context $s$ and outputs the mode of $\pi$, and $\pi(a \mid \text{mode})$ is the predicted probability of action $a$. $y$ is information about the target distribution. We want the mode of $\pi$ to correspond to areas where $y$ is maximized.
Candidate
$$
L(a, h_\theta(s), y) = \left\lvert -\lvert h_\theta(s) - a\rvert^p - y \right\rvert^{1/p}
$$
where $p$ is close to 0.
End of explanation
# Mode
p=0.1
q=1/p
t = np.linspace(-2,2,200).reshape(-1, 1)
L = np.mean(np.power(np.abs(-np.power(np.abs(t - x[np.newaxis,:]), p) - y[np.newaxis,:]), q), axis=1)
plt.plot(t, L)
plt.show()
# Median
p=1.0
q=2.0
t = np.linspace(-2,2,200).reshape(-1, 1)
L = np.mean(np.power(np.abs(-np.power(np.abs(t - x[np.newaxis,:]), p) - y[np.newaxis,:]), q), axis=1)
#plt.ylim(0.5, 1.)
plt.plot(t, L)
plt.show()
# Mean
p=2.0
q=2.0
t = np.linspace(-2,2,200).reshape(-1, 1)
L = np.mean(np.power(np.abs(-np.power(np.abs(t - x[np.newaxis,:]), p) - y[np.newaxis,:]), q), axis=1)
#plt.ylim(0.5, 1.)
plt.plot(t, L)
plt.show()
Explanation: Generalize the loss above to
$$
L(a, h_\theta(s), y) = \left\lvert -\lvert h_\theta(s) - a\rvert^p - y \right\rvert^{q}
$$
where $q = 1/p$. Bringing $p$ arbitrarily close to 0 converges to the non-differentiable $L^0$ loss. Choosing $p=0.1$ seems to be small enough for practable purposes.
End of explanation |
8,507 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div style="width
Step1: We pull out this dataset and call subset() to set up requesting a subset of the data.
Step2: We can then use the ncss object to create a new query object, which
facilitates asking for data from the server.
Step3: We can look at the ncss.variables object to see what variables are available from the dataset
Step4: We construct a query asking for data corresponding to a latitude and longitude box where 43 lat is the northern extent, 35 lat is the southern extent, 260 long is the western extent and 249 is the eastern extent. Note that longitude values are the longitude distance from the prime meridian. We request the data for the current time. This request will return all surface temperatures for points in our bounding box for a single time. Note the string representation of the query is a properly encoded query string.
Step5: We now request data from the server using this query. The NCSS class handles parsing this NetCDF data (using the netCDF4 module). If we print out the variable names, we see our requested variables, as well as a few others (more metadata information)
Step6: We'll pull out the temperature variable.
Step7: We'll pull out the useful variables for latitude, and longitude, and time (which is the time, in hours since the forecast run). Notice the variable names are labeled to show how many dimensions each variable is. This will come in to play soon when we prepare to plot. Try printing one of the variables to see some info on the data!
Step8: Now we make our data suitable for plotting. We'll import numpy so we can combine lat/longs (meshgrid) and remove one-dimensional entities from our arrays (squeeze). Also we'll use netCDF4's num2date to change the time since the model run to an actual date.
Step9: Now we can plot these up using matplotlib. We import cartopy and matplotlib classes, create our figure, add a map, then add the temperature data and grid points. | Python Code:
%matplotlib inline
from siphon.catalog import TDSCatalog
best_gfs = TDSCatalog('http://thredds.ucar.edu/thredds/catalog/grib/NCEP/GFS/'
'Global_0p25deg/catalog.xml?dataset=grib/NCEP/GFS/Global_0p25deg/Best')
best_gfs.datasets
Explanation: <div style="width:1000 px">
<div style="float:right; width:98 px; height:98px;">
<img src="https://raw.githubusercontent.com/Unidata/MetPy/master/metpy/plots/_static/unidata_150x150.png" alt="Unidata Logo" style="height: 98px;">
</div>
<h1>Using Siphon to query the NetCDF Subset Service</h1>
<h3>Unidata Python Workshop</h3>
<div style="clear:both"></div>
</div>
<hr style="height:2px;">
Objectives
Learn what Siphon is
Employ Siphon's NCSS class to retrieve data from a THREDDS Data Server (TDS)
Plot a map using numpy arrays, matplotlib, and cartopy!
Introduction:
Siphon is a python package that makes downloading data from Unidata data technologies a breeze! In our examples, we'll focus on interacting with the netCDF Subset Service (NCSS) as well as the radar server to retrieve grid data and radar data.
But first!
Bookmark these resources for when you want to use Siphon later!
+ latest Siphon documentation
+ Siphon github repo
+ TDS documentation
+ netCDF subset service documentation
Let's get started!
First, we'll import the TDSCatalog class from Siphon and put the special 'matplotlib' line in so our map will show up later in the notebook. Let's construct an instance of TDSCatalog pointing to our dataset of interest. In this case, I've chosen the TDS' "Best" virtual dataset for the GFS global 0.25 degree collection of GRIB files. This will give us a good resolution for our map. This catalog contains a single dataset.
End of explanation
best_ds = list(best_gfs.datasets.values())[0]
ncss = best_ds.subset()
Explanation: We pull out this dataset and call subset() to set up requesting a subset of the data.
End of explanation
query = ncss.query()
Explanation: We can then use the ncss object to create a new query object, which
facilitates asking for data from the server.
End of explanation
ncss.variables
Explanation: We can look at the ncss.variables object to see what variables are available from the dataset:
End of explanation
from datetime import datetime
query.lonlat_box(north=43, south=35, east=260, west=249).time(datetime.utcnow())
query.accept('netcdf4')
query.variables('Temperature_surface')
Explanation: We construct a query asking for data corresponding to a latitude and longitude box where 43 lat is the northern extent, 35 lat is the southern extent, 260 long is the western extent and 249 is the eastern extent. Note that longitude values are the longitude distance from the prime meridian. We request the data for the current time. This request will return all surface temperatures for points in our bounding box for a single time. Note the string representation of the query is a properly encoded query string.
End of explanation
from xarray.backends import NetCDF4DataStore
import xarray as xr
data = ncss.get_data(query)
data = xr.open_dataset(NetCDF4DataStore(data))
list(data)
Explanation: We now request data from the server using this query. The NCSS class handles parsing this NetCDF data (using the netCDF4 module). If we print out the variable names, we see our requested variables, as well as a few others (more metadata information)
End of explanation
temp_3d = data['Temperature_surface']
Explanation: We'll pull out the temperature variable.
End of explanation
# Helper function for finding proper time variable
def find_time_var(var, time_basename='time'):
for coord_name in var.coords:
if coord_name.startswith(time_basename):
return var.coords[coord_name]
raise ValueError('No time variable found for ' + var.name)
time_1d = find_time_var(temp_3d)
lat_1d = data['lat']
lon_1d = data['lon']
time_1d
Explanation: We'll pull out the useful variables for latitude, and longitude, and time (which is the time, in hours since the forecast run). Notice the variable names are labeled to show how many dimensions each variable is. This will come in to play soon when we prepare to plot. Try printing one of the variables to see some info on the data!
End of explanation
import numpy as np
from netCDF4 import num2date
from metpy.units import units
# Reduce the dimensions of the data and get as an array with units
temp_2d = temp_3d.metpy.unit_array.squeeze()
# Combine latitude and longitudes
lon_2d, lat_2d = np.meshgrid(lon_1d, lat_1d)
Explanation: Now we make our data suitable for plotting. We'll import numpy so we can combine lat/longs (meshgrid) and remove one-dimensional entities from our arrays (squeeze). Also we'll use netCDF4's num2date to change the time since the model run to an actual date.
End of explanation
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from metpy.plots import ctables
# Create a new figure
fig = plt.figure(figsize=(15, 12))
# Add the map and set the extent
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent([-100.03, -111.03, 35, 43])
# Retrieve the state boundaries using cFeature and add to plot
ax.add_feature(cfeature.STATES, edgecolor='gray')
# Contour temperature at each lat/long
contours = ax.contourf(lon_2d, lat_2d, temp_2d.to('degF'), 200, transform=ccrs.PlateCarree(),
cmap='RdBu_r')
#Plot a colorbar to show temperature and reduce the size of it
fig.colorbar(contours)
# Make a title with the time value
ax.set_title(f'Temperature forecast (\u00b0F) for {time_1d[0].values}Z', fontsize=20)
# Plot markers for each lat/long to show grid points for 0.25 deg GFS
ax.plot(lon_2d.flatten(), lat_2d.flatten(), linestyle='none', marker='o',
color='black', markersize=2, alpha=0.3, transform=ccrs.PlateCarree());
Explanation: Now we can plot these up using matplotlib. We import cartopy and matplotlib classes, create our figure, add a map, then add the temperature data and grid points.
End of explanation |
8,508 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: 사용자 정의 학습
Step2: 붓꽃 분류 문제
당신이 식물학자라고 상상하고, 주어진 붓꽃을 자동적으로 분류하는 방법을 찾고 있다고 가정합시다. 머신러닝은 통계적으로 꽃을 분류할 수 있는 다양한 알고리즘을 제공합니다. 예를 들어, 정교한 머신러닝 프로그램은 사진을 통해 꽃을 분류할 수 있습니다. 이번 튜토리얼의 목적은 좀 더 겸손하게, 측정된 꽃받침과 꽃잎의 길이와 폭을 토대로 붓꽃을 분류하는 것입니다.
이 붓꽃은 약 300종입니다. 하지만 이번 튜토리얼에서는 오직 3가지 품종을 기준으로 분류할 것입니다.
Iris setosa
Iris virginica
Iris versicolor
<table>
<tr><td>
<img src="https
Step3: 데이터 탐색
이 데이터셋(iris_training.csv)은 콤마 ','로 구분된 CSV 파일입니다. head -n5 명령을 사용하여 처음 5개 항목을 확인합니다.
Step4: 처음 5개의 데이터로부터 다음을 주목하세요.
첫 번째 줄은 다음과 같은 정보를 포함하고 있는 헤더(header)입니다.
총 120개의 샘플이 있으며, 각 샘플들은 4개의 특성(feature), 3개의 레이블(label)을 가지고 있습니다.
후속행은 데이터 레코드입니다. 한 줄당 한가지 샘플입니다.
처음 4개의 필드는 특성입니다.
Step5: 각각의 레이블은 "setosa"와 같은 문자형 이름과 연관되어있습니다. 하지만 머신러닝은 전형적으로 숫자형 값에 의존합니다. 레이블을 다음과 같이 맵핑(mapping) 합니다.
0
Step6: tf.data.Dataset 생성
텐서플로의 Dataset API는 데이터를 적재할 때 발생하는 다양한 경우를 다룰 수 있습니다. 이는 훈련에 필요한 형태로 데이터를 읽고 변환하는 고수준 API입니다. 더 많은 정보를 위해서는 데이터셋 빠른 실행 가이드를 참조하세요.
데이터셋이 CSV 파일이므로, 적절한 형태로 데이터를 구분하기위해 make_csv_dataset 함수를 사용하겠습니다. 이 함수는 훈련 모델을 위한 데이터를 생성하므로, 초기값은 셔플(shuffle=True, shuffle_buffer_size=10000)과 무한반복(num_epochs=None)으로 설정되어있습니다. 또한 배치 사이즈(batch_size)를 설정해줍니다.
Step7: make_csv_dataset 함수는 (features, label) 쌍으로 구성된 tf.data.Dataset을 반환합니다. features는 딕셔너리 객체인
Step8: 유사한 특성의 값은 같이 그룹 되어있거나, 배치 돼있다는 사실에 주목하세요. 각 샘플 행의 필드는 해당 특성 배열에 추가됩니다. batch_size를 조절하여 이 특성 배열에 저장된 샘플의 수를 설정하세요.
또한 배치(batch)로부터 약간의 특성을 도식화하여 군집돼있는 데이터를 확인할 수 있습니다.
Step10: 모델 구축 단계를 단순화하기 위해, 특성 딕셔너리를 (batch_size, num_features)의 형태를 가지는 단일 배열로 다시 구성하는 함수를 생성합니다.
이 함수는 텐서의 리스트(list)로부터 값을 취하고 특정한 차원으로 결합된 텐서를 생성하는 tf.stack 메서드(method)를 사용합니다.
Step11: 그 후 각 (features,label)쌍의 특성을 훈련 데이터셋에 쌓기위해 tf.data.Dataset.map 메서드를 사용합니다.
Step12: 데이터셋의 특성 요소는 이제 형태가 (batch_size, num_features)인 배열입니다. 첫 5개행의 샘플을 살펴봅시다.
Step13: 모델 타입 선정
왜 모델을 사용해야하는가?
모델은 특성(feature)과 레이블(label) 과의 관계입니다. 붓꽃 분류 문제에서 모델은 측정된 꽃받침과 꽃잎 사이의 관계를 정의하고 붓꽃의 품종을 예측합니다. 몇 가지 간단한 모델은 몇 줄의 대수학으로 표현할 수 있으나, 복잡한 머신러닝 모델은 요약하기 힘든 굉장히 많은 수의 매개변수를 가지고 있습니다.
머신러닝을 사용하지 않고 4가지의 특성 사이의 관계를 결정하고 붓꽃을 품종을 예측하실 수 있으신가요? 즉, 특정 품종의 꽃받침과 꽃잎과의 관계를 정의할 수 있을 정도로 데이터셋을 분석했다면, 전통적인 프로그래밍 기술(예를 들어 굉장히 많은 조건문)을 사용하여 모델은 만들 수 있으신가요? 더 복잡한 데이터셋에서 이는 불가능에 가까울 수 있습니다. 잘 구성된 머신러닝은 사용자를 위한 모델을 결정합니다. 만약 충분히 좋은 샘플을 잘 구성된 머신러닝 모델에 제공한다면, 프로그램은 사용자를 위한 특성 간의 관계를 이해하고 제공합니다.
모델 선정
이제 학습을 위한 모델의 종류를 선정해야합니다. 여러 종류의 모델이 있고, 이를 선택하는 것은 많은 경험이 필요합니다. 이번 튜토리얼에서는 붓꽃 분류 문제를 해결하기위해 신경망(neural network) 모델을 사용하겠습니다. 신경망 모델은 특성과 레이블 사이의 복잡한 관계를 찾을 수 있습니다. 신경망은 하나 또는 그 이상의 은닉층(hidden layer)으로 구성된 그래프입니다. 각각의 은닉층은 하나 이상의 뉴런(neuron)으로 구성되어있습니다. 몇가지 신경망의 범주가 있으며, 이번 튜토리얼에서는 밀집(dense) 또는 완전 연결 신경망(fully-connected neural network)를 사용합니다
Step14: 활성화 함수(activation function)는 각 층에서 출력의 크기를 결정합니다. 이러한 비선형성은 중요하며, 활성화 함수가 없는 모델은 하나의 층과 동일하다고 생각할 수 있습니다. 사용 가능한 활성화 함수는 많지만, ReLU가 은닉층에 주로 사용됩니다.
이상적인 은닉층과 뉴런의 개수는 문제와 데이터셋에 의해 좌우됩니다. 머신러닝의 여러 측면과 마찬가지로, 최적의 신경망 타입을 결정하는 것은 많은 경험과 지식이 필요합니다. 경험을 토대로 보면 은닉층과 뉴런의 증가는 전형적으로 강력한 모델을 생성하므로, 모델을 효과적으로 훈련시키기 위해서 더 많은 데이터를 필요로 합니다.
모델 사용
이 모델이 특성의 배치에 대해 수행하는 작업을 간단히 살펴봅시다.
Step15: 각 샘플은 각 클래스에 대한 로짓(logit)을 반환합니다.
이 로짓(logit)을 각 클래스에 대한 확률로 변환하기 위하서 소프트맥스(softmax) 함수를 사용하겠습니다.
Step16: tf.argmax는 예측된 값 중 가장 큰 확률(원하는 클래스)을 반환합니다. 하지만 모델이 아직 훈련되지 않았으므로 이는 좋은 예측이 아닙니다.
Step17: 모델 훈련하기
훈련 단계는 모델이 점진적으로 최적화되거나 데이터셋을 학습하는 머신러닝의 과정입니다. 훈련의 목적은 미지의 데이터를 예측하기 위해, 훈련 데이터셋의 구조에 대해서 충분히 학습하는 것입니다. 만약 모델이 훈련 데이터셋에 대해서 과하게 학습된다면 오직 훈련 데이터셋에 대해서 작동할 것이며, 일반화되기 힘들 것입니다. 이러한 문제를 과대적합(overfitting) 이라고 합니다. 이는 마치 문제를 이해하고 해결한다기보다는 답을 기억하는 것이라고 생각할 수 있습니다.
붓꽃 분류 문제는 지도 학습(supervised machine learning)의 예시 중 하나입니다.
Step18: 모델을 최적화하기 위해 사용되는 그래디언트(gradient)를 계산하기 위해 tf.GradientTape 컨텍스트를 사용합니다. 더 자세한 정보는 즉시 실행 가이드를 확인하세요.
Step19: 옵티마이저 생성
옵티마이저(optimizer)는 손실 함수를 최소화하기 위해 계산된 그래디언트를 모델의 변수에 적용합니다. 손실 함수를 구부러진 곡선의 표면(그림 3)으로 생각할 수 있으며, 이 함수의 최저점을 찾고자 합니다. 그래디언트는 가장 가파른 상승 방향을 가리키며 따라서 반대 방향으로 이동하는 여행을 합니다. 각 배치마다의 손실과 기울기를 반복적으로 계산하여 훈련과정 동안 모델을 조정합니다. 점진적으로, 모델은 손실을 최소화하기 위해 가중치(weight)와 편향(bias)의 최적의 조합을 찾아냅니다. 손실이 낮을수록 더 좋은 모델의 예측을 기대할 수 있습니다.
<table>
<tr><td>
<img src="https
Step20: 이 값들을 단일 최적화 단계를 계산하기 위해 사용합니다.
Step21: 훈련 루프
모든 사항이 갖춰졌으므로 모델을 훈련할 준비가 되었습니다! 훈련 루프는 더 좋은 예측을 위해 데이터셋을 모델로 제공합니다. 다음의 코드 블럭은 아래의 훈련 단계를 작성한 것입니다.
각 에포크(epoch) 반복. 에포크는 데이터셋을 통과시키는 횟수입니다.
에포크 내에서, 특성 (x)와 레이블 (y)가 포함된 훈련 데이터셋에 있는 샘플을 반복합니다.
샘플의 특성을 사용하여 결과를 예측 하고 레이블과 비교합니다. 예측의 부정확도를 측정하고 모델의 손실과 그래디언트를 계산하기 위해 사용합니다.
모델의 변수를 업데이트하기 위해 옵티마이저를 사용합니다.
시각화를 위해 몇가지 값들을 저장합니다.
각 에포크를 반복합니다.
num_epochs 변수는 데이터셋의 반복 횟수입니다. 직관과는 반대로, 모델을 길게 학습하는 것이 더 나은 모델이 될 것이라고 보장하지 못합니다. num_epochs는 조정가능한 하이퍼파라미터(hyperparameter) 입니다. 적절한 횟수를 선택하는 것은 많은 경험과 직관을 필요로 합니다.
Step22: 시간에 따른 손실함수 시각화
모델의 훈련 과정을 출력하는 것도 도움이 되지만, 훈련 과정을 직접 보는 것이 더 도움이 되곤합니다. 텐서보드(tensorboard)는 텐서플로에 패키지 되어있는 굉장히 유용한 시각화 툴입니다. 하지만 matplotlib 모듈을 사용하여 일반적인 도표를 출력할 수 있습니다.
이 도표를 해석하는 것은 여러 경험이 필요하지만, 결국 모델을 최적화하기 위해 손실이 내려가고 정확도가 올라가는 것을 원합니다.
Step23: 모델 유효성 평가
이제 모델은 훈련되었습니다. 모델의 성능에 대한 몇가지 통계를 얻을 수 있습니다.
평가(Evaluating)는 모델이 예측을 얼마나 효과적으로 수행하는지 결정하는 것을 의미합니다. 붓꽃 분류 모델의 유효성을 결정하기 위해, 몇가지 꽃잎과 꽃받침 데이터를 통과시키고 어떠한 품종을 예측하는지 확인합니다. 그 후 실제 품종과 비교합니다. 예를 들어, 절반의 데이터를 올바르게 예측한 모델의 정확도 는 0.5입니다. 그림 4는 조금 더 효과적인 모델입니다. 5개의 예측 중 4개를 올바르게 예측하여 80% 정확도를 냅니다.
<table cellpadding="8" border="0">
<colgroup>
<col span="4" >
<col span="1" bgcolor="lightblue">
<col span="1" bgcolor="lightgreen">
</colgroup>
<tr bgcolor="lightgray">
<th colspan="4">샘플 특성</th>
<th colspan="1">레이블</th>
<th colspan="1" >모델 예측</th>
</tr>
<tr>
<td>5.9</td><td>3.0</td><td>4.3</td><td>1.5</td><td align="center">1</td><td align="center">1</td>
</tr>
<tr>
<td>6.9</td><td>3.1</td><td>5.4</td><td>2.1</td><td align="center">2</td><td align="center">2</td>
</tr>
<tr>
<td>5.1</td><td>3.3</td><td>1.7</td><td>0.5</td><td align="center">0</td><td align="center">0</td>
</tr>
<tr>
<td>6.0</td> <td>3.4</td> <td>4.5</td> <td>1.6</td> <td align="center">1</td><td align="center" bgcolor="red">2</td>
</tr>
<tr>
<td>5.5</td><td>2.5</td><td>4.0</td><td>1.3</td><td align="center">1</td><td align="center">1</td>
</tr>
<tr><td align="center" colspan="6">
<b>그림 4.</b> 80% 정확도 붓꽃 분류기.<br/>
</td></tr>
</table>
테스트 데이터 세트 설정
모델을 평가하는 것은 모델을 훈련하는 것과 유사합니다. 가장 큰 차이는 훈련 데이터가 아닌 테스트 데이터 세트 를 사용했다는 것입니다. 공정하게 모델의 유효성을 평가하기 위해, 모델을 평가하기 위한 샘플은 반드시 훈련 데이터와 달라야합니다.
테스트 데이터 세트를 설정하는 것은 훈련 데이터 세트를 설정하는 것과 유사합니다. CSV 파일을 다운로드하고 값을 파싱합니다. 그 후 셔플은 적용하지 않습니다.
Step24: 테스트 데이터 세트를 사용한 모델 평가
훈련 단계와는 다르게 모델은 테스트 데이터에 대해서 오직 한 번의 에포크를 진행합니다. 다음의 코드 셀은 테스트 셋에 있는 샘플에 대해 실행하고 실제 레이블과 비교합니다. 이는 전체 테스트 데이터 세트에 대한 정확도를 측정하는데 사용됩니다.
Step25: 마지막 배치에서 모델이 올바르게 예측한 것을 확인할 수 있습니다.
Step26: 훈련된 모델로 예측하기
이제 붓꽃을 분류하기 위해 완벽하지는 않지만 어느 정도 검증된 모델을 가지고 있습니다. 훈련된 모델을 사용하여 레이블 되지 않은 데이터를 예측해봅시다.
실제로는 레이블 되지 않은 샘플들은 여러 소스(앱, CSV 파일, 직접 제공 등)로부터 제공될 수 있습니다. 지금은 레이블을 예측하기 위해 수동으로 3개의 레이블 되지 않은 샘플을 제공하겠습니다. 레이블은 다음과 같은 붓꽃 이름으로 매핑되어있습니다.
* 0 | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Explanation: Copyright 2018 The TensorFlow Authors.
End of explanation
import os
import matplotlib.pyplot as plt
import tensorflow.compat.v1 as tf
print("텐서플로 버전: {}".format(tf.__version__))
print("즉시 실행: {}".format(tf.executing_eagerly()))
Explanation: 사용자 정의 학습: 자세히 둘러보기
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/r1/tutorials/eager/custom_training_walkthrough.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />구글 코랩(Colab)에서 실행하기</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ko/r1/tutorials/eager/custom_training_walkthrough.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />깃허브(GitHub) 소스 보기</a>
</td>
</table>
Note: 이 문서는 텐서플로 커뮤니티에서 번역했습니다. 커뮤니티 번역 활동의 특성상 정확한 번역과 최신 내용을 반영하기 위해 노력함에도
불구하고 공식 영문 문서의 내용과 일치하지 않을 수 있습니다.
이 번역에 개선할 부분이 있다면
tensorflow/docs 깃헙 저장소로 풀 리퀘스트를 보내주시기 바랍니다.
문서 번역이나 리뷰에 참여하려면
docs-ko@tensorflow.org로
메일을 보내주시기 바랍니다.
이번 튜토리얼은 붓꽃의 품종을 분류하기 위한 머신러닝 모델을 구축할 것입니다. 다음을 위해 즉시 실행(eager execution)을 사용합니다.
1. 모델 구축
2. 모델 훈련
3. 예측을 위한 모델 사용
텐서플로 프로그래밍
이번 튜토리얼에서는 다음과 같은 고수준 텐서플로의 개념을 사용합니다.
즉시 실행(eager execution) 개발 환경,
데이터셋 API를 활용한 데이터 가져오기,
케라스 API를 활용한 모델과 층(layer) 구축 .
이번 튜토리얼은 다른 텐서플로 프로그램과 유사하게 구성되어있습니다.
데이터 가져오기 및 분석.
모델 타입 선정.
모델 훈련.
모델 효과 평가.
예측을 위한 훈련된 모델 사용.
프로그램 설정
임포트 및 즉시 실행 구성
텐서플로를 포함하여 필요한 파이썬 모듈을 임포트하고, 즉시 실행을 활성화합니다. 즉시 실행은 텐서플로 연산이 나중에 실행되는 계산 그래프(computational graph)를 만드는 대신에 연산을 즉시 평가하고 구체적인 값을 반환하게 합니다. 만약 파이썬 대화형 창이나 상호작용 콘솔을 사용하시면 더욱 익숙할 겁니다. 즉시 실행은 Tensorlow >=1.8 부터 사용 가능합니다.
즉시 실행이 활성화될 때, 동일한 프로그램내에서 비활성화 할 수 없습니다. 더 많은 세부사항은 즉시 실행 가이드를 참조하세요.
End of explanation
train_dataset_url = "https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv"
train_dataset_fp = tf.keras.utils.get_file(fname=os.path.basename(train_dataset_url),
origin=train_dataset_url)
print("데이터셋이 복사된 위치: {}".format(train_dataset_fp))
Explanation: 붓꽃 분류 문제
당신이 식물학자라고 상상하고, 주어진 붓꽃을 자동적으로 분류하는 방법을 찾고 있다고 가정합시다. 머신러닝은 통계적으로 꽃을 분류할 수 있는 다양한 알고리즘을 제공합니다. 예를 들어, 정교한 머신러닝 프로그램은 사진을 통해 꽃을 분류할 수 있습니다. 이번 튜토리얼의 목적은 좀 더 겸손하게, 측정된 꽃받침과 꽃잎의 길이와 폭을 토대로 붓꽃을 분류하는 것입니다.
이 붓꽃은 약 300종입니다. 하지만 이번 튜토리얼에서는 오직 3가지 품종을 기준으로 분류할 것입니다.
Iris setosa
Iris virginica
Iris versicolor
<table>
<tr><td>
<img src="https://www.tensorflow.org/images/iris_three_species.jpg"
alt="Petal geometry compared for three iris species: Iris setosa, Iris virginica, and Iris versicolor">
</td></tr>
<tr><td align="center">
<b>그림 1.</b> <a href="https://commons.wikimedia.org/w/index.php?curid=170298">Iris setosa</a> (by <a href="https://commons.wikimedia.org/wiki/User:Radomil">Radomil</a>, CC BY-SA 3.0), <a href="https://commons.wikimedia.org/w/index.php?curid=248095">Iris versicolor</a>, (by <a href="https://commons.wikimedia.org/wiki/User:Dlanglois">Dlanglois</a>, CC BY-SA 3.0), and <a href="https://www.flickr.com/photos/33397993@N05/3352169862">Iris virginica</a> (by <a href="https://www.flickr.com/photos/33397993@N05">Frank Mayfield</a>, CC BY-SA 2.0).<br/>
</td></tr>
</table>
다행히도 다른 사람들이 먼저 꽃받침과 꽃잎의 길이와 폭이 측정된 120개의 붓꽃 데이터를 만들어 놓았습니다. 이것은 머신러닝 분류 문제에 있어 초보자에게 유명한 고전 데이터셋입니다.
훈련 데이터 가져오기 및 파싱
데이터를 불러오고 파이썬 프로그램이 사용할 수 있는 구조로 전환합니다.
데이터셋 다운로드
tf.keras.utils.get_file 함수를 사용하여 데이터셋을 다운로드합니다. 이 함수는 다운로드된 파일의 경로를 반환합니다.
End of explanation
!head -n5 {train_dataset_fp}
Explanation: 데이터 탐색
이 데이터셋(iris_training.csv)은 콤마 ','로 구분된 CSV 파일입니다. head -n5 명령을 사용하여 처음 5개 항목을 확인합니다.
End of explanation
# CSV 파일안에서 컬럼의 순서
column_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']
feature_names = column_names[:-1]
label_name = column_names[-1]
print("특성: {}".format(feature_names))
print("레이블: {}".format(label_name))
Explanation: 처음 5개의 데이터로부터 다음을 주목하세요.
첫 번째 줄은 다음과 같은 정보를 포함하고 있는 헤더(header)입니다.
총 120개의 샘플이 있으며, 각 샘플들은 4개의 특성(feature), 3개의 레이블(label)을 가지고 있습니다.
후속행은 데이터 레코드입니다. 한 줄당 한가지 샘플입니다.
처음 4개의 필드는 특성입니다.: 이것들은 샘플의 특징을 나타냅니다. 이 필드들는 붓꽃의 측정값을 부동소수점으로 나타냅니다.
마지막 컬럼(column)은 레이블(label)입니다.: 레이블은 예측하고자 하는 값을 나타냅니다. 이 데이터셋에서는 꽃의 이름과 관련된 정수값 0, 1, 2를 나타냅니다.
코드로 표현하면 다음과 같습니다.:
End of explanation
class_names = ['Iris setosa', 'Iris versicolor', 'Iris virginica']
Explanation: 각각의 레이블은 "setosa"와 같은 문자형 이름과 연관되어있습니다. 하지만 머신러닝은 전형적으로 숫자형 값에 의존합니다. 레이블을 다음과 같이 맵핑(mapping) 합니다.
0: Iris setosa
1: Iris versicolor
2: Iris virginica
특성과 레이블에 관한 더 많은 정보를 위해서는 머신러닝 특강의 전문용어 부분을 참조하세요.
End of explanation
batch_size = 32
train_dataset = tf.contrib.data.make_csv_dataset(
train_dataset_fp,
batch_size,
column_names=column_names,
label_name=label_name,
num_epochs=1)
Explanation: tf.data.Dataset 생성
텐서플로의 Dataset API는 데이터를 적재할 때 발생하는 다양한 경우를 다룰 수 있습니다. 이는 훈련에 필요한 형태로 데이터를 읽고 변환하는 고수준 API입니다. 더 많은 정보를 위해서는 데이터셋 빠른 실행 가이드를 참조하세요.
데이터셋이 CSV 파일이므로, 적절한 형태로 데이터를 구분하기위해 make_csv_dataset 함수를 사용하겠습니다. 이 함수는 훈련 모델을 위한 데이터를 생성하므로, 초기값은 셔플(shuffle=True, shuffle_buffer_size=10000)과 무한반복(num_epochs=None)으로 설정되어있습니다. 또한 배치 사이즈(batch_size)를 설정해줍니다.
End of explanation
features, labels = next(iter(train_dataset))
features
Explanation: make_csv_dataset 함수는 (features, label) 쌍으로 구성된 tf.data.Dataset을 반환합니다. features는 딕셔너리 객체인: {'feature_name': value}로 주어집니다.
또한 즉시 실행 활성화로 이 Dataset은 반복가능합니다. 다음은 특성(feature)을 살펴봅시다.
End of explanation
plt.scatter(features['petal_length'].numpy(),
features['sepal_length'].numpy(),
c=labels.numpy(),
cmap='viridis')
plt.xlabel("petal length")
plt.ylabel("sepal length");
Explanation: 유사한 특성의 값은 같이 그룹 되어있거나, 배치 돼있다는 사실에 주목하세요. 각 샘플 행의 필드는 해당 특성 배열에 추가됩니다. batch_size를 조절하여 이 특성 배열에 저장된 샘플의 수를 설정하세요.
또한 배치(batch)로부터 약간의 특성을 도식화하여 군집돼있는 데이터를 확인할 수 있습니다.
End of explanation
def pack_features_vector(features, labels):
Pack the features into a single array.
features = tf.stack(list(features.values()), axis=1)
return features, labels
Explanation: 모델 구축 단계를 단순화하기 위해, 특성 딕셔너리를 (batch_size, num_features)의 형태를 가지는 단일 배열로 다시 구성하는 함수를 생성합니다.
이 함수는 텐서의 리스트(list)로부터 값을 취하고 특정한 차원으로 결합된 텐서를 생성하는 tf.stack 메서드(method)를 사용합니다.
End of explanation
train_dataset = train_dataset.map(pack_features_vector)
Explanation: 그 후 각 (features,label)쌍의 특성을 훈련 데이터셋에 쌓기위해 tf.data.Dataset.map 메서드를 사용합니다.
End of explanation
features, labels = next(iter(train_dataset))
print(features[:5])
Explanation: 데이터셋의 특성 요소는 이제 형태가 (batch_size, num_features)인 배열입니다. 첫 5개행의 샘플을 살펴봅시다.
End of explanation
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(4,)), # input shape required
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(3)
])
Explanation: 모델 타입 선정
왜 모델을 사용해야하는가?
모델은 특성(feature)과 레이블(label) 과의 관계입니다. 붓꽃 분류 문제에서 모델은 측정된 꽃받침과 꽃잎 사이의 관계를 정의하고 붓꽃의 품종을 예측합니다. 몇 가지 간단한 모델은 몇 줄의 대수학으로 표현할 수 있으나, 복잡한 머신러닝 모델은 요약하기 힘든 굉장히 많은 수의 매개변수를 가지고 있습니다.
머신러닝을 사용하지 않고 4가지의 특성 사이의 관계를 결정하고 붓꽃을 품종을 예측하실 수 있으신가요? 즉, 특정 품종의 꽃받침과 꽃잎과의 관계를 정의할 수 있을 정도로 데이터셋을 분석했다면, 전통적인 프로그래밍 기술(예를 들어 굉장히 많은 조건문)을 사용하여 모델은 만들 수 있으신가요? 더 복잡한 데이터셋에서 이는 불가능에 가까울 수 있습니다. 잘 구성된 머신러닝은 사용자를 위한 모델을 결정합니다. 만약 충분히 좋은 샘플을 잘 구성된 머신러닝 모델에 제공한다면, 프로그램은 사용자를 위한 특성 간의 관계를 이해하고 제공합니다.
모델 선정
이제 학습을 위한 모델의 종류를 선정해야합니다. 여러 종류의 모델이 있고, 이를 선택하는 것은 많은 경험이 필요합니다. 이번 튜토리얼에서는 붓꽃 분류 문제를 해결하기위해 신경망(neural network) 모델을 사용하겠습니다. 신경망 모델은 특성과 레이블 사이의 복잡한 관계를 찾을 수 있습니다. 신경망은 하나 또는 그 이상의 은닉층(hidden layer)으로 구성된 그래프입니다. 각각의 은닉층은 하나 이상의 뉴런(neuron)으로 구성되어있습니다. 몇가지 신경망의 범주가 있으며, 이번 튜토리얼에서는 밀집(dense) 또는 완전 연결 신경망(fully-connected neural network)를 사용합니다: 완전 연결 신경망(fully-connected neural network)은 하나의 뉴런에 이전층의 모든 뉴런의 입력을 받는 신경망입니다. 예를 들어, 그림 2는 입력층, 2개의 은닉층, 그리고 출력층으로 구성된 완전 연결 신경망입니다.
<table>
<tr><td>
<img src="https://www.tensorflow.org/images/custom_estimators/full_network.png"
alt="A diagram of the network architecture: Inputs, 2 hidden layers, and outputs">
</td></tr>
<tr><td align="center">
<b>그림 2.</b> A neural network with features, hidden layers, and predictions.<br/>
</td></tr>
</table>
그림 2의 모델이 훈련된 다음 레이블 되어있지 않은 데이터를 제공했을때, 모델은 주어진 데이터의 3가지(주어진 레이블의 개수) 예측을 출력합니다. 이러한 예측은 추론(inference)이라고 불립니다. 이 샘플에서 출력의 합은 1.0입니다. 그림 2에서 예측은 Iris setosa 0.02, Iris versicolor 0.95, Iris virginica에 0.03로 주어집니다. 이는 모델이 95%의 확률로 주어진 데이터를 Iris versicolor로 예측한다는 것을 의미합니다.
케라스를 사용한 모델 생성
텐서플로의 tf.keras API는 모델과 층을 생성하기 위한 풍부한 라이브러리를 제공합니다. 케라스가 구성 요소를 연결하기 위한 복잡함을 모두 처리해 주기 때문에 모델을 구축하고 실험하는 것이 쉽습니다.
tf.keras.Sequential은 여러 층을 연이어 쌓은 모델입니다. 이 구조는 층의 인스턴스를 취하며, 아래의 경우 각 층당 10개의 노드(node)를 가지는 2개의 Dense(완전 연결 층)과 3개의 예측(레이블의 수) 노드를 가지는 출력 층으로 구성되어있습니다. 첫 번째 층의 input_shape 매개변수는 데이터셋의 특성의 수와 관계있습니다.
End of explanation
predictions = model(features)
predictions[:5]
Explanation: 활성화 함수(activation function)는 각 층에서 출력의 크기를 결정합니다. 이러한 비선형성은 중요하며, 활성화 함수가 없는 모델은 하나의 층과 동일하다고 생각할 수 있습니다. 사용 가능한 활성화 함수는 많지만, ReLU가 은닉층에 주로 사용됩니다.
이상적인 은닉층과 뉴런의 개수는 문제와 데이터셋에 의해 좌우됩니다. 머신러닝의 여러 측면과 마찬가지로, 최적의 신경망 타입을 결정하는 것은 많은 경험과 지식이 필요합니다. 경험을 토대로 보면 은닉층과 뉴런의 증가는 전형적으로 강력한 모델을 생성하므로, 모델을 효과적으로 훈련시키기 위해서 더 많은 데이터를 필요로 합니다.
모델 사용
이 모델이 특성의 배치에 대해 수행하는 작업을 간단히 살펴봅시다.
End of explanation
tf.nn.softmax(predictions[:5])
Explanation: 각 샘플은 각 클래스에 대한 로짓(logit)을 반환합니다.
이 로짓(logit)을 각 클래스에 대한 확률로 변환하기 위하서 소프트맥스(softmax) 함수를 사용하겠습니다.
End of explanation
print("예측: {}".format(tf.argmax(predictions, axis=1)))
print(" 레이블: {}".format(labels))
Explanation: tf.argmax는 예측된 값 중 가장 큰 확률(원하는 클래스)을 반환합니다. 하지만 모델이 아직 훈련되지 않았으므로 이는 좋은 예측이 아닙니다.
End of explanation
def loss(model, x, y):
y_ = model(x)
return tf.losses.sparse_softmax_cross_entropy(labels=y, logits=y_)
l = loss(model, features, labels)
print("손실 테스트: {}".format(l))
Explanation: 모델 훈련하기
훈련 단계는 모델이 점진적으로 최적화되거나 데이터셋을 학습하는 머신러닝의 과정입니다. 훈련의 목적은 미지의 데이터를 예측하기 위해, 훈련 데이터셋의 구조에 대해서 충분히 학습하는 것입니다. 만약 모델이 훈련 데이터셋에 대해서 과하게 학습된다면 오직 훈련 데이터셋에 대해서 작동할 것이며, 일반화되기 힘들 것입니다. 이러한 문제를 과대적합(overfitting) 이라고 합니다. 이는 마치 문제를 이해하고 해결한다기보다는 답을 기억하는 것이라고 생각할 수 있습니다.
붓꽃 분류 문제는 지도 학습(supervised machine learning)의 예시 중 하나입니다.: 지도학습은 모델이 레이블을 포함한 훈련 데이터로부터 학습됩니다. 비지도 학습(unsupervised machine learning)에서는 훈련 데이터가 레이블을 포함하고 있지 않습니다. 대신에 모델은 특성 간의 패턴을 찾습니다.
손실 함수와 그래디언트 함수 정의하기
훈련과 평가단계에서 모델의 손실(loss)을 계산해야 합니다. 손실은 모델의 예측이 원하는 레이블과 얼마나 일치하는지, 또한 모델이 잘 작동하는지에 대한 척도로 사용됩니다. 이 값을 최소화하고, 최적화 해야합니다.
모델의 손실은 tf.keras.losses.categorical_crossentropy 함수를 사용해 계산할 것입니다. 이 함수는 모델의 클래스(레이블)과 예측된 값(로짓)을 입력받아 샘플의 평균 손실을 반환합니다.
End of explanation
def grad(model, inputs, targets):
with tf.GradientTape() as tape:
loss_value = loss(model, inputs, targets)
return loss_value, tape.gradient(loss_value, model.trainable_variables)
Explanation: 모델을 최적화하기 위해 사용되는 그래디언트(gradient)를 계산하기 위해 tf.GradientTape 컨텍스트를 사용합니다. 더 자세한 정보는 즉시 실행 가이드를 확인하세요.
End of explanation
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
global_step = tf.contrib.eager.Variable(0)
Explanation: 옵티마이저 생성
옵티마이저(optimizer)는 손실 함수를 최소화하기 위해 계산된 그래디언트를 모델의 변수에 적용합니다. 손실 함수를 구부러진 곡선의 표면(그림 3)으로 생각할 수 있으며, 이 함수의 최저점을 찾고자 합니다. 그래디언트는 가장 가파른 상승 방향을 가리키며 따라서 반대 방향으로 이동하는 여행을 합니다. 각 배치마다의 손실과 기울기를 반복적으로 계산하여 훈련과정 동안 모델을 조정합니다. 점진적으로, 모델은 손실을 최소화하기 위해 가중치(weight)와 편향(bias)의 최적의 조합을 찾아냅니다. 손실이 낮을수록 더 좋은 모델의 예측을 기대할 수 있습니다.
<table>
<tr><td>
<img src="https://cs231n.github.io/assets/nn3/opt1.gif" width="70%"
alt="Optimization algorithms visualized over time in 3D space.">
</td></tr>
<tr><td align="center">
<b> 그림 3.</b> 3차원 공간에 대한 최적화 알고리즘 시각화.<br/>(Source: <a href="http://cs231n.github.io/neural-networks-3/">Stanford class CS231n</a>, MIT License, Image credit: <a href="https://twitter.com/alecrad">Alec Radford</a>)
</td></tr>
</table>
텐서플로는 훈련을 위해 사용 가능한 여러종류의 최적화 알고리즘을 가지고 있습니다. 이번 모델에서는 확률적 경사 하강법(stochastic gradient descent, SGD) 을 구현한 tf.train.GradientDescentOptimizer를 사용하겠습니다. learning_rate은 경사하강 과정의 크기를 나타내는 매개변수이며, 더 나은 결과를 위해 조절가능한 하이퍼파라미터(hyperparameter) 입니다.
옵티마이저(optimizer)와 global_step을 설정합니다.
End of explanation
loss_value, grads = grad(model, features, labels)
print("단계: {}, 초기 손실: {}".format(global_step.numpy(),
loss_value.numpy()))
optimizer.apply_gradients(zip(grads, model.trainable_variables), global_step)
print("단계: {}, 손실: {}".format(global_step.numpy(),
loss(model, features, labels).numpy()))
Explanation: 이 값들을 단일 최적화 단계를 계산하기 위해 사용합니다.
End of explanation
## Note: 이 셀을 다시 실행하면 동일한 모델의 변수가 사용됩니다.
from tensorflow import contrib
tfe = contrib.eager
# 도식화를 위해 결과를 저장합니다.
train_loss_results = []
train_accuracy_results = []
num_epochs = 201
for epoch in range(num_epochs):
epoch_loss_avg = tfe.metrics.Mean()
epoch_accuracy = tfe.metrics.Accuracy()
# 훈련 루프 - 32개의 배치를 사용합니다.
for x, y in train_dataset:
# 모델을 최적화합니다.
loss_value, grads = grad(model, x, y)
optimizer.apply_gradients(zip(grads, model.trainable_variables),
global_step)
# 진행 상황을 추적합니다.
epoch_loss_avg(loss_value) # 현재 배치 손실을 추가합니다.
# 예측된 레이블과 실제 레이블 비교합니다.
epoch_accuracy(tf.argmax(model(x), axis=1, output_type=tf.int32), y)
# epoch 종료
train_loss_results.append(epoch_loss_avg.result())
train_accuracy_results.append(epoch_accuracy.result())
if epoch % 50 == 0:
print("에포크 {:03d}: 손실: {:.3f}, 정확도: {:.3%}".format(epoch,
epoch_loss_avg.result(),
epoch_accuracy.result()))
Explanation: 훈련 루프
모든 사항이 갖춰졌으므로 모델을 훈련할 준비가 되었습니다! 훈련 루프는 더 좋은 예측을 위해 데이터셋을 모델로 제공합니다. 다음의 코드 블럭은 아래의 훈련 단계를 작성한 것입니다.
각 에포크(epoch) 반복. 에포크는 데이터셋을 통과시키는 횟수입니다.
에포크 내에서, 특성 (x)와 레이블 (y)가 포함된 훈련 데이터셋에 있는 샘플을 반복합니다.
샘플의 특성을 사용하여 결과를 예측 하고 레이블과 비교합니다. 예측의 부정확도를 측정하고 모델의 손실과 그래디언트를 계산하기 위해 사용합니다.
모델의 변수를 업데이트하기 위해 옵티마이저를 사용합니다.
시각화를 위해 몇가지 값들을 저장합니다.
각 에포크를 반복합니다.
num_epochs 변수는 데이터셋의 반복 횟수입니다. 직관과는 반대로, 모델을 길게 학습하는 것이 더 나은 모델이 될 것이라고 보장하지 못합니다. num_epochs는 조정가능한 하이퍼파라미터(hyperparameter) 입니다. 적절한 횟수를 선택하는 것은 많은 경험과 직관을 필요로 합니다.
End of explanation
fig, axes = plt.subplots(2, sharex=True, figsize=(12, 8))
fig.suptitle('Training Metrics')
axes[0].set_ylabel("loss", fontsize=14)
axes[0].plot(train_loss_results)
axes[1].set_ylabel("Accuracy", fontsize=14)
axes[1].set_xlabel("epoch", fontsize=14)
axes[1].plot(train_accuracy_results);
Explanation: 시간에 따른 손실함수 시각화
모델의 훈련 과정을 출력하는 것도 도움이 되지만, 훈련 과정을 직접 보는 것이 더 도움이 되곤합니다. 텐서보드(tensorboard)는 텐서플로에 패키지 되어있는 굉장히 유용한 시각화 툴입니다. 하지만 matplotlib 모듈을 사용하여 일반적인 도표를 출력할 수 있습니다.
이 도표를 해석하는 것은 여러 경험이 필요하지만, 결국 모델을 최적화하기 위해 손실이 내려가고 정확도가 올라가는 것을 원합니다.
End of explanation
test_url = "https://storage.googleapis.com/download.tensorflow.org/data/iris_test.csv"
test_fp = tf.keras.utils.get_file(fname=os.path.basename(test_url),
origin=test_url)
test_dataset = tf.contrib.data.make_csv_dataset(
test_fp,
batch_size,
column_names=column_names,
label_name='species',
num_epochs=1,
shuffle=False)
test_dataset = test_dataset.map(pack_features_vector)
Explanation: 모델 유효성 평가
이제 모델은 훈련되었습니다. 모델의 성능에 대한 몇가지 통계를 얻을 수 있습니다.
평가(Evaluating)는 모델이 예측을 얼마나 효과적으로 수행하는지 결정하는 것을 의미합니다. 붓꽃 분류 모델의 유효성을 결정하기 위해, 몇가지 꽃잎과 꽃받침 데이터를 통과시키고 어떠한 품종을 예측하는지 확인합니다. 그 후 실제 품종과 비교합니다. 예를 들어, 절반의 데이터를 올바르게 예측한 모델의 정확도 는 0.5입니다. 그림 4는 조금 더 효과적인 모델입니다. 5개의 예측 중 4개를 올바르게 예측하여 80% 정확도를 냅니다.
<table cellpadding="8" border="0">
<colgroup>
<col span="4" >
<col span="1" bgcolor="lightblue">
<col span="1" bgcolor="lightgreen">
</colgroup>
<tr bgcolor="lightgray">
<th colspan="4">샘플 특성</th>
<th colspan="1">레이블</th>
<th colspan="1" >모델 예측</th>
</tr>
<tr>
<td>5.9</td><td>3.0</td><td>4.3</td><td>1.5</td><td align="center">1</td><td align="center">1</td>
</tr>
<tr>
<td>6.9</td><td>3.1</td><td>5.4</td><td>2.1</td><td align="center">2</td><td align="center">2</td>
</tr>
<tr>
<td>5.1</td><td>3.3</td><td>1.7</td><td>0.5</td><td align="center">0</td><td align="center">0</td>
</tr>
<tr>
<td>6.0</td> <td>3.4</td> <td>4.5</td> <td>1.6</td> <td align="center">1</td><td align="center" bgcolor="red">2</td>
</tr>
<tr>
<td>5.5</td><td>2.5</td><td>4.0</td><td>1.3</td><td align="center">1</td><td align="center">1</td>
</tr>
<tr><td align="center" colspan="6">
<b>그림 4.</b> 80% 정확도 붓꽃 분류기.<br/>
</td></tr>
</table>
테스트 데이터 세트 설정
모델을 평가하는 것은 모델을 훈련하는 것과 유사합니다. 가장 큰 차이는 훈련 데이터가 아닌 테스트 데이터 세트 를 사용했다는 것입니다. 공정하게 모델의 유효성을 평가하기 위해, 모델을 평가하기 위한 샘플은 반드시 훈련 데이터와 달라야합니다.
테스트 데이터 세트를 설정하는 것은 훈련 데이터 세트를 설정하는 것과 유사합니다. CSV 파일을 다운로드하고 값을 파싱합니다. 그 후 셔플은 적용하지 않습니다.
End of explanation
test_accuracy = tfe.metrics.Accuracy()
for (x, y) in test_dataset:
logits = model(x)
prediction = tf.argmax(logits, axis=1, output_type=tf.int32)
test_accuracy(prediction, y)
print("테스트 세트 정확도: {:.3%}".format(test_accuracy.result()))
Explanation: 테스트 데이터 세트를 사용한 모델 평가
훈련 단계와는 다르게 모델은 테스트 데이터에 대해서 오직 한 번의 에포크를 진행합니다. 다음의 코드 셀은 테스트 셋에 있는 샘플에 대해 실행하고 실제 레이블과 비교합니다. 이는 전체 테스트 데이터 세트에 대한 정확도를 측정하는데 사용됩니다.
End of explanation
tf.stack([y,prediction],axis=1)
Explanation: 마지막 배치에서 모델이 올바르게 예측한 것을 확인할 수 있습니다.
End of explanation
predict_dataset = tf.convert_to_tensor([
[5.1, 3.3, 1.7, 0.5,],
[5.9, 3.0, 4.2, 1.5,],
[6.9, 3.1, 5.4, 2.1]
])
predictions = model(predict_dataset)
for i, logits in enumerate(predictions):
class_idx = tf.argmax(logits).numpy()
p = tf.nn.softmax(logits)[class_idx]
name = class_names[class_idx]
print("예 {} 예측: {} ({:4.1f}%)".format(i, name, 100*p))
Explanation: 훈련된 모델로 예측하기
이제 붓꽃을 분류하기 위해 완벽하지는 않지만 어느 정도 검증된 모델을 가지고 있습니다. 훈련된 모델을 사용하여 레이블 되지 않은 데이터를 예측해봅시다.
실제로는 레이블 되지 않은 샘플들은 여러 소스(앱, CSV 파일, 직접 제공 등)로부터 제공될 수 있습니다. 지금은 레이블을 예측하기 위해 수동으로 3개의 레이블 되지 않은 샘플을 제공하겠습니다. 레이블은 다음과 같은 붓꽃 이름으로 매핑되어있습니다.
* 0: Iris setosa
* 1: Iris versicolor
* 2: Iris virginica
End of explanation |
8,509 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 3
Step1: Predicting consumption expeditures
The parameters needed to produce the plots are as follows
Step2: Panel B
Step3: Panel C
Step4: Panel D | Python Code:
from fig_utils import *
import matplotlib.pyplot as plt
import time
%matplotlib inline
Explanation: Figure 3: Cluster-level consumptions
This notebook generates individual panels of Figure 3 in "Combining satellite imagery and machine learning to predict poverty".
End of explanation
# Plot parameters
country = 'nigeria'
country_path = '../data/LSMS/nigeria/'
dimension = None
k = 5
k_inner = 5
points = 10
alpha_low = 1
alpha_high = 5
margin = 0.25
# Plot single panel
t0 = time.time()
X, y, y_hat, r_squareds_test = predict_consumption(country, country_path,
dimension, k, k_inner, points, alpha_low,
alpha_high, margin)
t1 = time.time()
print 'Finished in {} seconds'.format(t1-t0)
Explanation: Predicting consumption expeditures
The parameters needed to produce the plots are as follows:
country: Name of country being evaluated as a lower-case string
country_path: Path of directory containing LSMS data corresponding to the specified country
dimension: Number of dimensions to reduce image features to using PCA. Defaults to None, which represents no dimensionality reduction.
k: Number of cross validation folds
k_inner: Number of inner cross validation folds for selection of regularization parameter
points: Number of regularization parameters to try
alpha_low: Log of smallest regularization parameter to try
alpha_high: Log of largest regularization parameter to try
margin: Adjusts margins of output plot
The data directory should contain the following 5 files for each country:
conv_features.npy: (n, 4096) array containing image features corresponding to n clusters
consumptions.npy: (n,) vector containing average cluster consumption expenditures
nightlights.npy: (n,) vector containing the average nightlights value for each cluster
households.npy: (n,) vector containing the number of households for each cluster
image_counts.npy: (n,) vector containing the number of images available for each cluster
Exact results may differ slightly with each run due to randomly splitting data into training and test sets.
Panel A
End of explanation
# Plot parameters
country = 'tanzania'
country_path = '../data/LSMS/tanzania/'
dimension = None
k = 5
k_inner = 5
points = 10
alpha_low = 1
alpha_high = 5
margin = 0.25
# Plot single panel
t0 = time.time()
X, y, y_hat, r_squareds_test = predict_consumption(country, country_path,
dimension, k, k_inner, points, alpha_low,
alpha_high, margin)
t1 = time.time()
print 'Finished in {} seconds'.format(t1-t0)
Explanation: Panel B
End of explanation
# Plot parameters
country = 'uganda'
country_path = '../data/LSMS/uganda/'
dimension = None
k = 5
k_inner = 5
points = 10
alpha_low = 1
alpha_high = 5
margin = 0.25
# Plot single panel
t0 = time.time()
X, y, y_hat, r_squareds_test = predict_consumption(country, country_path,
dimension, k, k_inner, points, alpha_low,
alpha_high, margin)
t1 = time.time()
print 'Finished in {} seconds'.format(t1-t0)
Explanation: Panel C
End of explanation
# Plot parameters
country = 'malawi'
country_path = '../data/LSMS/malawi/'
dimension = None
k = 5
k_inner = 5
points = 10
alpha_low = 1
alpha_high = 5
margin = 0.25
# Plot single panel
t0 = time.time()
X, y, y_hat, r_squareds_test = predict_consumption(country, country_path,
dimension, k, k_inner, points, alpha_low,
alpha_high, margin)
t1 = time.time()
print 'Finished in {} seconds'.format(t1-t0)
Explanation: Panel D
End of explanation |
8,510 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning with H2O - Tutorial 2
Step1: <br>
Step2: <br>
Explain why we need to transform
<br>
Step3: <br>
Doing the same for 'Pclass'
<br> | Python Code:
# Start and connect to a local H2O cluster
import h2o
h2o.init(nthreads = -1)
Explanation: Machine Learning with H2O - Tutorial 2: Basic Data Manipulation
<hr>
Objective:
This tutorial demonstrates basic data manipulation with H2O.
<hr>
Titanic Dataset:
Source: https://www.kaggle.com/c/titanic/data
<hr>
Full Technical Reference:
http://docs.h2o.ai/h2o/latest-stable/h2o-py/docs/frame.html
<br>
End of explanation
# Import Titanic data (local CSV)
titanic = h2o.import_file("kaggle_titanic.csv")
# Explore the dataset using various functions
titanic.head(10)
Explanation: <br>
End of explanation
# Explore the column 'Survived'
titanic['Survived'].summary()
# Use hist() to create a histogram
titanic['Survived'].hist()
# Use table() to summarize 0s and 1s
titanic['Survived'].table()
# Convert 'Survived' to categorical variable
titanic['Survived'] = titanic['Survived'].asfactor()
# Look at the summary of 'Survived' again
# The feature is now an 'enum' (enum is the name of categorical variable in Java)
titanic['Survived'].summary()
Explanation: <br>
Explain why we need to transform
<br>
End of explanation
# Explore the column 'Pclass'
titanic['Pclass'].summary()
# Use hist() to create a histogram
titanic['Pclass'].hist()
# Use table() to summarize 1s, 2s and 3s
titanic['Pclass'].table()
# Convert 'Pclass' to categorical variable
titanic['Pclass'] = titanic['Pclass'].asfactor()
# Explore the column 'Pclass' again
titanic['Pclass'].summary()
Explanation: <br>
Doing the same for 'Pclass'
<br>
End of explanation |
8,511 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
観測されたデータ。N(5,1)から作られた10個の乱数。
Step1: [ベイズ推論]</P>
<p>確率変数$X_1, X_2,..., X_n$が互いに独立に平均がμ、分散が1であるような正規分布に従うとする。</p>
<p>μの事前分布にt分布を仮定する。
<P>1 初期値μ^(0)を決め、t=1とおく。</p>
<p>2 現在μ^(t-1)であるとき、次の点μ^tの候補μ'を$μ'$~ $N(μ^{(t-1)}, r^2)$により発生させて、$$ α(μ^{(t-1)}, μ'|x) = min \{ 1, \frac{π(μ')}{π(μ^{(t-1)})}\}$$とおく。</p>
<p>3 (0, 1)上の一様乱数uを発生させて、$$μ^{(t)}=μ' if u≤α(μ^{(t-1)}, μ'|x)のとき$$ $$μ^{(t)}=u^{(t-1)} if μ^{(t-1)}>α(μ^{(t-1)}, μ'|x)のとき$$とする。</p>
<p>4 tをt+1として2にもどる。
事前分布に自由度5のt分布を仮定する。r^2=0.001とする。
Step2: $\mu$の事前分布に無情報事前分布を仮定する。 | Python Code:
X = np.zeros(10)
for i in range(len(X)):
X[i] = np.random.normal(5,1)
X
Explanation: 観測されたデータ。N(5,1)から作られた10個の乱数。
End of explanation
class RWMH:
def __init__(self, X):
self.mu = 2
self.freedom = 5.0
self.x_var = np.mean(X)
def prior_dist(self, t):
ft = math.gamma((self.freedom+1.0)/2.0)/(math.sqrt(self.freedom*math.pi)*math.gamma((self.freedom)/2.0))*pow(1+pow(t, 2)/self.freedom, -(self.freedom+1)/2.0)
return ft
def prop_dist(self):
self.mu = np.random.normal(self.mu, 0.5)
return self.mu
def accept(self, mu_new, mu):
return min([1, self.prior_dist(mu_new)/self.prior_dist(mu)])
def simulate(self):
mu = np.zeros(110000)
mu[0] = self.mu
for i in range(1,110000):
mu_new = self.prop_dist()
u = np.random.uniform()
if u <= self.accept(mu_new, mu[i-1]):
mu[i] = mu_new
else:
mu[i] = mu[i-1]
self.mu = mu[i]
return mu
rwmh = RWMH(X)
mu = rwmh.simulate()
plt.plot(mu)
plt.hist(mu)
plt.hist(mu[10000:])
mu.mean()
Explanation: [ベイズ推論]</P>
<p>確率変数$X_1, X_2,..., X_n$が互いに独立に平均がμ、分散が1であるような正規分布に従うとする。</p>
<p>μの事前分布にt分布を仮定する。
<P>1 初期値μ^(0)を決め、t=1とおく。</p>
<p>2 現在μ^(t-1)であるとき、次の点μ^tの候補μ'を$μ'$~ $N(μ^{(t-1)}, r^2)$により発生させて、$$ α(μ^{(t-1)}, μ'|x) = min \{ 1, \frac{π(μ')}{π(μ^{(t-1)})}\}$$とおく。</p>
<p>3 (0, 1)上の一様乱数uを発生させて、$$μ^{(t)}=μ' if u≤α(μ^{(t-1)}, μ'|x)のとき$$ $$μ^{(t)}=u^{(t-1)} if μ^{(t-1)}>α(μ^{(t-1)}, μ'|x)のとき$$とする。</p>
<p>4 tをt+1として2にもどる。
事前分布に自由度5のt分布を仮定する。r^2=0.001とする。
End of explanation
class RWMH:
def __init__(self, X):
self.mu = 5
self.x_var = np.mean(X)
def prior_dist(self, t):
ft = np.random.normal(0, 10000)
return ft
def prop_dist(self):
self.mu = np.random.normal(self.mu, 0.001)
return self.mu
def accept(self, mu_new, mu):
return min([1, self.prior_dist(mu_new)/self.prior_dist(mu)])
def simulate(self):
mu = np.zeros(11000)
mu[0] = self.mu
for i in range(1,11000):
mu_new = self.prop_dist()
u = np.random.uniform()
if u <= self.accept(mu_new, mu[i-1]):
mu[i] = mu_new
else:
mu[i] = mu[i-1]
self.mu = mu[i]
return mu
rwmh = RWMH(X)
mu = rwmh.simulate()
plt.plot(mu)
plt.hist(mu)
plt.hist(mu[1000:])
Explanation: $\mu$の事前分布に無情報事前分布を仮定する。
End of explanation |
8,512 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
Positional Astronomy
Previous
Step1: Import section specific modules
Step2: 3.4 Direction Cosine Coordinates ($l$,$m$,$n$)
There is another useful astronomical coordinate system that we ought to introduce at this juncture, namely the direction cosine coordinate system. The direction cosine coordinate system is quite powerful and allows us to redefine the fundamental reference point on the celestial sphere, from which we measure all other celestial objects, to an arbitrary location (i.e. we can make local sky-maps around our own chosen reference point; the vernal equinox need not be our fundamental reference point). Usually this arbitrary location is chosen to be the celestial source that we are interested in observing. We generally refer to this arbitrary location as the field centre or phase centre.
<div class=advice>
<b>Note
Step3: Recall that we can use Eq. 3.1 ⤵ <!--\label{pos
Step4: Plotting the result. | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
Explanation: Outline
Glossary
Positional Astronomy
Previous: 3.3 Horizontal Coordinates (ALT/AZ)
Next: 3.x Further Reading and References
Import standard modules:
End of explanation
from IPython.display import HTML
HTML('../style/code_toggle.html')
Explanation: Import section specific modules:
End of explanation
RA_rad = (np.pi/12) * np.array([5. + 30./60, 5 + 32./60 + 0.4/3600, 5 + 36./60 + 12.8/3600, 5 + 40./60 + 45.5/3600])
DEC_rad = (np.pi/180)*np.array([60., 60. + 17.0/60 + 57./3600, 61. + 12./60 + 6.9/3600, 61 + 56./60 + 34./3600])
Flux_sources_labels = np.array(["", "1 Jy", "0.5 Jy", "0.2 Jy"])
Flux_sources = np.array([1., 0.5, 0.1]) #in Janskys
print "RA (rad) of Sources and Field Center = ", RA_rad
print "DEC (rad) of Sources = ", DEC_rad
Explanation: 3.4 Direction Cosine Coordinates ($l$,$m$,$n$)
There is another useful astronomical coordinate system that we ought to introduce at this juncture, namely the direction cosine coordinate system. The direction cosine coordinate system is quite powerful and allows us to redefine the fundamental reference point on the celestial sphere, from which we measure all other celestial objects, to an arbitrary location (i.e. we can make local sky-maps around our own chosen reference point; the vernal equinox need not be our fundamental reference point). Usually this arbitrary location is chosen to be the celestial source that we are interested in observing. We generally refer to this arbitrary location as the field centre or phase centre.
<div class=advice>
<b>Note:</b> The direction cosine coordinate system is useful for another reason, when we use
it to image interferometric data, then it becomes evident that there exists a Fourier relationship between the sky brightness function and the measurements that an interferometer makes (see <a href='../4_Visibility_Space/4_0_introduction.ipynb'>Chapter 4 ➞</a>).
</div>
<br>
We use three coordinates in the direction cosine coordinate system, namely $l$, $m$ and $n$. The coordinates $l$, $m$ and $n$ are dimensionless direction cosines, i.e.
\begin{eqnarray}
l &=& \cos(\alpha) = \frac{a_1}{|\mathbf{a}|}\
m &=& \cos(\beta) = \frac{a_2}{|\mathbf{a}|}\
n &=& \cos(\gamma) = \frac{a_3}{|\mathbf{a}|}
\end{eqnarray}
<a id='pos:fig:cosines'></a> <!--\label{pos:fig:cosines}--><img src='figures/cosine.svg' width=35%>
Figure 3.4.1: Definition of direction cosines.
The quantities $\alpha$, $\beta$, $\gamma$, $a_1$, $a_2$, $a_3$ and $\mathbf{a}$ are all defined in Fig. 3.4.1 ⤵<!--\ref{pos:fig:cosines}-->. Moreover, $|\cdot|$ denotes the magnitude of its operand. The definitions above also imply that $l^2+m^2+n^2 = 1$. When $|\mathbf{a}|=1$ then we may simply interpret $l$, $m$ and $n$ as Cartesian coordinates, i.e. we may simply relabel the axes $x$, $y$ and $z$ (in Fig. 3.4.1 ⤵<!--\ref{pos:fig:cosines}-->) to
$l$, $m$ and $n$.
So the question now arises, how do we use $l$, $m$ and $n$ to uniquely identify a location on the celestial sphere? The direction cosine coordinate system (and the relationship between it and the celestial coordinate sytem) is depicted in Fig 3.4.2 ⤵<!--\ref{pos:fig:convert_lmn_ra_dec}-->. Note that the $n$-axis points toward the field center (which is denoted by $\boldsymbol{s}_c$ in Fig 3.4.2 ⤵<!--\ref{pos:fig:convert_lmn_ra_dec}-->). It should be clear from Fig 3.4.2 ⤵<!--\ref{pos:fig:convert_lmn_ra_dec}--> that we can use $\mathbf{s} = (l,m,n)$ to uniquely idnetify any location on the celestial sphere.
<a id='pos:fig:convert_lmn_ra_dec'></a> <!--\label{pos:fig:convert_lmn_ra_dec}--><img src='figures/conversion2.svg' width=40%>
Figure 3.4.2: The source-celestial pole-field center triangle; which enables us to derive the conversion equations between direction cosine and equatorial coordinates. The red plane represents the fundamental plane of the equatorial coordinate system, while the blue plane represents the fundamental plane of the direction cosine coordinate system. We are able to label the orthogonal fundamental axes of the direction cosine coordinate system $l$,$m$ and $n$, since the radius of the celestial sphere is equal to one.
We use the following equations to convert between the equatorial and direction cosine coordinate systems:
<a id='pos:eq:convert_lmn_ra_dec'></a> <!--\label{pos:eq:convert_lmn_ra_dec}-->
<p class=conclusion>
<font size=4><b>Converting between the equatorial and direction cosine coordinates (3.1)</b></font>
<br>
<br>
\begin{eqnarray}
l &=& \sin \theta \sin \psi = \cos \delta \sin \Delta \alpha \nonumber\\
m &=& \sin \theta \cos \psi = \sin \delta \cos \delta_0 - \cos \delta \sin \delta_0 \cos\Delta \alpha \nonumber\\
\delta &=& \sin^{-1}(m\cos \delta_0 + \sin \delta_0\sqrt{1-l^2-m^2})\nonumber\\
\alpha &=& \alpha_0 + \tan^{-1}\bigg(\frac{l}{\cos\delta_0\sqrt{1-l^2-m^2}-m\sin\delta_0}\bigg)\nonumber
\end{eqnarray}
</p>
<div class=advice>
<b>Note:</b> See <a href='../0_Introduction/2_Appendix.ipynb'>Appendix ➞</a> for the derivation of the above relations.
</div>
We can obtain the conversion relations above by applying the spherical trigonemetric identities in <a href='../2_Mathematical_Groundwork/2_13_spherical_trigonometry.ipynb'>$\S$ 2.13 ➞</a> to the triangle depicted in Fig. Fig 3.4.2 ⤵ <!--\ref{pos:fig:convert_lmn_ra_dec}--> (the one formed by the source the field center and the NCP).
There is another important interpretation of direction cosine coordinates we should
be cognisant of. If we project the direction cosine position vector $\mathbf{s}$ of a celestial body onto the $lm$-plane it's projected length will be equal to $\sin \theta$, where $\theta$ is the angular distance between your field center $\mathbf{s}_c$ and $\mathbf{s}$ measured along the surface of the celestial sphere. If $\theta$ is small we may use the small angle approximation, i.e. $\sin \theta \approx \theta$. The projected length of $\mathbf{s}$ is also equal to $\sqrt{l^2+m^2}$, implying that $l^2+m^2 \approx \theta^2$. We may therefore loosely interpret $\sqrt{l^2+m^2}$ as the angular distance measured between the source at $\mathbf{s}$ and the field-center $\mathbf{s}_c$ measured along the surface of the celestial sphere, i.e. we may measure $l$ and $m$ in $^{\circ}$.
The explenation above is graphically illustrated in Figure 3.4.3 ⤵ <!--\ref{pos:fig:understand_lm}-->.
<a id='pos:fig:understand_lm'></a> <!--\label{pos:fig:understand_lm}--><img src='figures/conversion2b.svg' width=40%>
Figure 3.4.3: Why do we measure $l$ and $m$ in degrees?
<p class=conclusion>
<font size=4><b>Three interpretations of direction cosine coordinates</b></font>
<br>
<br>
• **Direction cosines**: $l$,$m$ and $n$ are direction cosines<br><br>
• **Cartesian coordinates**: $l$,$m$ and $n$ are Cartesian coordinates if we work on the
unit sphere<br><br>
• <b>Angular distance</b>: $\sqrt{l^2+m^2}$ denotes the angular distance $\theta$, $(l,m,n)$ is from the field center (if $\theta$ is sufficiently small).
</p>
3.4.1 Example
Here we have a couple of sources given in RA ($\alpha$) and DEC ($\delta$):
* Source 1: (5h 32m 0.4s,60$^{\circ}$17' 57'') - 1Jy
* Source 2: (5h 36m 12.8s,61$^{\circ}$ 12' 6.9'') - 0.5Jy
* Source 3: (5h 40m 45.5s,61$^{\circ}$ 56' 34'') - 0.2Jy
The field center is located at $(\alpha_0,\delta_0) = $ (5h 30m,60$^{\circ}$). The first step is to convert right ascension and declination into radians with
\begin{eqnarray}
\alpha_{\textrm{rad}} &=& \frac{\pi}{12} \bigg(h + \frac{m}{60} + \frac{s}{3600}\bigg)\
\delta_{\textrm{rad}} &=& \frac{\pi}{180} \bigg(d + \frac{m_{\textrm{arcmin}}}{60}+\frac{s_{\textrm{arcsec}}}{3600}\bigg)
\end{eqnarray}
In the above equations $h,~m,~s,~d,~m_{\textrm{arcmin}}$ and $s_{\textrm{arcsec}}$ respectively denote hours, minutes, seconds, degrees, arcminutes and arcseconds. If we apply the above to our three sources we obtain
End of explanation
RA_delta_rad = RA_rad-RA_rad[0] #calculating delta alpha
l = np.cos(DEC_rad) * np.sin(RA_delta_rad)
m = (np.sin(DEC_rad) * np.cos(DEC_rad[0]) - np.cos(DEC_rad) * np.sin(DEC_rad[0]) * np.cos(RA_delta_rad))
print "l (degrees) = ", l*(180./np.pi)
print "m (degrees) = ", m*(180./np.pi)
Explanation: Recall that we can use Eq. 3.1 ⤵ <!--\label{pos:eq:convert_lmn_ra_dec}--> to convert between equatorial
and direction cosine coordinates, in terms of the current example this translates into the python code below. Note that before we can do the conversion we first need to calculate $\Delta \alpha$.
End of explanation
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim([-4., 4.])
plt.ylim([-4., 4.])
plt.xlabel("$l$ [degrees]")
plt.ylabel("$m$ [degrees]")
plt.plot(l[0], m[0], "bx")
plt.hold("on")
plt.plot(l[1:]*(180/np.pi), m[1:]*(180/np.pi), "ro")
counter = 1
for xy in zip(l[1:]*(180/np.pi)+0.25, m[1:]*(180/np.pi)+0.25):
ax.annotate(Flux_sources_labels[counter], xy=xy, textcoords='offset points',horizontalalignment='right',
verticalalignment='bottom')
counter = counter + 1
plt.grid()
Explanation: Plotting the result.
End of explanation |
8,513 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Radial Wavefunctions and Quantum Defects
In this tutorial we show how to access quantum defects and wavefunctions, which are used for the computation of matrix elements, using the Python API. Some aspects of this are discussed in Appendix A of the pairinteraction paper J. Phys. B
Step1: Our code starts with loading the required modules for the computation. It is irrelevant whether we use the pireal or picomplex modules here, because we do not calculate any matrix elements.
Step2: Keep in mind that pairinteraction is a Rydberg interaction calculator. All techniques presented below work well for the high-$n$ states of Rydberg atoms, but fail miserably for low-lying states.
While the pairinteraction software normally uses the unit system described in the introduction, for the wavefunction it has proven advantageous to perform the calculation in atomic units, i.e. all units below are atomic units (in contrast to the presentation in Appendix A of the pairinteraction paper, where we use SI units throughout).
Coulomb wavefunctions
Using non-relativistic quantum defect theory it is possible to find radial wavefunctions. Therefore the Schrödinger equation is solved for a given energy eigenvalue, which results in modified radial wavefunctions with an effective (non-integer) quantum number $n^*$. The derivation is discussed in more detail in M. J. Seaton, Reports on Progress in Physics 46, 167 (1983) (around equation 2.77).
$$
r\;\Psi^{\text{rad}}{n^l}(r) = \frac{1}{\sqrt{n^{2} \Gamma(n^+l+1) \Gamma(n^-l)}}
W{n^,l+1/2}\left( \frac{2 r}{n^} \right).
$$
where $\Gamma(z)$ is the Gamma function and $W_{k,m}(z)$ is the so-called Whittaker function. These wavefunctions are highly accurate for large distances and have the correct binding energy. You can access these wavefunctions in pairinteraction using the Whittaker class.
Numerov's method and model potentials
Model potentials
Another method to determine the radial wavefunctions is by solving the Schrödinger equation numerically using an effective Coulomb potential. The so-called model potential is usually decomposed into three contributions
$$
V_{\text{mod}}(r) = V_{\text{C}}(r) + V_{\text{P}}(r) + V_{\text{s.o.}}(r).
$$
The first term is the charge contribution resulting from the charged core which is screened by the filled electron shells
$$
% (18a) in Dalgarno1994
V_{\mathrm{C}}(r) = - \frac{1 + (Z-1)\mathrm{e}^{-\alpha_1 r} - r(\alpha_3+\alpha_4 r)\mathrm{e}^{-\alpha_2 r}}{r},
$$
with coefficients $\alpha_{1,2,3,4}$ depending on the atomic species and the orbital angular momentum $l$. These coefficients are provided with pairinteraction in an embedded database. It is possible to substitute these coefficients with your own at runtime.
For the core polarization, only the leading dipole term is considered, which results in
Step3: The parameters of the model potentials can be accessed like member variables of the qd object. They have mnemonic names to mirror their meaning in the model potentials presented above.
Step4: The effective principal quantum number in quantum defect theory is defined as series expansion
$$
n^* = n - \delta_{nlj}
\quad\text{with}\quad
\delta_{nlj} = \delta_0
+ \frac{\delta_2}{(n-\delta_0)^2}
+ \frac{\delta_4}{(n-\delta_0)^4}
+ \frac{\delta_6}{(n-\delta_0)^6} .
$$
Similarly the effective energy eigenvalues are given as
$$
E_{nlj} = - \frac{1}{2 R_\infty} \frac{R^}{n^{2}} .
$$
The parameters $\delta_{0,2,4,6,\dots}$ and $R^$ are also loaded from the database, but since they are only important for the calculation of $n^$ and $E_{nlj}$ there is no interface to query their values. The quantities $n^*$ and $E_{nlj}$, however, can be queried.
Step5: Even though these parameters can be accessed like member variables, they are read-only values and attempting to change them will result in an error.
Radial wavefunction in pairinteraction
Two types of radial wavefunctions are available in pairinteraction
Step6: The wavefunctions which we obtain from these methods are unscaled, i.e. they have their original scaling as defined by the calculation. The $x$-axes are square root scaled. The result returned by the Coulomb wavefunction method is $r \;\Psi^{\text{rad}}(r)$. The result calculated by Numerov's method is $X(x)$, as defined above, and must be multiplied by $\sqrt{x}$ to get $r \;\Psi^{\text{rad}}(r)$. | Python Code:
%matplotlib inline
Explanation: Radial Wavefunctions and Quantum Defects
In this tutorial we show how to access quantum defects and wavefunctions, which are used for the computation of matrix elements, using the Python API. Some aspects of this are discussed in Appendix A of the pairinteraction paper J. Phys. B: At. Mol. Opt. Phys. 50, 133001 (2017).
This feature is mostly used internally and therefore the interfaces are not so user-friendly.
Ahead of our Python code, we call an IPython magic function to make the output of plotting commands displayed inline within the notebook.
End of explanation
# Arrays
import numpy as np
# Plotting
import matplotlib.pyplot as plt
# pairinteraction :-)
from pairinteraction import pireal as pi
Explanation: Our code starts with loading the required modules for the computation. It is irrelevant whether we use the pireal or picomplex modules here, because we do not calculate any matrix elements.
End of explanation
qd = pi.QuantumDefect("Rb", 50, 0, 0.5)
Explanation: Keep in mind that pairinteraction is a Rydberg interaction calculator. All techniques presented below work well for the high-$n$ states of Rydberg atoms, but fail miserably for low-lying states.
While the pairinteraction software normally uses the unit system described in the introduction, for the wavefunction it has proven advantageous to perform the calculation in atomic units, i.e. all units below are atomic units (in contrast to the presentation in Appendix A of the pairinteraction paper, where we use SI units throughout).
Coulomb wavefunctions
Using non-relativistic quantum defect theory it is possible to find radial wavefunctions. Therefore the Schrödinger equation is solved for a given energy eigenvalue, which results in modified radial wavefunctions with an effective (non-integer) quantum number $n^*$. The derivation is discussed in more detail in M. J. Seaton, Reports on Progress in Physics 46, 167 (1983) (around equation 2.77).
$$
r\;\Psi^{\text{rad}}{n^l}(r) = \frac{1}{\sqrt{n^{2} \Gamma(n^+l+1) \Gamma(n^-l)}}
W{n^,l+1/2}\left( \frac{2 r}{n^} \right).
$$
where $\Gamma(z)$ is the Gamma function and $W_{k,m}(z)$ is the so-called Whittaker function. These wavefunctions are highly accurate for large distances and have the correct binding energy. You can access these wavefunctions in pairinteraction using the Whittaker class.
Numerov's method and model potentials
Model potentials
Another method to determine the radial wavefunctions is by solving the Schrödinger equation numerically using an effective Coulomb potential. The so-called model potential is usually decomposed into three contributions
$$
V_{\text{mod}}(r) = V_{\text{C}}(r) + V_{\text{P}}(r) + V_{\text{s.o.}}(r).
$$
The first term is the charge contribution resulting from the charged core which is screened by the filled electron shells
$$
% (18a) in Dalgarno1994
V_{\mathrm{C}}(r) = - \frac{1 + (Z-1)\mathrm{e}^{-\alpha_1 r} - r(\alpha_3+\alpha_4 r)\mathrm{e}^{-\alpha_2 r}}{r},
$$
with coefficients $\alpha_{1,2,3,4}$ depending on the atomic species and the orbital angular momentum $l$. These coefficients are provided with pairinteraction in an embedded database. It is possible to substitute these coefficients with your own at runtime.
For the core polarization, only the leading dipole term is considered, which results in:
$$
V_{\mathrm{P}}(r) = -\frac{\alpha_d}{2 r^4} \left[ 1 - \mathrm{e}^{-(r/r_c)^6} \right].
$$
Here, $\alpha_d$ is again the core dipole polarizability and $r_c$ is the effective core size, obtained by comparing the numerical solutions with the experimentally observed energy levels.
In addition to these two terms, we add an effective expression for the spin-orbit interaction
$$
V_{\mathrm{s.o.}}(r > r_c) = \frac{2 \alpha}{r^3} \mathbf{l}\cdot\mathbf{s} = \frac{\alpha}{r^3} [j(j+1) - l(l+1) - s(s+1)].
$$
where $\alpha\approx1/137$ is the fine-structure constant.
Numerov's method
Numerov's method can be used to solve differential equations of the form
$$
\frac{d^2 y}{d x^2} + g(x) y(x) = 0.
$$
The iterative solution can be achieved as follows:
$$
y_{n+1} \left( 1 - \frac{h^2}{12} g_{n+1} \right)
= \left( 2 + \frac{5 h^2}{6} g_{n} \right) y_{n}
- \left( 1 - \frac{h^2}{12} g_{n-1} \right) y_{n-1}
+ \mathcal{O}(h^6).
$$
where $y_{n}=y(x_{n})$, $g_{n}=g(x_{n})$, $s_{n}=s(x_{n})$, and $h=x_{n+1}-x_{n}$.
To save space it is useful to reduce the sampling towards large distances from the core as the periods of osciallations become longer and longer. To this end we introduce the square root scaling:
$$
x = \sqrt{r} \;,\quad X^{\text{rad}}{nlj}(x) = x^{3/2} \Psi^{\text{rad}}{nlj}(r).
$$
This scaling keeps the number of grid points between nodes of the wave function constant. In this scaling the $g(r)$ in Numerov's method is given by
$$
g(r) = \frac{(2 l + 1/2)(2 l + 3/2)}{r} + 8 r (V_{\text{mod}}(r) - E).
$$
We integrate the equation from outside to inside. Since the wavefunction has to decay to zero at infinity we choose $y_0 = 0$. Now depending on the number of nodes of wavefunction we decide whether to set $y_1 = \pm\epsilon$, where $\epsilon$ is a small number. As the inner cutoff we choose an augmented version of the classical turning point
$$
r_{\text{min}} = n^2 - n \sqrt{n^2 - (l-1)^2}.
$$
Other schemes for terminating the integration exist which are based on identifying nodes but for large $n$ the augmented classical turning point works well and is easy to implement.
Quantum defects and model potential in pairinteraction
The model potentials and quantum defects are stored in a database which is shipped together with pairinteraction. For performance reasons it is baked into the binary so that it is available in memory at all times. The internal database can also be swapped out with a user-provided one at runtime.
To obtain the parameters from the database we use the QuantumDefect class.
End of explanation
print("Core polarizability: ac =",qd.ac)
print("Effective coulomb potential")
print(" Z =",qd.Z,"(core charge)")
print(" a1 =",qd.a1)
print(" a2 =",qd.a2)
print(" a3 =",qd.a3)
print(" a4 =",qd.a4)
print("Effective core radius: rc =",qd.rc)
Explanation: The parameters of the model potentials can be accessed like member variables of the qd object. They have mnemonic names to mirror their meaning in the model potentials presented above.
End of explanation
print("Effective quantum number: n* =",qd.nstar)
print("State energy: E(n*) =",qd.energy)
Explanation: The effective principal quantum number in quantum defect theory is defined as series expansion
$$
n^* = n - \delta_{nlj}
\quad\text{with}\quad
\delta_{nlj} = \delta_0
+ \frac{\delta_2}{(n-\delta_0)^2}
+ \frac{\delta_4}{(n-\delta_0)^4}
+ \frac{\delta_6}{(n-\delta_0)^6} .
$$
Similarly the effective energy eigenvalues are given as
$$
E_{nlj} = - \frac{1}{2 R_\infty} \frac{R^}{n^{2}} .
$$
The parameters $\delta_{0,2,4,6,\dots}$ and $R^$ are also loaded from the database, but since they are only important for the calculation of $n^$ and $E_{nlj}$ there is no interface to query their values. The quantities $n^*$ and $E_{nlj}$, however, can be queried.
End of explanation
n = pi.Numerov(qd).integrate()
w = pi.Whittaker(qd).integrate()
Explanation: Even though these parameters can be accessed like member variables, they are read-only values and attempting to change them will result in an error.
Radial wavefunction in pairinteraction
Two types of radial wavefunctions are available in pairinteraction:
The numerical wavefunctions computed using Numerov's method and the model potentials.
The analytical Coulomb wavefunctions based on the Whittaker functions.
Those two schemes can accessed by classes with the names of their underlying method, Numerov and Whittaker. Merely instatiating an object of either class only allocates memory but does not perform any computations. To actually run the integration, you have to call the integrate() member function.
End of explanation
plt.xlabel("$r$ ($a_0$)")
plt.ylabel("$r^2|\Psi(r)|^2$ [a.u.]")
plt.plot(n[:,0]**2,np.abs(np.sqrt(n[:,0])*n[:,1])**2,'-',label="numeric WF")
plt.plot(w[:,0]**2,np.abs(w[:,1])**2,'--',label="Coulomb WF")
plt.legend();
Explanation: The wavefunctions which we obtain from these methods are unscaled, i.e. they have their original scaling as defined by the calculation. The $x$-axes are square root scaled. The result returned by the Coulomb wavefunction method is $r \;\Psi^{\text{rad}}(r)$. The result calculated by Numerov's method is $X(x)$, as defined above, and must be multiplied by $\sqrt{x}$ to get $r \;\Psi^{\text{rad}}(r)$.
End of explanation |
8,514 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyGamma15 statistics tutorial
Welcome to the PyGamma15 statistics tutorial!
The actual tutorial will consist of an IPython notebook
with some descriptions and code to get you started,
and instructions / excercises where you get to implement
a statistical analysis.
This IPython notebook is not the actual tutorial,
it's just here for you to check if you have all the
required software installed and working.
Please install all the packages mentioned here
and then execute the code below to verify that
everything works before the workshop or at least
before the tutorial.
For further information see the description here.
Scientific Python packages
You'll need numpy, pandas, scipy and matplotlib.
Step1: iminuit
Let's see if the first example from the iminuit docs works ...
Step2: emcee
Same for emcee ... let's see if the first example from the docs works.
(You don't have to understand what this does for now ... just check if it runs for you without error.)
Step3: uncertainties
We might also use the uncertainties package for error propagation. So please install that as well ... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import scipy.stats
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.plot([1, 3, 6], [2, 5, 3]);
Explanation: PyGamma15 statistics tutorial
Welcome to the PyGamma15 statistics tutorial!
The actual tutorial will consist of an IPython notebook
with some descriptions and code to get you started,
and instructions / excercises where you get to implement
a statistical analysis.
This IPython notebook is not the actual tutorial,
it's just here for you to check if you have all the
required software installed and working.
Please install all the packages mentioned here
and then execute the code below to verify that
everything works before the workshop or at least
before the tutorial.
For further information see the description here.
Scientific Python packages
You'll need numpy, pandas, scipy and matplotlib.
End of explanation
from iminuit import Minuit
def f(x, y, z):
return (x - 2) ** 2 + (y - 3) ** 2 + (z - 4) ** 2
m = Minuit(f, pedantic=False, print_level=0)
m.migrad()
print(m.values) # {'x': 2,'y': 3,'z': 4}
print(m.errors) # {'x': 1,'y': 1,'z': 1}
Explanation: iminuit
Let's see if the first example from the iminuit docs works ...
End of explanation
import emcee
def lnprob(x, ivar):
return -0.5 * np.sum(ivar * x ** 2)
ndim, nwalkers = 10, 100
ivar = 1. / np.random.rand(ndim)
p0 = [np.random.rand(ndim) for i in range(nwalkers)]
sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=[ivar])
samples = sampler.run_mcmc(p0, 1000)
Explanation: emcee
Same for emcee ... let's see if the first example from the docs works.
(You don't have to understand what this does for now ... just check if it runs for you without error.)
End of explanation
from uncertainties import ufloat
x = ufloat(1, 0.1)
print(2 * x)
Explanation: uncertainties
We might also use the uncertainties package for error propagation. So please install that as well ...
End of explanation |
8,515 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interactive Web application with Dash
Authors
Step1: Data collection (2/6)
Query d_labitems table (Dictionary table for mapping)
Query labevents table (History of the labitem order)
Join two tables
Query prescriptions table (History of the prscription order)
Step2: Data preparation for labevents table (3/6)
Convert data type to datetime and extract only year value
Step3: Data preparation for prescriptions table (4/6)
Filter conditions
Step4: Create a structure and presentation of your web with HTML and CSS (5/6)
Step5: Define the reactive behavior with Python (6/6) | Python Code:
# # Dash packages installation
# !conda install -c conda-forge dash-renderer -y
# !conda install -c conda-forge dash -y
# !conda install -c conda-forge dash-html-components -y
# !conda install -c conda-forge dash-core-components -y
# !conda install -c conda-forge plotly -y
import dash
import dash_core_components as dcc
import dash_html_components as html
import flask
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import numpy as np
import pandas as pd
pd.set_option('display.max_columns', 999)
import pandas.io.sql as psql
Explanation: Interactive Web application with Dash
Authors: Prof. med. Thomas Ganslandt Thomas.Ganslandt@medma.uni-heidelberg.de <br>
and Kim Hee HeeEun.Kim@medma.uni-heidelberg.de <br>
Heinrich-Lanz-Center for Digital Health (HLZ) of the Medical Faculty Mannheim <br>
Heidelberg University
This tutorial is prepared for TMF summer school on 03.07.2019
Prerequisite: MIMIC-III files locally
You should place the following MIMIC-III data files in the data/ subfolder:
D_LABITEMS.csv
LABEVENTS.csv
PRESCRIPTIONS.csv
Dash
https://dash.plot.ly/gallery <br>
Dash is a Python framework for creating data-driven web applications <br>
Dash apps are written on top of Flask, Plotly, and React
Flask is a Python web framework
Plotly is specifically a charting library built on top of D3.js
React is a JavaScript library for building user interfaces maintained by Facebook and a community
Case Study 2: Labitems Trend Visualization
Trend analysis is the widespread practice of collecting information and attempting to spot a pattern. This case study will illustrate a drug reaction of a sepsis patient. This case study tracks the biomarker and prescription history of patient 41976. It visualizes the relation between two key biomarkers of sepsis (White Blood Cells and Neutrophils) and
'41976' patient is choosen for this case study because this patient contains most and interesting records among other sepsis patients '10006', '10013', '10036', '10056', '40601'
Import Python pakages (1/6)
End of explanation
d_lab = pd.read_csv("data/D_LABITEMS.csv")
d_lab.columns = map(str.lower, d_lab.columns)
d_lab.drop(columns = ['row_id'], inplace = True)
lab = pd.read_csv("data/LABEVENTS.csv")
lab.columns = map(str.lower, lab.columns)
lab = lab[lab['subject_id'] == 41976]
lab.drop(columns = ['row_id'], inplace = True)
lab = pd.merge(d_lab, lab, on = 'itemid', how = 'inner')
print(lab.columns)
lab[['subject_id', 'hadm_id', 'itemid', 'label', 'value']].head()
presc = pd.read_csv("data/PRESCRIPTIONS.csv")
presc.columns = map(str.lower, presc.columns)
presc = presc[presc['subject_id'] == 41976]
presc.drop(columns = ['row_id'], inplace = True)
print(presc.columns)
presc[['subject_id', 'hadm_id', 'icustay_id', 'drug']].head()
Explanation: Data collection (2/6)
Query d_labitems table (Dictionary table for mapping)
Query labevents table (History of the labitem order)
Join two tables
Query prescriptions table (History of the prscription order)
End of explanation
lab['charttime'] = pd.to_datetime(lab['charttime'], errors = 'coerce')
lab.sort_values(by='charttime', inplace=True)
lab.set_index('charttime', inplace = True)
lab.head(1)
Explanation: Data preparation for labevents table (3/6)
Convert data type to datetime and extract only year value
End of explanation
presc['dose_val_rx'] = pd.to_numeric(presc['dose_val_rx'], errors = 'coerce')
presc = presc[presc['dose_unit_rx']=='mg']
presc = presc[presc['drug'].isin(['Vancomycin','Meropenem','Levofloxacin'])]
temp_df = pd.DataFrame()
for item in presc.drug.unique():
temp = presc[presc['drug'].str.contains(item)]
temp['norm_size'] = temp['dose_val_rx'] / temp['dose_val_rx'].max()
temp_df = temp_df.append(temp)
presc = pd.merge(presc, temp_df, on=list(presc.columns))
presc['startdate'] = pd.to_datetime(presc['startdate'], errors = 'coerce')
presc.sort_values(by='startdate', inplace=True)
presc.set_index('startdate', inplace = True)
presc.head(1)
Explanation: Data preparation for prescriptions table (4/6)
Filter conditions:
unit: 'mg'
antibiotics medicines: ('Vancomycin','Meropenem','Levofloxacin')
Contruct a normalized dose column
Convert data type to datetime and extract only year value
End of explanation
list_patient = ['41976']
list_biomarker = ['White Blood Cells', 'Neutrophils']
list_drug = ['Vancomycin','Meropenem','Levofloxacin']
# stylesheets = ['./resources/bWLwgP.css']
app = dash.Dash()
app.layout = html.Div([
dcc.Dropdown(
id = 'patient',
value = '41976',
multi = False,
options = [{'label': i, 'value': i} for i in list_patient],
),
dcc.Dropdown(
id = 'biomarker',
value = 'White Blood Cells',
multi = False,
options = [{'label': i, 'value': i} for i in list_biomarker],
),
dcc.Dropdown(
id = 'drug',
value = ['Vancomycin'],
multi = True,
options = [{'label': i, 'value': i} for i in list_drug],
),
dcc.Graph(id = 'graph'),
])
Explanation: Create a structure and presentation of your web with HTML and CSS (5/6)
End of explanation
@app.callback(Output('graph', 'figure'),
[Input('patient', 'value'),
Input('biomarker', 'value'),
Input('drug', 'value')])
def update_graph(patient, biomarker, drug):
traces = []
temp_l = lab[lab['subject_id'].astype(str) == patient]
temp_p = presc[presc['subject_id'].astype(str) == patient]
temp_min = 0
item = biomarker
temp = temp_l[temp_l['label'] == item]
temp_min = float(temp.value.astype(float).min())
trace = go.Scatter(
x = temp.index,
y = temp.value,
name = item,
mode = 'lines+markers',
)
traces.append(trace)
for i, item in enumerate(drug):
temp = temp_p[ temp_p['drug'] == item]
trace = go.Scatter(
x = temp.index,
y = np.ones((1, len(temp)))[0] * temp_min - i - 1,
name = item,
mode = 'markers',
marker = {
'size': temp.norm_size * 10
}
)
traces.append(trace)
layout = go.Layout(
legend = {'x': 0.5, 'y': -0.1, 'orientation': 'h', 'xanchor': 'center'},
margin = {'l': 300, 'b': 10, 't': 10, 'r': 300},
hovermode = 'closest',
)
return {'data': traces, 'layout': layout}
app.run_server(port = 8050)
Explanation: Define the reactive behavior with Python (6/6)
End of explanation |
8,516 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple Linear Regression
We need to read our data from a <tt>csv</tt> file. The module csv offers a number of functions for reading and writing a <tt>csv</tt> file.
Step1: Let us read the data.
Step2: Since <em style="color
Step3: It seems that about $75\%$ of the fuel consumption is explained by the engine displacement. We can get a better model of the fuel consumption if we use more variables for explaining the fuel consumption. For example, the weight of a car is also responsible for its fuel consumption. | Python Code:
import csv
Explanation: Simple Linear Regression
We need to read our data from a <tt>csv</tt> file. The module csv offers a number of functions for reading and writing a <tt>csv</tt> file.
End of explanation
with open('cars.csv') as handle:
reader = csv.DictReader(handle, delimiter=',')
Data = [] # engine displacement
for row in reader:
Data.append(row)
Data[:5]
import numpy as np
Explanation: Let us read the data.
End of explanation
def simple_linear_regression(X, Y):
xMean = np.mean(X)
yMean = np.mean(Y)
ϑ1 = np.sum((X - xMean) * (Y - yMean)) / np.sum((X - xMean) ** 2)
ϑ0 = yMean - ϑ1 * xMean
TSS = np.sum((Y - yMean) ** 2)
RSS = np.sum((ϑ1 * X + ϑ0 - Y) ** 2)
R2 = 1 - RSS/TSS
return R2
Explanation: Since <em style="color:blue;">kilometres per litre</em> is the inverse of the fuel consumption, the vector Y is defined as follows:
End of explanation
def coefficient_of_determination(name, Data):
X = np.array([float(line[name]) for line in Data])
Y = np.array([1/float(line['mpg']) for line in Data])
R2 = simple_linear_regression(X, Y)
print(f'coefficient of determination of fuel consumption w.r.t. {name:12s}: {round(R2, 2)}')
DependentVars = ['cyl', 'displacement', 'hp', 'weight', 'acc', 'year']
for name in DependentVars:
coefficient_of_determination(name, Data)
Explanation: It seems that about $75\%$ of the fuel consumption is explained by the engine displacement. We can get a better model of the fuel consumption if we use more variables for explaining the fuel consumption. For example, the weight of a car is also responsible for its fuel consumption.
End of explanation |
8,517 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Responses for RXTE HEXTE
Step1: Sherpa Stuff
Daniela is doing some sherpa testing right now ...
Step2: RXTE does not have BIN_LO and BIN_HI set. Because of course it doesn't.
Step3: RXTE HEXTE has an ARF, just like a regular X-ray telescope (and unlike RXTE/PCA, which doesn't)
Step4: Let's also load the rmf
Step5: Ok, so all of our files have the same units. This is good.
Let's also get the ARF and RMF from sherpa
Step6: Now we can make a model spectrum we can play around with! clarsach has an implementation of a Powerlaw model that matches the ISIS one that created the data
Step7: Let's save model with ARF and RMF applied
Step8: Okay, that looks pretty good!
Building a Model
Let's build a model for fitting a model to the data. We're going to do nothing fancy here, just a simple Poisson likelihood. It's similar to the one in the TestAthenaXIFU notebook, except it uses the Clarsach powerlaw function and integrates over bins.
Step10: The sherpa stuff works! Good!
Making Our Own ARF/RMF Classes
Ideally, we don't want to be dependent on the sherpa implementation.
We're now going to write our own implementations, and then test them on the model above.
Let's write a function that applies the ARF, which is just straightforward element-wise multiplication
Step11: Let's look at the RMF, which is more complex. This requires a matrix multiplication. However, the response matrices are compressed to remove zeros and save space in memory, so they require a little more complex fiddling. Here's an implementation that is basically almost a line-by-line translation of the C++ code
Step13: Let's see if we can make this more vectorized
Step14: Let's time the different implementations and compare them to the sherpa version (which is basically a wrapper around the C++)
Step15: So my vectorized implementation is ~20 times slower than the sherpa version, and the non-vectorized version is really slow. But are they all the same?
Step19: They are! It looks like for this particular RXTE data set, it's working!
Making an ARF/RMF Class
the ARF and RMF code would live well in a class, so let's wrap it into a class
Step20: Let's make an object of that class and then make another model with the RMF applied
Step21: Hooray! What does the total spectrum look like?
Step22: There is, of course, also an implementation in clarsach | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
# try:
# import seaborn as sns
# except ImportError:
# print("No seaborn installed. Oh well.")
import numpy as np
# import pandas as pd
import astropy.io.fits as fits
from astropy.table import Table
import sherpa.astro.ui as ui
import astropy.modeling.models as models
from astropy.modeling.fitting import _fitter_to_model_params
from scipy.special import gammaln as scipy_gammaln
import os.path
# from clarsach.respond import RMF, ARF
Explanation: Responses for RXTE HEXTE
End of explanation
datadir = "./"
ui.load_data(id="p1", filename=datadir+"RXTE_HEXTE_ClusterA.fak")
d = ui.get_data("p1")
# conversion factor from keV to angstrom
c = 12.3984191
# This is the data in angstrom
bin_lo = d.bin_lo
bin_hi = d.bin_hi
print(bin_lo)
counts = d.counts
exposure = d.exposure
channel = d.channel
Explanation: Sherpa Stuff
Daniela is doing some sherpa testing right now ...
End of explanation
plt.figure(figsize=(10,7))
plt.plot(channel, counts)
Explanation: RXTE does not have BIN_LO and BIN_HI set. Because of course it doesn't.
End of explanation
arf_list = fits.open(datadir+"rxte_hexte_00may26_pwa.arf")
arf_list[1].data.field("ENERG_LO")[:10]
arf_list[1].data.columns
specresp = arf_list[1].data.field("SPECRESP")
energ_lo = arf_list[1].data.field("ENERG_LO")
energ_hi = arf_list[1].data.field("ENERG_HI")
energ_lo.shape
Explanation: RXTE HEXTE has an ARF, just like a regular X-ray telescope (and unlike RXTE/PCA, which doesn't):
End of explanation
rmf_list = fits.open(datadir+"rxte_hexte_97mar20c_pwa.rmf")
rmf_list[1].header["TUNIT1"]
rmf_list.info()
rmf_list["EBOUNDS"].columns
energ_lo = rmf_list["MATRIX"].data.field("ENERG_LO")
energ_hi = rmf_list["MATRIX"].data.field("ENERG_HI")
bin_lo = rmf_list["EBOUNDS"].data.field("E_MIN")
bin_hi = rmf_list["EBOUNDS"].data.field("E_MAX")
bin_mid = bin_lo + (bin_hi - bin_lo)/2.
Explanation: Let's also load the rmf:
End of explanation
arf = d.get_arf()
rmf = d.get_rmf()
rmf
Explanation: Ok, so all of our files have the same units. This is good.
Let's also get the ARF and RMF from sherpa:
End of explanation
from clarsach.models.powerlaw import Powerlaw
pl = Powerlaw(norm=1.0, phoindex=2.0)
m = pl.calculate(ener_lo=energ_lo, ener_hi=energ_hi)
plt.figure()
plt.loglog(energ_lo, m)
m_arf = arf.apply_arf(m)
m_rmf = rmf.apply_rmf(m_arf)
plt.figure()
plt.plot(bin_mid, counts, label="data")
plt.plot(bin_mid, m_rmf*1e5, label="model with RMF")
plt.legend()
Explanation: Now we can make a model spectrum we can play around with! clarsach has an implementation of a Powerlaw model that matches the ISIS one that created the data:
End of explanation
np.savetxt("../data/rxte_hexte_m_arf.txt", np.array([energ_lo, m_arf]).T)
np.savetxt("../data/rxte_hexte_m_rmf.txt", np.array([bin_mid, m_rmf]).T)
Explanation: Let's save model with ARF and RMF applied:
End of explanation
class PoissonLikelihood(object):
def __init__(self, x_low, x_high, y, model, arf=None, rmf=None, exposure=1.0):
self.x_low = x_low
self.x_high = x_high
self.y = y
self.model = model
self.arf = arf
self.rmf = rmf
self.exposure = exposure
def evaluate(self, pars):
# store the new parameters in the model
self.model.norm = pars[0]
self.model.phoindex = pars[1]
# evaluate the model at the positions x
mean_model = self.model.calculate(self.x_low, self.x_high)
# run the ARF and RMF calculations
if self.arf is not None:
m_arf = self.arf.apply_arf(mean_model)
else:
m_arf = mean_model
if self.rmf is not None:
ymodel = self.rmf.apply_rmf(m_arf)
else:
ymodel = mean_model
ymodel += 1e-20
ymodel *= self.exposure
# compute the log-likelihood
loglike = np.sum(-ymodel + self.y*np.log(ymodel) \
- scipy_gammaln(self.y + 1.))
if np.isfinite(loglike):
return loglike
else:
return -1.e16
def __call__(self, pars):
l = -self.evaluate(pars)
#print(l)
return l
loglike = PoissonLikelihood(energ_lo, energ_hi, counts, pl, arf=arf, rmf=rmf, exposure=exposure)
loglike([1.0, 2.0])
from scipy.optimize import minimize
opt = minimize(loglike, [1.0, 2.0], method="powell")
opt
m_fit = pl.calculate(energ_lo, energ_hi)
m_fit_arf = arf.apply_arf(m_fit)
m_fit_rmf = rmf.apply_rmf(m_fit_arf) * exposure
plt.figure()
plt.plot(bin_mid, counts, label="data")
plt.plot(bin_mid, m_fit_rmf, label="model with ARF")
plt.legend()
Explanation: Okay, that looks pretty good!
Building a Model
Let's build a model for fitting a model to the data. We're going to do nothing fancy here, just a simple Poisson likelihood. It's similar to the one in the TestAthenaXIFU notebook, except it uses the Clarsach powerlaw function and integrates over bins.
End of explanation
def apply_arf(spec, specresp, exposure=1.0):
Apply the anxilliary response to
a spectrum.
Parameters
----------
spec : numpy.ndarray
The source spectrum in flux units
specresp: numpy.ndarray
The response
exposure : float
The exposure of the observation
Returns
-------
spec_arf : numpy.ndarray
The spectrum with the response applied.
spec_arf = spec*specresp*exposure
return spec_arf
m_arf = apply_arf(m, arf.specresp)
m_arf_sherpa = arf.apply_arf(m)
np.allclose(m_arf, m_arf_sherpa)
plt.plot(m_arf, label="Clarsach ARF")
plt.plot(m_arf_sherpa, label="Sherpa ARF")
plt.legend()
Explanation: The sherpa stuff works! Good!
Making Our Own ARF/RMF Classes
Ideally, we don't want to be dependent on the sherpa implementation.
We're now going to write our own implementations, and then test them on the model above.
Let's write a function that applies the ARF, which is just straightforward element-wise multiplication:
End of explanation
def rmf_fold(spec, rmf, nchannels=None):
#current_num_groups = 0
#current_num_chans = 0
nchannels = spec.shape[0]
resp_idx = 0
first_chan_idx = 0
num_chans_idx =0
counts_idx = 0
counts = np.zeros(nchannels)
for i in range(nchannels):
source_bin_i = spec[i]
current_num_groups = rmf.n_grp[i]
while current_num_groups:
counts_idx = int(rmf.f_chan[first_chan_idx] - rmf.offset)
current_num_chans = rmf.n_chan[num_chans_idx]
first_chan_idx += 1
num_chans_idx +=1
while current_num_chans:
counts[counts_idx] += rmf.matrix[resp_idx] * source_bin_i
counts_idx += 1
resp_idx += 1
current_num_chans -= 1
current_num_groups -= 1
return counts
Explanation: Let's look at the RMF, which is more complex. This requires a matrix multiplication. However, the response matrices are compressed to remove zeros and save space in memory, so they require a little more complex fiddling. Here's an implementation that is basically almost a line-by-line translation of the C++ code:
End of explanation
def rmf_fold_vector(spec, rmf, nchannels=None):
Fold the spectrum through the redistribution matrix.
Parameters
----------
spec : numpy.ndarray
The (model) spectrum to be folded
rmf : sherpa.RMFData object
The object with the RMF data
# get the number of channels in the data
nchannels = spec.shape[0]
# an empty array for the output counts
counts = np.zeros(nchannels)
#print('len(nchannels): ' + str(nchannels))
# index for n_chan and f_chan incrementation
k = 0
# index for the response matrix incrementation
resp_idx = 0
# loop over all channels
for i in range(nchannels):
# this is the current bin in the flux spectrum to
# be folded
source_bin_i = spec[i]
# get the current number of groups
current_num_groups = rmf.n_grp[i]
for j in range(current_num_groups):
counts_idx = int(rmf.f_chan[k] - rmf.offset)
current_num_chans = int(rmf.n_chan[k])
k += 1
counts[counts_idx:counts_idx+current_num_chans] += rmf.matrix[resp_idx:resp_idx+current_num_chans] * source_bin_i
resp_idx += current_num_chans
return counts
Explanation: Let's see if we can make this more vectorized:
End of explanation
# not vectorized version
m_rmf = rmf_fold(m_arf, rmf)
%timeit m_rmf = rmf_fold(m_arf, rmf)
# vectorized version
m_rmf_v = rmf_fold_vector(m_arf, rmf)
%timeit m_rmf_v = rmf_fold_vector(m_arf, rmf)
# C++ (sherpa) version
m_rmf2 = rmf.apply_rmf(m_arf)
%timeit m_rmf2 = rmf.apply_rmf(m_arf)
Explanation: Let's time the different implementations and compare them to the sherpa version (which is basically a wrapper around the C++):
End of explanation
np.allclose(m_rmf_v[:len(m_rmf2)], m_rmf2)
np.allclose(m_rmf[:len(m_rmf2)], m_rmf2)
Explanation: So my vectorized implementation is ~20 times slower than the sherpa version, and the non-vectorized version is really slow. But are they all the same?
End of explanation
class RMF(object):
def __init__(self, filename):
self._load_rmf(filename)
pass
def _load_rmf(self, filename):
Load an RMF from a FITS file.
Parameters
----------
filename : str
The file name with the RMF file
Attributes
----------
n_grp : numpy.ndarray
the Array with the number of channels in each
channel set
f_chan : numpy.ndarray
The starting channel for each channel group;
If an element i in n_grp > 1, then the resulting
row entry in f_chan will be a list of length n_grp[i];
otherwise it will be a single number
n_chan : numpy.ndarray
The number of channels in each channel group. The same
logic as for f_chan applies
matrix : numpy.ndarray
The redistribution matrix as a flattened 1D vector
energ_lo : numpy.ndarray
The lower edges of the energy bins
energ_hi : numpy.ndarray
The upper edges of the energy bins
detchans : int
The number of channels in the detector
# open the FITS file and extract the MATRIX extension
# which contains the redistribution matrix and
# anxillary information
hdulist = fits.open(filename)
# get all the extension names
extnames = np.array([h.name for h in hdulist])
# figure out the right extension to use
if "MATRIX" in extnames:
h = hdulist["MATRIX"]
elif "SPECRESP MATRIX" in extnames:
h = hdulist["SPECRESP MATRIX"]
data = h.data
hdr = h.header
hdulist.close()
# extract + store the attributes described in the docstring
n_grp = np.array(data.field("N_GRP"))
f_chan = np.array(data.field('F_CHAN'))
n_chan = np.array(data.field("N_CHAN"))
matrix = np.array(data.field("MATRIX"))
self.energ_lo = np.array(data.field("ENERG_LO"))
self.energ_hi = np.array(data.field("ENERG_HI"))
self.detchans = hdr["DETCHANS"]
self.offset = self.__get_tlmin(h)
# flatten the variable-length arrays
self.n_grp, self.f_chan, self.n_chan, self.matrix = \
self.__flatten_arrays(n_grp, f_chan, n_chan, matrix)
return
def __get_tlmin(self, h):
Get the tlmin keyword for `F_CHAN`.
Parameters
----------
h : an astropy.io.fits.hdu.table.BinTableHDU object
The extension containing the `F_CHAN` column
Returns
-------
tlmin : int
The tlmin keyword
# get the header
hdr = h.header
# get the keys of all
keys = np.array(list(hdr.keys()))
# find the place where the tlmin keyword is defined
t = np.array(["TLMIN" in k for k in keys])
# get the index of the TLMIN keyword
tlmin_idx = np.hstack(np.where(t))[0]
# get the corresponding value
tlmin = np.int(list(hdr.items())[tlmin_idx][1])
return tlmin
def __flatten_arrays(self, n_grp, f_chan, n_chan, matrix):
# find all non-zero groups
nz_idx = (n_grp > 0)
# stack all non-zero rows in the matrix
matrix_flat = np.hstack(matrix[nz_idx])
# some matrices actually have more elements
# than groups in `n_grp`, so we'll only pick out
# those values that have a correspondence in
# n_grp
f_chan_new = []
n_chan_new = []
for i,t in enumerate(nz_idx):
if t:
n = n_grp[i]
f = f_chan[i]
nc = n_chan[i]
f_chan_new.append(f[:n])
n_chan_new.append(nc[:n])
n_chan_flat = np.hstack(n_chan_new)
f_chan_flat = np.hstack(f_chan_new)
# if n_chan is zero, we'll remove those as well.
nz_idx2 = (n_chan_flat > 0)
n_chan_flat = n_chan_flat[nz_idx2]
f_chan_flat = f_chan_flat[nz_idx2]
return n_grp, f_chan_flat, n_chan_flat, matrix_flat
def apply_rmf(self, spec):
Fold the spectrum through the redistribution matrix.
The redistribution matrix is saved as a flattened 1-dimensional
vector to save space. In reality, for each entry in the flux
vector, there exists one or more sets of channels that this
flux is redistributed into. The additional arrays `n_grp`,
`f_chan` and `n_chan` store this information:
* `n_group` stores the number of channel groups for each
energy bin
* `f_chan` stores the *first channel* that each channel
for each channel set
* `n_chan` stores the number of channels in each channel
set
As a result, for a given energy bin i, we need to look up the
number of channel sets in `n_grp` for that energy bin. We
then need to loop over the number of channel sets. For each
channel set, we look up the first channel into which flux
will be distributed as well as the number of channels in the
group. We then need to also loop over the these channels and
actually use the corresponding elements in the redistribution
matrix to redistribute the photon flux into channels.
All of this is basically a big bookkeeping exercise in making
sure to get the indices right.
Parameters
----------
spec : numpy.ndarray
The (model) spectrum to be folded
Returns
-------
counts : numpy.ndarray
The (model) spectrum after folding, in
counts/s/channel
# an empty array for the output counts
counts = np.zeros_like(spec)
# index for n_chan and f_chan incrementation
k = 0
# index for the response matrix incrementation
resp_idx = 0
# loop over all channels
for i in range(spec.shape[0]):
# this is the current bin in the flux spectrum to
# be folded
source_bin_i = spec[i]
# get the current number of groups
current_num_groups = self.n_grp[i]
# loop over the current number of groups
for j in range(current_num_groups):
current_num_chans = int(self.n_chan[k])
if current_num_chans == 0:
k += 1
resp_idx += current_num_chans
continue
else:
# get the right index for the start of the counts array
# to put the data into
counts_idx = int(self.f_chan[k] - self.offset)
# this is the current number of channels to use
k += 1
# add the flux to the subarray of the counts array that starts with
# counts_idx and runs over current_num_chans channels
counts[counts_idx:counts_idx+current_num_chans] += self.matrix[resp_idx:resp_idx+current_num_chans] * \
np.float(source_bin_i)
# iterate the response index for next round
resp_idx += current_num_chans
return counts[:self.detchans]
Explanation: They are! It looks like for this particular RXTE data set, it's working!
Making an ARF/RMF Class
the ARF and RMF code would live well in a class, so let's wrap it into a class:
End of explanation
rmf_new = RMF(datadir+"rxte_hexte_97mar20c_pwa.rmf")
m_rmf = rmf_new.apply_rmf(m_arf)
Explanation: Let's make an object of that class and then make another model with the RMF applied:
End of explanation
plt.figure(figsize=(10, 6))
plt.plot(m_rmf)
#plt.plot(m_rmf_v)
Explanation: Hooray! What does the total spectrum look like?
End of explanation
from clarsach import respond
rmf_c = respond.RMF(datadir+"rxte_hexte_97mar20c_pwa.rmf")
m_rmf_c = rmf_new.apply_rmf(m_arf)
np.allclose(m_rmf_c, m_rmf2)
plt.figure()
plt.plot(bin_mid, counts, label="data")
plt.plot(bin_mid, m_rmf_c*exposure, label="model", alpha=0.5)
Explanation: There is, of course, also an implementation in clarsach:
End of explanation |
8,518 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fuzzy Logic for Python 3
The doctests in the modules should give a good idea how to use things by themselves, while here are some examples how to use everything together.
Installation
First things first
Step1: let's show off a few interesting functions ;)
Step2: Domains
After specifying the domain and assigning sets, calling a domain with a value returns a dict of memberships of the sets in that domain.
Step3: Many times you end up with sets that never hit 1 like with sigmoids, triangular funcs that hit the border of the domain or after operations with other sets. Then it is often needed to normalize (define max(set) == 1). Note that Set.normalized() returns a set that (unlike other set ops) is already bound to the domain and given the name "normalized_{set.name}". This can't be circumvented because normalizing is only defined on a given domain.
Step4: Inference
After measuring a RL value and mapping it to sets within a domain, it is normally needed to translate the result to another domain that corresponds to some sort of control mechanism. This translation or mapping is called inference and is rooted in the logical conclusion operation A => B, for example
Step6: There are a few things to note in this example. Firstly, make sure to pass in the values as a single dictionary at the end, not as parameters.
If a rule has zero weight - in this example a temp of 22 results in cold weighted with S(0,20) as 0 - the Rule returns None, which makes sure this condition is ignored in subsequent calculations. Also you might notice that the result is a value of 1633, which is way more than motor.fast with R(1000,1500) would suggest. However, since the domain motor is defined between 0 and 2000, the center of gravity method used for evaluation takes many of the values between 1500 and 2000 weighted with 1 into account, giving this slightly unexpected result.
Writing a single Rule or a few this way is explicit and simple to understand, but considering only 2 input variables with 3 Sets each, this already means 9 lines of code, with each element repeated 3 times. Also, most resources like books present these rules as tables or spreadsheets, which can be overly complicated or at least annoying to rewrite as explicit Rules.
To help with such cases, I've added the ability to transform 2D tables into Rules. This functionality uses pandas to import a table written as multi-line string for now, but it would be easy to accept Excel spreadsheets, csv and all the other formats supported by pandas. However, this functionality comes with three potential drawbacks | Python Code:
from matplotlib import pyplot
pyplot.rc("figure", figsize=(10, 10))
from fuzzylogic.classes import Domain
from fuzzylogic.functions import R, S, alpha
T = Domain("test", 0, 30, res=0.1)
T.up = R(1,10)
T.up.plot()
T.down = S(20, 29)
T.down.plot()
T.polygon = T.up & T.down
T.polygon.plot()
T.inv_polygon = ~T.polygon
T.inv_polygon.plot()
Explanation: Fuzzy Logic for Python 3
The doctests in the modules should give a good idea how to use things by themselves, while here are some examples how to use everything together.
Installation
First things first: To install fuzzylogic, just enter python -m pip install fuzzylogic and you should be good to go!
Functions and Sets
Defining a domain with its range and resolution should be trivial since most real world instruments come with those specifications. However, defining the fuzzy sets within those domains is where the fun begins as only a human can tell whether something is "hot" or "not", right?
Why the distinction? Functions only map values, nothing special there at all - which is good for testing and performance. Sets on the other hand implement logical operations that have special python syntax, which makes it easy to work with but a little more difficult to test and adds some performance overhead. So, sets are for abstraction and easy handling, functions for performance.
Domains
You can use (I do so regularly) fuzzy functions outside any specific fuzzy context. However, if you want to take advantage of the logic of fuzzy sets, plot stuff or defuzzyfy values, you need to use Domains. Domains and Sets are special in a way that they intrically rely on each other. This is enforced by how assignments work. Regular Domain attributes are the sets that were assigned to the domain. Also, if just a function is assigned it is automatically wrapped in a Set.
End of explanation
from fuzzylogic.classes import Domain, Set
from fuzzylogic.functions import (sigmoid, gauss, trapezoid,
triangular_sigmoid, rectangular)
T = Domain("test", 0, 70, res=0.1)
T.sigmoid = sigmoid(1,1,20)
T.sigmoid.plot()
T.gauss = gauss(10, 0.01, c_m=0.9)
T.gauss.plot()
T.trapezoid = trapezoid(25, 30, 35, 40, c_m=0.9)
T.trapezoid.plot()
T.triangular_sigmoid = triangular_sigmoid(40, 70, c=55)
T.triangular_sigmoid.plot()
Explanation: let's show off a few interesting functions ;)
End of explanation
from fuzzylogic.classes import Domain
from fuzzylogic.functions import alpha, triangular
from fuzzylogic.hedges import plus, minus, very
numbers = Domain("numbers", 0, 20, res=0.1)
close_to_10 = alpha(floor=0.2, ceiling=0.8, func=triangular(0, 20))
close_to_5 = triangular(1, 10)
numbers.foo = minus(close_to_5)
numbers.bar = very(close_to_10)
numbers.bar.plot()
numbers.foo.plot()
numbers.baz = numbers.foo + numbers.bar
numbers.baz.plot()
numbers(8)
from fuzzylogic.classes import Domain
from fuzzylogic.functions import bounded_sigmoid
T = Domain("temperature", 0, 100, res=0.1)
T.cold = bounded_sigmoid(5,15, inverse=True)
T.cold.plot()
T.hot = bounded_sigmoid(20, 40)
T.hot.plot()
T.warm = ~T.hot & ~T.cold
T.warm.plot()
T(10)
Explanation: Domains
After specifying the domain and assigning sets, calling a domain with a value returns a dict of memberships of the sets in that domain.
End of explanation
from fuzzylogic.classes import Domain
from fuzzylogic.functions import alpha, trapezoid
N = Domain("numbers", 0, 6, res=0.01)
N.two_or_so = alpha(floor=0, ceiling=0.7, func=trapezoid(0, 1.9, 2.1, 4))
N.two_or_so.plot()
N.x = N.two_or_so.normalized()
N.x.plot()
Explanation: Many times you end up with sets that never hit 1 like with sigmoids, triangular funcs that hit the border of the domain or after operations with other sets. Then it is often needed to normalize (define max(set) == 1). Note that Set.normalized() returns a set that (unlike other set ops) is already bound to the domain and given the name "normalized_{set.name}". This can't be circumvented because normalizing is only defined on a given domain.
End of explanation
from fuzzylogic.classes import Domain, Set, Rule
from fuzzylogic.hedges import very
from fuzzylogic.functions import R, S
temp = Domain("Temperature", -80, 80)
hum = Domain("Humidity", 0, 100)
motor = Domain("Speed", 0, 2000)
temp.cold = S(0,20)
temp.hot = R(15,30)
hum.dry = S(20,50)
hum.wet = R(40,70)
motor.fast = R(1000,1500)
motor.slow = ~motor.fast
R1 = Rule({(temp.hot, hum.dry): motor.fast})
R2 = Rule({(temp.cold, hum.dry): very(motor.slow)})
R3 = Rule({(temp.hot, hum.wet): very(motor.fast)})
R4 = Rule({(temp.cold, hum.wet): motor.slow})
rules = Rule({(temp.hot, hum.dry): motor.fast,
(temp.cold, hum.dry): very(motor.slow),
(temp.hot, hum.wet): very(motor.fast),
(temp.cold, hum.wet): motor.slow,
})
rules == R1 | R2 | R3 | R4 == sum([R1, R2, R3, R4])
values = {hum: 45, temp: 22}
print(R1(values), R2(values), R3(values), R4(values), "=>", rules(values))
Explanation: Inference
After measuring a RL value and mapping it to sets within a domain, it is normally needed to translate the result to another domain that corresponds to some sort of control mechanism. This translation or mapping is called inference and is rooted in the logical conclusion operation A => B, for example: If it rains then the street is wet.
The street may be wet for a number of reasons, but if it rains it will be wet for sure. This IF A THEN B can also be written as
(A AND B) OR NOT(A AND TRUE). This may look straight forward for boolean logic, but since we are not just dealing with True and False, there are a number of ways in fuzzy logic to actually implement this.
Here is a simple but fully working example with all moving parts, demonstrating the use in the context of an HVAC system.
It also demonstrates the three different ways to set up complex combinations of rules: you can either define each rule one by one and then combine them via the | operator, or you can put the rules into a list and use sum(..) to combine them into one in a single step, or you can define one big and complex rule right from the start. Which way best suits your needs depends on how complex each rule is and how/where you define them in your code and whether you need to use them in different places in different combinations.
End of explanation
table =
hum.dry hum.wet
temp.cold very(motor.slow) motor.slow
temp.hot motor.fast very(motor.fast)
from fuzzylogic.classes import rule_from_table
table_rules = rule_from_table(table, globals())
assert table_rules == rules
Explanation: There are a few things to note in this example. Firstly, make sure to pass in the values as a single dictionary at the end, not as parameters.
If a rule has zero weight - in this example a temp of 22 results in cold weighted with S(0,20) as 0 - the Rule returns None, which makes sure this condition is ignored in subsequent calculations. Also you might notice that the result is a value of 1633, which is way more than motor.fast with R(1000,1500) would suggest. However, since the domain motor is defined between 0 and 2000, the center of gravity method used for evaluation takes many of the values between 1500 and 2000 weighted with 1 into account, giving this slightly unexpected result.
Writing a single Rule or a few this way is explicit and simple to understand, but considering only 2 input variables with 3 Sets each, this already means 9 lines of code, with each element repeated 3 times. Also, most resources like books present these rules as tables or spreadsheets, which can be overly complicated or at least annoying to rewrite as explicit Rules.
To help with such cases, I've added the ability to transform 2D tables into Rules. This functionality uses pandas to import a table written as multi-line string for now, but it would be easy to accept Excel spreadsheets, csv and all the other formats supported by pandas. However, this functionality comes with three potential drawbacks: The content of cells are strings - which has no IDE support (so typos might slip through), which are eval()ed - which can pose a security risk if the table is provided by an untrusted source. Thirdly, only rules with 2 input variables can be modelled this way, unlike 'classic' Rules which allow an unlimited number of input variables.
Please note, the second argument to this function must be the namespace where all Domains, Sets and hedges are defined that are used within the table. This is due to the fact that the evaluation of those names actually happens in a module where those names normally aren't defined.
End of explanation |
8,519 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Fully-Connected Neural Nets
In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.
In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a forward and a backward function. The forward function will receive inputs, weights, and other parameters and will return both an output and a cache object storing data needed for the backward pass, like this
Step4: Affine layer
Step5: Affine layer
Step6: ReLU layer
Step7: ReLU layer
Step8: "Sandwich" layers
There are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file cs231n/layer_utils.py.
For now take a look at the affine_relu_forward and affine_relu_backward functions, and run the following to numerically gradient check the backward pass
Step9: Loss layers
Step10: Two-layer network
In the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.
Open the file cs231n/classifiers/fc_net.py and complete the implementation of the TwoLayerNet class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation.
Step11: Solver
In the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.
Open the file cs231n/solver.py and read through it to familiarize yourself with the API. After doing so, use a Solver instance to train a TwoLayerNet that achieves at least 50% accuracy on the validation set.
Step12: Multilayer network
Next you will implement a fully-connected network with an arbitrary number of hidden layers.
Read through the FullyConnectedNet class in the file cs231n/classifiers/fc_net.py.
Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon.
Initial loss and gradient check
As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?
For gradient checking, you should expect to see errors around 1e-6 or less.
Step13: As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs.
Step14: Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs.
Step15: Inline question
Step16: Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster.
Step17: RMSProp and Adam
RMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.
In the file cs231n/optim.py, implement the RMSProp update rule in the rmsprop function and implement the Adam update rule in the adam function, and check your implementations using the tests below.
[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop
Step18: Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules
Step19: Train a good model!
Train the best fully-connected model that you can on CIFAR-10, storing your best model in the best_model variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.
If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.
You might find it useful to complete the BatchNormalization.ipynb and Dropout.ipynb notebooks before completing this part, since those techniques can help you train powerful models.
Step20: Test you model
Run your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. | Python Code:
# As usual, a bit of setup
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from cs231n.solver import Solver
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading external modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
def rel_error(x, y):
returns relative error
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
# Load the (preprocessed) CIFAR10 data.
data = get_CIFAR10_data()
for k, v in data.iteritems():
print '%s: ' % k, v.shape
Explanation: Fully-Connected Neural Nets
In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.
In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a forward and a backward function. The forward function will receive inputs, weights, and other parameters and will return both an output and a cache object storing data needed for the backward pass, like this:
```python
def layer_forward(x, w):
Receive inputs x and weights w
# Do some computations ...
z = # ... some intermediate value
# Do some more computations ...
out = # the output
cache = (x, w, z, out) # Values we need to compute gradients
return out, cache
```
The backward pass will receive upstream derivatives and the cache object, and will return gradients with respect to the inputs and weights, like this:
```python
def layer_backward(dout, cache):
Receive derivative of loss with respect to outputs and cache,
and compute derivative with respect to inputs.
# Unpack cache values
x, w, z, out = cache
# Use values in cache to compute derivatives
dx = # Derivative of loss with respect to x
dw = # Derivative of loss with respect to w
return dx, dw
```
After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.
In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch Normalization as a tool to more efficiently optimize deep networks.
End of explanation
# Test the affine_forward function
num_inputs = 2
input_shape = (4, 5, 6)
output_dim = 3
input_size = num_inputs * np.prod(input_shape)
weight_size = output_dim * np.prod(input_shape)
x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape)
w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim)
b = np.linspace(-0.3, 0.1, num=output_dim)
out, _ = affine_forward(x, w, b)
correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297],
[ 3.25553199, 3.5141327, 3.77273342]])
# Compare your output with ours. The error should be around 1e-9.
print 'Testing affine_forward function:'
print 'difference: ', rel_error(out, correct_out)
Explanation: Affine layer: foward
Open the file cs231n/layers.py and implement the affine_forward function.
Once you are done you can test your implementaion by running the following:
End of explanation
# Test the affine_backward function
x = np.random.randn(10, 2, 3)
w = np.random.randn(6, 5)
b = np.random.randn(5)
dout = np.random.randn(10, 5)
dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout)
dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout)
db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout)
_, cache = affine_forward(x, w, b)
dx, dw, db = affine_backward(dout, cache)
# The error should be around 1e-10
print 'Testing affine_backward function:'
print 'dx error: ', rel_error(dx_num, dx)
print 'dw error: ', rel_error(dw_num, dw)
print 'db error: ', rel_error(db_num, db)
Explanation: Affine layer: backward
Now implement the affine_backward function and test your implementation using numeric gradient checking.
End of explanation
# Test the relu_forward function
x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4)
out, _ = relu_forward(x)
correct_out = np.array([[ 0., 0., 0., 0., ],
[ 0., 0., 0.04545455, 0.13636364,],
[ 0.22727273, 0.31818182, 0.40909091, 0.5, ]])
# Compare your output with ours. The error should be around 1e-8
print 'Testing relu_forward function:'
print 'difference: ', rel_error(out, correct_out)
Explanation: ReLU layer: forward
Implement the forward pass for the ReLU activation function in the relu_forward function and test your implementation using the following:
End of explanation
x = np.random.randn(10, 10)
dout = np.random.randn(*x.shape)
dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout)
_, cache = relu_forward(x)
dx = relu_backward(dout, cache)
# The error should be around 1e-12
print 'Testing relu_backward function:'
print 'dx error: ', rel_error(dx_num, dx)
Explanation: ReLU layer: backward
Now implement the backward pass for the ReLU activation function in the relu_backward function and test your implementation using numeric gradient checking:
End of explanation
from cs231n.layer_utils import affine_relu_forward, affine_relu_backward
x = np.random.randn(2, 3, 4)
w = np.random.randn(12, 10)
b = np.random.randn(10)
dout = np.random.randn(2, 10)
out, cache = affine_relu_forward(x, w, b)
dx, dw, db = affine_relu_backward(dout, cache)
dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout)
dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout)
db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout)
print 'Testing affine_relu_forward:'
print 'dx error: ', rel_error(dx_num, dx)
print 'dw error: ', rel_error(dw_num, dw)
print 'db error: ', rel_error(db_num, db)
Explanation: "Sandwich" layers
There are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file cs231n/layer_utils.py.
For now take a look at the affine_relu_forward and affine_relu_backward functions, and run the following to numerically gradient check the backward pass:
End of explanation
num_classes, num_inputs = 10, 50
x = 0.001 * np.random.randn(num_inputs, num_classes)
y = np.random.randint(num_classes, size=num_inputs)
dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False)
loss, dx = svm_loss(x, y)
# Test svm_loss function. Loss should be around 9 and dx error should be 1e-9
print 'Testing svm_loss:'
print 'loss: ', loss
print 'dx error: ', rel_error(dx_num, dx)
dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False)
loss, dx = softmax_loss(x, y)
# Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8
print '\nTesting softmax_loss:'
print 'loss: ', loss
print 'dx error: ', rel_error(dx_num, dx)
Explanation: Loss layers: Softmax and SVM
You implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in cs231n/layers.py.
You can make sure that the implementations are correct by running the following:
End of explanation
N, D, H, C = 3, 5, 50, 7
X = np.random.randn(N, D)
y = np.random.randint(C, size=N)
std = 1e-2
model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std)
print 'Testing initialization ... '
W1_std = abs(model.params['W1'].std() - std)
b1 = model.params['b1']
W2_std = abs(model.params['W2'].std() - std)
b2 = model.params['b2']
assert W1_std < std / 10, 'First layer weights do not seem right'
assert np.all(b1 == 0), 'First layer biases do not seem right'
assert W2_std < std / 10, 'Second layer weights do not seem right'
assert np.all(b2 == 0), 'Second layer biases do not seem right'
print 'Testing test-time forward pass ... '
model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H)
model.params['b1'] = np.linspace(-0.1, 0.9, num=H)
model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C)
model.params['b2'] = np.linspace(-0.9, 0.1, num=C)
X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T
scores = model.loss(X)
correct_scores = np.asarray(
[[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096],
[12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143],
[12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]])
scores_diff = np.abs(scores - correct_scores).sum()
assert scores_diff < 1e-6, 'Problem with test-time forward pass'
print 'Testing training loss (no regularization)'
y = np.asarray([0, 5, 1])
loss, grads = model.loss(X, y)
correct_loss = 3.4702243556
assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss'
model.reg = 1.0
loss, grads = model.loss(X, y)
correct_loss = 26.5948426952
assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss'
for reg in [0.0, 0.7]:
print 'Running numeric gradient check with reg = ', reg
model.reg = reg
loss, grads = model.loss(X, y)
for name in sorted(grads):
f = lambda _: model.loss(X, y)[0]
grad_num = eval_numerical_gradient(f, model.params[name], verbose=False)
print '%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))
Explanation: Two-layer network
In the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.
Open the file cs231n/classifiers/fc_net.py and complete the implementation of the TwoLayerNet class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation.
End of explanation
model = TwoLayerNet()
solver = None
##############################################################################
# TODO: Use a Solver instance to train a TwoLayerNet that achieves at least #
# 50% accuracy on the validation set. #
##############################################################################
solver = Solver(model, data, update_rule='sgd', optim_config={'learning_rate': 1e-3}, lr_decay=0.95, num_epochs=10, batch_size=100, print_every=100)
solver.train()
##############################################################################
# END OF YOUR CODE #
##############################################################################
# Run this cell to visualize training loss and train / val accuracy
plt.subplot(2, 1, 1)
plt.title('Training loss')
plt.plot(solver.loss_history, 'o')
plt.xlabel('Iteration')
plt.subplot(2, 1, 2)
plt.title('Accuracy')
plt.plot(solver.train_acc_history, '-o', label='train')
plt.plot(solver.val_acc_history, '-o', label='val')
plt.plot([0.5] * len(solver.val_acc_history), 'k--')
plt.xlabel('Epoch')
plt.legend(loc='lower right')
plt.gcf().set_size_inches(15, 12)
plt.show()
Explanation: Solver
In the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.
Open the file cs231n/solver.py and read through it to familiarize yourself with the API. After doing so, use a Solver instance to train a TwoLayerNet that achieves at least 50% accuracy on the validation set.
End of explanation
N, D, H1, H2, C = 2, 15, 20, 30, 10
X = np.random.randn(N, D)
y = np.random.randint(C, size=(N,))
for reg in [0, 3.14]:
print 'Running check with reg = ', reg
model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,
reg=reg, weight_scale=5e-2, dtype=np.float64)
loss, grads = model.loss(X, y)
print 'Initial loss: ', loss
for name in sorted(grads):
f = lambda _: model.loss(X, y)[0]
grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)
print '%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))
Explanation: Multilayer network
Next you will implement a fully-connected network with an arbitrary number of hidden layers.
Read through the FullyConnectedNet class in the file cs231n/classifiers/fc_net.py.
Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon.
Initial loss and gradient check
As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?
For gradient checking, you should expect to see errors around 1e-6 or less.
End of explanation
# TODO: Use a three-layer Net to overfit 50 training examples.
num_train = 50
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
weight_scale = 1e-2
learning_rate = 1e-2
model = FullyConnectedNet([100, 100],
weight_scale=weight_scale, dtype=np.float64)
solver = Solver(model, small_data,
print_every=10, num_epochs=20, batch_size=25,
update_rule='sgd',
optim_config={
'learning_rate': learning_rate,
}
)
solver.train()
plt.plot(solver.loss_history, 'o')
plt.title('Training loss history')
plt.xlabel('Iteration')
plt.ylabel('Training loss')
plt.show()
Explanation: As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs.
End of explanation
# TODO: Use a five-layer Net to overfit 50 training examples.
num_train = 50
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
learning_rate = 1e-3
weight_scale = 1e-1
model = FullyConnectedNet([100, 100, 100, 100],
weight_scale=weight_scale, dtype=np.float64)
solver = Solver(model, small_data,
print_every=10, num_epochs=20, batch_size=25,
update_rule='sgd',
optim_config={
'learning_rate': learning_rate,
}
)
solver.train()
plt.plot(solver.loss_history, 'o')
plt.title('Training loss history')
plt.xlabel('Iteration')
plt.ylabel('Training loss')
plt.show()
Explanation: Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs.
End of explanation
from cs231n.optim import sgd_momentum
N, D = 4, 5
w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D)
dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D)
v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D)
config = {'learning_rate': 1e-3, 'velocity': v}
next_w, _ = sgd_momentum(w, dw, config=config)
expected_next_w = np.asarray([
[ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789],
[ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526],
[ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263],
[ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]])
expected_velocity = np.asarray([
[ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158],
[ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105],
[ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053],
[ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]])
print 'next_w error: ', rel_error(next_w, expected_next_w)
print 'velocity error: ', rel_error(expected_velocity, config['velocity'])
Explanation: Inline question:
Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net?
Answer:
[FILL THIS IN]
Update rules
So far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD.
SGD+Momentum
Stochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochstic gradient descent.
Open the file cs231n/optim.py and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function sgd_momentum and run the following to check your implementation. You should see errors less than 1e-8.
End of explanation
num_train = 4000
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
solvers = {}
for update_rule in ['sgd', 'sgd_momentum']:
print 'running with ', update_rule
model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2)
solver = Solver(model, small_data,
num_epochs=5, batch_size=100,
update_rule=update_rule,
optim_config={
'learning_rate': 1e-2,
},
verbose=True)
solvers[update_rule] = solver
solver.train()
print
plt.subplot(3, 1, 1)
plt.title('Training loss')
plt.xlabel('Iteration')
plt.subplot(3, 1, 2)
plt.title('Training accuracy')
plt.xlabel('Epoch')
plt.subplot(3, 1, 3)
plt.title('Validation accuracy')
plt.xlabel('Epoch')
for update_rule, solver in solvers.iteritems():
plt.subplot(3, 1, 1)
plt.plot(solver.loss_history, 'o', label=update_rule)
plt.subplot(3, 1, 2)
plt.plot(solver.train_acc_history, '-o', label=update_rule)
plt.subplot(3, 1, 3)
plt.plot(solver.val_acc_history, '-o', label=update_rule)
for i in [1, 2, 3]:
plt.subplot(3, 1, i)
plt.legend(loc='upper center', ncol=4)
plt.gcf().set_size_inches(15, 15)
plt.show()
Explanation: Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster.
End of explanation
# Test RMSProp implementation; you should see errors less than 1e-7
from cs231n.optim import rmsprop
N, D = 4, 5
w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D)
dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D)
cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D)
config = {'learning_rate': 1e-2, 'cache': cache}
next_w, _ = rmsprop(w, dw, config=config)
expected_next_w = np.asarray([
[-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247],
[-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774],
[ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447],
[ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]])
expected_cache = np.asarray([
[ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321],
[ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377],
[ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936],
[ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]])
print 'next_w error: ', rel_error(expected_next_w, next_w)
print 'cache error: ', rel_error(expected_cache, config['cache'])
# Test Adam implementation; you should see errors around 1e-7 or less
from cs231n.optim import adam
N, D = 4, 5
w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D)
dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D)
m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D)
v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D)
config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5}
next_w, _ = adam(w, dw, config=config)
expected_next_w = np.asarray([
[-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977],
[-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929],
[ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969],
[ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]])
expected_v = np.asarray([
[ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,],
[ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,],
[ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,],
[ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]])
expected_m = np.asarray([
[ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474],
[ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316],
[ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158],
[ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]])
print 'next_w error: ', rel_error(expected_next_w, next_w)
print 'v error: ', rel_error(expected_v, config['v'])
print 'm error: ', rel_error(expected_m, config['m'])
Explanation: RMSProp and Adam
RMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.
In the file cs231n/optim.py, implement the RMSProp update rule in the rmsprop function and implement the Adam update rule in the adam function, and check your implementations using the tests below.
[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).
[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015.
End of explanation
learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3}
for update_rule in ['adam', 'rmsprop']:
print 'running with ', update_rule
model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2)
solver = Solver(model, small_data,
num_epochs=5, batch_size=100,
update_rule=update_rule,
optim_config={
'learning_rate': learning_rates[update_rule]
},
verbose=True)
solvers[update_rule] = solver
solver.train()
print
plt.subplot(3, 1, 1)
plt.title('Training loss')
plt.xlabel('Iteration')
plt.subplot(3, 1, 2)
plt.title('Training accuracy')
plt.xlabel('Epoch')
plt.subplot(3, 1, 3)
plt.title('Validation accuracy')
plt.xlabel('Epoch')
for update_rule, solver in solvers.iteritems():
plt.subplot(3, 1, 1)
plt.plot(solver.loss_history, 'o', label=update_rule)
plt.subplot(3, 1, 2)
plt.plot(solver.train_acc_history, '-o', label=update_rule)
plt.subplot(3, 1, 3)
plt.plot(solver.val_acc_history, '-o', label=update_rule)
for i in [1, 2, 3]:
plt.subplot(3, 1, i)
plt.legend(loc='upper center', ncol=4)
plt.gcf().set_size_inches(15, 15)
plt.show()
Explanation: Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules:
End of explanation
best_model = None
################################################################################
# TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might #
# batch normalization and dropout useful. Store your best model in the #
# best_model variable. #
################################################################################
pass
################################################################################
# END OF YOUR CODE #
################################################################################
Explanation: Train a good model!
Train the best fully-connected model that you can on CIFAR-10, storing your best model in the best_model variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.
If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.
You might find it useful to complete the BatchNormalization.ipynb and Dropout.ipynb notebooks before completing this part, since those techniques can help you train powerful models.
End of explanation
y_test_pred = np.argmax(best_model.loss(X_test), axis=1)
y_val_pred = np.argmax(best_model.loss(X_val), axis=1)
print 'Validation set accuracy: ', (y_val_pred == y_val).mean()
print 'Test set accuracy: ', (y_test_pred == y_test).mean()
Explanation: Test you model
Run your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set.
End of explanation |
8,520 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
discretize a point in a (3,3) matrix
Step1: randomwalk each point for 1 day equivalent
Step2: make a grid from a scatter of many points
Step3: Find maximum time step without leaking mosquitos from the 3x3 grid
Step4: matrix generator for geting all possible combinations of matrix
<pre>
0 | 3 | 5
1 | X | 6
2 | 4 | 7
</pre> | Python Code:
def findquadrant(point,size):
y,x = point
halfsize = size/2
if x < -halfsize:
if y > halfsize: return [0,0]
if y < -halfsize: return [2,0]
return [1,0]
if x > halfsize:
if y > halfsize: return [0,2]
if y < -halfsize: return [2,2]
return [1,2]
if y > halfsize: return [0,1]
if y < -halfsize: return [2,1]
return [1,1]
def findStep(points, box):
tempo = 0
while check_howmany(points, box) < 0.05:
for i in points:
a = uniform(0, 2*pi)
vvar, hvar = V*dt*sin(a), V*dt*cos(a)
i[0] += vvar; i[1] += hvar
tempo += dt
return tempo
Explanation: discretize a point in a (3,3) matrix
End of explanation
def randomWalk(points, nonacessquadrants, time):
dt = 1
for atime in range(time):
for i in points:
a = uniform(0, 2*pi)
vvar, hvar = V*dt*sin(a), V*dt*cos(a)
i[0] += vvar; i[1] += hvar
#if findquadrant(i, size) in nonacessquadrants: i[0] -= 2*vvar
#if findquadrant(i, size) in nonacessquadrants: i[0] += 2*vvar; i[1] -= 2*hvar
#if findquadrant(i, size) in nonacessquadrants: i[0] -= 2*vvar
return points
Explanation: randomwalk each point for 1 day equivalent
End of explanation
def gridify(somelist, size):
shape = (3,3)
grid = np.zeros(shape)
for point in somelist:
quadrant = findquadrant(point,size)
grid[quadrant[0]][quadrant[1]] += 1
grid = grid/grid.sum()
return np.array(grid)
V = 300/60 #meters per minute
dt = 1 #min
npoints = 40000
size = 68
def newpoints(n):
return np.array([[uniform(-size/2,size/2),uniform(-size/2,size/2)] for i in range(n)])
Explanation: make a grid from a scatter of many points
End of explanation
%%time
def MaxStep(box):
a = 0
for i in range(7):
a += findStep(newpoints(npoints), box)
a = a/5
for i in range(int(a),0, -1):
if 24*60 % i == 0: return i
return("deu ruim")
b= MaxStep(68.66)
a = 24*60/b
print(a)
Explanation: Find maximum time step without leaking mosquitos from the 3x3 grid
End of explanation
%%time
allmatrices = list(product(*(repeat((0, 1), 8))))
print(len(allmatrices))
dictionary_matrix_to_num = {}
dict_num_to_weights = {}
nowalls = gridify(randomWalk(newpoints(npoints), [], MaxStep(68.66)), size)
avgcorner = (nowalls[0,0]+nowalls[2,2]+nowalls[2,0]+nowalls[0,2])/4
avgwall = (nowalls[1,0]+nowalls[0,1]+nowalls[2,1]+nowalls[1,2])/4
nowalls[0,0], nowalls[2,2], nowalls[2,0], nowalls[0,2] = [avgcorner for i in range(4)]
nowalls[1,0], nowalls[0,1], nowalls[2,1], nowalls[1,2] = [avgwall for i in range(4)]
print(nowalls)
for index, case in enumerate(allmatrices):
dictionary_matrix_to_num[case] = index
multiplier = np.ones((3,3))
if case[0] == 1: multiplier[0,0] = 0
if case[1] == 1: multiplier[1,0] = 0
if case[2] == 1: multiplier[2,0] = 0
if case[3] == 1: multiplier[0,1] = 0
if case[4] == 1: multiplier[2,1] = 0
if case[5] == 1: multiplier[0,2] = 0
if case[6] == 1: multiplier[1,2] = 0
if case[7] == 1: multiplier[2,2] = 0
if index%25 == 0: print(index, case)
dict_num_to_weights[index] = nowalls*multiplier/(nowalls*multiplier).sum()
a = dict_num_to_weights[145]
print(a)
plt.imshow(dict_num_to_weights[145])
plt.show()
import pickle as pkl
MyDicts = [dictionary_matrix_to_num, dict_num_to_weights]
pkl.dump( MyDicts, open( "myDicts.p", "wb" ) )
#to read the pickled dicts use:
# dictionary_matrix_to_num, dict_num_to_weights = pkl.load( open ("myDicts.p", "rb") )
a = [(1,2), (3,4)]
a, b = zip(*a)
a
Explanation: matrix generator for geting all possible combinations of matrix
<pre>
0 | 3 | 5
1 | X | 6
2 | 4 | 7
</pre>
End of explanation |
8,521 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stage 5, Report
https
Step1: Filling in Missing Values
Step2: Generating Features
Here, we generate all the features we decided upon after our final iteration of cross validation and debugging. We only use the relevant subset of all these features in the reported iterations below.
Step3: Generate training set
Step4: Joining Tables
Step5: Adventure Time! | Python Code:
import py_entitymatching as em
import os
import pandas as pd
# specify filepaths for tables A and B.
path_A = 'tableA.csv'
path_B = 'tableB.csv'
# read table A; table A has 'ID' as the key attribute
A = em.read_csv_metadata(path_A, key='id')
# read table B; table B has 'ID' as the key attribute
B = em.read_csv_metadata(path_B, key='id')
Explanation: Stage 5, Report
https://github.com/anhaidgroup/py_entitymatching/blob/master/notebooks/vldb_demo/Demo_notebook_v6.ipynb
End of explanation
# Impute missing values
# Manually set metadata properties, as current py_entitymatching.impute_table()
# requires 'fk_ltable', 'fk_rtable', 'ltable', 'rtable' properties
em.set_property(A, 'fk_ltable', 'id')
em.set_property(A, 'fk_rtable', 'id')
em.set_property(A, 'ltable', A)
em.set_property(A, 'rtable', A)
A_all_attrs = list(A.columns.values)
A_impute_attrs = ['year','min_num_players','max_num_players','min_gameplay_time','max_gameplay_time','min_age']
A_exclude_attrs = list(set(A_all_attrs) - set(A_impute_attrs))
A1 = em.impute_table(A, exclude_attrs=A_exclude_attrs, missing_val='NaN', strategy='most_frequent', axis=0, val_all_nans=0, verbose=True)
# Compare number of missing values to check the results
print(sum(A['min_num_players'].isnull()))
print(sum(A1['min_num_players'].isnull()))
# Do the same thing for B
em.set_property(B, 'fk_ltable', 'id')
em.set_property(B, 'fk_rtable', 'id')
em.set_property(B, 'ltable', B)
em.set_property(B, 'rtable', B)
B_all_attrs = list(B.columns.values)
# TODO: add 'min_age'
B_impute_attrs = ['year','min_num_players','max_num_players','min_gameplay_time','max_gameplay_time']
B_exclude_attrs = list(set(B_all_attrs) - set(B_impute_attrs))
B1 = em.impute_table(B, exclude_attrs=B_exclude_attrs, missing_val='NaN', strategy='most_frequent', axis=0, val_all_nans=0, verbose=True)
# Compare number of missing values to check the results
print(sum(B['min_num_players'].isnull()))
print(sum(B1['min_num_players'].isnull()))
# Load the pre-labeled data
S = em.read_csv_metadata('sample_labeled.csv',
key='_id',
ltable=A1, rtable=B1,
fk_ltable='ltable_id', fk_rtable='rtable_id')
path_total_cand_set = 'candidate_set_C1.csv'
total_cand_set = em.read_csv_metadata(path_total_cand_set,
key='_id',
ltable=A1, rtable=B1,
fk_ltable='ltable_id', fk_rtable='rtable_id')
# Split S into I an J
IJ = em.split_train_test(S, train_proportion=0.75, random_state=35)
I = IJ['train']
J = IJ['test']
corres = em.get_attr_corres(A1, B1)
Explanation: Filling in Missing Values
End of explanation
# Generate a set of features
#import pdb; pdb.set_trace();
import py_entitymatching.feature.attributeutils as au
import py_entitymatching.feature.simfunctions as sim
import py_entitymatching.feature.tokenizers as tok
ltable = A1
rtable = B1
# Get similarity functions for generating the features for matching
sim_funcs = sim.get_sim_funs_for_matching()
# Get tokenizer functions for generating the features for matching
tok_funcs = tok.get_tokenizers_for_matching()
# Get the attribute types of the input tables
attr_types_ltable = au.get_attr_types(ltable)
attr_types_rtable = au.get_attr_types(rtable)
# Get the attribute correspondence between the input tables
attr_corres = au.get_attr_corres(ltable, rtable)
print(attr_types_ltable['name'])
print(attr_types_rtable['name'])
attr_types_ltable['name'] = 'str_bt_5w_10w'
attr_types_rtable['name'] = 'str_bt_5w_10w'
# Get the features
F = em.get_features(ltable, rtable, attr_types_ltable,
attr_types_rtable, attr_corres,
tok_funcs, sim_funcs)
#F = em.get_features_for_matching(A1, B1)
print(F['feature_name'])
# Convert the I into a set of feature vectors using F
# Here, we add name edit distance as a feature
include_features_2 = [
'min_num_players_min_num_players_lev_dist',
'max_num_players_max_num_players_lev_dist',
'min_gameplay_time_min_gameplay_time_lev_dist',
'max_gameplay_time_max_gameplay_time_lev_dist',
'name_name_lev_dist'
]
F_2 = F.loc[F['feature_name'].isin(include_features_2)]
Explanation: Generating Features
Here, we generate all the features we decided upon after our final iteration of cross validation and debugging. We only use the relevant subset of all these features in the reported iterations below.
End of explanation
# Apply train, test set evaluation
I_table = em.extract_feature_vecs(I, feature_table=F_2, attrs_after='label', show_progress=False)
J_table = em.extract_feature_vecs(J, feature_table=F_2, attrs_after='label', show_progress=False)
total_cand_set_features = em.extract_feature_vecs(total_cand_set, feature_table=F_2, show_progress=False)
m = em.LogRegMatcher(name='LogReg', random_state=0)
m.fit(table=I_table, exclude_attrs=['_id', 'ltable_id', 'rtable_id','label'], target_attr='label')
total_cand_set_features['prediction'] = m.predict(
table=total_cand_set_features,
exclude_attrs=['_id', 'ltable_id', 'rtable_id'],
)
Explanation: Generate training set
End of explanation
# Join tables on matched tuples
match_tuples = total_cand_set_features[total_cand_set_features['prediction']==1]
match_tuples = match_tuples[['ltable_id','rtable_id']]
A1['ltable_id'] = A1['id']
B1['rtable_id'] = B1['id']
joined_tables = pd.merge(match_tuples, A1, how='left', on='ltable_id')
joined_tables = pd.merge(joined_tables, B1, how='left', on='rtable_id')
for n in A1.columns:
if not n in ['_id', 'ltable_id', 'rtable_id']:
joined_tables[n] = joined_tables.apply((lambda row: row[n+'_y'] if pd.isnull(row[n+'_x']) else row[n+'_x']), axis=1)
joined_tables = joined_tables.drop(n+'_x', axis=1).drop(n+'_y',axis=1)
joined_tables.to_csv('joined_table.csv')
joined_tables
Explanation: Joining Tables
End of explanation
import pandas as pd
import matplotlib as plt
from scipy.stats.stats import pearsonr
%matplotlib inline
joined_tables = pd.read_csv('new_joined_table.csv')
joined_tables.iloc[1:4].to_csv('4_tuples.csv')
from StringIO import StringIO
import prettytable
pt = prettytable.from_csv(open('new_joined_table.csv'))
print pt
joined_tables.columns
print 'Size: ' + str(len(joined_tables))
for c in joined_tables.columns:
print c + ' : '+ str(sum(joined_tables[c].isnull()))
print (len(joined_tables.iloc[12]))
# Rating vs year
joined_tables.groupby('year').agg({'year': 'mean','rating': 'mean'}).plot.scatter(x='year', y='rating')
joined_tables.plot.scatter(x='year', y='rating')
pearsonr(
joined_tables['year'][joined_tables['rating'].notnull()],
joined_tables['rating'][joined_tables['rating'].notnull()]
)
# Complexity weight vs year
joined_tables.plot.scatter(x='year', y='complexity_weight')
pearsonr(joined_tables['year'][joined_tables['complexity_weight'].notnull()],joined_tables['complexity_weight'][joined_tables['complexity_weight'].notnull()])
# Price mean vs year
joined_tables.groupby('year').agg({'year': 'mean','mean_price': 'mean'}).plot.scatter(x='year', y='mean_price')
joined_tables.plot.scatter(x='year', y='mean_price')
pearsonr(joined_tables['year'][joined_tables['mean_price'].notnull()],joined_tables['mean_price'][joined_tables['mean_price'].notnull()])
# Price mean vs rating
joined_tables.plot.scatter(x='rating', y='mean_price')
nonull = joined_tables['rating'].notnull() & joined_tables['mean_price'].notnull()
pearsonr(joined_tables['rating'][nonull],joined_tables['mean_price'][nonull])
# Num players vs complexity weight
joined_tables.plot.scatter(x='complexity_weight', y='min_num_players')
nonull = joined_tables['complexity_weight'].notnull() & joined_tables['min_num_players'].notnull()
pearsonr(joined_tables['complexity_weight'][nonull],joined_tables['min_num_players'][nonull])
#complexity weight vs gameplay time
joined_tables.plot.scatter(x='max_gameplay_time', y='complexity_weight')
nonull = joined_tables['complexity_weight'].notnull() & joined_tables['min_gameplay_time'].notnull()
pearsonr(joined_tables['complexity_weight'][nonull],joined_tables['min_gameplay_time'][nonull])
Explanation: Adventure Time!
End of explanation |
8,522 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Frequency-tagging
Step1: Data preprocessing
Due to a generally high SNR in SSVEP/vSSR, typical preprocessing steps
are considered optional. This doesn't mean, that a proper cleaning would not
increase your signal quality!
Raw data have FCz reference, so we will apply common-average rereferencing.
We will apply a 0.1 highpass filter.
Lastly, we will cut the data in 20 s epochs corresponding to the trials.
Step2: Frequency analysis
Now we compute the frequency spectrum of the EEG data.
You will already see the peaks at the stimulation frequencies and some of
their harmonics, without any further processing.
The 'classical' PSD plot will be compared to a plot of the SNR spectrum.
SNR will be computed as a ratio of the power in a given frequency bin
to the average power in its neighboring bins.
This procedure has two advantages over using the raw PSD
Step4: Calculate signal to noise ratio (SNR)
SNR - as we define it here - is a measure of relative power
Step5: Now we call the function to compute our SNR spectrum.
As described above, we have to define two parameters.
how many noise bins do we want?
do we want to skip the n bins directly next to the target bin?
Tweaking these parameters can drastically impact the resulting spectrum,
but mainly if you choose extremes.
E.g. if you'd skip very many neighboring bins, broad band power modulations
(such as the alpha peak) should reappear in the SNR spectrum.
On the other hand, if you skip none you might miss or smear peaks if the
induced power is distributed over two or more frequency bins (e.g. if the
stimulation frequency isn't perfectly constant, or you have very narrow
bins).
Here, we want to compare power at each bin with average power of the
three neighboring bins (on each side) and skip one bin directly next
to it.
Step6: Plot PSD and SNR spectra
Now we will plot grand average PSD (in blue) and SNR (in red) ± sd
for every frequency bin.
PSD is plotted on a log scale.
Step7: You can see that the peaks at the stimulation frequencies (12 Hz, 15 Hz)
and their harmonics are visible in both plots (just as the line noise at
50 Hz).
Yet, the SNR spectrum shows them more prominently as peaks from a
noisy but more or less constant baseline of SNR = 1.
You can further see that the SNR processing removes any broad-band power
differences (such as the increased power in alpha band around 10 Hz),
and also removes the 1/f decay in the PSD.
Note, that while the SNR plot implies the possibility of values below 0
(mean minus sd) such values do not make sense.
Each SNR value is a ratio of positive PSD values, and the lowest possible PSD
value is 0 (negative Y-axis values in the upper panel only result from
plotting PSD on a log scale).
Hence SNR values must be positive and can minimally go towards 0.
Extract SNR values at the stimulation frequency
Our processing yielded a large array of many SNR values for each trial x
channel x frequency-bin of the PSD array.
For statistical analysis we obviously need to define specific subsets of this
array. First of all, we are only interested in SNR at the stimulation
frequency, but we also want to restrict the analysis to a spatial ROI.
Lastly, answering your interesting research questions will probably rely on
comparing SNR in different trials.
Therefore we will have to find the indices of trials, channels, etc.
Alternatively, one could subselect the trials already at the epoching step,
using MNE's event information, and process different epoch structures
separately.
Let's only have a look at the trials with 12 Hz stimulation, for now.
Step8: Get index for the stimulation frequency (12 Hz)
Ideally, there would be a bin with the stimulation frequency exactly in its
center. However, depending on your Spectral decomposition this is not
always the case. We will find the bin closest to it - this one should contain
our frequency tagged response.
Step9: Get indices for the different trial types
Step10: Get indices of EEG channels forming the ROI
Step11: Apply the subset, and check the result
Now we simply need to apply our selection and yield a result. Therefore,
we typically report grand average SNR over the subselection.
In this tutorial we don't verify the presence of a neural response.
This is commonly done in the ASSR literature where SNR is
often lower. An F-test or Hotelling T² would be
appropriate for this purpose.
Step12: Topography of the vSSR
But wait...
As described in the intro, we have decided a priori to work with average
SNR over a subset of occipital channels - a visual region of interest (ROI)
- because we expect SNR to be higher on these channels than in other
channels.
Let's check out, whether this was a good decision!
Here we will plot average SNR for each channel location as a topoplot.
Then we will do a simple paired T-test to check, whether average SNRs over
the two sets of channels are significantly different.
Step13: We can see, that 1) this participant indeed exhibits a cluster of channels
with high SNR in the occipital region and 2) that the average SNR over all
channels is smaller than the average of the visual ROI computed above.
The difference is statistically significant. Great!
Such a topography plot can be a nice tool to explore and play with your data
- e.g. you could try how changing the reference will affect the spatial
distribution of SNR values.
However, we also wanted to show this plot to point at a potential
problem with frequency-tagged (or any other brain imaging) data
Step14: As you can easily see there are striking differences between the trials.
Let's verify this using a series of two-tailed paired T-Tests.
Step15: Debriefing
So that's it, we hope you enjoyed our little tour through this example
dataset.
As you could see, frequency-tagging is a very powerful tool that can yield
very high signal to noise ratios and effect sizes that enable you to detect
brain responses even within a single participant and single trials of only
a few seconds duration.
Bonus exercises
For the overly motivated amongst you, let's see what else we can show with
these data.
Using the PSD function as implemented in MNE makes it very easy to change
the amount of data that is actually used in the spectrum
estimation.
Here we employ this to show you some features of frequency
tagging data that you might or might not have already intuitively expected
Step16: You can see that the signal estimate / our SNR measure increases with the
trial duration.
This should be easy to understand | Python Code:
# Authors: Dominik Welke <dominik.welke@web.de>
# Evgenii Kalenkovich <e.kalenkovich@gmail.com>
#
# License: BSD-3-Clause
import matplotlib.pyplot as plt
import mne
import numpy as np
from scipy.stats import ttest_rel
Explanation: Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset
In this tutorial we compute the frequency spectrum and quantify signal-to-noise
ratio (SNR) at a target frequency in EEG data recorded during fast periodic
visual stimulation (FPVS) at 12 Hz and 15 Hz in different trials.
Extracting SNR at stimulation frequency is a simple way to quantify frequency
tagged responses in MEEG (a.k.a. steady state visually evoked potentials,
SSVEP, or visual steady-state responses, vSSR in the visual domain,
or auditory steady-state responses, ASSR in the auditory domain).
For a general introduction to the method see
Norcia et al. (2015) <https://doi.org/10.1167/15.6.4> for the visual domain,
and Picton et al. (2003) <https://doi.org/10.3109/14992020309101316> for
the auditory domain.
Data and outline:
We use a simple example dataset with frequency tagged visual stimulation:
N=2 participants observed checkerboard patterns inverting with a constant
frequency of either 12.0 Hz of 15.0 Hz.
32 channels wet EEG was recorded.
(see ssvep-dataset for more information).
We will visualize both the power-spectral density (PSD) and the SNR
spectrum of the epoched data,
extract SNR at stimulation frequency,
plot the topography of the response,
and statistically separate 12 Hz and 15 Hz responses in the different trials.
Since the evoked response is mainly generated in early visual areas of the
brain the statistical analysis will be carried out on an occipital
ROI.
:depth: 2
End of explanation
# Load raw data
data_path = mne.datasets.ssvep.data_path()
bids_fname = data_path + '/sub-02/ses-01/eeg/sub-02_ses-01_task-ssvep_eeg.vhdr'
raw = mne.io.read_raw_brainvision(bids_fname, preload=True, verbose=False)
raw.info['line_freq'] = 50.
# Set montage
montage = mne.channels.make_standard_montage('easycap-M1')
raw.set_montage(montage, verbose=False)
# Set common average reference
raw.set_eeg_reference('average', projection=False, verbose=False)
# Apply bandpass filter
raw.filter(l_freq=0.1, h_freq=None, fir_design='firwin', verbose=False)
# Construct epochs
event_id = {
'12hz': 255,
'15hz': 155
}
events, _ = mne.events_from_annotations(raw, verbose=False)
tmin, tmax = -1., 20. # in s
baseline = None
epochs = mne.Epochs(
raw, events=events,
event_id=[event_id['12hz'], event_id['15hz']], tmin=tmin,
tmax=tmax, baseline=baseline, verbose=False)
Explanation: Data preprocessing
Due to a generally high SNR in SSVEP/vSSR, typical preprocessing steps
are considered optional. This doesn't mean, that a proper cleaning would not
increase your signal quality!
Raw data have FCz reference, so we will apply common-average rereferencing.
We will apply a 0.1 highpass filter.
Lastly, we will cut the data in 20 s epochs corresponding to the trials.
End of explanation
tmin = 1.
tmax = 20.
fmin = 1.
fmax = 90.
sfreq = epochs.info['sfreq']
psds, freqs = mne.time_frequency.psd_welch(
epochs,
n_fft=int(sfreq * (tmax - tmin)),
n_overlap=0, n_per_seg=None,
tmin=tmin, tmax=tmax,
fmin=fmin, fmax=fmax,
window='boxcar',
verbose=False)
Explanation: Frequency analysis
Now we compute the frequency spectrum of the EEG data.
You will already see the peaks at the stimulation frequencies and some of
their harmonics, without any further processing.
The 'classical' PSD plot will be compared to a plot of the SNR spectrum.
SNR will be computed as a ratio of the power in a given frequency bin
to the average power in its neighboring bins.
This procedure has two advantages over using the raw PSD:
it normalizes the spectrum and accounts for 1/f power decay.
power modulations which are not very narrow band will disappear.
Calculate power spectral density (PSD)
The frequency spectrum will be computed using Fast Fourier transform (FFT).
This seems to be common practice in the steady-state literature and is
based on the exact knowledge of the stimulus and the assumed response -
especially in terms of it's stability over time.
For a discussion see e.g.
Bach & Meigen (1999) <https://doi.org/10.1023/A:1002648202420>_
We will exclude the first second of each trial from the analysis:
steady-state response often take a while to stabilize, and the
transient phase in the beginning can distort the signal estimate.
this section of data is expected to be dominated by responses related to
the stimulus onset, and we are not interested in this.
In MNE we call plain FFT as a special case of Welch's method, with only a
single Welch window spanning the entire trial and no specific windowing
function (i.e. applying a boxcar window).
End of explanation
def snr_spectrum(psd, noise_n_neighbor_freqs=1, noise_skip_neighbor_freqs=1):
Compute SNR spectrum from PSD spectrum using convolution.
Parameters
----------
psd : ndarray, shape ([n_trials, n_channels,] n_frequency_bins)
Data object containing PSD values. Works with arrays as produced by
MNE's PSD functions or channel/trial subsets.
noise_n_neighbor_freqs : int
Number of neighboring frequencies used to compute noise level.
increment by one to add one frequency bin ON BOTH SIDES
noise_skip_neighbor_freqs : int
set this >=1 if you want to exclude the immediately neighboring
frequency bins in noise level calculation
Returns
-------
snr : ndarray, shape ([n_trials, n_channels,] n_frequency_bins)
Array containing SNR for all epochs, channels, frequency bins.
NaN for frequencies on the edges, that do not have enough neighbors on
one side to calculate SNR.
# Construct a kernel that calculates the mean of the neighboring
# frequencies
averaging_kernel = np.concatenate((
np.ones(noise_n_neighbor_freqs),
np.zeros(2 * noise_skip_neighbor_freqs + 1),
np.ones(noise_n_neighbor_freqs)))
averaging_kernel /= averaging_kernel.sum()
# Calculate the mean of the neighboring frequencies by convolving with the
# averaging kernel.
mean_noise = np.apply_along_axis(
lambda psd_: np.convolve(psd_, averaging_kernel, mode='valid'),
axis=-1, arr=psd
)
# The mean is not defined on the edges so we will pad it with nas. The
# padding needs to be done for the last dimension only so we set it to
# (0, 0) for the other ones.
edge_width = noise_n_neighbor_freqs + noise_skip_neighbor_freqs
pad_width = [(0, 0)] * (mean_noise.ndim - 1) + [(edge_width, edge_width)]
mean_noise = np.pad(
mean_noise, pad_width=pad_width, constant_values=np.nan
)
return psd / mean_noise
Explanation: Calculate signal to noise ratio (SNR)
SNR - as we define it here - is a measure of relative power:
it's the ratio of power in a given frequency bin - the 'signal' -
to a 'noise' baseline - the average power in the surrounding frequency bins.
This approach was initially proposed by
Meigen & Bach (1999) <https://doi.org/10.1023/A:1002097208337>_
Hence, we need to set some parameters for this baseline - how many
neighboring bins should be taken for this computation, and do we want to skip
the direct neighbors (this can make sense if the stimulation frequency is not
super constant, or frequency bands are very narrow).
The function below does what we want.
End of explanation
snrs = snr_spectrum(psds, noise_n_neighbor_freqs=3,
noise_skip_neighbor_freqs=1)
Explanation: Now we call the function to compute our SNR spectrum.
As described above, we have to define two parameters.
how many noise bins do we want?
do we want to skip the n bins directly next to the target bin?
Tweaking these parameters can drastically impact the resulting spectrum,
but mainly if you choose extremes.
E.g. if you'd skip very many neighboring bins, broad band power modulations
(such as the alpha peak) should reappear in the SNR spectrum.
On the other hand, if you skip none you might miss or smear peaks if the
induced power is distributed over two or more frequency bins (e.g. if the
stimulation frequency isn't perfectly constant, or you have very narrow
bins).
Here, we want to compare power at each bin with average power of the
three neighboring bins (on each side) and skip one bin directly next
to it.
End of explanation
fig, axes = plt.subplots(2, 1, sharex='all', sharey='none', figsize=(8, 5))
freq_range = range(np.where(np.floor(freqs) == 1.)[0][0],
np.where(np.ceil(freqs) == fmax - 1)[0][0])
psds_plot = 10 * np.log10(psds)
psds_mean = psds_plot.mean(axis=(0, 1))[freq_range]
psds_std = psds_plot.std(axis=(0, 1))[freq_range]
axes[0].plot(freqs[freq_range], psds_mean, color='b')
axes[0].fill_between(
freqs[freq_range], psds_mean - psds_std, psds_mean + psds_std,
color='b', alpha=.2)
axes[0].set(title="PSD spectrum", ylabel='Power Spectral Density [dB]')
# SNR spectrum
snr_mean = snrs.mean(axis=(0, 1))[freq_range]
snr_std = snrs.std(axis=(0, 1))[freq_range]
axes[1].plot(freqs[freq_range], snr_mean, color='r')
axes[1].fill_between(
freqs[freq_range], snr_mean - snr_std, snr_mean + snr_std,
color='r', alpha=.2)
axes[1].set(
title="SNR spectrum", xlabel='Frequency [Hz]',
ylabel='SNR', ylim=[-2, 30], xlim=[fmin, fmax])
fig.show()
Explanation: Plot PSD and SNR spectra
Now we will plot grand average PSD (in blue) and SNR (in red) ± sd
for every frequency bin.
PSD is plotted on a log scale.
End of explanation
# define stimulation frequency
stim_freq = 12.
Explanation: You can see that the peaks at the stimulation frequencies (12 Hz, 15 Hz)
and their harmonics are visible in both plots (just as the line noise at
50 Hz).
Yet, the SNR spectrum shows them more prominently as peaks from a
noisy but more or less constant baseline of SNR = 1.
You can further see that the SNR processing removes any broad-band power
differences (such as the increased power in alpha band around 10 Hz),
and also removes the 1/f decay in the PSD.
Note, that while the SNR plot implies the possibility of values below 0
(mean minus sd) such values do not make sense.
Each SNR value is a ratio of positive PSD values, and the lowest possible PSD
value is 0 (negative Y-axis values in the upper panel only result from
plotting PSD on a log scale).
Hence SNR values must be positive and can minimally go towards 0.
Extract SNR values at the stimulation frequency
Our processing yielded a large array of many SNR values for each trial x
channel x frequency-bin of the PSD array.
For statistical analysis we obviously need to define specific subsets of this
array. First of all, we are only interested in SNR at the stimulation
frequency, but we also want to restrict the analysis to a spatial ROI.
Lastly, answering your interesting research questions will probably rely on
comparing SNR in different trials.
Therefore we will have to find the indices of trials, channels, etc.
Alternatively, one could subselect the trials already at the epoching step,
using MNE's event information, and process different epoch structures
separately.
Let's only have a look at the trials with 12 Hz stimulation, for now.
End of explanation
# find index of frequency bin closest to stimulation frequency
i_bin_12hz = np.argmin(abs(freqs - stim_freq))
# could be updated to support multiple frequencies
# for later, we will already find the 15 Hz bin and the 1st and 2nd harmonic
# for both.
i_bin_24hz = np.argmin(abs(freqs - 24))
i_bin_36hz = np.argmin(abs(freqs - 36))
i_bin_15hz = np.argmin(abs(freqs - 15))
i_bin_30hz = np.argmin(abs(freqs - 30))
i_bin_45hz = np.argmin(abs(freqs - 45))
Explanation: Get index for the stimulation frequency (12 Hz)
Ideally, there would be a bin with the stimulation frequency exactly in its
center. However, depending on your Spectral decomposition this is not
always the case. We will find the bin closest to it - this one should contain
our frequency tagged response.
End of explanation
i_trial_12hz = np.where(epochs.events[:, 2] == event_id['12hz'])[0]
i_trial_15hz = np.where(epochs.events[:, 2] == event_id['15hz'])[0]
Explanation: Get indices for the different trial types
End of explanation
# Define different ROIs
roi_vis = ['POz', 'Oz', 'O1', 'O2', 'PO3', 'PO4', 'PO7',
'PO8', 'PO9', 'PO10', 'O9', 'O10'] # visual roi
# Find corresponding indices using mne.pick_types()
picks_roi_vis = mne.pick_types(epochs.info, eeg=True, stim=False,
exclude='bads', selection=roi_vis)
Explanation: Get indices of EEG channels forming the ROI
End of explanation
snrs_target = snrs[i_trial_12hz, :, i_bin_12hz][:, picks_roi_vis]
print("sub 2, 12 Hz trials, SNR at 12 Hz")
print(f'average SNR (occipital ROI): {snrs_target.mean()}')
Explanation: Apply the subset, and check the result
Now we simply need to apply our selection and yield a result. Therefore,
we typically report grand average SNR over the subselection.
In this tutorial we don't verify the presence of a neural response.
This is commonly done in the ASSR literature where SNR is
often lower. An F-test or Hotelling T² would be
appropriate for this purpose.
End of explanation
# get average SNR at 12 Hz for ALL channels
snrs_12hz = snrs[i_trial_12hz, :, i_bin_12hz]
snrs_12hz_chaverage = snrs_12hz.mean(axis=0)
# plot SNR topography
fig, ax = plt.subplots(1)
mne.viz.plot_topomap(snrs_12hz_chaverage, epochs.info, vmin=1., axes=ax)
print("sub 2, 12 Hz trials, SNR at 12 Hz")
print("average SNR (all channels): %f" % snrs_12hz_chaverage.mean())
print("average SNR (occipital ROI): %f" % snrs_target.mean())
tstat_roi_vs_scalp = \
ttest_rel(snrs_target.mean(axis=1), snrs_12hz.mean(axis=1))
print("12 Hz SNR in occipital ROI is significantly larger than 12 Hz SNR over "
"all channels: t = %.3f, p = %f" % tstat_roi_vs_scalp)
Explanation: Topography of the vSSR
But wait...
As described in the intro, we have decided a priori to work with average
SNR over a subset of occipital channels - a visual region of interest (ROI)
- because we expect SNR to be higher on these channels than in other
channels.
Let's check out, whether this was a good decision!
Here we will plot average SNR for each channel location as a topoplot.
Then we will do a simple paired T-test to check, whether average SNRs over
the two sets of channels are significantly different.
End of explanation
snrs_roi = snrs[:, picks_roi_vis, :].mean(axis=1)
freq_plot = [12, 15, 24, 30, 36, 45]
color_plot = [
'darkblue', 'darkgreen', 'mediumblue', 'green', 'blue', 'seagreen'
]
xpos_plot = [-5. / 12, -3. / 12, -1. / 12, 1. / 12, 3. / 12, 5. / 12]
fig, ax = plt.subplots()
labels = ['12 Hz trials', '15 Hz trials']
x = np.arange(len(labels)) # the label locations
width = 0.6 # the width of the bars
res = dict()
# loop to plot SNRs at stimulation frequencies and harmonics
for i, f in enumerate(freq_plot):
# extract snrs
stim_12hz_tmp = \
snrs_roi[i_trial_12hz, np.argmin(abs(freqs - f))]
stim_15hz_tmp = \
snrs_roi[i_trial_15hz, np.argmin(abs(freqs - f))]
SNR_tmp = [stim_12hz_tmp.mean(), stim_15hz_tmp.mean()]
# plot (with std)
ax.bar(
x + width * xpos_plot[i], SNR_tmp, width / len(freq_plot),
yerr=np.std(SNR_tmp),
label='%i Hz SNR' % f, color=color_plot[i])
# store results for statistical comparison
res['stim_12hz_snrs_%ihz' % f] = stim_12hz_tmp
res['stim_15hz_snrs_%ihz' % f] = stim_15hz_tmp
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('SNR')
ax.set_title('Average SNR at target frequencies')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend(['%i Hz' % f for f in freq_plot], title='SNR at:')
ax.set_ylim([0, 70])
ax.axhline(1, ls='--', c='r')
fig.show()
Explanation: We can see, that 1) this participant indeed exhibits a cluster of channels
with high SNR in the occipital region and 2) that the average SNR over all
channels is smaller than the average of the visual ROI computed above.
The difference is statistically significant. Great!
Such a topography plot can be a nice tool to explore and play with your data
- e.g. you could try how changing the reference will affect the spatial
distribution of SNR values.
However, we also wanted to show this plot to point at a potential
problem with frequency-tagged (or any other brain imaging) data:
there are many channels and somewhere you will likely find some
statistically significant effect.
It is very easy - even unintended - to end up double-dipping or p-hacking.
So if you want to work with an ROI or individual channels, ideally select
them a priori - before collecting or looking at the data - and preregister
this decision so people will believe you.
If you end up selecting an ROI or individual channel for reporting because
this channel or ROI shows an effect, e.g. in an explorative analysis, this
is also fine but make it transparently and correct for multiple comparison.
Statistical separation of 12 Hz and 15 Hz vSSR
After this little detour into open science, let's move on and
do the analyses we actually wanted to do:
We will show that we can easily detect and discriminate the brains responses
in the trials with different stimulation frequencies.
In the frequency and SNR spectrum plot above, we had all trials mixed up.
Now we will extract 12 and 15 Hz SNR in both types of trials individually,
and compare the values with a simple t-test.
We will also extract SNR of the 1st and 2nd harmonic for both stimulation
frequencies. These are often reported as well and can show interesting
interactions.
End of explanation
# Compare 12 Hz and 15 Hz SNR in trials after averaging over channels
tstat_12hz_trial_stim = \
ttest_rel(res['stim_12hz_snrs_12hz'], res['stim_12hz_snrs_15hz'])
print("12 Hz Trials: 12 Hz SNR is significantly higher than 15 Hz SNR"
": t = %.3f, p = %f" % tstat_12hz_trial_stim)
tstat_12hz_trial_1st_harmonic = \
ttest_rel(res['stim_12hz_snrs_24hz'], res['stim_12hz_snrs_30hz'])
print("12 Hz Trials: 24 Hz SNR is significantly higher than 30 Hz SNR"
": t = %.3f, p = %f" % tstat_12hz_trial_1st_harmonic)
tstat_12hz_trial_2nd_harmonic = \
ttest_rel(res['stim_12hz_snrs_36hz'], res['stim_12hz_snrs_45hz'])
print("12 Hz Trials: 36 Hz SNR is significantly higher than 45 Hz SNR"
": t = %.3f, p = %f" % tstat_12hz_trial_2nd_harmonic)
print()
tstat_15hz_trial_stim = \
ttest_rel(res['stim_15hz_snrs_12hz'], res['stim_15hz_snrs_15hz'])
print("15 Hz trials: 12 Hz SNR is significantly lower than 15 Hz SNR"
": t = %.3f, p = %f" % tstat_15hz_trial_stim)
tstat_15hz_trial_1st_harmonic = \
ttest_rel(res['stim_15hz_snrs_24hz'], res['stim_15hz_snrs_30hz'])
print("15 Hz trials: 24 Hz SNR is significantly lower than 30 Hz SNR"
": t = %.3f, p = %f" % tstat_15hz_trial_1st_harmonic)
tstat_15hz_trial_2nd_harmonic = \
ttest_rel(res['stim_15hz_snrs_36hz'], res['stim_15hz_snrs_45hz'])
print("15 Hz trials: 36 Hz SNR is significantly lower than 45 Hz SNR"
": t = %.3f, p = %f" % tstat_15hz_trial_2nd_harmonic)
Explanation: As you can easily see there are striking differences between the trials.
Let's verify this using a series of two-tailed paired T-Tests.
End of explanation
stim_bandwidth = .5
# shorten data and welch window
window_lengths = [i for i in range(2, 21, 2)]
window_snrs = [[]] * len(window_lengths)
for i_win, win in enumerate(window_lengths):
# compute spectrogram
windowed_psd, windowed_freqs = mne.time_frequency.psd_welch(
epochs[str(event_id['12hz'])],
n_fft=int(sfreq * win),
n_overlap=0, n_per_seg=None,
tmin=0, tmax=win,
window='boxcar',
fmin=fmin, fmax=fmax, verbose=False)
# define a bandwidth of 1 Hz around stimfreq for SNR computation
bin_width = windowed_freqs[1] - windowed_freqs[0]
skip_neighbor_freqs = \
round((stim_bandwidth / 2) / bin_width - bin_width / 2. - .5) if (
bin_width < stim_bandwidth) else 0
n_neighbor_freqs = \
int((sum((windowed_freqs <= 13) & (windowed_freqs >= 11)
) - 1 - 2 * skip_neighbor_freqs) / 2)
# compute snr
windowed_snrs = \
snr_spectrum(
windowed_psd,
noise_n_neighbor_freqs=n_neighbor_freqs if (
n_neighbor_freqs > 0
) else 1,
noise_skip_neighbor_freqs=skip_neighbor_freqs)
window_snrs[i_win] = \
windowed_snrs[
:, picks_roi_vis,
np.argmin(
abs(windowed_freqs - 12.))].mean(axis=1)
fig, ax = plt.subplots(1)
ax.boxplot(window_snrs, labels=window_lengths, vert=True)
ax.set(title='Effect of trial duration on 12 Hz SNR',
ylabel='Average SNR', xlabel='Trial duration [s]')
ax.axhline(1, ls='--', c='r')
fig.show()
Explanation: Debriefing
So that's it, we hope you enjoyed our little tour through this example
dataset.
As you could see, frequency-tagging is a very powerful tool that can yield
very high signal to noise ratios and effect sizes that enable you to detect
brain responses even within a single participant and single trials of only
a few seconds duration.
Bonus exercises
For the overly motivated amongst you, let's see what else we can show with
these data.
Using the PSD function as implemented in MNE makes it very easy to change
the amount of data that is actually used in the spectrum
estimation.
Here we employ this to show you some features of frequency
tagging data that you might or might not have already intuitively expected:
Effect of trial duration on SNR
First we will simulate shorter trials by taking only the first x s of our 20s
trials (2, 4, 6, 8, ..., 20 s), and compute the SNR using a FFT window
that covers the entire epoch:
End of explanation
# 3s sliding window
window_length = 4
window_starts = [i for i in range(20 - window_length)]
window_snrs = [[]] * len(window_starts)
for i_win, win in enumerate(window_starts):
# compute spectrogram
windowed_psd, windowed_freqs = mne.time_frequency.psd_welch(
epochs[str(event_id['12hz'])],
n_fft=int(sfreq * window_length) - 1,
n_overlap=0, n_per_seg=None,
window='boxcar',
tmin=win, tmax=win + window_length,
fmin=fmin, fmax=fmax,
verbose=False)
# define a bandwidth of 1 Hz around stimfreq for SNR computation
bin_width = windowed_freqs[1] - windowed_freqs[0]
skip_neighbor_freqs = \
round((stim_bandwidth / 2) / bin_width - bin_width / 2. - .5) if (
bin_width < stim_bandwidth) else 0
n_neighbor_freqs = \
int((sum((windowed_freqs <= 13) & (windowed_freqs >= 11)
) - 1 - 2 * skip_neighbor_freqs) / 2)
# compute snr
windowed_snrs = snr_spectrum(
windowed_psd,
noise_n_neighbor_freqs=n_neighbor_freqs if (
n_neighbor_freqs > 0) else 1,
noise_skip_neighbor_freqs=skip_neighbor_freqs)
window_snrs[i_win] = \
windowed_snrs[:, picks_roi_vis, np.argmin(
abs(windowed_freqs - 12.))].mean(axis=1)
fig, ax = plt.subplots(1)
colors = plt.get_cmap('Greys')(np.linspace(0, 1, 10))
for i in range(10):
ax.plot(window_starts, np.array(window_snrs)[:, i], color=colors[i])
ax.set(title='Time resolved 12 Hz SNR - %is sliding window' % window_length,
ylabel='Average SNR', xlabel='t0 of analysis window [s]')
ax.axhline(1, ls='--', c='r')
ax.legend(['individual trials in greyscale'])
fig.show()
Explanation: You can see that the signal estimate / our SNR measure increases with the
trial duration.
This should be easy to understand: in longer recordings there is simply
more signal (one second of additional stimulation adds, in our case, 12
cycles of signal) while the noise is (hopefully) stochastic and not locked
to the stimulation frequency.
In other words: with more data the signal term grows faster than the noise
term.
We can further see that the very short trials with FFT windows < 2-3s are not
great - here we've either hit the noise floor and/or the transient response
at the trial onset covers too much of the trial.
Again, this tutorial doesn't statistically test for the presence of a neural
response, but an F-test or Hotelling T² would be appropriate for this
purpose.
Time resolved SNR
..and finally we can trick MNE's PSD implementation to make it a
sliding window analysis and come up with a time resolved SNR measure.
This will reveal whether a participant blinked or scratched their head..
Each of the ten trials is coded with a different color in the plot below.
End of explanation |
8,523 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ATM 623
Step1: Contents
Simulation versus parameterization of heat transport
The temperature diffusion parameterization
Solving the temperature diffusion equation with climlab
Parameterizing the radiation terms
The one-dimensional diffusive energy balance model
The annual-mean EBM
Effects of diffusivity in the EBM
Summary
Step2: All these traveling weather systems tend to move warm, moist air poleward and cold, dry air equatorward. There is thus a net poleward energy transport.
A model like this needs to simulate the weather in order to model the heat transport.
A simpler statistical approach
Let’s emphasize
Step3: At each timestep, the warm temperatures get cooler (at the equator) while the cold polar temperatures get warmer!
Diffusion is acting to reduce the temperature gradient.
If we let this run a long time, what should happen??
Try it yourself and find out!
Mathematical aside
Step4: <a id='section4'></a>
4. Parameterizing the radiation terms
Let's go back to the complete budget with our heat transport parameterization
$$ C(\phi) \frac{\partial T_s}{\partial t} = \text{ASR}(\phi) - \text{OLR}(\phi) + \frac{D}{\cos\phi } \frac{\partial }{\partial \phi} \left( \cos\phi ~ \frac{\partial T_s}{\partial \phi} \right) $$
We want to express this as a closed equation for surface temperature $T_s$.
First, as usual, we can write the solar term as
$$ \text{ASR} = (1-\alpha) ~ Q $$
For now, we will assume that the planetary albedo is fixed (does not depend on temperature). Therefore the entire shortwave term $(1-\alpha) Q$ is a fixed source term in our budget. It varies in space and time but does not depend on $T_s$.
Note that the solar term is (at least in annual average) larger at equator than poles… and transport term acts to flatten out the temperatures.
Now, we almost have a model we can solve for T! Just need to express the OLR in terms of temperature.
So… what’s the link between OLR and temperature????
[ discuss ]
We spent a good chunk of the course looking at this question, and developed a model of a vertical column of air.
We are trying now to build a model of the equator-to-pole (or pole-to-pole) temperature structure.
We COULD use an array of column models, representing temperature as a function of height and latitude (and time).
But instead, we will keep things simple, one spatial dimension at a time.
Introduce the following simple parameterization
Step5: We're going to plot the data and the best fit line, but also another line using these values
Step6: Discuss these curves...
Suggestion of at least 3 different regimes with different slopes (cold, medium, warm).
Unbiased "best fit" is actually a poor fit over all the intermediate temperatures.
The astute reader will note that... by taking the zonal average of the data before the regression, we are biasing this estimate toward cold temperatures. [WHY?]
Let's take these reference values
Step7: The albedo increases markedly toward the poles.
There are several reasons for this
Step8: Of course we are not fitting all the details of the observed albedo curve. But we do get the correct global mean a reasonable representation of the equator-to-pole gradient in albedo.
<a id='section6'></a>
6. The annual-mean EBM
Suppose we take the annual mean of the planetary energy budget.
If the albedo is fixed, then the average is pretty simple. Our EBM equation is purely linear, so the change over one year is just
$$ C \frac{\Delta \overline{T_s}}{\text{1 year}} = \left(1-\alpha(\phi) \right) ~ \overline{Q}(\phi) - \left( A + B~\overline{T_s} \right) + \frac{D}{\cos\phi } \frac{\partial }{\partial \phi} \left( \cos\phi ~ \frac{\partial \overline{T_s}}{\partial \phi} \right) $$
where $\overline{T_s}(\phi)$ is the annual mean surface temperature, and $\overline{Q}(\phi)$ is the annual mean insolation (both functions of latitude).
Notice that once we average over the seasonal cycle, there are no time-dependent forcing terms. The temperature will just evolve toward a steady equilibrium.
The equilibrium temperature is then the solution of this Ordinary Differential Equation (setting $\Delta \overline{T_s} = 0$ above)
Step9: Example EBM using climlab
Here is a simple example using the parameter values we just discussed.
For simplicity, this model will use the annual mean insolation, so the forcing is steady in time.
We haven't yet selected an appropriate value for the diffusivity $D$. Let's just try something and see what happens
Step10: The upshot
Step11: When $D=0$, every latitude is in radiative equilibrium and the heat transport is zero. As we have already seen, this gives an equator-to-pole temperature gradient much too high.
When $D$ is large, the model is very efficient at moving heat poleward. The heat transport is large and the temperture gradient is weak.
The real climate seems to lie in a sweet spot in between these limits.
It looks like our fitting criteria are met reasonably well with $D=0.6$ W m$^{-2}$ K$^{-1}$
Also, note that the global mean temperature (plotted in dashed blue) is completely insensitive to $D$. Look at the EBM equation and convince yourself that this must be true, since the transport term vanishes from the global average, and there is no non-linear temperature dependence in this model.
<a id='section8'></a>
8. Summary | Python Code:
# Ensure compatibility with Python 2 and 3
from __future__ import print_function, division
Explanation: ATM 623: Climate Modeling
Brian E. J. Rose, University at Albany
Lecture 18: The one-dimensional energy balance model
Warning: content out of date and not maintained
You really should be looking at The Climate Laboratory book by Brian Rose, where all the same content (and more!) is kept up to date.
Here you are likely to find broken links and broken code.
About these notes:
This document uses the interactive Jupyter notebook format. The notes can be accessed in several different ways:
The interactive notebooks are hosted on github at https://github.com/brian-rose/ClimateModeling_courseware
The latest versions can be viewed as static web pages rendered on nbviewer
A complete snapshot of the notes as of May 2017 (end of spring semester) are available on Brian's website.
Also here is a legacy version from 2015.
Many of these notes make use of the climlab package, available at https://github.com/brian-rose/climlab
End of explanation
from IPython.display import YouTubeVideo
YouTubeVideo('As85L34fKYQ')
Explanation: Contents
Simulation versus parameterization of heat transport
The temperature diffusion parameterization
Solving the temperature diffusion equation with climlab
Parameterizing the radiation terms
The one-dimensional diffusive energy balance model
The annual-mean EBM
Effects of diffusivity in the EBM
Summary: parameter values in the diffusive EBM
<a id='section1'></a>
1. Simulation versus parameterization of heat transport
In the previous lectures we have seen how heat transport by winds and ocean currents acts to COOL the tropics and WARM the poles. The observed temperature gradient is a product of both the insolation and the heat transport!
We were able to ignore this issue in our models of the global mean temperature, because the transport just moves energy around between latitude bands – does not create or destroy energy.
But if want to move beyond the global mean and create models of the equator-to-pole temperature structure, we cannot ignore heat transport. Has to be included somehow!
This leads to us the old theme of simulation versus parameterization.
Complex climate models like the CESM simulate the heat transport by solving the full equations of motion for the atmosphere (and ocean too, if coupled).
Simulation of synoptic-scale variability in CESM
Let's revisit an animation of the global 6-hourly sea-level pressure field from our slab ocean simulation with CESM. (We first saw this back in Lecture 5)
End of explanation
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import climlab
from climlab import constants as const
# First define an initial temperature field
# that is warm at the equator and cold at the poles
# and varies smoothly with latitude in between
from climlab.utils import legendre
sfc = climlab.domain.zonal_mean_surface(num_lat=90, water_depth=10.)
lat = sfc.lat.points
initial = 12. - 40. * legendre.P2(np.sin(np.deg2rad(lat)))
fig, ax = plt.subplots()
ax.plot(lat, initial)
ax.set_xlabel('Latitude')
ax.set_ylabel('Temperature (deg C)')
## Set up the climlab diffusion process
# make a copy of initial so that it remains unmodified
Ts = climlab.Field(np.array(initial), domain=sfc)
# thermal diffusivity in W/m**2/degC
D = 0.55
# create the climlab diffusion process
# setting the diffusivity and a timestep of ONE MONTH
d = climlab.dynamics.MeridionalHeatDiffusion(name='Diffusion',
state=Ts, D=D, timestep=const.seconds_per_month)
print( d)
# We are going to step forward one month at a time
# and store the temperature each time
niter = 5
temp = np.zeros((Ts.size, niter+1))
temp[:, 0] = np.squeeze(Ts)
for n in range(niter):
d.step_forward()
temp[:, n+1] = np.squeeze(Ts)
# Now plot the temperatures
fig,ax = plt.subplots()
ax.plot(lat, temp)
ax.set_xlabel('Latitude')
ax.set_ylabel('Temperature (deg C)')
ax.legend(range(niter+1))
Explanation: All these traveling weather systems tend to move warm, moist air poleward and cold, dry air equatorward. There is thus a net poleward energy transport.
A model like this needs to simulate the weather in order to model the heat transport.
A simpler statistical approach
Let’s emphasize: the most important role for heat transport by winds and ocean currents is to more energy from where it’s WARM to where it’s COLD, thereby reducing the temperature gradient (equator to pole) from what it would be if the planet were in radiative-convective equilibrium everywhere with no north-south motion.
This is the basis for the parameterization of heat transport often used in simple climate models.
Discuss analogy with molecular heat conduction: metal rod with one end in the fire.
Define carefully temperature gradient dTs / dy
Measures how quickly the temperature decreases as we move northward
(negative in NH, positive in SH)
In any conduction or diffusion process, the flux (transport) of a quantity is always DOWN-gradient (from WARM to COLD).
So our parameterization will look like
$$ \mathcal{H} = -K ~ dT / dy $$
Where $K$ is some positive number “diffusivity of the climate system”.
<a id='section2'></a>
2. The temperature diffusion parameterization
Last time we wrote down an energy budget for a thin zonal band centered at latitude $\phi$:
$$ \frac{\partial E(\phi)}{\partial t} = \text{ASR}(\phi) - \text{OLR}(\phi) - \frac{1}{2 \pi a^2 \cos\phi } \frac{\partial \mathcal{H}}{\partial \phi} $$
where we have written every term as an explicit function of latitude to remind ourselves that this is a local budget, unlike the zero-dimensional global budget we considered at the start of the course.
Let’s now formally introduce a parameterization that approximates the heat transport as a down-gradient diffusion process:
$$ \mathcal{H}(\phi) \approx -2 \pi a^2 \cos\phi ~ D ~ \frac{\partial T_s}{\partial \phi} $$
With $D$ a parameter for the diffusivity or thermal conductivity of the climate system, a number in W m$^{-2}$ ºC$^{-1}$.
The value of $D$ will be chosen to match observations – i.e. tuned.
Notice that we have explicitly chosen to the use surface temperature gradient to set the heat transport. This is a convenient (and traditional) choice to make, but it is not the only possibility! We could instead tune our parameterization to some measure of the free-tropospheric temperature gradient.
The diffusive parameterization in the planetary energy budget
Plug the parameterization into our energy budget to get
$$ \frac{\partial E(\phi)}{\partial t} = \text{ASR}(\phi) - \text{OLR}(\phi) - \frac{1}{2 \pi a^2 \cos\phi } \frac{\partial }{\partial \phi} \left( -2 \pi a^2 \cos\phi ~ D ~ \frac{\partial T_s}{\partial \phi} \right) $$
If we assume that $D$ is a constant (does not vary with latitude), then this simplifies to
$$ \frac{\partial E(\phi)}{\partial t} = \text{ASR}(\phi) - \text{OLR}(\phi) + \frac{D}{\cos\phi } \frac{\partial }{\partial \phi} \left( \cos\phi ~ \frac{\partial T_s}{\partial \phi} \right) $$
Surface temperature is a good measure of column heat content
Let's now make the same assumption we made back at the beginning of the course when we first wrote down the zero-dimensional EBM.
Most of the heat capacity is in the oceans, so that the energy content of each column $E$ is proportional to surface temperature:
$$ E(\phi) = C(\phi) ~ T_s(\phi) $$
where $C$ is effective heat capacity of the atmosphere - ocean column, in units of J m$^{-2}$ K$^{-1}$. Here we are writing $C$ are a function of latitude so that our model is general enough to allow different land-ocean fractions at different latitudes.
A heat equation for surface temperature
Now our budget becomes a PDE for the surface temperature $T_s(\phi, t)$:
$$ C(\phi) \frac{\partial T_s}{\partial t} = \text{ASR}(\phi) - \text{OLR}(\phi) + \frac{D}{\cos\phi } \frac{\partial }{\partial \phi} \left( \cos\phi ~ \frac{\partial T_s}{\partial \phi} \right) $$
Notice that if we were NOT on a spherical planet and didn’t have to worry about the changing size of latitude circles, this would look something like
$$ \frac{\partial T}{\partial t} = K \frac{\partial^2 T}{\partial y^2} + \text{forcing terms} $$
with $K = D/C$ in m$^{2}$ s$^{-1}$.
Does equation look familiar?
This is the heat equation, one of the central equations in classical mathematical physics.
This equation describes the behavior of a diffusive system, i.e. how mixing by random molecular motion smears out the temperature.
In our case, the analogy is between the random molecular motion of a metal rod, and the net mixing / stirring effect of weather systems.
Take the global average...
Take the integral $\int_{-\pi/2}^{\pi/2} \cos\phi ~ d\phi$ of each term.
$$ C \frac{\partial \overline{T_s}}{\partial t} d\phi = \overline{\text{ASR}} - \overline{\text{OLR}} + D \int_{-\pi/2}^{\pi/2} \frac{\partial }{\partial \phi} \left( \cos\phi ~ \frac{\partial T_s}{\partial \phi} \right) d\phi$$
The global average of the last term (heat transport) must go to zero (why?)
Therefore this reduces to our familiar zero-dimensional EBM.
<a id='section3'></a>
3. Solving the temperature diffusion equation with climlab
climlab has a pre-defined process for solving the meridional diffusion equation. Let's look at a simple example in which diffusion is the ONLY process that changes the temperature.
End of explanation
x = np.linspace(-1,1)
fig,ax = plt.subplots()
ax.plot(x, legendre.P2(x))
ax.set_title('$P_2(x)$')
Explanation: At each timestep, the warm temperatures get cooler (at the equator) while the cold polar temperatures get warmer!
Diffusion is acting to reduce the temperature gradient.
If we let this run a long time, what should happen??
Try it yourself and find out!
Mathematical aside: the Legendre Polynomials
Here we have used a function called the “2nd Legendre polynomial”, defined as
$$ P_2 (x) = \frac{1}{2} \left( 3x^2-1 \right) $$
where we have also set
$$ x = \sin\phi $$
Just turns out to be a useful mathematical description of the relatively smooth changes in things like annual-mean insolation from equator to pole.
In fact these are so useful that they are coded up in a special module within climlab:
End of explanation
import xarray as xr
## The NOAA ESRL server is shutdown! January 2019
ncep_url = "http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis.derived/"
ncep_Ts = xr.open_dataset( ncep_url + "surface_gauss/skt.sfc.mon.1981-2010.ltm.nc", decode_times=False)
#url = 'http://apdrc.soest.hawaii.edu:80/dods/public_data/Reanalysis_Data/NCEP/NCEP/clima/'
#ncep_Ts = xr.open_dataset(url + 'surface_gauss/skt')
lat_ncep = ncep_Ts.lat; lon_ncep = ncep_Ts.lon
print( ncep_Ts)
Ts_ncep_annual = ncep_Ts.skt.mean(dim=('lon','time'))
ncep_ulwrf = xr.open_dataset( ncep_url + "other_gauss/ulwrf.ntat.mon.1981-2010.ltm.nc", decode_times=False)
ncep_dswrf = xr.open_dataset( ncep_url + "other_gauss/dswrf.ntat.mon.1981-2010.ltm.nc", decode_times=False)
ncep_uswrf = xr.open_dataset( ncep_url + "other_gauss/uswrf.ntat.mon.1981-2010.ltm.nc", decode_times=False)
#ncep_ulwrf = xr.open_dataset(url + "other_gauss/ulwrf")
#ncep_dswrf = xr.open_dataset(url + "other_gauss/dswrf")
#ncep_uswrf = xr.open_dataset(url + "other_gauss/uswrf")
OLR_ncep_annual = ncep_ulwrf.ulwrf.mean(dim=('lon','time'))
ASR_ncep_annual = (ncep_dswrf.dswrf - ncep_uswrf.uswrf).mean(dim=('lon','time'))
from scipy.stats import linregress
slope, intercept, r_value, p_value, std_err = linregress(Ts_ncep_annual, OLR_ncep_annual)
print( 'Best fit is A = %0.0f W/m2 and B = %0.1f W/m2/degC' %(intercept, slope))
Explanation: <a id='section4'></a>
4. Parameterizing the radiation terms
Let's go back to the complete budget with our heat transport parameterization
$$ C(\phi) \frac{\partial T_s}{\partial t} = \text{ASR}(\phi) - \text{OLR}(\phi) + \frac{D}{\cos\phi } \frac{\partial }{\partial \phi} \left( \cos\phi ~ \frac{\partial T_s}{\partial \phi} \right) $$
We want to express this as a closed equation for surface temperature $T_s$.
First, as usual, we can write the solar term as
$$ \text{ASR} = (1-\alpha) ~ Q $$
For now, we will assume that the planetary albedo is fixed (does not depend on temperature). Therefore the entire shortwave term $(1-\alpha) Q$ is a fixed source term in our budget. It varies in space and time but does not depend on $T_s$.
Note that the solar term is (at least in annual average) larger at equator than poles… and transport term acts to flatten out the temperatures.
Now, we almost have a model we can solve for T! Just need to express the OLR in terms of temperature.
So… what’s the link between OLR and temperature????
[ discuss ]
We spent a good chunk of the course looking at this question, and developed a model of a vertical column of air.
We are trying now to build a model of the equator-to-pole (or pole-to-pole) temperature structure.
We COULD use an array of column models, representing temperature as a function of height and latitude (and time).
But instead, we will keep things simple, one spatial dimension at a time.
Introduce the following simple parameterization:
$$ OLR = A + B T_s $$
With $T_s$ the zonal average surface temperature in ºC, A is a constant in W m$^{-2}$ and B is a constant in W m$^{-2}$ ºC$^{-1}$.
OLR versus surface temperature in NCEP Reanalysis data
Let's look at the data to find reasonable values for $A$ and $B$.
End of explanation
# More standard values
A = 210.
B = 2.
fig, ax1 = plt.subplots(figsize=(8,6))
ax1.plot( Ts_ncep_annual, OLR_ncep_annual, 'o' , label='data')
ax1.plot( Ts_ncep_annual, intercept + slope * Ts_ncep_annual, 'k--', label='best fit')
ax1.plot( Ts_ncep_annual, A + B * Ts_ncep_annual, 'r--', label='B=2')
ax1.set_xlabel('Surface temperature (C)', fontsize=16)
ax1.set_ylabel('OLR (W m$^{-2}$)', fontsize=16)
ax1.set_title('OLR versus surface temperature from NCEP reanalysis', fontsize=18)
ax1.legend(loc='upper left')
ax1.grid()
Explanation: We're going to plot the data and the best fit line, but also another line using these values:
End of explanation
days = np.linspace(1.,50.)/50 * const.days_per_year
Qann_ncep = climlab.solar.insolation.daily_insolation(lat_ncep, days ).mean(dim='day')
albedo_ncep = 1 - ASR_ncep_annual / Qann_ncep
albedo_ncep_global = np.average(albedo_ncep, weights=np.cos(np.deg2rad(lat_ncep)))
print( 'The annual, global mean planetary albedo is %0.3f' %albedo_ncep_global)
fig,ax = plt.subplots()
ax.plot(lat_ncep, albedo_ncep)
ax.grid();
ax.set_xlabel('Latitude')
ax.set_ylabel('Albedo');
Explanation: Discuss these curves...
Suggestion of at least 3 different regimes with different slopes (cold, medium, warm).
Unbiased "best fit" is actually a poor fit over all the intermediate temperatures.
The astute reader will note that... by taking the zonal average of the data before the regression, we are biasing this estimate toward cold temperatures. [WHY?]
Let's take these reference values:
$$ A = 210 ~ \text{W m}^{-2}, ~~~ B = 2 ~ \text{W m}^{-2}~^\circ\text{C}^{-1} $$
Note that in the global average, recall $\overline{T_s} = 288 \text{ K} = 15^\circ\text{C}$
And so this parameterization gives
$$ \overline{\text{OLR}} = 210 + 15 \times 2 = 240 ~\text{W m}^{-2} $$
And the observed global mean is $\overline{\text{OLR}} = 239 ~\text{W m}^{-2} $
So this is consistent.
<a id='section5'></a>
5. The one-dimensional diffusive energy balance model
Putting the above OLR parameterization into our budget equation gives
$$ C(\phi) \frac{\partial T_s}{\partial t} = (1-\alpha) ~ Q - \left( A + B~T_s \right) + \frac{D}{\cos\phi } \frac{\partial }{\partial \phi} \left( \cos\phi ~ \frac{\partial T_s}{\partial \phi} \right) $$
This is the equation for a very important and useful simple model of the climate system. It is typically referred to as the (one-dimensional) Energy Balance Model.
(although as we have seen over and over, EVERY climate model is actually an “energy balance model” of some kind)
Also for historical reasons this is often called the Budyko-Sellers model, after Budyko and Sellers who both (independently of each other) published influential papers on this subject in 1969.
Recap: parameters in this model are
C: heat capacity in J m$^{-2}$ ºC$^{-1}$
A: longwave emission at 0ºC in W m$^{-2}$
B: increase in emission per degree, in W m$^{-2}$ ºC$^{-1}$
D: horizontal (north-south) diffusivity of the climate system in W m$^{-2}$ ºC$^{-1}$
We also need to specify the albedo.
Tune albedo formula to match observations
Let's go back to the NCEP Reanalysis data to see how planetary albedo actually varies as a function of latitude.
End of explanation
# Add a new curve to the previous figure
a0 = albedo_ncep_global
a2 = 0.25
ax.plot(lat_ncep, a0 + a2 * legendre.P2(np.sin(np.deg2rad(lat_ncep))))
fig
Explanation: The albedo increases markedly toward the poles.
There are several reasons for this:
surface snow and ice increase toward the poles
Cloudiness is an important (but complicated) factor.
Albedo increases with solar zenith angle (the angle at which the direct solar beam strikes a surface)
Approximating the observed albedo with a Legendre polynomial
Like temperature and insolation, this can be approximated by a smooth function that increases with latitude:
$$ \alpha(\phi) \approx \alpha_0 + \alpha_2 P_2(\sin\phi) $$
where $P_2$ is the 2nd Legendre polynomial (see above).
In effect we are using a truncated series expansion of the full meridional structure of $\alpha$. $a_0$ is the global average, and $a_2$ is proportional to the equator-to-pole gradient in $\alpha$.
We will set
$$ \alpha_0 = 0.354, ~~~ \alpha_2 = 0.25 $$
End of explanation
# Some imports needed to make and display animations
from IPython.display import HTML
from matplotlib import animation
def setup_figure():
templimits = -20,32
radlimits = -340, 340
htlimits = -6,6
latlimits = -90,90
lat_ticks = np.arange(-90,90,30)
fig, axes = plt.subplots(3,1,figsize=(8,10))
axes[0].set_ylabel('Temperature (deg C)')
axes[0].set_ylim(templimits)
axes[1].set_ylabel('Energy budget (W m$^{-2}$)')
axes[1].set_ylim(radlimits)
axes[2].set_ylabel('Heat transport (PW)')
axes[2].set_ylim(htlimits)
axes[2].set_xlabel('Latitude')
for ax in axes: ax.set_xlim(latlimits); ax.set_xticks(lat_ticks); ax.grid()
fig.suptitle('Diffusive energy balance model with annual-mean insolation', fontsize=14)
return fig, axes
def initial_figure(model):
# Make figure and axes
fig, axes = setup_figure()
# plot initial data
lines = []
lines.append(axes[0].plot(model.lat, model.Ts)[0])
lines.append(axes[1].plot(model.lat, model.ASR, 'k--', label='SW')[0])
lines.append(axes[1].plot(model.lat, -model.OLR, 'r--', label='LW')[0])
lines.append(axes[1].plot(model.lat, model.net_radiation, 'c-', label='net rad')[0])
lines.append(axes[1].plot(model.lat, model.heat_transport_convergence, 'g--', label='dyn')[0])
lines.append(axes[1].plot(model.lat,
model.net_radiation+model.heat_transport_convergence, 'b-', label='total')[0])
axes[1].legend(loc='upper right')
lines.append(axes[2].plot(model.lat_bounds, model.heat_transport)[0])
lines.append(axes[0].text(60, 25, 'Day 0'))
return fig, axes, lines
def animate(day, model, lines):
model.step_forward()
# The rest of this is just updating the plot
lines[0].set_ydata(model.Ts)
lines[1].set_ydata(model.ASR)
lines[2].set_ydata(-model.OLR)
lines[3].set_ydata(model.net_radiation)
lines[4].set_ydata(model.heat_transport_convergence)
lines[5].set_ydata(model.net_radiation+model.heat_transport_convergence)
lines[6].set_ydata(model.heat_transport)
lines[-1].set_text('Day {}'.format(int(model.time['days_elapsed'])))
return lines
# A model starting from isothermal initial conditions
e = climlab.EBM_annual()
e.Ts[:] = 15. # in degrees Celsius
e.compute_diagnostics()
# Plot initial data
fig, axes, lines = initial_figure(e)
ani = animation.FuncAnimation(fig, animate, frames=np.arange(1, 100), fargs=(e, lines))
HTML(ani.to_html5_video())
Explanation: Of course we are not fitting all the details of the observed albedo curve. But we do get the correct global mean a reasonable representation of the equator-to-pole gradient in albedo.
<a id='section6'></a>
6. The annual-mean EBM
Suppose we take the annual mean of the planetary energy budget.
If the albedo is fixed, then the average is pretty simple. Our EBM equation is purely linear, so the change over one year is just
$$ C \frac{\Delta \overline{T_s}}{\text{1 year}} = \left(1-\alpha(\phi) \right) ~ \overline{Q}(\phi) - \left( A + B~\overline{T_s} \right) + \frac{D}{\cos\phi } \frac{\partial }{\partial \phi} \left( \cos\phi ~ \frac{\partial \overline{T_s}}{\partial \phi} \right) $$
where $\overline{T_s}(\phi)$ is the annual mean surface temperature, and $\overline{Q}(\phi)$ is the annual mean insolation (both functions of latitude).
Notice that once we average over the seasonal cycle, there are no time-dependent forcing terms. The temperature will just evolve toward a steady equilibrium.
The equilibrium temperature is then the solution of this Ordinary Differential Equation (setting $\Delta \overline{T_s} = 0$ above):
$$ 0 = \left(1-\alpha(\phi) \right) ~ \overline{Q}(\phi) - \left( A + B~\overline{T_s} \right) + \frac{D}{\cos\phi } \frac{d }{d \phi} \left( \cos\phi ~ \frac{d \overline{T_s}}{d \phi} \right) $$
You will often see this equation written in terms of the independent variable
$$ x = \sin\phi $$
which is 0 at the equator and $\pm1$ at the poles. Substituting this for $\phi$, noting that $dx = \cos\phi~ d\phi$ and rearranging a bit gives
$$ \frac{D}{B} \frac{d }{d x} \left( (1-x^2) ~ \frac{d \overline{T_s}}{d x} \right) - \overline{T_s} = -\frac{\left(1-\alpha(x) \right) ~ \overline{Q}(x) - A}{B} $$
This is actually a 2nd order ODE, and actually a 2-point Boundary Value Problem for the temperature $T(x)$, where the boundary conditions are no-flux at the boundaries (usually the poles).
This form can be convenient for analytical solutions. As we will see, the non-dimensional number $D/B$ is a very important measure of the efficiency of heat transport in the climate system. We will return to this later.
Numerical solutions of the time-dependent EBM
We will leave the time derivative in our model, because this is the most convenient way to find the equilibrium solution!
There is code available in climlab to solve the diffusive EBM.
Animating the adjustment of annual mean EBM to equilibrium
Before looking at the details of how to set up an EBM in climlab, let's look at an animation of the adjustment of the model (its temperature and energy budget) from an isothermal initial condition.
For reference, all the code necessary to generate the animation is here in the notebook.
End of explanation
D = 0.1
model = climlab.EBM_annual(A=210, B=2, D=D, a0=0.354, a2=0.25)
print( model)
model.param
model.integrate_years(10)
fig, axes = plt.subplots(1,2, figsize=(12,4))
ax = axes[0]
ax.plot(model.lat, model.Ts, label=('D = %0.1f' %D))
ax.plot(lat_ncep, Ts_ncep_annual, label='obs')
ax.set_ylabel('Temperature (degC)')
ax = axes[1]
energy_in = np.squeeze(model.ASR - model.OLR)
ax.plot(model.lat, energy_in, label=('D = %0.1f' %D))
ax.plot(lat_ncep, ASR_ncep_annual - OLR_ncep_annual, label='obs')
ax.set_ylabel('Net downwelling radiation at TOA (W m$^{-2}$)')
for ax in axes:
ax.set_xlabel('Latitude'); ax.legend(); ax.grid();
def inferred_heat_transport( energy_in, lat_deg ):
'''Returns the inferred heat transport (in PW) by integrating the net energy imbalance from pole to pole.'''
from scipy import integrate
from climlab import constants as const
lat_rad = np.deg2rad( lat_deg )
return ( 1E-15 * 2 * np.math.pi * const.a**2 *
integrate.cumtrapz( np.cos(lat_rad)*energy_in,
x=lat_rad, initial=0. ) )
fig, ax = plt.subplots()
ax.plot(model.lat, inferred_heat_transport(energy_in, model.lat), label=('D = %0.1f' %D))
ax.set_ylabel('Heat transport (PW)')
ax.legend(); ax.grid()
ax.set_xlabel('Latitude')
Explanation: Example EBM using climlab
Here is a simple example using the parameter values we just discussed.
For simplicity, this model will use the annual mean insolation, so the forcing is steady in time.
We haven't yet selected an appropriate value for the diffusivity $D$. Let's just try something and see what happens:
End of explanation
Darray = np.arange(0., 2.05, 0.05)
model_list = []
Tmean_list = []
deltaT_list = []
Hmax_list = []
for D in Darray:
ebm = climlab.EBM_annual(A=210, B=2, a0=0.354, a2=0.25, D=D)
ebm.integrate_years(20., verbose=False)
Tmean = ebm.global_mean_temperature()
deltaT = np.max(ebm.Ts) - np.min(ebm.Ts)
energy_in = np.squeeze(ebm.ASR - ebm.OLR)
Htrans = inferred_heat_transport(energy_in, ebm.lat)
Hmax = np.max(Htrans)
model_list.append(ebm)
Tmean_list.append(Tmean)
deltaT_list.append(deltaT)
Hmax_list.append(Hmax)
color1 = 'b'
color2 = 'r'
fig = plt.figure(figsize=(8,6))
ax1 = fig.add_subplot(111)
ax1.plot(Darray, deltaT_list, color=color1)
ax1.plot(Darray, Tmean_list, 'b--')
ax1.set_xlabel('D (W m$^{-2}$ K$^{-1}$)', fontsize=14)
ax1.set_xticks(np.arange(Darray[0], Darray[-1], 0.2))
ax1.set_ylabel('$\Delta T$ (equator to pole)', fontsize=14, color=color1)
for tl in ax1.get_yticklabels():
tl.set_color(color1)
ax2 = ax1.twinx()
ax2.plot(Darray, Hmax_list, color=color2)
ax2.set_ylabel('Maximum poleward heat transport (PW)', fontsize=14, color=color2)
for tl in ax2.get_yticklabels():
tl.set_color(color2)
ax1.set_title('Effect of diffusivity on temperature gradient and heat transport in the EBM', fontsize=16)
ax1.grid()
ax1.plot([0.6, 0.6], [0, 140], 'k-');
Explanation: The upshot: compared to observations, this model has a much too large equator-to-pole temperature gradient, and not enough poleward heat transport!
Apparently we need to increase the diffusivity to get a better fit.
<a id='section7'></a>
7. Effects of diffusivity in the annual mean EBM
In-class investigation:
Solve the annual-mean EBM (integrate out to equilibrium) over a range of different diffusivity parameters.
Make three plots:
Global-mean temperature as a function of $D$
Equator-to-pole temperature difference $\Delta T$ as a function of $D$
Maximum poleward heat transport $\mathcal{H}_{max}$ as a function of $D$
Choose a value of $D$ that gives a reasonable approximation to observations:
$\Delta T \approx 45$ ºC
$\mathcal{H}_{max} \approx 5.5$ PW
One possible way to do this:
End of explanation
%load_ext version_information
%version_information numpy, scipy, matplotlib, xarray, climlab
Explanation: When $D=0$, every latitude is in radiative equilibrium and the heat transport is zero. As we have already seen, this gives an equator-to-pole temperature gradient much too high.
When $D$ is large, the model is very efficient at moving heat poleward. The heat transport is large and the temperture gradient is weak.
The real climate seems to lie in a sweet spot in between these limits.
It looks like our fitting criteria are met reasonably well with $D=0.6$ W m$^{-2}$ K$^{-1}$
Also, note that the global mean temperature (plotted in dashed blue) is completely insensitive to $D$. Look at the EBM equation and convince yourself that this must be true, since the transport term vanishes from the global average, and there is no non-linear temperature dependence in this model.
<a id='section8'></a>
8. Summary: parameter values in the diffusive EBM
Our model is defined by the following equation
$$ C \frac{\partial T_s}{\partial t} = (1-\alpha) ~ Q - \left( A + B~T_s \right) + \frac{D}{\cos\phi } \frac{\partial }{\partial \phi} \left( \cos\phi ~ \frac{\partial T_s}{\partial \phi} \right) $$
with the albedo given by
$$ \alpha(\phi) = \alpha_0 + \alpha_2 P_2(\sin\phi) $$
We have chosen the following parameter values, which seems to give a reasonable fit to the observed annual mean temperature and energy budget:
$ A = 210 ~ \text{W m}^{-2}$
$ B = 2 ~ \text{W m}^{-2}~^\circ\text{C}^{-1} $
$ a_0 = 0.354$
$ a_2 = 0.25$
$ D = 0.6 ~ \text{W m}^{-2}~^\circ\text{C}^{-1} $
There is one parameter left to choose: the heat capacity $C$. We can't use the annual mean energy budget and temperatures to guide this choice.
[Why?]
We will instead look at seasonally varying models in the next set of notes.
<div class="alert alert-success">
[Back to ATM 623 notebook home](../index.ipynb)
</div>
Version information
End of explanation |
8,524 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
You are currently looking at version 1.2 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook FAQ course resource.
Assignment 2 - Pandas Introduction
All questions are weighted the same in this assignment.
Part 1
The following code loads the olympics dataset (olympics.csv), which was derrived from the Wikipedia entry on All Time Olympic Games Medals, and does some basic data cleaning.
The columns are organized as # of Summer games, Summer medals, # of Winter games, Winter medals, total # number of games, total # of medals. Use this dataset to answer the questions below.
Step1: Question 0 (Example)
What is the first country in df?
This function should return a Series.
Step2: Question 1
Which country has won the most gold medals in summer games?
This function should return a single string value.
Step3: Question 2
Which country had the biggest difference between their summer and winter gold medal counts?
This function should return a single string value.
Step4: Question 3
Which country has the biggest difference between their summer gold medal counts and winter gold medal counts relative to their total gold medal count?
$$\frac{Summer~Gold - Winter~Gold}{Total~Gold}$$
Only include countries that have won at least 1 gold in both summer and winter.
This function should return a single string value.
Step5: Question 4
Write a function that creates a Series called "Points" which is a weighted value where each gold medal (Gold.2) counts for 3 points, silver medals (Silver.2) for 2 points, and bronze medals (Bronze.2) for 1 point. The function should return only the column (a Series object) which you created.
This function should return a Series named Points of length 146
Step6: Part 2
For the next set of questions, we will be using census data from the United States Census Bureau. Counties are political and geographic subdivisions of states in the United States. This dataset contains population data for counties and states in the US from 2010 to 2015. See this document for a description of the variable names.
The census dataset (census.csv) should be loaded as census_df. Answer questions using this as appropriate.
Question 5
Which state has the most counties in it? (hint
Step7: Question 6
Only looking at the three most populous counties for each state, what are the three most populous states (in order of highest population to lowest population)? Use CENSUS2010POP.
This function should return a list of string values.
Step8: Question 7
Which county has had the largest absolute change in population within the period 2010-2015? (Hint
Step9: Question 8
In this datafile, the United States is broken up into four regions using the "REGION" column.
Create a query that finds the counties that belong to regions 1 or 2, whose name starts with 'Washington', and whose POPESTIMATE2015 was greater than their POPESTIMATE 2014.
This function should return a 5x2 DataFrame with the columns = ['STNAME', 'CTYNAME'] and the same index ID as the census_df (sorted ascending by index). | Python Code:
import pandas as pd
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
for col in df.columns:
if col[:2]=='01':
df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
if col[:2]=='02':
df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
if col[:2]=='03':
df.rename(columns={col:'Bronze'+col[4:]}, inplace=True)
if col[:1]=='№':
df.rename(columns={col:'#'+col[1:]}, inplace=True)
names_ids = df.index.str.split('\s\(') # split the index by '('
df.index = names_ids.str[0] # the [0] element is the country name (new index)
df['ID'] = names_ids.str[1].str[:3] # the [1] element is the abbreviation or ID (take first 3 characters from that)
df = df.drop('Totals')
df.head()
Explanation: You are currently looking at version 1.2 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook FAQ course resource.
Assignment 2 - Pandas Introduction
All questions are weighted the same in this assignment.
Part 1
The following code loads the olympics dataset (olympics.csv), which was derrived from the Wikipedia entry on All Time Olympic Games Medals, and does some basic data cleaning.
The columns are organized as # of Summer games, Summer medals, # of Winter games, Winter medals, total # number of games, total # of medals. Use this dataset to answer the questions below.
End of explanation
# You should write your whole answer within the function provided. The autograder will call
# this function and compare the return value against the correct solution value
def answer_zero():
# This function returns the row for Afghanistan, which is a Series object. The assignment
# question description will tell you the general format the autograder is expecting
return df.iloc[0]
# You can examine what your function returns by calling it in the cell. If you have questions
# about the assignment formats, check out the discussion forums for any FAQs
answer_zero()
Explanation: Question 0 (Example)
What is the first country in df?
This function should return a Series.
End of explanation
def answer_one():
answer = df.sort(['Gold'], ascending = False)
return answer.index[0]
answer_one()
Explanation: Question 1
Which country has won the most gold medals in summer games?
This function should return a single string value.
End of explanation
def answer_two():
df['Gold_difference'] = df['Gold'] - df['Gold.1']
answer = df.sort(['Gold_difference'], ascending = False)
return answer.index[0]
answer_two()
Explanation: Question 2
Which country had the biggest difference between their summer and winter gold medal counts?
This function should return a single string value.
End of explanation
def answer_three():
only_gold = df[(df['Gold.1'] > 0) & (df['Gold'] > 0)]
only_gold['big_difference'] = (only_gold['Gold'] - only_gold['Gold.1']) / only_gold['Gold.2']
answer = only_gold.sort(['big_difference'], ascending = False)
return answer.index[0]
answer_three()
Explanation: Question 3
Which country has the biggest difference between their summer gold medal counts and winter gold medal counts relative to their total gold medal count?
$$\frac{Summer~Gold - Winter~Gold}{Total~Gold}$$
Only include countries that have won at least 1 gold in both summer and winter.
This function should return a single string value.
End of explanation
def answer_four():
df['Points'] = (df['Gold.2'] * 3) + (df['Silver.2'] * 2) + (df['Bronze.2'] * 1)
return df['Points']
answer_four()
Explanation: Question 4
Write a function that creates a Series called "Points" which is a weighted value where each gold medal (Gold.2) counts for 3 points, silver medals (Silver.2) for 2 points, and bronze medals (Bronze.2) for 1 point. The function should return only the column (a Series object) which you created.
This function should return a Series named Points of length 146
End of explanation
census_df = pd.read_csv('census.csv')
census_df
def answer_five():
newdf = census_df.groupby(['STNAME']).count()
answer = newdf.sort(['CTYNAME'], ascending = False)
return answer.index[0]
answer_five()
Explanation: Part 2
For the next set of questions, we will be using census data from the United States Census Bureau. Counties are political and geographic subdivisions of states in the United States. This dataset contains population data for counties and states in the US from 2010 to 2015. See this document for a description of the variable names.
The census dataset (census.csv) should be loaded as census_df. Answer questions using this as appropriate.
Question 5
Which state has the most counties in it? (hint: consider the sumlevel key carefully! You'll need this for future questions too...)
This function should return a single string value.
End of explanation
def answer_six():
ctydf = census_df[census_df['SUMLEV'] == 50]
ctydfs = ctydf.sort(['CENSUS2010POP'], ascending = False)
ctydfst3 = ctydfs.groupby('STNAME').head(3)
ldf = ctydfst3.groupby(['STNAME']).sum()
answer = ldf.sort(['CENSUS2010POP'], ascending = False)
return answer.index[0:3].tolist()
answer_six()
Explanation: Question 6
Only looking at the three most populous counties for each state, what are the three most populous states (in order of highest population to lowest population)? Use CENSUS2010POP.
This function should return a list of string values.
End of explanation
def answer_seven():
return "YOUR ANSWER HERE"
Explanation: Question 7
Which county has had the largest absolute change in population within the period 2010-2015? (Hint: population values are stored in columns POPESTIMATE2010 through POPESTIMATE2015, you need to consider all six columns.)
e.g. If County Population in the 5 year period is 100, 120, 80, 105, 100, 130, then its largest change in the period would be |130-80| = 50.
This function should return a single string value.
End of explanation
def answer_eight():
ctydf = census_df[(census_df['SUMLEV'] == 50) & (census_df['REGION'] < 3)]
ctydfwas = ctydf.loc[(ctydf['CTYNAME'] == 'Washington County') & (ctydf['POPESTIMATE2015'] > ctydf['POPESTIMATE2014'])]
columns_to_keep = ['STNAME',
'CTYNAME']
ansdf = ctydfwas[columns_to_keep]
return ansdf
answer_eight()
Explanation: Question 8
In this datafile, the United States is broken up into four regions using the "REGION" column.
Create a query that finds the counties that belong to regions 1 or 2, whose name starts with 'Washington', and whose POPESTIMATE2015 was greater than their POPESTIMATE 2014.
This function should return a 5x2 DataFrame with the columns = ['STNAME', 'CTYNAME'] and the same index ID as the census_df (sorted ascending by index).
End of explanation |
8,525 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. _tick-locators
Step1: Note that the Y axis in this plot has sensible ticks that cover the full data domain $[0, 1]$, while the X axis also has sensible ticks that include "round" numbers like 20 even though the X values only cover $[0, 19]$. The algorithm for identifying "good" "round" tick values is provided by Toyplot's
Step2: We can also override the default formatting string used to generate the locator labels
Step3: Anytime you use log scale axes in a plot, Toyplot automatically uses the
Step4: If you don't like the "superscript" notation that the Log locator produces, you could replace it with your own locator and custom format
Step5: Or even display raw tick values
Step6: Although you might not think of
Step7: By default the Integer locator generates a tick/label for every integer in the range $[0, N)$ ... as you visualize larger matrices, you'll find that a label for every row and column becomes crowded, in which case you can override the default step parameter to space-out the labels
Step8: For the ultimate flexibility in positioning tick locations and labels, you can use the
Step9: Note that in the above example the implicit $[0, N)$ tick locations match the implicit $[0, N)$ X coordinates that are generated for each bar when you don't supply any X coordinates of your own. This is by design!
You can also use Explicit locators with a list of tick locations, and a set of tick labels will be generated using a format string. For example
Step10: Finally, you can supply both locations and labels to an Explicit locator
Step11: Explicit locators are also a good way to handle timeseries using timestamps or Python datetime objects. For this example, we will create a series "x" that contains datetime objects, and a series "y" containing values
Step12: Now, we can extract a set of locations and labels, formatting the datetime objects to suit
Step13: Because timestamp labels tend to be fairly long, this is often a case where you'll want to adjust the orientation of the labels so they don't overlap (note in the following example that we had to make the canvas larger and position the axes manually on the canvas to make room for the vertical labels - and we manually placed the x axis label to avoid overlap) | Python Code:
import numpy
x = numpy.arange(20)
y = numpy.linspace(0, 1, len(x)) ** 2
import toyplot
canvas, axes, mark = toyplot.plot(x, y, width=300)
Explanation: .. _tick-locators:
Tick Locators
When you create a figure in Toyplot, you begin by creating a :class:canvas<toyplot.canvas.Canvas>, add :mod:axes<toyplot.axes>, and add data to the axes in the form of marks. The axes map data from its domain to a range on the canvas, generating ticks in domain-space with tick labels as an integral part of the process.
To generate tick locations and tick labels, the axes delegate to the tick locator classes in the :mod:toyplot.locator module. Each tick locator class is responsible for generating a collection of tick locations from the range of values in an axis domain, and there are several different classes available that implement different strategies for generating "good" tick locations. If you don't specify any tick locators when creating axes, sensible defaults will be chosen for you. For example:
End of explanation
canvas, axes, mark = toyplot.plot(x, y, width=300)
axes.x.ticks.locator = toyplot.locator.Basic(count=5)
Explanation: Note that the Y axis in this plot has sensible ticks that cover the full data domain $[0, 1]$, while the X axis also has sensible ticks that include "round" numbers like 20 even though the X values only cover $[0, 19]$. The algorithm for identifying "good" "round" tick values is provided by Toyplot's :class:toyplot.locator.Extended locator.
However, let's say that we prefer to always have ticks that include the exact minimum and maximum data domain values, and evenly divide the rest of the domain. In this case, we can override the default choice of locator with the :class:toyplot.locator.Basic tick locator:
End of explanation
canvas, axes, mark = toyplot.plot(x, y, width=300)
axes.x.ticks.locator = toyplot.locator.Basic(count=5, format="{:.2f}")
Explanation: We can also override the default formatting string used to generate the locator labels:
End of explanation
canvas, axes, mark = toyplot.plot(x, y, xscale="log10", width=300)
Explanation: Anytime you use log scale axes in a plot, Toyplot automatically uses the :class:toyplot.locator.Log locator to provide ticks that are evenly-spaced :
End of explanation
canvas, axes, mark = toyplot.plot(x, y, xscale="log10", width=300)
axes.x.ticks.locator = toyplot.locator.Log(base=10, format="{base}^{exponent}")
Explanation: If you don't like the "superscript" notation that the Log locator produces, you could replace it with your own locator and custom format:
End of explanation
canvas, axes, mark = toyplot.plot(x, y, xscale="log2", width=300)
axes.x.ticks.locator = toyplot.locator.Log(base=2, format="{:.0f}")
Explanation: Or even display raw tick values:
End of explanation
numpy.random.seed(1234)
canvas, table = toyplot.matrix(numpy.random.random((5, 5)), width=300)
Explanation: Although you might not think of :ref:table-axes as needing tick locators, when you use :func:toyplot.matrix or :meth:toyplot.canvas.Canvas.matrix to visualize a matrix of values, it generates a table visualization and uses :class:toyplot.locator.Integer locators to generate row and column labels:
End of explanation
canvas, table = toyplot.matrix(numpy.random.random((50, 50)), width=400, step=5)
Explanation: By default the Integer locator generates a tick/label for every integer in the range $[0, N)$ ... as you visualize larger matrices, you'll find that a label for every row and column becomes crowded, in which case you can override the default step parameter to space-out the labels:
End of explanation
fruits = ["Apples", "Oranges", "Kiwi", "Miracle Fruit", "Durian"]
counts = [452, 347, 67, 21, 5]
canvas, axes, mark = toyplot.bars(counts, width=400, height=300)
axes.x.ticks.locator = toyplot.locator.Explicit(labels=fruits)
Explanation: For the ultimate flexibility in positioning tick locations and labels, you can use the :class:toyplot.locator.Explicit locator. With it, you can specify an explicit set of labels, and a set of $[0, N)$ integer locations will be created to match. This is particularly useful if you are working with categorical data:
End of explanation
x = numpy.linspace(0, 2 * numpy.pi)
y = numpy.sin(x)
locations=[0, numpy.pi/2, numpy.pi, 3*numpy.pi/2, 2*numpy.pi]
canvas, axes, mark = toyplot.plot(x, y, width=500, height=300)
axes.x.ticks.locator = toyplot.locator.Explicit(locations=locations, format="{:.2f}")
Explanation: Note that in the above example the implicit $[0, N)$ tick locations match the implicit $[0, N)$ X coordinates that are generated for each bar when you don't supply any X coordinates of your own. This is by design!
You can also use Explicit locators with a list of tick locations, and a set of tick labels will be generated using a format string. For example:
End of explanation
labels = ["0", u"\u03c0 / 2", u"\u03c0", u"3\u03c0 / 2", u"2\u03c0"]
canvas, axes, mark = toyplot.plot(x, y, width=500, height=300)
axes.x.ticks.locator = toyplot.locator.Explicit(locations=locations, labels=labels)
Explanation: Finally, you can supply both locations and labels to an Explicit locator:
End of explanation
import datetime
import toyplot.data
data = toyplot.data.read_csv("commute-obd.csv")
observations = numpy.logical_and(data["name"] == "Vehicle Speed", data["value"] != "NODATA")
timestamps = data["timestamp"][observations]
x = [datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f") for timestamp in timestamps]
y = data["value"][observations]
Explanation: Explicit locators are also a good way to handle timeseries using timestamps or Python datetime objects. For this example, we will create a series "x" that contains datetime objects, and a series "y" containing values:
End of explanation
locations = []
labels = []
for index, timestamp in enumerate(x):
if timestamp.minute % 5 == 0 and 0 < timestamp.second < 5:
locations.append(index)
labels.append(timestamp.strftime("%H:%M"))
canvas, axes, mark = toyplot.plot(y, label="Vehicle Speed", xlabel="Time", ylabel="km/h", width=600, height=300)
axes.x.ticks.locator = toyplot.locator.Explicit(locations=locations, labels=labels)
axes.x.ticks.show = True
Explanation: Now, we can extract a set of locations and labels, formatting the datetime objects to suit:
End of explanation
locations = []
labels = []
for index, timestamp in enumerate(x):
if timestamp.minute % 5 == 0 and 0 < timestamp.second < 5:
locations.append(index)
labels.append(timestamp.strftime("%Y-%m-%d %H:%M"))
canvas = toyplot.Canvas(width=600, height=400)
canvas.text(300, 360, "Time", style={"font-weight":"bold"})
axes = canvas.axes(label="Vehicle Speed", ylabel="km/h", bounds=(50, -50, 50, -150))
axes.x.ticks.locator = toyplot.locator.Explicit(locations=locations, labels=labels)
axes.x.ticks.show = True
axes.x.ticks.labels.angle = 90
axes.x.ticks.labels.style = {"baseline-shift":0, "text-anchor":"end", "-toyplot-anchor-shift":"-6px"}
mark = axes.plot(y)
Explanation: Because timestamp labels tend to be fairly long, this is often a case where you'll want to adjust the orientation of the labels so they don't overlap (note in the following example that we had to make the canvas larger and position the axes manually on the canvas to make room for the vertical labels - and we manually placed the x axis label to avoid overlap):
End of explanation |
8,526 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The JAX emulator
Step1: Generate CIGALE SEDs
Step2: Generate values for CIGALE
Redshift
Step3: AGN frac
Step4: DeepNet building
I will build a multi input, multi output deepnet model as my emulator, with parameters as input and the observed flux as outputs. I will train on log10 flux to make the model easier to train, and have already standarised the input parameters. I wilkl be using stax which can be thought of as the Keras equivalent for JAX. This blog was useful starting point.
I will use batches to help train the network
Step5: Investigate performance of each band of emulator
To visulise performance of the trainied emulator, I will show the difference between real and emulated for each band.
Step6: Save network
Having trained and validated network, I need to save the network and relevant functions
Step7: Does SED look right? | Python Code:
from astropy.cosmology import WMAP9 as cosmo
import jax
import numpy as onp
import pylab as plt
import astropy.units as u
import scipy.integrate as integrate
%matplotlib inline
import jax.numpy as np
from jax import grad, jit, vmap, value_and_grad
from jax import random
from jax import vmap # for auto-vectorizing functions
from functools import partial # for use with vmap
from jax import jit # for compiling functions for speedup
from jax.experimental import stax # neural network library
from jax.experimental.stax import Conv, Dense, MaxPool, Relu, Flatten, LogSoftmax, LeakyRelu # neural network layers
from jax.experimental import optimizers
from jax.tree_util import tree_multimap # Element-wise manipulation of collections of numpy arrays
import matplotlib.pyplot as plt # visualization
# Generate key which is used to generate random numbers
key = random.PRNGKey(2)
from xidplus import cigale
onp.random.seed(2)
Explanation: The JAX emulator: CIGALE prototype
In this notebook, I will prototype my idea for emulating radiative transfer codes with a Deepnet in order for it to be used inside xidplus. As numpyro uses JAX, the Deepnet wil ideally be trained with a JAX network. I will use CIGALE
Advice from Kasia
Use the following modules:
* Dale 2014 dust module with one parameter ($\alpha$) however, $\alpha$ can only take certian values in Cigale
* 0.0625, 0.1250, 0.1875, 0.2500,0.3125, 0.3750, 0.4375, 0.5000, 0.5625, 0.6250, 0.6875, 0.7500,0.8125, 0.8750, 0.9375, 1.0000, 1.0625, 1.1250, 1.1875, 1.2500,1.3125, 1.3750, 1.4375, 1.5000, 1.5625, 1.6250, 1.6875, 1.7500, 1.8125, 1.8750, 1.9375, 2.0000, 2.0625, 2.1250, 2.1875, 2.2500,2.3125, 2.3750, 2.4375, 2.5000, 2.5625, 2.6250, 2.6875, 2.7500,2.8125, 2.8750, 2.9375, 3.0000, 3.0625, 3.1250, 3.1875, 3.2500, 3.3125, 3.3750, 3.4375, 3.5000, 3.5625, 3.6250, 3.6875, 3.7500, 3.8125, 3.8750, 3.9375, 4.0000
* sfhdelayed starforamtion history module. Has parameters $\tau$ (500-6500) ($age$ can be calculated from redshift). $f_{burst}$ is set to 0
* bc03stellar population synthesis module (don't change parameters)
* dustatt_2powerlaws
* set $Av_BC$ the V band attenuation in the birth clouds to between 0 - 4
* set BC_to_ISM_factor to 0.7
Final parameters: $alpha$, $AV_BC$,$\tau$,$z$,$SFR$,$AGN$
Ideally, I would generate values from prior. I can do that for $AV_BC$,$\tau$,$z$,$SFR$,$AGN$ but not $\alpha$ given that there are fixed values.
End of explanation
from astropy.io import fits
from astropy.table import Table
import scipy.stats as stats
alpha=onp.array([0.0625, 0.1250, 0.1875, 0.2500,0.3125, 0.3750, 0.4375, 0.5000, 0.5625, 0.6250, 0.6875, 0.7500,0.8125, 0.8750, 0.9375, 1.0000, 1.0625, 1.1250, 1.1875, 1.2500,1.3125, 1.3750, 1.4375, 1.5000, 1.5625, 1.6250, 1.6875, 1.7500, 1.8125, 1.8750, 1.9375, 2.0000, 2.0625, 2.1250, 2.1875, 2.2500,2.3125, 2.3750, 2.4375, 2.5000, 2.5625, 2.6250, 2.6875, 2.7500,2.8125, 2.8750, 2.9375, 3.0000, 3.0625, 3.1250, 3.1875, 3.2500, 3.3125, 3.3750, 3.4375, 3.5000, 3.5625, 3.6250, 3.6875, 3.7500, 3.8125, 3.8750, 3.9375, 4.0000])
alpha_rv = stats.randint(0, len(alpha))
av_bc_rv=stats.uniform(0.1,4.0)
tau_rv=stats.randint(500,6500)
z_rv=stats.uniform(0.01,6)
sfr_rv=stats.loguniform(0.01,30000)
agn_frac_rv=stats.beta(1,3)
from astropy.cosmology import Planck13
z=z_rv.rvs(1)[0]
onp.int(Planck13.age(z).value*1000)
alpha[alpha_rv.rvs(1)[0]]
nsamp=1
from astropy.constants import L_sun, M_sun
from astropy.table import vstack
col_scale=['spire_250','spire_350','spire_500','dust.luminosity','sfh.sfr','stellar.m_star']
parameter_names=onp.array(['tau_main','age_main','Av_BC','alpha','fracAGN','redshift'])
all_SEDs=[]
for i in range(0,nsamp):
z=z_rv.rvs(1)[0]
parameters={'tau_main':[tau_rv.rvs(1)[0]],'age_main':[onp.int(Planck13.age(z).value*1000)],
'Av_BC':[av_bc_rv.rvs(1)[0]],'alpha':[alpha[alpha_rv.rvs(1)[0]]],'fracAGN':[agn_frac_rv.rvs(1)[0]],'redshift':[z]}
path_to_cigale='/Volumes/pdh_storage/cigale/'
path_to_ini_file='pcigale_kasia_nn.ini'
SEDs=cigale.generate_SEDs(parameter_names, parameters, path_to_cigale, path_to_ini_file, filename = 'tmp_single')
#set more appropriate units for dust
SEDs['dust.luminosity']=SEDs['dust.luminosity']/L_sun.value
scale=1.0/SEDs['sfh.sfr']
for c in col_scale:
SEDs[c]=SEDs[c]*scale*sfr_rv.rvs(1)[0]
all_SEDs.append(SEDs)
if i and i % 100 == 0:
tmp_SEDs=vstack(all_SEDs)
tmp_SEDs.write('kasia_gen_SEDs_{}.fits'.format(i),overwrite=True)
all_SEDs=[]
all_SEDs[0]
Explanation: Generate CIGALE SEDs
End of explanation
onp.array2string(10.0**np.arange(-2.5,0.77,0.1), separator=',',formatter={'float_kind':lambda x: "%.4f" % x}).replace('\n','')
onp.array2string(np.arange(0.1,4,0.3),separator=',',formatter={'float_kind':lambda x: "%.4f" % x}).replace('\n','')
Explanation: Generate values for CIGALE
Redshift
End of explanation
onp.array2string(np.arange(0.001,1,0.075),separator=',',formatter={'float_kind':lambda x: "%.3f" % x}).replace('\n','')
SEDs=Table.read('/Volumes/pdh_storage/cigale/out/models-block-0.fits')
#set more appropriate units for dust
from astropy.constants import L_sun, M_sun
SEDs['dust.luminosity']=SEDs['dust.luminosity']/L_sun.value
SEDs=SEDs[onp.isfinite(SEDs['spire_250'])]
SEDs
from astropy.table import vstack
(1.0/dataset['sfh.sfr'])*dataset['sfh.sfr']*10.0**scale_table
# define a range of scales
scale=np.arange(8,14,0.25)
#repeat the SED table by the number of scale steps
dataset=vstack([SEDs for i in range(0,scale.size)])
#repeat the scale range by the number of entries in table (so I can easily multiply each column)
scale_table=np.repeat(scale,len(SEDs))
#parameters to scale
col_scale=['spire_250','spire_350','spire_500','dust.luminosity','sfh.sfr','stellar.m_star']
for c in col_scale:
dataset[c]=dataset[c]*10.0**scale_table
dataset['log10_sfh.sfr']=onp.log10(dataset['sfh.sfr'])
dataset['log10_universe.redshift']=onp.log10(dataset['universe.redshift'])
# transform AGN fraction to logit scale
dataset['logit_agnfrac']=onp.log(dataset['agn.fracAGN']/(1-dataset['agn.fracAGN']))
#shuffle dataset
dataset=dataset[onp.random.choice(len(dataset), len(dataset), replace=False)]
plt.hist(dataset['log10_sfh.sfr'],bins=(np.arange(0,14)));
dataset
Explanation: AGN frac
End of explanation
dataset=dataset[0:18000000]
len(dataset)/1200
split=0.75
inner_batch_size=1200
train_ind=onp.round(0.75*len(dataset)).astype(int)
train=dataset[0:train_ind]
validation=dataset[train_ind:]
input_cols=['log10_sfh.sfr','agn.fracAGN','universe.redshift', 'attenuation.Av_BC','dust.alpha','sfh.tau_main']
output_cols=['spire_250','spire_350','spire_500']
train_batch_X=np.asarray([i.data for i in train[input_cols].values()]).reshape(len(input_cols)
,inner_batch_size,onp.round(len(train)/inner_batch_size).astype(int)).T.astype(float)
train_batch_Y=np.asarray([np.log(i.data) for i in train[output_cols].values()]).reshape(len(output_cols),
inner_batch_size,onp.round(len(train)/inner_batch_size).astype(int)).T.astype(float)
validation_batch_X=np.asarray([i.data for i in validation[input_cols].values()]).reshape(len(input_cols)
,inner_batch_size,onp.round(len(validation)/inner_batch_size).astype(int)).T.astype(float)
validation_batch_Y=np.asarray([np.log(i.data) for i in validation[output_cols].values()]).reshape(len(output_cols),
inner_batch_size,onp.round(len(validation)/inner_batch_size).astype(int)).T.astype(float)
# Use stax to set up network initialization and evaluation functions
net_init, net_apply = stax.serial(
Dense(128), LeakyRelu,
Dense(128), LeakyRelu,
Dense(128), LeakyRelu,
Dense(128), Relu,
Dense(len(output_cols))
)
in_shape = (-1, len(input_cols),)
out_shape, net_params = net_init(key,in_shape)
def loss(params, inputs, targets):
# Computes average loss for the batch
predictions = net_apply(params, inputs)
return np.mean((targets - predictions)**2)
def batch_loss(p,x_b,y_b):
loss_b=vmap(partial(loss,p))(x_b,y_b)
return np.mean(loss_b)
opt_init, opt_update, get_params= optimizers.adam(step_size=5e-4)
out_shape, net_params = net_init(key,in_shape)
opt_state = opt_init(net_params)
@jit
def step(i, opt_state, x1, y1):
p = get_params(opt_state)
g = grad(batch_loss)(p, x1, y1)
loss_tmp=batch_loss(p,x1,y1)
return opt_update(i, g, opt_state),loss_tmp
np_batched_loss_1 = []
valid_loss=[]
for i in range(10000):
opt_state, l = step(i, opt_state, train_batch_X, train_batch_Y)
p = get_params(opt_state)
valid_loss.append(batch_loss(p,validation_batch_X,validation_batch_Y))
np_batched_loss_1.append(l)
if i % 100 == 0:
print(i)
net_params = get_params(opt_state)
for i in range(2000):
opt_state, l = step(i, opt_state, train_batch_X, train_batch_Y)
p = get_params(opt_state)
valid_loss.append(batch_loss(p,validation_batch_X,validation_batch_Y))
np_batched_loss_1.append(l)
if i % 100 == 0:
print(i)
net_params = get_params(opt_state)
plt.figure(figsize=(20,10))
plt.semilogy(np_batched_loss_1,label='Training loss')
plt.semilogy(valid_loss,label='Validation loss')
plt.xlabel('Iteration')
plt.ylabel('Loss (MSE)')
plt.legend()
Explanation: DeepNet building
I will build a multi input, multi output deepnet model as my emulator, with parameters as input and the observed flux as outputs. I will train on log10 flux to make the model easier to train, and have already standarised the input parameters. I wilkl be using stax which can be thought of as the Keras equivalent for JAX. This blog was useful starting point.
I will use batches to help train the network
End of explanation
net_params = get_params(opt_state)
predictions = net_apply(net_params,validation_batch_X)
validation_batch_X.shape
validation_batch_X[0,:,:].shape
res=((np.exp(predictions)-np.exp(validation_batch_Y))/(np.exp(validation_batch_Y)))
fig,axes=plt.subplots(1,len(output_cols),figsize=(50,len(output_cols)))
for i in range(0,len(output_cols)):
axes[i].hist(res[:,:,i].flatten()*100.0,np.arange(-10,10,0.1))
axes[i].set_title(output_cols[i])
axes[i].set_xlabel(r'$\frac{f_{pred} - f_{True}}{f_{True}} \ \%$ error')
plt.subplots_adjust(wspace=0.5)
Explanation: Investigate performance of each band of emulator
To visulise performance of the trainied emulator, I will show the difference between real and emulated for each band.
End of explanation
import cloudpickle
with open('CIGALE_emulator_20210330_log10sfr_uniformAGN_z.pkl', 'wb') as f:
cloudpickle.dump({'net_init':net_init,'net_apply': net_apply,'params':net_params}, f)
net_init, net_apply
Explanation: Save network
Having trained and validated network, I need to save the network and relevant functions
End of explanation
wave=np.array([250,350,500])
plt.loglog(wave,np.exp(net_apply(net_params,np.array([2.95, 0.801, 0.1]))),'o')
#plt.loglog(wave,10.0**net_apply(net_params,np.array([3.0,0.0,0.0])),'o')
plt.loglog(wave,dataset[(dataset['universe.redshift']==0.1) & (dataset['agn.fracAGN'] == 0.801) & (dataset['sfh.sfr']>900) & (dataset['sfh.sfr']<1100)][output_cols].values())
dataset[(dataset['universe.redshift']==0.1) & (dataset['agn.fracAGN'] == 0.801) & (dataset['sfh.sfr']>900) & (dataset['sfh.sfr']<1100)]
import xidplus
from xidplus.numpyro_fit.misc import load_emulator
obj=load_emulator('CIGALE_emulator_20210330_log10sfr_uniformAGN_z.pkl')
type(obj['params'])
import json
import numpy as np
np.savez('CIGALE_emulator_20210610_kasia',obj['params'],allow_pickle=True)
ls
x=np.load('params_save.npz',allow_pickle=True)
x['arr_0'].tolist()
obj['params']
Explanation: Does SED look right?
End of explanation |
8,527 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Assignment 5
The goal of this assignment is to train a Word2Vec skip-gram model over Text8 data.
Step2: Download the data from the source website if necessary.
Step4: Read the data into a string.
Step5: Build the dictionary and replace rare words with UNK token.
Step6: Function to generate a training batch for the skip-gram model.
Step7: Train a skip-gram model. | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
%matplotlib inline
from __future__ import print_function
import collections
import math
import numpy as np
import os
import random
import tensorflow as tf
import zipfile
from matplotlib import pylab
from six.moves import range
from six.moves.urllib.request import urlretrieve
from sklearn.manifold import TSNE
from itertools import compress
Explanation: Deep Learning
Assignment 5
The goal of this assignment is to train a Word2Vec skip-gram model over Text8 data.
End of explanation
url = 'http://mattmahoney.net/dc/'
def maybe_download(filename, expected_bytes):
Download a file if not present, and make sure it's the right size.
if not os.path.exists(filename):
filename, _ = urlretrieve(url + filename, filename)
statinfo = os.stat(filename)
if statinfo.st_size == expected_bytes:
print('Found and verified %s' % filename)
else:
print(statinfo.st_size)
raise Exception(
'Failed to verify ' + filename + '. Can you get to it with a browser?')
return filename
filename = maybe_download('text8.zip', 31344016)
Explanation: Download the data from the source website if necessary.
End of explanation
def read_data(filename):
Extract the first file enclosed in a zip file as a list of words
with zipfile.ZipFile(filename) as f:
data = tf.compat.as_str(f.read(f.namelist()[0])).split()
return data
words = read_data(filename)
print('Data size %d' % len(words))
Explanation: Read the data into a string.
End of explanation
vocabulary_size = 50000
def build_dataset(words):
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
if word in dictionary:
index = dictionary[word]
else:
index = 0 # dictionary['UNK']
unk_count = unk_count + 1
data.append(index)
count[0][1] = unk_count
reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reverse_dictionary
data, count, dictionary, reverse_dictionary = build_dataset(words)
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10])
del words # Hint to reduce memory.
Explanation: Build the dictionary and replace rare words with UNK token.
End of explanation
data_index = 0
def generate_batch(batch_size, num_skips, skip_window):
global data_index
assert batch_size % num_skips == 0
assert num_skips <= 2 * skip_window
batch = np.ndarray(shape=(batch_size), dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
buffer = collections.deque(maxlen=span)
for _ in range(span):
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
for i in range(batch_size // num_skips):
target = skip_window # target label at the center of the buffer
targets_to_avoid = [ skip_window ]
for j in range(num_skips):
while target in targets_to_avoid:
target = random.randint(0, span - 1)
targets_to_avoid.append(target)
batch[i * num_skips + j] = buffer[skip_window]
labels[i * num_skips + j, 0] = buffer[target]
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
return batch, labels
def generate_batch_cbow(batch_size, skip_window):
global data_index
surrounding_words = 2 * skip_window # words surrounding the target
assert batch_size % surrounding_words == 0
total_labels = batch_size / surrounding_words
batch = np.ndarray(shape=(batch_size), dtype=np.int32)
labels = np.ndarray(shape=(total_labels, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
buffer = collections.deque(maxlen=span)
for _ in range(span):
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
for i in range(total_labels):
target = skip_window # target label at the center of the buffer
targets_to_avoid = [ skip_window ]
labels[i, 0] = buffer[target] # label the target
for j in range(surrounding_words):
while target in targets_to_avoid:
target = random.randint(0, span - 1)
targets_to_avoid.append(target)
batch[i * surrounding_words + j] = buffer[target]
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
return batch, labels
Explanation: Function to generate a training batch for the skip-gram model.
End of explanation
batch_size = 128
embedding_size = 128 # Dimension of the embedding vector.
skip_window = 1 # How many words to consider left and right.
num_skips = 2 # How many times to reuse an input to generate a label.
# We pick a random validation set to sample nearest neighbors. here we limit the
# validation samples to the words that have a low numeric ID, which by
# construction are also the most frequent.
valid_size = 16 # Random set of words to evaluate similarity on.
valid_window = 100 # Only pick dev samples in the head of the distribution.
valid_examples = np.array(random.sample(range(valid_window), valid_size))
num_sampled = 64 # Number of negative examples to sample.
surrounding_words = 2 * skip_window
total_labels = batch_size / surrounding_words
graph = tf.Graph()
with graph.as_default(), tf.device('/cpu:0'):
# Input data.
train_dataset = tf.placeholder(tf.int32, shape=[batch_size])
train_labels = tf.placeholder(tf.int32, shape=[total_labels, 1])
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
# Variables.
embeddings = tf.Variable(
tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
softmax_weights = tf.Variable(
tf.truncated_normal([vocabulary_size, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
softmax_biases = tf.Variable(tf.zeros([vocabulary_size]))
# Model.
# Look up embeddings for inputs.
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
mask = np.zeros(batch_size, dtype=np.int32)
mask_index = -1
for i in range(batch_size):
if i % surrounding_words == 0:
mask_index = mask_index + 1
mask[i] = mask_index
embed_filtered = tf.segment_sum(embed, mask)
# Compute the softmax loss, using a sample of the negative labels each time.
loss = tf.reduce_mean(
tf.nn.sampled_softmax_loss(weights=softmax_weights, biases=softmax_biases, inputs=embed_filtered,
labels=train_labels, num_sampled=num_sampled, num_classes=vocabulary_size))
# Optimizer.
# Note: The optimizer will optimize the softmax_weights AND the embeddings.
# This is because the embeddings are defined as a variable quantity and the
# optimizer's `minimize` method will by default modify all variable quantities
# that contribute to the tensor it is passed.
# See docs on `tf.train.Optimizer.minimize()` for more details.
optimizer = tf.train.AdagradOptimizer(1.0).minimize(loss)
# Compute the similarity between minibatch examples and all embeddings.
# We use the cosine distance:
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
valid_embeddings = tf.nn.embedding_lookup(
normalized_embeddings, valid_dataset)
similarity = tf.matmul(valid_embeddings, tf.transpose(normalized_embeddings))
num_steps = 100001
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().run()
print('Initialized')
average_loss = 0
for step in range(num_steps):
batch_data, batch_labels = generate_batch_cbow(
batch_size, skip_window)
feed_dict = {train_dataset : batch_data, train_labels : batch_labels}
_, l = session.run([optimizer, loss], feed_dict=feed_dict)
average_loss += l
if step % 2000 == 0:
if step > 0:
average_loss = average_loss / 2000
# The average loss is an estimate of the loss over the last 2000 batches.
print('Average loss at step %d: %f' % (step, average_loss))
average_loss = 0
# note that this is expensive (~20% slowdown if computed every 500 steps)
if step % 10000 == 0:
sim = similarity.eval()
for i in range(valid_size):
valid_word = reverse_dictionary[valid_examples[i]]
top_k = 8 # number of nearest neighbors
nearest = (-sim[i, :]).argsort()[1:top_k+1]
log = 'Nearest to %s:' % valid_word
for k in range(top_k):
close_word = reverse_dictionary[nearest[k]]
log = '%s %s,' % (log, close_word)
print(log)
final_embeddings = normalized_embeddings.eval()
num_points = 400
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
two_d_embeddings = tsne.fit_transform(final_embeddings[1:num_points+1, :])
def plot(embeddings, labels):
assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
pylab.figure(figsize=(15,15)) # in inches
for i, label in enumerate(labels):
x, y = embeddings[i,:]
pylab.scatter(x, y)
pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
ha='right', va='bottom')
pylab.show()
words = [reverse_dictionary[i] for i in range(1, num_points+1)]
plot(two_d_embeddings, words)
Explanation: Train a skip-gram model.
End of explanation |
8,528 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calculating radial distribution functions
Radial distribution functions can be calculated from one or more pymatgen Structure objects by using the vasppy.rdf.RadialDistributionFunction class.
Step1: The default required arguments for creating a RadialDistributionFunction object are a list of pymatgen Structure objects, and the numerical indices of the atoms (or Site objects) that we want to compute the rdf between.
Step2: To compute a rdf between different species, we need to pass both indices_i and indices_j.
Step3: The Na and Cl sublattices are equivalent, so the Na–Na and Cl–Cl rdfs sit on top of each other.
A smeared rdf can be produced using the smeared_rdf() method, which applies a Gaussian kernel to the raw rdf data. The smeared_rdf() method takes on optional argument sigma, which can be used to set the width of the Gaussian (default = 0.1)
Step4: Selecting atoms by their species strings
Atom indices can also be selected by species string with the RadialDistributionFunction.from_species_strings() method
Step5: Calculating a RDF from a VASP XDATCAR
Step6: Weighted RDF calculations
For calculating RDFs from Monte Carlo simulation trajectories RadialDistributionFunction can be passed an optional weights argument, which takes a list of numerical weights for each structure. | Python Code:
# Create a pymatgen Structure for NaCl
from pymatgen import Structure, Lattice
# Create a pymatgen Structure for NaCl
from pymatgen import Structure, Lattice
a = 5.6402 # NaCl lattice parameter
lattice = Lattice.from_parameters(a, a, a, 90.0, 90.0, 90.0)
lattice
structure = Structure.from_spacegroup(sg='Fm-3m', lattice=lattice,
species=['Na', 'Cl'],
coords=[[0,0,0], [0.5, 0, 0]])
structure
from vasppy.rdf import RadialDistributionFunction
Explanation: Calculating radial distribution functions
Radial distribution functions can be calculated from one or more pymatgen Structure objects by using the vasppy.rdf.RadialDistributionFunction class.
End of explanation
indices_na = [i for i, site in enumerate(structure) if site.species_string is 'Na']
indices_cl = [i for i, site in enumerate(structure) if site.species_string is 'Cl']
print(indices_na)
print(indices_cl)
rdf_nana = RadialDistributionFunction(structures=[structure],
indices_i=indices_na)
rdf_clcl = RadialDistributionFunction(structures=[structure],
indices_i=indices_cl)
Explanation: The default required arguments for creating a RadialDistributionFunction object are a list of pymatgen Structure objects, and the numerical indices of the atoms (or Site objects) that we want to compute the rdf between.
End of explanation
rdf_nacl = RadialDistributionFunction(structures=[structure],
indices_i=indices_na, indices_j=indices_cl)
import matplotlib.pyplot as plt
plt.plot(rdf_nana.r, rdf_nana.rdf, label='Na-Na')
plt.plot(rdf_clcl.r, rdf_clcl.rdf, label='Cl-Cl')
plt.plot(rdf_nacl.r, rdf_nacl.rdf, label='Na-Cl')
plt.legend()
plt.show()
Explanation: To compute a rdf between different species, we need to pass both indices_i and indices_j.
End of explanation
plt.plot(rdf_nana.r, rdf_nana.smeared_rdf(), label='Na-Na') # default smearing of 0.1
plt.plot(rdf_clcl.r, rdf_clcl.smeared_rdf(sigma=0.050), label='Cl-Cl')
plt.plot(rdf_nacl.r, rdf_nacl.smeared_rdf(sigma=0.2), label='Na-Cl')
plt.legend()
plt.show()
Explanation: The Na and Cl sublattices are equivalent, so the Na–Na and Cl–Cl rdfs sit on top of each other.
A smeared rdf can be produced using the smeared_rdf() method, which applies a Gaussian kernel to the raw rdf data. The smeared_rdf() method takes on optional argument sigma, which can be used to set the width of the Gaussian (default = 0.1)
End of explanation
rdf_nana = RadialDistributionFunction.from_species_strings(structures=[structure],
species_i='Na')
rdf_clcl = RadialDistributionFunction.from_species_strings(structures=[structure],
species_i='Cl')
rdf_nacl = RadialDistributionFunction.from_species_strings(structures=[structure],
species_i='Na', species_j='Cl')
plt.plot(rdf_nana.r, rdf_nana.smeared_rdf(), label='Na-Na')
plt.plot(rdf_clcl.r, rdf_clcl.smeared_rdf(), label='Cl-Cl')
plt.plot(rdf_nacl.r, rdf_nacl.smeared_rdf(), label='Na-Cl')
plt.legend()
plt.show()
Explanation: Selecting atoms by their species strings
Atom indices can also be selected by species string with the RadialDistributionFunction.from_species_strings() method:
End of explanation
from pymatgen.io.vasp import Xdatcar
xd = Xdatcar('data/NaCl_800K_MD_XDATCAR')
rdf_nana_800K = RadialDistributionFunction.from_species_strings(structures=xd.structures,
species_i='Na')
rdf_clcl_800K = RadialDistributionFunction.from_species_strings(structures=xd.structures,
species_i='Cl')
rdf_nacl_800K = RadialDistributionFunction.from_species_strings(structures=xd.structures,
species_i='Na', species_j='Cl')
plt.plot(rdf_nana_800K.r, rdf_nana_800K.smeared_rdf(), label='Na-Na')
plt.plot(rdf_clcl_800K.r, rdf_clcl_800K.smeared_rdf(), label='Cl-Cl')
plt.plot(rdf_nacl_800K.r, rdf_nacl_800K.smeared_rdf(), label='Na-Cl')
plt.legend()
plt.show()
Explanation: Calculating a RDF from a VASP XDATCAR
End of explanation
struct_1 = struct_2 = struct_3 = structure
rdf_nacl_mc = RadialDistributionFunction(structures=[struct_1, struct_2, struct_3],
indices_i=indices_na, indices_j=indices_cl,
weights=[34, 27, 146])
# structures and weights lists must be equal lengths
Explanation: Weighted RDF calculations
For calculating RDFs from Monte Carlo simulation trajectories RadialDistributionFunction can be passed an optional weights argument, which takes a list of numerical weights for each structure.
End of explanation |
8,529 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Memory consumption
Step1: Counting error rate | Python Code:
import collections
import subprocess
import itertools
import os
import time
import madoka
import numpy as np
import redis
ALPHANUM = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
NUM_ALPHANUM_COMBINATION = 238328
zipf_array = np.random.zipf(1.5, NUM_ALPHANUM_COMBINATION)
def python_memory_usage():
return int(subprocess.getoutput('ps up %s' % os.getpid()).split()[15])
def redis_memory_usage():
lines = subprocess.getoutput('ps').splitlines()
for line in lines:
if 'redis-server' in line:
pid = line.split()[0]
break
return int(subprocess.getoutput('ps up %s' % pid).split()[15])
def count(counter):
for (i, chars) in enumerate(itertools.product(ALPHANUM, repeat=3)):
chars = ''.join(chars)
counter[chars] = int(zipf_array[i])
return counter
def benchmark(counter, start_mem_usage):
counter = count(counter)
end_mem_usage = python_memory_usage()
diff = end_mem_usage - start_mem_usage
print('memory consumption is {:,d} KB'.format(diff))
return counter
def redis_benchmark():
db = redis.Redis()
db.flushall()
start_mem_usage = redis_memory_usage()
with db.pipeline() as pipe:
for (i, chars) in enumerate(itertools.product(ALPHANUM, repeat=3)):
chars = ''.join(chars)
pipe.set(chars, int(zipf_array[i]))
pipe.execute()
end_mem_usage = redis_memory_usage()
diff = end_mem_usage - start_mem_usage
print('memory consumption is {:,d} KB'.format(diff))
print('collections.Counter')
start_mem_usage = python_memory_usage()
start_time = time.process_time()
counter = collections.Counter()
benchmark(counter, start_mem_usage)
end_time = time.process_time()
print('Processsing Time is %5f sec.' % (end_time - start_time))
del counter
print('*' * 30)
print('madoka.Sketch')
start_mem_usage = python_memory_usage()
start_time = time.process_time()
sketch = madoka.Sketch()
benchmark(sketch, start_mem_usage)
end_time = time.process_time()
print('Processsing Time is %5f sec.' % (end_time - start_time))
del sketch
print('*' * 30)
print('Redis')
start_time = time.process_time()
redis_benchmark()
end_time = time.process_time()
print('Processsing Time is %5f sec.' % (end_time - start_time))
Explanation: Memory consumption
End of explanation
sketch = madoka.Sketch()
diffs = []
for (i, chars) in enumerate(itertools.product(ALPHANUM, repeat=3)):
chars = ''.join(chars)
sketch[chars] = int(zipf_array[i])
diff = abs(sketch[chars] - int(zipf_array[i]))
if diff > 0:
diffs.append(diff / int(zipf_array[i]) * 100)
else:
diffs.append(0)
print(np.average(diffs))
Explanation: Counting error rate
End of explanation |
8,530 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PLEASE MAKE A COPY BEFORE CHANGING
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https
Step1: Input your settings to run the model
project_id
Step4: Get data from BigQuery
Query the Google Analytics 360 in BigQuery to create the RFM matrix containing the following columns.
user_id
Step5: Train the model
Using the transformed dataset we fit the BetaGeoFitter model. Once the model is trained we can plot probability of alive Matrix.
Once the BetaGeofitter model is trained, we can train a Gamma Model to estimate future average order value.
Step6: Results
In this section we display the following by user
Step7: Optional | Python Code:
!pip install -q lifetimes
!pip install -q --upgrade git+https://github.com/HIPS/autograd.git@master
!pip install -U -q PyDrive
from google.colab import auth
from googleapiclient.discovery import build
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from oauth2client.client import GoogleCredentials
from lifetimes import BetaGeoFitter
from lifetimes.plotting import plot_frequency_recency_matrix
from lifetimes.plotting import plot_probability_alive_matrix
from lifetimes.plotting import plot_period_transactions
from lifetimes.plotting import plot_calibration_purchases_vs_holdout_purchases
from lifetimes.plotting import plot_history_alive
from lifetimes import GammaGammaFitter
import datetime
import pandas as pd
import matplotlib.pyplot as plt
# Allow plots to be displayed inline.
%matplotlib inline
# Authenticate the user
auth.authenticate_user()
Explanation: PLEASE MAKE A COPY BEFORE CHANGING
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
<b>Important</b>
This content are intended for educational and informational purposes only.
Introduction
objective: The goal of this colab is to calculate the Lifetime Value of your customer base. The method used for calculation is the BG/NDB model as described in this paper.
Code Section
End of explanation
project_id = 'my-project'#@param
table_name = 'bigquery-public-data.google_analytics_sample.ga_sessions_*'#@param
time_unit = 'weeks'#@param ['days', 'weeks', 'months']
units_to_predict = 52#@param
start_date = '2018-01-01'#@param{type:"date"}
end_date = '2019-01-01'#@param{type:"date"}
number_of_segments = 5#@param
id_type = 'client_id'#@param ['client_id', 'user_id']
user_id_dimension_index = 0#@param
data_import_key_index = 11#@param
data_import_value_index = 12#@param
dc = {}
dc['start_date'] = start_date.replace('-', '')
dc['end_date'] = end_date.replace('-', '')
dc['table_name'] = table_name
dc['id_type'] = id_type
dc['user_id_dimension_index'] = user_id_dimension_index
if time_unit == 'days':
dc['time_unit'] = 1
elif time_unit == 'weeks' or time_unit == '':
dc['time_unit'] = 7
else:
dc['time_unit'] = 12
Explanation: Input your settings to run the model
project_id: The id of Google Cloud project where the query will run.
table_name: Name of the Google Analytics table
transaction.
time_unit: The granularity to group transactions (weeks is usually the best)
units_to_predict: Number of periods to predict (in case of using weeks as time_unit, 52 would predict a year ahead)
number_of_segments: Number segments to group the users in.
id_type: Two options of IDs. client_id is based on GA cookie (not cross device and can change overtime. user_id can be provide better acurracy).
use_id_dimension_index: The custom dimension index that is holding the user id value. If the id_type is user_id, this field is mandatory.
data_import_key_index: The custom dimension index that is holding the user id. If you are not sure, don't worry, it can be changed later.
data_import_value_index: The custom dimension index that is holding the LTV segment. If you are not sure, don't worry, it can be changed later.
New Section
End of explanation
q1 =
WITH transactions as (
SELECT
clientid AS user_id,
PARSE_DATE('%Y%m%d', date) AS transaction_date,
SUM(totals.totalTransactionRevenue) / 1000000 AS transaction_value
FROM
`{table_name}`
WHERE
_TABLE_SUFFIX BETWEEN '{start_date}'
AND '{end_date}' AND totals.transactions > 0
AND totals.totalTransactionRevenue > 0
GROUP BY
1, 2)
SELECT
user_id,
COUNT(1) AS total_transactions,
ROUND(SUM(transaction_value)/COUNT(1),1) AS average_order_value,
(COUNT(1)-1) AS frequency,
ROUND (DATE_DIFF(MAX(transaction_date),
MIN(transaction_date),
DAY) / {time_unit} ,1) # time multiplyer
AS recency,
ROUND((DATE_DIFF((SELECT MAX(transaction_date) FROM transactions),
MIN(transaction_date),
DAY)+1) / {time_unit} ,1) # time multiplyer
AS T
FROM
transactions
GROUP BY
1
.format(**dc)
q2 =
WITH transactions as(
SELECT
cds.value as user_id,
PARSE_DATE('%Y%m%d', date) AS transaction_date,
SUM(totals.totalTransactionRevenue) / 1000000 AS transaction_value
FROM
`{table_name}`,
UNNEST(customdimensions) AS cds
WHERE
_TABLE_SUFFIX BETWEEN '{start_date}'
AND '{end_date}'
AND cds.index = {user_id_dimension_index}
AND totals.transactions > 0
GROUP BY
1,2)
SELECT
user_id,
COUNT(1) AS total_transactions,
ROUND(SUM(transaction_value)/COUNT(1),1) AS average_order_value,
(COUNT(1)-1) AS frequency,
ROUND (DATE_DIFF(MAX(transaction_date),
MIN(transaction_date),
DAY) / 7 ,1) # time multiplyer
AS recency,
ROUND((DATE_DIFF((SELECT MAX(transaction_date) FROM transactions),
MIN(transaction_date),
DAY)+1) / 7 ,1) # time multiplyer
AS T
FROM
transactions
GROUP BY
1
.format(**dc)
if id_type == 'user_id' and user_id_dimension_index != 0:
q = q2
else:
q = q1
df = pd.io.gbq.read_gbq(q, project_id=project_id, verbose=False, dialect='standard')
df.head()
Explanation: Get data from BigQuery
Query the Google Analytics 360 in BigQuery to create the RFM matrix containing the following columns.
user_id: id of the user
total_transactions: Ammount of transaction during the period.
average_order_value: Sum of total_transaction_value / total_transactions
frequency: Represents the number of repeat purchases the customer has made.
recency: Represents the age of the customer when they made their most recent purchase. This is equal to the duration between a customer’s first purchase and their latest purchase. (Thus if they have made only 1 purchase, the recency is 0.)
T: Represents the age of the customer in whatever time units chosen (weekly, in the above dataset). This is equal to the duration between a customer’s first purchase and the end of the period under study.
End of explanation
bgf = BetaGeoFitter(penalizer_coef=0.0)
bgf.fit(df['frequency'], df['recency'], df['T'])
plt.figure(figsize=(10,10))
plot_frequency_recency_matrix(bgf)
;
plt.figure(figsize=(10,10))
plot_probability_alive_matrix(bgf)
;
ggf = GammaGammaFitter(penalizer_coef = 0)
ggf.fit(df['total_transactions'],
df['average_order_value'])
df['prob_alive'] = bgf.conditional_probability_alive(df['frequency'], df['recency'], df['T'])
df['predicted_transactions'] = bgf.conditional_expected_number_of_purchases_up_to_time(units_to_predict, df['frequency'], df['recency'], df['T'])
df['predicted_aov'] = ggf.conditional_expected_average_profit(df['total_transactions'], df['average_order_value'])
df['predicted_ltv'] = df['predicted_transactions'] * df['predicted_aov']
Explanation: Train the model
Using the transformed dataset we fit the BetaGeoFitter model. Once the model is trained we can plot probability of alive Matrix.
Once the BetaGeofitter model is trained, we can train a Gamma Model to estimate future average order value.
End of explanation
df['segment'] = pd.qcut(df['predicted_ltv'], number_of_segments, labels=list(range(1,number_of_segments+1)))
summary = df.groupby('segment').agg({'prob_alive':'mean', 'predicted_transactions': 'mean',
'predicted_aov': 'mean',
'predicted_ltv': ['mean','sum']})
summary = summary.round(2)
df.head()
data_import_key_index = 'ga:dimension{}'.format(data_import_key_index)
data_import_value_index = 'ga:dimension{}'.format(data_import_value_index)
df = df[['user_id', 'segment']]
df.columns = [data_import_key_index, data_import_value_index]
df.head()
Explanation: Results
In this section we display the following by user:
prob_alive: The probability of a customer being alive
predicted_transactions: The predicted number of transactions in the predicted period
predicted_aov: The predicted average order value in the predicted period
predicted_ltv: The total customer life time value for the predicted period. (predicted_ltv = predicted_aov * predicted_transactions)
We also group the customer into N segments.
End of explanation
def output_to_googledrive(df, output_file_name='ltv.csv'):
date = str(datetime.datetime.today()).split()[0]
file_name = date + '_' + output_file_name
file_url = 'https://drive.google.com/open?id='
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
uploaded = drive.CreateFile({'title': file_name})
uploaded.SetContentString(df.to_csv(index=False))
uploaded.Upload()
print(file_name)
print('Full File URL: {}{}'.format(file_url, uploaded.get('id')))
output_to_googledrive(df, output_file_name='full_ltv.csv')
output_to_googledrive(summary, output_file_name='summary_ltv.csv')
Explanation: Optional: Save output to drive.
End of explanation |
8,531 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Instanciation de poppyrate
Exemple d'instanciation d'un poppyrate tel qu'il pourrais être lancé comme service, avec un serveur snap, http et remote(rpc).
Ce notebook peut servir de base à dupliquer pour instancier le robot et l'utiliser directement.
Step1: Logs
Activation des logs en info dans le fichier logs//poppyrate.log
Step2: Instanciation de l'objet robot
Création de l'objet robot avec les 3 services en tache de fond.
⚠ Attention pour couper ces services il faudra redemarrer le kernel ipython.
Step3: Utilisation du robot | Python Code:
import logging
import logging.handlers
from poppy_rate import PoppyRate
import poppy_rate
import poppy_rate.primitives as pp
Explanation: Instanciation de poppyrate
Exemple d'instanciation d'un poppyrate tel qu'il pourrais être lancé comme service, avec un serveur snap, http et remote(rpc).
Ce notebook peut servir de base à dupliquer pour instancier le robot et l'utiliser directement.
End of explanation
handler = logging.handlers.TimedRotatingFileHandler('logs/poppyrate.log', when="midnight", backupCount=10)
formatter = logging.Formatter('\033[1;30m%(asctime)s \033[0;33m%(levelname)s \033[1;32m%(threadName)s \033[0m%(module)s:%(lineno)-4s \033[0m%(message)s\033[0m')
handler.setFormatter(formatter)
handler.setLevel('INFO')
logging.root.handlers = []
logging.root.addHandler(handler)
logging.root.setLevel('INFO')
Explanation: Logs
Activation des logs en info dans le fichier logs//poppyrate.log
End of explanation
robot = PoppyRate(simulator = "vrep", use_snap=True, use_remote=True, use_http=True, start_services=True)
Explanation: Instanciation de l'objet robot
Création de l'objet robot avec les 3 services en tache de fond.
⚠ Attention pour couper ces services il faudra redemarrer le kernel ipython.
End of explanation
robot.play_sound.start()
robot.abs_x.goal_position = -10
robot.head_z.goal_position = 20
robot.dance_beat_motion.start()
robot.stand_position.start()
robot.say_hello.start()
import operator
# liste triée par t° de tuples (nom_moteur,t°)
temperatures =sorted([(m.name, m.present_temperature) for m in robot.motors], key=operator.itemgetter(1), reverse=True)
#affiche le tout
for m,t in temperatures:
print "{:>20}: {}°C".format(m,t)
robot.compliant = True
robot.close()
import os
directory = os.path.join(os.path.split(os.path.dirname(os.path.abspath(pp.__file__)))[0],'media','sounds')
[f[:-4] for f in os.listdir(directory) if f.endswith('.ogg')]
os.path.split?
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'media'
from types import MethodType
def say_something(something):
def fn(self):
print("hello %s" % something)
return fn
#def fn(self,):
# print("hello")
prim = robot.say_hello
for k in ['world', 'universe']:
setattr(prim, 'say_%s'%k, MethodType(say_something(k), prim, type(prim)))
prim.say_world()
Explanation: Utilisation du robot
End of explanation |
8,532 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
News Headline Analysis
In this project we're analyzing news headlines written by two journalists – a finance reporter from the Business Insider, and a celebrity reporter from the Huffington post – to find similarities and differences between the ways that these authors write headlines for their news articles and blog posts. Our selected reporters are
Step1: Let's see an example
Step2: Loading the data
Let's load the Pickled data file for the first author (Akin Oyedele) which contains 700 headlines, and let's see an example of what a headline might look like
Step3: Parsing the data
Now that we have all the headlines for the first author loaded, we're going to analyze them, create parse trees for each headline, and store them together with some basic information about the headline in the same object
Step4: Let's see what the numeric attributes for headlines written by this author look like. We're going to use Pandas for this.
Step5: From this information, we're going to extract the chunk type sequence of each headline (i.e. the first level of the parse tree) and use it as an indicator of the overall structure of the headline. So in the above example, we would extract and use the following sequence of chunk types in our analysis
Step6: Now let's see how that works with our chunk type sequences, for two randomly selected headlines from the first author
Step7: Pair-wise similarity matrix for the headlines
We're now going to apply the same sequence similarity metric to all of our headlines, and create a 700x700 matrix of pairwise similarity scores between the headlines
Step8: Visualization
To make things clearer and more understandable, let's try and put all the headlines written by the first author on a 2d scatter plot, where similarly structured headlines are close together.
For that we're going to first use tSNE to reduce the dimensionality of our similarity matrix from 700 down to 2
Step9: And to add a bit of color to our visualization, let's use K-Means to identify 5 clusters of similar headlines, which we will use in our visualization
Step10: Finally let's plot the actual chart using Bokeh
Step11: The above interactive chart shows a number of dense groups of headlines, as well as some sparse ones. Some of the dense groups that stand out more are
Step12: The basic stats don't show a significant difference between the headlines written by the two authors.
Step13: Now that we have analyzed the headlines for the second author, let's see how many common patterns exist between the two authors
Step14: We observe that about 50% (347/700) of the headlines have a similar structure.
Visualization of headlines by the two authors
Our approach here is quite similar to what we did for the first author. The only difference is that here we're going to use colors to indicate the author and not the cluster this time (blue for author1 and orange for author2). | Python Code:
from pattern.en import parsetree
Explanation: News Headline Analysis
In this project we're analyzing news headlines written by two journalists – a finance reporter from the Business Insider, and a celebrity reporter from the Huffington post – to find similarities and differences between the ways that these authors write headlines for their news articles and blog posts. Our selected reporters are:
Akin Oyedele the Business Insider who covers market updates; and
Carly Ledbetter from the Huffington Post who mainly writes about celebrities.
Approach
We're initially going to collect and parse news headlines from each of the authors in order to obtain a parse tree. Then we're going to extract certain information from these parse trees that are indicative of the overall structure of the headline.
Next, we will define a simple sequence similarity metric to compare any pair of headlines quantitatively, and we will apply the same method to all of the headlines we've gathered for each author, to find out how similar each pair of headlines is.
Finally, we're going to use K-Means and tSNE to produce a visual map of all the headlines, where we can see the similarities and the differences between the two authors more clearly.
Data
For this project we've gathered 700 headlines for each author using the AYLIEN News API which we're going to analyze using Python. You can obtain the Pickled data files directly from the GitHub repository, or by using the data collection notebook that we've prepared for this project.
A primer on parse trees
In linguistics, a parse tree is a rooted tree that represents the syntactic structure of a sentence, according to some pre-defined grammar.
For a simple sentence like "The cat sat on the mat", a parse tree might look like this:
We're going to use the Pattern library for Python to parse the headlines and create parse trees for them:
End of explanation
s = parsetree('The cat sat on the mat.')
for sentence in s:
for chunk in sentence.chunks:
print chunk.type, [(w.string, w.type) for w in chunk.words]
Explanation: Let's see an example:
End of explanation
import cPickle as pickle
author1 = pickle.load( open( "author1.p", "rb" ) )
author1[0]
Explanation: Loading the data
Let's load the Pickled data file for the first author (Akin Oyedele) which contains 700 headlines, and let's see an example of what a headline might look like:
End of explanation
for story in author1:
story["title_length"] = len(story["title"])
story["title_chunks"] = [chunk.type for chunk in parsetree(story["title"])[0].chunks]
story["title_chunks_length"] = len(story["title_chunks"])
author1[0]
Explanation: Parsing the data
Now that we have all the headlines for the first author loaded, we're going to analyze them, create parse trees for each headline, and store them together with some basic information about the headline in the same object:
End of explanation
import pandas as pd
df1 = pd.DataFrame.from_dict(author1)
df1.describe()
Explanation: Let's see what the numeric attributes for headlines written by this author look like. We're going to use Pandas for this.
End of explanation
import difflib
print "Similarity scores for...\n"
print "Two identical sequences: ", difflib.SequenceMatcher(None,["A","B","C"],["A","B","C"]).ratio()
print "Two similar sequences: ", difflib.SequenceMatcher(None,["A","B","C"],["A","B","D"]).ratio()
print "Two completely different sequences: ", difflib.SequenceMatcher(None,["A","B","C"],["X","Y","Z"]).ratio()
Explanation: From this information, we're going to extract the chunk type sequence of each headline (i.e. the first level of the parse tree) and use it as an indicator of the overall structure of the headline. So in the above example, we would extract and use the following sequence of chunk types in our analysis:
['NP', 'PP', 'NP', 'VP']
Similarity
We have loaded all the headlines written by the first author, and created and stored their parse trees. Next, we need to find a similarity metric that given two chunk type sequences, tells us how similar these two headlines are, from a structural perspective.
For that we're going to use the SequenceMatcher class of difflib, which produces a similarity score between 0 and 1 for any two sequences (Python lists):
End of explanation
v1 = author1[3]["title_chunks"]
v2 = author1[1]["title_chunks"]
print v1, v2, difflib.SequenceMatcher(None,v1,v2).ratio()
Explanation: Now let's see how that works with our chunk type sequences, for two randomly selected headlines from the first author:
End of explanation
import numpy as np
chunks = [author["title_chunks"] for author in author1]
m = np.zeros((700,700))
for i, chunkx in enumerate(chunks):
for j, chunky in enumerate(chunks):
m[i][j] = difflib.SequenceMatcher(None,chunkx,chunky).ratio()
Explanation: Pair-wise similarity matrix for the headlines
We're now going to apply the same sequence similarity metric to all of our headlines, and create a 700x700 matrix of pairwise similarity scores between the headlines:
End of explanation
from sklearn.manifold import TSNE
tsne_model = TSNE(n_components=2, verbose=1, random_state=0)
tsne = tsne_model.fit_transform(m)
Explanation: Visualization
To make things clearer and more understandable, let's try and put all the headlines written by the first author on a 2d scatter plot, where similarly structured headlines are close together.
For that we're going to first use tSNE to reduce the dimensionality of our similarity matrix from 700 down to 2:
End of explanation
from sklearn.cluster import MiniBatchKMeans
kmeans_model = MiniBatchKMeans(n_clusters=5, init='k-means++', n_init=1,
init_size=1000, batch_size=1000, verbose=False, max_iter=1000)
kmeans = kmeans_model.fit(m)
kmeans_clusters = kmeans.predict(m)
kmeans_distances = kmeans.transform(m)
Explanation: And to add a bit of color to our visualization, let's use K-Means to identify 5 clusters of similar headlines, which we will use in our visualization:
End of explanation
import bokeh.plotting as bp
from bokeh.models import HoverTool, BoxSelectTool
from bokeh.plotting import figure, show, output_notebook
colormap = np.array([
"#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c",
"#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5",
"#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f",
"#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5"
])
output_notebook()
plot_author1 = bp.figure(plot_width=900, plot_height=700, title="Author1",
tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave",
x_axis_type=None, y_axis_type=None, min_border=1)
plot_author1.scatter(x=tsne[:,0], y=tsne[:,1],
color=colormap[kmeans_clusters],
source=bp.ColumnDataSource({
"chunks": [x["title_chunks"] for x in author1],
"title": [x["title"] for x in author1],
"cluster": kmeans_clusters
}))
hover = plot_author1.select(dict(type=HoverTool))
hover.tooltips={"chunks": "@chunks (title: \"@title\")", "cluster": "@cluster"}
show(plot_author1)
Explanation: Finally let's plot the actual chart using Bokeh:
End of explanation
author2 = pickle.load( open( "author2.p", "rb" ) )
for story in author2:
story["title_length"] = len(story["title"])
story["title_chunks"] = [chunk.type for chunk in parsetree(story["title"])[0].chunks]
story["title_chunks_length"] = len(story["title_chunks"])
pd.DataFrame.from_dict(author2).describe()
Explanation: The above interactive chart shows a number of dense groups of headlines, as well as some sparse ones. Some of the dense groups that stand out more are:
The NP, VP group on the left, which typically consists of short, snappy stock update headlines such as "Viacom is crashing";
The VP, NP group on the top right, which is mostly announcement headlines in the "Here comes the..." format; and
The NP, VP, ADJP, PP, VP group at bottom left, where we have headlines such as "Industrial production falls more than expected" or "ADP private payrolls rise more than expected".
If you look closely you will find other interesting groups, as well as their similarities/disimilarities when compared to their neighbors.
Comparing the two authors
Finally, let's load the headlines for the second author and see how they compare to the ones from the first one. The steps are quite similar to the above, except this time we're going to calculate the similarity of both sets of headlines and store it in a 1400x1400 matrix:
End of explanation
chunks_joint = [author["title_chunks"] for author in (author1+author2)]
m_joint = np.zeros((1400,1400))
for i, chunkx in enumerate(chunks_joint):
for j, chunky in enumerate(chunks_joint):
sm=difflib.SequenceMatcher(None,chunkx,chunky)
m_joint[i][j] = sm.ratio()
Explanation: The basic stats don't show a significant difference between the headlines written by the two authors.
End of explanation
set1= [author["title_chunks"] for author in author1]
set2= [author["title_chunks"] for author in author2]
list_new = [itm for itm in set1 if itm in set2]
len(list_new)
Explanation: Now that we have analyzed the headlines for the second author, let's see how many common patterns exist between the two authors:
End of explanation
tsne_joint = tsne_model.fit_transform(m_joint)
plot_joint = bp.figure(plot_width=900, plot_height=700, title="Author1 vs. Author2",
tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave",
x_axis_type=None, y_axis_type=None, min_border=1)
plot_joint.scatter(x=tsne_joint[:,0], y=tsne_joint[:,1],
color=colormap[([0] * 700 + [3] * 700)],
source=bp.ColumnDataSource({
"chunks": [x["title_chunks"] for x in author1] + [x["title_chunks"] for x in author2],
"title": [x["title"] for x in author1] + [x["title"] for x in author2]
}))
hover = plot_joint.select(dict(type=HoverTool))
hover.tooltips={"chunks": "@chunks (title: \"@title\")"}
show(plot_joint)
Explanation: We observe that about 50% (347/700) of the headlines have a similar structure.
Visualization of headlines by the two authors
Our approach here is quite similar to what we did for the first author. The only difference is that here we're going to use colors to indicate the author and not the cluster this time (blue for author1 and orange for author2).
End of explanation |
8,533 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hardware simulators - gem5 target support
The gem5 simulator is a modular platform for computer-system architecture research, encompassing system-level architecture as well as processor microarchitecture.
Before creating the gem5 target, the inputs needed by gem5 should have been created (eg gem5 binary, kernel suitable for gem5, disk image, device tree blob, etc). For more information, see GEM5 - Main Page.
Environment setup
Step1: Target configuration
The definitions below need to be changed to the paths pointing to the gem5 binaries on your development machine.
M5_PATH needs to be set in your environment
platform - the currently supported platforms are
Step2: Run workloads on gem5
This is an example of running a workload and extracting stats from the simulation using m5 commands. For more information about m5 commands, see http
Step3: Trace analysis
For more information on this please check examples/trace_analysis/TraceAnalysis_TasksLatencies.ipynb. | Python Code:
from conf import LisaLogging
LisaLogging.setup()
# One initial cell for imports
import json
import logging
import os
from env import TestEnv
# Suport for FTrace events parsing and visualization
import trappy
from trappy.ftrace import FTrace
from trace import Trace
# Support for plotting
# Generate plots inline
%matplotlib inline
import numpy
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Hardware simulators - gem5 target support
The gem5 simulator is a modular platform for computer-system architecture research, encompassing system-level architecture as well as processor microarchitecture.
Before creating the gem5 target, the inputs needed by gem5 should have been created (eg gem5 binary, kernel suitable for gem5, disk image, device tree blob, etc). For more information, see GEM5 - Main Page.
Environment setup
End of explanation
# Root path of the gem5 workspace
base = "/home/vagrant/gem5/"
conf = {
# Only 'linux' is supported by gem5 for now
# 'android' is a WIP
"platform" : 'linux',
# Preload settings for a specific target
"board" : 'gem5',
# Host that will run the gem5 instance
"host" : "workstation-lin",
"gem5" : {
# System to simulate
"system" : {
# Platform description
"platform" : {
# Gem5 platform description
# LISA will also look for an optional gem5<platform> board file
# located in the same directory as the description file.
"description" : os.path.join(base, "juno.py"),
"args" : [
"--atomic",
# Resume simulation from a previous checkpoint
# Checkpoint must be taken before Virtio folders are mounted
# "--checkpoint-indir " + os.path.join(base, "Juno/atomic/",
# "checkpoints"),
# "--checkpoint-resume 1",
]
},
# Kernel compiled for gem5 with Virtio flags
"kernel" : os.path.join(base, "platform_juno/", "vmlinux"),
# DTB of the system to simulate
"dtb" : os.path.join(base, "platform_juno/", "armv8_juno_r2.dtb"),
# Disk of the distrib to run
"disk" : os.path.join(base, "binaries/", "aarch64-ubuntu-trusty-headless.img")
},
# gem5 settings
"simulator" : {
# Path to gem5 binary
"bin" : os.path.join(base, "gem5/build/ARM/gem5.fast"),
# Args to be given to the binary
"args" : [
# Zilch
],
}
},
# FTrace events to collect for all the tests configuration which have
# the "ftrace" flag enabled
"ftrace" : {
"events" : [
"sched_switch",
"sched_wakeup",
"sched_overutilized",
"sched_load_avg_cpu",
"sched_load_avg_task",
"sched_load_waking_task",
"cpu_capacity",
"cpu_frequency",
"cpu_idle",
"sched_energy_diff"
],
"buffsize" : 100 * 1024,
},
"modules" : ["cpufreq", "bl", "gem5stats"],
# Tools required by the experiments
"tools" : ['trace-cmd', 'sysbench'],
# Output directory on host
"results_dir" : "gem5_res"
}
# Create the hardware target. Patience is required :
# ~40 minutes to resume from a checkpoint (detailed)
# ~5 minutes to resume from a checkpoint (atomic)
# ~3 hours to start from scratch (detailed)
# ~15 minutes to start from scratch (atomic)
te = TestEnv(conf)
target = te.target
Explanation: Target configuration
The definitions below need to be changed to the paths pointing to the gem5 binaries on your development machine.
M5_PATH needs to be set in your environment
platform - the currently supported platforms are:
- linux - accessed via SSH connection
board - the currently supported boards are:
- gem5 - target is a gem5 simulator
host - target IP or MAC address of the platform hosting the simulator
gem5 - the settings for the simulation are:
system
platform
description - python description of the platform to simulate
args - arguments to be given to the python script (./gem5.fast model.py --help)
kernel - kernel image to run on the simulated platform
dtb - dtb of the platform to simulate
disk - disk image to run on the platform
simulator
bin - path to the gem5 simulator binary
args - arguments to be given to the gem5 binary (./gem5.fast --help)
modules - devlib modules to be enabled
exclude_modules - devlib modules to be disabled
tools - binary tools (available under ./tools/$ARCH/) to install by default
ping_time - wait time before trying to access the target after reboot
reboot_time - maximum time to wait after rebooting the target
features - list of test environment features to enable
- no-kernel - do not deploy kernel/dtb images
- no-reboot - do not force reboot the target at each configuration change
- debug - enable debugging messages
ftrace - ftrace configuration
events
functions
buffsize
results_dir - location of results of the experiments
End of explanation
# This function is an example use of gem5's ROI functionality
def record_time(command):
roi = 'time'
target.gem5stats.book_roi(roi)
target.gem5stats.roi_start(roi)
target.execute(command)
target.gem5stats.roi_end(roi)
res = target.gem5stats.match(['host_seconds', 'sim_seconds'], [roi])
target.gem5stats.free_roi(roi)
return res
# Initialise command: [binary/script, arguments]
workload = 'sysbench'
args = '--test=cpu --max-time=1 run'
# Install binary if needed
path = target.install_if_needed("/home/vagrant/lisa/tools/arm64/" + workload)
command = path + " " + args
# FTrace the execution of this workload
te.ftrace.start()
res = record_time(command)
te.ftrace.stop()
print "{} -> {}s wall-clock execution time, {}s simulation-clock execution time".format(command,
sum(map(float, res['host_seconds']['time'])),
sum(map(float, res['sim_seconds']['time'])))
Explanation: Run workloads on gem5
This is an example of running a workload and extracting stats from the simulation using m5 commands. For more information about m5 commands, see http://gem5.org/M5ops
End of explanation
# Load traces in memory (can take several minutes)
platform_file = os.path.join(te.res_dir, 'platform.json')
te.platform_dump(te.res_dir, platform_file)
with open(platform_file, 'r') as fh:
platform = json.load(fh)
trace_file = os.path.join(te.res_dir, 'trace.dat')
te.ftrace.get_trace(trace_file)
trace = Trace(trace_file, conf['ftrace']['events'], platform, normalize_time=False)
# Plot some stuff
trace.analysis.cpus.plotCPU()
# Simulations done
target.disconnect()
Explanation: Trace analysis
For more information on this please check examples/trace_analysis/TraceAnalysis_TasksLatencies.ipynb.
End of explanation |
8,534 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
$$ \LaTeX \text{ command declarations here.}
\newcommand{\R}{\mathbb{R}}
\renewcommand{\vec}[1]{\mathbf{#1}}
\newcommand{\X}{\mathcal{X}}
\newcommand{\D}{\mathcal{D}}
\newcommand{\G}{\mathcal{G}}
\newcommand{\L}{\mathcal{L}}
\newcommand{\X}{\mathcal{X}}
\newcommand{\Parents}{\mathrm{Parents}}
\newcommand{\NonDesc}{\mathrm{NonDesc}}
\newcommand{\I}{\mathcal{I}}
\newcommand{\dsep}{\text{d-sep}}
\newcommand{\Cat}{\mathrm{Categorical}}
\newcommand{\Bin}{\mathrm{Binomial}}
$$
HMMs and the Baum-Welch Algorithm
As covered in lecture, the Baum-Welch Algorithm is a derivation of the EM algorithm for HMMs where we learn the paramaters A, B and $\pi$ given a set of observations.
In this hands-on exercise we will build upon the forward and backward algorithms from last exercise, which can be used for the E-step, and implement Baum-Welch ourselves!
Like last time, we'll work with an example where we observe a sequence of words backed by a latent part of speech variable.
$X$
Step1: Review
Step3: Implementing Baum-welch
With the forward and backward algorithm implementions ready, let's use them to implement baum-welch, EM for HMMs.
In the M step, here's the parameters are updated
Step4: Training with examples
Let's try producing updated parameters to our HMM using a few examples. How did the A and B matrixes get updated with data? Was any confidence gained in the emission probabilities of nouns? Verbs?
Step5: Tracing through the implementation
Let's look at a trace of one iteration. Study the steps carefully and make sure you understand how we are updating the parameters, corresponding to these updates | Python Code:
import numpy as np
np.set_printoptions(suppress=True)
parts_of_speech = DETERMINER, NOUN, VERB, END = 0, 1, 2, 3
words = THE, DOG, CAT, WALKED, RAN, IN, PARK, END = 0, 1, 2, 3, 4, 5, 6, 7
# transition probabilities
A = np.array([
# D N V E
[0.1, 0.8, 0.1, 0.0], # D: determiner most likely to go to noun
[0.1, 0.1, 0.6, 0.2], # N: noun most likely to go to verb
[0.4, 0.3, 0.2, 0.1], # V
[0.0, 0.0, 0.0, 1.0]]) # E: end always goes to end
# distribution of parts of speech for the first word of a sentence
pi = np.array([0.4, 0.3, 0.3, 0.0])
# emission probabilities
B = np.array([
# D N V E
[ 0.8, 0.1, 0.1, 0. ], # the
[ 0.1, 0.8, 0.1, 0. ], # dog
[ 0.1, 0.8, 0.1, 0. ], # cat
[ 0. , 0. , 1. , 0. ], # walked
[ 0. , 0.2 , 0.8 , 0. ], # ran
[ 1. , 0. , 0. , 0. ], # in
[ 0. , 0.1, 0.9, 0. ], # park
[ 0. , 0. , 0. , 1. ]]) # end
B = B / np.sum(B, axis=0)
# utilties for printing out parameters of HMM
import pandas as pd
pos_labels = ["D", "N", "V", "E"]
word_labels = ["the", "dog", "cat", "walked", "ran", "in", "park", "end"]
def print_B(B):
print(pd.DataFrame(B, columns=pos_labels, index=word_labels))
def print_A(A):
print(pd.DataFrame(A, columns=pos_labels, index=pos_labels))
print_A(A)
print_B(B)
Explanation: $$ \LaTeX \text{ command declarations here.}
\newcommand{\R}{\mathbb{R}}
\renewcommand{\vec}[1]{\mathbf{#1}}
\newcommand{\X}{\mathcal{X}}
\newcommand{\D}{\mathcal{D}}
\newcommand{\G}{\mathcal{G}}
\newcommand{\L}{\mathcal{L}}
\newcommand{\X}{\mathcal{X}}
\newcommand{\Parents}{\mathrm{Parents}}
\newcommand{\NonDesc}{\mathrm{NonDesc}}
\newcommand{\I}{\mathcal{I}}
\newcommand{\dsep}{\text{d-sep}}
\newcommand{\Cat}{\mathrm{Categorical}}
\newcommand{\Bin}{\mathrm{Binomial}}
$$
HMMs and the Baum-Welch Algorithm
As covered in lecture, the Baum-Welch Algorithm is a derivation of the EM algorithm for HMMs where we learn the paramaters A, B and $\pi$ given a set of observations.
In this hands-on exercise we will build upon the forward and backward algorithms from last exercise, which can be used for the E-step, and implement Baum-Welch ourselves!
Like last time, we'll work with an example where we observe a sequence of words backed by a latent part of speech variable.
$X$: discrete distribution over bag of words
$Z$: discrete distribution over parts of speech
$A$: the probability of a part of speech given a previous part of speech, e.g, what do we expect to see after a noun?
$B$: the distribution of words given a particular part of speech, e.g, what words are we likely to see if we know it is a verb?
$x_{i}s$ a sequence of observed words (a sentence). Note: in for both variables we have a special "end" outcome that signals the end of a sentence. This makes sense as a part of speech tagger would like to have a sense of sentence boundaries.
End of explanation
def forward(params, observations):
pi, A, B = params
N = len(observations)
S = pi.shape[0]
alpha = np.zeros((N, S))
# base case
alpha[0, :] = pi * B[observations[0], :]
# recursive case
for i in range(1, N):
for s2 in range(S):
for s1 in range(S):
alpha[i, s2] += alpha[i-1, s1] * A[s1, s2] * B[observations[i], s2]
return (alpha, np.sum(alpha[N-1,:]))
def print_forward(params, observations):
alpha, za = forward(params, observations)
print(pd.DataFrame(
alpha,
columns=pos_labels,
index=[word_labels[i] for i in observations]))
print_forward((pi, A, B), [THE, DOG, WALKED, IN, THE, PARK, END])
print_forward((pi, A, B), [THE, CAT, RAN, IN, THE, PARK, END])
def backward(params, observations):
pi, A, B = params
N = len(observations)
S = pi.shape[0]
beta = np.zeros((N, S))
# base case
beta[N-1, :] = 1
# recursive case
for i in range(N-2, -1, -1):
for s1 in range(S):
for s2 in range(S):
beta[i, s1] += beta[i+1, s2] * A[s1, s2] * B[observations[i+1], s2]
return (beta, np.sum(pi * B[observations[0], :] * beta[0,:]))
backward((pi, A, B), [THE, DOG, WALKED, IN, THE, PARK, END])
Explanation: Review: Forward / Backward
Here are solutions to last hands-on lecture's coding problems along with example uses with a pre-defined A and B matrices.
$\alpha_t(z_t) = B_{z_t,x_t} \sum_{z_{t-1}} \alpha_{t-1}(z_{t-1}) A_{z_{t-1}, z_t} $
$\beta(z_t) = \sum_{z_{t+1}} A_{z_t, z_{t+1}} B_{z_{t+1}, x_{t+1}} \beta_{t+1}(z_{t+1})$
End of explanation
# Some utitlities for tracing our implementation below
def left_pad(i, s):
return "\n".join(["{}{}".format(' '*i, l) for l in s.split("\n")])
def pad_print(i, s):
print(left_pad(i, s))
def pad_print_args(i, **kwargs):
pad_print(i, "\n".join(["{}:\n{}".format(k, kwargs[k]) for k in sorted(kwargs.keys())]))
def baum_welch(training, pi, A, B, iterations, trace=False):
pi, A, B = np.copy(pi), np.copy(A), np.copy(B) # take copies, as we modify them
S = pi.shape[0]
# iterations of EM
for it in range(iterations):
if trace:
pad_print(0, "for it={} in range(iterations)".format(it))
pad_print_args(2, A=A, B=B, pi=pi, S=S)
pi1 = np.zeros_like(pi)
A1 = np.zeros_like(A)
B1 = np.zeros_like(B)
for observations in training:
if trace:
pad_print(2, "for observations={} in training".format(observations))
#
# E-Step: compute forward-backward matrices
#
alpha, za = forward((pi, A, B), observations)
beta, zb = backward((pi, A, B), observations)
if trace:
pad_print(4, alpha, za = forward((pi, A, B), observations)\nbeta, zb = backward((pi, A, B), observations))
pad_print_args(4, alpha=alpha, beta=beta, za=za, zb=zb)
assert abs(za - zb) < 1e-6, "it's badness 10000 if the marginals don't agree ({} vs {})".format(za, zb)
#
# M-step: calculating the frequency of starting state, transitions and (state, obs) pairs
#
# Update PI:
pi1 += alpha[0, :] * beta[0, :] / za
if trace:
pad_print(4, "pi1 += alpha[0, :] * beta[0, :] / za")
pad_print_args(4, pi1=pi1)
pad_print(4, "for i in range(0, len(observations)):")
# Update B (transition) matrix
for i in range(0, len(observations)):
# Hint: B1 can be updated similarly to PI for each row 1
if trace:
pad_print_args(4, B1=B1)
pad_print(4, "for i in range(1, len(observations)):")
# Update A (emission) matrix
for i in range(1, len(observations)):
if trace:
pad_print(6, "for s1 in range(S={})".format(S))
for s1 in range(S):
if trace: pad_print(8, "for s2 in range(S={})".format(S))
for s2 in range(S):
if trace: pad_print_args(4, A1=A1)
# normalise pi1, A1, B1
return pi, A, B
Explanation: Implementing Baum-welch
With the forward and backward algorithm implementions ready, let's use them to implement baum-welch, EM for HMMs.
In the M step, here's the parameters are updated:
$ p(z_{t-1}, z_t | \X, \theta) = \frac{\alpha_{t-1}(z_{t-1}) \beta_t(z_t) A_{z_{t-1}, z_t} B_{z_t, x_t}}{\sum_k \alpha_t(k)\beta_t(k)} $
First, let's look at an implementation of this below and see how it works when applied to some training data.
End of explanation
pi2, A2, B2 = baum_welch([
[THE, DOG, WALKED, IN, THE, PARK, END, END], # END -> END needs at least one transition example
[THE, DOG, RAN, IN, THE, PARK, END],
[THE, CAT, WALKED, IN, THE, PARK, END],
[THE, DOG, RAN, IN, THE, PARK, END]], pi, A, B, 10, trace=False)
print("original A")
print_A(A)
print("updated A")
print_A(A2)
print("\noriginal B")
print_B(B)
print("updated B")
print_B(B2)
print("\nForward probabilities of sample using updated params:")
print_forward((pi2, A2, B2), [THE, DOG, WALKED, IN, THE, PARK, END])
Explanation: Training with examples
Let's try producing updated parameters to our HMM using a few examples. How did the A and B matrixes get updated with data? Was any confidence gained in the emission probabilities of nouns? Verbs?
End of explanation
pi3, A3, B3 = baum_welch([
[THE, DOG, WALKED, IN, THE, PARK, END, END],
[THE, CAT, RAN, IN, THE, PARK, END, END]], pi, A, B, 1, trace=True)
print("\n\n")
print_A(A3)
print_B(B3)
Explanation: Tracing through the implementation
Let's look at a trace of one iteration. Study the steps carefully and make sure you understand how we are updating the parameters, corresponding to these updates:
$ p(z_{t-1}, z_t | \X, \theta) = \frac{\alpha_{t-1}(z_{t-1}) \beta_t(z_t) A_{z_{t-1}, z_t} B_{z_t, x_t}}{\sum_k \alpha_t(k)\beta_t(k)} $
End of explanation |
8,535 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify document publication status
Step4: Document Table of Contents
1. Key Properties
2. Key Properties --> Conservation Properties
3. Key Properties --> Timestepping Framework
4. Key Properties --> Software Properties
5. Grid
6. Grid --> Horizontal
7. Grid --> Vertical
8. Soil
9. Soil --> Soil Map
10. Soil --> Snow Free Albedo
11. Soil --> Hydrology
12. Soil --> Hydrology --> Freezing
13. Soil --> Hydrology --> Drainage
14. Soil --> Heat Treatment
15. Snow
16. Snow --> Snow Albedo
17. Vegetation
18. Energy Balance
19. Carbon Cycle
20. Carbon Cycle --> Vegetation
21. Carbon Cycle --> Vegetation --> Photosynthesis
22. Carbon Cycle --> Vegetation --> Autotrophic Respiration
23. Carbon Cycle --> Vegetation --> Allocation
24. Carbon Cycle --> Vegetation --> Phenology
25. Carbon Cycle --> Vegetation --> Mortality
26. Carbon Cycle --> Litter
27. Carbon Cycle --> Soil
28. Carbon Cycle --> Permafrost Carbon
29. Nitrogen Cycle
30. River Routing
31. River Routing --> Oceanic Discharge
32. Lakes
33. Lakes --> Method
34. Lakes --> Wetlands
1. Key Properties
Land surface key properties
1.1. Model Overview
Is Required
Step5: 1.2. Model Name
Is Required
Step6: 1.3. Description
Is Required
Step7: 1.4. Land Atmosphere Flux Exchanges
Is Required
Step8: 1.5. Atmospheric Coupling Treatment
Is Required
Step9: 1.6. Land Cover
Is Required
Step10: 1.7. Land Cover Change
Is Required
Step11: 1.8. Tiling
Is Required
Step12: 2. Key Properties --> Conservation Properties
TODO
2.1. Energy
Is Required
Step13: 2.2. Water
Is Required
Step14: 2.3. Carbon
Is Required
Step15: 3. Key Properties --> Timestepping Framework
TODO
3.1. Timestep Dependent On Atmosphere
Is Required
Step16: 3.2. Time Step
Is Required
Step17: 3.3. Timestepping Method
Is Required
Step18: 4. Key Properties --> Software Properties
Software properties of land surface code
4.1. Repository
Is Required
Step19: 4.2. Code Version
Is Required
Step20: 4.3. Code Languages
Is Required
Step21: 5. Grid
Land surface grid
5.1. Overview
Is Required
Step22: 6. Grid --> Horizontal
The horizontal grid in the land surface
6.1. Description
Is Required
Step23: 6.2. Matches Atmosphere Grid
Is Required
Step24: 7. Grid --> Vertical
The vertical grid in the soil
7.1. Description
Is Required
Step25: 7.2. Total Depth
Is Required
Step26: 8. Soil
Land surface soil
8.1. Overview
Is Required
Step27: 8.2. Heat Water Coupling
Is Required
Step28: 8.3. Number Of Soil layers
Is Required
Step29: 8.4. Prognostic Variables
Is Required
Step30: 9. Soil --> Soil Map
Key properties of the land surface soil map
9.1. Description
Is Required
Step31: 9.2. Structure
Is Required
Step32: 9.3. Texture
Is Required
Step33: 9.4. Organic Matter
Is Required
Step34: 9.5. Albedo
Is Required
Step35: 9.6. Water Table
Is Required
Step36: 9.7. Continuously Varying Soil Depth
Is Required
Step37: 9.8. Soil Depth
Is Required
Step38: 10. Soil --> Snow Free Albedo
TODO
10.1. Prognostic
Is Required
Step39: 10.2. Functions
Is Required
Step40: 10.3. Direct Diffuse
Is Required
Step41: 10.4. Number Of Wavelength Bands
Is Required
Step42: 11. Soil --> Hydrology
Key properties of the land surface soil hydrology
11.1. Description
Is Required
Step43: 11.2. Time Step
Is Required
Step44: 11.3. Tiling
Is Required
Step45: 11.4. Vertical Discretisation
Is Required
Step46: 11.5. Number Of Ground Water Layers
Is Required
Step47: 11.6. Lateral Connectivity
Is Required
Step48: 11.7. Method
Is Required
Step49: 12. Soil --> Hydrology --> Freezing
TODO
12.1. Number Of Ground Ice Layers
Is Required
Step50: 12.2. Ice Storage Method
Is Required
Step51: 12.3. Permafrost
Is Required
Step52: 13. Soil --> Hydrology --> Drainage
TODO
13.1. Description
Is Required
Step53: 13.2. Types
Is Required
Step54: 14. Soil --> Heat Treatment
TODO
14.1. Description
Is Required
Step55: 14.2. Time Step
Is Required
Step56: 14.3. Tiling
Is Required
Step57: 14.4. Vertical Discretisation
Is Required
Step58: 14.5. Heat Storage
Is Required
Step59: 14.6. Processes
Is Required
Step60: 15. Snow
Land surface snow
15.1. Overview
Is Required
Step61: 15.2. Tiling
Is Required
Step62: 15.3. Number Of Snow Layers
Is Required
Step63: 15.4. Density
Is Required
Step64: 15.5. Water Equivalent
Is Required
Step65: 15.6. Heat Content
Is Required
Step66: 15.7. Temperature
Is Required
Step67: 15.8. Liquid Water Content
Is Required
Step68: 15.9. Snow Cover Fractions
Is Required
Step69: 15.10. Processes
Is Required
Step70: 15.11. Prognostic Variables
Is Required
Step71: 16. Snow --> Snow Albedo
TODO
16.1. Type
Is Required
Step72: 16.2. Functions
Is Required
Step73: 17. Vegetation
Land surface vegetation
17.1. Overview
Is Required
Step74: 17.2. Time Step
Is Required
Step75: 17.3. Dynamic Vegetation
Is Required
Step76: 17.4. Tiling
Is Required
Step77: 17.5. Vegetation Representation
Is Required
Step78: 17.6. Vegetation Types
Is Required
Step79: 17.7. Biome Types
Is Required
Step80: 17.8. Vegetation Time Variation
Is Required
Step81: 17.9. Vegetation Map
Is Required
Step82: 17.10. Interception
Is Required
Step83: 17.11. Phenology
Is Required
Step84: 17.12. Phenology Description
Is Required
Step85: 17.13. Leaf Area Index
Is Required
Step86: 17.14. Leaf Area Index Description
Is Required
Step87: 17.15. Biomass
Is Required
Step88: 17.16. Biomass Description
Is Required
Step89: 17.17. Biogeography
Is Required
Step90: 17.18. Biogeography Description
Is Required
Step91: 17.19. Stomatal Resistance
Is Required
Step92: 17.20. Stomatal Resistance Description
Is Required
Step93: 17.21. Prognostic Variables
Is Required
Step94: 18. Energy Balance
Land surface energy balance
18.1. Overview
Is Required
Step95: 18.2. Tiling
Is Required
Step96: 18.3. Number Of Surface Temperatures
Is Required
Step97: 18.4. Evaporation
Is Required
Step98: 18.5. Processes
Is Required
Step99: 19. Carbon Cycle
Land surface carbon cycle
19.1. Overview
Is Required
Step100: 19.2. Tiling
Is Required
Step101: 19.3. Time Step
Is Required
Step102: 19.4. Anthropogenic Carbon
Is Required
Step103: 19.5. Prognostic Variables
Is Required
Step104: 20. Carbon Cycle --> Vegetation
TODO
20.1. Number Of Carbon Pools
Is Required
Step105: 20.2. Carbon Pools
Is Required
Step106: 20.3. Forest Stand Dynamics
Is Required
Step107: 21. Carbon Cycle --> Vegetation --> Photosynthesis
TODO
21.1. Method
Is Required
Step108: 22. Carbon Cycle --> Vegetation --> Autotrophic Respiration
TODO
22.1. Maintainance Respiration
Is Required
Step109: 22.2. Growth Respiration
Is Required
Step110: 23. Carbon Cycle --> Vegetation --> Allocation
TODO
23.1. Method
Is Required
Step111: 23.2. Allocation Bins
Is Required
Step112: 23.3. Allocation Fractions
Is Required
Step113: 24. Carbon Cycle --> Vegetation --> Phenology
TODO
24.1. Method
Is Required
Step114: 25. Carbon Cycle --> Vegetation --> Mortality
TODO
25.1. Method
Is Required
Step115: 26. Carbon Cycle --> Litter
TODO
26.1. Number Of Carbon Pools
Is Required
Step116: 26.2. Carbon Pools
Is Required
Step117: 26.3. Decomposition
Is Required
Step118: 26.4. Method
Is Required
Step119: 27. Carbon Cycle --> Soil
TODO
27.1. Number Of Carbon Pools
Is Required
Step120: 27.2. Carbon Pools
Is Required
Step121: 27.3. Decomposition
Is Required
Step122: 27.4. Method
Is Required
Step123: 28. Carbon Cycle --> Permafrost Carbon
TODO
28.1. Is Permafrost Included
Is Required
Step124: 28.2. Emitted Greenhouse Gases
Is Required
Step125: 28.3. Decomposition
Is Required
Step126: 28.4. Impact On Soil Properties
Is Required
Step127: 29. Nitrogen Cycle
Land surface nitrogen cycle
29.1. Overview
Is Required
Step128: 29.2. Tiling
Is Required
Step129: 29.3. Time Step
Is Required
Step130: 29.4. Prognostic Variables
Is Required
Step131: 30. River Routing
Land surface river routing
30.1. Overview
Is Required
Step132: 30.2. Tiling
Is Required
Step133: 30.3. Time Step
Is Required
Step134: 30.4. Grid Inherited From Land Surface
Is Required
Step135: 30.5. Grid Description
Is Required
Step136: 30.6. Number Of Reservoirs
Is Required
Step137: 30.7. Water Re Evaporation
Is Required
Step138: 30.8. Coupled To Atmosphere
Is Required
Step139: 30.9. Coupled To Land
Is Required
Step140: 30.10. Quantities Exchanged With Atmosphere
Is Required
Step141: 30.11. Basin Flow Direction Map
Is Required
Step142: 30.12. Flooding
Is Required
Step143: 30.13. Prognostic Variables
Is Required
Step144: 31. River Routing --> Oceanic Discharge
TODO
31.1. Discharge Type
Is Required
Step145: 31.2. Quantities Transported
Is Required
Step146: 32. Lakes
Land surface lakes
32.1. Overview
Is Required
Step147: 32.2. Coupling With Rivers
Is Required
Step148: 32.3. Time Step
Is Required
Step149: 32.4. Quantities Exchanged With Rivers
Is Required
Step150: 32.5. Vertical Grid
Is Required
Step151: 32.6. Prognostic Variables
Is Required
Step152: 33. Lakes --> Method
TODO
33.1. Ice Treatment
Is Required
Step153: 33.2. Albedo
Is Required
Step154: 33.3. Dynamics
Is Required
Step155: 33.4. Dynamic Lake Extent
Is Required
Step156: 33.5. Endorheic Basins
Is Required
Step157: 34. Lakes --> Wetlands
TODO
34.1. Description
Is Required | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-gris', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: EC-EARTH3-GRIS
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energy Balance, Carbon Cycle, Nitrogen Cycle, River Routing, Lakes.
Properties: 154 (96 required)
Model descriptions: Model description details
Initialized From: --
Notebook Help: Goto notebook help page
Notebook Initialised: 2018-02-15 16:53:59
Document Setup
IMPORTANT: to be executed each time you run the notebook
End of explanation
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
Explanation: Document Authors
Set document authors
End of explanation
# Set as follows: DOC.set_contributor("name", "email")
# TODO - please enter value(s)
Explanation: Document Contributors
Specify document contributors
End of explanation
# Set publication status:
# 0=do not publish, 1=publish.
DOC.set_publication_status(0)
Explanation: Document Publication
Specify document publication status
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.model_overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: Document Table of Contents
1. Key Properties
2. Key Properties --> Conservation Properties
3. Key Properties --> Timestepping Framework
4. Key Properties --> Software Properties
5. Grid
6. Grid --> Horizontal
7. Grid --> Vertical
8. Soil
9. Soil --> Soil Map
10. Soil --> Snow Free Albedo
11. Soil --> Hydrology
12. Soil --> Hydrology --> Freezing
13. Soil --> Hydrology --> Drainage
14. Soil --> Heat Treatment
15. Snow
16. Snow --> Snow Albedo
17. Vegetation
18. Energy Balance
19. Carbon Cycle
20. Carbon Cycle --> Vegetation
21. Carbon Cycle --> Vegetation --> Photosynthesis
22. Carbon Cycle --> Vegetation --> Autotrophic Respiration
23. Carbon Cycle --> Vegetation --> Allocation
24. Carbon Cycle --> Vegetation --> Phenology
25. Carbon Cycle --> Vegetation --> Mortality
26. Carbon Cycle --> Litter
27. Carbon Cycle --> Soil
28. Carbon Cycle --> Permafrost Carbon
29. Nitrogen Cycle
30. River Routing
31. River Routing --> Oceanic Discharge
32. Lakes
33. Lakes --> Method
34. Lakes --> Wetlands
1. Key Properties
Land surface key properties
1.1. Model Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of land surface model.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.model_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 1.2. Model Name
Is Required: TRUE Type: STRING Cardinality: 1.1
Name of land surface model code (e.g. MOSES2.2)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 1.3. Description
Is Required: TRUE Type: STRING Cardinality: 1.1
General description of the processes modelled (e.g. dymanic vegation, prognostic albedo, etc.)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.land_atmosphere_flux_exchanges')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "water"
# "energy"
# "carbon"
# "nitrogen"
# "phospherous"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 1.4. Land Atmosphere Flux Exchanges
Is Required: FALSE Type: ENUM Cardinality: 0.N
Fluxes exchanged with the atmopshere.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.atmospheric_coupling_treatment')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 1.5. Atmospheric Coupling Treatment
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the treatment of land surface coupling with the Atmosphere model component, which may be different for different quantities (e.g. dust: semi-implicit, water vapour: explicit)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.land_cover')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "bare soil"
# "urban"
# "lake"
# "land ice"
# "lake ice"
# "vegetated"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 1.6. Land Cover
Is Required: TRUE Type: ENUM Cardinality: 1.N
Types of land cover defined in the land surface model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.land_cover_change')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 1.7. Land Cover Change
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe how land cover change is managed (e.g. the use of net or gross transitions)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.tiling')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 1.8. Tiling
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the general tiling procedure used in the land surface (if any). Include treatment of physiography, land/sea, (dynamic) vegetation coverage and orography/roughness
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.conservation_properties.energy')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 2. Key Properties --> Conservation Properties
TODO
2.1. Energy
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe if/how energy is conserved globally and to what level (e.g. within X [units]/year)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.conservation_properties.water')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 2.2. Water
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe if/how water is conserved globally and to what level (e.g. within X [units]/year)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.conservation_properties.carbon')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 2.3. Carbon
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe if/how carbon is conserved globally and to what level (e.g. within X [units]/year)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.timestepping_framework.timestep_dependent_on_atmosphere')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 3. Key Properties --> Timestepping Framework
TODO
3.1. Timestep Dependent On Atmosphere
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is a time step dependent on the frequency of atmosphere coupling?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.timestepping_framework.time_step')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 3.2. Time Step
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Overall timestep of land surface model (i.e. time between calls)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.timestepping_framework.timestepping_method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 3.3. Timestepping Method
Is Required: TRUE Type: STRING Cardinality: 1.1
General description of time stepping method and associated time step(s)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.software_properties.repository')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 4. Key Properties --> Software Properties
Software properties of land surface code
4.1. Repository
Is Required: FALSE Type: STRING Cardinality: 0.1
Location of code for this component.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.software_properties.code_version')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 4.2. Code Version
Is Required: FALSE Type: STRING Cardinality: 0.1
Code version identifier.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.key_properties.software_properties.code_languages')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 4.3. Code Languages
Is Required: FALSE Type: STRING Cardinality: 0.N
Code language(s).
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.grid.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 5. Grid
Land surface grid
5.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of the grid in the land surface
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.grid.horizontal.description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 6. Grid --> Horizontal
The horizontal grid in the land surface
6.1. Description
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the general structure of the horizontal grid (not including any tiling)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.grid.horizontal.matches_atmosphere_grid')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 6.2. Matches Atmosphere Grid
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Does the horizontal grid match the atmosphere?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.grid.vertical.description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 7. Grid --> Vertical
The vertical grid in the soil
7.1. Description
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the general structure of the vertical grid in the soil (not including any tiling)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.grid.vertical.total_depth')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 7.2. Total Depth
Is Required: TRUE Type: INTEGER Cardinality: 1.1
The total depth of the soil (in metres)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8. Soil
Land surface soil
8.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of soil in the land surface
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.heat_water_coupling')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8.2. Heat Water Coupling
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the coupling between heat and water in the soil
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.number_of_soil layers')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 8.3. Number Of Soil layers
Is Required: TRUE Type: INTEGER Cardinality: 1.1
The number of soil layers
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.prognostic_variables')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8.4. Prognostic Variables
Is Required: TRUE Type: STRING Cardinality: 1.1
List the prognostic variables of the soil scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.soil_map.description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9. Soil --> Soil Map
Key properties of the land surface soil map
9.1. Description
Is Required: TRUE Type: STRING Cardinality: 1.1
General description of soil map
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.soil_map.structure')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.2. Structure
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the soil structure map
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.soil_map.texture')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.3. Texture
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the soil texture map
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.soil_map.organic_matter')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.4. Organic Matter
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the soil organic matter map
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.soil_map.albedo')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.5. Albedo
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the soil albedo map
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.soil_map.water_table')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.6. Water Table
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the soil water table map, if any
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.soil_map.continuously_varying_soil_depth')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 9.7. Continuously Varying Soil Depth
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Does the soil properties vary continuously with depth?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.soil_map.soil_depth')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.8. Soil Depth
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the soil depth map
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.snow_free_albedo.prognostic')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 10. Soil --> Snow Free Albedo
TODO
10.1. Prognostic
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is snow free albedo prognostic?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.snow_free_albedo.functions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "vegetation type"
# "soil humidity"
# "vegetation state"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 10.2. Functions
Is Required: FALSE Type: ENUM Cardinality: 0.N
If prognostic, describe the dependancies on snow free albedo calculations
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.snow_free_albedo.direct_diffuse')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "distinction between direct and diffuse albedo"
# "no distinction between direct and diffuse albedo"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 10.3. Direct Diffuse
Is Required: FALSE Type: ENUM Cardinality: 0.1
If prognostic, describe the distinction between direct and diffuse albedo
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.snow_free_albedo.number_of_wavelength_bands')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 10.4. Number Of Wavelength Bands
Is Required: FALSE Type: INTEGER Cardinality: 0.1
If prognostic, enter the number of wavelength bands used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 11. Soil --> Hydrology
Key properties of the land surface soil hydrology
11.1. Description
Is Required: TRUE Type: STRING Cardinality: 1.1
General description of the soil hydrological model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.time_step')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 11.2. Time Step
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Time step of river soil hydrology in seconds
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.tiling')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 11.3. Tiling
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the soil hydrology tiling, if any.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.vertical_discretisation')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 11.4. Vertical Discretisation
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the typical vertical discretisation
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.number_of_ground_water_layers')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 11.5. Number Of Ground Water Layers
Is Required: TRUE Type: INTEGER Cardinality: 1.1
The number of soil layers that may contain water
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.lateral_connectivity')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "perfect connectivity"
# "Darcian flow"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 11.6. Lateral Connectivity
Is Required: TRUE Type: ENUM Cardinality: 1.N
Describe the lateral connectivity between tiles
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Bucket"
# "Force-restore"
# "Choisnel"
# "Explicit diffusion"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 11.7. Method
Is Required: TRUE Type: ENUM Cardinality: 1.1
The hydrological dynamics scheme in the land surface model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.freezing.number_of_ground_ice_layers')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 12. Soil --> Hydrology --> Freezing
TODO
12.1. Number Of Ground Ice Layers
Is Required: TRUE Type: INTEGER Cardinality: 1.1
How many soil layers may contain ground ice
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.freezing.ice_storage_method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 12.2. Ice Storage Method
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the method of ice storage
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.freezing.permafrost')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 12.3. Permafrost
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the treatment of permafrost, if any, within the land surface scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.drainage.description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 13. Soil --> Hydrology --> Drainage
TODO
13.1. Description
Is Required: TRUE Type: STRING Cardinality: 1.1
General describe how drainage is included in the land surface scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.hydrology.drainage.types')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Gravity drainage"
# "Horton mechanism"
# "topmodel-based"
# "Dunne mechanism"
# "Lateral subsurface flow"
# "Baseflow from groundwater"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 13.2. Types
Is Required: FALSE Type: ENUM Cardinality: 0.N
Different types of runoff represented by the land surface model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.heat_treatment.description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 14. Soil --> Heat Treatment
TODO
14.1. Description
Is Required: TRUE Type: STRING Cardinality: 1.1
General description of how heat treatment properties are defined
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.heat_treatment.time_step')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 14.2. Time Step
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Time step of soil heat scheme in seconds
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.heat_treatment.tiling')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 14.3. Tiling
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the soil heat treatment tiling, if any.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.heat_treatment.vertical_discretisation')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 14.4. Vertical Discretisation
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the typical vertical discretisation
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.heat_treatment.heat_storage')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Force-restore"
# "Explicit diffusion"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 14.5. Heat Storage
Is Required: TRUE Type: ENUM Cardinality: 1.1
Specify the method of heat storage
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.soil.heat_treatment.processes')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "soil moisture freeze-thaw"
# "coupling with snow temperature"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 14.6. Processes
Is Required: TRUE Type: ENUM Cardinality: 1.N
Describe processes included in the treatment of soil heat
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 15. Snow
Land surface snow
15.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of snow in the land surface
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.tiling')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 15.2. Tiling
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the snow tiling, if any.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.number_of_snow_layers')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 15.3. Number Of Snow Layers
Is Required: TRUE Type: INTEGER Cardinality: 1.1
The number of snow levels used in the land surface scheme/model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.density')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "constant"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 15.4. Density
Is Required: TRUE Type: ENUM Cardinality: 1.1
Description of the treatment of snow density
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.water_equivalent')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "diagnostic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 15.5. Water Equivalent
Is Required: TRUE Type: ENUM Cardinality: 1.1
Description of the treatment of the snow water equivalent
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.heat_content')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "diagnostic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 15.6. Heat Content
Is Required: TRUE Type: ENUM Cardinality: 1.1
Description of the treatment of the heat content of snow
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.temperature')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "diagnostic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 15.7. Temperature
Is Required: TRUE Type: ENUM Cardinality: 1.1
Description of the treatment of snow temperature
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.liquid_water_content')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "diagnostic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 15.8. Liquid Water Content
Is Required: TRUE Type: ENUM Cardinality: 1.1
Description of the treatment of snow liquid water
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.snow_cover_fractions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "ground snow fraction"
# "vegetation snow fraction"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 15.9. Snow Cover Fractions
Is Required: TRUE Type: ENUM Cardinality: 1.N
Specify cover fractions used in the surface snow scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.processes')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "snow interception"
# "snow melting"
# "snow freezing"
# "blowing snow"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 15.10. Processes
Is Required: TRUE Type: ENUM Cardinality: 1.N
Snow related processes in the land surface scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.prognostic_variables')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 15.11. Prognostic Variables
Is Required: TRUE Type: STRING Cardinality: 1.1
List the prognostic variables of the snow scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.snow_albedo.type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "prescribed"
# "constant"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 16. Snow --> Snow Albedo
TODO
16.1. Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Describe the treatment of snow-covered land albedo
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.snow.snow_albedo.functions')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "vegetation type"
# "snow age"
# "snow density"
# "snow grain type"
# "aerosol deposition"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 16.2. Functions
Is Required: FALSE Type: ENUM Cardinality: 0.N
*If prognostic, *
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 17. Vegetation
Land surface vegetation
17.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of vegetation in the land surface
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.time_step')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 17.2. Time Step
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Time step of vegetation scheme in seconds
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.dynamic_vegetation')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 17.3. Dynamic Vegetation
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is there dynamic evolution of vegetation?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.tiling')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 17.4. Tiling
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the vegetation tiling, if any.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.vegetation_representation')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "vegetation types"
# "biome types"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.5. Vegetation Representation
Is Required: TRUE Type: ENUM Cardinality: 1.1
Vegetation classification used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.vegetation_types')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "broadleaf tree"
# "needleleaf tree"
# "C3 grass"
# "C4 grass"
# "vegetated"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.6. Vegetation Types
Is Required: FALSE Type: ENUM Cardinality: 0.N
List of vegetation types in the classification, if any
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.biome_types')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "evergreen needleleaf forest"
# "evergreen broadleaf forest"
# "deciduous needleleaf forest"
# "deciduous broadleaf forest"
# "mixed forest"
# "woodland"
# "wooded grassland"
# "closed shrubland"
# "opne shrubland"
# "grassland"
# "cropland"
# "wetlands"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.7. Biome Types
Is Required: FALSE Type: ENUM Cardinality: 0.N
List of biome types in the classification, if any
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.vegetation_time_variation')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "fixed (not varying)"
# "prescribed (varying from files)"
# "dynamical (varying from simulation)"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.8. Vegetation Time Variation
Is Required: TRUE Type: ENUM Cardinality: 1.1
How the vegetation fractions in each tile are varying with time
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.vegetation_map')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 17.9. Vegetation Map
Is Required: FALSE Type: STRING Cardinality: 0.1
If vegetation fractions are not dynamically updated , describe the vegetation map used (common name and reference, if possible)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.interception')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 17.10. Interception
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is vegetation interception of rainwater represented?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.phenology')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "diagnostic (vegetation map)"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.11. Phenology
Is Required: TRUE Type: ENUM Cardinality: 1.1
Treatment of vegetation phenology
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.phenology_description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 17.12. Phenology Description
Is Required: FALSE Type: STRING Cardinality: 0.1
General description of the treatment of vegetation phenology
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.leaf_area_index')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prescribed"
# "prognostic"
# "diagnostic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.13. Leaf Area Index
Is Required: TRUE Type: ENUM Cardinality: 1.1
Treatment of vegetation leaf area index
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.leaf_area_index_description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 17.14. Leaf Area Index Description
Is Required: FALSE Type: STRING Cardinality: 0.1
General description of the treatment of leaf area index
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.biomass')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "diagnostic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.15. Biomass
Is Required: TRUE Type: ENUM Cardinality: 1.1
*Treatment of vegetation biomass *
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.biomass_description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 17.16. Biomass Description
Is Required: FALSE Type: STRING Cardinality: 0.1
General description of the treatment of vegetation biomass
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.biogeography')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "diagnostic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.17. Biogeography
Is Required: TRUE Type: ENUM Cardinality: 1.1
Treatment of vegetation biogeography
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.biogeography_description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 17.18. Biogeography Description
Is Required: FALSE Type: STRING Cardinality: 0.1
General description of the treatment of vegetation biogeography
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.stomatal_resistance')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "light"
# "temperature"
# "water availability"
# "CO2"
# "O3"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 17.19. Stomatal Resistance
Is Required: TRUE Type: ENUM Cardinality: 1.N
Specify what the vegetation stomatal resistance depends on
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.stomatal_resistance_description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 17.20. Stomatal Resistance Description
Is Required: FALSE Type: STRING Cardinality: 0.1
General description of the treatment of vegetation stomatal resistance
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.vegetation.prognostic_variables')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 17.21. Prognostic Variables
Is Required: TRUE Type: STRING Cardinality: 1.1
List the prognostic variables of the vegetation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.energy_balance.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 18. Energy Balance
Land surface energy balance
18.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of energy balance in land surface
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.energy_balance.tiling')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 18.2. Tiling
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the energy balance tiling, if any.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.energy_balance.number_of_surface_temperatures')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 18.3. Number Of Surface Temperatures
Is Required: TRUE Type: INTEGER Cardinality: 1.1
The maximum number of distinct surface temperatures in a grid cell (for example, each subgrid tile may have its own temperature)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.energy_balance.evaporation')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "alpha"
# "beta"
# "combined"
# "Monteith potential evaporation"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 18.4. Evaporation
Is Required: TRUE Type: ENUM Cardinality: 1.N
Specify the formulation method for land surface evaporation, from soil and vegetation
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.energy_balance.processes')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "transpiration"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 18.5. Processes
Is Required: TRUE Type: ENUM Cardinality: 1.N
Describe which processes are included in the energy balance scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 19. Carbon Cycle
Land surface carbon cycle
19.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of carbon cycle in land surface
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.tiling')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 19.2. Tiling
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the carbon cycle tiling, if any.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.time_step')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 19.3. Time Step
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Time step of carbon cycle in seconds
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.anthropogenic_carbon')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "grand slam protocol"
# "residence time"
# "decay time"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 19.4. Anthropogenic Carbon
Is Required: FALSE Type: ENUM Cardinality: 0.N
Describe the treament of the anthropogenic carbon pool
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.prognostic_variables')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 19.5. Prognostic Variables
Is Required: TRUE Type: STRING Cardinality: 1.1
List the prognostic variables of the carbon scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.number_of_carbon_pools')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 20. Carbon Cycle --> Vegetation
TODO
20.1. Number Of Carbon Pools
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Enter the number of carbon pools used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.carbon_pools')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 20.2. Carbon Pools
Is Required: FALSE Type: STRING Cardinality: 0.1
List the carbon pools used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.forest_stand_dynamics')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 20.3. Forest Stand Dynamics
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the treatment of forest stand dyanmics
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.photosynthesis.method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 21. Carbon Cycle --> Vegetation --> Photosynthesis
TODO
21.1. Method
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the general method used for photosynthesis (e.g. type of photosynthesis, distinction between C3 and C4 grasses, Nitrogen depencence, etc.)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.autotrophic_respiration.maintainance_respiration')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 22. Carbon Cycle --> Vegetation --> Autotrophic Respiration
TODO
22.1. Maintainance Respiration
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the general method used for maintainence respiration
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.autotrophic_respiration.growth_respiration')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 22.2. Growth Respiration
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the general method used for growth respiration
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 23. Carbon Cycle --> Vegetation --> Allocation
TODO
23.1. Method
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the general principle behind the allocation scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.allocation_bins')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "leaves + stems + roots"
# "leaves + stems + roots (leafy + woody)"
# "leaves + fine roots + coarse roots + stems"
# "whole plant (no distinction)"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 23.2. Allocation Bins
Is Required: TRUE Type: ENUM Cardinality: 1.1
Specify distinct carbon bins used in allocation
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.allocation_fractions')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "fixed"
# "function of vegetation type"
# "function of plant allometry"
# "explicitly calculated"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 23.3. Allocation Fractions
Is Required: TRUE Type: ENUM Cardinality: 1.1
Describe how the fractions of allocation are calculated
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.phenology.method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 24. Carbon Cycle --> Vegetation --> Phenology
TODO
24.1. Method
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the general principle behind the phenology scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.vegetation.mortality.method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 25. Carbon Cycle --> Vegetation --> Mortality
TODO
25.1. Method
Is Required: TRUE Type: STRING Cardinality: 1.1
Describe the general principle behind the mortality scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.litter.number_of_carbon_pools')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 26. Carbon Cycle --> Litter
TODO
26.1. Number Of Carbon Pools
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Enter the number of carbon pools used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.litter.carbon_pools')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 26.2. Carbon Pools
Is Required: FALSE Type: STRING Cardinality: 0.1
List the carbon pools used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.litter.decomposition')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 26.3. Decomposition
Is Required: FALSE Type: STRING Cardinality: 0.1
List the decomposition methods used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.litter.method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 26.4. Method
Is Required: FALSE Type: STRING Cardinality: 0.1
List the general method used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.soil.number_of_carbon_pools')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 27. Carbon Cycle --> Soil
TODO
27.1. Number Of Carbon Pools
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Enter the number of carbon pools used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.soil.carbon_pools')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 27.2. Carbon Pools
Is Required: FALSE Type: STRING Cardinality: 0.1
List the carbon pools used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.soil.decomposition')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 27.3. Decomposition
Is Required: FALSE Type: STRING Cardinality: 0.1
List the decomposition methods used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.soil.method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 27.4. Method
Is Required: FALSE Type: STRING Cardinality: 0.1
List the general method used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.is_permafrost_included')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 28. Carbon Cycle --> Permafrost Carbon
TODO
28.1. Is Permafrost Included
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is permafrost included?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.emitted_greenhouse_gases')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 28.2. Emitted Greenhouse Gases
Is Required: FALSE Type: STRING Cardinality: 0.1
List the GHGs emitted
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.decomposition')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 28.3. Decomposition
Is Required: FALSE Type: STRING Cardinality: 0.1
List the decomposition methods used
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.impact_on_soil_properties')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 28.4. Impact On Soil Properties
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the impact of permafrost on soil properties
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.nitrogen_cycle.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 29. Nitrogen Cycle
Land surface nitrogen cycle
29.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of the nitrogen cycle in the land surface
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.nitrogen_cycle.tiling')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 29.2. Tiling
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the notrogen cycle tiling, if any.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.nitrogen_cycle.time_step')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 29.3. Time Step
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Time step of nitrogen cycle in seconds
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.nitrogen_cycle.prognostic_variables')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 29.4. Prognostic Variables
Is Required: TRUE Type: STRING Cardinality: 1.1
List the prognostic variables of the nitrogen scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 30. River Routing
Land surface river routing
30.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of river routing in the land surface
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.tiling')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 30.2. Tiling
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the river routing, if any.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.time_step')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 30.3. Time Step
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Time step of river routing scheme in seconds
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.grid_inherited_from_land_surface')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 30.4. Grid Inherited From Land Surface
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is the grid inherited from land surface?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.grid_description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 30.5. Grid Description
Is Required: FALSE Type: STRING Cardinality: 0.1
General description of grid, if not inherited from land surface
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.number_of_reservoirs')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 30.6. Number Of Reservoirs
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Enter the number of reservoirs
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.water_re_evaporation')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "flood plains"
# "irrigation"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 30.7. Water Re Evaporation
Is Required: TRUE Type: ENUM Cardinality: 1.N
TODO
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.coupled_to_atmosphere')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 30.8. Coupled To Atmosphere
Is Required: FALSE Type: BOOLEAN Cardinality: 0.1
Is river routing coupled to the atmosphere model component?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.coupled_to_land')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 30.9. Coupled To Land
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the coupling between land and rivers
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.quantities_exchanged_with_atmosphere')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "heat"
# "water"
# "tracers"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 30.10. Quantities Exchanged With Atmosphere
Is Required: FALSE Type: ENUM Cardinality: 0.N
If couple to atmosphere, which quantities are exchanged between river routing and the atmosphere model components?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.basin_flow_direction_map')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "present day"
# "adapted for other periods"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 30.11. Basin Flow Direction Map
Is Required: TRUE Type: ENUM Cardinality: 1.1
What type of basin flow direction map is being used?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.flooding')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 30.12. Flooding
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the representation of flooding, if any
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.prognostic_variables')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 30.13. Prognostic Variables
Is Required: TRUE Type: STRING Cardinality: 1.1
List the prognostic variables of the river routing
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.oceanic_discharge.discharge_type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "direct (large rivers)"
# "diffuse"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 31. River Routing --> Oceanic Discharge
TODO
31.1. Discharge Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Specify how rivers are discharged to the ocean
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.river_routing.oceanic_discharge.quantities_transported')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "heat"
# "water"
# "tracers"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 31.2. Quantities Transported
Is Required: TRUE Type: ENUM Cardinality: 1.N
Quantities that are exchanged from river-routing to the ocean model component
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 32. Lakes
Land surface lakes
32.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of lakes in the land surface
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.coupling_with_rivers')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 32.2. Coupling With Rivers
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Are lakes coupled to the river routing model component?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.time_step')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 32.3. Time Step
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Time step of lake scheme in seconds
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.quantities_exchanged_with_rivers')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "heat"
# "water"
# "tracers"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 32.4. Quantities Exchanged With Rivers
Is Required: FALSE Type: ENUM Cardinality: 0.N
If coupling with rivers, which quantities are exchanged between the lakes and rivers
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.vertical_grid')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 32.5. Vertical Grid
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the vertical grid of lakes
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.prognostic_variables')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 32.6. Prognostic Variables
Is Required: TRUE Type: STRING Cardinality: 1.1
List the prognostic variables of the lake scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.method.ice_treatment')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 33. Lakes --> Method
TODO
33.1. Ice Treatment
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is lake ice included?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.method.albedo')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "prognostic"
# "diagnostic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 33.2. Albedo
Is Required: TRUE Type: ENUM Cardinality: 1.1
Describe the treatment of lake albedo
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.method.dynamics')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "No lake dynamics"
# "vertical"
# "horizontal"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 33.3. Dynamics
Is Required: TRUE Type: ENUM Cardinality: 1.N
Which dynamics of lakes are treated? horizontal, vertical, etc.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.method.dynamic_lake_extent')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 33.4. Dynamic Lake Extent
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is a dynamic lake extent scheme included?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.method.endorheic_basins')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 33.5. Endorheic Basins
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Basins not flowing to ocean included?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.land.lakes.wetlands.description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 34. Lakes --> Wetlands
TODO
34.1. Description
Is Required: FALSE Type: STRING Cardinality: 0.1
Describe the treatment of wetlands, if any
End of explanation |
8,536 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples and Exercises from Think Stats, 2nd Edition
http
Step1: Given a list of values, there are several ways to count the frequency of each value.
Step2: You can use a Python dictionary
Step3: You can use a Counter (which is a dictionary with additional methods)
Step4: Or you can use the Hist object provided by thinkstats2
Step5: Hist provides Freq, which looks up the frequency of a value.
Step6: You can also use the bracket operator, which does the same thing.
Step7: If the value does not appear, it has frequency 0.
Step8: The Values method returns the values
Step9: So you can iterate the values and their frequencies like this
Step10: Or you can use the Items method
Step11: thinkplot is a wrapper for matplotlib that provides functions that work with the objects in thinkstats2.
For example Hist plots the values and their frequencies as a bar graph.
Config takes parameters that label the x and y axes, among other things.
Step12: As an example, I'll replicate some of the figures from the book.
First, I'll load the data from the pregnancy file and select the records for live births.
Step13: Here's the histogram of birth weights in pounds. Notice that Hist works with anything iterable, including a Pandas Series. The label attribute appears in the legend when you plot the Hist.
Step14: Before plotting the ages, I'll apply floor to round down
Step15: As an exercise, plot the histogram of pregnancy lengths (column prglngth).
Step16: Hist provides smallest, which select the lowest values and their frequencies.
Step17: Use Largest to display the longest pregnancy lengths.
Step18: From live births, we can selection first babies and others using birthord, then compute histograms of pregnancy length for the two groups.
Step19: We can use width and align to plot two histograms side-by-side.
Step20: Series provides methods to compute summary statistics
Step21: Here are the mean and standard deviation
Step22: As an exercise, confirm that std is the square root of var
Step23: Here's are the mean pregnancy lengths for first babies and others
Step24: And here's the difference (in weeks)
Step26: This functon computes the Cohen effect size, which is the difference in means expressed in number of standard deviations
Step27: Compute the Cohen effect size for the difference in pregnancy length for first babies and others.
Step28: Exercises
Using the variable totalwgt_lb, investigate whether first babies are lighter or heavier than others.
Compute Cohen’s effect size to quantify the difference between the groups. How does it compare to the difference in pregnancy length?
Step29: For the next few exercises, we'll load the respondent file
Step30: Make a histogram of <tt>totincr</tt> the total income for the respondent's family. To interpret the codes see the codebook.
Step31: Make a histogram of <tt>age_r</tt>, the respondent's age at the time of interview.
Step32: Make a histogram of <tt>numfmhh</tt>, the number of people in the respondent's household.
Step33: Make a histogram of <tt>parity</tt>, the number of children borne by the respondent. How would you describe this distribution?
Step34: This data is left-skewed with a long tail. Women are about as likely to have 1 as 2 children, though parity drops off significantly after 2 children.
Use Hist.Largest to find the largest values of <tt>parity</tt>.
Step35: Let's investigate whether people with higher income have higher parity. Keep in mind that in this study, we are observing different people at different times during their lives, so this data is not the best choice for answering this question. But for now let's take it at face value.
Use <tt>totincr</tt> to select the respondents with the highest income (level 14). Plot the histogram of <tt>parity</tt> for just the high income respondents.
Step36: Find the largest parities for high income respondents.
Step37: Compare the mean <tt>parity</tt> for high income respondents and others.
Step38: Compute the Cohen effect size for this difference. How does it compare with the difference in pregnancy length for first babies and others? | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import nsfg
import first
Explanation: Examples and Exercises from Think Stats, 2nd Edition
http://thinkstats2.com
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/licenses/MIT
End of explanation
t = [1, 2, 2, 3, 5]
Explanation: Given a list of values, there are several ways to count the frequency of each value.
End of explanation
hist = {}
for x in t:
hist[x] = hist.get(x, 0) + 1
hist
Explanation: You can use a Python dictionary:
End of explanation
from collections import Counter
counter = Counter(t)
counter
Explanation: You can use a Counter (which is a dictionary with additional methods):
End of explanation
import thinkstats2
hist = thinkstats2.Hist([1, 2, 2, 3, 5])
hist
Explanation: Or you can use the Hist object provided by thinkstats2:
End of explanation
hist.Freq(2)
Explanation: Hist provides Freq, which looks up the frequency of a value.
End of explanation
hist[2]
Explanation: You can also use the bracket operator, which does the same thing.
End of explanation
hist[4]
Explanation: If the value does not appear, it has frequency 0.
End of explanation
hist.Values()
Explanation: The Values method returns the values:
End of explanation
for val in sorted(hist.Values()):
print(val, hist[val])
Explanation: So you can iterate the values and their frequencies like this:
End of explanation
for val, freq in hist.Items():
print(val, freq)
Explanation: Or you can use the Items method:
End of explanation
import thinkplot
thinkplot.Hist(hist)
thinkplot.Config(xlabel='value', ylabel='frequency')
Explanation: thinkplot is a wrapper for matplotlib that provides functions that work with the objects in thinkstats2.
For example Hist plots the values and their frequencies as a bar graph.
Config takes parameters that label the x and y axes, among other things.
End of explanation
preg = nsfg.ReadFemPreg()
live = preg[preg.outcome == 1]
Explanation: As an example, I'll replicate some of the figures from the book.
First, I'll load the data from the pregnancy file and select the records for live births.
End of explanation
hist = thinkstats2.Hist(live.birthwgt_lb, label='birthwgt_lb')
thinkplot.Hist(hist)
thinkplot.Config(xlabel='Birth weight (pounds)', ylabel='Count')
Explanation: Here's the histogram of birth weights in pounds. Notice that Hist works with anything iterable, including a Pandas Series. The label attribute appears in the legend when you plot the Hist.
End of explanation
ages = np.floor(live.agepreg)
hist = thinkstats2.Hist(ages, label='agepreg')
thinkplot.Hist(hist)
thinkplot.Config(xlabel='years', ylabel='Count')
Explanation: Before plotting the ages, I'll apply floor to round down:
End of explanation
# Solution goes here
length = live.prglngth
hist = thinkstats2.Hist(length, label = 'preglngth')
thinkplot.Hist(hist)
thinkplot.Config(xlabel='Weeks', ylabel='Count')
Explanation: As an exercise, plot the histogram of pregnancy lengths (column prglngth).
End of explanation
for weeks, freq in hist.Smallest(10):
print(weeks, freq)
Explanation: Hist provides smallest, which select the lowest values and their frequencies.
End of explanation
# Solution goes here
for weeks, freq in hist.Largest(10):
print(weeks, freq)
Explanation: Use Largest to display the longest pregnancy lengths.
End of explanation
firsts = live[live.birthord == 1]
others = live[live.birthord != 1]
first_hist = thinkstats2.Hist(firsts.prglngth, label='first')
other_hist = thinkstats2.Hist(others.prglngth, label='other')
Explanation: From live births, we can selection first babies and others using birthord, then compute histograms of pregnancy length for the two groups.
End of explanation
width = 0.45
thinkplot.PrePlot(2)
thinkplot.Hist(first_hist, align='right', width=width)
thinkplot.Hist(other_hist, align='left', width=width)
thinkplot.Config(xlabel='weeks', ylabel='Count', xlim=[27, 46])
Explanation: We can use width and align to plot two histograms side-by-side.
End of explanation
mean = live.prglngth.mean()
var = live.prglngth.var()
std = live.prglngth.std()
Explanation: Series provides methods to compute summary statistics:
End of explanation
mean, std
Explanation: Here are the mean and standard deviation:
End of explanation
# Solution goes here
std == np.sqrt(var)
Explanation: As an exercise, confirm that std is the square root of var:
End of explanation
firsts.prglngth.mean(), others.prglngth.mean()
Explanation: Here's are the mean pregnancy lengths for first babies and others:
End of explanation
firsts.prglngth.mean() - others.prglngth.mean()
Explanation: And here's the difference (in weeks):
End of explanation
def CohenEffectSize(group1, group2):
Computes Cohen's effect size for two groups.
group1: Series or DataFrame
group2: Series or DataFrame
returns: float if the arguments are Series;
Series if the arguments are DataFrames
diff = group1.mean() - group2.mean()
var1 = group1.var()
var2 = group2.var()
n1, n2 = len(group1), len(group2)
pooled_var = (n1 * var1 + n2 * var2) / (n1 + n2)
d = diff / np.sqrt(pooled_var)
return d
Explanation: This functon computes the Cohen effect size, which is the difference in means expressed in number of standard deviations:
End of explanation
# Solution goes here
CohenEffectSize(firsts.prglngth, others.prglngth)
Explanation: Compute the Cohen effect size for the difference in pregnancy length for first babies and others.
End of explanation
# Solution goes here
firsts_hist=thinkstats2.Hist(np.round(firsts.totalwgt_lb), label='firsts')
others_hist=thinkstats2.Hist(np.round(others.totalwgt_lb), label='others')
print('mean')
print('firsts:', firsts.totalwgt_lb.mean())
print('others:', others.totalwgt_lb.mean())
print('')
print('stdev')
print('firsts:', firsts.totalwgt_lb.mean())
print('others:', others.totalwgt_lb.mean())
print('')
print('median')
print('firsts:', firsts.totalwgt_lb.median())
print('others:', others.totalwgt_lb.median())
width=0.45
thinkplot.PrePlot(2)
thinkplot.Hist(firsts_hist, align='left', width=width)
thinkplot.Hist(others_hist, align='right', width=width)
thinkplot.Config(xlabel='pounds', ylabel='Count', xlim=(0, 15))
# Solution goes here
CohenEffectSize(firsts.totalwgt_lb, others.totalwgt_lb)
Explanation: Exercises
Using the variable totalwgt_lb, investigate whether first babies are lighter or heavier than others.
Compute Cohen’s effect size to quantify the difference between the groups. How does it compare to the difference in pregnancy length?
End of explanation
resp = nsfg.ReadFemResp()
Explanation: For the next few exercises, we'll load the respondent file:
End of explanation
# Solution goes here
inc_hist = thinkstats2.Hist(resp.totincr)
thinkplot.Hist(inc_hist)
Explanation: Make a histogram of <tt>totincr</tt> the total income for the respondent's family. To interpret the codes see the codebook.
End of explanation
# Solution goes here
age_hist = thinkstats2.Hist(resp.age_r)
thinkplot.Hist(age_hist)
Explanation: Make a histogram of <tt>age_r</tt>, the respondent's age at the time of interview.
End of explanation
# Solution goes here
fmhh_hist = thinkstats2.Hist(resp.numfmhh)
thinkplot.Hist(fmhh_hist)
Explanation: Make a histogram of <tt>numfmhh</tt>, the number of people in the respondent's household.
End of explanation
# Solution goes here
parity_hist = thinkstats2.Hist(resp.parity)
thinkplot.Hist(parity_hist)
Explanation: Make a histogram of <tt>parity</tt>, the number of children borne by the respondent. How would you describe this distribution?
End of explanation
# Solution goes here
parity_hist.Largest(10)
Explanation: This data is left-skewed with a long tail. Women are about as likely to have 1 as 2 children, though parity drops off significantly after 2 children.
Use Hist.Largest to find the largest values of <tt>parity</tt>.
End of explanation
# Solution goes here
hinc = resp[resp['totincr'] == 14]
other = resp[resp['totincr'] < 14]
hinc_hist = thinkstats2.Hist(hinc.parity)
thinkplot.Hist(hinc_hist)
Explanation: Let's investigate whether people with higher income have higher parity. Keep in mind that in this study, we are observing different people at different times during their lives, so this data is not the best choice for answering this question. But for now let's take it at face value.
Use <tt>totincr</tt> to select the respondents with the highest income (level 14). Plot the histogram of <tt>parity</tt> for just the high income respondents.
End of explanation
# Solution goes here
hinc_hist.Largest(5)
Explanation: Find the largest parities for high income respondents.
End of explanation
# Solution goes here
print('mean parity, high income:', hinc.parity.mean())
print('mean parity, other:', other.parity.mean())
Explanation: Compare the mean <tt>parity</tt> for high income respondents and others.
End of explanation
# Solution goes here
CohenEffectSize(hinc.parity, other.parity)
Explanation: Compute the Cohen effect size for this difference. How does it compare with the difference in pregnancy length for first babies and others?
End of explanation |
8,537 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpretive Tag Statistics for Katherine Mansfield's "The Garden Party"
First, let's get all the necessary programming libraries that will allow us to do these computations.
Step1: Next, let's read the XML file of the short story.
Step2: Read all the critical remarks.
Step3: These functions will extract the tags from the critical remarks.
Step4: Create a de-duplicated list of tags represented.
Step5: Create a table of all the tags, and where they occur according to lexia.
Step6: Create a function for checking whether a tag is associated with a certain lexia.
Step7: Assemble a matrix of all tags, and whether they occur in certain lexia. Turn this into a data frame.
Step8: While we're at it, let's find the most frequent tags.
Step9: Group lexia by 10s, so the data are more meaningful than ones and zeroes.
Step10: Let's examine some of the tags. Where do references to flora occur in the story (as tagged)? Do these co-occur with references to sexuality? | Python Code:
from bs4 import BeautifulSoup # For processing XMLfrom BeautifulSoup
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
import itertools
from math import floor
matplotlib.style.use('ggplot')
import numpy as np
Explanation: Interpretive Tag Statistics for Katherine Mansfield's "The Garden Party"
First, let's get all the necessary programming libraries that will allow us to do these computations.
End of explanation
doc = open('garden-party.xml').read()
soup = BeautifulSoup(doc, 'lxml')
Explanation: Next, let's read the XML file of the short story.
End of explanation
interps = soup.findAll('interp')
Explanation: Read all the critical remarks.
End of explanation
def getTags(interp):
descs = interp.findAll('desc')
descList = []
for desc in descs:
descList.append(desc.string)
return descList
def getAllTags(interps):
allTags = []
for interp in interps:
tags = getTags(interp)
for tag in tags:
allTags.append(tag)
return allTags
Explanation: These functions will extract the tags from the critical remarks.
End of explanation
def dedupe(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
allTags = dedupe(getAllTags(interps))
print(str(allTags))
len(allTags)
Explanation: Create a de-duplicated list of tags represented.
End of explanation
tagDict = {}
for interp in interps:
number = int(interp.attrs['n'])
tags = getTags(interp)
tagDict[number] = tags
Explanation: Create a table of all the tags, and where they occur according to lexia.
End of explanation
def checkTags(tag):
hasTags = []
for n in tagDict:
if tag in tagDict[n]:
hasTags.append(1)
else:
hasTags.append(0)
return hasTags
Explanation: Create a function for checking whether a tag is associated with a certain lexia.
End of explanation
hasTagMatrix = {}
for tag in allTags:
hasTagMatrix[tag] = checkTags(tag)
df = pd.DataFrame(hasTagMatrix)
df.head()
Explanation: Assemble a matrix of all tags, and whether they occur in certain lexia. Turn this into a data frame.
End of explanation
s = df.sum(axis='rows').sort_values(ascending=False)
mostFrequentTags = s[s>3]
mft = mostFrequentTags.plot(kind='bar', alpha=0.5, figsize=(10,5))
mft.set_xlabel('tag')
mft.set_ylabel('number of occurrences')
fig = mft.get_figure()
fig.tight_layout()
fig.savefig('images/mtf.png') # save it to a file
Explanation: While we're at it, let's find the most frequent tags.
End of explanation
chunkSize=5
def chunkdf(df, chunkSize):
groups = df.groupby(lambda x: floor(x/chunkSize)).sum()
return groups
groups = chunkdf(df, chunkSize)
Explanation: Group lexia by 10s, so the data are more meaningful than ones and zeroes.
End of explanation
party = [145, 150] # These are the lexia where the party occurs. Let's draw dotted lines there.
partyAdjusted = [x/chunkSize for x in party]
def plotTags(tags, thisdf=groups):
plot = thisdf[tags].plot(kind='area', alpha=0.5, figsize=(10,5))
ymax = plot.get_ylim()[1]
plot.axvspan(partyAdjusted[0], partyAdjusted[1], facecolor="0.65", alpha=0.5)
plot.text(partyAdjusted[0]+0.2,ymax/2,'party',rotation=90)
plot.set_xlabel('lexia number / ' + str(chunkSize))
plot.set_ylabel('number of occurrences')
fig = plot.get_figure()
fig.tight_layout()
fig.savefig('images/' + '-'.join(tags) + '.png') # save it to a file
fig = plotTags(['flora', 'sexuality'])
plotTags(['flora', 'butterflies'])
plotTags(['desire', 'eyes'])
plotTags(['flora', 'sexuality', 'death'])
plotTags(['darkness', 'light'])
plotTags(['black', 'death', 'oil'])
plotTags(['flora', 'green'])
plotTags(['green', 'light', 'black', 'darkness'])
plotTags(['hats', 'voices'])
plotTags(['sounds', 'colors', 'touch'])
plotTags(['class'])
Explanation: Let's examine some of the tags. Where do references to flora occur in the story (as tagged)? Do these co-occur with references to sexuality?
End of explanation |
8,538 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting with matplotlib
The most common facility for plotting with the Python numerical suite is to use the matplotlib package. We will cover a few of the basic approaches to plotting figures. If you are interested in learning more about matplotlib or are looking to see how you might create a particular plot check out the matplotlib gallery for inspiration.
A MATLAB style interface
To start, matplotlib was designed to look very similar to MATLAB's plotting commands, here are a few examples that are along these lines
Step1: These commands import the necessary functions for NumPy and matplotlib for our demos. The first command is so that the IPython notebook will make our plots and display them in the notebook.
First off, lets plot a simple quadratic function $f(x) = x^2 + 2x + 3$
Step2: We can also label our plot (please do this), set the bounds and change the style of the plot
Step3: The othe major way to plot data is via a pseudo-color plot. A pseudo-color plot takes 3-dimensional data (or 2-dimensional depending on how you look at it) and plots it using color to represent the values of the function. Say we have a function $f(x, y)$, we can plot a pseudo-color by using the following commands.
Step4: Here we have used a new way to create NumPy ndarrays so that we can easily evaluate 2-dimensional functions. The function meshgrid takes two 1-dimensional arrays and turns them into 2, 2-dimensional arrays whose matching indices will provide an easy to use set of arrays that can be evaluate 2-dimensional functions.
Now as pretty as this rainbow plot is, it does not actually communicate as effectively as it could. This default colormap (a colormap is how we decide which values are colored which way) called "jet" is fairly ubiquitous in scientific and engineering visualization. Unfortunately the jet colormap tends to emphasize only certain parts of the range of values. I highly suggest looking at this explanation of how to choose a colormap if you are interested. The bottom line is, do not use jet if you can help it.
Anyway, let us make this plot also more useful.
Step5: A better way...
A much better way to "build" plots is to use a more object-oriented approach. In this case, we create the objects and manipulate them which allows us to have more control over how we create plots. Here we will create the annotated plots so that we have examples on how to do the same things (notice that they are very similar). The basic premise of this approach is that you generate objects that can be manipulated and remain persistent.
Step6: Here is the other example with a few extra tricks added in. | Python Code:
%matplotlib inline
import numpy
import matplotlib.pyplot as plt
Explanation: Plotting with matplotlib
The most common facility for plotting with the Python numerical suite is to use the matplotlib package. We will cover a few of the basic approaches to plotting figures. If you are interested in learning more about matplotlib or are looking to see how you might create a particular plot check out the matplotlib gallery for inspiration.
A MATLAB style interface
To start, matplotlib was designed to look very similar to MATLAB's plotting commands, here are a few examples that are along these lines:
End of explanation
x = numpy.linspace(-5, 5, 100)
y = x**2 + 2 * x + 3
plt.plot(x, y)
Explanation: These commands import the necessary functions for NumPy and matplotlib for our demos. The first command is so that the IPython notebook will make our plots and display them in the notebook.
First off, lets plot a simple quadratic function $f(x) = x^2 + 2x + 3$:
End of explanation
plt.plot(x, y, 'r--')
plt.xlabel("time (s)")
plt.ylabel("Tribble Population")
plt.title("Tribble Growth")
plt.xlim([0, 4])
plt.ylim([0, 25])
Explanation: We can also label our plot (please do this), set the bounds and change the style of the plot:
End of explanation
x = numpy.linspace(-1, 1, 100)
y = numpy.linspace(-1, 1, 100)
X, Y = numpy.meshgrid(x, y)
F = numpy.sin(X**2) + numpy.cos(Y**2)
plt.pcolor(X, Y, F)
plt.show()
Explanation: The othe major way to plot data is via a pseudo-color plot. A pseudo-color plot takes 3-dimensional data (or 2-dimensional depending on how you look at it) and plots it using color to represent the values of the function. Say we have a function $f(x, y)$, we can plot a pseudo-color by using the following commands.
End of explanation
color_map = plt.get_cmap("Oranges")
plt.gcf().set_figwidth(plt.gcf().get_figwidth() * 2)
plt.subplot(1, 2, 1, aspect="equal")
plt.pcolor(X, Y, F, cmap=color_map)
plt.colorbar()
plt.xlabel("x (m)")
plt.ylabel("y (m)")
plt.title("Tribble Density ($N/m^2$)")
plt.subplot(1, 2, 2, aspect="equal")
plt.pcolor(X, Y, X*Y, cmap=plt.get_cmap("RdBu"))
plt.xlabel("x (m)")
plt.ylabel("y (m)")
plt.title("Klignon Population ($N$)")
plt.colorbar()
plt.autoscale(enable=True, tight=False)
plt.show()
Explanation: Here we have used a new way to create NumPy ndarrays so that we can easily evaluate 2-dimensional functions. The function meshgrid takes two 1-dimensional arrays and turns them into 2, 2-dimensional arrays whose matching indices will provide an easy to use set of arrays that can be evaluate 2-dimensional functions.
Now as pretty as this rainbow plot is, it does not actually communicate as effectively as it could. This default colormap (a colormap is how we decide which values are colored which way) called "jet" is fairly ubiquitous in scientific and engineering visualization. Unfortunately the jet colormap tends to emphasize only certain parts of the range of values. I highly suggest looking at this explanation of how to choose a colormap if you are interested. The bottom line is, do not use jet if you can help it.
Anyway, let us make this plot also more useful.
End of explanation
x = numpy.linspace(-5, 5, 100)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
growth_curve = axes.plot(x, x**2 + 2 * x + 3, 'r--')
axes.set_xlabel("time (s)")
axes.set_ylabel("Tribble Population")
axes.set_title("Tribble Growth")
axes.set_xlim([0, 4])
axes.set_ylim([0, 25])
Explanation: A better way...
A much better way to "build" plots is to use a more object-oriented approach. In this case, we create the objects and manipulate them which allows us to have more control over how we create plots. Here we will create the annotated plots so that we have examples on how to do the same things (notice that they are very similar). The basic premise of this approach is that you generate objects that can be manipulated and remain persistent.
End of explanation
x = numpy.linspace(-1, 1, 100)
y = numpy.linspace(-1, 1, 100)
X, Y = numpy.meshgrid(x, y)
fig = plt.figure()
fig.set_figwidth(fig.get_figwidth() * 2)
axes = fig.add_subplot(1, 2, 1, aspect='equal')
tribble_density = axes.pcolor(X, Y, numpy.sin(X**2) + numpy.cos(Y**2), cmap=plt.get_cmap("Oranges"))
axes.set_xlabel("x (km)")
axes.set_ylabel("y (km)")
axes.set_title("Tribble Density ($N/km^2$)")
cbar = fig.colorbar(tribble_density, ax=axes)
cbar.set_label("$1/km^2$")
axes = fig.add_subplot(1, 2, 2, aspect='equal')
klingon_population_density = axes.pcolor(X, Y, X * Y + 1, cmap=plt.get_cmap("RdBu"))
axes.set_xlabel("x (km)")
axes.set_ylabel("y (km)")
axes.set_title("Klingon Population ($N$)")
cbar = fig.colorbar(klingon_population_density, ax=axes)
cbar.set_label("Number (thousands)")
plt.show()
Explanation: Here is the other example with a few extra tricks added in.
End of explanation |
8,539 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Iterable Operation Extensions
<--- Back
Table of Contents for this notebook
The Iterable Operation Extensions
Table of Contents for this notebook
Overview
IterEnumerateInstances
IterEnumerateInstancePaths
IterAssociatorInstances
IterAssociatorInstancePaths
IterReferenceInstances
IterReferenceInstancePaths
IterQueryInstances
Using list comprehensions with iter operations
Using iter operations and forcing the use of traditional operations
Using iter operations and forcing the use of pull operations
The iterable operation extensions (short
Step1: In this example (and the examples below), the connection has a default namespace set. This allows us to omit the namespace from the subsequent IterEnumerateInstances() method.
This example and the following examples also shows exception handling with pywbem
Step2: IterAssociatorInstances
The IterAssociatorInstances() method requests the instances associated with a source instance from the server. It uses either the OpenAssociatorInstances() if the server supports it or otherwise Associators().
The operation returns an iterator for instances, that is being processed in a for-loop.
The following code executes EnumerateInstanceNames() to enumerate instances of a class and selects the first instance to act as a source instance for the association operation
Step3: IterAssociatorInstancePaths
The IterAssociatorInstancePaths() method requests the instance paths of the instances associated with a source instance from the server. It uses either the OpenAssociatorInstancePaths() if the server supports it or otherwise AssociatorNames().
The operation returns an iterator for instance paths, that is being processed in a for-loop.
The following code executes EnumerateInstanceNames() to enumerate instances of a class and selects the first instance to act as a source instance for the association operation
Step4: IterReferenceInstances
The IterReferenceInstances() method requests the instances referencing a source instance from the server. It uses either the OpenReferenceInstances() if the server supports it or otherwise References().
The operation returns an iterator for instances, that is being processed in a for-loop.
The following code executes EnumerateInstanceNames() to enumerate instances of a class and selects the first instance to act as a source instance for the reference operation
Step5: IterReferenceInstancePaths
The IterReferenceInstancePaths() method requests the instance paths of the instances referencing a source instance from the server. It uses either the OpenReferenceInstancePaths() if the server supports it or otherwise ReferenceNames().
The operation returns an iterator for instance paths, that is being processed in a for-loop.
The following code executes EnumerateInstanceNames() to enumerate instances of a class and selects the first instance to act as a source instance for the reference operation
Step6: IterQueryInstances
The IterQueryInstances() method requests the instances returned by a query from the server. It uses either the OpenQueryInstances() if the server supports it or otherwise ExecQuery().
This operation returns an object with two properties
Step7: Using list comprehensions with iter operations
As an alternative to the for-loop processing of the iterator returned by the Iter...() method, a list comprehension can be use to perform the entire processing sequence in a single statement
Step8: Using iter operations and forcing the use of traditional operations
The following example forces the use of the traditional operations by setting the use_pull_operations flag on the connection to False
Step9: Using iter operations and forcing the use of pull operations
The following example forces the use of the pull operations by setting the use_pull_operations flag on the connection to True. If the server does not support pull operations an exception "CIM_ERR_NOT_SUPPORTED" will be returned. | Python Code:
import pywbem
# Global variables used by all examples:
server = 'http://localhost'
username = 'user'
password = 'password'
namespace = 'root/cimv2'
classname = 'CIM_ComputerSystem'
max_obj_cnt = 100
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True)
try:
inst_iterator = conn.IterEnumerateInstances(classname,
MaxObjectCount=max_obj_cnt)
for inst in inst_iterator:
print('path=%s' % inst.path)
print(inst.tomof())
except pywbem.Error as exc:
print('Operation failed: %s' % exc)
Explanation: The Iterable Operation Extensions
<--- Back
Table of Contents for this notebook
The Iterable Operation Extensions
Table of Contents for this notebook
Overview
IterEnumerateInstances
IterEnumerateInstancePaths
IterAssociatorInstances
IterAssociatorInstancePaths
IterReferenceInstances
IterReferenceInstancePaths
IterQueryInstances
Using list comprehensions with iter operations
Using iter operations and forcing the use of traditional operations
Using iter operations and forcing the use of pull operations
The iterable operation extensions (short: iter operations) are a set of methods added to pywbem.WBEMConnection class in pywbem version 0.10.0 to simplify the use of the pull vs. traditional operations (the original enumeration operations such as EnumerateInstances).
They simplify executing instance enumerations (EnumerateInstances, Associators, and References) by merging the traditional operations and pull operations so the client developer only has to code the iter operations and the Pywbem environment uses the Pull or traditional operations based on the server characteristics.
The purpose and function and usage of these WBEMConnection methods is defined in the [Concepts section] (https://pywbem.readthedocs.io/en/latest/concepts.html#iter-operations) of the online pywbem documentation.
IterEnumerateInstances
The IterEnumerateInstances() method requests the instances of a class from the server. It uses either the OpenEnumerateInstances() if the server supports it or otherwise EnumerateInstances().
The operation returns an iterator for instances, that is being processed in a for-loop.
End of explanation
# Global variables from first example are used
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True)
try:
path_iterator = conn.IterEnumerateInstancePaths(classname,
MaxObjectCount=max_obj_cnt)
for path in path_iterator:
print('path=%s' % path)
except pywbem.Error as exc:
print('Operation failed: %s' % exc)
Explanation: In this example (and the examples below), the connection has a default namespace set. This allows us to omit the namespace from the subsequent IterEnumerateInstances() method.
This example and the following examples also shows exception handling with pywbem: Pywbem wraps any exceptions that are considered runtime errors, and raises them as subclasses of pywbem.Error. Any other exceptions are considered programming errors. Therefore, the code above only needs to catch pywbem.Error.
Note that the creation of the pywbem.WBEMConnection object in the code above does not need to be protected by exception handling; its initialization code does not raise any pywbem runtime errors.
IterEnumerateInstancePaths
The IterEnumerateInstancePaths() method requests the instance paths of the instances of a class from the server. It uses either the OpenEnumerateInstances() if the server supports it or otherwise EnumerateInstanceNames().
The operation returns an iterator for instance paths, that is being processed in a for-loop:
End of explanation
# Global variables from first example are used
max_obj_cnt = 100
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True)
try:
# Find an instance path for the source end of an association.
source_paths = conn.EnumerateInstanceNames(classname)
if source_paths:
inst_iterator = conn.IterAssociatorInstances(source_paths[0],
MaxObjectCount=max_obj_cnt)
for inst in inst_iterator:
print('path=%s' % inst.path)
print(inst.tomof())
else:
print('%s class has no instances and therefore no associations', classname)
except pywbem.Error as exc:
print('Operation failed: %s' % exc)
Explanation: IterAssociatorInstances
The IterAssociatorInstances() method requests the instances associated with a source instance from the server. It uses either the OpenAssociatorInstances() if the server supports it or otherwise Associators().
The operation returns an iterator for instances, that is being processed in a for-loop.
The following code executes EnumerateInstanceNames() to enumerate instances of a class and selects the first instance to act as a source instance for the association operation:
End of explanation
# Global variables from first example are used
max_obj_cnt = 100
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True)
try:
# Find an instance path for the source end of an association.
source_paths = conn.EnumerateInstanceNames(classname)
if source_paths:
path_iterator = conn.IterAssociatorInstancePaths(source_paths[0],
MaxObjectCount=max_obj_cnt)
for path in path_iterator:
print('path=%s' % path)
else:
print('%s class has no instances and therefore no instance associations', classname)
except pywbem.Error as exc:
print('Operation failed: %s' % exc)
Explanation: IterAssociatorInstancePaths
The IterAssociatorInstancePaths() method requests the instance paths of the instances associated with a source instance from the server. It uses either the OpenAssociatorInstancePaths() if the server supports it or otherwise AssociatorNames().
The operation returns an iterator for instance paths, that is being processed in a for-loop.
The following code executes EnumerateInstanceNames() to enumerate instances of a class and selects the first instance to act as a source instance for the association operation:
End of explanation
# Global variables from first example are used
max_obj_cnt = 100
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True)
try:
# Find an instance path for the source end of an association.
source_paths = conn.EnumerateInstanceNames(classname)
if source_paths:
inst_iterator = conn.IterAssociatorInstances(source_paths[0],
MaxObjectCount=max_obj_cnt)
for instance in inst_iterator:
print('path=%s' % inst.path)
print(inst.tomof())
else:
print('%s class has no instances and therefore no instance associations', classname)
except pywbem.Error as exc:
print('Operation failed: %s' % exc)
Explanation: IterReferenceInstances
The IterReferenceInstances() method requests the instances referencing a source instance from the server. It uses either the OpenReferenceInstances() if the server supports it or otherwise References().
The operation returns an iterator for instances, that is being processed in a for-loop.
The following code executes EnumerateInstanceNames() to enumerate instances of a class and selects the first instance to act as a source instance for the reference operation:
End of explanation
# Global variables from first example are used
max_obj_cnt = 100
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True)
try:
# Find an instance path for the source end of an association.
source_paths = conn.EnumerateInstanceNames(classname)
if source_paths:
path_iterator = conn.IterReferenceInstancePaths(source_paths[0],
MaxObjectCount=max_obj_cnt)
for path in path_iterator:
print('path=%s' % path)
else:
print('%s class has no instances and therefore no instance associations', classname)
except pywbem.Error as exc:
print('Operation failed: %s' % exc)
Explanation: IterReferenceInstancePaths
The IterReferenceInstancePaths() method requests the instance paths of the instances referencing a source instance from the server. It uses either the OpenReferenceInstancePaths() if the server supports it or otherwise ReferenceNames().
The operation returns an iterator for instance paths, that is being processed in a for-loop.
The following code executes EnumerateInstanceNames() to enumerate instances of a class and selects the first instance to act as a source instance for the reference operation:
End of explanation
# Global variables from first example are used
query_language = "DMTF:CQL"
query = 'Select * from Pywbem_Person'
max_obj_cnt = 10
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True)
try:
inst_result = conn.IterQueryInstances(query_language, query,
MaxObjectCount=max_obj_cnt)
for inst in inst_result.generator:
print(inst.tomof())
else:
print('query has no result')
except pywbem.Error as exc:
print('Operation failed: %s' % exc)
Explanation: IterQueryInstances
The IterQueryInstances() method requests the instances returned by a query from the server. It uses either the OpenQueryInstances() if the server supports it or otherwise ExecQuery().
This operation returns an object with two properties:
query_result_class (CIMClass): The query result class, if requested via the ReturnQueryResultClass parameter which is only used with the [OpenQueryInstances()] operation and is not available with the [ExecQuery()] operation. None, if a query result class was not requested.
generator - A generator object that allows the user to iterate the CIM instances representing the query result. These instances do not have an instance path set.
End of explanation
# Global variables from first example are used
max_obj_cnt = 100
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True)
try:
paths = [path for path in conn.IterEnumerateInstancePaths(classname,
MaxObjectCount=max_obj_cnt)]
print(*paths, sep='\n')
except pywbem.Error as exc:
print('Operation failed: %s' % exc)
Explanation: Using list comprehensions with iter operations
As an alternative to the for-loop processing of the iterator returned by the Iter...() method, a list comprehension can be use to perform the entire processing sequence in a single statement:
End of explanation
# Global variables from first example are used
max_obj_cnt = 100
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True,
use_pull_operations=False)
try:
inst_iterator = conn.IterEnumerateInstances(classname,
MaxObjectCount=max_obj_cnt)
for inst in inst_iterator:
print('path=%s' % inst.path)
print(inst.tomof())
except pywbem.Error as exc:
print('Operation failed: %s' % exc)
Explanation: Using iter operations and forcing the use of traditional operations
The following example forces the use of the traditional operations by setting the use_pull_operations flag on the connection to False:
End of explanation
# Global variables from first example are used
max_obj_cnt = 100
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True,
use_pull_operations=True)
try:
inst_iterator = conn.IterEnumerateInstances(classname,
MaxObjectCount=max_obj_cnt)
for inst in inst_iterator:
print('path=%s' % inst.path)
print(inst.tomof())
except pywbem.Error as exc:
print('Operation failed: %s' % exc)
Explanation: Using iter operations and forcing the use of pull operations
The following example forces the use of the pull operations by setting the use_pull_operations flag on the connection to True. If the server does not support pull operations an exception "CIM_ERR_NOT_SUPPORTED" will be returned.
End of explanation |
8,540 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python and Natural Language Technologies
Type system and built-in types
Lecture 02
13 September 2017
PEP8, the Python style guide
widely accepted style guide for Python
PEP8 by Guido himself, 2001
Specifies
Step1: Strongly typed
most implicit conversions are disallowed.
conversions between numeric types are OK
Step2: conversions between numeric types and string are not allowed
Step3: we must explicitely cast it
Step4: Note that many other languages like Javascript allow implicit casting
Step5: Built-in types and operators
boolean operators
three boolean operators
Step6: boolean type
two boolean values
Step7: Numeric types
three numeric types
Step8: implicit conversion between numeric types is supported in arithmetic operations
the resulting type is the one with less data loss
Step9: Precision and range
integers have unlimited precision
different from Python2, where integers are usually implemented using C's long type
Step10: in Python2 numbers are automatically converted to Python's long type when they exceed maxint
Step11: Python3
Step12: float
floats are usually implemented using C's double.
complex numbers use two floats for their real and imaginary parts
check sys.float_info for more information
Step13: Arithmetic operators
addition, subtraction and product work the same as in C/C++
Step14: quotient operator
Python 2 vs. 3 difference
in Python3 operator/ computes the float quotient even if the operands are both integers
Step15: in Python2 the quotient is integer if both operands are integers
the result is the floor of the quotient
Step16: this is not the case if one or both of the operands are float
Step17: Explicit floor quotient operator
Step18: Comparison operators
Step19: operators can be chained
Step20: Other operators for numeric types
remainder
Step21: power
Step22: absolute value
Step23: round
Step24: Explicit conversions between numeric types
Step25: math and cmath
additional operations
cmath is for complex numbers
Step26: Mutable vs. immutable types
instances of mutable types can be modified in place
immutable objects have the same value during their lifetime
are numeric types mutable or immutable?
Step27: How about booleans?
Step28: There is only one True and one False object.
How about lists?
Step29: Lists are mutable.
Sequence types
all sequences support the following basic operations
| operation | behaviour |
|
Step30: Advanced indexing, ranges
Step31: Q. What is the output?
Step32: Lists are mutable, elements can be added or changed
Step33: elements don't need to be of the same type
Step34: lists can be traversed with for loops
Step35: enumerate
if we need the indices too, the built-in enumerate function iterates over index-element pairs
Step36: List sorting
lists can be sorted using the built-in sorted function
Step37: the sorting key can be specified using the key argument
Step38: tuple
tuple
tuple is an immutable sequence
it may be empty
Step39: tuples can be indexed the same way as lists
Step40: tuples contain immutable references, however, the objects may be mutable
Step41: dictionary
dictionary
basic and only built-in map type
maps keys to values
Step42: equivalent to
Step43: removing keys
Step44: iterating dictionaries
keys and values can be iterated separately or together
iterating keys
Step45: iterating values
Step46: iterating both
Step47: Under the hood
uses hash table (same as C++'s std
Step48: tuples are immutable too
Step49: however lists are not
Step50: Q. Can these be dictionary keys?
Step51: set
set
collection of unique, hashable elements
implements basic set operations (intersection, union, difference)
Step52: deleting elements
Step53: frozenset
immutable counterpart of set
Step54: set operations
implemented as
methods
overloaded operators
Step55: these operations return new sets
Step56: issubset and issuperset
Step57: useful set properties
creating a set is a convenient way of getting the unique elements of a sequence
Step58: sets and dictionaries provide O(1) lookup
in contrast lists provide O(n) lookup
Step59: Functions with variable number of arguments
recall that functions may take positional and keyword arguments
Step60: arguments may have default values starting from the rightmost argument
Step61: args and kwargs
both positional and keyword arguments can be captured in arbitrary numbers using the * and ** operators
positional arguments are captured in a tuple
Step62: keyword arguments are captured in a dictionary
Step63: we usually capture both
Step64: Mutable default arguments
be careful with mutable default arguments
Step65: best not to use mutable defaults
One solution is to create a new list inside a function
Step66: Lambda expressions
Lambda expressions
unnamed functions
may take parameters
can access local scope
Step67: Let's sort this list by absolute value. The built-in sorted's default behavior is not enough right now
Step68: but we can specify the key to use
Step69: we can use any callable as the key
Step70: Strings
Strings
strings are immutable sequences of Unicode code points
strings can be constructed in various ways
Step71: immutability makes it impossible to change a string (unlike C-style string or C++'s std
Step72: all string operations create new objects
Step73: strings support most operations available for lists
advanced indexing
Step74: Character encodings - Unicode
Unicode provides a mapping from letters to code points or numbers
| character | Unicode code point |
| ---- | ---- |
| a | U+0061 |
| ő | U+0151 |
| ش | U+0634 |
| گ | U+06AF |
| ¿ | U+00BF |
| ư | U+01B0 |
| Ң | U+04A2 |
| ⛵ | U+26F5 |
actual text needs to be stored as a byte array/sequence (byte strings)
character encoding
Step75: and automatically decodes byte sequnces when reading from file
Step76: Python 2 does not do this automatically
Step77: Python 2's str type is a byte string, different from Python 3's str which is a Unicode string
Python 2 has a separate unicode type for Unicode strings
we need to manually decode the byte string
Manual string decoding in Python 2
Step78: we also need to manually encode the text
Step79: bytes in Python 3
Python 3 has a different type called bytes for byte strings
one way to get a byte string is to encode a Unicode string
Step80: String operations
most sequence operations are supported
large variety of basic string manipulation
Step81: since each function returns a new string, they can be chained after another
Step82: Binary predicates (i.e. yes-no questions)
Step83: split and join
Step84: use explicit token separators
Step85: Q. Compute the word frequencies in a Wikipedia article.
Step86: various other ways for counting word frequencies here
String formatting
Python features several string formatting options.
str.format
non-str objects are automatically cast to str
under the hood
Step87: Format specification mini language
% operator
note that the arguments need to be parenthesized (make it a tuple)
Step88: string interpolation
f-strings were added in Python 3.6 in PEP498 | Python Code:
i = 2
type(i), id(i)
i = "foo"
type(i), id(i)
Explanation: Introduction to Python and Natural Language Technologies
Type system and built-in types
Lecture 02
13 September 2017
PEP8, the Python style guide
widely accepted style guide for Python
PEP8 by Guido himself, 2001
Specifies:
indentation
line length
module imports
class names, function names etc.
We shall use PEP8 throughout this course.
Type system
Dynamic type system
no need to declare variables
the = operator binds a reference to any arbitrary object
End of explanation
i = 2
f = 1.2
s = i + f
print(type(i), type(f))
print(type(i + f))
print(s)
Explanation: Strongly typed
most implicit conversions are disallowed.
conversions between numeric types are OK:
End of explanation
# print("I am " + 20 + " years old")
Explanation: conversions between numeric types and string are not allowed
End of explanation
print("I am " + str(20) + " years old")
Explanation: we must explicitely cast it:
End of explanation
%%javascript
element.text("I am " + 20 + " years old")
%%javascript
element.text("1" + 1)
%%javascript
element.text(1 + "1")
%%perl
print "1" + 1
Explanation: Note that many other languages like Javascript allow implicit casting:
End of explanation
x = 2
x < 2 or x >= 2
x > 0 and x < 10
not x < 0
Explanation: Built-in types and operators
boolean operators
three boolean operators: and, or and not
End of explanation
x = True
type(x)
True and False
True or False
not True
Explanation: boolean type
two boolean values: True and False (must be capitalized)
End of explanation
i = 2
f = 1.2
c = 1+2j
type(i), type(f), type(c)
Explanation: Numeric types
three numeric types: int, float and complex
an object's type is derived from its initial value
End of explanation
c2 = i + c
print(c2, type(c2))
Explanation: implicit conversion between numeric types is supported in arithmetic operations
the resulting type is the one with less data loss
End of explanation
%%python2
import sys
import math
max_i = sys.maxint
print(max_i, math.log(max_i, 2))
Explanation: Precision and range
integers have unlimited precision
different from Python2, where integers are usually implemented using C's long type
End of explanation
%%python2
import sys
max_i = sys.maxint
print(type(max_i), type(max_i+1))
Explanation: in Python2 numbers are automatically converted to Python's long type when they exceed maxint
End of explanation
type(2**63 + 1)
Explanation: Python3
End of explanation
import sys
sys.float_info
sys.int_info
Explanation: float
floats are usually implemented using C's double.
complex numbers use two floats for their real and imaginary parts
check sys.float_info for more information
End of explanation
i = 2
f = 4.2
c = 4.1-3j
s1 = i + f
s2 = f - c
s3 = i * c
print(s1, type(s1))
print(s2, type(s2))
print(s3, type(s3))
Explanation: Arithmetic operators
addition, subtraction and product work the same as in C/C++
End of explanation
-3 / 2
Explanation: quotient operator
Python 2 vs. 3 difference
in Python3 operator/ computes the float quotient even if the operands are both integers
End of explanation
%%python2
q = -3 / 2
print(q, type(q))
Explanation: in Python2 the quotient is integer if both operands are integers
the result is the floor of the quotient
End of explanation
%%python2
q = -3.0 / 2
print(q, type(q))
Explanation: this is not the case if one or both of the operands are float
End of explanation
-3.0 // 2
Explanation: Explicit floor quotient operator
End of explanation
x = 23
x < 24
x >= 22
Explanation: Comparison operators
End of explanation
23 < x < 100
23 <= x < 100
Explanation: operators can be chained
End of explanation
5 % 3
Explanation: Other operators for numeric types
remainder
End of explanation
2 ** 3
2 ** 0.5
Explanation: power
End of explanation
abs(-2 - 1j)
Explanation: absolute value
End of explanation
round(2.3456), round(2.3456, 2)
Explanation: round
End of explanation
float(2)
int(2.5)
Explanation: Explicit conversions between numeric types
End of explanation
import math
math.log(16), math.log(16, 2), math.exp(2), \
math.exp(math.log(10))
Explanation: math and cmath
additional operations
cmath is for complex numbers
End of explanation
x = 2
old_id = id(x)
x += 1
print(id(x) == old_id)
Explanation: Mutable vs. immutable types
instances of mutable types can be modified in place
immutable objects have the same value during their lifetime
are numeric types mutable or immutable?
End of explanation
x = True
y = False
print(id(x) == id(y))
x = False
print(id(x) == id(y))
Explanation: How about booleans?
End of explanation
l1 = [0, 1]
old_id = id(l1)
l1.append(2)
old_id == id(l1)
Explanation: There is only one True and one False object.
How about lists?
End of explanation
l = [1, 2, 2, 3]
l
l[1]
# l[4] # raises IndexError
l[-1]
Explanation: Lists are mutable.
Sequence types
all sequences support the following basic operations
| operation | behaviour |
| :----- | :----- |
| x in s | True if an item of s is equal to x, else False |
| x not in s | False if an item of s is equal to x, else True |
| s + t | the concatenation of s and t |
| s * n or n * s | equivalent to adding s to itself n times |
| s[i] | ith item of s, origin 0 |
| s[i:j] | slice of s from i to j |
| s[i:j:k] | slice of s from i to j with step k |
| len(s) | length of s |
| min(s) | smallest item of s |
| max(s) | largest item of s |
| s.index(x[, i[, j]]) | index of the first occurrence of x in s (at or after index i and before index j) |
| s.count(x) | total number of occurrences of x in s |
Table source
list
list
mutable sequence type
End of explanation
l = []
for i in range(20):
l.append(2*i + 1)
l[:10]
l[-4:]
i = 2
l[i:i+3]
l[2:10:3]
Explanation: Advanced indexing, ranges
End of explanation
l[::-1]
Explanation: Q. What is the output?
End of explanation
l = []
l.append(1)
l.append(2)
l.append(2)
l
l[1] = 12
l.extend([3, 4, 5])
len(l), l
Explanation: Lists are mutable, elements can be added or changed:
End of explanation
l = [1, -1, "foo", 2, "bar"]
l
Explanation: elements don't need to be of the same type
End of explanation
for element in l:
print(element)
Explanation: lists can be traversed with for loops
End of explanation
for i, element in enumerate(l):
print(i, element)
Explanation: enumerate
if we need the indices too, the built-in enumerate function iterates over index-element pairs
End of explanation
l = [3, -1, 2, 11]
for e in sorted(l):
print(e)
Explanation: List sorting
lists can be sorted using the built-in sorted function
End of explanation
shopping_list = [
["apple", 5],
["pear", 2],
["milk", 1],
["bread", 3],
]
for product in sorted(shopping_list, key=lambda x: -x[1]):
print(product)
Explanation: the sorting key can be specified using the key argument
End of explanation
t = ()
print(type(t), len(t))
t = ([1, 2, 3], "foo")
type(t), len(t)
t
Explanation: tuple
tuple
tuple is an immutable sequence
it may be empty
End of explanation
t[1], t[-1]
Explanation: tuples can be indexed the same way as lists
End of explanation
t = ([1, 2, 3], "foo")
# t[0]= "bar" # this raises a TypeError
for e in t:
print(id(e))
print("\nChanging an element of t[0]\n")
t[0][1] = 11
for e in t:
print(id(e))
print("\n", t)
Explanation: tuples contain immutable references, however, the objects may be mutable
End of explanation
d = {} # empty dictionary same as d = dict()
d["apple"] = 12
d["plum"] = 2
d
Explanation: dictionary
dictionary
basic and only built-in map type
maps keys to values
End of explanation
d = {"apple": 12, "plum": 2}
d
Explanation: equivalent to
End of explanation
del d["apple"]
d
Explanation: removing keys
End of explanation
d = {"apple": 12, "plum": 2}
for key in d.keys():
print(key, d[key])
Explanation: iterating dictionaries
keys and values can be iterated separately or together
iterating keys
End of explanation
for value in d.values():
print(value)
Explanation: iterating values
End of explanation
for key, value in d.items():
print(key, value)
Explanation: iterating both
End of explanation
d = {}
d[1] = "a" # numeric types are immutable
d[3+2j] = "b"
d["c"] = 1.0
d
Explanation: Under the hood
uses hash table (same as C++'s std::unordered_map)
constraints on key values: they must be hashable i.e. they cannot be or contain mutable objects
keys can be mixed type
End of explanation
d[("apple", 1)] = -2
d
Explanation: tuples are immutable too
End of explanation
# d[["apple", 1]] = 12 # raises TypeError
Explanation: however lists are not
End of explanation
key1 = (2, (3, 4))
key2 = (2, [], (3, 4))
# d = {}
# d[key1] = 1
# d[key2] = 2
Explanation: Q. Can these be dictionary keys?
End of explanation
s = set()
s.add(2)
s.add(3)
s.add(2)
s
s = {2, 3, 2}
type(s), s
Explanation: set
set
collection of unique, hashable elements
implements basic set operations (intersection, union, difference)
End of explanation
s.add(2)
s.remove(2)
# s.remove(2) # raises KeyError, since we already removed this element
s.discard(2) # removes if present, does not raise exception
Explanation: deleting elements
End of explanation
fs = frozenset([1, 2])
# fs.add(2) # raises AttributeError
fs = frozenset([1, 2])
s = {1, 2}
d = dict()
d[fs] = 1
# d[s] = 2 # raises TypeError
d
Explanation: frozenset
immutable counterpart of set
End of explanation
s1 = {1, 2, 3, 4, 5}
s2 = {2, 5, 6, 7}
s1 & s2 # s1.intersection(s2) or s2.intersection(s1)
s1 | s2 # s1.union(s2) OR s2.union(s1)
s1 - s2, s2 - s1 # s1.difference(s2), s2.difference(s1)
Explanation: set operations
implemented as
methods
overloaded operators
End of explanation
s3 = s1 & s2
type(s3), id(s3) == id(s1), id(s3) == id(s2)
Explanation: these operations return new sets
End of explanation
s1 < s2, s1.issubset(s2)
{1, 2} < s1
s1.issuperset({1, 6})
Explanation: issubset and issuperset
End of explanation
l = [1, 2, 3, -1, 1, 2, 1, 0]
uniq = set(l)
uniq
Explanation: useful set properties
creating a set is a convenient way of getting the unique elements of a sequence
End of explanation
import random
n = 10000
l = list(range(n))
random.shuffle(l)
s = set(l)
len(s), len(l)
{2, -1, 12, "aa", "bb"}
{"aa", "cc", 2, "bb"}
%%timeit
2 in l
%%timeit
2 in s
Explanation: sets and dictionaries provide O(1) lookup
in contrast lists provide O(n) lookup
End of explanation
def foo(arg1, arg2, arg3):
print(arg1, arg2, arg3)
foo(1, 2, 3)
foo(1, arg3=2, arg2=3)
Explanation: Functions with variable number of arguments
recall that functions may take positional and keyword arguments
End of explanation
def foo(arg1, arg2, arg3=12):
print(arg1, arg2, arg3)
foo(-1, -4)
Explanation: arguments may have default values starting from the rightmost argument
End of explanation
def arbitrary_positional_f(*args):
print(type(args))
for arg in args:
print(arg)
arbitrary_positional_f(1, 2, -1)
# arbitrary_positional_f(1, 2, arg=-1) # raises TypeError
Explanation: args and kwargs
both positional and keyword arguments can be captured in arbitrary numbers using the * and ** operators
positional arguments are captured in a tuple
End of explanation
def arbitrary_keyword_f(**kwargs):
print(type(kwargs))
for argname, value in kwargs.items():
print(argname, value)
arbitrary_keyword_f(arg1=1, arg2=12)
# arbitrary_keyword_f(12, arg=12) # TypeError
Explanation: keyword arguments are captured in a dictionary
End of explanation
def arbitrary_arg_f(*args, **kwargs):
if args:
print("Positional arguments")
for arg in args:
print(arg)
else:
print("No positional arguments")
if kwargs:
print("Keyword arguments")
for argname, value in kwargs.items():
print(argname, value)
else:
print("No keyword arguments")
arbitrary_arg_f()
arbitrary_arg_f(12, -2, param1="foo")
Explanation: we usually capture both
End of explanation
def insert_value(value, l=[]):
l.append(value)
print(l)
l1 = []
insert_value(12, l1)
l2 = []
insert_value(14, l2)
insert_value(-1)
insert_value(-3)
Explanation: Mutable default arguments
be careful with mutable default arguments
End of explanation
def insert_value(value, l=None):
if l is None:
l = []
l.append(value)
return l
l = insert_value(2)
l
insert_value(12)
Explanation: best not to use mutable defaults
One solution is to create a new list inside a function:
End of explanation
l = [-1, 0, -10, 2, 3]
Explanation: Lambda expressions
Lambda expressions
unnamed functions
may take parameters
can access local scope
End of explanation
for e in sorted(l):
print(e)
Explanation: Let's sort this list by absolute value. The built-in sorted's default behavior is not enough right now:
End of explanation
for e in sorted(l, key=lambda x : abs(x)):
print(e)
Explanation: but we can specify the key to use
End of explanation
for e in sorted(l, key=abs):
print(e)
Explanation: we can use any callable as the key
End of explanation
single = 'abc'
double = "abc"
single == double
Explanation: Strings
Strings
strings are immutable sequences of Unicode code points
strings can be constructed in various ways
End of explanation
s = "abc"
# s[1] = "c" # TypeError
Explanation: immutability makes it impossible to change a string (unlike C-style string or C++'s std::string)
End of explanation
print(id(s))
s += "def"
id(s)
Explanation: all string operations create new objects
End of explanation
s = "abcdefghijkl"
s[::2]
Explanation: strings support most operations available for lists
advanced indexing
End of explanation
s = "ábc"
print(type(s))
with open("file.txt", "w") as f:
f.write(s)
f.write("\n")
Explanation: Character encodings - Unicode
Unicode provides a mapping from letters to code points or numbers
| character | Unicode code point |
| ---- | ---- |
| a | U+0061 |
| ő | U+0151 |
| ش | U+0634 |
| گ | U+06AF |
| ¿ | U+00BF |
| ư | U+01B0 |
| Ң | U+04A2 |
| ⛵ | U+26F5 |
actual text needs to be stored as a byte array/sequence (byte strings)
character encoding: code point - byte array correspondence
encoding: Unicode code point $\rightarrow$ byte sequence
decoding: byte sequence $\rightarrow$ Unicode code point
most popular encoding: UTF-8
| character | Unicode code point | UTF-8 byte sequence |
| ---- | ---- | ---- |
| a | U+0061 | 61 |
| ő | U+0151 | C5 91 |
| ش | U+0634 | D8 B4 |
| گ | U+06AF | DA AF |
| ¿ | U+00BF | C2 BF |
| ư | U+01B0 | C6 B0 |
| Ң | U+04A2 | D2 A2 |
| ⛵ | U+26F5 | E2 9B B5 |
Python3 automatically encodes Unicode strings when:
- writing to file
- printing
- any kind of operation that requires byte string conversion
End of explanation
with open("file.txt") as f:
text = f.read().strip()
print(text)
type(text)
Explanation: and automatically decodes byte sequnces when reading from file:
End of explanation
%%python2
with open("file.txt") as f:
text = f.read().strip()
print(text)
print(text[0], len(text), type(text))
Explanation: Python 2 does not do this automatically
End of explanation
%%python2
with open("file.txt") as f:
text = f.read().decode('utf8').strip()
print(type(text), len(text))
print(text[0].encode('utf8'))
Explanation: Python 2's str type is a byte string, different from Python 3's str which is a Unicode string
Python 2 has a separate unicode type for Unicode strings
we need to manually decode the byte string
Manual string decoding in Python 2
End of explanation
%%python2
with open("file.txt") as f:
text = f.read().decode('utf8').strip()
print(text[0].encode('utf8'))
# print(text) # raise UnicodeEncodeError - can you interpret the error message?
print(text.encode('utf8'))
Explanation: we also need to manually encode the text
End of explanation
unicode_string = "ábc"
utf8_string = unicode_string.encode("utf8")
latin2_string = unicode_string.encode("latin2")
type(unicode_string), type(utf8_string), type(latin2_string)
len(unicode_string), len(utf8_string), len(latin2_string)
Explanation: bytes in Python 3
Python 3 has a different type called bytes for byte strings
one way to get a byte string is to encode a Unicode string
End of explanation
"abC".upper(), "ABC".lower(), "abc".title()
s = "\tabc \n"
print("<START>" + s + "<STOP>")
s.strip()
s.rstrip()
s.lstrip()
"abca".strip("a")
Explanation: String operations
most sequence operations are supported
large variety of basic string manipulation: lower, upper, title
End of explanation
" abcd abc".strip().rstrip("c").lstrip("ab")
Explanation: since each function returns a new string, they can be chained after another
End of explanation
"abc".startswith("ab"), "abc".endswith("cd")
"abc".istitle(), "Abc".istitle()
" \t\n".isspace()
"989".isdigit()
Explanation: Binary predicates (i.e. yes-no questions)
End of explanation
s = "the quick brown fox jumps over the lazy dog"
words = s.split()
words
s = "R.E.M."
s.split(".")
"-".join(words)
Explanation: split and join
End of explanation
" <W> ".join(words)
Explanation: use explicit token separators
End of explanation
import urllib.request
wp_url = "https://en.wikipedia.org/wiki/Budapest"
text = urllib.request.urlopen(wp_url).read()
text = text.decode('utf8')
words = text.split()
len(words), len(set(words))
word_freq = {}
for word in words:
if word not in word_freq:
word_freq[word] = 1
else:
word_freq[word] += 1
for word, freq in sorted(word_freq.items(), key=lambda x: -x[1])[:20]:
print(word, freq)
Explanation: Q. Compute the word frequencies in a Wikipedia article.
End of explanation
name = "John"
age = 25
print("My name is {0} and I'm {1} years old. I turned {1} last December".format(name, age))
print("My name is {} and I'm {} years old.".format(name, age))
# print("My name is {} and I'm {} years old. I turned {} last December".format(name, age)) # raises IndexError
print("My name is {name} and I'm {age} years old. I turned {age} last December".format(
name=name, age=age))
Explanation: various other ways for counting word frequencies here
String formatting
Python features several string formatting options.
str.format
non-str objects are automatically cast to str
under the hood: the object's __format__ method is called if it exists, otherwise its __str__ is called
End of explanation
print("My name is %s and I'm %d years old" % (name, age))
Explanation: Format specification mini language
% operator
note that the arguments need to be parenthesized (make it a tuple)
End of explanation
import sys
age2 = 12
if sys.version_info >= (3, 6):
print(f"My name is {name} and I'm {age} years old {age2}")
Explanation: string interpolation
f-strings were added in Python 3.6 in PEP498
End of explanation |
8,541 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, make the validation set with different drivers
Step1: fastai's statefarm has 3478 pics in validation set and 18946 in training, so let's get something close to that
Step2: now starts the actual work
Step3: Let's predict on the test set
The following is mashed together from fast.ai
Step4: That took forever (one hour? didn't time it perfectly)
Step5: Private score
Step6: Let's try something else - can I look at what the model predicts for the training set?
Let's have a look at the images with a 'bad' maximum probability, around 50% -
how many training pictures do we have with bad probabilities?
Step7: Give me all training pictures that don't have a class 'probability' above 90%
Step8: This is marked as class0 -
c0
Step9: This doesn't have any 'good' class, everything is low, which is weird - could be the not-straight head angle, but who knows. I just realised that some pictures have a blue tape-like thing on the driver window (see above and below), some pictures don't have that sheet, which is probably confusing.
TODO
Step10: This is marked as 'talking to passenger', but it may as well be c0, driving normally.
Kick out the 'bad' pictures
I believe that these low quality marks 'confuse' the network, so a network trained without those pictures should work slightly better.
Step11: 1580 pictures are 'weird', which is not that much compared to our 18587 pictures (roughly 8.5%)
Step12: OK we removed the weird ones.
Step13: That took forever (one hour? didn't time it perfectly)
Step14: Private score | Python Code:
%%bash
cut -f 1 -d ',' driver_imgs_list.csv | grep -v subject | uniq -c
lines=$(expr `wc -l driver_imgs_list.csv | cut -f 1 -d ' '` - 1)
echo "Got ${lines} pics"
Explanation: First, make the validation set with different drivers
End of explanation
import csv
import os
to_get = set(['p081','p075', 'p072', 'p066', 'p064'])
with open('driver_imgs_list.csv') as f:
next(f)
for line in csv.reader(f):
if line[0] in to_get:
if os.path.exists('train/%s/%s' %(line[1], line[2])):
os.popen('mv train/%s/%s valid/%s/%s'%(line[1], line[2], line[1], line[2]))
import glob
print('Training has', len(glob.glob('train/*/*jpg')))
print('Validation has', len(glob.glob('valid/*/*jpg')))
Explanation: fastai's statefarm has 3478 pics in validation set and 18946 in training, so let's get something close to that
End of explanation
batch_size = 64
gen_t = image.ImageDataGenerator(rotation_range=15, height_shift_range=0.05,
shear_range=0.1, channel_shift_range=20, width_shift_range=0.1)
trn_batches = get_batches(path+'train', gen_t, batch_size=batch_size)
val_batches = get_batches(path+'valid', batch_size=batch_size*2, shuffle=False)
from vgg16bn import Vgg16BN
model = vgg_ft_bn(10)
model.compile(optimizer=Adam(1e-3),
loss='categorical_crossentropy', metrics=['accuracy'])
model.fit_generator(trn_batches, trn_batches.N, nb_epoch=3, validation_data=val_batches,
nb_val_samples=val_batches.N)
model.optimizer.lr = 1e-5
model.fit_generator(trn_batches, trn_batches.N, nb_epoch=3, validation_data=val_batches,
nb_val_samples=val_batches.N)
last_conv_idx = [i for i,l in enumerate(model.layers) if type(l) is Convolution2D][-1]
conv_layers = model.layers[:last_conv_idx+1]
conv_model = Sequential(conv_layers)
trn_batches = get_batches(path+'train', gen_t, batch_size=batch_size, shuffle=False)
conv_feat = conv_model.predict_generator(trn_batches, trn_batches.nb_sample)
conv_val_feat = conv_model.predict_generator(val_batches, val_batches.nb_sample)
save_array(path+'results/conv_val_feat.dat', conv_val_feat)
save_array(path+'results/conv_feat.dat', conv_feat)
#print(type(conv_feat))
conv_feat = load_array(path+'results/conv_feat.dat')
conv_val_feat = load_array(path+'results/conv_val_feat.dat')
print(type(conv_feat))
#print(conv_layers[-1].output_shape)
def get_bn_layers(p):
return [
MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]),
Flatten(),
Dropout(p),
Dense(512, activation='relu'),
BatchNormalization(),
Dropout(p),
Dense(512, activation='relu'),
BatchNormalization(),
Dropout(p),
Dense(10, activation='softmax')
]
p = 0.8
(val_classes, trn_classes, val_labels, trn_labels,
val_filenames, filenames, test_filenames) = get_classes(path)
bn_model = Sequential(get_bn_layers(p))
bn_model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
bn_model.fit(conv_feat, trn_labels, batch_size=batch_size, nb_epoch=1,
validation_data=(conv_val_feat, val_labels))
bn_model.optimizer.lr = 1e-7
bn_model.fit(conv_feat, trn_labels, batch_size=batch_size, nb_epoch=7,
validation_data=(conv_val_feat, val_labels))
Explanation: now starts the actual work
End of explanation
test_batches = get_batches(path+'test', batch_size=batch_size, shuffle=False, class_mode=None)
conv_test_feat = conv_model.predict_generator(test_batches, test_batches.nb_sample)
Explanation: Let's predict on the test set
The following is mashed together from fast.ai
End of explanation
preds = bn_model.predict(conv_test_feat, batch_size=batch_size*2)
subm = do_clip(preds,0.93)
subm_name = path+'results/subm.gz'
classes = sorted(trn_batches.class_indices, key=trn_batches.class_indices.get)
submission = pd.DataFrame(subm, columns=classes)
submission.insert(0, 'img', [a[4:] for a in test_filenames])
submission.head()
submission.to_csv(subm_name, index=False, compression='gzip')
from IPython.display import FileLink
FileLink(subm_name)
Explanation: That took forever (one hour? didn't time it perfectly)
End of explanation
bn_model.save_weights(path+'models/bn_model.h5')
bn_model.load_weights(path+'models/bn_model.h5')
bn_feat = bn_model.predict(conv_feat, batch_size=batch_size)
bn_val_feat = bn_model.predict(conv_val_feat, batch_size=batch_size)
Explanation: Private score: 0.94359
Public score: 1.18213
End of explanation
np.max(bn_feat[:,1])
Explanation: Let's try something else - can I look at what the model predicts for the training set?
Let's have a look at the images with a 'bad' maximum probability, around 50% -
how many training pictures do we have with bad probabilities?
End of explanation
np.where(np.amax(bn_feat, axis=1) < 0.9)
def check_training_picture(bn_feat, filenames, number):
print(bn_feat[number,:])
print(filenames[number])
plt.imshow(mpimg.imread('train/' + filenames[number]))
check_training_picture(bn_feat, filenames, 22)
Explanation: Give me all training pictures that don't have a class 'probability' above 90%
End of explanation
check_training_picture(bn_feat, filenames, 45)
Explanation: This is marked as class0 -
c0: normal driving
c1: texting - right
c2: talking on the phone - right
c3: texting - left
c4: talking on the phone - left
c5: operating the radio
c6: drinking
c7: reaching behind
c8: hair and makeup
c9: talking to passenger
That hand is probably confusing, but it's mostly the correct class.
End of explanation
check_training_picture(bn_feat, filenames, 17421)
Explanation: This doesn't have any 'good' class, everything is low, which is weird - could be the not-straight head angle, but who knows. I just realised that some pictures have a blue tape-like thing on the driver window (see above and below), some pictures don't have that sheet, which is probably confusing.
TODO: find a way to mask that window
End of explanation
to_remove = np.where(np.amax(bn_feat, axis=1) < 0.9)[0]
print(len(to_remove))
print(1580./18587*100)
Explanation: This is marked as 'talking to passenger', but it may as well be c0, driving normally.
Kick out the 'bad' pictures
I believe that these low quality marks 'confuse' the network, so a network trained without those pictures should work slightly better.
End of explanation
to_remove_files = set([filenames[index] for index in to_remove])
list(to_remove_files)[:5]
out = open('weird_files.txt', 'w')
for f in to_remove_files:
out.write('%s\n'%f)
print(path)
%pwd
to_remove_files = [x.rstrip() for x in open('/home/ubuntu/statefarm/train/weird_files.txt')]
len(to_remove_files)
to_remove_files[:5]
%%bash
mkdir weird_ones
mkdir weird_ones/train
for i in {0..9}; do mkdir /home/ubuntu/statefarm/weird_ones/train/c${i}; done
%cd /home/ubuntu/statefarm/train
for l in glob.glob('*/*jpg'):
if l in to_remove_files:
os.popen('mv %s ../weird_ones/train/%s'%(l, l))
%%bash
find . -type f | wc -l
Explanation: 1580 pictures are 'weird', which is not that much compared to our 18587 pictures (roughly 8.5%)
End of explanation
path = "/home/ubuntu/statefarm/"
batch_size = 64
gen_t = image.ImageDataGenerator(rotation_range=15, height_shift_range=0.05,
shear_range=0.1, channel_shift_range=20, width_shift_range=0.1)
trn_batches = get_batches(path+'train', gen_t, batch_size=batch_size)
val_batches = get_batches(path+'valid', batch_size=batch_size*2, shuffle=False)
from vgg16bn import Vgg16BN
model = vgg_ft_bn(10)
model.compile(optimizer=Adam(1e-3),
loss='categorical_crossentropy', metrics=['accuracy'])
model.fit_generator(trn_batches, trn_batches.N, nb_epoch=3, validation_data=val_batches,
nb_val_samples=val_batches.N)
model.optimizer.lr = 1e-5
model.fit_generator(trn_batches, trn_batches.N, nb_epoch=3, validation_data=val_batches,
nb_val_samples=val_batches.N)
last_conv_idx = [i for i,l in enumerate(model.layers) if type(l) is Convolution2D][-1]
conv_layers = model.layers[:last_conv_idx+1]
conv_model = Sequential(conv_layers)
trn_batches = get_batches(path+'train', gen_t, batch_size=batch_size, shuffle=False)
conv_feat = conv_model.predict_generator(trn_batches, trn_batches.nb_sample)
conv_val_feat = conv_model.predict_generator(val_batches, val_batches.nb_sample)
#print(conv_layers[-1].output_shape)
def get_bn_layers(p):
return [
MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]),
Flatten(),
Dropout(p),
Dense(512, activation='relu'),
BatchNormalization(),
Dropout(p),
Dense(512, activation='relu'),
BatchNormalization(),
Dropout(p),
Dense(10, activation='softmax')
]
p = 0.8
(val_classes, trn_classes, val_labels, trn_labels,
val_filenames, filenames, test_filenames) = get_classes(path)
bn_model = Sequential(get_bn_layers(p))
bn_model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
bn_model.fit(conv_feat, trn_labels, batch_size=batch_size, nb_epoch=1,
validation_data=(conv_val_feat, val_labels))
bn_model.optimizer.lr = 1e-5
bn_model.fit(conv_feat, trn_labels, batch_size=batch_size, nb_epoch=7,
validation_data=(conv_val_feat, val_labels))
bn_model.optimizer.lr = 1e-7
bn_model.fit(conv_feat, trn_labels, batch_size=batch_size, nb_epoch=7,
validation_data=(conv_val_feat, val_labels))
test_batches = get_batches(path+'test', batch_size=batch_size, shuffle=False, class_mode=None)
conv_test_feat = conv_model.predict_generator(test_batches, test_batches.nb_sample)
Explanation: OK we removed the weird ones.
End of explanation
preds = bn_model.predict(conv_test_feat, batch_size=batch_size*2)
subm = do_clip(preds,0.93)
subm_name = path+'results/subm_woweird.gz'
classes = sorted(trn_batches.class_indices, key=trn_batches.class_indices.get)
submission = pd.DataFrame(subm, columns=classes)
submission.insert(0, 'img', [a[4:] for a in test_filenames])
submission.head()
submission.to_csv(subm_name, index=False, compression='gzip')
from IPython.display import FileLink
FileLink(subm_name)
Explanation: That took forever (one hour? didn't time it perfectly)
End of explanation
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
img = glob.glob('train/*/*jpg')[100]
img = cv2.imread(img)
(rects, weights) = hog.detectMultiScale(img, winStride=(4, 4), padding=(8, 8), scale=1.05)
for (x, y, w, h) in rects:
cv2.rectangle(orig, (x, y), (x + w, y + h), (0, 0, 255), 2)
rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
pick = non_max_suppression(rects, probs=None, overlapThresh=0.5)
for (xA, yA, xB, yB) in pick:
cv2.rectangle(img, (xA, yA), (xB, yB), (0, 255, 0), 2)
#plt.imshow(img)
#cv2.imshow('hi', img)
img.save('test.png')
Explanation: Private score: 0.92506
Public score: 1.11814
RESULTS
Interestingly, the validation accuracy and validation loss is VERY similar, almost identical to the above. The training accuracy is slightly better.
TODO: Fix the validation problems too
TRYING OUT CUTTING FROM PICTURES
End of explanation |
8,542 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The resilu linearity / non-linearity
The function $resilu(x)=\frac{x}{1-e^{-x}}$ can be written as the sum of a linear funciton and a function that limits to relu(x).
By using resilu(x) and 'non'-linearity in neural networks, the effect of a skip-connection should thus be included 'for free'.
Step1: Comparing $resilu(x)=\frac{x}{1-e^{-x}}$ with the $relu(x)$ function.
By introducing a parameter $a$, $relu(x)$ is a limit of $resilu(x,a)$
Step2: Resilu(x) can be split into a sum of two functions
Step3: Numerical instability at $x=0$
$\frac{x}{1-e^{-x}}$ is obviously numerically unstable at $x=0$, which could be seen as a phase transition or an unstable fixed point.
In order to use the resilu(x) function, the function itself and it's derivate (which are both not numerically stable around $x=0$ are approximated with $\mathcal{O}(4)$ taylor expansions for a small interval $-h<0<h$ in the actual implementation. See Resilu and dResilu() implementation
Series expansion to work with instabilities
Taylor series approximation for resilu(x)
Step4: $d/dx$ $resilu(x)$ and it's Taylor approximation | Python Code:
import copy
import numpy as np
import matplotlib.pyplot as plt
import math
import sympy
x=np.arange(-20,20,0.01)
def resilu(x):
return x/(1.0-np.exp(x*-1.0))
def relu(x):
y=copy.copy(x)
y[y<0]=0.0
return y
Explanation: The resilu linearity / non-linearity
The function $resilu(x)=\frac{x}{1-e^{-x}}$ can be written as the sum of a linear funciton and a function that limits to relu(x).
By using resilu(x) and 'non'-linearity in neural networks, the effect of a skip-connection should thus be included 'for free'.
End of explanation
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.plot(x,resilu(x),label='resilu')
ax.plot(x,relu(x),linestyle=':',label='relu')
ax.legend()
def resilu_nonlin(x):
return x/(np.exp(x)-1.0)
def resilu_lin(x):
return x
Explanation: Comparing $resilu(x)=\frac{x}{1-e^{-x}}$ with the $relu(x)$ function.
By introducing a parameter $a$, $relu(x)$ is a limit of $resilu(x,a)$:
$$\lim_{a\to\infty}\frac{x}{1-e^{-x a}}=relu(x)$$
End of explanation
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.plot(x,resilu_nonlin(x),label='resilu (non-lin part)')
ax.plot(x,resilu_lin(x),label='resilu (lin part)')
ax.plot(x,resilu_nonlin(x)+resilu_lin(x),label='non-lin + lin (= complete resilu)')
ax.plot(x,relu(x),linestyle=':',label='relu(x)')
ax.plot(x,relu(-x),linestyle=':',label='relu(-x)')
ax.legend()
Explanation: Resilu(x) can be split into a sum of two functions:
linear part $f_1(x)=x$
non-linear part $f_2(x)=\frac{x}{e^x-1}$, with exactly similar limit properties as the complete resilu function: $lim_{a\to\infty}\frac{x}{e^{x a}-1}=relu(-x)$
$$
resilu(x)=f_1(x)+f_2(x)=\frac{x}{e^x-1} + x = \frac{x}{1-e^{-x}}
$$
This should show that using resilu non-linearity should be äquivalent to using a 'standard' non-linearity and a skip connection that ommits the nonlinearity as additive residual connection. The only difference are arbitrary linear transformations which the net can easily cancel out.
End of explanation
x=sympy.Symbol('x')
sympy.series(x/(1-sympy.exp(-x)),x,n=10)
Explanation: Numerical instability at $x=0$
$\frac{x}{1-e^{-x}}$ is obviously numerically unstable at $x=0$, which could be seen as a phase transition or an unstable fixed point.
In order to use the resilu(x) function, the function itself and it's derivate (which are both not numerically stable around $x=0$ are approximated with $\mathcal{O}(4)$ taylor expansions for a small interval $-h<0<h$ in the actual implementation. See Resilu and dResilu() implementation
Series expansion to work with instabilities
Taylor series approximation for resilu(x)
End of explanation
sympy.diff(x/(1-sympy.exp(-x)),x)
sympy.series(sympy.diff(x/(1-sympy.exp(-x)),x),x,n=10)
sympy.diff(sympy.series(x/(1-sympy.exp(-x)),x,n=10),x)
Explanation: $d/dx$ $resilu(x)$ and it's Taylor approximation
End of explanation |
8,543 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Questão 1
Step1: Questão 2
Step2: Questão 3
Step3: Questão 4 | Python Code:
import numpy as np
from math import pi
import matplotlib.pyplot as plot
%matplotlib notebook
x = np.arange(-5, 5.001, 0.0001)
y = (x**4)-(16*(x**2)) + 16
plot.plot(x,y,'c')
plot.grid(True)
Explanation: Questão 1: Faça um gráfico da função $f(x) = x^4-16x^2+16$ para x de -5 a 5.
Coloque a grade.
Olhando para o gráfico, para quais valores de x temos f(x) = 0?
End of explanation
print('Para a f(x) = ax^2 + bx+ c, diga os valores de a, b e c:\n')
a = float(input('Valor de a: '))
b = float(input('Valor de b: '))
c = float(input('Valor de c: '))
delta = b**2 - 4*a*c
xmax = (-b)/(2*a)
x = np.arange(xmax-4, xmax+4.001, 0.001)
y = a*(x**2) + b*x + c
plot.plot(x, y, 'c')
plot.grid(True)
Explanation: Questão 2: Faça um programa que pede ao usuário para:
1. digitar um número a,
2. digitar um número b,
3. digitar um número c.
Em seguida, seu programa deve mostrar ao usuário o gráfico da função $f(x) = ax^2 + bx+ c$.
A dificuldade deste exercício é escolher um domínio para plotar $f$. Faça essa escolha de modo que a parábola fique centralizada.
End of explanation
t = np.arange(0, 2*pi + 0.001, 0.001)
x = 0 + 2*np.sin(t)
y = 0 + 2*np.cos(t)
plot.plot(x, y, 'c')
plot.axis('equal')
t = np.arange(0, 2*pi+0.001, 0.001)
x = 2+2*np.sin(t)
y = 2+2*np.cos(t)
plot.plot(x, y, 'c')
plot.axis('equal')
plot.grid(True)
Explanation: Questão 3: Faça um gráfico com dois círculos:
um com raio 2 e centro (0,0)
e outro em com raio 2 e centro (2,2).
Em quais pontos eles se cruzam? (Coloque a grade para ajudar.)
End of explanation
t = np.arange(0, 2*pi+0.001, 0.001)
for r in np.arange(1, 13.5, 0.5):
x = r*np.sin(t)
y = r*np.cos(t)
plot.plot(x, y, 'c')
plot.axis('equal')
plot.grid(True)
Explanation: Questão 4: Faça um programa que gere o gráfico abaixo (25 círculos concêntricos de raios $1, 1.5, \dots, 13$).
<img src="http://tidia4.ufabc.edu.br/access/content/group/8398384e-4091-4504-9c21-eae9a6a24a61/Unidade%206/circles.png">
Dica: use o comando for.
End of explanation |
8,544 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image features exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the assignments page on the course website.
We have seen that we can achieve reasonable performance on an image classification task by training a linear classifier on the pixels of the input image. In this exercise we will show that we can improve our classification performance by training linear classifiers not on raw pixels but on features that are computed from the raw pixels.
All of your work for this exercise will be done in this notebook.
Step1: Load data
Similar to previous exercises, we will load CIFAR-10 data from disk.
Step2: Extract Features
For each image we will compute a Histogram of Oriented
Gradients (HOG) as well as a color histogram using the hue channel in HSV
color space. We form our final feature vector for each image by concatenating
the HOG and color histogram feature vectors.
Roughly speaking, HOG should capture the texture of the image while ignoring
color information, and the color histogram represents the color of the input
image while ignoring texture. As a result, we expect that using both together
ought to work better than using either alone. Verifying this assumption would
be a good thing to try for the bonus section.
The hog_feature and color_histogram_hsv functions both operate on a single
image and return a feature vector for that image. The extract_features
function takes a set of images and a list of feature functions and evaluates
each feature function on each image, storing the results in a matrix where
each column is the concatenation of all feature vectors for a single image.
Step3: Train SVM on features
Using the multiclass SVM code developed earlier in the assignment, train SVMs on top of the features extracted above; this should achieve better results than training SVMs directly on top of raw pixels.
Step4: Inline question 1 | Python Code:
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading extenrnal modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
Explanation: Image features exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the assignments page on the course website.
We have seen that we can achieve reasonable performance on an image classification task by training a linear classifier on the pixels of the input image. In this exercise we will show that we can improve our classification performance by training linear classifiers not on raw pixels but on features that are computed from the raw pixels.
All of your work for this exercise will be done in this notebook.
End of explanation
from cs231n.features import color_histogram_hsv, hog_feature
def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000):
# Load the raw CIFAR-10 data
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# Subsample the data
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val = y_train[mask]
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
return X_train, y_train, X_val, y_val, X_test, y_test
X_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data()
Explanation: Load data
Similar to previous exercises, we will load CIFAR-10 data from disk.
End of explanation
from cs231n.features import *
num_color_bins = 10 # Number of bins in the color histogram
feature_fns = [hog_feature, lambda img: color_histogram_hsv(img, nbin=num_color_bins)]
X_train_feats = extract_features(X_train, feature_fns, verbose=True)
X_val_feats = extract_features(X_val, feature_fns)
X_test_feats = extract_features(X_test, feature_fns)
# Preprocessing: Subtract the mean feature
mean_feat = np.mean(X_train_feats, axis=0, keepdims=True)
X_train_feats -= mean_feat
X_val_feats -= mean_feat
X_test_feats -= mean_feat
# Preprocessing: Divide by standard deviation. This ensures that each feature
# has roughly the same scale.
std_feat = np.std(X_train_feats, axis=0, keepdims=True)
X_train_feats /= std_feat
X_val_feats /= std_feat
X_test_feats /= std_feat
# Preprocessing: Add a bias dimension
X_train_feats = np.hstack([X_train_feats, np.ones((X_train_feats.shape[0], 1))])
X_val_feats = np.hstack([X_val_feats, np.ones((X_val_feats.shape[0], 1))])
X_test_feats = np.hstack([X_test_feats, np.ones((X_test_feats.shape[0], 1))])
Explanation: Extract Features
For each image we will compute a Histogram of Oriented
Gradients (HOG) as well as a color histogram using the hue channel in HSV
color space. We form our final feature vector for each image by concatenating
the HOG and color histogram feature vectors.
Roughly speaking, HOG should capture the texture of the image while ignoring
color information, and the color histogram represents the color of the input
image while ignoring texture. As a result, we expect that using both together
ought to work better than using either alone. Verifying this assumption would
be a good thing to try for the bonus section.
The hog_feature and color_histogram_hsv functions both operate on a single
image and return a feature vector for that image. The extract_features
function takes a set of images and a list of feature functions and evaluates
each feature function on each image, storing the results in a matrix where
each column is the concatenation of all feature vectors for a single image.
End of explanation
# Use the validation set to tune the learning rate and regularization strength
from cs231n.classifiers.linear_classifier import LinearSVM
learning_rates = [1e-9, 1e-8, 1e-7]
regularization_strengths = [1e5, 1e6, 1e7]
results = {}
best_val = -1
best_svm = None
pass
################################################################################
# TODO: #
# Use the validation set to set the learning rate and regularization strength. #
# This should be identical to the validation that you did for the SVM; save #
# the best trained classifer in best_svm. You might also want to play #
# with different numbers of bins in the color histogram. If you are careful #
# you should be able to get accuracy of near 0.44 on the validation set. #
################################################################################
for l in learning_rates:
for r in regularization_strengths:
svm = LinearSVM()
svm.train(X_train_feats, y_train, learning_rate=l, reg=r, num_iters=1500, batch_size=200)
y_train_pred = svm.predict(X_train_feats)
y_val_pred = svm.predict(X_val_feats)
training_accuracy = np.mean(y_train == y_train_pred)
validation_accuracy = np.mean(y_val == y_val_pred)
results[(l, r)] = (training_accuracy, validation_accuracy)
if validation_accuracy > best_val:
best_val = validation_accuracy
best_svm = svm
################################################################################
# END OF YOUR CODE #
################################################################################
# Print out results.
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print 'lr %e reg %e train accuracy: %f val accuracy: %f' % (
lr, reg, train_accuracy, val_accuracy)
print 'best validation accuracy achieved during cross-validation: %f' % best_val
# Evaluate your trained SVM on the test set
y_test_pred = best_svm.predict(X_test_feats)
test_accuracy = np.mean(y_test == y_test_pred)
print test_accuracy
# An important way to gain intuition about how an algorithm works is to
# visualize the mistakes that it makes. In this visualization, we show examples
# of images that are misclassified by our current system. The first column
# shows images that our system labeled as "plane" but whose true label is
# something other than "plane".
examples_per_class = 8
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
for cls, cls_name in enumerate(classes):
idxs = np.where((y_test != cls) & (y_test_pred == cls))[0]
idxs = np.random.choice(idxs, examples_per_class, replace=False)
for i, idx in enumerate(idxs):
plt.subplot(examples_per_class, len(classes), i * len(classes) + cls + 1)
plt.imshow(X_test[idx].astype('uint8'))
plt.axis('off')
if i == 0:
plt.title(cls_name)
plt.show()
Explanation: Train SVM on features
Using the multiclass SVM code developed earlier in the assignment, train SVMs on top of the features extracted above; this should achieve better results than training SVMs directly on top of raw pixels.
End of explanation
print X_train_feats.shape
from cs231n.classifiers.neural_net import TwoLayerNet
input_dim = X_train_feats.shape[1]
hidden_dim = 500
num_classes = 10
net = TwoLayerNet(input_dim, hidden_dim, num_classes)
best_net = None
################################################################################
# TODO: Train a two-layer neural network on image features. You may want to #
# cross-validate various parameters as in previous sections. Store your best #
# model in the best_net variable. #
################################################################################
best_val = -1
best_stats = None
learning_rates = np.logspace(-10, 0, 5) # np.logspace(-10, 10, 8) #-10, -9, -8, -7, -6, -5, -4
regularization_strengths = np.logspace(-3, 5, 5) # causes numeric issues: np.logspace(-5, 5, 8) #[-4, -3, -2, -1, 1, 2, 3, 4, 5, 6]
results = {}
iters = 2000 #100
for lr in learning_rates:
for rs in regularization_strengths:
net = TwoLayerNet(input_dim, hidden_dim, num_classes)
# Train the network
stats = net.train(X_train_feats, y_train, X_val_feats, y_val,
num_iters=iters, batch_size=200,
learning_rate=lr, learning_rate_decay=0.95,
reg=rs)
y_train_pred = net.predict(X_train_feats)
acc_train = np.mean(y_train == y_train_pred)
y_val_pred = net.predict(X_val_feats)
acc_val = np.mean(y_val == y_val_pred)
results[(lr, rs)] = (acc_train, acc_val)
if best_val < acc_val:
best_stats = stats
best_val = acc_val
best_net = net
# Print out results.
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print 'lr %e reg %e train accuracy: %f val accuracy: %f' % (
lr, reg, train_accuracy, val_accuracy)
print 'best validation accuracy achieved during cross-validation: %f' % best_val
################################################################################
# END OF YOUR CODE #
################################################################################
# Run your neural net classifier on the test set. You should be able to
# get more than 55% accuracy.
test_acc = (best_net.predict(X_test_feats) == y_test).mean()
print test_acc
# Plot the loss function and train / validation accuracies
plt.subplot(2, 1, 1)
plt.plot(best_stats['loss_history'])
plt.title('Loss history')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.subplot(2, 1, 2)
plt.plot(best_stats['train_acc_history'], label='train')
plt.plot(best_stats['val_acc_history'], label='val')
plt.title('Classification accuracy history')
plt.xlabel('Epoch')
plt.ylabel('Clasification accuracy')
plt.show()
Explanation: Inline question 1:
Describe the misclassification results that you see. Do they make sense?
Neural Network on image features
Earlier in this assigment we saw that training a two-layer neural network on raw pixels achieved better classification performance than linear classifiers on raw pixels. In this notebook we have seen that linear classifiers on image features outperform linear classifiers on raw pixels.
For completeness, we should also try training a neural network on image features. This approach should outperform all previous approaches: you should easily be able to achieve over 55% classification accuracy on the test set; our best model achieves about 60% classification accuracy.
End of explanation |
8,545 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
Challenge Problems
1. Spinodal Decomposition - Cahn-Hilliard
1.1 Parameter Values
1.2 Initial Conditions
1.3 Domains
1.a Square Periodic
1.b No Flux
1.c T-Shape No Flux
1.d Sphere
1.4 Tasks
2. Ostwald Ripening -- coupled Cahn-Hilliard and Allen-Cahn equations
2.1 Parameter Values
2.2 Initial Conditions
2.3 Domains
2.a Square Periodic
2.b No Flux
2.c T-Shape No Flux
2.d Sphere
2.4 Tasks
Challenge Problems
For the first hackathon there are two challenge problems, a spinodal decomposition problem and an Ostwald ripening problem. The only solutions included here currently are with FiPy.
1. Spinodal Decomposition - Cahn-Hilliard
The free energy density is given by,
$$ f = f_0 \left[ c \left( \vec{r} \right) \right] + \frac{\kappa}{2} \left| \nabla c \left( \vec{r} \right) \right|^2 $$
where $f_0$ is the bulk free energy density given by,
$$ f_0\left[ c \left( \vec{r} \right) \right] =
- \frac{A}{2} \left(c - c_m\right)^2
+ \frac{B}{4} \left(c - c_m\right)^4
+ \frac{c_{\alpha}}{4} \left(c - c_{\alpha} \right)^4
+ \frac{c_{\beta}}{4} \left(c - c_{\beta} \right)^4 $$
where $c_m = \frac{1}{2} \left( c_{\alpha} + c_{\beta} \right)$ and $c_{\alpha}$ and $c_{\beta}$ are the concentrations at which the bulk free energy density has minima (corresponding to the solubilities in the matrix phase and the second phase, respectively).
The time evolution of the concentration field, $c$, is given by the Cahn-Hilliard equation
Step1: 1.b No Flux
2D square domain with $L_x = L_y = 200$ and zero flux boundary conditions.
1.c T-Shape No Flux
T-shaped reiong with zero flux boundary conditions with $a=b=100$ and $c=d=20.$
Step2: 1.d Sphere
Domain is the surface of a sphere with radius 100, but with initial conditions of
$$ c\left(\theta, \phi, 0\right) = \bar{c}_0 + \epsilon \cos \left( \sqrt{233} \theta \right)
\sin \left( \sqrt{239} \phi \right) $$
where $\theta$ and $\phi$ are the polar and azimuthal angles in a spherical coordinate system. $\bar{c}_0$ and $\epsilon$ are given by the values in the table above.
1.4 Tasks
Your task for each domain,
Calculate the time evolution of the concentration -- store concentration at time steps to make a movie
Plot the free energy as a function of time steps until you judge that convergence or a local equilibrium has been reached.
Present wall clock time for the calculations, and wall clock time per core used in the calculation.
For domain a. above, demonstrate that the solution is robust with respect to meshing by refining the mesh (e.g. reduce the mesh size by about a factor of $\sqrt{2}$ in linear dimensions -- use whatever convenient way you have to refine the mesh without exploding the computational time).
2. Ostwald Ripening -- coupled Cahn-Hilliard and Allen-Cahn equations
Expanded problem in that the phase field, described by variables $\eta_i$, is now coupled to the concentration field $c$. The Ginzberg-Landau free energy density is now taken to be,
$$ f = f_0 \left[ C \left( \vec{r} \right), \eta_1, ... , \eta_p \right]
+ \frac{\kappa_C}{2} \left[ \nabla C \left( \vec{r} \right) \right]^2 +
\sum_{i=1}^p \frac{\kappa_C}{2} \left[ \nabla \eta_i \left( \vec{r} \right) \right]^2
$$
Here, $f_0$ is a bulk free energy density,
$$ f_0 \left[ C \left( \vec{r} \right), \eta_1, ... , \eta_p \right]
= f_1 \left( C \right) + \sum_{i=1}^p f_2 \left( C, \eta_i \right)
+ \sum_{i=1}^p \sum_{j\ne i}^p f_3 \left( \eta_j, \eta_i \right) $$
Here, $ f_1 \left( C \right) $ is the free energy density due to the concentration field, $C$, with local minima at $C_{\alpha}$ and $C_{\beta}$ corresponding to the solubilities in the matrix phase and the second phase, respectively; $f_2\left(C , \eta_i \right)$ is an interaction term between the concentration field and the phase fields, and $f_3 \left( \eta_i, \eta_j \right)$ is the free energy density of the phase fields. Simple models for these free energy densities are,
$$ f_1\left( C \right) =
- \frac{A}{2} \left(C - C_m\right)^2
+ \frac{B}{4} \left(C - C_m\right)^4
+ \frac{D_{\alpha}}{4} \left(C - C_{\alpha} \right)^4
+ \frac{D_{\beta}}{4} \left(C - C_{\beta} \right)^4 $$
where
$$ C_m = \frac{1}{2} \left(C_{\alpha} + C_{\beta} \right) $$
and
$$ f_2 \left( C, \eta_i \right) = - \frac{\gamma}{2} \left( C - C_{\alpha} \right)^2 \eta_i^2 + \frac{\beta}{2} \eta_i^4 $$
where
$$ f_3 \left( \eta_i, \eta_j \right) = \frac{ \epsilon_{ij} }{2} \eta_i^2 \eta_j^2, i \ne j $$
The time evolution of the system is now given by coupled Cahn-Hilliard and Allen-Cahn (time dependent Gizberg-Landau) equations for the conserved concentration field and the non-conserved phase fields
Step3: 2.b No Flux
2D square domain with $L_x = L_y = 200$ and zero flux boundary conditions.
2.c T-Shape No Flux
T-shaped reiong with zero flux boundary conditions with $a=b=100$ and $c=d=20.$ | Python Code:
from IPython.display import SVG
SVG(filename='../images/block1.svg')
Explanation: Table of Contents
Challenge Problems
1. Spinodal Decomposition - Cahn-Hilliard
1.1 Parameter Values
1.2 Initial Conditions
1.3 Domains
1.a Square Periodic
1.b No Flux
1.c T-Shape No Flux
1.d Sphere
1.4 Tasks
2. Ostwald Ripening -- coupled Cahn-Hilliard and Allen-Cahn equations
2.1 Parameter Values
2.2 Initial Conditions
2.3 Domains
2.a Square Periodic
2.b No Flux
2.c T-Shape No Flux
2.d Sphere
2.4 Tasks
Challenge Problems
For the first hackathon there are two challenge problems, a spinodal decomposition problem and an Ostwald ripening problem. The only solutions included here currently are with FiPy.
1. Spinodal Decomposition - Cahn-Hilliard
The free energy density is given by,
$$ f = f_0 \left[ c \left( \vec{r} \right) \right] + \frac{\kappa}{2} \left| \nabla c \left( \vec{r} \right) \right|^2 $$
where $f_0$ is the bulk free energy density given by,
$$ f_0\left[ c \left( \vec{r} \right) \right] =
- \frac{A}{2} \left(c - c_m\right)^2
+ \frac{B}{4} \left(c - c_m\right)^4
+ \frac{c_{\alpha}}{4} \left(c - c_{\alpha} \right)^4
+ \frac{c_{\beta}}{4} \left(c - c_{\beta} \right)^4 $$
where $c_m = \frac{1}{2} \left( c_{\alpha} + c_{\beta} \right)$ and $c_{\alpha}$ and $c_{\beta}$ are the concentrations at which the bulk free energy density has minima (corresponding to the solubilities in the matrix phase and the second phase, respectively).
The time evolution of the concentration field, $c$, is given by the Cahn-Hilliard equation:
$$ \frac{\partial c}{\partial t} = \nabla \cdot \left[
D \left( c \right) \nabla \left( \frac{ \partial f_0 }{ \partial c} - \kappa \nabla^2 c \right)
\right] $$
where $D$ is the diffusivity.
1.1 Parameter Values
Use the following parameter values.
<table width="200">
<tr>
<td> $c_{\alpha}$ </td>
<td> 0.05 </td>
</tr>
<tr>
<td> $c_{\beta}$ </td>
<td> 0.95 </td>
</tr>
<tr>
<td> A </td>
<td> 2.0 </td>
</tr>
<tr>
<td> $\kappa$ </td>
<td> 2.0 </td>
</tr>
</table>
with
$$ B = \frac{A}{\left( c_{\alpha} - c_m \right)^2} $$
$$ D = D_{\alpha} = D_{\beta} = \frac{2}{c_{\beta} - c_{\alpha}} $$
1.2 Initial Conditions
Set $c\left(\vec{r}, t\right)$ such that
$$ c\left(\vec{r}, 0\right) = \bar{c}_0 + \epsilon \cos \left( \vec{q} \cdot \vec{r} \right) $$
where
<table width="200">
<tr>
<td> $\bar{c}_0$ </td>
<td> 0.45 </td>
</tr>
<tr>
<td> $\vec{q}$ </td>
<td> $\left(\sqrt{2},\sqrt{3}\right)$ </td>
</tr>
<tr>
<td> $\epsilon$ </td>
<td> 0.01 </td>
</tr>
</table>
1.3 Domains
1.a Square Periodic
2D square domain with $L_x = L_y = 200$ and periodic boundary conditions.
End of explanation
from IPython.display import SVG
SVG(filename='../images/t-shape.svg')
Explanation: 1.b No Flux
2D square domain with $L_x = L_y = 200$ and zero flux boundary conditions.
1.c T-Shape No Flux
T-shaped reiong with zero flux boundary conditions with $a=b=100$ and $c=d=20.$
End of explanation
from IPython.display import SVG
SVG(filename='../images/block1.svg')
Explanation: 1.d Sphere
Domain is the surface of a sphere with radius 100, but with initial conditions of
$$ c\left(\theta, \phi, 0\right) = \bar{c}_0 + \epsilon \cos \left( \sqrt{233} \theta \right)
\sin \left( \sqrt{239} \phi \right) $$
where $\theta$ and $\phi$ are the polar and azimuthal angles in a spherical coordinate system. $\bar{c}_0$ and $\epsilon$ are given by the values in the table above.
1.4 Tasks
Your task for each domain,
Calculate the time evolution of the concentration -- store concentration at time steps to make a movie
Plot the free energy as a function of time steps until you judge that convergence or a local equilibrium has been reached.
Present wall clock time for the calculations, and wall clock time per core used in the calculation.
For domain a. above, demonstrate that the solution is robust with respect to meshing by refining the mesh (e.g. reduce the mesh size by about a factor of $\sqrt{2}$ in linear dimensions -- use whatever convenient way you have to refine the mesh without exploding the computational time).
2. Ostwald Ripening -- coupled Cahn-Hilliard and Allen-Cahn equations
Expanded problem in that the phase field, described by variables $\eta_i$, is now coupled to the concentration field $c$. The Ginzberg-Landau free energy density is now taken to be,
$$ f = f_0 \left[ C \left( \vec{r} \right), \eta_1, ... , \eta_p \right]
+ \frac{\kappa_C}{2} \left[ \nabla C \left( \vec{r} \right) \right]^2 +
\sum_{i=1}^p \frac{\kappa_C}{2} \left[ \nabla \eta_i \left( \vec{r} \right) \right]^2
$$
Here, $f_0$ is a bulk free energy density,
$$ f_0 \left[ C \left( \vec{r} \right), \eta_1, ... , \eta_p \right]
= f_1 \left( C \right) + \sum_{i=1}^p f_2 \left( C, \eta_i \right)
+ \sum_{i=1}^p \sum_{j\ne i}^p f_3 \left( \eta_j, \eta_i \right) $$
Here, $ f_1 \left( C \right) $ is the free energy density due to the concentration field, $C$, with local minima at $C_{\alpha}$ and $C_{\beta}$ corresponding to the solubilities in the matrix phase and the second phase, respectively; $f_2\left(C , \eta_i \right)$ is an interaction term between the concentration field and the phase fields, and $f_3 \left( \eta_i, \eta_j \right)$ is the free energy density of the phase fields. Simple models for these free energy densities are,
$$ f_1\left( C \right) =
- \frac{A}{2} \left(C - C_m\right)^2
+ \frac{B}{4} \left(C - C_m\right)^4
+ \frac{D_{\alpha}}{4} \left(C - C_{\alpha} \right)^4
+ \frac{D_{\beta}}{4} \left(C - C_{\beta} \right)^4 $$
where
$$ C_m = \frac{1}{2} \left(C_{\alpha} + C_{\beta} \right) $$
and
$$ f_2 \left( C, \eta_i \right) = - \frac{\gamma}{2} \left( C - C_{\alpha} \right)^2 \eta_i^2 + \frac{\beta}{2} \eta_i^4 $$
where
$$ f_3 \left( \eta_i, \eta_j \right) = \frac{ \epsilon_{ij} }{2} \eta_i^2 \eta_j^2, i \ne j $$
The time evolution of the system is now given by coupled Cahn-Hilliard and Allen-Cahn (time dependent Gizberg-Landau) equations for the conserved concentration field and the non-conserved phase fields:
$$
\begin{eqnarray}
\frac{\partial C}{\partial t} &=& \nabla \cdot \left {
D \nabla \left[ \frac{\delta F}{\delta C} \right] \right } \
&=& D \left[ -A + 3 B \left( C- C_m \right)^2 + 3 D_{\alpha} \left( C - C_{\alpha} \right)^2 + 3 D_{\beta} \left( C - C_{\beta} \right)^2 \right] \nabla^2 C \
& & -D \gamma \sum_{i=1}^{p} \left[ \eta_i^2 \nabla^2 C + 4 \nabla C \cdot \nabla \eta_i + 2 \left( C - C_{\alpha} \right) \nabla^2 \eta_i \right] - D \kappa_C \nabla^4 C
\end{eqnarray}
$$
and the phase field equations
$$
\begin{eqnarray}
\frac{\partial \eta_i}{\partial t} &=& - L_i \frac{\delta F}{\delta \eta_i} \
&=& \frac{\partial f_2}{\delta \eta_i} + \frac{\partial f_3}{\delta \eta_i} - \kappa_i \nabla^2 \eta_i \left(\vec{r}, t\right) \
&=& L_i \gamma \left( C - C_{\alpha} \right)^2 \eta_i - L_i \beta \eta_i^3 - L_i \eta_i \sum_{j\ne i}^{p} \epsilon_{ij} \eta^2_j + L_i \kappa_i \nabla^2 \eta_i
\end{eqnarray}
$$
2.1 Parameter Values
Use the following parameter values.
<table width="200">
<tr>
<td> $C_{\alpha}$ </td>
<td> 0.05 </td>
</tr>
<tr>
<td> $C_{\beta}$ </td>
<td> 0.95 </td>
</tr>
<tr>
<td> A </td>
<td> 2.0 </td>
</tr>
<tr>
<td> $\kappa_i$ </td>
<td> 2.0 </td>
</tr>
<tr>
<td> $\kappa_j$ </td>
<td> 2.0 </td>
</tr>
<tr>
<td> $\kappa_k$ </td>
<td> 2.0 </td>
</tr>
<tr>
<td> $\epsilon_{ij}$ </td>
<td> 3.0 </td>
</tr>
<tr>
<td> $\beta$ </td>
<td> 1.0 </td>
</tr>
<tr>
<td> $p$ </td>
<td> 10 </td>
</tr>
</table>
with
$$ B = \frac{A}{\left( C_{\alpha} - C_m \right)^2} $$
$$ \gamma = \frac{2}{\left(C_{\beta} - C_{\alpha}\right)^2} $$
$$ D = D_{\alpha} = D_{\beta} = \frac{\gamma}{\delta^2} $$
The diffusion coefficient, $D$, is constant and isotropic and the same (unity) for both phases; the mobility-related constants, $L_i$, are the same (unity) for all phase fields.
2.2 Initial Conditions
Set $c\left(\vec{r}, t\right)$ such that
$$
\begin{eqnarray}
c\left(\vec{r}, 0\right) &=& \bar{c}_0 + \epsilon \cos \left( \vec{q} \cdot \vec{r} \right) \
\eta_i\left(\vec{r}, 0\right) &=& \bar{\eta}_0 + 0.01 \epsilon_i \cos^2 \left( \vec{q} \cdot \vec{r} \right)
\end{eqnarray}
$$
where
<table width="200">
<tr>
<td> $\bar{c}_0$ </td>
<td> 0.5 </td>
</tr>
<tr>
<td> $\vec{q}$ </td>
<td> $\left(\sqrt{2},\sqrt{3}\right)$ </td>
</tr>
<tr>
<td> $\epsilon$ </td>
<td> 0.01 </td>
</tr>
<tr>
<td> $\vec{q}_i$ </td>
<td> $\left( \sqrt{23 + i}, \sqrt{149 + i} \right)$ </td>
</tr>
<tr>
<td> $\epsilon_i$ </td>
<td> 0.979285, 0.219812, 0.837709, 0.695603, 0.225115,
0.389266, 0.585953, 0.614471, 0.918038, 0.518569 </td>
</tr>
<tr>
<td> $\eta_0$ </td>
<td> 0.0 </td>
</tr>
</table>
2.3 Domains
2.a Square Periodic
2D square domain with $L_x = L_y = 200$ and periodic boundary conditions.
End of explanation
from IPython.display import SVG
SVG(filename='../images/t-shape.svg')
Explanation: 2.b No Flux
2D square domain with $L_x = L_y = 200$ and zero flux boundary conditions.
2.c T-Shape No Flux
T-shaped reiong with zero flux boundary conditions with $a=b=100$ and $c=d=20.$
End of explanation |
8,546 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
The purpose of this product is to classify population depending on their uses of their phone and phone brands. This classification is the first step to tailor advertising campaigns by third parties based on the usage of the mobile according to the age and gender of the population. For this we have a sample of the population using Mobile Talk data in China. Although this product has been developed for the Chinese population, it can be used globally as further research has shown that other mobile operators in other countries have access to the same type of data.
In this case the groups have been preset based on gender and age range that are specifically important for the client of Mobile Talk. This groups can be tailored to the needs of the advertising company depending on the information that the mobile operator is willing to share with the final client or that wants to use to tailor its own offering.
From the data extracted we are going to get the main features that will be used to classify the population according to their demographics. For this we are going to focus on the apps they use and the device brand. The steps that will be followed to develop this product are
Step1: 2. Dataset Creation
The first objective is to create a dataset that unifies the different files that have been uploaded into the notebook. For this there will be a set of merging actions based on the information provided that will be combined with cleaning actions to avoid oversizing the final dataset prior to the features generation.
To merge this information the hypothesis around the potential features that can explain the demographics of the users for further classification has been used
Step2: The dataset stands as follows. There are more than 2.8 million entries being all the values of the cells integers
Step3: The devices ids are now linked to the applabels so that it contains the information about the different categories of the apps is included. In this case the 20 digit identifier of the app is substituted by a category that identifies the kind of app that is active in each device.
Step4: The new dataset is cleansed removing the empty values and changing the type of variable so that they can be merged afterwards without increasing disproportionately the number of rows.
Step5: Information is retrieved about the size and type of the variables in the dataset. The dataset is now ready to be merged.
Step6: The dataset containing data about the usage of the apps, the activity, device id is linked with the dataset containing the device id and information about the gender, age and age group. The age groups used are the ones provided in the dataset and have not been changed.
There are 12 groups that differentiate the age and gender. The groups roughly split the population in even groups and the distribution of data points for each group is shown in the following graph.
Step7: Information about the new datasets is retrieved to see the type of variables and to clean the data eliminating any missing cell.
Step8: Further cleansing is done dropping the empty cells and resetting the index to have a better view of the data points available.
Step9: In the Chinese market the number of apps that is actually used from the ones installed in the devices equate to roughly 50%.
Step10: Visual inspection of the distribution of data between ages show that the data is skewed to the right, showing that most of the data represents the age group between 20 and 35 years old. This corresponds to the grouping that has been done age-wise.
Step11: Each group contains 20 apps in total. From an apps usage standpoint, the most important group of apps according to its usage corresponds to financial, lottery and gaming apps followed by apps related to smart appliances and wearables in second place. The third place is taken by the apps used for banking and payment services. On the lower end the apps that show a smaller usage are the leisure related ones like photography, wedding planners or trips abroad. This apps equate to 90 and are presenting a lower usage due to its characteristics and the sample taste.
Step12: Dummy variables are created based on the apps that are installed on the devices. In this case 484 additional columns are created with categorical data that counts the appearance of each app category in the device. To avoid the dummy variable trap whereby collinearity exists between the variables one redundant category is dropped when transforming the categorical variables into dummies.
Step13: Before adding the data about the phone brands and models, a dictionary has been taken from Kaggle and augmented with additional brands to translate the brands from Chinese to English. Additionally, those brands that have no translation have been designed with “UBXX” where UB stands for unknown brand and XX are two digits. This has been done to easy queries on the dataframe and visualizations of the dataset. The translation of the brands form Chinese to English has been included in the phone dataset and dummy variables have been created for each brand. This gives as a result a sparse data frame with zero if the device is not of that brand and 1 when the device is associated to a certain brand.
Step14: The phone brands dataset has been added to the previous dataset containing all the information about apps, age, gender, etc. In the instances in which the device id does not appear the NaN results have been filled in with zeros. The devices that are duplicate have been deleted to make the dataset manageable from a computing perspective reducing from two million rows to 23k data rows. The device id and device model columns have been dropped as in further research they were not adding information for the feature generation. Additionally, a dummy variable has been created for the variable gender.
Step15: As it is shown in the graph below, eight brands represent 90% of the sample in the Chinese market.
Step16: To avoid the dummy variable trap whereby collinearity exists between the variables one redundant category is dropped when transforming the categorical variables into dummies.
Step17: The new dataset has been cleansed eliminating all the columns that are zeros. In this case, 345 columns have been deleted related to brands that were not associated to devices. The output variable that groups gender and age “group” has been transformed into numbers so that supervised algorithms are used for prediction.
Step18: The gender split in the data is not even, being more male than women in the customer base of the company. This has an impact in the further segmentation by age (including gender) expecting groups that have a lower number of data points in the case it is for women. A visual inspection of the groups show that the groups are unbalanced. This will impact the accuracy of the models for classification purposes. Further resampling is required and in this case, up-sampling will be considered using the number of samples in the largest group
Step19: As the different groups are not balanced, the minority groups are balanced resampling the data and up-sampling the minority groups. This will allow the different algorithms to achieve a better accuracy in general. Algorithms like random forest are highly sensitive to unbalanced groups in the output variable.
Step20: As part of the data cleansing actions, the device id column has been dropped and dummy variables have been created for the gender variable additionally all those columns that are constant and filled in only with zeros have been dropped. To avoid the dummy variable trap whereby collinearity exists between the variables one redundant category is dropped when transforming the categorical variables into dummies. The different groups have been mapped to 0-11 to be used in further modelling. In this case although different trials have taken place, after improving the significance of the features the twelve groups for the classification problem have been kept.
Step21: As it can be appreciated the average age of the users is 31 years with a standard deviation of nearly 10 years. The interquartile age is between 26 and 37 years. For each of the labels and brands it can be seen that all the ones included appear at least once as it was expected from the data wrangling actions. Although group appears in the table, the results obtained means that the group M23-26 grouping male between 23 and 26 is the most significant one in terms of appearance.
Step22: The dataset has been split between the predictors and the output variable. As abovementioned, the output variable is the group of age and gender and the input variables are the features created based on the app labels, gender and phone brand used by the users. To improve the quality of the features the data has been preprocessed and scaled.
Step23: The size of the final dataset is 274 variables and 40k rows of data from which features will be generated.
Step24: To have a better understanding of the correlation between variables, and due to the large amount of variables in this dataset, a correlation matrix has been created. To check the level of correlation between variables, only those with a correlation greater than 0.5 and lower than 1 (in absolute terms) have been printed.
Step25: As it can be observed only the pone brand "OPPO" and the app label 706 present the highest correlation equal to 0.42. Further inspection shows that this brand includes a "customized" app in all the phones to access special features. As expected there is no negative correlation higher than 0.4 (in absolute terms) due to the characteristics of the data. There are no apps that cannot be installed in certain phone brands or that decrease when the number of phones of that brand increases.
The dataset has been split into predictors and target variable and the dataset split into a train and test data set (70/30) defining five folds for cross validation. This train test split will be used for the feature generation steps and as part of the unsupervised exploratory data analysis.
Step26: 3. Feature Generation
The feature selection process will start with a PCA analysis to understand the number of features required to describe more than 90% of the variance of the outcome variable. Once the number of features is identified, the following methods will be used to select the features that will be used to run build the binary classifier
Step27: Due to the characteristics of the variables the use of all the features create a lot of noise and when the supervised models are run, there is overfitting in all cases. Hence, the number of variables is reduced using Kbest using only those that have an explanatory power higher than 1. A dataframe is created with this new set of features.
Step28: To select the features, Feature Importance using Random Forest is used. In this case the result given by the random forest feature selection is not meaningful therefore the result given by kbest() will be used as a first step before running PCA for generating the new set of features. From the random forest feature selection it can be observed that the number of features has to be reduced significantly as there are a lot of features that are adding noise and with low explanatory power.
Step29: The feature selection using Radnom forest shows the high contribution of age, gender and certain brands over the apps ids. It cn be seen that all of them have a contribution and after running iteratively on the 16 best features selected by Random Forest the accuracy obtained with Logistic Regression was very low. Once features from kbest were added to the feature space accuracy results improved. Hence the features obtained using kbest() will be the ones that will be transformed using PCA. As a second step, the variables selected by Kbest are transformed using PCA analysis. For this, the correlation matrix of the new set of variables is created and non existing values are filled in with zeros.
Step30: Calculate the eigen-values and vectors and determine the explained variance by each component.
Step31: From the PCA analysis abovementioned the PCA features are created. After analysing the feature generation using recursive feature analysis and feature selection using kbest(), the PCA features will be used. Additionally, there is no need to have the initial features as predictors or now which ones have been used as the main purpose of the classification process is to maximize the accuracy.
Step32: 4. Model Selection
The dataset is split 70/30 train test and several models will be tuned in the training set and run on the test set calculating their accuracy using cross validation. The purpose of this is to train and test the classification models avoiding overfitting, exposing the algorithms to unknown data in the test set. The cross validation will be done using five folds, in this case and as data has been resampled the representation of each class is even across folds avoiding the need to stratify the data, although its use would reduce the bias and variance effects if classes were not evenly distributed in the dataset.
Step33: All models' hyperparameters will be tuned in the training set using cross validation and gridsearch tuning several parameters considered in the pipeline (gridsearch). Except for specific cases that will be discussed one by one, the algorithm or variations (solver, etc) to be used has been decided in advance considering the topology of the dataset.
The models that have been selected to be tested on the dataset to accurately classify the data are
Step34: The tuned model is fit and run on the test set and the computational effort is measured considering the time required to fit the test set.
Step35: The model requires 3.3 min to run which will be used as a time threshold to measure the computational effort of other models. To calculate the accuracy the model is evaluated on the test set. From the classification report it can be seen that the data representing each class is evenly distributed across the classes. This reduces the probability of bias of the model when calculating the probabilities of each predicted value.
Step36: The overall accuracy of the Logistic Regression model is 95.62%. Although the overall accuracy is good and the computational effort low, the classification report and confusion matrix show overfitting as there will be some data points misclassified. The high accuracy of the model can be explained by the lack of correlation between the predictors (independent variables). Only two variables out of 120 presented a correlation of 0.5 (max correlation value in the dataset) which have been eliminated when during the feature generation process and through PCA. The PCA components are all independent from each other and by definition there is no collinearity between the 120 components that have been chosen. Additionally linearity between the independent variable and the log odds exists. Furthermore, the dataset is big enough to use this classification algorithm.
4.2 Naive Bayes
From the Naïve Bayes models the Bernoulli algorithm has been implemented because Bernoulli model can be trained using less data and be less prone to overfitting. The hyperparameter to be tuned is "alpha".
Step37: The value for "alpha" is the smallest of the values chosen to tune the parameters of the model. In this case the gridsearch has been carried out with values ranging from 0.001 to 10 before fitting the above set. In all cases, 10 was the value that was appearing as the best one in terms of overall accuracy. The tuned model is fit and run on the test set and the computational effort is measured considering the time required to fit the test set.
Step38: Once the algorithm is trained it is run on the test set. The maximum precision obtained is 70% for the first class being all of the rest lower than 50%. From an accuracy perspective this algorithm doesn't seem to be a good candidate for our product. Cross validation has been performed to avoid overfitting
Step39: In this case the low accuracy of the Naïve-Bayes classifier can be explained because of the continuous structure of the data once the scaler and PCA has been applied. Although the features are strongly independent due to the PCA transformation of them, this classifier is good when it is used for binary problems with two classes. In this case, the existence of 12 different classes makes it harder for this algorithm to classify accurately.
4.3 K-nearest neighbors
A K-Neighbors model has been implemented and tuned on the train set. The parameters tuned are
Step40: The value for "n_neighbors" is the smallest of the values chosen to tune the parameters of the model. In this case the gridsearch has been carried out with values ranging from 3 to 11, always odd as the number of classes is even before fitting the above set. In all cases, 5 was the value that was appearing as the best one in terms of overall accuracy. The algorithm to be used has been set to "auto" and the algorithm used is "brute force" in this case as k < n_samples/2 and no specific metrics have been given. In this case the leaf size has been set to the default value of 30 considering the number of features used. The choice fo distance as the weight instead of uniform is reasonable were the points are weighted by the inverse of their distance. In this case features are different from each other ranging from different types of apps to device brands. The tuned model is fit and run on the test set and the computational effort is measured considering the time required to fit the test set.
Step41: In this case, due to the characteristics of the algorithm (lazy algorithm) all the work is done in the previous step as the prediction is required. This algorithm goes through all the dataset comparing each data point with the instances that it has previously seen while it was trained. This could be the reason why this step requires some more time than the previous and next ones (1.1 min per fold).
From the requirements to achieve good accuracy only two out of the three have been fulfilled, hence not a very high accuracy is expected. Data has been scaled and missing values have been addressed but the dimensionality of the problem is very large. In this case the dimensionality is 120 and the Euclidean distance does not perform well with high dimensions as points that may be similar may have very large distances.
As it can be seen the confusion matrix and the classification report are not adding value from an information perspective as it appears to have no misclassification. In this case, there is overfitting that is corrected through cross validation
Step42: As it was expected the accuracy obtained for this problem with this algorithm is lower than the values that are normally obtained with lower dimensionalities. As previously discussed this has to do with the fact that the Euclidean distance doesn´t perform accurately with high dimensionality problems and that it is used to measure the weight of each vote through the inverse of its value.
4.4 SGD Classifier
The SGD Classifier uses regularized linear models with stochastic gradient descendent learning. The model is updated in its learning rate after the gradient of the loss is estaimated for each sample. This classifier can work with sparse data as the one obtained from building up the features when working with categorical ones. In this case from the types of penalties the algorithm accepts, it uses L2 instead of a combination of L1 and L2 implemented through Elastic Net.
Step43: The parameters show that the smoothing continues to be loose as a first option as it is a regression with a gradient descendent algorithm. Regarding the loss, the hinge loss is used which means that the real loss, in case it is not convergent due to the sparse data used, is replaced by the upper bond forcing its convergence. Time required is significantly higher than with previous classifiers.
Step44: From a visual inspection of the classification report it can be observed how the lack of clear boundaries between data points is impacting the overall accuracy. Only in the case of group 6 the precision is over 90%, for the rest of them the maximum precision obtained is at a maximum of 60%. This will show up when the results are cross validated giving low accuracies.
Step45: As the features describing each group are scattered not having clear boundaries between each group, the result obtained from the SGD algorithm is low and it is not expected to grow with a higher number of iterations. In this case and using square hinge the decision boundary will not be able to improve the misclassification of the different points. In any case, the accuracy is too low to be used 47.88%. Although the SGD solves the same classification problems than the logistic regression and can be more efficient in this case the improvement from a computing effort perspective does not compensate the low results obtained by the classifier.
4.5 Random Forest
The hyperparamters of the random forest model will be tuned. The parameters to be tuned are (in the same order as the hyperparameter tuning has been performed)
Step46: The number of trees used is 170 being the depth of each tree 31. After several simulations, the parameters have stayed stable around these values. The random forest algorithm is an ensemble algorithm that works bringing together different decision trees and being more powerful than an individual decision tree. In this case it introduces randomness because it choses from a random sample of features the one that is decreasing how often a randomly chosen element will be incorrectly labelled using gini criterion. The high number of estimators ensure the accuracy of the model while it increases the computational effort required. In this case, it is important to have the classes balanced as in one of the 31 nodes it could happen that one of the minority classes disappear. From the random forest feature selection only "is active", "gender" and "age" add have significant explanatory power being the rest of the features noise to the model. The noise has been reduced by reducing the number ofo features and applying PCA to the model to gain in the explanatory power of the variance. The number of trees in the random forest classifier decreases the risk of overfitting while the number of nodes "depth" reduces the samples available and features available in each sample which can increase the risk of misclassification reducing the overall accuracy. Moreover "deep" trees can compensate the lower risk of overfitting by increasing the number of trees as it increases the probability of overfitting overall.
Once the parameters are tuned, the model is fit and run on the test set. As it can be seen from the hyperparameter tuning, the model requires much more time (computational effort) than the previous models. The increase in accuracy must justify the significant increase of time required to fit the model.
Step47: There is a significant increase in the computational effort required by this algorithm as it was expected. The classification report and the classification matrix present overfitting as the precision in all cases is one and there are no misclassified elements. To avoid this overfitting problem, cross validation has been performed on the random forest.
Step48: In this case, the overall accuracy of the model is 81.04% which is somehow low for this type of algorithms. In this case and after running the random forest feature selection this might have happened due to the additional features that are increasing the noise instead of adding information to the algorithm based on this feature selection process. As there are only four, when run in a set of trees of 31 nodes, it can happen that none of them remains until the end misclassifying results based on the remaining features that the algorithm picks randomly.
4.6 Linear Support Vector Machine
A linear support vector classifier has been set up and tuned on the training data and run on the test set. The hyperparameters that have been tuned are
Step49: Although the Linear SVC has been implemented as it is more scalable than the support vector classifier, the time required to fit the values compared to the other algorithms makes it a weak candidate to go into production. Compared to the logistic regression classifier there must be a significant increase so that this classifier worth it in terms of computational effort. C has been tuned to 100 to control the misclassification that is allowed by this classifier. The tradeoff between the values of this parameter is the bias-variance trade off. If the parameter is low the classifier will allow small numbers of misclassification having a low bias but allowing a high variance. In our case, the parameter is high which is better from a scaling perspective but might have a high amount of bias under fitting the data in the classification problem. Hinge loss has been selected as the loss function to calculate the weights of the misclassifications on the training data and apply them to the test data.
Step50: Although the computational effort required when fitting the dataset is lower than initially expected, the accuracy is higher than in the case of the random forest and very close to the logistic regression classifier. The classification report and the classification matrix present overfitting as the precision in all cases is one and there are no misclassified elements. To avoid this overfitting problem, cross validation has been performed on the random forest.
Step51: In this case the support vector classifier uses a linear kernel for the kernel trick and a sparse representation of data (aligned to the features that have been generated for this problem) reducing the amount of computing effort required. In this case, there is a need to create linear hyperplanes that is able to separate one class over the rest until the 12 have been classified. Due to the characteristics of the data (PCA components are used as features and are oriented to maximize the explanation of the variance across classes) added to the C parameter the accuracy of the Linear Support Vector Classifier is higher than expected requiring less computational effort than the initially foreseen.
4.7 Gradient Boosting Classifier
The hyperparamters of the gradient boosting classifier that are tuned are the same than in the case of the random forest. The parameters to be tuned are (in the same order as the hyperparameter tuning has been performed)
Step52: In this case, as it is a boosting model, the data is passed over and over again tuning the parameters every time the data is passed. This is the reason why compared to the random forest it requires so much time. The number of trees is higher than the number of trees used in random forest and the depth is nearly doubling the one previously calculated for the random forest. In this case the computational effort has grown exponentially compared to other classifiers so it is expected that the accuracy is much higher than in the case of the logistic regression classifier to be a candidate for production. In this case, as it is based on random forest a slight increase of its accuracy is expected, hence it will not be as high as the one achieved with the logistic regression for the same reasons that applied to the random forest.
Once the parameters are tuned, the model is fit and run on the test set.
Step53: In this case, the algorithm uses the gradient descendent algorithm to follow the steepest path that reduces the loss. In each step the tree is fitted to predict a negative gradient. The friedman_mse parameter used by default calculates the step after the direction has been set. As in the case of Random Forest, this classifier presents overfitting in the classification report and confusion matrix. To reduce the overfitting cross validation is applied.
Step54: The gradient boosting algorithm has a similar approach to the random forest in the classification of the classes. In this case the depth of the trees is bigger and the number of trees also. The number of trees helps to reduce the overfitting while the depth has a negative effect in the misclassification reducing the accuracy. The same principle regarding the feature selection applies than in the case of random forest so it is not strange to find in this case an overall accuracy close to the one obtained with random forest. In the implementation of the descendent gradient over the random forest algorithm has not significantly improved the accuracy while it has increased the computational effort required to achieve it. Hence, this algorithm is discarded for production.
4.8 Support Vector Classifier
A support vector classifier has been set up and tuned on the training data and run on the test set. The hyperparameters that have been tuned are
Step55: The time required to tune the parameters has been lower than expected especially for a dataset as large as ours. The use of a high C aims to classify the training examples correctly by selecting more samples as support vectors. In this case, the use of PC helps to set up the boundaries using data that has been preprocessed to explain the maximum possible variance by rotating it. The model is fit in the test set.
Step56: As expected, the confusion matrix and classification report present overfitting. To avoid the overfitting presented in both cases, cross validation is used to fit to obtain the overall accuracy.
Step57: In this case the accuracy obtained is 92.29% which is similar to the one obtained with the logistic regression model but it requires less computational effort. This is due to the transformation done when preprocessing the data with PCA as the kernel trick requires less time (the data is already in the axis that maximize the variance) than expected and therefore less computational power. This is a strong candidate to go into production if the PCA is maintained before the algorithm is run as otherwise the time will increase quadratic (as complexity).
This model will be compared the deep learning classification results although this model is preferred as it allows to keep the features (and requires less computational effort) which is better from the perspective of refining the feature generation in the future
4.9 Model Selection - Conclusions
Features have been generated once the dataset has been created using kbest and PCA. The number of features has been reduced to 120 to obtain the highest possible overall accuracy using cross validation over a 70/30 train/test split with five folds. In this case there is no additional weight on misclassification hence, the overall accuracy has been used to measure the accuracy of the models and the time required to fit the test data to measure the computing effort required by each model. The features that have been used are the PC from a PCA as we don´t need to track back to the initial features. The initial kbest analysis and the unsupervised analysis already determines the most important features that can be found in the data without needing to implement them when running the different models. All models have been tuned using gridsearch and the results from higher to lower accuracy are as follows
Step58: To match the input requirements of the neural network, the dependent variable is transformed into a categorical sparse matrix. This matrix will have the same number of rows but will create one row per class used in the dependent vector.
Step59: Although gridsearchCV from sklearn can be used to tune the parameters if the neural network in this case and due to computational restrictions, a trial and error approach has been selected. The process to build the model has been as follows.
Increase the number of layers and with it the batch size increasing the overall accuracy of the model
Increase the size of the hidden neural networks while increasing the dropout rate to reduce overfitting.
Increasing the size of each layer up to 264 increasing the number of trainable parameters which improved the accuracy of the model.
Try different activation functions such as "relu", "elu", "selu" being "relu" the preferred option from an accuracy standpoint is "relu" as it provides higher accuracy.
Introduce the batch normalization, normalizing the input of each neural layer are part of the model architecture and performing the normalization in each mini batch. Both accuracy and speed improve when the batch normalization is used.
Increase the epochs giving time for the neural network to be trained increasing them from 15 to 200 and achieving better results when 200 epochs are used.
Different optimizers have been used
Step60: After several trials the optimum batch size for the model and epochs are 1250 and 200 respectively. Once the model is trained on the train set is tested and an overall accuracy of 98.91% is achieved. This accuracy is higher than all the accuracies achieved with the previous models.
Step61: Although the accuracy obtained by this model is higher than the one achieved by any other model, the logistic regression and support vector machine models are the preferred ones as candidates for production. The neural network, although it gives a higher accuracy does not allow to distinguish the explanatory power of each of the features that are used. This is not required during image recognition but is necessary for the purpose of this exercise. Furthermore, the model is far more complex than the previous one and requires more computational power once it is in production. For all this reasons although the accuracy is higher than in the previous cases, the logistic regression and support vector machine models are still the best candidates for production.
6. Unsupervised Clustering
To have a better understanding of the potential clients and relationship between them unsupervised clustering will be carried out. In this case Affinity propagation, Meanshift, Spectral and Kmeans clustering will be compared and one technique will be chosen to cluster the customers and extract meaningful information for the marketing team. Once the clustering is selected, the number of clusters will be selected and the information will be extracted. As in the case of supervised learning the PCA components were used, in this case the dataset is built up to include the information that is going to be analyzed.
Step62: The dataset contains information that will not be normalized and that will be used afterwards such as gender, age and group (age range).
Step63: To work with the different clustering techniques a copy of the dataset will be done and the information will be normalized. This will improve the performance of the different clustering techniques.
Step64: A dataframe containing the information about the groups, age and gender is built and the groups are codified into integers. An independent variable is created containing this information to check the accuracy of the clustering technique that is selected.
Step65: Once the affinity propagation technique has been tested, the number of clusters is excessive for the data points available reason why this technique is discarded.
Step66: Once the affinity propagation technique is discarded, the meanshift technique is tested. In this case different bandwidths have been tested to see the kernel density surfaces that better suits the data. Higher bandwidths create a smoother kernel density surface, leading to fewer peaks because smaller hills are smoothed out, whereas lower bandwidths lead to a surface with more peaks.
Step67: The silhouette score is compared between spectral clustering and kmeans. After checking and discarding the Affinity clustering technique due to the number of clusters obtained, both spectral and kmeans are compared to select the best one from a clustering perspective. The number of clusters varies from 2 to 11 (as initially preset) to see which one offers better clusters based on the silhouette score.
Step68: For lower numbers of clusters kmeans present a higher silhouette score while for big number of clusters close to the preset number of groups spectral clustering performs better. Further analysis will be dome from a kmeans clustering perspective to see the best number of clusters for this clustering technique following the elbow technique.
Step69: The best number of clusters from both the silhouette and the elbow technique perspective is six that will be the number of clusters used following this technique to cluster the customer base. The data will be clustered using kmeans and 6 clusters to get insights about the customer base. In this case, five, six and seven clusters have been tried being 6 the most relevant one.
Step70: The predictive capacity of kmeans clustering with six clusters will be checked. In this case the predictive performance is very low 15% compared to the one obtained from the supervised models. Hence its use as a predictive tool is discarded for classification purposes.
Step71: The data is aggregated by clusters and gender to inspect the average age per cluster. In all clusters the average age is the same standard deviation so it is not representative of the groups
Step72: Information regarding the apps that people use is obtained from the clusters. It can be seen that three apps are the most used ones across clusters App 549, 706 and 548 that according to the documentation equate to Property Industry 1.0, Customized 1 and Industry tag. In the first and third cases they are construction inspection and tagging apps. The second case seems to be an app that is preinstalled in the phone. This might indicate the kind of population we are addressing although the calls are done from all around China. It could be the case that the sample is representative of a specific kind of population and the data has already being segmented reason why the average age in all clusters is nearly the same and around 30 years.
Step73: In this case and following the same clustering scheme, only information relative to the phone brands has been kept. It appears that for the population under analysis, Xiaomi, OPPO and Samsung are the most popular ones being Vivo more popular among the female than male and Meizu more popular among male compared to female.
Step74: To be able to plot the different clusters PCA is run and the 2 principal components are extracted. In this case two are preferred to three components due to computational restrictions.
Step75: Once the PC are defined, a plot function is defined with the characteristics of the plot that is going to be done. | Python Code:
#Uplaod the data into the notbook and select the rows that will be used after previous visual inspection of the datasets
datadir = 'D:/Users/Borja.gonzalez/Desktop/Thinkful-DataScience-Borja'
gatrain = pd.read_csv('gender_age_train.csv',usecols=['device_id','gender','age','group'] )
gatest = pd.read_csv('gender_age_test.csv')
phone = pd.read_csv('phone_brand_device_model.csv')
app_events = pd.read_csv('app_events.csv', usecols = ['event_id', 'app_id','is_active'])
applabels = pd.read_csv('app_labels.csv')
events = pd.read_csv('events.csv', usecols = ['event_id', 'device_id'])
# Get rid of duplicate device ids in phone
phone = phone.drop_duplicates('device_id',keep='first')
Explanation: Introduction
The purpose of this product is to classify population depending on their uses of their phone and phone brands. This classification is the first step to tailor advertising campaigns by third parties based on the usage of the mobile according to the age and gender of the population. For this we have a sample of the population using Mobile Talk data in China. Although this product has been developed for the Chinese population, it can be used globally as further research has shown that other mobile operators in other countries have access to the same type of data.
In this case the groups have been preset based on gender and age range that are specifically important for the client of Mobile Talk. This groups can be tailored to the needs of the advertising company depending on the information that the mobile operator is willing to share with the final client or that wants to use to tailor its own offering.
From the data extracted we are going to get the main features that will be used to classify the population according to their demographics. For this we are going to focus on the apps they use and the device brand. The steps that will be followed to develop this product are:
Data Wrangling: Acquire the data and transform categorical data into data that can be used for classification after merging the data from different sources. In this step special attention has been taken to the empty cells and duplicates present in each dataset so that the final dataset is manageable.
Dataset creation: Build the final dataset and cleanse it accordingly so that it can be used for classification purposes. In this case the categorical features are hotenconded representing by 1 the presence of an app on a device and zero the absence. The same criteria has been followed with the phone brand. In this case, brands have been translated into English using information available. Local brands, for which information was not available have been substituted with UBXX standing for “unkown brand” followed by two digits.
Features Generation: The most meaningful features have been selected using different methods and transformed using PCA so that the classification accuracy is maximized. The initial analysis to generate the features give the most important ones to measure the relationship they have with the outcome variable (group by gender and age). For the classification purposes there is no need to keep them as accuracy is the objective of the classification exercise. In this case kbest, random forest feature selection and recursive feature elimination has been used as a preliminary step. The final number of features to determine the PCA components have been chosen so that the accuracy of the algorithms in enhanced.
Model Selection: Several supervised algorithms have been used as a preliminary step to determine the one that is giving highest accuracy and that is suitable for production. Computing effort and suitability for production is measured based on the computing time required by each of them. There is a compromise that has to be achieved between accuracy and computing effort to make the product a feasible product. The algorithms that will be tested are logistic regression, Naïve-Bayes, k-nearest neighbors, support vector classifier, linear vector classifier, random forest, decision tree, SGD classifier and Gradient Boosting classifier. From the obtained results the algorithm that suits best the abovementioned criteria will be selected as final product.
Deep learning classification: in this case, the raw data is passed through a Multilayer Classifier analyzing the effect of different layers and configurations of the neural network to maximize the accuracy of the model. In this case due to the amount of data points available we are expecting high accuracy but maybe lower than the accuracy that is normally obtained with this models. The goal is to achieve the highest accuracy through this model.
Unsupervised Clustering: Cluster the data to see the information that it can be extracted from it and the basic features that characterize each group. Meanshift, Spectral, Affinity and kmeans clustering will be tested to see which one is the most suitable based on the different metrics used for comparison such as silhouette, homogeneity, completeness, V-measure and adjusted Rand. The number of clusters between spectral clustering and kmeans that achieves the best result is the one that will be used to cluster the information.
Conclusion The main findings will be summarized and the selected algorithm will be presented as a conclusion summarising the main features of the product.
1. Data Wrangling
The data that is going to be used is retrieved from https://www.kaggle.com/c/talkingdata-mobile-user-demographics. In this case, we have several folders that give information about demographics and use of their mobile phones. More specifically, we will focus on the gender-age file as the base to create the features for further analysis. This file contains the information and clusters that are relevant to be used for online advertising campaigns, including device id, age, gender and age group.
The dataset provided by Kaggle as the test in the abovementioned link has been discarded as it is providing devices that are not contained in the training dataset and is adding noise to the dataset as we don´t have any relevant information from which we can create features.
The phone brand dataset is linking the device id with the phone brand and model. The device model will be used and grouped by phone brand to use it as one of the features. In this case and for further merging of the datasets the duplicates in phone brands have been dropped as it will increase the dataset making it unmanageable not adding information.
The appevents dataset links the events or usage of the different apps to the app id that categorizes the apps within certain groups such as gaming, finance, etc. In this case the app ides will be used as a categorical features to have a better description of the interests of the target audience. The linking column will be the events as it appears in both datasets (app_events and device apps) including information about the app to see if it is active or just installed.
The applabels dataset “translates” a 20 digits id into the abovementioned categories.
The events dataset gives information about the location and the time in which the app is used in the device. In this case the information about the location has been discarded as it is not accurate giving as locations points outside of China hence not adding relevant information for the features generation.
End of explanation
#Merge the app_events and events to accrss app_ids.
device_apps = (
app_events
# Merge on event_id
.merge(events, how = 'left', left_on = 'event_id', right_on = 'event_id')
# event_id itself is not interesting
.drop('event_id', axis = 1)
# Because the events correspond to more than just
# being installed, there are many duplicates
.drop_duplicates())
Explanation: 2. Dataset Creation
The first objective is to create a dataset that unifies the different files that have been uploaded into the notebook. For this there will be a set of merging actions based on the information provided that will be combined with cleaning actions to avoid oversizing the final dataset prior to the features generation.
To merge this information the hypothesis around the potential features that can explain the demographics of the users for further classification has been used: app labels, device brands, gender and age. This transforms the problem into selecting and generation the categorical features (predictors) to determine based on them if the user is in a certain age range and gender (target).
The order in which the different datasets are merged is not random. Several ways of merging the data have been tried and this is the one that allows to build a model that will predict the age range and gender gathering as much relevant information as possible.
In this case the information about events (usage of the phone) and app_events that identifies app ids is merged using as the merging column the events. As a result information about the device id the use of the app and the app id are in the same dataframe which allows further merging to arrive to the applabels and device brands. In this merging the duplicates have been left out to avoid oversizing the dataframe. From the information of this dataset there are 459k rows of data that match usage, device id to app id. The timestamp has been eliminated from the dataset as it does not add relevant information and there are data points missing.
End of explanation
#Get information about the new dataset
print(device_apps.info())
#Print the first five rows fo the dataset
device_apps.head()
Explanation: The dataset stands as follows. There are more than 2.8 million entries being all the values of the cells integers
End of explanation
#Translate the apps_id to apps categories to build features
apps = (
device_apps
# Merge on event_id
.merge(applabels, how = 'left', left_on = 'app_id', right_on = 'app_id')
# event_id itself is not interesting
.drop('app_id', axis = 1)
# Because the events correspond to more than just
# being installed, there are many duplicates
.drop_duplicates())
Explanation: The devices ids are now linked to the applabels so that it contains the information about the different categories of the apps is included. In this case the 20 digit identifier of the app is substituted by a category that identifies the kind of app that is active in each device.
End of explanation
#Clean the dataset removing empty cells from the data set
apps = apps.dropna()
#convert first or second to str or int
apps['device_id'] = apps['device_id'].astype(int)
#Motor['Motor'] = Motor['Motor'].astype(str)
#Merge the column back into the dataset
gatrain['device_id'] = gatrain['device_id'].astype(int)
Explanation: The new dataset is cleansed removing the empty values and changing the type of variable so that they can be merged afterwards without increasing disproportionately the number of rows.
End of explanation
#Get information of the new dataset and chekc tha the transformation into integers has happened before
#merging datasets
print(apps.info())
#Print the first five rows of the dataframe
apps.head()
Explanation: Information is retrieved about the size and type of the variables in the dataset. The dataset is now ready to be merged.
End of explanation
#Merge dataset about devices and apps with demographic data
apps_with_groups = (
apps
# Merge on event_id
.merge(gatrain, how = 'left', on = 'device_id')
# event_id itself is not interesting
# .drop('device_id', axis = 1)
# Because the events correspond to more than just
# being installed, there are many duplicates
.drop_duplicates())
Explanation: The dataset containing data about the usage of the apps, the activity, device id is linked with the dataset containing the device id and information about the gender, age and age group. The age groups used are the ones provided in the dataset and have not been changed.
There are 12 groups that differentiate the age and gender. The groups roughly split the population in even groups and the distribution of data points for each group is shown in the following graph.
End of explanation
#Get information about the dataset
print(apps_with_groups.info())
#Identify nul values in the dataset
print(apps_with_groups.isnull().sum())
Explanation: Information about the new datasets is retrieved to see the type of variables and to clean the data eliminating any missing cell.
End of explanation
#Drop empty cells
apps_with_groups = apps_with_groups.dropna()
#Reset index in the new dataset
apps_with_groups.reset_index(drop= True)
#Print first five rows
apps_with_groups.head()
Explanation: Further cleansing is done dropping the empty cells and resetting the index to have a better view of the data points available.
End of explanation
#Plot installed vs active apps
plt.figure(figsize=(20, 5))
sns.set_style("white")
ax = sns.countplot(x="is_active", data=apps_with_groups, palette="Set3")
ax.set_title('Active vs Installed Apps')
ax.set_ylabel('Number of Occurrences')
ax.set_xticklabels(['Installed','Active'], fontsize=10)
plt.tight_layout()
plt.show()
Explanation: In the Chinese market the number of apps that is actually used from the ones installed in the devices equate to roughly 50%.
End of explanation
#Plot the distribution of age in the dataset
plt.figure(figsize=(20, 9))
apps_with_groups.age.hist(bins=50, grid = False)
plt.title('Age Distribution of the Sample')
plt.xlabel('Age')
plt.ylabel('Frequency')
plt.tight_layout()
plt.show()
Explanation: Visual inspection of the distribution of data between ages show that the data is skewed to the right, showing that most of the data represents the age group between 20 and 35 years old. This corresponds to the grouping that has been done age-wise.
End of explanation
#Plot grouping the apps in different bins to understand its usage.
#Bins range from 10-50 for more detailed analysis
plt.figure(figsize=(20, 9))
apps_with_groups.label_id.value_counts(bins = 50).plot(kind='bar', grid=False)
plt.title('Apps grouped by usage')
plt.xlabel('Group of Apps')
plt.ylabel('Occurrences')
plt.tight_layout()
plt.show()
Explanation: Each group contains 20 apps in total. From an apps usage standpoint, the most important group of apps according to its usage corresponds to financial, lottery and gaming apps followed by apps related to smart appliances and wearables in second place. The third place is taken by the apps used for banking and payment services. On the lower end the apps that show a smaller usage are the leisure related ones like photography, wedding planners or trips abroad. This apps equate to 90 and are presenting a lower usage due to its characteristics and the sample taste.
End of explanation
#Create dummy variables for the categories found in the apps
dataset_with_dummy_variables = pd.get_dummies(apps_with_groups, columns = ['label_id'], sparse = True).reset_index(drop= True)
#Print the first 5 rows of data
dataset_with_dummy_variables.head()
Explanation: Dummy variables are created based on the apps that are installed on the devices. In this case 484 additional columns are created with categorical data that counts the appearance of each app category in the device. To avoid the dummy variable trap whereby collinearity exists between the variables one redundant category is dropped when transforming the categorical variables into dummies.
End of explanation
#Add a brand name "UBXX" per brand in Chinese for which we don´t have a translation
english_phone_brands_mapping = {"三星": "samsung","天语": "Ktouch", "海信": "hisense", "联想": "lenovo", "欧比": "obi",
"爱派尔": "ipair", "努比亚": "nubia", "优米": "youmi", "朵唯": "dowe", "黑米": "heymi",
"锤子": "hammer", "酷比魔方": "koobee", "美图": "meitu", "尼比鲁": "nibilu", "一加": "oneplus",
"优购": "yougo", "诺基亚": "nokia", "糖葫芦": "candy", "中国移动": "ccmc", "语信": "yuxin",
"基伍": "kiwu", "青橙": "greeno", "华硕": "asus", "夏新": "panasonic", "维图": "weitu",
"艾优尼": "aiyouni", "摩托罗拉": "moto", "乡米": "xiangmi", "米奇": "micky", "大可乐": "bigcola",
"沃普丰": "wpf", "神舟": "hasse", "摩乐": "mole", "飞秒": "fs", "米歌": "mige", "富可视": "fks",
"德赛": "desci", "梦米": "mengmi", "乐视": "lshi", "小杨树": "smallt", "纽曼": "newman",
"邦华": "banghua", "E派": "epai", "易派": "epai", "普耐尔": "pner", "欧新": "ouxin", "西米": "ximi",
"海尔": "haier", "波导": "bodao", "糯米": "nuomi", "唯米": "weimi", "酷珀": "kupo", "谷歌": "google",
"昂达": "ada", "聆韵": "lingyun", "小米": "Xiaomi", "华为": "Huawei", "魅族": "Meizu", "中兴": "ZTE",
"酷派": "Coolpad", "金立": "Gionee", "SUGAR": "SUGAR", "OPPO": "OPPO", "vivo": "vivo", "HTC": "HTC",
"LG": "LG", "ZUK": "ZUK", "TCL": "TCL", "LOGO": "LOGO", "SUGAR": "SUGAR", "Lovme": "Lovme",
"PPTV": "PPTV", "ZOYE": "ZOYE", "MIL": "MIL", "索尼" : "Sony", "欧博信" : "Opssom", "奇酷" : "Qiku",
"酷比" : "CUBE", "康佳" : "Konka", "亿通" : "Yitong", "金星数码" : "JXD", "至尊宝" : "Monkey King",
"百立丰" : "Hundred Li Feng", "贝尔丰" : "Bifer", "百加" : "Bacardi", "诺亚信" : "Noain",
"广信" : "Kingsun", "世纪天元" : "Ctyon", "青葱" : "Cong", "果米" : "Taobao", "斐讯" : "Phicomm",
"长虹" : "Changhong", "欧奇" : "Oukimobile", "先锋" : "XFPLAY", "台电" : "Teclast", "大Q" : "Daq",
"蓝魔" : "Ramos", "奥克斯" : "AUX", "索尼" : "Sony", "欧博信" : "Opssom", "奇酷" : "Qiku",
"酷比" : "CUBE", "康佳" : "Konka", "亿通" : "Yitong", "金星数码" : "JXD", "至尊宝" : "Monkey King",
"百立丰" : "Hundred Li Feng", "贝尔丰" : "Bifer", "百加" : "Bacardi", "诺亚信" : "Noain",
"广信" : "Kingsun", "世纪天元" : "Ctyon", "青葱" : "Cong", "果米" : "Taobao", "斐讯" : "Phicomm",
"长虹" : "Changhong", "欧奇" : "Oukimobile", "先锋" : "XFPLAY", "台电" : "Teclast", "大Q" : "Daq",
"蓝魔" : "Ramos", "奥克斯" : "AUX", "飞利浦": "Philips", "智镁": "Zhimei", "惠普": "HP",
"原点": "Origin", "戴尔": "Dell", "碟米": "Diemi", "西门子": "Siemens", "亚马逊": "Amazon",
"宏碁": "Acer",
'世纪星': "UB1", '丰米': "UB2", '优语':'UB3', '凯利通': "UB4", '唯比': "UB5", '嘉源': "UB6",
'大显': "UB7", '天宏时代': "UB8", '宝捷讯': 'UB9','帷幄': 'UB10', '德卡诺': 'UB11',
'恒宇丰': 'UB12', '本为': 'UB13', '极米': 'UB14', '欧乐迪': 'UB15', '欧乐酷': 'UB16',
'欧沃': 'UB17', '瑞米': 'UB18', '瑞高': 'UB19', '白米': 'UB20', '虾米': 'UB21', '赛博宇华': 'UB22',
'首云': 'UB23', '鲜米': 'UB24'}
Explanation: Before adding the data about the phone brands and models, a dictionary has been taken from Kaggle and augmented with additional brands to translate the brands from Chinese to English. Additionally, those brands that have no translation have been designed with “UBXX” where UB stands for unknown brand and XX are two digits. This has been done to easy queries on the dataframe and visualizations of the dataset. The translation of the brands form Chinese to English has been included in the phone dataset and dummy variables have been created for each brand. This gives as a result a sparse data frame with zero if the device is not of that brand and 1 when the device is associated to a certain brand.
End of explanation
#Replace the brands in Chinese for the brands in English
phone['phone_brand'].replace(english_phone_brands_mapping, inplace=True)
#Drop the device model column as it is not adding information
phone = phone.drop('device_model',axis=1)
#Retreive information about the new dataset before getting the dummy variables
phone.info()
Explanation: The phone brands dataset has been added to the previous dataset containing all the information about apps, age, gender, etc. In the instances in which the device id does not appear the NaN results have been filled in with zeros. The devices that are duplicate have been deleted to make the dataset manageable from a computing perspective reducing from two million rows to 23k data rows. The device id and device model columns have been dropped as in further research they were not adding information for the feature generation. Additionally, a dummy variable has been created for the variable gender.
End of explanation
#Plot the distribution of brands by occurrence
plt.figure(figsize=(20, 9))
phone.phone_brand.value_counts().plot(kind='bar', grid=False)
plt.title('Distribution of Phones per Brand')
plt.xlabel('Brands')
plt.ylabel('Occurrences')
plt.tight_layout()
plt.show()
Explanation: As it is shown in the graph below, eight brands represent 90% of the sample in the Chinese market.
End of explanation
#Build the dummy variables with the phone brand
phone_dummies = pd.get_dummies(phone, columns = ['phone_brand'], sparse = True).reset_index(drop= True)
#Merge the demographic dataset with the phone dataset
final_dataset = (
dataset_with_dummy_variables
# Merge on event_id
.merge(phone_dummies, how = 'left', left_on = 'device_id', right_on = 'device_id')
# event_id itself is not interesting
.fillna(0))
#Information about the dataset
final_dataset.info()
Explanation: To avoid the dummy variable trap whereby collinearity exists between the variables one redundant category is dropped when transforming the categorical variables into dummies.
End of explanation
#Drop from the final dataset duplicates for the devices keeping the first one
final_dataset = final_dataset.drop_duplicates('device_id',keep= 'first').reset_index(drop=True)
#Get infomation of the new dataset to see the rows that have been eliminated
print(final_dataset.info())
#Print the first five rows of the dataset
final_dataset.head()
Explanation: The new dataset has been cleansed eliminating all the columns that are zeros. In this case, 345 columns have been deleted related to brands that were not associated to devices. The output variable that groups gender and age “group” has been transformed into numbers so that supervised algorithms are used for prediction.
End of explanation
#Visualize the number of answers by Gender and by Category
#Check the outcome variable and see if there is any imbalance
plt.figure(figsize=(20, 5))
sns.set_style("white")
plt.subplot(1, 2, 1)
ax = sns.countplot(x="gender", data=final_dataset, palette="Set2")
ax.set_title('Classification by Gender')
ax.set_ylabel('Number of Occurrences')
ax.set_xticklabels(['Male','Female'], fontsize=10)
plt.ylim(0, 17500)
plt.subplot(1, 2, 2)
ax = sns.countplot(x="group", data=final_dataset, palette="Set1")
ax.set_title('Classification by Age Range & Gender')
ax.set_ylabel('Number of Occurrences')
ax.set_xticklabels(['M39+','M32-38', 'M29-31', 'M27-28', 'M23-26','M22-','F43+','F33-42', 'F29-32', 'F27-28', 'F24-26', 'F23-'], fontsize=10)
plt.ylim(0, 4000)
plt.tight_layout()
plt.show()
#Count number of datapoints for each group to resample all of them.
print(final_dataset['group'].value_counts())
Explanation: The gender split in the data is not even, being more male than women in the customer base of the company. This has an impact in the further segmentation by age (including gender) expecting groups that have a lower number of data points in the case it is for women. A visual inspection of the groups show that the groups are unbalanced. This will impact the accuracy of the models for classification purposes. Further resampling is required and in this case, up-sampling will be considered using the number of samples in the largest group: males between 32 and 38 years (3338 samples).
End of explanation
#Upsample minority classes
# Separate majority and minority classes
final_dataset_majority = final_dataset[final_dataset.group=='M32-38']
#Minorty classes
final_dataset_minority_1 = final_dataset[final_dataset.group=='M39+']
final_dataset_minority_2 = final_dataset[final_dataset.group=='M23-26']
final_dataset_minority_3 = final_dataset[final_dataset.group=='M29-31']
final_dataset_minority_4 = final_dataset[final_dataset.group=='M22-']
final_dataset_minority_5 = final_dataset[final_dataset.group=='F33-42']
final_dataset_minority_6 = final_dataset[final_dataset.group=='M27-28']
final_dataset_minority_7 = final_dataset[final_dataset.group=='F29-32']
final_dataset_minority_8 = final_dataset[final_dataset.group=='F23-']
final_dataset_minority_9 = final_dataset[final_dataset.group=='F43+']
final_dataset_minority_10 = final_dataset[final_dataset.group=='F24-26']
final_dataset_minority_11 = final_dataset[final_dataset.group=='F27-28']
# Upsample airlines minorities
final_dataset_upsampled_1 = resample(final_dataset_minority_1, replace=True, n_samples=3338, random_state=123)
final_dataset_upsampled_2 = resample(final_dataset_minority_2, replace=True, n_samples=3338, random_state=123)
final_dataset_upsampled_3 = resample(final_dataset_minority_3, replace=True, n_samples=3338, random_state=123)
final_dataset_upsampled_4 = resample(final_dataset_minority_4, replace=True, n_samples=3338, random_state=123)
final_dataset_upsampled_5 = resample(final_dataset_minority_5, replace=True, n_samples=3338, random_state=123)
final_dataset_upsampled_6 = resample(final_dataset_minority_6, replace=True, n_samples=3338, random_state=123)
final_dataset_upsampled_7 = resample(final_dataset_minority_7, replace=True, n_samples=3338, random_state=123)
final_dataset_upsampled_8 = resample(final_dataset_minority_8, replace=True, n_samples=3338, random_state=123)
final_dataset_upsampled_9 = resample(final_dataset_minority_9, replace=True, n_samples=3338, random_state=123)
final_dataset_upsampled_10 = resample(final_dataset_minority_10, replace=True, n_samples=3338, random_state=123)
final_dataset_upsampled_11 = resample(final_dataset_minority_11, replace=True, n_samples=3338, random_state=123)
# Combine majority class with upsampled minority classes
final_dataset_upsampled = pd.concat([final_dataset_majority, final_dataset_upsampled_1, final_dataset_upsampled_2,
final_dataset_upsampled_3, final_dataset_upsampled_4, final_dataset_upsampled_5,
final_dataset_upsampled_6, final_dataset_upsampled_7, final_dataset_upsampled_8,
final_dataset_upsampled_9, final_dataset_upsampled_10, final_dataset_upsampled_11])
# Display new class counts
final_dataset_upsampled.group.value_counts()
Explanation: As the different groups are not balanced, the minority groups are balanced resampling the data and up-sampling the minority groups. This will allow the different algorithms to achieve a better accuracy in general. Algorithms like random forest are highly sensitive to unbalanced groups in the output variable.
End of explanation
#Get dummy variables for the gender variable and reset index
clean_final_dataset = pd.get_dummies(final_dataset_upsampled, columns = ['gender'], sparse = True,).reset_index(drop= True)
#Delete column with device_id
clean_final_dataset = clean_final_dataset.drop('device_id', axis = 1)
#Delete columns that are all zeros
clean_final_dataset = clean_final_dataset.drop(clean_final_dataset.columns[(clean_final_dataset == 0).all()], axis = 1)
#Substitute the categorical output variable
clean_final_dataset['group'] = clean_final_dataset['group'].map({'M39+' :0,'M32-38':1, 'M29-31':2, 'M27-28':3, 'M23-26':4,'M22-': 5,
'F43+' :6,'F33-42':7, 'F29-32':8, 'F27-28':9, 'F24-26':10, 'F23-':11 })
#Print the first five rows of the new dataset
clean_final_dataset.head()
Explanation: As part of the data cleansing actions, the device id column has been dropped and dummy variables have been created for the gender variable additionally all those columns that are constant and filled in only with zeros have been dropped. To avoid the dummy variable trap whereby collinearity exists between the variables one redundant category is dropped when transforming the categorical variables into dummies. The different groups have been mapped to 0-11 to be used in further modelling. In this case although different trials have taken place, after improving the significance of the features the twelve groups for the classification problem have been kept.
End of explanation
#Describe the data using statistics
clean_final_dataset.describe()
Explanation: As it can be appreciated the average age of the users is 31 years with a standard deviation of nearly 10 years. The interquartile age is between 26 and 37 years. For each of the labels and brands it can be seen that all the ones included appear at least once as it was expected from the data wrangling actions. Although group appears in the table, the results obtained means that the group M23-26 grouping male between 23 and 26 is the most significant one in terms of appearance.
End of explanation
#Build the predictors and output variables
X = clean_final_dataset.drop('group',axis = 1)
y = clean_final_dataset.group
#Preprocess and scale data
names = X.columns
X_processed = pd.DataFrame(normalize(preprocessing.scale(X)), columns = names)
Explanation: The dataset has been split between the predictors and the output variable. As abovementioned, the output variable is the group of age and gender and the input variables are the features created based on the app labels, gender and phone brand used by the users. To improve the quality of the features the data has been preprocessed and scaled.
End of explanation
#Check shape of X_processed and y
print(X_processed.shape, y.shape)
#Print the groups in y
print(y.unique())
Explanation: The size of the final dataset is 274 variables and 40k rows of data from which features will be generated.
End of explanation
#Build the correlation matrix between scores
correlation_mat = X_processed.corr()
#Check the correlation between values
corr_values = correlation_mat.unstack()
corr_values_sorted = corr_values.sort_values(kind="quicksort", ascending=False)
#Check high postivie correlations (between 0.4 and 1)
print(('Values presenting correlation between 0.4 and 1 (excluding 1) \n\n {}:')
.format(corr_values_sorted[corr_values_sorted.between(0.4, 0.99, inclusive=True)]))
#Check high negative correlations (between -0.4 and -1)
print(('Values presenting correlation between -0.4 and -1 (excluding -1) \n\n {}:')
.format(corr_values_sorted[corr_values_sorted.between(-0.4, -0.99, inclusive=True)]))
Explanation: To have a better understanding of the correlation between variables, and due to the large amount of variables in this dataset, a correlation matrix has been created. To check the level of correlation between variables, only those with a correlation greater than 0.5 and lower than 1 (in absolute terms) have been printed.
End of explanation
#Split the dataset into a training and testing dataset 70/30
X_train, X_test, y_train, y_test = train_test_split(X_processed, y,test_size=0.3, random_state=42)
Explanation: As it can be observed only the pone brand "OPPO" and the app label 706 present the highest correlation equal to 0.42. Further inspection shows that this brand includes a "customized" app in all the phones to access special features. As expected there is no negative correlation higher than 0.4 (in absolute terms) due to the characteristics of the data. There are no apps that cannot be installed in certain phone brands or that decrease when the number of phones of that brand increases.
The dataset has been split into predictors and target variable and the dataset split into a train and test data set (70/30) defining five folds for cross validation. This train test split will be used for the feature generation steps and as part of the unsupervised exploratory data analysis.
End of explanation
#Feature Selection.
#Scores for the most relevant features (should we start with the one that has more explanatory power)
#Feature extraction. Starting and fitting the model
test = SelectKBest()
fit = test.fit(X_processed, y)
#Identify features with highest score from a predictive perspective (for all programs)
names = X_processed.columns
#Put the features and scores into a dataframe.
best_features = pd.DataFrame(fit.scores_, index = names).reset_index()
best_features.columns = ['Best Features', 'Scores']
#Show the features in descending order from those that have more explanatory power to the ones that have less.
best_features.sort_values(by=['Scores'], ascending=False)
Explanation: 3. Feature Generation
The feature selection process will start with a PCA analysis to understand the number of features required to describe more than 90% of the variance of the outcome variable. Once the number of features is identified, the following methods will be used to select the features that will be used to run build the binary classifier:
Feature Importance using Random Forest
Feature Selection using kbest()
The features obtained by each of the methods will be compared to see if the selected ones are stable and the final number of features will be determined by the number of features obtained from PCA. The number of features is determined from the results obtained from PCA analysis.
End of explanation
#Select all the features that have an explanatory power higher than 1.
list_of_best_features = best_features.loc[best_features['Scores'] > 1]['Best Features'].tolist()
#Create a dataframe with the new features
columns = list_of_best_features
X_best_features = pd.DataFrame(X_processed, columns = columns).reset_index(drop= True)
#Print information of the dataset
X_best_features.info()
Explanation: Due to the characteristics of the variables the use of all the features create a lot of noise and when the supervised models are run, there is overfitting in all cases. Hence, the number of variables is reduced using Kbest using only those that have an explanatory power higher than 1. A dataframe is created with this new set of features.
End of explanation
#Start the Random Forest Classifier
rf = RandomForestClassifier()
rf.fit(X_processed, y)
#Define feature importance
feature_importance = rf.feature_importances_
# Make importances relative to max importance.
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
pos = np.arange(sorted_idx.shape[0]) + .5
#Plot the features importance
plt.figure(figsize=(7, 50))
plt.subplot(1, 1, 1)
plt.barh(pos, feature_importance[sorted_idx], align='center')
plt.yticks(pos, X_processed.columns[sorted_idx])
plt.xlabel('Relative Importance')
plt.title('Feature Importance')
plt.show()
Explanation: To select the features, Feature Importance using Random Forest is used. In this case the result given by the random forest feature selection is not meaningful therefore the result given by kbest() will be used as a first step before running PCA for generating the new set of features. From the random forest feature selection it can be observed that the number of features has to be reduced significantly as there are a lot of features that are adding noise and with low explanatory power.
End of explanation
# Assign the value to a new variable
corr_variable = X_best_features
#Build the correlation matrix
correlation_matrix = corr_variable.corr()
#Clean the correlation matrix adding zeros to the cells that are non existent
correlation_matrix = correlation_matrix.fillna(0)
Explanation: The feature selection using Radnom forest shows the high contribution of age, gender and certain brands over the apps ids. It cn be seen that all of them have a contribution and after running iteratively on the 16 best features selected by Random Forest the accuracy obtained with Logistic Regression was very low. Once features from kbest were added to the feature space accuracy results improved. Hence the features obtained using kbest() will be the ones that will be transformed using PCA. As a second step, the variables selected by Kbest are transformed using PCA analysis. For this, the correlation matrix of the new set of variables is created and non existing values are filled in with zeros.
End of explanation
#Eigenvectores & Eigenvalues
eig_vals, eig_vecs = np.linalg.eig(correlation_matrix)
sklearn_pca = PCA(n_components=len(corr_variable.columns))
Y_sklearn = sklearn_pca.fit_transform(correlation_matrix)
print(
'The percentage of total variance in the dataset explained by each',
'component from Sklearn PCA.\n',
sklearn_pca.explained_variance_ratio_
)
Explanation: Calculate the eigen-values and vectors and determine the explained variance by each component.
End of explanation
#PCA features
# Create a scaler object
sc = StandardScaler()
# Fit the scaler to the features and transform
X_std = X_best_features
# Create a PCA object from Scree plot the number of components is 120
pca = decomposition.PCA(n_components=120)
# Fit the PCA and transform the data
X_std_pca = pca.fit_transform(X_std)
# View the new feature data's shape
X_std_pca.shape
# Create a new dataframe with the new features
X_pca = pd.DataFrame(X_std_pca)
#Check the shape of the dataframe containing the PCA components
X_pca.shape
Explanation: From the PCA analysis abovementioned the PCA features are created. After analysing the feature generation using recursive feature analysis and feature selection using kbest(), the PCA features will be used. Additionally, there is no need to have the initial features as predictors or now which ones have been used as the main purpose of the classification process is to maximize the accuracy.
End of explanation
#Split into test and train sets
X_train, X_test, y_train, y_test = train_test_split(X_pca, y, test_size=0.3, random_state=42)
#KFold for cross validation analysis
kf = KFold(5)
Explanation: 4. Model Selection
The dataset is split 70/30 train test and several models will be tuned in the training set and run on the test set calculating their accuracy using cross validation. The purpose of this is to train and test the classification models avoiding overfitting, exposing the algorithms to unknown data in the test set. The cross validation will be done using five folds, in this case and as data has been resampled the representation of each class is even across folds avoiding the need to stratify the data, although its use would reduce the bias and variance effects if classes were not evenly distributed in the dataset.
End of explanation
# Initialize and fit the model.
log_reg = LogisticRegression(class_weight='balanced', multi_class= 'multinomial', solver = 'lbfgs', max_iter = 1500)
#Tune parameters: C parameter
c_param = [100, 200, 1000]
parameters = {'C': c_param}
#Fit parameters
log_reg_tuned = GridSearchCV(log_reg, param_grid=parameters, n_jobs = -1, cv=kf, verbose = 1)
#Fit the tunned classifier in the training space
log_reg_tuned.fit(X_train, y_train)
#Print the best parameters
print(('Best paramenters logistic regression:\n {}\n').format(log_reg_tuned.best_params_))
Explanation: All models' hyperparameters will be tuned in the training set using cross validation and gridsearch tuning several parameters considered in the pipeline (gridsearch). Except for specific cases that will be discussed one by one, the algorithm or variations (solver, etc) to be used has been decided in advance considering the topology of the dataset.
The models that have been selected to be tested on the dataset to accurately classify the data are:
4.1 Logistic Regression
4.2 Naïve - Bayes (Bernoulli)
4.3. KNeighbors Classifier
4.4 Random Forest
4.5 Support Vector Machine
4.6 Gradient Boosting Classifier
4.7 Linear Support Vector Machine
All classes have been transformed from their original categorical tag to values from 0 to 11 to enable classification. In this case there is no bias towards a type I or type II misclassification error in terms of cost. There is no "negative or positive" case as if one of the groups of users is misclassified, then the marketing effort will be inefficient. Hence, both errors have the same weight and the overall accuracy will be used as hyperparameter tuning score and as an indicator of overall final accuracy. The time required to fit the model and run the cross validation using five folds will be used to indicate the computational effort of each model.
4.1 Logistic Regression
The first model to be run is the Logistic Regression model. The following hyperparameters of the model have been tuned using searchgridCV and the overall accuracy as the selection strategy:
Parameter "C" will be tuned in the training set. Lower values of C parameter will show a higher regularization.
The model is initialized and several values are tested. Lower values of parameter "C" will give a stronger regularization of the model. The solver is set to "lbfgs" as it provides a similar accuracy than "liblinear" reducing the computational effort considerably (from 45 min to 3.3 min) being adequate for the problem and size of the dataset.
End of explanation
#Once the model has been trained test it on the test dataset
log_reg_tuned.fit(X_test, y_test)
# Predict on test set
predtest_y = log_reg_tuned.predict(X_test)
Explanation: The tuned model is fit and run on the test set and the computational effort is measured considering the time required to fit the test set.
End of explanation
#Evaluation of the model (testing)
#Define the Target values
target_names = ['0.0', '1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','10.0','11,0']
#Print the Classification Report
print(('Classification Report: \n {}').format(classification_report(y_test, predtest_y, target_names=target_names)))
#Calculate the confusion matrix
confusion_lr = confusion_matrix(y_test, predtest_y)
#Print the Confusion Matrix
print(('Confusion Matrix: \n\n {}\n').format(confusion_lr))
#Print the overall accuracy per class
print(('Logistic Regression set accuracy: {0:.2f} % \n').format(cross_val_score(log_reg_tuned, X_test,
y_test,cv=kf).mean()*100))
Explanation: The model requires 3.3 min to run which will be used as a time threshold to measure the computational effort of other models. To calculate the accuracy the model is evaluated on the test set. From the classification report it can be seen that the data representing each class is evenly distributed across the classes. This reduces the probability of bias of the model when calculating the probabilities of each predicted value.
End of explanation
# Initialize and fit the model.
naive_bayes_bernoulli= BernoulliNB()
#Tune hyperparameters
#Create range of values to fit parameters
alpha = [10, 100, 200, 1000]
parameters = {'alpha': alpha}
#Fit parameters using gridsearch
naive_bayes_bernoulli_tuned = GridSearchCV(naive_bayes_bernoulli, n_jobs = -1, param_grid=parameters, cv=kf, verbose = 1)
#Fit the tunned classifier in the training space
naive_bayes_bernoulli_tuned.fit(X_train, y_train)
#Print the best parameters
print(('Best paramenters logistic Naive-Bayes Bernoulli: \n{}\n').format(naive_bayes_bernoulli_tuned.best_params_))
Explanation: The overall accuracy of the Logistic Regression model is 95.62%. Although the overall accuracy is good and the computational effort low, the classification report and confusion matrix show overfitting as there will be some data points misclassified. The high accuracy of the model can be explained by the lack of correlation between the predictors (independent variables). Only two variables out of 120 presented a correlation of 0.5 (max correlation value in the dataset) which have been eliminated when during the feature generation process and through PCA. The PCA components are all independent from each other and by definition there is no collinearity between the 120 components that have been chosen. Additionally linearity between the independent variable and the log odds exists. Furthermore, the dataset is big enough to use this classification algorithm.
4.2 Naive Bayes
From the Naïve Bayes models the Bernoulli algorithm has been implemented because Bernoulli model can be trained using less data and be less prone to overfitting. The hyperparameter to be tuned is "alpha".
End of explanation
#Once the model has been trained test it on the test dataset
naive_bayes_bernoulli_tuned.fit(X_test, y_test)
# Predict on test set
predtest_y = naive_bayes_bernoulli_tuned.predict(X_test)
Explanation: The value for "alpha" is the smallest of the values chosen to tune the parameters of the model. In this case the gridsearch has been carried out with values ranging from 0.001 to 10 before fitting the above set. In all cases, 10 was the value that was appearing as the best one in terms of overall accuracy. The tuned model is fit and run on the test set and the computational effort is measured considering the time required to fit the test set.
End of explanation
#Evaluation of the model (testing)
#Define the Target values
target_names = ['0.0', '1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','10.0','11,0']
#Print the Classification Report
print(('Classification Report: \n {}').format(classification_report(y_test, predtest_y, target_names=target_names)))
#Calculate the Confusion Matrix
confusion_ber = confusion_matrix(y_test, predtest_y)
#Print the Confusion Matrix
print(('Confusion Matrix: \n\n {}\n').format(confusion_ber))
#Print the overall accuracy
print(('Bernoulli Classifier set accuracy: {0:.2f} % \n').format(cross_val_score(naive_bayes_bernoulli_tuned,
X_test,
y_test,
cv=kf).mean()*100))
Explanation: Once the algorithm is trained it is run on the test set. The maximum precision obtained is 70% for the first class being all of the rest lower than 50%. From an accuracy perspective this algorithm doesn't seem to be a good candidate for our product. Cross validation has been performed to avoid overfitting:
End of explanation
#Train model
# Initialize and fit the model.
KNN = KNeighborsClassifier()
#Tune hyperparameters
#Create range of values to fit parameters
neighbors = [5, 7,9, 11]
weights = ['uniform', 'distance']
#Fit parameters
parameters = {'n_neighbors': neighbors, 'weights': weights}
#Fit parameters using gridsearch
KNN_tuned = GridSearchCV(KNN, param_grid=parameters, n_jobs = -1, cv=kf, verbose = 1)
#Fit the tunned classifier in the training space
KNN_tuned.fit(X_train, y_train)
#Print the best parameters
print(('Best paramenters KNN:\n {}\n').format(
KNN_tuned.best_params_))
Explanation: In this case the low accuracy of the Naïve-Bayes classifier can be explained because of the continuous structure of the data once the scaler and PCA has been applied. Although the features are strongly independent due to the PCA transformation of them, this classifier is good when it is used for binary problems with two classes. In this case, the existence of 12 different classes makes it harder for this algorithm to classify accurately.
4.3 K-nearest neighbors
A K-Neighbors model has been implemented and tuned on the train set. The parameters tuned are:
Number of neighbors which will determine the number of points used to classify into each of the categories the data points
Two weighting systems to be tested: uniform and distance.
The number of neighbors when tuning the model has been capped to 11
End of explanation
#Once the model has been trained test it on the test dataset
KNN_tuned.fit(X_test, y_test)
# Predict on test set
predtest_y = KNN_tuned.predict(X_test)
Explanation: The value for "n_neighbors" is the smallest of the values chosen to tune the parameters of the model. In this case the gridsearch has been carried out with values ranging from 3 to 11, always odd as the number of classes is even before fitting the above set. In all cases, 5 was the value that was appearing as the best one in terms of overall accuracy. The algorithm to be used has been set to "auto" and the algorithm used is "brute force" in this case as k < n_samples/2 and no specific metrics have been given. In this case the leaf size has been set to the default value of 30 considering the number of features used. The choice fo distance as the weight instead of uniform is reasonable were the points are weighted by the inverse of their distance. In this case features are different from each other ranging from different types of apps to device brands. The tuned model is fit and run on the test set and the computational effort is measured considering the time required to fit the test set.
End of explanation
#Evaluation of the model (testing)
#Define targets
target_names = ['0.0', '1.0', '2.0', '3.0', '4.0', '5.0', '6.0', '7.0', '8.0', '9.0', '10.0', '11.0']
#Print classification report
print(('Classification Report KNN: \n {}\n').format(classification_report(y_test, predtest_y, target_names=target_names)))
#Calculate confusion matrix
confusion_knn = confusion_matrix(y_test, predtest_y)
#Print confusion matrix
print(('Confusion Matrix KNN: \n\n {}\n\n').format(confusion_knn))
#Print overall accuracy
print(('KNN accuracy: {0:.2f} %\n').format(cross_val_score(KNN_tuned, X_test, y_test,cv=kf).mean()*100))
Explanation: In this case, due to the characteristics of the algorithm (lazy algorithm) all the work is done in the previous step as the prediction is required. This algorithm goes through all the dataset comparing each data point with the instances that it has previously seen while it was trained. This could be the reason why this step requires some more time than the previous and next ones (1.1 min per fold).
From the requirements to achieve good accuracy only two out of the three have been fulfilled, hence not a very high accuracy is expected. Data has been scaled and missing values have been addressed but the dimensionality of the problem is very large. In this case the dimensionality is 120 and the Euclidean distance does not perform well with high dimensions as points that may be similar may have very large distances.
As it can be seen the confusion matrix and the classification report are not adding value from an information perspective as it appears to have no misclassification. In this case, there is overfitting that is corrected through cross validation:
End of explanation
#Train model
# Initialize and fit the model.
SGD = SGDClassifier(class_weight = 'balanced', max_iter=1000)
#Tune hyperparameters
#Create range of values to fit parameters
loss_param = ['hinge', 'squared_hinge']
alpha_param = [0.0001, 0.001, 0.01, 0.1, 1]
#Fit parameters
parameters = {'loss': loss_param,'alpha': alpha_param}
#Fit parameters using gridsearch
SGD_tuned = GridSearchCV(SGD, param_grid=parameters, n_jobs = -1, cv=kf, verbose = 1)
#Fit the tunned classifier in the training space
SGD_tuned.fit(X_train, y_train)
#Print the best parameters
print(('Best paramenters SDG:\n {}\n').format(SGD_tuned.best_params_))
Explanation: As it was expected the accuracy obtained for this problem with this algorithm is lower than the values that are normally obtained with lower dimensionalities. As previously discussed this has to do with the fact that the Euclidean distance doesn´t perform accurately with high dimensionality problems and that it is used to measure the weight of each vote through the inverse of its value.
4.4 SGD Classifier
The SGD Classifier uses regularized linear models with stochastic gradient descendent learning. The model is updated in its learning rate after the gradient of the loss is estaimated for each sample. This classifier can work with sparse data as the one obtained from building up the features when working with categorical ones. In this case from the types of penalties the algorithm accepts, it uses L2 instead of a combination of L1 and L2 implemented through Elastic Net.
End of explanation
#Once the model has been trained test it on the test dataset
SGD_tuned.fit(X_test, y_test)
# Predict on test set
predtest_y = SGD_tuned.predict(X_test)
Explanation: The parameters show that the smoothing continues to be loose as a first option as it is a regression with a gradient descendent algorithm. Regarding the loss, the hinge loss is used which means that the real loss, in case it is not convergent due to the sparse data used, is replaced by the upper bond forcing its convergence. Time required is significantly higher than with previous classifiers.
End of explanation
#Evaluation of the model (testing)
#Define the Target values
target_names = ['0.0', '1.0', '2.0', '3.0', '4.0', '5.0', '6.0', '7.0', '8.0', '9.0', '10.0', '11.0']
#Print the Classification report
print(('Classification Report: \n {}\n').format(classification_report(y_test, predtest_y,target_names=target_names)))
#Calculate the confusion Matrix
confusion_sgd = confusion_matrix(y_test, predtest_y)
#Print the Confusion Matrix
print(('Confusion Matrix: \n\n {}\n\n').format(confusion_sgd))
#Print the SGD overall accuracy
print(('SGD accuracy: {0:.2f} %\n').format(cross_val_score(SGD_tuned, X_test, y_test,cv=kf).mean()*100))
Explanation: From a visual inspection of the classification report it can be observed how the lack of clear boundaries between data points is impacting the overall accuracy. Only in the case of group 6 the precision is over 90%, for the rest of them the maximum precision obtained is at a maximum of 60%. This will show up when the results are cross validated giving low accuracies.
End of explanation
# Initialize and fit the model.
rf = RandomForestClassifier()
#Tune hyperparameters
#Create range of values to fit parameters
n_estimators_param = np.arange(50,191,10)
max_depth_param = np.arange(1,40,5)
#Fit parameters
parameters = {'n_estimators': n_estimators_param, 'max_depth': max_depth_param}
#Fit parameters using gridsearch
rf_tuned = GridSearchCV(rf, param_grid=parameters, n_jobs = -1, cv=kf, verbose = 1)
#Fit the tunned classifier in the training space
rf_tuned.fit(X_train, y_train)
#Print the best parameters
print(('Best paramenters Random Forest:\n {}\n').format(rf_tuned.best_params_))
Explanation: As the features describing each group are scattered not having clear boundaries between each group, the result obtained from the SGD algorithm is low and it is not expected to grow with a higher number of iterations. In this case and using square hinge the decision boundary will not be able to improve the misclassification of the different points. In any case, the accuracy is too low to be used 47.88%. Although the SGD solves the same classification problems than the logistic regression and can be more efficient in this case the improvement from a computing effort perspective does not compensate the low results obtained by the classifier.
4.5 Random Forest
The hyperparamters of the random forest model will be tuned. The parameters to be tuned are (in the same order as the hyperparameter tuning has been performed):
N_estimators determining the number of trees that will be part of the algorithm.
Max depth determining the size of the tree.
End of explanation
#Once the model has been trained test it on the test dataset
rf_tuned.fit(X_test, y_test)
# Predict on test set
predtest_y = rf_tuned.predict(X_test)
Explanation: The number of trees used is 170 being the depth of each tree 31. After several simulations, the parameters have stayed stable around these values. The random forest algorithm is an ensemble algorithm that works bringing together different decision trees and being more powerful than an individual decision tree. In this case it introduces randomness because it choses from a random sample of features the one that is decreasing how often a randomly chosen element will be incorrectly labelled using gini criterion. The high number of estimators ensure the accuracy of the model while it increases the computational effort required. In this case, it is important to have the classes balanced as in one of the 31 nodes it could happen that one of the minority classes disappear. From the random forest feature selection only "is active", "gender" and "age" add have significant explanatory power being the rest of the features noise to the model. The noise has been reduced by reducing the number ofo features and applying PCA to the model to gain in the explanatory power of the variance. The number of trees in the random forest classifier decreases the risk of overfitting while the number of nodes "depth" reduces the samples available and features available in each sample which can increase the risk of misclassification reducing the overall accuracy. Moreover "deep" trees can compensate the lower risk of overfitting by increasing the number of trees as it increases the probability of overfitting overall.
Once the parameters are tuned, the model is fit and run on the test set. As it can be seen from the hyperparameter tuning, the model requires much more time (computational effort) than the previous models. The increase in accuracy must justify the significant increase of time required to fit the model.
End of explanation
#Evaluation of the model (testing)
#Define the targets
target_names = ['0.0', '1.0', '2.0', '3.0', '4.0', '5.0', '6.0', '7.0', '8.0', '9.0', '10.0', '11.0']
#Print the classification report
print(('Classification Report RF: \n {}\n').format(classification_report(y_test, predtest_y,target_names=target_names)))
#Calculate the confusion matrix
confusion_rf = confusion_matrix(y_test, predtest_y)
#Print the confusion matrix
print(('Confusion Matrix RF: \n\n {}\n\n').format(confusion_rf))
#Print the overall accuracy
print(('Random Forest accuracy RF: {0:.2f} %\n').format(cross_val_score(rf_tuned,
X_test,
y_test, cv=kf).mean()*100))
Explanation: There is a significant increase in the computational effort required by this algorithm as it was expected. The classification report and the classification matrix present overfitting as the precision in all cases is one and there are no misclassified elements. To avoid this overfitting problem, cross validation has been performed on the random forest.
End of explanation
# Initialize and fit the model.
LSVC = LinearSVC(multi_class = 'crammer_singer')
#Tune hyperparameters
#Create range of values to fit parameters
loss_param = ['hinge','squared_hinge']
C_param = [10, 100, 1000]
#Fit parameters
parameters = {'loss': loss_param, 'C': C_param}
#Fit parameters using gridsearch
LSVC_tuned = GridSearchCV(LSVC, param_grid=parameters, n_jobs = -1, cv=kf, verbose = 1)
#Fit the tunned classifier in the training space
LSVC_tuned.fit(X_train, y_train)
#Print the best parameters
print(('Best paramenters Linear SVC:\n {}\n').format(LSVC_tuned.best_params_))
Explanation: In this case, the overall accuracy of the model is 81.04% which is somehow low for this type of algorithms. In this case and after running the random forest feature selection this might have happened due to the additional features that are increasing the noise instead of adding information to the algorithm based on this feature selection process. As there are only four, when run in a set of trees of 31 nodes, it can happen that none of them remains until the end misclassifying results based on the remaining features that the algorithm picks randomly.
4.6 Linear Support Vector Machine
A linear support vector classifier has been set up and tuned on the training data and run on the test set. The hyperparameters that have been tuned are:
C parameter, acting on the margin hyperplane having a bigger margin when C is smaller. (The value of C will tell the SVM how much misclassification is to be avoided).
The loss parameter.
In this case the crammer singer algorithm is used to solve the multiclass classification problem. This algorithm optimizes the joint objective over all classes but it is not interesting from a production standpoint as it rarely leads to better accuracy and is more expensive to compute. Due to the size of the feature´s space the linear SVC has been used first instead of the SVC due to computational restrictions. If the accuracy is high enough then the SVC will be discarded, otherwise it will be tested.
End of explanation
#Once the model has been trained test it on the test dataset
LSVC_tuned.fit(X_test, y_test)
# Predict on test set
predtest_y = LSVC_tuned.predict(X_test)
Explanation: Although the Linear SVC has been implemented as it is more scalable than the support vector classifier, the time required to fit the values compared to the other algorithms makes it a weak candidate to go into production. Compared to the logistic regression classifier there must be a significant increase so that this classifier worth it in terms of computational effort. C has been tuned to 100 to control the misclassification that is allowed by this classifier. The tradeoff between the values of this parameter is the bias-variance trade off. If the parameter is low the classifier will allow small numbers of misclassification having a low bias but allowing a high variance. In our case, the parameter is high which is better from a scaling perspective but might have a high amount of bias under fitting the data in the classification problem. Hinge loss has been selected as the loss function to calculate the weights of the misclassifications on the training data and apply them to the test data.
End of explanation
#Evaluation of the model (testing)
#Define the targets
target_names = ['0.0', '1.0', '2.0', '3.0', '4.0', '5.0', '6.0', '7.0', '8.0', '9.0', '10.0', '11.0']
#Print the classification report
print(('Classification Report: \n {}\n').format(
classification_report(y_test, predtest_y,
target_names=target_names)))
#Calculate the confusion matrix
confusion_svc = confusion_matrix(y_test, predtest_y)
#Print the confusion matrix
print((
'Confusion Matrix: \n\n {}\n\n').format(confusion_svc))
#Print the overall accuracy
print((
'Linear SVC accuracy: {0:.2f} %\n'
).format(cross_val_score(LSVC_tuned, X_test, y_test,cv=kf).mean()*100))
Explanation: Although the computational effort required when fitting the dataset is lower than initially expected, the accuracy is higher than in the case of the random forest and very close to the logistic regression classifier. The classification report and the classification matrix present overfitting as the precision in all cases is one and there are no misclassified elements. To avoid this overfitting problem, cross validation has been performed on the random forest.
End of explanation
# Train model
GBC = GradientBoostingClassifier()
#Tune hyperparameters
#Create range of values to fit parameters
n_estimators_param = np.arange(140,211,10)
max_depth_param = np.arange(30,71,10)
#Fit parameters
parameters = {'n_estimators': n_estimators_param, 'max_depth': max_depth_param}
#Fit parameters
GBC_tuned = GridSearchCV(GBC, param_grid=parameters, n_jobs = -1, cv=kf, verbose = 1)
#Fit the tunned model
GBC_tuned.fit(X_train, y_train)
#The best hyper parameters set
print("Best Hyper Parameters:", GBC_tuned.best_params_)
Explanation: In this case the support vector classifier uses a linear kernel for the kernel trick and a sparse representation of data (aligned to the features that have been generated for this problem) reducing the amount of computing effort required. In this case, there is a need to create linear hyperplanes that is able to separate one class over the rest until the 12 have been classified. Due to the characteristics of the data (PCA components are used as features and are oriented to maximize the explanation of the variance across classes) added to the C parameter the accuracy of the Linear Support Vector Classifier is higher than expected requiring less computational effort than the initially foreseen.
4.7 Gradient Boosting Classifier
The hyperparamters of the gradient boosting classifier that are tuned are the same than in the case of the random forest. The parameters to be tuned are (in the same order as the hyperparameter tuning has been performed):
N_estimators determining the number of trees that will be part of the algorithm.
Max depth determining the size of the tree.
End of explanation
#Fit on the test set
GBC_tuned.fit(X_test, y_test)
# Predict on test set
predtestgb_y = GBC_tuned.predict(X_test)
Explanation: In this case, as it is a boosting model, the data is passed over and over again tuning the parameters every time the data is passed. This is the reason why compared to the random forest it requires so much time. The number of trees is higher than the number of trees used in random forest and the depth is nearly doubling the one previously calculated for the random forest. In this case the computational effort has grown exponentially compared to other classifiers so it is expected that the accuracy is much higher than in the case of the logistic regression classifier to be a candidate for production. In this case, as it is based on random forest a slight increase of its accuracy is expected, hence it will not be as high as the one achieved with the logistic regression for the same reasons that applied to the random forest.
Once the parameters are tuned, the model is fit and run on the test set.
End of explanation
#Evaluation of the model (testing)
#Define the targets
target_names = ['0.0', '1.0', '2.0', '3.0', '4.0', '5.0', '6.0', '7.0', '8.0', '9.0', '10.0', '11.0']
#Print the classification report
print(('Classification Report: \n {}\n').format(classification_report(y_test, predtestgb_y,target_names=target_names)))
#Calculate the confusion matrix
confusion_GBC = confusion_matrix(y_test, predtestgb_y)
#Print the confusion matrix
print(('Confusion Matrix: \n\n {}\n\n').format(confusion_GBC))
#Print the overall accuracy
print(( 'Gradient Boosting Classifier accuracy: {0:.2f} %\n').format(cross_val_score(GBC_tuned
, X_test, y_test,cv=kf).mean()*100))
Explanation: In this case, the algorithm uses the gradient descendent algorithm to follow the steepest path that reduces the loss. In each step the tree is fitted to predict a negative gradient. The friedman_mse parameter used by default calculates the step after the direction has been set. As in the case of Random Forest, this classifier presents overfitting in the classification report and confusion matrix. To reduce the overfitting cross validation is applied.
End of explanation
# Train model
# Initialize and fit the model.
svc = SVC(class_weight='balanced')
#Tune hyperparameters
#Create range of values to fit parameters
C_param = [10,100,1000]
#Fit parameters
parameters = {'C': C_param}
#Fit parameters using gridsearch
svc_tunned = GridSearchCV(svc, param_grid=parameters, n_jobs = -1, cv=kf, verbose = 1)
#Fit the tunned classifier in the training space
svc_tunned.fit(X_train, y_train)
#The best hyper parameters set
print("Best Hyper Parameters:", svc_tunned.best_params_)
Explanation: The gradient boosting algorithm has a similar approach to the random forest in the classification of the classes. In this case the depth of the trees is bigger and the number of trees also. The number of trees helps to reduce the overfitting while the depth has a negative effect in the misclassification reducing the accuracy. The same principle regarding the feature selection applies than in the case of random forest so it is not strange to find in this case an overall accuracy close to the one obtained with random forest. In the implementation of the descendent gradient over the random forest algorithm has not significantly improved the accuracy while it has increased the computational effort required to achieve it. Hence, this algorithm is discarded for production.
4.8 Support Vector Classifier
A support vector classifier has been set up and tuned on the training data and run on the test set. The hyperparameters that have been tuned are:
C parameter, acting on the margin hyperplane having a bigger margin when C is smaller.
End of explanation
#Fit tunned model on Test set
svc_tunned.fit(X_test, y_test)
# Predict on training set
predtestsvc_y = svc_tunned.predict(X_test)
Explanation: The time required to tune the parameters has been lower than expected especially for a dataset as large as ours. The use of a high C aims to classify the training examples correctly by selecting more samples as support vectors. In this case, the use of PC helps to set up the boundaries using data that has been preprocessed to explain the maximum possible variance by rotating it. The model is fit in the test set.
End of explanation
#Evaluation of the model (testing)
#Define the targets
target_names = ['0.0', '1.0', '2.0', '3.0', '4.0', '5.0', '6.0', '7.0', '8.0', '9.0', '10.0', '11.0']
#Print the classification report
print(('Classification Report: \n {}\n').format(classification_report(y_test, predtestsvc_y, target_names=target_names)))
#Calculate the confusion matrix
confusion_SVC = confusion_matrix(y_test, predtestsvc_y)
#Print the confusion matrix
print(('Confusion Matrix: \n\n {}\n\n').format(confusion_SVC))
#Print the overall accuracy
print(( 'SVC accuracy: {0:.2f} %\n').format(cross_val_score(svc_tunned, X_test, y_test,cv=kf).mean()*100))
Explanation: As expected, the confusion matrix and classification report present overfitting. To avoid the overfitting presented in both cases, cross validation is used to fit to obtain the overall accuracy.
End of explanation
#Split data in a train and test set
X_tr, X_te, y_tr, y_te = train_test_split(X_processed, y,test_size=0.3, random_state=42)
#Check the size of each of the sets.
X_tr.shape, X_te.shape, y_tr.shape, y_te.shape
Explanation: In this case the accuracy obtained is 92.29% which is similar to the one obtained with the logistic regression model but it requires less computational effort. This is due to the transformation done when preprocessing the data with PCA as the kernel trick requires less time (the data is already in the axis that maximize the variance) than expected and therefore less computational power. This is a strong candidate to go into production if the PCA is maintained before the algorithm is run as otherwise the time will increase quadratic (as complexity).
This model will be compared the deep learning classification results although this model is preferred as it allows to keep the features (and requires less computational effort) which is better from the perspective of refining the feature generation in the future
4.9 Model Selection - Conclusions
Features have been generated once the dataset has been created using kbest and PCA. The number of features has been reduced to 120 to obtain the highest possible overall accuracy using cross validation over a 70/30 train/test split with five folds. In this case there is no additional weight on misclassification hence, the overall accuracy has been used to measure the accuracy of the models and the time required to fit the test data to measure the computing effort required by each model. The features that have been used are the PC from a PCA as we don´t need to track back to the initial features. The initial kbest analysis and the unsupervised analysis already determines the most important features that can be found in the data without needing to implement them when running the different models. All models have been tuned using gridsearch and the results from higher to lower accuracy are as follows:
Logistic Regression. Accuracy: 95.72%. Computing effort: 3.3 min.
Linear Support Vector Classifier. Accuracy: 94.99%. Computing Effort: 19.9 min.
Support Vector Classifier. Accuracy: 92.29%. Computing effort: 57.3s.
Random Forest. Accuracy: 81.04%. Computing Effort: 81.04%. Computing effort: 7.3 min.
Gradient Boosting Classifier: Accuracy 79.25%. Computing effort: 90.2 min.
K-nearest neighbors. Accuracy: 71.36%. Computing effort: 1.5 min.
SGD Classifier. Accuracy: 47.88%. Computing effort: 9.5 min.
Naïve-Bayes Classifier. Accuracy: 37.93%. Computing effort: 1.5s.
From the abovementioned results the classifiers that are good candidates to go into production are logistic regression due to its high accuracy, simplicity and low computational effort and support vector machine. The latter presents a low computational effort due to the transformation of the features that has been done during the features generation. Regarding support vector machine, it presents scalability problems hence the best candidate remains the logistic regression algorithm. Although deep learning models are also tested, the supervised ones that have been tested in this section are preferred as they allow to track back results to the most relevant features. Furthermore, they require less computational power and are less complex and more transparent form a costumer´s perspective.
5. Deep Learning Classification
To carry out the multiclass classification based on demographics (gender and age) using the apps and brand of the device of the Chinese population sample under analysis, a Multilayer Perceptron has been built. In this case the data requires to be prepared so that it fits the MLP. The purpose of this MLP is to achieve higher accuracy than the supervised learning algorithms used up until now.
As the neural networks work better with scaled data, the processed data has been split into train and test with a 70/30 split. In this case it is not needed to produce the feature generation and selection to achieve high performance with the neural network so the preprocessed raw data is used.
End of explanation
# Convert class vectors to binary class matrices
# So instead of one column with 10 values, create 12 binary columns
y_train_mlp = keras.utils.to_categorical(y_tr, num_classes=12)
y_test_mlp = keras.utils.to_categorical(y_te, num_classes=12)
print(y_train_mlp.shape, y_test_mlp.shape)
Explanation: To match the input requirements of the neural network, the dependent variable is transformed into a categorical sparse matrix. This matrix will have the same number of rows but will create one row per class used in the dependent vector.
End of explanation
#Start the model
model = Sequential()
#Set up the outter layer
model.add(Dense(264, activation='relu', input_dim=274))
# Dropout layers remove features and fight overfitting
model.add(Dropout(0.5))
model.add(Dense(264, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(264, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(264, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(264, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(264, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(264, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
# End with a number of units equal to the number of classes we have for our outcome
model.add(Dense(12, activation='softmax'))
#Model features
model.summary()
# Compile the model to put it all together.
RMS = RMSprop()
model.compile(loss='categorical_crossentropy',optimizer= RMS,metrics=['accuracy'])
Explanation: Although gridsearchCV from sklearn can be used to tune the parameters if the neural network in this case and due to computational restrictions, a trial and error approach has been selected. The process to build the model has been as follows.
Increase the number of layers and with it the batch size increasing the overall accuracy of the model
Increase the size of the hidden neural networks while increasing the dropout rate to reduce overfitting.
Increasing the size of each layer up to 264 increasing the number of trainable parameters which improved the accuracy of the model.
Try different activation functions such as "relu", "elu", "selu" being "relu" the preferred option from an accuracy standpoint is "relu" as it provides higher accuracy.
Introduce the batch normalization, normalizing the input of each neural layer are part of the model architecture and performing the normalization in each mini batch. Both accuracy and speed improve when the batch normalization is used.
Increase the epochs giving time for the neural network to be trained increasing them from 15 to 200 and achieving better results when 200 epochs are used.
Different optimizers have been used: SGD and RMS, giving RMS a better accuracy than SGD when combined with batch normalization (as SDG eliminates the normalization done by the batch normalizer).
The model used is as follows. The input layer has the input dimension of the vector and 264 neurons. It has 5 hidden layers and the output layer has the dimension of the classification vector (12). Between each layer the batch normalization is introduced to reduce the internal covariate shift and an additional dropout is introduced to reduce overfitting. Although the dropouts could be avoided by using the batch normalization, the preferred option is to introduce the dropout to avoid overfitting.
End of explanation
#Run the model
history = model.fit(X_tr, y_train_mlp,
epochs=200,
verbose=1,
batch_size=1250)
#Evaluate the model
score = model.evaluate(X_te, y_test_mlp, verbose=1)
#Print results
print('Test loss:', score[0])
print('Test accuracy:', score[1])
Explanation: After several trials the optimum batch size for the model and epochs are 1250 and 200 respectively. Once the model is trained on the train set is tested and an overall accuracy of 98.91% is achieved. This accuracy is higher than all the accuracies achieved with the previous models.
End of explanation
#Delete column with device_id
uns_final_dataset = final_dataset.drop('device_id', axis = 1)
#Delete columns that are all zeros
uns_final_dataset = uns_final_dataset.drop(uns_final_dataset.columns[(uns_final_dataset == 0).all()], axis = 1)
#Print the first five rows of the new dataset
uns_final_dataset.head()
Explanation: Although the accuracy obtained by this model is higher than the one achieved by any other model, the logistic regression and support vector machine models are the preferred ones as candidates for production. The neural network, although it gives a higher accuracy does not allow to distinguish the explanatory power of each of the features that are used. This is not required during image recognition but is necessary for the purpose of this exercise. Furthermore, the model is far more complex than the previous one and requires more computational power once it is in production. For all this reasons although the accuracy is higher than in the previous cases, the logistic regression and support vector machine models are still the best candidates for production.
6. Unsupervised Clustering
To have a better understanding of the potential clients and relationship between them unsupervised clustering will be carried out. In this case Affinity propagation, Meanshift, Spectral and Kmeans clustering will be compared and one technique will be chosen to cluster the customers and extract meaningful information for the marketing team. Once the clustering is selected, the number of clusters will be selected and the information will be extracted. As in the case of supervised learning the PCA components were used, in this case the dataset is built up to include the information that is going to be analyzed.
End of explanation
#Drop gender, age and group for the analysis and obtain the information describing the dataset
uns_final_dataset_clean= uns_final_dataset.drop(['gender','age','group'],axis=1)
#Extract information
uns_final_dataset_clean.info()
Explanation: The dataset contains information that will not be normalized and that will be used afterwards such as gender, age and group (age range).
End of explanation
#Make a copy of DF
X_tr = uns_final_dataset_clean
#Standardize
X_tr_std = normalize(X_tr)
Explanation: To work with the different clustering techniques a copy of the dataset will be done and the information will be normalized. This will improve the performance of the different clustering techniques.
End of explanation
#Dataframe containing information about the group, age and gender
uns_final_dataset_additional_information = final_dataset[['group','age','gender']]
#Codify the groups into integers
uns_final_dataset_additional_information['group'] = uns_final_dataset_additional_information['group'].map({'M39+' :0,'M32-38':1, 'M29-31':2, 'M27-28':3, 'M23-26':4,'M22-': 5,
'F43+' :6,'F33-42':7, 'F29-32':8, 'F27-28':9, 'F24-26':10, 'F23-':11 })
#Build the indepnedent bariable to check the classfying accuracy of the final clustering technique
y = uns_final_dataset_additional_information['group']
Explanation: A dataframe containing the information about the groups, age and gender is built and the groups are codified into integers. An independent variable is created containing this information to check the accuracy of the clustering technique that is selected.
End of explanation
# Declare the model and fit it.
af = AffinityPropagation().fit(X_tr_std)
# Pull the number of clusters and cluster assignments for each data point.
cluster_centers_indices = af.cluster_centers_indices_
n_clusters_ = len(cluster_centers_indices)
labels = af.labels_
print('Estimated number of clusters: {}'.format(n_clusters_))
Explanation: Once the affinity propagation technique has been tested, the number of clusters is excessive for the data points available reason why this technique is discarded.
End of explanation
# Here we set the bandwidth. This function automatically derives a bandwidth
# number based on an inspection of the distances among points in the data.
for quantile in np.linspace(0.1,1,10,endpoint=False):
bandwidth = estimate_bandwidth(X_tr_std, quantile=quantile, n_samples=5000)
# Declare and fit the model.
ms = MeanShift(bandwidth=bandwidth, bin_seeding=True)
ms.fit(X_tr_std)
# Extract cluster assignments for each data point.
labels = ms.labels_
# Coordinates of the cluster centers.
cluster_centers = ms.cluster_centers_
# Count clusters.
n_clusters_ = len(np.unique(labels))
print('Bandwidth:', quantile)
print("Number of estimated clusters: {}".format(n_clusters_))
Explanation: Once the affinity propagation technique is discarded, the meanshift technique is tested. In this case different bandwidths have been tested to see the kernel density surfaces that better suits the data. Higher bandwidths create a smoother kernel density surface, leading to fewer peaks because smaller hills are smoothed out, whereas lower bandwidths lead to a surface with more peaks.
End of explanation
#Compare from a silhouette_score perspective kmeans against Spectral Clustering
range_n_clusters = np.arange(10)+2
for n_clusters in range_n_clusters:
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the formed
# clusters
# Initialize the clusterer with n_clusters value and a random generator
# seed of 10 for reproducibility.
spec_clust = SpectralClustering(n_clusters=n_clusters)
cluster_labels1 = spec_clust.fit_predict(X_tr_std)
silhouette_avg1 = silhouette_score(X_tr_std, cluster_labels1)
kmeans = KMeans(n_clusters=n_clusters, init='k-means++', n_init=10).fit(X_tr_std)
cluster_labels2 = kmeans.fit_predict(X_tr_std)
silhouette_avg2 = silhouette_score(X_tr_std, cluster_labels2)
print("For n_clusters =", n_clusters,
"av. sil_score for Spec. clust is :", silhouette_avg1,
"av. sil_score for kmeans is :",silhouette_avg2 )
Explanation: The silhouette score is compared between spectral clustering and kmeans. After checking and discarding the Affinity clustering technique due to the number of clusters obtained, both spectral and kmeans are compared to select the best one from a clustering perspective. The number of clusters varies from 2 to 11 (as initially preset) to see which one offers better clusters based on the silhouette score.
End of explanation
# In order to find the optimal number of K we use elbow method.
#Iterate on the number of clusters
cluster_error = []
range_n_clusters = range(2,12, 1)
for k in range_n_clusters:
kmeanModel = KMeans(n_clusters=k, init='k-means++', n_init=11)
kmeanModel.fit(X_tr_std)
cluster_error.append(kmeanModel.inertia_)
#Build DataFrame
clusters_df = pd.DataFrame({ "num_clusters": range_n_clusters , 'cluster_error': cluster_error })
# Plot the elbow Plot
plt.figure(figsize=(10,5))
plt.plot(clusters_df.num_clusters, clusters_df.cluster_error, marker = "o")
plt.xlabel('k')
plt.ylabel('Cluster Error')
plt.title('The Elbow Method')
plt.show()
Explanation: For lower numbers of clusters kmeans present a higher silhouette score while for big number of clusters close to the preset number of groups spectral clustering performs better. Further analysis will be dome from a kmeans clustering perspective to see the best number of clusters for this clustering technique following the elbow technique.
End of explanation
#Cluster the data
#Number of clusters
num_clusters=6
#Cluster the information
kmeans = KMeans(n_clusters=num_clusters, init='k-means++', n_init=10).fit(X_tr_std)
labels = kmeans.labels_
#Glue back to original data
X_tr['clusters'] = labels
X_tr['gender'] = uns_final_dataset.gender
X_tr['age'] = uns_final_dataset.age
X_tr['group'] = uns_final_dataset.group
Explanation: The best number of clusters from both the silhouette and the elbow technique perspective is six that will be the number of clusters used following this technique to cluster the customer base. The data will be clustered using kmeans and 6 clusters to get insights about the customer base. In this case, five, six and seven clusters have been tried being 6 the most relevant one.
End of explanation
clusters = kmeans.fit_predict(X_tr_std)
# Permute the labels
labels = np.zeros_like(clusters)
for i in range(num_clusters):
mask = (clusters == i)
labels[mask] = mode(y[mask])[0]
# Compute the accuracy
print(accuracy_score(y, labels))
Explanation: The predictive capacity of kmeans clustering with six clusters will be checked. In this case the predictive performance is very low 15% compared to the one obtained from the supervised models. Hence its use as a predictive tool is discarded for classification purposes.
End of explanation
#Determine pivot table
X_age = X_tr.pivot_table(values='age', index=["clusters","gender"], aggfunc=[np.mean,np.std])
#Print the age distribution
print(X_age)
Explanation: The data is aggregated by clusters and gender to inspect the average age per cluster. In all clusters the average age is the same standard deviation so it is not representative of the groups
End of explanation
#Show only columns containing apps
filter_col = [col for col in X_tr if col.startswith('label_id')]
#Determine pivot table
X_apps = X_tr.pivot_table(values=filter_col, index=["clusters","gender"], aggfunc=np.sum)
#Print the apps that are more relevant
print(X_apps.idxmax(axis=1))
#Show table
print(X_apps)
Explanation: Information regarding the apps that people use is obtained from the clusters. It can be seen that three apps are the most used ones across clusters App 549, 706 and 548 that according to the documentation equate to Property Industry 1.0, Customized 1 and Industry tag. In the first and third cases they are construction inspection and tagging apps. The second case seems to be an app that is preinstalled in the phone. This might indicate the kind of population we are addressing although the calls are done from all around China. It could be the case that the sample is representative of a specific kind of population and the data has already being segmented reason why the average age in all clusters is nearly the same and around 30 years.
End of explanation
#Filter columns that only have the brands
filter_col = [col for col in X_tr if col.startswith('phone_brand')]
#Determine pivot table
X_phone_brand = X_tr.pivot_table(values=filter_col, index=["clusters",'gender'], aggfunc=np.sum)
#Print the brand that appears more times
print(X_phone_brand.idxmax(axis=1))
#Print the table for further analysis
print(X_phone_brand)
Explanation: In this case and following the same clustering scheme, only information relative to the phone brands has been kept. It appears that for the population under analysis, Xiaomi, OPPO and Samsung are the most popular ones being Vivo more popular among the female than male and Meizu more popular among male compared to female.
End of explanation
# mash the data down into 2 dimensions
ndimensions = 2
#Run PCA analysis and create 2 PC
pca = PCA(n_components=ndimensions, random_state=123)
pca.fit(X_tr_std)
#Transform the PC to arrays to build a dataframe
X_pca_array = pca.transform(X_tr_std)
#Build the dataframe with PCA components
X_pca = pd.DataFrame(X_pca_array, columns=['PC1','PC2']) # PC=principal component
#Build a dataframe copying the result obtained form PCA analysis
df_plot = X_pca.copy()
#Add to the dataframe the labels of the clusters and the information relative to the groups
df_plot['clusters'] = X_tr['clusters']
df_plot['groups'] = y
#Print head
df_plot.head()
Explanation: To be able to plot the different clusters PCA is run and the 2 principal components are extracted. In this case two are preferred to three components due to computational restrictions.
End of explanation
#Plot the clusters using PCA components
#Define the plotting function
def plotData(df, groupby):
"make a scatterplot of the first two principal components of the data, colored by the groupby field"
# make a figure with just one subplot specifying multiple subplots
fig, ax = plt.subplots(figsize = (7,7))
# color map
cmap = mpl.cm.get_cmap('prism')
#plot each cluster on the same graph.
for i, cluster in df.groupby(groupby):
cluster.plot(ax = ax, # need to pass this so all scatterplots are on same graph
kind = 'scatter',
x = 'PC1', y = 'PC2',
color = cmap(i/(num_clusters-1)), # cmap maps a number to a color
label = "%s %i" % (groupby, i),
s=30) # dot size
ax.grid()
ax.axhline(0, color='black')
ax.axvline(0, color='black')
ax.set_title("Principal Components Analysis (PCA) of Mobile Operator Data")
# forked from https://www.kaggle.com/bburns/iris-exploration-pca-k-means-and-gmm-clustering
#Plot the clusters each datapoint was assigned to
plotData(df_plot, 'clusters')
Explanation: Once the PC are defined, a plot function is defined with the characteristics of the plot that is going to be done.
End of explanation |
8,547 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional layers, followed by a fully connected layer. We'll use it to classify handwritten digits in the MNIST dataset, which should be familiar to you by now.
This is not a good network for classfying MNIST digits. You could create a much simpler network and get better results. However, to give you hands-on experience with batch normalization, we had to make an example that was
Step3: Batch Normalization using tf.layers.batch_normalization<a id="example_1"></a>
This version of the network uses tf.layers for almost everything, and expects you to implement batch normalization using tf.layers.batch_normalization
We'll use the following function to create fully connected layers in our network. We'll create them with the specified number of neurons and a ReLU activation function.
This version of the function does not include batch normalization.
Step6: We'll use the following function to create convolutional layers in our network. They are very basic
Step8: Run the following cell, along with the earlier cells (to load the dataset and define the necessary functions).
This cell builds the network without batch normalization, then trains it on the MNIST dataset. It displays loss and accuracy data periodically while training.
Step10: With this many layers, it's going to take a lot of iterations for this network to learn. By the time you're done training these 800 batches, your final test and validation accuracies probably won't be much better than 10%. (It will be different each time, but will most likely be less than 15%.)
Using batch normalization, you'll be able to train this same network to over 90% in that same number of batches.
Add batch normalization
We've copied the previous three cells to get you started. Edit these cells to add batch normalization to the network. For this exercise, you should use tf.layers.batch_normalization to handle most of the math, but you'll need to make a few other changes to your network to integrate batch normalization. You may want to refer back to the lesson notebook to remind yourself of important things, like how your graph operations need to know whether or not you are performing training or inference.
If you get stuck, you can check out the Batch_Normalization_Solutions notebook to see how we did things.
TODO
Step12: TODO
Step13: TODO
Step15: With batch normalization, you should now get an accuracy over 90%. Notice also the last line of the output
Step17: TODO
Step18: TODO | Python Code:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)
Explanation: Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional layers, followed by a fully connected layer. We'll use it to classify handwritten digits in the MNIST dataset, which should be familiar to you by now.
This is not a good network for classfying MNIST digits. You could create a much simpler network and get better results. However, to give you hands-on experience with batch normalization, we had to make an example that was:
1. Complicated enough that training would benefit from batch normalization.
2. Simple enough that it would train quickly, since this is meant to be a short exercise just to give you some practice adding batch normalization.
3. Simple enough that the architecture would be easy to understand without additional resources.
This notebook includes two versions of the network that you can edit. The first uses higher level functions from the tf.layers package. The second is the same network, but uses only lower level functions in the tf.nn package.
Batch Normalization with tf.layers.batch_normalization
Batch Normalization with tf.nn.batch_normalization
The following cell loads TensorFlow, downloads the MNIST dataset if necessary, and loads it into an object named mnist. You'll need to run this cell before running anything else in the notebook.
End of explanation
DO NOT MODIFY THIS CELL
def fully_connected(prev_layer, num_units):
Create a fully connectd layer with the given layer as input and the given number of neurons.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param num_units: int
The size of the layer. That is, the number of units, nodes, or neurons.
:returns Tensor
A new fully connected layer
layer = tf.layers.dense(prev_layer, num_units, activation=tf.nn.relu)
return layer
Explanation: Batch Normalization using tf.layers.batch_normalization<a id="example_1"></a>
This version of the network uses tf.layers for almost everything, and expects you to implement batch normalization using tf.layers.batch_normalization
We'll use the following function to create fully connected layers in our network. We'll create them with the specified number of neurons and a ReLU activation function.
This version of the function does not include batch normalization.
End of explanation
DO NOT MODIFY THIS CELL
def conv_layer(prev_layer, layer_depth):
Create a convolutional layer with the given layer as input.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param layer_depth: int
We'll set the strides and number of feature maps based on the layer's depth in the network.
This is *not* a good way to make a CNN, but it helps us create this example with very little code.
:returns Tensor
A new convolutional layer
strides = 2 if layer_depth % 3 == 0 else 1
conv_layer = tf.layers.conv2d(prev_layer, layer_depth*4, 3, strides, 'same', activation=tf.nn.relu)
return conv_layer
Explanation: We'll use the following function to create convolutional layers in our network. They are very basic: we're always using a 3x3 kernel, ReLU activation functions, strides of 1x1 on layers with odd depths, and strides of 2x2 on layers with even depths. We aren't bothering with pooling layers at all in this network.
This version of the function does not include batch normalization.
End of explanation
DO NOT MODIFY THIS CELL
def train(num_batches, batch_size, learning_rate):
# Build placeholders for the input samples and labels
inputs = tf.placeholder(tf.float32, [None, 28, 28, 1])
labels = tf.placeholder(tf.float32, [None, 10])
# Feed the inputs into a series of 20 convolutional layers
layer = inputs
for layer_i in range(1, 20):
layer = conv_layer(layer, layer_i)
# Flatten the output from the convolutional layers
orig_shape = layer.get_shape().as_list()
layer = tf.reshape(layer, shape=[-1, orig_shape[1] * orig_shape[2] * orig_shape[3]])
# Add one fully connected layer
layer = fully_connected(layer, 100)
# Create the output layer with 1 node for each
logits = tf.layers.dense(layer, 10)
# Define loss and training operations
model_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))
train_opt = tf.train.AdamOptimizer(learning_rate).minimize(model_loss)
# Create operations to test accuracy
correct_prediction = tf.equal(tf.argmax(logits,1), tf.argmax(labels,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Train and test the network
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for batch_i in range(num_batches):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# train this batch
sess.run(train_opt, {inputs: batch_xs, labels: batch_ys})
# Periodically check the validation or training loss and accuracy
if batch_i % 100 == 0:
loss, acc = sess.run([model_loss, accuracy], {inputs: mnist.validation.images,
labels: mnist.validation.labels})
print('Batch: {:>2}: Validation loss: {:>3.5f}, Validation accuracy: {:>3.5f}'.format(batch_i, loss, acc))
elif batch_i % 25 == 0:
loss, acc = sess.run([model_loss, accuracy], {inputs: batch_xs, labels: batch_ys})
print('Batch: {:>2}: Training loss: {:>3.5f}, Training accuracy: {:>3.5f}'.format(batch_i, loss, acc))
# At the end, score the final accuracy for both the validation and test sets
acc = sess.run(accuracy, {inputs: mnist.validation.images,
labels: mnist.validation.labels})
print('Final validation accuracy: {:>3.5f}'.format(acc))
acc = sess.run(accuracy, {inputs: mnist.test.images,
labels: mnist.test.labels})
print('Final test accuracy: {:>3.5f}'.format(acc))
# Score the first 100 test images individually. This won't work if batch normalization isn't implemented correctly.
correct = 0
for i in range(100):
correct += sess.run(accuracy,feed_dict={inputs: [mnist.test.images[i]],
labels: [mnist.test.labels[i]]})
print("Accuracy on 100 samples:", correct/100)
num_batches = 800
batch_size = 64
learning_rate = 0.002
tf.reset_default_graph()
with tf.Graph().as_default():
train(num_batches, batch_size, learning_rate)
Explanation: Run the following cell, along with the earlier cells (to load the dataset and define the necessary functions).
This cell builds the network without batch normalization, then trains it on the MNIST dataset. It displays loss and accuracy data periodically while training.
End of explanation
def fully_connected(prev_layer, num_units, is_training):
Create a fully connectd layer with the given layer as input and the given number of neurons.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param num_units: int
The size of the layer. That is, the number of units, nodes, or neurons.
:returns Tensor
A new fully connected layer
layer = tf.layers.dense(prev_layer, num_units, use_bias = False, activation=None)
layer = tf.layers.batch_normalization(layer, training=is_training)
layer = tf.nn.relu(layer)
return layer
Explanation: With this many layers, it's going to take a lot of iterations for this network to learn. By the time you're done training these 800 batches, your final test and validation accuracies probably won't be much better than 10%. (It will be different each time, but will most likely be less than 15%.)
Using batch normalization, you'll be able to train this same network to over 90% in that same number of batches.
Add batch normalization
We've copied the previous three cells to get you started. Edit these cells to add batch normalization to the network. For this exercise, you should use tf.layers.batch_normalization to handle most of the math, but you'll need to make a few other changes to your network to integrate batch normalization. You may want to refer back to the lesson notebook to remind yourself of important things, like how your graph operations need to know whether or not you are performing training or inference.
If you get stuck, you can check out the Batch_Normalization_Solutions notebook to see how we did things.
TODO: Modify fully_connected to add batch normalization to the fully connected layers it creates. Feel free to change the function's parameters if it helps.
End of explanation
def conv_layer(prev_layer, layer_depth, is_training):
Create a convolutional layer with the given layer as input.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param layer_depth: int
We'll set the strides and number of feature maps based on the layer's depth in the network.
This is *not* a good way to make a CNN, but it helps us create this example with very little code.
:returns Tensor
A new convolutional layer
strides = 2 if layer_depth % 3 == 0 else 1
conv_layer = tf.layers.conv2d(prev_layer, layer_depth*4, 3, strides, 'same', use_bias=False, activation=None)
conv_layer = tf.layers.batch_normalization(conv_layer, training=is_training)
conv_layer = tf.nn.relu(conv_layer)
return conv_layer
Explanation: TODO: Modify conv_layer to add batch normalization to the convolutional layers it creates. Feel free to change the function's parameters if it helps.
End of explanation
def train(num_batches, batch_size, learning_rate):
# Build placeholders for the input samples and labels
inputs = tf.placeholder(tf.float32, [None, 28, 28, 1])
labels = tf.placeholder(tf.float32, [None, 10])
is_training = tf.placeholder(tf.bool)
# Feed the inputs into a series of 20 convolutional layers
layer = inputs
for layer_i in range(1, 20):
layer = conv_layer(layer, layer_i, is_training)
# Flatten the output from the convolutional layers
orig_shape = layer.get_shape().as_list()
layer = tf.reshape(layer, shape=[-1, orig_shape[1] * orig_shape[2] * orig_shape[3]])
# Add one fully connected layer
layer = fully_connected(layer, 100, is_training)
# Create the output layer with 1 node for each
logits = tf.layers.dense(layer, 10)
# Define loss and training operations
model_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
train_opt = tf.train.AdamOptimizer(learning_rate).minimize(model_loss)
# Create operations to test accuracy
correct_prediction = tf.equal(tf.argmax(logits,1), tf.argmax(labels,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Train and test the network
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for batch_i in range(num_batches):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# train this batch
sess.run(train_opt, {inputs: batch_xs, labels: batch_ys, is_training: True})
# Periodically check the validation or training loss and accuracy
if batch_i % 100 == 0:
loss, acc = sess.run([model_loss, accuracy], {inputs: mnist.validation.images,
labels: mnist.validation.labels, is_training:False})
print('Batch: {:>2}: Validation loss: {:>3.5f}, Validation accuracy: {:>3.5f}'.format(batch_i, loss, acc))
elif batch_i % 25 == 0:
loss, acc = sess.run([model_loss, accuracy], {inputs: batch_xs, labels: batch_ys, is_training:False})
print('Batch: {:>2}: Training loss: {:>3.5f}, Training accuracy: {:>3.5f}'.format(batch_i, loss, acc))
# At the end, score the final accuracy for both the validation and test sets
acc = sess.run(accuracy, {inputs: mnist.validation.images,
labels: mnist.validation.labels,
is_training: False})
print('Final validation accuracy: {:>3.5f}'.format(acc))
acc = sess.run(accuracy, {inputs: mnist.test.images,
labels: mnist.test.labels,
is_training:False})
print('Final test accuracy: {:>3.5f}'.format(acc))
# Score the first 100 test images individually. This won't work if batch normalization isn't implemented correctly.
correct = 0
for i in range(100):
correct += sess.run(accuracy,feed_dict={inputs: [mnist.test.images[i]],
labels: [mnist.test.labels[i]],
is_training:False})
print("Accuracy on 100 samples:", correct/100)
num_batches = 800
batch_size = 64
learning_rate = 0.002
tf.reset_default_graph()
with tf.Graph().as_default():
train(num_batches, batch_size, learning_rate)
Explanation: TODO: Edit the train function to support batch normalization. You'll need to make sure the network knows whether or not it is training, and you'll need to make sure it updates and uses its population statistics correctly.
End of explanation
def fully_connected(prev_layer, num_units):
Create a fully connectd layer with the given layer as input and the given number of neurons.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param num_units: int
The size of the layer. That is, the number of units, nodes, or neurons.
:returns Tensor
A new fully connected layer
layer = tf.layers.dense(prev_layer, num_units, activation=tf.nn.relu)
return layer
Explanation: With batch normalization, you should now get an accuracy over 90%. Notice also the last line of the output: Accuracy on 100 samples. If this value is low while everything else looks good, that means you did not implement batch normalization correctly. Specifically, it means you either did not calculate the population mean and variance while training, or you are not using those values during inference.
Batch Normalization using tf.nn.batch_normalization<a id="example_2"></a>
Most of the time you will be able to use higher level functions exclusively, but sometimes you may want to work at a lower level. For example, if you ever want to implement a new feature – something new enough that TensorFlow does not already include a high-level implementation of it, like batch normalization in an LSTM – then you may need to know these sorts of things.
This version of the network uses tf.nn for almost everything, and expects you to implement batch normalization using tf.nn.batch_normalization.
Optional TODO: You can run the next three cells before you edit them just to see how the network performs without batch normalization. However, the results should be pretty much the same as you saw with the previous example before you added batch normalization.
TODO: Modify fully_connected to add batch normalization to the fully connected layers it creates. Feel free to change the function's parameters if it helps.
Note: For convenience, we continue to use tf.layers.dense for the fully_connected layer. By this point in the class, you should have no problem replacing that with matrix operations between the prev_layer and explicit weights and biases variables.
End of explanation
def conv_layer(prev_layer, layer_depth):
Create a convolutional layer with the given layer as input.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param layer_depth: int
We'll set the strides and number of feature maps based on the layer's depth in the network.
This is *not* a good way to make a CNN, but it helps us create this example with very little code.
:returns Tensor
A new convolutional layer
strides = 2 if layer_depth % 3 == 0 else 1
in_channels = prev_layer.get_shape().as_list()[3]
out_channels = layer_depth*4
weights = tf.Variable(
tf.truncated_normal([3, 3, in_channels, out_channels], stddev=0.05))
bias = tf.Variable(tf.zeros(out_channels))
conv_layer = tf.nn.conv2d(prev_layer, weights, strides=[1,strides, strides, 1], padding='SAME')
conv_layer = tf.nn.bias_add(conv_layer, bias)
conv_layer = tf.nn.relu(conv_layer)
return conv_layer
Explanation: TODO: Modify conv_layer to add batch normalization to the fully connected layers it creates. Feel free to change the function's parameters if it helps.
Note: Unlike in the previous example that used tf.layers, adding batch normalization to these convolutional layers does require some slight differences to what you did in fully_connected.
End of explanation
def train(num_batches, batch_size, learning_rate):
# Build placeholders for the input samples and labels
inputs = tf.placeholder(tf.float32, [None, 28, 28, 1])
labels = tf.placeholder(tf.float32, [None, 10])
# Feed the inputs into a series of 20 convolutional layers
layer = inputs
for layer_i in range(1, 20):
layer = conv_layer(layer, layer_i)
# Flatten the output from the convolutional layers
orig_shape = layer.get_shape().as_list()
layer = tf.reshape(layer, shape=[-1, orig_shape[1] * orig_shape[2] * orig_shape[3]])
# Add one fully connected layer
layer = fully_connected(layer, 100)
# Create the output layer with 1 node for each
logits = tf.layers.dense(layer, 10)
# Define loss and training operations
model_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))
train_opt = tf.train.AdamOptimizer(learning_rate).minimize(model_loss)
# Create operations to test accuracy
correct_prediction = tf.equal(tf.argmax(logits,1), tf.argmax(labels,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Train and test the network
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for batch_i in range(num_batches):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# train this batch
sess.run(train_opt, {inputs: batch_xs, labels: batch_ys})
# Periodically check the validation or training loss and accuracy
if batch_i % 100 == 0:
loss, acc = sess.run([model_loss, accuracy], {inputs: mnist.validation.images,
labels: mnist.validation.labels})
print('Batch: {:>2}: Validation loss: {:>3.5f}, Validation accuracy: {:>3.5f}'.format(batch_i, loss, acc))
elif batch_i % 25 == 0:
loss, acc = sess.run([model_loss, accuracy], {inputs: batch_xs, labels: batch_ys})
print('Batch: {:>2}: Training loss: {:>3.5f}, Training accuracy: {:>3.5f}'.format(batch_i, loss, acc))
# At the end, score the final accuracy for both the validation and test sets
acc = sess.run(accuracy, {inputs: mnist.validation.images,
labels: mnist.validation.labels})
print('Final validation accuracy: {:>3.5f}'.format(acc))
acc = sess.run(accuracy, {inputs: mnist.test.images,
labels: mnist.test.labels})
print('Final test accuracy: {:>3.5f}'.format(acc))
# Score the first 100 test images individually. This won't work if batch normalization isn't implemented correctly.
correct = 0
for i in range(100):
correct += sess.run(accuracy,feed_dict={inputs: [mnist.test.images[i]],
labels: [mnist.test.labels[i]]})
print("Accuracy on 100 samples:", correct/100)
num_batches = 800
batch_size = 64
learning_rate = 0.002
tf.reset_default_graph()
with tf.Graph().as_default():
train(num_batches, batch_size, learning_rate)
Explanation: TODO: Edit the train function to support batch normalization. You'll need to make sure the network knows whether or not it is training.
End of explanation |
8,548 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kernel hypothesis testing in Shogun
By Heiko Strathmann - <a href="mailto
Step1: Some Formal Basics (skip if you just want code examples)
To set the context, we here briefly describe statistical hypothesis testing. Informally, one defines a hypothesis on a certain domain and then uses a statistical test to check whether this hypothesis is true. Formally, the goal is to reject a so-called null-hypothesis $H_0$, which is the complement of an alternative-hypothesis $H_A$.
To distinguish the hypotheses, a test statistic is computed on sample data. Since sample data is finite, this corresponds to sampling the true distribution of the test statistic. There are two different distributions of the test statistic -- one for each hypothesis. The null-distribution corresponds to test statistic samples under the model that $H_0$ holds; the alternative-distribution corresponds to test statistic samples under the model that $H_A$ holds.
In practice, one tries to compute the quantile of the test statistic in the null-distribution. In case the test statistic is in a high quantile, i.e. it is unlikely that the null-distribution has generated the test statistic -- the null-hypothesis $H_0$ is rejected.
There are two different kinds of errors in hypothesis testing
Step2: Now how to compare these two sets of samples? Clearly, a t-test would be a bad idea since it basically compares mean and variance of $X$ and $Y$. But we set that to be equal. By chance, the estimates of these statistics might differ, but that is unlikely to be significant. Thus, we have to look at higher order statistics of the samples. In fact, kernel two-sample tests look at all (infinitely many) higher order moments.
Step3: Quadratic Time MMD
We now describe the quadratic time MMD, as described in [1, Lemma 6], which is implemented in Shogun. All methods in this section are implemented in <a href="http
Step4: Any sub-class of <a href="http
Step5: Precomputing Kernel Matrices
Bootstrapping re-computes the test statistic for a bunch of permutations of the test data. For kernel two-sample test methods, in particular those of the MMD class, this means that only the joint kernel matrix of $X$ and $Y$ needs to be permuted. Thus, we can precompute the matrix, which gives a significant performance boost. Note that this is only possible if the matrix can be stored in memory. Below, we use Shogun's <a href="http
Step6: Now let us visualise distribution of MMD statistic under $H_0
Step7: Null and Alternative Distribution Illustrated
Visualise both distributions, $H_0
Step8: Different Ways to Approximate the Null Distribution for the Quadratic Time MMD
As already mentioned, bootstrapping the null distribution is expensive business. There exist a couple of methods that are more sophisticated and either allow very fast approximations without guarantees or reasonably fast approximations that are consistent. We present a selection from [2], which are implemented in Shogun.
The first one is a spectral method that is based around the Eigenspectrum of the kernel matrix of the joint samples. It is faster than bootstrapping while being a consistent test. Effectively, the null-distribution of the biased statistic is sampled, but in a more efficient way than the bootstrapping approach. The converges as
$$
m\mmd^2_b \rightarrow \sum_{l=1}^\infty \lambda_l z_l^2
$$
where $z_l\sim \mathcal{N}(0,2)$ are i.i.d. normal samples and $\lambda_l$ are Eigenvalues of expression 2 in [2], which can be empirically estimated by $\hat\lambda_l=\frac{1}{m}\nu_l$ where $\nu_l$ are the Eigenvalues of the centred kernel matrix of the joint samples $X$ and $Y$. The distribution above can be easily sampled. Shogun's implementation has two parameters
Step9: The above plot of the Eigenspectrum shows that the Eigenvalues are decaying extremely fast. We choose the number for the approximation such that all Eigenvalues bigger than some threshold are used. In this case, we will not loose a lot of accuracy while gaining a significant speedup. For slower decaying Eigenspectrums, this approximation might be more expensive.
Step10: The Gamma Moment Matching Approximation and Type I errors
$\DeclareMathOperator{\var}{var}$
Another method for approximating the null-distribution is by matching the first two moments of a <a href="http
Step11: As we can see, the above example was kind of unfortunate, as the approximation fails badly. We check the type I error to verify that. This works similar to sampling the alternative distribution
Step12: We see that Gamma basically never rejects, which is inline with the fact that the p-value was massively overestimated above. Note that for the other tests, the p-value is also not at its desired value, but this is due to the low number of samples/repetitions in the above code. Increasing them leads to consistent type I errors.
Linear Time MMD on Gaussian Blobs
So far, we basically had to precompute the kernel matrix for reasonable runtimes. This is not possible for more than a few thousand points. The linear time MMD statistic, implemented in <a href="http
Step13: We now describe the linear time MMD, as described in [1, Section 6], which is implemented in Shogun. A fast, unbiased estimate for the original MMD expression which still uses all available data can be obtained by dividing data into two parts and then compute
$$
\mmd_l^2[\mathcal{F},X,Y]=\frac{1}{m_2}\sum_{i=1}^{m_2} k(x_{2i},x_{2i+1})+k(y_{2i},y_{2i+1})-k(x_{2i},y_{2i+1})-
k(x_{2i+1},y_{2i})
$$
where $ m_2=\lfloor\frac{m}{2} \rfloor$. While the above expression assumes that $m$ data are available from each distribution, the statistic in general works in an online setting where features are obtained one by one. Since only pairs of four points are considered at once, this allows to compute it on data streams. In addition, the computational costs are linear in the number of samples that are considered from each distribution. These two properties make the linear time MMD very applicable for large scale two-sample tests. In theory, any number of samples can be processed -- time is the only limiting factor.
We begin by illustrating how to pass data to <a href="http
Step14: Sometimes, one might want to use <a href="http
Step15: The Gaussian Approximation to the Null Distribution
As for any two-sample test in Shogun, bootstrapping can be used to approximate the null distribution. This results in a consistent, but slow test. The number of samples to take is the only parameter. Note that since <a href="http
Step16: Kernel Selection for the MMD -- Overview
$\DeclareMathOperator{\argmin}{arg\,min}
\DeclareMathOperator{\argmax}{arg\,max}$
Now which kernel do we actually use for our tests? So far, we just plugged in arbritary ones. However, for kernel two-sample testing, it is possible to do something more clever.
Shogun's kernel selection methods for MMD based two-sample tests are all based around [3, 4]. For the <a href="http
Step17: Now perform two-sample test with that kernel
Step18: For the linear time MMD, the null and alternative distributions look different than for the quadratic time MMD as plotted above. Let's sample them (takes longer, reduce number of samples a bit). Note how we can tell the linear time MMD to smulate the null hypothesis, which is necessary since we cannot permute by hand as samples are not in memory)
Step19: And visualise again. Note that both null and alternative distribution are Gaussian, which allows the fast null distribution approximation and the optimal kernel selection | Python Code:
%pylab inline
%matplotlib inline
# import all Shogun classes
from modshogun import *
Explanation: Kernel hypothesis testing in Shogun
By Heiko Strathmann - <a href="mailto:heiko.strathmann@gmail.com">heiko.strathmann@gmail.com</a> - <a href="github.com/karlnapf">github.com/karlnapf</a> - <a href="herrstrathmann.de">herrstrathmann.de</a>
This notebook describes Shogun's framework for <a href="http://en.wikipedia.org/wiki/Statistical_hypothesis_testing">statistical hypothesis testing</a>. We begin by giving a brief outline of the problem setting and then describe various implemented algorithms. All the algorithms discussed here are for <a href="http://en.wikipedia.org/wiki/Kernel_embedding_of_distributions#Kernel_two_sample_test">Kernel two-sample testing</a> with Maximum Mean Discrepancy and are based on embedding probability distributions into <a href="http://en.wikipedia.org/wiki/Reproducing_kernel_Hilbert_space">Reproducing Kernel Hilbert Spaces</a>( RKHS ).
Methods for two-sample testing currently consist of tests based on the Maximum Mean Discrepancy. There are two types of tests available, a quadratic time test and a linear time test. Both come in various flavours.
Independence testing is currently based in the Hilbert Schmidt Independence Criterion.
End of explanation
# use scipy for generating samples
from scipy.stats import norm, laplace
def sample_gaussian_vs_laplace(n=220, mu=0.0, sigma2=1, b=sqrt(0.5)):
# sample from both distributions
X=norm.rvs(size=n, loc=mu, scale=sigma2)
Y=laplace.rvs(size=n, loc=mu, scale=b)
return X,Y
mu=0.0
sigma2=1
b=sqrt(0.5)
n=220
X,Y=sample_gaussian_vs_laplace(n, mu, sigma2, b)
# plot both densities and histograms
figure(figsize=(18,5))
suptitle("Gaussian vs. Laplace")
subplot(121)
Xs=linspace(-2, 2, 500)
plot(Xs, norm.pdf(Xs, loc=mu, scale=sigma2))
plot(Xs, laplace.pdf(Xs, loc=mu, scale=b))
title("Densities")
xlabel("$x$")
ylabel("$p(x)$")
_=legend([ 'Gaussian','Laplace'])
subplot(122)
hist(X, alpha=0.5)
xlim([-5,5])
ylim([0,100])
hist(Y,alpha=0.5)
xlim([-5,5])
ylim([0,100])
legend(["Gaussian", "Laplace"])
_=title('Histograms')
Explanation: Some Formal Basics (skip if you just want code examples)
To set the context, we here briefly describe statistical hypothesis testing. Informally, one defines a hypothesis on a certain domain and then uses a statistical test to check whether this hypothesis is true. Formally, the goal is to reject a so-called null-hypothesis $H_0$, which is the complement of an alternative-hypothesis $H_A$.
To distinguish the hypotheses, a test statistic is computed on sample data. Since sample data is finite, this corresponds to sampling the true distribution of the test statistic. There are two different distributions of the test statistic -- one for each hypothesis. The null-distribution corresponds to test statistic samples under the model that $H_0$ holds; the alternative-distribution corresponds to test statistic samples under the model that $H_A$ holds.
In practice, one tries to compute the quantile of the test statistic in the null-distribution. In case the test statistic is in a high quantile, i.e. it is unlikely that the null-distribution has generated the test statistic -- the null-hypothesis $H_0$ is rejected.
There are two different kinds of errors in hypothesis testing:
A type I error is made when $H_0: p=q$ is wrongly rejected. That is, the test says that the samples are from different distributions when they are not.
A type II error is made when $H_A: p\neq q$ is wrongly accepted. That is, the test says that the samples are from the same distribution when they are not.
A so-called consistent test achieves zero type II error for a fixed type I error.
To decide whether to reject $H_0$, one could set a threshold, say at the $95\%$ quantile of the null-distribution, and reject $H_0$ when the test statistic lies below that threshold. This means that the chance that the samples were generated under $H_0$ are $5\%$. We call this number the test power $\alpha$ (in this case $\alpha=0.05$). It is an upper bound on the probability for a type I error. An alternative way is simply to compute the quantile of the test statistic in the null-distribution, the so-called p-value, and to compare the p-value against a desired test power, say $\alpha=0.05$, by hand. The advantage of the second method is that one not only gets a binary answer, but also an upper bound on the type I error.
In order to construct a two-sample test, the null-distribution of the test statistic has to be approximated. One way of doing this for any two-sample test is called bootstrapping, or the permutation test, where samples from both sources are mixed and permuted repeatedly and the test statistic is computed for every of those configurations. While this method works for every statistical hypothesis test, it might be very costly because the test statistic has to be re-computed many times. For many test statistics, there are more sophisticated methods of approximating the null distribution.
Base class for Hypothesis Testing
Shogun implements statistical testing in the abstract class <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CHypothesisTest.html">CHypothesisTest</a>. All implemented methods will work with this interface at their most basic level. This class offers methods to
compute the implemented test statistic,
compute p-values for a given value of the test statistic,
compute a test threshold for a given p-value,
sampling the null distribution, i.e. perform the permutation test or bootstrappig of the null-distribution, and
performing a full two-sample test, and either returning a p-value or a binary rejection decision. This method is most useful in practice. Note that, depending on the used test statistic, it might be faster to call this than to compute threshold and test statistic seperately with the above methods.
There are special subclasses for testing two distributions against each other (<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CTwoSampleTest.html">CTwoSampleTest</a>, <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CIndependenceTest.html">CIndependenceTest</a>), kernel two-sample testing (<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CKernelTwoSampleTest.html">CKernelTwoSampleTest</a>), and kernel independence testing (<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CKernelIndependenceTest.html">CKernelIndependenceTest</a>), which however mostly differ in internals and constructors.
Kernel Two-Sample Testing with the Maximum Mean Discrepancy
$\DeclareMathOperator{\mmd}{MMD}$
An important class of hypothesis tests are the two-sample tests.
In two-sample testing, one tries to find out whether two sets of samples come from different distributions. Given two probability distributions $p,q$ on some arbritary domains $\mathcal{X}, \mathcal{Y}$ respectively, and i.i.d. samples $X={x_i}{i=1}^m\subseteq \mathcal{X}\sim p$ and $Y={y_i}{i=1}^n\subseteq \mathcal{Y}\sim p$, the two sample test distinguishes the hypothesises
\begin{align}
H_0: p=q\
H_A: p\neq q
\end{align}
In order to solve this problem, it is desirable to have a criterion than takes a positive unique value if $p\neq q$, and zero if and only if $p=q$. The so called Maximum Mean Discrepancy (MMD), has this property and allows to distinguish any two probability distributions, if used in a reproducing kernel Hilbert space (RKHS). It is the distance of the mean embeddings $\mu_p, \mu_q$ of the distributions $p,q$ in such a RKHS $\mathcal{F}$ -- which can also be expressed in terms of expectation of kernel functions, i.e.
\begin{align}
\mmd[\mathcal{F},p,q]&=||\mu_p-\mu_q||\mathcal{F}^2\
&=\textbf{E}{x,x'}\left[ k(x,x')\right]-
2\textbf{E}{x,y}\left[ k(x,y)\right]
+\textbf{E}{y,y'}\left[ k(y,y')\right]
\end{align}
Note that this formulation does not assume any form of the input data, we just need a kernel function whose feature space is a RKHS, see [2, Section 2] for details. This has the consequence that in Shogun, we can do tests on any type of data (<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CDenseFeatures.html">CDenseFeatures</a>, <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CSparseFeatures.html">CSparseFeatures</a>, <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CStringFeatures.html">CStringFeatures</a>, etc), as long as we or you provide a positive definite kernel function under the interface of <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CKernel.html">CKernel</a>.
We here only describe how to use the MMD for two-sample testing. Shogun offers two types of test statistic based on the MMD, one with quadratic costs both in time and space, and one with linear time and constant space costs. Both come in different versions and with different methods how to approximate the null-distribution in order to construct a two-sample test.
Running Example Data. Gaussian vs. Laplace
In order to illustrate kernel two-sample testing with Shogun, we use a couple of toy distributions. The first dataset we consider is the 1D Standard Gaussian
$p(x)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(-\frac{(x-\mu)^2}{\sigma^2}\right)$
with mean $\mu$ and variance $\sigma^2$, which is compared against the 1D Laplace distribution
$p(x)=\frac{1}{2b}\exp\left(-\frac{|x-\mu|}{b}\right)$
with the same mean $\mu$ and variance $2b^2$. In order to increase difficulty, we set $b=\sqrt{\frac{1}{2}}$, which means that $2b^2=\sigma^2=1$.
End of explanation
print "Gaussian vs. Laplace"
print "Sample means: %.2f vs %.2f" % (mean(X), mean(Y))
print "Samples variances: %.2f vs %.2f" % (var(X), var(Y))
Explanation: Now how to compare these two sets of samples? Clearly, a t-test would be a bad idea since it basically compares mean and variance of $X$ and $Y$. But we set that to be equal. By chance, the estimates of these statistics might differ, but that is unlikely to be significant. Thus, we have to look at higher order statistics of the samples. In fact, kernel two-sample tests look at all (infinitely many) higher order moments.
End of explanation
# turn data into Shogun representation (columns vectors)
feat_p=RealFeatures(X.reshape(1,len(X)))
feat_q=RealFeatures(Y.reshape(1,len(Y)))
# choose kernel for testing. Here: Gaussian
kernel_width=1
kernel=GaussianKernel(10, kernel_width)
# create mmd instance of test-statistic
mmd=QuadraticTimeMMD(kernel, feat_p, feat_q)
# compute biased and unbiased test statistic (default is unbiased)
mmd.set_statistic_type(BIASED)
biased_statistic=mmd.compute_statistic()
mmd.set_statistic_type(UNBIASED)
unbiased_statistic=mmd.compute_statistic()
print "%d x MMD_b[X,Y]^2=%.2f" % (len(X), biased_statistic)
print "%d x MMD_u[X,Y]^2=%.2f" % (len(X), unbiased_statistic)
Explanation: Quadratic Time MMD
We now describe the quadratic time MMD, as described in [1, Lemma 6], which is implemented in Shogun. All methods in this section are implemented in <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CQuadraticTimeMMD.html">CQuadraticTimeMMD</a>, which accepts any type of features in Shogun, and use it on the above toy problem.
An unbiased estimate for the MMD expression above can be obtained by estimating expected values with averaging over independent samples
$$
\mmd_u[\mathcal{F},X,Y]^2=\frac{1}{m(m-1)}\sum_{i=1}^m\sum_{j\neq i}^mk(x_i,x_j) + \frac{1}{n(n-1)}\sum_{i=1}^n\sum_{j\neq i}^nk(y_i,y_j)-\frac{2}{mn}\sum_{i=1}^m\sum_{j\neq i}^nk(x_i,y_j)
$$
A biased estimate would be
$$
\mmd_b[\mathcal{F},X,Y]^2=\frac{1}{m^2}\sum_{i=1}^m\sum_{j=1}^mk(x_i,x_j) + \frac{1}{n^ 2}\sum_{i=1}^n\sum_{j=1}^nk(y_i,y_j)-\frac{2}{mn}\sum_{i=1}^m\sum_{j\neq i}^nk(x_i,y_j)
.$$
Computing the test statistic using <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CQuadraticTimeMMD.html">CQuadraticTimeMMD</a> does exactly this, where it is possible to choose between the two above expressions. Note that some methods for approximating the null-distribution only work with one of both types. Both statistics' computational costs are quadratic both in time and space. Note that the method returns $m\mmd_b[\mathcal{F},X,Y]^2$ since null distribution approximations work on $m$ times null distribution. Here is how the test statistic itself is computed.
End of explanation
# this is not necessary as bootstrapping is the default
mmd.set_null_approximation_method(PERMUTATION)
mmd.set_statistic_type(UNBIASED)
# to reduce runtime, should be larger practice
mmd.set_num_null_samples(100)
# now show a couple of ways to compute the test
# compute p-value for computed test statistic
p_value=mmd.compute_p_value(unbiased_statistic)
print "P-value of MMD value %.2f is %.2f" % (unbiased_statistic, p_value)
# compute threshold for rejecting H_0 for a given test power
alpha=0.05
threshold=mmd.compute_threshold(alpha)
print "Threshold for rejecting H0 with a test power of %.2f is %.2f" % (alpha, threshold)
# performing the test by hand given the above results, note that those two are equivalent
if unbiased_statistic>threshold:
print "H0 is rejected with confidence %.2f" % alpha
if p_value<alpha:
print "H0 is rejected with confidence %.2f" % alpha
# or, compute the full two-sample test directly
# fixed test power, binary decision
binary_test_result=mmd.perform_test(alpha)
if binary_test_result:
print "H0 is rejected with confidence %.2f" % alpha
significance_test_result=mmd.perform_test()
print "P-value of MMD test is %.2f" % significance_test_result
if significance_test_result<alpha:
print "H0 is rejected with confidence %.2f" % alpha
Explanation: Any sub-class of <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CHypothesisTest.html">CHypothesisTest</a> can compute approximate the null distribution using permutation/bootstrapping. This way always is guaranteed to produce consistent results, however, it might take a long time as for each sample of the null distribution, the test statistic has to be computed for a different permutation of the data. Note that each of the below calls samples from the null distribution. It is wise to choose one method in practice. Also note that we set the number of samples from the null distribution to a low value to reduce runtime. Choose larger in practice, it is in fact good to plot the samples.
End of explanation
# precompute kernel to be faster for null sampling
p_and_q=mmd.get_p_and_q()
kernel.init(p_and_q, p_and_q);
precomputed_kernel=CustomKernel(kernel);
mmd.set_kernel(precomputed_kernel);
# increase number of iterations since should be faster now
mmd.set_num_null_samples(500);
p_value_boot=mmd.perform_test();
print "P-value of MMD test is %.2f" % p_value_boot
Explanation: Precomputing Kernel Matrices
Bootstrapping re-computes the test statistic for a bunch of permutations of the test data. For kernel two-sample test methods, in particular those of the MMD class, this means that only the joint kernel matrix of $X$ and $Y$ needs to be permuted. Thus, we can precompute the matrix, which gives a significant performance boost. Note that this is only possible if the matrix can be stored in memory. Below, we use Shogun's <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CCustomKernel.html">CCustomKernel</a> class, which allows to precompute a kernel matrix (multithreaded) of a given kernel and store it in memory. Instances of this class can then be used as if they were standard kernels.
End of explanation
num_samples=500
# sample null distribution
mmd.set_num_null_samples(num_samples)
null_samples=mmd.sample_null()
# sample alternative distribution, generate new data for that
alt_samples=zeros(num_samples)
for i in range(num_samples):
X=norm.rvs(size=n, loc=mu, scale=sigma2)
Y=laplace.rvs(size=n, loc=mu, scale=b)
feat_p=RealFeatures(reshape(X, (1,len(X))))
feat_q=RealFeatures(reshape(Y, (1,len(Y))))
mmd=QuadraticTimeMMD(kernel, feat_p, feat_q)
alt_samples[i]=mmd.compute_statistic()
Explanation: Now let us visualise distribution of MMD statistic under $H_0:p=q$ and $H_A:p\neq q$. Sample both null and alternative distribution for that. Use the interface of <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CTwoSampleTest.html">CTwoSampleTest</a> to sample from the null distribution (permutations, re-computing of test statistic is done internally). For the alternative distribution, compute the test statistic for a new sample set of $X$ and $Y$ in a loop. Note that the latter is expensive, as the kernel cannot be precomputed, and infinite data is needed. Though it is not needed in practice but only for illustrational purposes here.
End of explanation
def plot_alt_vs_null(alt_samples, null_samples, alpha):
figure(figsize=(18,5))
subplot(131)
hist(null_samples, 50, color='blue')
title('Null distribution')
subplot(132)
title('Alternative distribution')
hist(alt_samples, 50, color='green')
subplot(133)
hist(null_samples, 50, color='blue')
hist(alt_samples, 50, color='green', alpha=0.5)
title('Null and alternative distriution')
# find (1-alpha) element of null distribution
null_samples_sorted=sort(null_samples)
quantile_idx=int(num_samples*(1-alpha))
quantile=null_samples_sorted[quantile_idx]
axvline(x=quantile, ymin=0, ymax=100, color='red', label=str(int(round((1-alpha)*100))) + '% quantile of null')
_=legend()
plot_alt_vs_null(alt_samples, null_samples, alpha)
Explanation: Null and Alternative Distribution Illustrated
Visualise both distributions, $H_0:p=q$ is rejected if a sample from the alternative distribution is larger than the $(1-\alpha)$-quantil of the null distribution. See [1] for more details on their forms. From the visualisations, we can read off the test's type I and type II error:
type I error is the area of the null distribution being right of the threshold
type II error is the area of the alternative distribution being left from the threshold
End of explanation
# optional: plot spectrum of joint kernel matrix
from numpy.linalg import eig
# get joint feature object and compute kernel matrix and its spectrum
feats_p_q=mmd.get_p_and_q()
mmd.get_kernel().init(feats_p_q, feats_p_q)
K=mmd.get_kernel().get_kernel_matrix()
w,_=eig(K)
# visualise K and its spectrum (only up to threshold)
figure(figsize=(18,5))
subplot(121)
imshow(K, interpolation="nearest")
title("Kernel matrix K of joint data $X$ and $Y$")
subplot(122)
thresh=0.1
plot(w[:len(w[w>thresh])])
_=title("Eigenspectrum of K until component %d" % len(w[w>thresh]))
Explanation: Different Ways to Approximate the Null Distribution for the Quadratic Time MMD
As already mentioned, bootstrapping the null distribution is expensive business. There exist a couple of methods that are more sophisticated and either allow very fast approximations without guarantees or reasonably fast approximations that are consistent. We present a selection from [2], which are implemented in Shogun.
The first one is a spectral method that is based around the Eigenspectrum of the kernel matrix of the joint samples. It is faster than bootstrapping while being a consistent test. Effectively, the null-distribution of the biased statistic is sampled, but in a more efficient way than the bootstrapping approach. The converges as
$$
m\mmd^2_b \rightarrow \sum_{l=1}^\infty \lambda_l z_l^2
$$
where $z_l\sim \mathcal{N}(0,2)$ are i.i.d. normal samples and $\lambda_l$ are Eigenvalues of expression 2 in [2], which can be empirically estimated by $\hat\lambda_l=\frac{1}{m}\nu_l$ where $\nu_l$ are the Eigenvalues of the centred kernel matrix of the joint samples $X$ and $Y$. The distribution above can be easily sampled. Shogun's implementation has two parameters:
Number of samples from null-distribution. The more, the more accurate. As a rule of thumb, use 250.
Number of Eigenvalues of the Eigen-decomposition of the kernel matrix to use. The more, the better the results get. However, the Eigen-spectrum of the joint gram matrix usually decreases very fast. Plotting the Spectrum can help. See [2] for details.
If the kernel matrices are diagonal dominant, this method is likely to fail. For that and more details, see the original paper. Computational costs are much lower than bootstrapping, which is the only consistent alternative. Since Eigenvalues of the gram matrix has to be computed, costs are in $\mathcal{O}(m^3)$.
Below, we illustrate how to sample the null distribution and perform two-sample testing with the Spectrum approximation in the class <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CQuadraticTimeMMD.html">CQuadraticTimeMMD</a>. This method only works with the biased statistic.
End of explanation
# threshold for eigenspectrum
thresh=0.1
# compute number of eigenvalues to use
num_eigen=len(w[w>thresh])
# finally, do the test, use biased statistic
mmd.set_statistic_type(BIASED)
#tell Shogun to use spectrum approximation
mmd.set_null_approximation_method(MMD2_SPECTRUM)
mmd.set_num_eigenvalues_spectrum(num_eigen)
mmd.set_num_samples_spectrum(num_samples)
# the usual test interface
p_value_spectrum=mmd.perform_test()
print "Spectrum: P-value of MMD test is %.2f" % p_value_spectrum
# compare with ground truth bootstrapping
mmd.set_null_approximation_method(PERMUTATION)
mmd.set_num_null_samples(num_samples)
p_value_boot=mmd.perform_test()
print "Bootstrapping: P-value of MMD test is %.2f" % p_value_spectrum
Explanation: The above plot of the Eigenspectrum shows that the Eigenvalues are decaying extremely fast. We choose the number for the approximation such that all Eigenvalues bigger than some threshold are used. In this case, we will not loose a lot of accuracy while gaining a significant speedup. For slower decaying Eigenspectrums, this approximation might be more expensive.
End of explanation
# tell Shogun to use gamma approximation
mmd.set_null_approximation_method(MMD2_GAMMA)
# the usual test interface
p_value_gamma=mmd.perform_test()
print "Gamma: P-value of MMD test is %.2f" % p_value_gamma
# compare with ground truth bootstrapping
mmd.set_null_approximation_method(PERMUTATION)
p_value_boot=mmd.perform_test()
print "Bootstrapping: P-value of MMD test is %.2f" % p_value_spectrum
Explanation: The Gamma Moment Matching Approximation and Type I errors
$\DeclareMathOperator{\var}{var}$
Another method for approximating the null-distribution is by matching the first two moments of a <a href="http://en.wikipedia.org/wiki/Gamma_distribution">Gamma distribution</a> and then compute the quantiles of that. This does not result in a consistent test, but usually also gives good results while being very fast. However, there are distributions where the method fail. Therefore, the type I error should always be monitored. Described in [2]. It uses
$$
m\mmd_b(Z) \sim \frac{x^{\alpha-1}\exp(-\frac{x}{\beta})}{\beta^\alpha \Gamma(\alpha)}
$$
where
$$
\alpha=\frac{(\textbf{E}(\text{MMD}_b(Z)))^2}{\var(\text{MMD}_b(Z))} \qquad \text{and} \qquad
\beta=\frac{m \var(\text{MMD}_b(Z))}{(\textbf{E}(\text{MMD}_b(Z)))^2}
$$
Then, any threshold and p-value can be computed using the gamma distribution in the above expression. Computational costs are in $\mathcal{O}(m^2)$. Note that the test is parameter free. It only works with the biased statistic.
End of explanation
# type I error is false alarm, therefore sample data under H0
num_trials=50
rejections_gamma=zeros(num_trials)
rejections_spectrum=zeros(num_trials)
rejections_bootstrap=zeros(num_trials)
num_samples=50
alpha=0.05
for i in range(num_trials):
X=norm.rvs(size=n, loc=mu, scale=sigma2)
Y=laplace.rvs(size=n, loc=mu, scale=b)
# simulate H0 via merging samples before computing the
Z=hstack((X,Y))
X=Z[:len(X)]
Y=Z[len(X):]
feat_p=RealFeatures(reshape(X, (1,len(X))))
feat_q=RealFeatures(reshape(Y, (1,len(Y))))
# gamma
mmd=QuadraticTimeMMD(kernel, feat_p, feat_q)
mmd.set_null_approximation_method(MMD2_GAMMA)
mmd.set_statistic_type(BIASED)
rejections_gamma[i]=mmd.perform_test(alpha)
# spectrum
mmd=QuadraticTimeMMD(kernel, feat_p, feat_q)
mmd.set_null_approximation_method(MMD2_SPECTRUM)
mmd.set_num_eigenvalues_spectrum(num_eigen)
mmd.set_num_samples_spectrum(num_samples)
mmd.set_statistic_type(BIASED)
rejections_spectrum[i]=mmd.perform_test(alpha)
# bootstrap (precompute kernel)
mmd=QuadraticTimeMMD(kernel, feat_p, feat_q)
p_and_q=mmd.get_p_and_q()
kernel.init(p_and_q, p_and_q)
precomputed_kernel=CustomKernel(kernel)
mmd.set_kernel(precomputed_kernel)
mmd.set_null_approximation_method(PERMUTATION)
mmd.set_num_null_samples(num_samples)
mmd.set_statistic_type(BIASED)
rejections_bootstrap[i]=mmd.perform_test(alpha)
convergence_gamma=cumsum(rejections_gamma)/(arange(num_trials)+1)
convergence_spectrum=cumsum(rejections_spectrum)/(arange(num_trials)+1)
convergence_bootstrap=cumsum(rejections_bootstrap)/(arange(num_trials)+1)
print "Average rejection rate of H0 for Gamma is %.2f" % mean(convergence_gamma)
print "Average rejection rate of H0 for Spectrum is %.2f" % mean(convergence_spectrum)
print "Average rejection rate of H0 for Bootstrapping is %.2f" % mean(rejections_bootstrap)
Explanation: As we can see, the above example was kind of unfortunate, as the approximation fails badly. We check the type I error to verify that. This works similar to sampling the alternative distribution: re-sample data (assuming infinite amounts), perform the test and average results. Below we compare type I errors or all methods for approximating the null distribution. This will take a while.
End of explanation
# paramters of dataset
m=20000
distance=10
stretch=5
num_blobs=3
angle=pi/4
# these are streaming features
gen_p=GaussianBlobsDataGenerator(num_blobs, distance, 1, 0)
gen_q=GaussianBlobsDataGenerator(num_blobs, distance, stretch, angle)
# stream some data and plot
num_plot=1000
features=gen_p.get_streamed_features(num_plot)
features=features.create_merged_copy(gen_q.get_streamed_features(num_plot))
data=features.get_feature_matrix()
figure(figsize=(18,5))
subplot(121)
grid(True)
plot(data[0][0:num_plot], data[1][0:num_plot], 'r.', label='$x$')
title('$X\sim p$')
subplot(122)
grid(True)
plot(data[0][num_plot+1:2*num_plot], data[1][num_plot+1:2*num_plot], 'b.', label='$x$', alpha=0.5)
_=title('$Y\sim q$')
Explanation: We see that Gamma basically never rejects, which is inline with the fact that the p-value was massively overestimated above. Note that for the other tests, the p-value is also not at its desired value, but this is due to the low number of samples/repetitions in the above code. Increasing them leads to consistent type I errors.
Linear Time MMD on Gaussian Blobs
So far, we basically had to precompute the kernel matrix for reasonable runtimes. This is not possible for more than a few thousand points. The linear time MMD statistic, implemented in <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CLinearTimeMMD.html">CLinearTimeMMD</a> can help here, as it accepts data under the streaming interface <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CStreamingFeatures.html">CStreamingFeatures</a>, which deliver data one-by-one.
And it can do more cool things, for example choose the best single (or combined) kernel for you. But we need a more fancy dataset for that to show its power. We will use one of Shogun's streaming based data generator, <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CGaussianBlobsDataGenerator.html">CGaussianBlobsDataGenerator</a> for that. This dataset consists of two distributions which are a grid of Gaussians where in one of them, the Gaussians are stretched and rotated. This dataset is regarded as challenging for two-sample testing.
End of explanation
block_size=100
# if features are already under the streaming interface, just pass them
mmd=LinearTimeMMD(kernel, gen_p, gen_q, m, block_size)
# compute an unbiased estimate in linear time
statistic=mmd.compute_statistic()
print "MMD_l[X,Y]^2=%.2f" % statistic
# note: due to the streaming nature, successive calls of compute statistic use different data
# and produce different results. Data cannot be stored in memory
for _ in range(5):
print "MMD_l[X,Y]^2=%.2f" % mmd.compute_statistic()
Explanation: We now describe the linear time MMD, as described in [1, Section 6], which is implemented in Shogun. A fast, unbiased estimate for the original MMD expression which still uses all available data can be obtained by dividing data into two parts and then compute
$$
\mmd_l^2[\mathcal{F},X,Y]=\frac{1}{m_2}\sum_{i=1}^{m_2} k(x_{2i},x_{2i+1})+k(y_{2i},y_{2i+1})-k(x_{2i},y_{2i+1})-
k(x_{2i+1},y_{2i})
$$
where $ m_2=\lfloor\frac{m}{2} \rfloor$. While the above expression assumes that $m$ data are available from each distribution, the statistic in general works in an online setting where features are obtained one by one. Since only pairs of four points are considered at once, this allows to compute it on data streams. In addition, the computational costs are linear in the number of samples that are considered from each distribution. These two properties make the linear time MMD very applicable for large scale two-sample tests. In theory, any number of samples can be processed -- time is the only limiting factor.
We begin by illustrating how to pass data to <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CLinearTimeMMD.html">CLinearTimeMMD</a>. In order not to loose performance due to overhead, it is possible to specify a block size for the data stream.
End of explanation
# data source
gen_p=GaussianBlobsDataGenerator(num_blobs, distance, 1, 0)
gen_q=GaussianBlobsDataGenerator(num_blobs, distance, stretch, angle)
# retreive some points, store them as non-streaming data in memory
data_p=gen_p.get_streamed_features(100)
data_q=gen_q.get_streamed_features(data_p.get_num_vectors())
print "Number of data is %d" % data_p.get_num_vectors()
# cast data in memory as streaming features again (which now stream from the in-memory data)
streaming_p=StreamingRealFeatures(data_p)
streaming_q=StreamingRealFeatures(data_q)
# it is important to start the internal parser to avoid deadlocks
streaming_p.start_parser()
streaming_q.start_parser()
# example to create mmd (note that m can be maximum the number of data in memory)
mmd=LinearTimeMMD(GaussianKernel(10,1), streaming_p, streaming_q, data_p.get_num_vectors(), 1)
print "Linear time MMD statistic: %.2f" % mmd.compute_statistic()
Explanation: Sometimes, one might want to use <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CLinearTimeMMD.html">CLinearTimeMMD</a> with data that is stored in memory. In that case, it is easy to data in the form of for example <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CStreamingDenseFeatures.html">CStreamingDenseFeatures</a> into <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CDenseFeatures.html">CDenseFeatures</a>.
End of explanation
mmd=LinearTimeMMD(kernel, gen_p, gen_q, m, block_size)
print "m=%d samples from p and q" % m
print "Binary test result is: " + ("Rejection" if mmd.perform_test(alpha) else "No rejection")
print "P-value test result is %.2f" % mmd.perform_test()
Explanation: The Gaussian Approximation to the Null Distribution
As for any two-sample test in Shogun, bootstrapping can be used to approximate the null distribution. This results in a consistent, but slow test. The number of samples to take is the only parameter. Note that since <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CLinearTimeMMD.html">CLinearTimeMMD</a> operates on streaming features, new data is taken from the stream in every iteration.
Bootstrapping is not really necessary since there exists a fast and consistent estimate of the null-distribution. However, to ensure that any approximation is accurate, it should always be checked against bootstrapping at least once.
Since both the null- and the alternative distribution of the linear time MMD are Gaussian with equal variance (and different mean), it is possible to approximate the null-distribution by using a linear time estimate for this variance. An unbiased, linear time estimator for
$$
\var[\mmd_l^2[\mathcal{F},X,Y]]
$$
can simply be computed by computing the empirical variance of
$$
k(x_{2i},x_{2i+1})+k(y_{2i},y_{2i+1})-k(x_{2i},y_{2i+1})-k(x_{2i+1},y_{2i}) \qquad (1\leq i\leq m_2)
$$
A normal distribution with this variance and zero mean can then be used as an approximation for the null-distribution. This results in a consistent test and is very fast. However, note that it is an approximation and its accuracy depends on the underlying data distributions. It is a good idea to compare to the bootstrapping approach first to determine an appropriate number of samples to use. This number is usually in the tens of thousands.
<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CLinearTimeMMD.html">CLinearTimeMMD</a> allows to approximate the null distribution in the same pass as computing the statistic itself (in linear time). This should always be used in practice since seperate calls of computing statistic and p-value will operator on different data from the stream. Below, we compute the test on a large amount of data (impossible to perform quadratic time MMD for this one as the kernel matrices cannot be stored in memory)
End of explanation
sigmas=[2**x for x in linspace(-5,5, 10)]
print "Choosing kernel width from", ["{0:.2f}".format(sigma) for sigma in sigmas]
combined=CombinedKernel()
for i in range(len(sigmas)):
combined.append_kernel(GaussianKernel(10, sigmas[i]))
# mmd instance using streaming features
block_size=1000
mmd=LinearTimeMMD(combined, gen_p, gen_q, m, block_size)
# optmal kernel choice is possible for linear time MMD
selection=MMDKernelSelectionOpt(mmd)
# select best kernel
best_kernel=selection.select_kernel()
best_kernel=GaussianKernel.obtain_from_generic(best_kernel)
print "Best single kernel has bandwidth %.2f" % best_kernel.get_width()
Explanation: Kernel Selection for the MMD -- Overview
$\DeclareMathOperator{\argmin}{arg\,min}
\DeclareMathOperator{\argmax}{arg\,max}$
Now which kernel do we actually use for our tests? So far, we just plugged in arbritary ones. However, for kernel two-sample testing, it is possible to do something more clever.
Shogun's kernel selection methods for MMD based two-sample tests are all based around [3, 4]. For the <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CLinearTimeMMD.html">CLinearTimeMMD</a>, [3] describes a way of selecting the optimal kernel in the sense that the test's type II error is minimised. For the linear time MMD, this is the method of choice. It is done via maximising the MMD statistic divided by its standard deviation and it is possible for single kernels and also for convex combinations of them. For the <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CQuadraticTimeMMD.html">CQuadraticTimeMMD</a>, the best method in literature is choosing the kernel that maximised the MMD statistic [4]. For convex combinations of kernels, this can be achieved via a $L2$ norm constraint. A detailed comparison of all methods on numerous datasets can be found in [5].
MMD Kernel selection in Shogun always involves an implementation of the base class <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelection.html">CMMDKernelSelection</a>, which defines the interface for kernel selection. If combinations of kernel should be considered, there is a sub-class <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelectionComb.html">CMMDKernelSelectionComb</a>. In addition, it involves setting up a number of baseline kernels $\mathcal{K}$ to choose from/combine in the form of a <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CCombinedKernel.html">CCombinedKernel</a>. All methods compute their results for a fixed set of these baseline kernels. We later give an example how to use these classes after providing a list of available methods.
<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelectionMedian.html">CMMDKernelSelectionMedian</a> Selects from a set <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CGaussianKernel.html">CGaussianKernel</a> instances the one whose width parameter is closest to the median of the pairwise distances in the data. The median is computed on a certain number of points from each distribution that can be specified as a parameter. Since the median is a stable statistic, one does not have to compute all pairwise distances but rather just a few thousands. This method a useful (and fast) heuristic that in many cases gives a good hint on where to start looking for Gaussian kernel widths. It is for example described in [1]. Note that it may fail badly in selecting a good kernel for certain problems.
<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelectionMax.html">CMMDKernelSelectionMax</a> Selects from a set of arbitrary baseline kernels a single one that maximises the used MMD statistic -- more specific its estimate.
$$
k^*=\argmax_{k\in\mathcal{K}} \hat \eta_k,
$$
where $\eta_k$ is an empirical MMD estimate for using a kernel $k$.
This was first described in [4] and was empirically shown to perform better than the median heuristic above. However, it remains a heuristic that comes with no guarantees. Since MMD estimates can be computed in linear and quadratic time, this method works for both methods. However, for the linear time statistic, there exists a better method.
<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelectionOpt.html">CMMDKernelSelectionOpt</a> Selects the optimal single kernel from a set of baseline kernels. This is done via maximising the ratio of the linear MMD statistic and its standard deviation.
$$
k^=\argmax_{k\in\mathcal{K}} \frac{\hat \eta_k}{\hat\sigma_k+\lambda},
$$
where $\eta_k$ is a linear time MMD estimate for using a kernel $k$ and $\hat\sigma_k$ is a linear time variance estimate of $\eta_k$ to which a small number $\lambda$ is added to prevent division by zero.
These are estimated in a linear time way with the streaming framework that was described earlier. Therefore, this method is only available for <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CLinearTimeMMD.html">CLinearTimeMMD</a>. Optimal here means that the resulting test's type II error is minimised for a fixed type I error. Important: For this method to work, the kernel needs to be selected on different* data than the test is performed on. Otherwise, the method will produce wrong results.
<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelectionCombMaxL2.html">CMMDKernelSelectionCombMaxL2</a> Selects a convex combination of kernels that maximises the MMD statistic. This is the multiple kernel analogous to <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelectionMax.html">CMMDKernelSelectionMax</a>. This is done via solving the convex program
$$
\boldsymbol{\beta}^*=\min_{\boldsymbol{\beta}} {\boldsymbol{\beta}^T\boldsymbol{\beta} : \boldsymbol{\beta}^T\boldsymbol{\eta}=\mathbf{1}, \boldsymbol{\beta}\succeq 0},
$$
where $\boldsymbol{\beta}$ is a vector of the resulting kernel weights and $\boldsymbol{\eta}$ is a vector of which each component contains a MMD estimate for a baseline kernel. See [3] for details. Note that this method is unable to select a single kernel -- even when this would be optimal.
Again, when using the linear time MMD, there are better methods available.
<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelectionCombOpt.html">CMMDKernelSelectionCombOpt</a> Selects a convex combination of kernels that maximises the MMD statistic divided by its covariance. This corresponds to \emph{optimal} kernel selection in the same sense as in class <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelectionOpt.html">CMMDKernelSelectionOpt</a> and is its multiple kernel analogous. The convex program to solve is
$$
\boldsymbol{\beta}^*=\min_{\boldsymbol{\beta}} (\hat Q+\lambda I) {\boldsymbol{\beta}^T\boldsymbol{\beta} : \boldsymbol{\beta}^T\boldsymbol{\eta}=\mathbf{1}, \boldsymbol{\beta}\succeq 0},
$$
where again $\boldsymbol{\beta}$ is a vector of the resulting kernel weights and $\boldsymbol{\eta}$ is a vector of which each component contains a MMD estimate for a baseline kernel. The matrix $\hat Q$ is a linear time estimate of the covariance matrix of the vector $\boldsymbol{\eta}$ to whose diagonal a small number $\lambda$ is added to prevent division by zero. See [3] for details. In contrast to <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelectionCombMaxL2.html">CMMDKernelSelectionCombMaxL2</a>, this method is able to select a single kernel when this gives a lower type II error than a combination. In this sense, it contains <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMMDKernelSelectionOpt.html">CMMDKernelSelectionOpt</a>.
MMD Kernel Selection in Shogun
In order to use one of the above methods for kernel selection, one has to create a new instance of <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CCombinedKernel.html">CCombinedKernel</a> append all desired baseline kernels to it. This combined kernel is then passed to the MMD class. Then, an object of any of the above kernel selection methods is created and the MMD instance is passed to it in the constructor. There are then multiple methods to call
compute_measures to compute a vector kernel selection criteria if a single kernel selection method is used. It will return a vector of selected kernel weights if a combined kernel selection method is used. For \shogunclass{CMMDKernelSelectionMedian}, the method does throw an error.
select_kernel returns the selected kernel of the method. For single kernels this will be one of the baseline kernel instances. For the combined kernel case, this will be the underlying <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CCombinedKernel.html">CCombinedKernel</a> instance where the subkernel weights are set to the weights that were selected by the method.
In order to utilise the selected kernel, it has to be passed to an MMD instance. We now give an example how to select the optimal single and combined kernel for the Gaussian Blobs dataset.
What is the best kernel to use here? This is tricky since the distinguishing characteristics are hidden at a small length-scale. Create some kernels to select the best from
End of explanation
alpha=0.05
mmd=LinearTimeMMD(best_kernel, gen_p, gen_q, m, block_size)
mmd.set_null_approximation_method(MMD1_GAUSSIAN);
p_value_best=mmd.perform_test();
print "Bootstrapping: P-value of MMD test with optimal kernel is %.2f" % p_value_best
Explanation: Now perform two-sample test with that kernel
End of explanation
mmd=LinearTimeMMD(best_kernel, gen_p, gen_q, 5000, block_size)
num_samples=500
# sample null and alternative distribution, implicitly generate new data for that
null_samples=zeros(num_samples)
alt_samples=zeros(num_samples)
for i in range(num_samples):
alt_samples[i]=mmd.compute_statistic()
# tell MMD to merge data internally while streaming
mmd.set_simulate_h0(True)
null_samples[i]=mmd.compute_statistic()
mmd.set_simulate_h0(False)
Explanation: For the linear time MMD, the null and alternative distributions look different than for the quadratic time MMD as plotted above. Let's sample them (takes longer, reduce number of samples a bit). Note how we can tell the linear time MMD to smulate the null hypothesis, which is necessary since we cannot permute by hand as samples are not in memory)
End of explanation
plot_alt_vs_null(alt_samples, null_samples, alpha)
Explanation: And visualise again. Note that both null and alternative distribution are Gaussian, which allows the fast null distribution approximation and the optimal kernel selection
End of explanation |
8,549 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dataset
Step1: RF
Step2: GBT
$$\tilde{x}^m = \tilde{x}^{m-1} - \lambda_m \nabla f(\tilde{x}^{m-1})$$
$$\tilde{y}^m = \tilde{y}^{m-1} - \lambda_m \nabla Q(\tilde{y}^{m-1}, y)$$
$$b_i = learn(X, -\nabla Q(\tilde{y}^{m-1}, y))$$
Example
$$ Q(\tilde{y}^m, y) = \frac12 \sum_{i=1}^L (\tilde{y}i^m - y_i)^2 $$
$$ -\nabla Q(\tilde{y}^m, y)
= -\nabla \left( \frac12 \sum{i=1}^L (\tilde{y}i^m - y_i)^2 \right)
= \sum{i=1}^L (y_i - \tilde{y}_i^m)
$$
AnyBoost
$$ Q(\tilde{y}^m, y) = \frac1L \sum_{i=1}^L \mathcal{L}(\tilde{y}^m y) $$
$$ -\nabla Q(\tilde{y}^m, y)
= -\frac1L \left [\frac{\partial \mathcal{L}(\tilde{y}i^m y_i)}{\partial \tilde{y}_i^m} \right]{i=1}^L
= -\frac1L \left[ \frac{\partial \mathcal{L}(M_i^m)}{\partial M_i^m} y_i \right]_{i=1}^L$$
AdaBoost
$$w_i^m
= - \frac{\partial \mathcal{L}(M_i^m)}{\partial M_i^m} y_i
= - \frac{\partial \exp(-M_i^m)}{\partial M_i^m} y_i
= \exp(-M_i^m)
= \exp \left( -y_i \sum_{t=1}^{m} \lambda_t b_t(x_i) \right)
= \prod_{t=1}^m \exp(-y_i \lambda_t b_t(x_i))
= w_i^{m-1} \exp(-y_i \lambda_m b_m(x_i))
$$ | Python Code:
def ground_truth(x):
return x * np.sin(x) + np.sin(2 * x)
def gen_data(n_samples=200):
np.random.seed(13)
x = np.random.uniform(0, 10, size=n_samples)
x.sort()
y = ground_truth(x) + 0.75 * np.random.normal(size=n_samples)
train_mask = np.random.randint(0, 2, size=n_samples).astype(np.bool)
x_train, y_train = x[train_mask, np.newaxis], y[train_mask]
x_test, y_test = x[~train_mask, np.newaxis], y[~train_mask]
return x_train, x_test, y_train, y_test
X_train, X_test, y_train, y_test = gen_data(200)
x_plot = np.linspace(0, 10, 500)
def plot_data(figsize=(8, 5)):
fig = plt.figure(figsize=figsize)
gt = plt.plot(x_plot, ground_truth(x_plot), alpha=0.4, label='ground truth')
plt.scatter(X_train, y_train, s=10, alpha=0.4)
plt.scatter(X_test, y_test, s=10, alpha=0.4, color='red')
plt.xlim((0, 10))
plt.ylabel('y')
plt.xlabel('x')
plot_data(figsize=(8, 5));
Explanation: Dataset
End of explanation
n_estimators = 1000
rf = RandomForestRegressor(n_estimators=n_estimators, random_state=30)
loss = metrics.mean_squared_error
rf.fit(X_train, y_train)
rf_errors = []
rf_estimators = rf.estimators_
for n in range(1, n_estimators):
rf.estimators_ = rf_estimators[:n]
rf_errors.append(loss(y_test, rf.predict(X_test)))
def plot_errors(*args, fig=None, **kwargs):
ax = gca()
ax.plot(*args, **kwargs)
ax.set_ylim((0, 1.5))
ylabel('MSE')
xlabel('n_estimators')
plot_errors(rf_errors, c='r')
Explanation: RF
End of explanation
def get_ensemble_errors(clf):
clf.fit(X_train, y_train)
train_loss , test_loss= [], []
estimators = clf.estimators_
for n in range(1, n_estimators):
clf.estimators_ = estimators[:n]
train_loss.append(loss(y_train, clf.predict(X_train)))
test_loss.append(loss(y_test, clf.predict(X_test)))
return train_loss , test_loss
sklearn_gbt = GradientBoostingRegressor(
n_estimators=n_estimators,
max_depth=1,
learning_rate=1.0,
random_state=50)
gbt_train_loss , gbt_test_loss = get_ensemble_errors(sklearn_gbt)
plot_errors(rf_errors, c='r', label='RF')
plot_errors(gbt_train_loss, c='b', label='GBT train')
plot_errors(gbt_test_loss, c='g', label='GBT test')
legend();
for clf_args in [
{'subsample': 1, 'learning_rate': 1},
{'subsample': 1, 'learning_rate': 0.1},
{'subsample': 1, 'learning_rate': 0.01},
{'subsample': 0.5, 'learning_rate': 1},
{'subsample': 0.5, 'learning_rate': 0.1},
{'subsample': 0.5, 'learning_rate': 0.01},
]:
clf = GradientBoostingRegressor(
n_estimators=n_estimators,
random_state=50,
**clf_args)
suffix = "subsample: {subsample}; rate: {learning_rate}".format(**clf_args)
train_loss , test_loss = get_ensemble_errors(clf)
# plot_errors(train_loss, label='Train ' + suffix)
plot_errors(test_loss, label='Test ' + suffix + "; Best: {:.3}".format(min(test_loss)))
plot_errors(rf_errors, label='RF test')
ax = gca()
ax.set_ylim((0, 2.5))
legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.);
Explanation: GBT
$$\tilde{x}^m = \tilde{x}^{m-1} - \lambda_m \nabla f(\tilde{x}^{m-1})$$
$$\tilde{y}^m = \tilde{y}^{m-1} - \lambda_m \nabla Q(\tilde{y}^{m-1}, y)$$
$$b_i = learn(X, -\nabla Q(\tilde{y}^{m-1}, y))$$
Example
$$ Q(\tilde{y}^m, y) = \frac12 \sum_{i=1}^L (\tilde{y}i^m - y_i)^2 $$
$$ -\nabla Q(\tilde{y}^m, y)
= -\nabla \left( \frac12 \sum{i=1}^L (\tilde{y}i^m - y_i)^2 \right)
= \sum{i=1}^L (y_i - \tilde{y}_i^m)
$$
AnyBoost
$$ Q(\tilde{y}^m, y) = \frac1L \sum_{i=1}^L \mathcal{L}(\tilde{y}^m y) $$
$$ -\nabla Q(\tilde{y}^m, y)
= -\frac1L \left [\frac{\partial \mathcal{L}(\tilde{y}i^m y_i)}{\partial \tilde{y}_i^m} \right]{i=1}^L
= -\frac1L \left[ \frac{\partial \mathcal{L}(M_i^m)}{\partial M_i^m} y_i \right]_{i=1}^L$$
AdaBoost
$$w_i^m
= - \frac{\partial \mathcal{L}(M_i^m)}{\partial M_i^m} y_i
= - \frac{\partial \exp(-M_i^m)}{\partial M_i^m} y_i
= \exp(-M_i^m)
= \exp \left( -y_i \sum_{t=1}^{m} \lambda_t b_t(x_i) \right)
= \prod_{t=1}^m \exp(-y_i \lambda_t b_t(x_i))
= w_i^{m-1} \exp(-y_i \lambda_m b_m(x_i))
$$
End of explanation |
8,550 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--NAVIGATION-->
< Bonus Materials I | Contents >
Bonus Materials II
Vectorised backtesting
Step1: Experiment With the Training Data Set
Step2: Vectorized Backtesting With the Test Set - Momentum
Note
Step3: Vectorized Backtesting With the Test Set - Reversion
Note | Python Code:
import numpy as np
import pandas as pd
import oandapy
import configparser
%matplotlib inline
import seaborn as sns
import matplotlib.pyplot as plt
config = configparser.ConfigParser()
config.read('../config/config_v1.ini')
account_id = config['oanda']['account_id']
api_key = config['oanda']['api_key']
oanda = oandapy.API(environment="practice",
access_token=api_key)
response = oanda.get_history(instrument="EUR_USD",
granularity="H1",
count = 5000)
res = pd.DataFrame(response['candles'])
res.columns = ['Close_Ask', 'Close_Bid', 'Complete',
'High_Ask', 'High_Bid', 'Low_Ask', 'Low_Bid',
'Open_Ask', 'Open_Bid', 'Time', 'Volume']
res = res.reindex_axis(['Time', 'Open_Bid', 'Open_Ask',
'High_Bid', 'High_Ask', 'Low_Bid',
'Low_Ask', 'Close_Bid', 'Close_Ask',
'Complete', 'Volume'],
axis=1)
df = res[['Time', 'Close_Bid', 'Close_Ask']].copy()
df['rtns'] = res['Close_Bid'].pct_change()
dtrain = df[0:4500].copy()
dtest = df[4500:].copy()
Explanation: <!--NAVIGATION-->
< Bonus Materials I | Contents >
Bonus Materials II
Vectorised backtesting
End of explanation
k = range(1,13)
h = 1
for oo in k:
dtrain['signal'] = np.sign(dtrain['rtns'].rolling(oo).sum())
dtrain['strategy_rtn'] = dtrain['signal'].shift(1) * dtrain['rtns']
res = dtrain['strategy_rtn'].dropna().sum()
print('{0:3} {1:>8.4f}'.format(oo, res))
Explanation: Experiment With the Training Data Set
End of explanation
dtest['signal'] = np.sign(dtest['rtns'].rolling(11).sum())
dtest['result'] = dtest['signal'].shift(1) * dtest['rtns']
dtest['result'].dropna().cumsum().plot(figsize=(10,6));
Explanation: Vectorized Backtesting With the Test Set - Momentum
Note: we use the k=11,h=1 combination as it has the highest returns in the training set
End of explanation
dtest['signal'] = - np.sign(dtest['rtns'].rolling(3).sum())
dtest['result'] = dtest['signal'].shift(1) * dtest['rtns']
dtest['result'].dropna().cumsum().plot(figsize=(10,6));
Explanation: Vectorized Backtesting With the Test Set - Reversion
Note: we use the k=3,h=1 combination as it has the highest returns in the training set for a reversion strategy
End of explanation |
8,551 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Préstamos
Juan David Velásquez Henao
jdvelasq@unal.edu.co
Universidad Nacional de Colombia, Sede Medellín
Facultad de Minas
Medellín, Colombia
Haga click aquí para acceder a la última versión online.
Haga click aquí para ver la última versión online en nbviewer.
Preparación
Step1: Bullet Loan
bullet_loan(amount, nrate, dispoints=0, orgpoints=0, prepmt=None)
En este tipo de préstamo se pagan únicamente intereses durante la vida del crédito; con la última cuota se paga el capital.
amount -- monto del crédito.
nrate -- tasa nominal de interés.
dispoints -- puntos (costo) de descuento como porcentaje de amount. Se consideran como intereses anticipados y son deducibles de impuestos.
orgpoints -- puntos (costo) de constitución como porcentaje de amount. Son costos no deducibles para el pago de impuestos.
prepmt -- flujo de efectivo que representa prepago de la deuda.
Ejemplo.- Modele un préstamo de $ 1000 a una tasa de interés del 10% y una duración de 10 años.
Step2: Ejemplo.-- Para el crédito anterior, suponga que se hace un prepago de la deuda por $ 500 en t = 5.
Step3: Ejemplo.-- Modele el crédito anterior suponiendo que la tasa cambia al 8% a partir de t = 6.
Step4: Balloon loan / tasa fija
fixed_rate_loan(amount, nrate, life, start, pyr=1,
grace=0, dispoints=0, orgpoints=0, prepmt=None,
balloonpmt=None)
En este tipo de crédito la tasa permanece fija durante toda la vida de la deuda. El pago periodico (intereses + capital) es constante. Admite la especificación de cuotas extras (balloon payments) pactadas desde el principio del crédito que tienen como fin reducir el pago períodico.
amount -- monto del crédito.
nrate -- tasa nominal de interés.
life -- plazo del crédito.
start -- especificación del período de inicio del crédito.
pyr -- número de periodos de capitalización por año para la tasa.
grace -- número de períodos de gracia antes del pago del capital.
dispoints -- puntos (costo) de descuento como porcentaje de amount. Se consideran como intereses anticipados y son deducibles de impuestos.
orgpoints -- puntos (costo) de constitución como porcentaje de amount. Son costos no deducibles para el pago de impuestos.
prepmt -- flujo de efectivo que representa prepago de la deuda.
balloonpmt -- pagos extra al pago períodico especificados como un objeto cashflow.
Ejemplo.-- Modele un préstamo de $ 1000 a un plazo de 10 años, cuotas anuales y una tasa del 10%.
Step5: Ejemplo.-- Considere el mismo crédito anterior. ¿Cómo se modifican los pagos períodicos, si se pacta un pago adicional de $ 200 en los períodos 5 y 10?.
Step6: Ejemplo.-- Considere el caso anterior y un prepago de la deuda de $ 100 en los períodos 3 y 7.
Step7: Ejemplo.-- Un crédito bullet puede modelarse como un crédito balloon usando un prepago al final igual al monto de la deuda.
Step8: Abono constante a capital
fixed_ppal_loan(amount, nrate, grace=0, dispoints=0, orgpoints=0,
prepmt=None, balloonpmt=None)
En este tipo de crédito el abono al capital es una cantidad fija durante todos los períodos, de tal forma que el pago total por período es variable (ya que incluye los intereses pagados sobre el saldo de la deuda).
amount -- monto del crédito.
nrate -- tasa nominal de interés.
grace -- número de períodos de gracia antes del pago del capital.
dispoints -- puntos (costo) de descuento como porcentaje de amount. Se consideran como intereses anticipados y son deducibles de impuestos.
orgpoints -- puntos (costo) de constitución como porcentaje de amount. Son costos no deducibles para el pago de impuestos.
prepmt -- flujo de efectivo que representa prepago de la deuda.
balloonpmt -- pagos extra al pago períodico especificados como un objeto cashflow.
Ejemplo.-- Modele un crédito por $ 1000 a 10 años y una tasa del 10%. Los pagos son anuales.
Step9: Buydown loan
buydown_loan(amount, nrate, grace=0, dispoints=0,
orgpoints=0, prepmt=None)
Este tipo de préstamo es similar a los préstamos de cuota fija (balloon loans) pero con tasa cambiante en el tiempo. No admiten cuotas adicionales para reducir el pago fijo períodico. Cuando hay un cambio en la tasa de interés, el pago períodico total se recalcula para reflejar el cambio de tasa de interés.
amount -- monto del crédito.
nrate -- tasa nominal de interés.
grace -- número de períodos de gracia antes del pago del capital.
dispoints -- puntos (costo) de descuento como porcentaje de amount. Se consideran como intereses anticipados y son deducibles de impuestos.
orgpoints -- puntos (costo) de constitución como porcentaje de amount. Son costos no deducibles para el pago de impuestos.
prepmt -- flujo de efectivo que representa prepago de la deuda.
Step10: to_cashflow(tax_rate=0)
Convierte el crédito a un flujo de fondos equivalente.
tax_rate -- impuesto de renta. Se usa para tener en cuenta la reducción del pago por impuesto de renta debido a que los intereses son considerados como costo financiero deducible de impuestos.
Step11: true_rate(tax_rate=0)
Calcula la tasa real del interés del crédito. Permite la comparación de créditos. Para el cálculo, el préstamo es convertido al flujo de efectivo equivalente teniendo en cuenta lo siguiente | Python Code:
# Importa la librería financiera.
# Solo es necesario ejecutar la importación una sola vez.
import cashflows as cf
Explanation: Préstamos
Juan David Velásquez Henao
jdvelasq@unal.edu.co
Universidad Nacional de Colombia, Sede Medellín
Facultad de Minas
Medellín, Colombia
Haga click aquí para acceder a la última versión online.
Haga click aquí para ver la última versión online en nbviewer.
Preparación
End of explanation
cf.bullet_loan(amount=1000,
nrate=cf.interest_rate(const_value=10, periods=11, start=2017, freq='A'),
dispoints=0,
orgpoints=0,
prepmt=None)
## se puede asignar a una variable
x = cf.bullet_loan(amount=1000,
nrate=cf.interest_rate(const_value=10, periods=11, start=2017, freq='A'),
dispoints=0,
orgpoints=0,
prepmt=None)
x
## todos los tipos de créditos tiene funciones
## para obtener las columnas de la tabla de
## amortizacion como un flujo de efectivo
x.Int_Payment
sum(x.Int_Payment)
x.Ppal_Payment ## pagos a capital
x.Beg_Ppal_Amount ## balance inicial del período
x.End_Ppal_Amount ## balance final del período
Explanation: Bullet Loan
bullet_loan(amount, nrate, dispoints=0, orgpoints=0, prepmt=None)
En este tipo de préstamo se pagan únicamente intereses durante la vida del crédito; con la última cuota se paga el capital.
amount -- monto del crédito.
nrate -- tasa nominal de interés.
dispoints -- puntos (costo) de descuento como porcentaje de amount. Se consideran como intereses anticipados y son deducibles de impuestos.
orgpoints -- puntos (costo) de constitución como porcentaje de amount. Son costos no deducibles para el pago de impuestos.
prepmt -- flujo de efectivo que representa prepago de la deuda.
Ejemplo.- Modele un préstamo de $ 1000 a una tasa de interés del 10% y una duración de 10 años.
End of explanation
## tasa de interés
nrate = cf.interest_rate(const_value=[10]*11, start=2018)
## prepago de duda
prepmt = cf.cashflow(const_value=[0]*11, start=2018)
prepmt[5] = 500
## crédito
cf.bullet_loan(amount=1000,
nrate=nrate,
dispoints=0,
orgpoints=0,
prepmt=prepmt)
## Si el prepago es mayor que la deuda, se ajusta el saldo.
prepmt = cf.cashflow(const_value=[0]*11, start=2018)
prepmt[5] = 5000
cf.bullet_loan(amount=1000,
nrate=nrate,
dispoints=0,
orgpoints=0,
prepmt=prepmt)
Explanation: Ejemplo.-- Para el crédito anterior, suponga que se hace un prepago de la deuda por $ 500 en t = 5.
End of explanation
nrate = cf.interest_rate(const_value=[10]*11, start=2018, chgpts={'2023':8})
cf.bullet_loan(amount=1000,
nrate=nrate,
dispoints=0,
orgpoints=0,
prepmt=None)
Explanation: Ejemplo.-- Modele el crédito anterior suponiendo que la tasa cambia al 8% a partir de t = 6.
End of explanation
cf.fixed_rate_loan(amount=1000, # monto
nrate=10, # tasa de interés
freq='A',
life=10, # número de cuotas
start=2018,
grace=0,
dispoints=0,
orgpoints=0,
prepmt=None,
balloonpmt=None)
Explanation: Balloon loan / tasa fija
fixed_rate_loan(amount, nrate, life, start, pyr=1,
grace=0, dispoints=0, orgpoints=0, prepmt=None,
balloonpmt=None)
En este tipo de crédito la tasa permanece fija durante toda la vida de la deuda. El pago periodico (intereses + capital) es constante. Admite la especificación de cuotas extras (balloon payments) pactadas desde el principio del crédito que tienen como fin reducir el pago períodico.
amount -- monto del crédito.
nrate -- tasa nominal de interés.
life -- plazo del crédito.
start -- especificación del período de inicio del crédito.
pyr -- número de periodos de capitalización por año para la tasa.
grace -- número de períodos de gracia antes del pago del capital.
dispoints -- puntos (costo) de descuento como porcentaje de amount. Se consideran como intereses anticipados y son deducibles de impuestos.
orgpoints -- puntos (costo) de constitución como porcentaje de amount. Son costos no deducibles para el pago de impuestos.
prepmt -- flujo de efectivo que representa prepago de la deuda.
balloonpmt -- pagos extra al pago períodico especificados como un objeto cashflow.
Ejemplo.-- Modele un préstamo de $ 1000 a un plazo de 10 años, cuotas anuales y una tasa del 10%.
End of explanation
balloonpmt = cf.cashflow(const_value=[0]*11, start=2018)
balloonpmt['2022'] = 200
balloonpmt['2028'] = 200
cf.fixed_rate_loan(amount=1000, # monto
nrate=10, # tasa de interés por período
life=10, # número de cuotas
start='2018',
grace=0,
dispoints=0,
orgpoints=0,
prepmt=None,
balloonpmt=balloonpmt)
Explanation: Ejemplo.-- Considere el mismo crédito anterior. ¿Cómo se modifican los pagos períodicos, si se pacta un pago adicional de $ 200 en los períodos 5 y 10?.
End of explanation
prepmt = cf.cashflow(const_value=[0]*11, start=2018)
prepmt['2021'] = 100
prepmt['2025'] = 100
cf.fixed_rate_loan(amount=1000,
nrate=10,
life=10,
start=2018,
grace=0,
dispoints=0,
orgpoints=0,
prepmt=prepmt,
balloonpmt=balloonpmt)
Explanation: Ejemplo.-- Considere el caso anterior y un prepago de la deuda de $ 100 en los períodos 3 y 7.
End of explanation
balloonpmt = cf.cashflow(const_value=[0]*11, start=2018)
balloonpmt['2028'] = 1000
cf.fixed_rate_loan(amount=1000,
nrate=10,
life=10,
start=2018,
grace=0,
dispoints=0,
orgpoints=0,
prepmt=None,
balloonpmt=balloonpmt)
Explanation: Ejemplo.-- Un crédito bullet puede modelarse como un crédito balloon usando un prepago al final igual al monto de la deuda.
End of explanation
nrate = cf.interest_rate(const_value=[10]*11, start=2018)
cf.fixed_ppal_loan(amount=1000,
nrate=nrate,
grace=0,
dispoints=0,
orgpoints=0,
prepmt=None,
balloonpmt=None)
##
## período de gracia de 3
##
nrate = cf.interest_rate(const_value=[10]*11, start=2018)
cf.fixed_ppal_loan(amount=1000,
nrate=nrate,
grace=3,
dispoints=0,
orgpoints=0,
prepmt=None,
balloonpmt=None)
##
## este tipo de crédito admite una tasa de interés variable
##
nrate = cf.interest_rate(const_value=[10]*11, start=2018, chgpts={'2024':8})
cf.fixed_ppal_loan(amount=1000,
nrate=nrate,
grace=0,
dispoints=0,
orgpoints=0,
prepmt=None,
balloonpmt=None)
##
## este tipo de crédito admite pagos adicionales
## programados como abono a la deuda
##
nrate = cf.interest_rate(const_value=[10]*11, start=2018)
balloonpmt = cf.cashflow(const_value=[0]*11, start=2018)
balloonpmt['2023'] = 500
cf.fixed_ppal_loan(amount=1000,
nrate=nrate,
grace=0,
dispoints=0,
orgpoints=0,
prepmt=None,
balloonpmt=balloonpmt)
##
## este tipo de crédito admite
## una tasa de interés variable
##
nrate = cf.interest_rate(const_value=[10]*11, start=2018, chgpts={'2024':8})
balloonpmt = cf.cashflow(const_value=[0]*11, start=2018)
balloonpmt['2023'] = 500
cf.fixed_ppal_loan(amount=1000,
nrate=nrate,
grace=0,
dispoints=0,
orgpoints=0,
prepmt=None,
balloonpmt=balloonpmt)
##
## ejemplo anterior con período de gracia
##
nrate = cf.interest_rate(const_value=[10]*11, start=2018, chgpts={'2024':8})
balloonpmt = cf.cashflow(const_value=[0]*11, start=2018)
balloonpmt['2023'] = 500
cf.fixed_ppal_loan(amount=1000,
nrate=nrate,
grace=5,
dispoints=0,
orgpoints=0,
prepmt=None,
balloonpmt=balloonpmt)
Explanation: Abono constante a capital
fixed_ppal_loan(amount, nrate, grace=0, dispoints=0, orgpoints=0,
prepmt=None, balloonpmt=None)
En este tipo de crédito el abono al capital es una cantidad fija durante todos los períodos, de tal forma que el pago total por período es variable (ya que incluye los intereses pagados sobre el saldo de la deuda).
amount -- monto del crédito.
nrate -- tasa nominal de interés.
grace -- número de períodos de gracia antes del pago del capital.
dispoints -- puntos (costo) de descuento como porcentaje de amount. Se consideran como intereses anticipados y son deducibles de impuestos.
orgpoints -- puntos (costo) de constitución como porcentaje de amount. Son costos no deducibles para el pago de impuestos.
prepmt -- flujo de efectivo que representa prepago de la deuda.
balloonpmt -- pagos extra al pago períodico especificados como un objeto cashflow.
Ejemplo.-- Modele un crédito por $ 1000 a 10 años y una tasa del 10%. Los pagos son anuales.
End of explanation
##
## los resultados son iguales a un crédito balloon
##
nrate = cf.interest_rate(const_value=[10]*11, start=2018)
cf.buydown_loan(amount=1000,
nrate=nrate,
dispoints=0,
orgpoints=0,
prepmt=None)
##
## cambios en la tasa de interés
##
nrate = cf.interest_rate(const_value=[10]*11, start=2018, chgpts={'2024':5})
cf.buydown_loan(amount=1000,
nrate=nrate,
dispoints=0,
orgpoints=0,
prepmt=None)
##
## se introducen 2 prepagos por $ 100 cada uno
## en t = 3, 6
##
nrate = cf.interest_rate(const_value=[10]*11, start=2018)
prepmt = cf.cashflow(const_value=[0]*11, start='2018')
prepmt['2021'] = 100
prepmt['2024'] = 100
cf.buydown_loan(amount=1000,
nrate=nrate,
dispoints=0,
orgpoints=0,
prepmt=prepmt)
Explanation: Buydown loan
buydown_loan(amount, nrate, grace=0, dispoints=0,
orgpoints=0, prepmt=None)
Este tipo de préstamo es similar a los préstamos de cuota fija (balloon loans) pero con tasa cambiante en el tiempo. No admiten cuotas adicionales para reducir el pago fijo períodico. Cuando hay un cambio en la tasa de interés, el pago períodico total se recalcula para reflejar el cambio de tasa de interés.
amount -- monto del crédito.
nrate -- tasa nominal de interés.
grace -- número de períodos de gracia antes del pago del capital.
dispoints -- puntos (costo) de descuento como porcentaje de amount. Se consideran como intereses anticipados y son deducibles de impuestos.
orgpoints -- puntos (costo) de constitución como porcentaje de amount. Son costos no deducibles para el pago de impuestos.
prepmt -- flujo de efectivo que representa prepago de la deuda.
End of explanation
nrate = cf.interest_rate(const_value=[10]*11, start=2018)
prepmt = cf.cashflow(const_value=[0]*11, start='2018')
prepmt['2021'] = 100
prepmt['2024'] = 100
cf.buydown_loan(amount=1000,
nrate=nrate,
dispoints=0,
orgpoints=0,
prepmt=prepmt).tocashflow()
Explanation: to_cashflow(tax_rate=0)
Convierte el crédito a un flujo de fondos equivalente.
tax_rate -- impuesto de renta. Se usa para tener en cuenta la reducción del pago por impuesto de renta debido a que los intereses son considerados como costo financiero deducible de impuestos.
End of explanation
nrate = cf.interest_rate(const_value=[10]*11, start=2018)
prepmt = cf.cashflow(const_value=[0]*11, start='2018')
prepmt['2021'] = 100
prepmt['2024'] = 100
cf.buydown_loan(amount=1000,
nrate=nrate,
dispoints=0,
orgpoints=0,
prepmt=prepmt).true_rate()
Explanation: true_rate(tax_rate=0)
Calcula la tasa real del interés del crédito. Permite la comparación de créditos. Para el cálculo, el préstamo es convertido al flujo de efectivo equivalente teniendo en cuenta lo siguiente:
Los puntos de causación son considerados como no deducibles y son ignorados en el cálculo del beneficio del impuesto de renta.
Los puntos de descuento son considerado como intereses prepagados y son deducibles de impuestos.
Si tax_rate es diferente de cero, la tasa de interés verdadera después de impuestos es calculada. Esto implica que en el cálculo solo la porción (1-tax_rate) de los intereses (incluyendo los puntos de descuento) es considerada en el cálculo.
End of explanation |
8,552 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--NAVIGATION-->
< Rates Information | Contents | Order Management >
Account Information
OANDA REST-V20 API Wrapper Doc on Account
OANDA API Getting Started
OANDA API Account
Account Details
Step1: Account List
Step2: Account Summary
Step3: Account Instruments | Python Code:
import pandas as pd
import oandapyV20
import oandapyV20.endpoints.accounts as accounts
import configparser
config = configparser.ConfigParser()
config.read('../config/config_v20.ini')
accountID = config['oanda']['account_id']
access_token = config['oanda']['api_key']
client = oandapyV20.API(access_token=access_token)
r = accounts.AccountDetails(accountID)
client.request(r)
print(r.response)
pd.Series(r.response['account'])
Explanation: <!--NAVIGATION-->
< Rates Information | Contents | Order Management >
Account Information
OANDA REST-V20 API Wrapper Doc on Account
OANDA API Getting Started
OANDA API Account
Account Details
End of explanation
r = accounts.AccountList()
client.request(r)
print(r.response)
Explanation: Account List
End of explanation
r = accounts.AccountSummary(accountID)
client.request(r)
print(r.response)
pd.Series(r.response['account'])
Explanation: Account Summary
End of explanation
r = accounts.AccountInstruments(accountID=accountID, params = "EUR_USD")
client.request(r)
pd.DataFrame(r.response['instruments'])
Explanation: Account Instruments
End of explanation |
8,553 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CD of Vinyl?
Gisteren deed mijn collega de boude uitspraak dat er steeds meer en meer op vinyl uitgebracht werd. Ik vroeg me af hoe sterk die gevoelde stijging was en besloot om snel een grafiekje te maken.
Context
Bij het Muziekcentrum, nu Kunstenpunt, worden releases van Vlaamse artiesten op geperste CDs of vinyl in een databank bijgehouden. Het type van drager is hier een objectief criterium om te bepalen wat er in de databank komt of niet. Dit criterium kan natuurlijk becritiseerd worden -- wat met digitale releases? -- en die discussie loopt continue binnen het Kunstenpunt.
Bovendien moeten we bij deze kleine, speelse oefening ook in het achterhoofd houden dat vele releases zowel op CD als op vinyl uitgebracht worden. Het Muziekcentrum, nu Kunstenpunt, zal dan eerder de vinyl-versie aankopen (omdat de CD versie soms later nog spontaan het archief bereikt). Hierdoor moeten de cijfers heel voorzichtig geïnterpreteerd worden.
Bovendien is het muziekcentrum in 1998 opgericht, en daardoor is de exhaustiviteit van de collectie voor 1998 niet gegarandeerd. Bovendien wil het muziekcentrum, nu Kunstenpunt, ook niet beweren dat het op dit moment exhaustief de collectie kan aanvullen. De gevonden cijfers zijn daardoor dus "tentatief".
De data
Ik heb uit een dump van de muziekcentrum databank de releases tot 2015 eruit gehaad, samen met het type van drager.
Step1: We poetsen het Jaar van uitgave even totdat er inderdaad enkel nog het jaar overblijft. Bovendien focussen we op releases vanaf 1983, het jaar waarin de CD speler op de markt kwam.
Step2: En dan limiteren we de dragers nog tot CDs en Vinyl.
Step3: De grafiek | Python Code:
from pandas import read_csv
df = read_csv("carriers.csv", delimiter=",", quoting=1, escapechar="\\", header=None)
df.columns = ["Titel", "Jaar van uitgave", "Type drager"]
df.head()
Explanation: CD of Vinyl?
Gisteren deed mijn collega de boude uitspraak dat er steeds meer en meer op vinyl uitgebracht werd. Ik vroeg me af hoe sterk die gevoelde stijging was en besloot om snel een grafiekje te maken.
Context
Bij het Muziekcentrum, nu Kunstenpunt, worden releases van Vlaamse artiesten op geperste CDs of vinyl in een databank bijgehouden. Het type van drager is hier een objectief criterium om te bepalen wat er in de databank komt of niet. Dit criterium kan natuurlijk becritiseerd worden -- wat met digitale releases? -- en die discussie loopt continue binnen het Kunstenpunt.
Bovendien moeten we bij deze kleine, speelse oefening ook in het achterhoofd houden dat vele releases zowel op CD als op vinyl uitgebracht worden. Het Muziekcentrum, nu Kunstenpunt, zal dan eerder de vinyl-versie aankopen (omdat de CD versie soms later nog spontaan het archief bereikt). Hierdoor moeten de cijfers heel voorzichtig geïnterpreteerd worden.
Bovendien is het muziekcentrum in 1998 opgericht, en daardoor is de exhaustiviteit van de collectie voor 1998 niet gegarandeerd. Bovendien wil het muziekcentrum, nu Kunstenpunt, ook niet beweren dat het op dit moment exhaustief de collectie kan aanvullen. De gevonden cijfers zijn daardoor dus "tentatief".
De data
Ik heb uit een dump van de muziekcentrum databank de releases tot 2015 eruit gehaad, samen met het type van drager.
End of explanation
def strip(s):
return int(s[0:4])
df["Jaar van uitgave"] = df["Jaar van uitgave"].apply(strip)
df = df[df["Jaar van uitgave"].between(1983, 2015)]
Explanation: We poetsen het Jaar van uitgave even totdat er inderdaad enkel nog het jaar overblijft. Bovendien focussen we op releases vanaf 1983, het jaar waarin de CD speler op de markt kwam.
End of explanation
def rename_levels(s):
if s.startswith("Vinyl"):
return "Vinyl"
else:
return s
df = df[df["Type drager"].isin(["CD", "Vinyl 7''", "Vinyl LP", "Vinyl 12''", "Vinyl 10''"])]
df["Type drager"] = df["Type drager"].apply(rename_levels)
Explanation: En dan limiteren we de dragers nog tot CDs en Vinyl.
End of explanation
from pandas import crosstab
import matplotlib.pyplot as plt
%matplotlib inline
df_ct = crosstab(df["Jaar van uitgave"], df["Type drager"])
df_ct.plot.area(figsize=(15, 5), alpha=0.5)
Explanation: De grafiek
End of explanation |
8,554 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part 2 - Drawing the Network
Drawing the Data
Now that we have a file containing the data that represents our network, we just need to load it and graph it. First, run the cell below by clicking on it and hitting Ctrl-Enter to import all of the utilities we need. You can reach each cell after this one by doing the same thing.
Step1: Let's pick the filename that contains our graph data.
Step2: Changing graph options
Now we can create the graph and draw it. Run the cell below to see the graph. You can try playing around with different ways of representing the graph. Try changing the following options in the code below and then re-running the cell
Step3: Making a really big graph
Let's say you want to save a non-interactive graph that's big enough to display on a large display system. You can use the code cell below to do it. | Python Code:
import wikinetworking as wn
import networkx as nx
import matplotlib.pyplot as plt
from pyquery import PyQuery
%matplotlib inline
print "OK"
Explanation: Part 2 - Drawing the Network
Drawing the Data
Now that we have a file containing the data that represents our network, we just need to load it and graph it. First, run the cell below by clicking on it and hitting Ctrl-Enter to import all of the utilities we need. You can reach each cell after this one by doing the same thing.
End of explanation
filename = "FILL_IN_A_FILENAME.json"
Explanation: Let's pick the filename that contains our graph data.
End of explanation
network = wn.load_dict(filename)
graph = wn.create_graph(network, minimum_weight=1)
layout = nx.spring_layout(graph)
graph_html = wn.make_interactive_graph(graph, pos=layout, cmap=plt.cm.viridis, edge_cmap=plt.cm.Reds)
Explanation: Changing graph options
Now we can create the graph and draw it. Run the cell below to see the graph. You can try playing around with different ways of representing the graph. Try changing the following options in the code below and then re-running the cell:
minimum_weight: The minimum number of links between two articlese before a line will be drawn between them
cmap: The range of colors for nodes. You can choose any color map in the matplotlib colormap reference. The nodes are colored based on their degree, or the number of neighbors a node has
edge_cmap: The range of colors for edges that connect nodes. The edges are colored based on their weight, which is (in this case) the number of links between two neighbors.
You may also try changing the minimum_weight parameter for wn.create_graph. Changing the minimum weight for displaying a relationship creates different clusterings of articles.
End of explanation
wn.save_big_graph(graph, pos=layout, cmap=plt.cm.viridis, edge_cmap=plt.cm.YlOrBr, font_size=1, node_size_factor=5,dpi=800)
Explanation: Making a really big graph
Let's say you want to save a non-interactive graph that's big enough to display on a large display system. You can use the code cell below to do it.
End of explanation |
8,555 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FloPy
ZoneBudget Example
This notebook demonstrates how to use the ZoneBudget class to extract budget information from the cell by cell budget file using an array of zones.
First set the path and import the required packages. The flopy path doesn't have to be set if you install flopy from a binary installer. If you want to run this notebook, you have to set the path to your own flopy path.
Step1: Read File Containing Zones
Using the read_zbarray utility, we can import zonebudget-style array files.
Step2: Extract Budget Information from ZoneBudget Object
At the core of the ZoneBudget object is a numpy structured array. The class provides some wrapper functions to help us interogate the array and save it to disk.
Step3: Convert Units
The ZoneBudget class supports the use of mathematical operators and returns a new copy of the object.
Step4: Alias Names
A dictionary of {zone
Step5: Return the Budgets as a Pandas DataFrame
Set kstpkper and totim keyword args to None (or omit) to return all times.
The get_dataframes() method will return a DataFrame multi-indexed on totim and name.
Step6: Slice the multi-index dataframe to retrieve a subset of the budget
Step7: Look at pumpage (WELLS_OUT) as a percentage of recharge (RECHARGE_IN)
Step8: Pass start_datetime and timeunit keyword arguments to return a dataframe with a datetime multi-index
Step9: Pass index_key to indicate which fields to use in the multi-index (defualt is "totim"; valid keys are "totim" and "kstpkper")
Step10: Write Budget Output to CSV
We can write the resulting recarray to a csv file with the .to_csv() method of the ZoneBudget object. | Python Code:
%matplotlib inline
from __future__ import print_function
import os
import sys
import platform
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
import flopy
print(sys.version)
print('numpy version: {}'.format(np.__version__))
print('matplotlib version: {}'.format(mpl.__version__))
print('pandas version: {}'.format(pd.__version__))
print('flopy version: {}'.format(flopy.__version__))
# Set path to example datafiles
loadpth = os.path.join('..', 'data', 'zonbud_examples')
cbc_f = os.path.join(loadpth, 'freyberg_mlt', 'freyberg.gitcbc')
Explanation: FloPy
ZoneBudget Example
This notebook demonstrates how to use the ZoneBudget class to extract budget information from the cell by cell budget file using an array of zones.
First set the path and import the required packages. The flopy path doesn't have to be set if you install flopy from a binary installer. If you want to run this notebook, you have to set the path to your own flopy path.
End of explanation
from flopy.utils import read_zbarray
zone_file = os.path.join(loadpth, 'zonef_mlt')
zon = read_zbarray(zone_file)
nlay, nrow, ncol = zon.shape
fig = plt.figure(figsize=(10, 4))
for lay in range(nlay):
ax = fig.add_subplot(1, nlay, lay+1)
im = ax.pcolormesh(zon[lay, :, :])
cbar = plt.colorbar(im)
plt.gca().set_aspect('equal')
plt.show()
np.unique(zon)
Explanation: Read File Containing Zones
Using the read_zbarray utility, we can import zonebudget-style array files.
End of explanation
# Create a ZoneBudget object and get the budget record array
zb = flopy.utils.ZoneBudget(cbc_f, zon, kstpkper=(0, 1096))
zb.get_budget()
# Get a list of the unique budget record names
zb.get_record_names()
# Look at a subset of fluxes
names = ['RECHARGE_IN', 'ZONE_1_IN', 'ZONE_3_IN']
zb.get_budget(names=names)
# Look at fluxes in from zone 2
names = ['RECHARGE_IN', 'ZONE_1_IN', 'ZONE_3_IN']
zones = ['ZONE_2']
zb.get_budget(names=names, zones=zones)
# Look at all of the mass-balance records
names = ['TOTAL_IN', 'TOTAL_OUT', 'IN-OUT', 'PERCENT_DISCREPANCY']
zb.get_budget(names=names)
Explanation: Extract Budget Information from ZoneBudget Object
At the core of the ZoneBudget object is a numpy structured array. The class provides some wrapper functions to help us interogate the array and save it to disk.
End of explanation
cmd = flopy.utils.ZoneBudget(cbc_f, zon, kstpkper=(0, 0))
cfd = cmd / 35.3147
inyr = (cfd / (250 * 250)) * 365 * 12
cmdbud = cmd.get_budget()
cfdbud = cfd.get_budget()
inyrbud = inyr.get_budget()
names = ['RECHARGE_IN']
rowidx = np.in1d(cmdbud['name'], names)
colidx = 'ZONE_1'
print('{:,.1f} cubic meters/day'.format(cmdbud[rowidx][colidx][0]))
print('{:,.1f} cubic feet/day'.format(cfdbud[rowidx][colidx][0]))
print('{:,.1f} inches/year'.format(inyrbud[rowidx][colidx][0]))
cmd is cfd
Explanation: Convert Units
The ZoneBudget class supports the use of mathematical operators and returns a new copy of the object.
End of explanation
aliases = {1: 'SURF', 2:'CONF', 3: 'UFA'}
zb = flopy.utils.ZoneBudget(cbc_f, zon, totim=[1097.], aliases=aliases)
zb.get_budget()
Explanation: Alias Names
A dictionary of {zone: "alias"} pairs can be passed to replace the typical "ZONE_X" fieldnames of the ZoneBudget structured array with more descriptive names.
End of explanation
zon = np.ones((nlay, nrow, ncol), np.int)
zon[1, :, :] = 2
zon[2, :, :] = 3
aliases = {1: 'SURF', 2:'CONF', 3: 'UFA'}
zb = flopy.utils.ZoneBudget(cbc_f, zon, kstpkper=None, totim=None, aliases=aliases)
df = zb.get_dataframes()
print(df.head())
print(df.tail())
Explanation: Return the Budgets as a Pandas DataFrame
Set kstpkper and totim keyword args to None (or omit) to return all times.
The get_dataframes() method will return a DataFrame multi-indexed on totim and name.
End of explanation
dateidx1 = 1092.
dateidx2 = 1097.
names = ['RECHARGE_IN', 'WELLS_OUT']
zones = ['SURF', 'CONF']
df.loc[(slice(dateidx1, dateidx2), names), :][zones]
Explanation: Slice the multi-index dataframe to retrieve a subset of the budget
End of explanation
dateidx1 = 1092.
dateidx2 = 1097.
zones = ['SURF']
# Pull out the individual records of interest
rech = df.loc[(slice(dateidx1, dateidx2), ['RECHARGE_IN']), :][zones]
pump = df.loc[(slice(dateidx1, dateidx2), ['WELLS_OUT']), :][zones]
# Remove the "record" field from the index so we can
# take the difference of the two DataFrames
rech = rech.reset_index()
rech = rech.set_index(['totim'])
rech = rech[zones]
pump = pump.reset_index()
pump = pump.set_index(['totim'])
pump = pump[zones] * -1
# Compute pumping as a percentage of recharge
pump_as_pct = (pump / rech) * 100.
pump_as_pct
# Use "slice(None)" to return all records
df.loc[(slice(dateidx1, dateidx2), slice(None)), :][zones]
# Or all times
df.loc[(slice(None), names), :][zones]
Explanation: Look at pumpage (WELLS_OUT) as a percentage of recharge (RECHARGE_IN)
End of explanation
df = zb.get_dataframes(start_datetime='1970-01-01', timeunit='D')
dateidx1 = pd.Timestamp('1972-12-01')
dateidx2 = pd.Timestamp('1972-12-06')
names = ['RECHARGE_IN', 'WELLS_OUT']
zones = ['SURF', 'CONF']
df.loc[(slice(dateidx1, dateidx2), names), :][zones]
Explanation: Pass start_datetime and timeunit keyword arguments to return a dataframe with a datetime multi-index
End of explanation
df = zb.get_dataframes(index_key='kstpkper')
df.head()
Explanation: Pass index_key to indicate which fields to use in the multi-index (defualt is "totim"; valid keys are "totim" and "kstpkper")
End of explanation
zb = flopy.utils.ZoneBudget(cbc_f, zon, kstpkper=[(0, 0), (0, 1096)])
zb.to_csv(os.path.join(loadpth, 'zonbud.csv'))
# Read the file in to see the contents
fname = os.path.join(loadpth, 'zonbud.csv')
try:
import pandas as pd
print(pd.read_csv(fname).to_string(index=False))
except:
with open(fname, 'r') as f:
for line in f.readlines():
print('\t'.join(line.split(',')))
Explanation: Write Budget Output to CSV
We can write the resulting recarray to a csv file with the .to_csv() method of the ZoneBudget object.
End of explanation |
8,556 | Given the following text description, write Python code to implement the functionality described.
Description:
Range and Update Sum Queries with Factorial
Python3 program to calculate sum of factorials in an interval and update with two types of operations ; Modulus ; Maximum size of input array ; Size for factorial array ; structure for queries with members type , leftIndex , rightIndex of the query ; function for updating the value ; function for calculating the required sum between two indexes ; function to return answer to queries ; Precomputing factorials ; Declaring a Set ; inserting indexes of those numbers which are lesser than 40 ; update query of the 1 st type ; find the left index of query in the set using binary search ; if it crosses the right index of query or end of set , then break ; update the value of arr [ i ] to its new value ; if updated value becomes greater than or equal to 40 remove it from the set ; increment the index ; update query of the 2 nd type ; update the value to its new value ; If the value is less than 40 , insert it into set , otherwise remove it ; sum query of the 3 rd type ; Driver Code ; input array using 1 - based indexing ; declaring array of structure of type queries ; answer the Queries
| Python Code:
from bisect import bisect_left as lower_bound
MOD = 1e9
MAX = 100
SZ = 40
BIT =[0 ] *(MAX + 1 )
fact =[0 ] *(SZ + 1 )
class queries :
def __init__(self , tpe , l , r ) :
self . type = tpe
self . l = l
self . r = r
def update(x , val , n ) :
global BIT
while x <= n :
BIT[x ] += val
x += x & - x
def summ(x ) :
global BIT
s = 0
while x > 0 :
s += BIT[x ]
x -= x & - x
return s
def answerQueries(arr : list , que : list , n : int , q : int ) :
global fact
fact[0 ] = 1
for i in range(1 , 41 ) :
fact[i ] = int(( fact[i - 1 ] * i ) % MOD )
s = set()
for i in range(1 , n ) :
if arr[i ] < 40 :
s . add(i )
update(i , fact[arr[i ] ] , n )
else :
update(i , 0 , n )
for i in range(q ) :
if que[i ] . type == 1 :
while True :
s = list(s )
s . sort()
it = lower_bound(s , que[i ] . l )
if it == len(s ) or s[it ] > que[i ] . r :
break
que[i ] . l = s[it ]
val = arr[s[it ] ] + 1
update(s[it ] , fact[val ] - fact[arr[s[it ] ] ] , n )
arr[s[it ] ] += 1
if arr[s[it ] ] >= 40 :
s . remove(it )
que[i ] . l += 1
elif que[i ] . type == 2 :
s = set(s )
idx = que[i ] . l
val = que[i ] . r
update(idx , fact[val ] - fact[arr[idx ] ] , n )
arr[idx ] = val
if val < 40 :
s . add(idx )
else :
s . remove(idx )
else :
print(( summ(que[i ] . r ) - summ(que[i ] . l - 1 ) ) )
if __name__== "__main __":
q = 6
arr =[0 , 1 , 2 , 1 , 4 , 5 ]
n = len(arr )
que =[queries(3 , 1 , 5 ) , queries(1 , 1 , 3 ) , queries(2 , 2 , 4 ) , queries(3 , 2 , 4 ) , queries(1 , 2 , 5 ) , queries(3 , 1 , 5 ) ]
answerQueries(arr , que , n , q )
|
8,557 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example
Consider sequences that are increasingly different. EDeN allows to turn them into vectors, whose similarity is decreasing.
Step1: Build an artificial dataset
Step2: define a function that builds a graph from a string, i.e. the path graph with the characters as node labels
Step3: make a generator that yields graphs
Step4: initialize the vectorizer object with the desired 'resolution'
Step5: obtain an iterator over the sequences processed into graphs
Step6: compute the vector encoding of each instance in a sparse data matrix
Step7: compute the pairwise similarity as the dot product between the vector representations of each sequence
Step8: visualize it as a picture is worth thousand words... | Python Code:
%matplotlib inline
Explanation: Example
Consider sequences that are increasingly different. EDeN allows to turn them into vectors, whose similarity is decreasing.
End of explanation
import random
def make_data(size):
text = ''.join([str(unichr(97+i)) for i in range(26)])
seqs = []
def swap_two_characters(seq):
'''define a function that swaps two characters at random positions in a string '''
line = list(seq)
id_i = random.randint(0,len(line)-1)
id_j = random.randint(0,len(line)-1)
line[id_i], line[id_j] = line[id_j], line[id_i]
return ''.join(line)
for i in range(size):
text = swap_two_characters( text )
seqs.append( text )
print text
return seqs
seqs = make_data(25)
Explanation: Build an artificial dataset: starting from the string 'abcdefghijklmnopqrstuvwxyz', generate iteratively strings by swapping two characters at random. In this way instances are progressively more dissimilar
End of explanation
import networkx as nx
def sequence_to_graph(seq):
'''convert a sequence into a EDeN 'compatible' graph
i.e. a graph with the attribute 'label' for every node and edge'''
G = nx.Graph()
for id,character in enumerate(seq):
G.add_node(id, label = character )
if id > 0:
G.add_edge(id-1, id, label = '-')
return G
Explanation: define a function that builds a graph from a string, i.e. the path graph with the characters as node labels
End of explanation
def pre_process(iterable):
for seq in iterable:
yield sequence_to_graph(seq)
Explanation: make a generator that yields graphs: generators are 'good' as they allow functional composition
End of explanation
%%time
from eden.graph import Vectorizer
vectorizer = Vectorizer( complexity = 4 )
Explanation: initialize the vectorizer object with the desired 'resolution'
End of explanation
%%time
graphs = pre_process( seqs )
Explanation: obtain an iterator over the sequences processed into graphs
End of explanation
%%time
X = vectorizer.transform( graphs )
print 'Instances: %d ; Features: %d with an avg of %d features per instance' % (X.shape[0], X.shape[1], X.getnnz()/X.shape[0])
Explanation: compute the vector encoding of each instance in a sparse data matrix
End of explanation
from sklearn import metrics
K=metrics.pairwise.pairwise_kernels(X, metric='linear')
print K
Explanation: compute the pairwise similarity as the dot product between the vector representations of each sequence
End of explanation
import pylab as plt
plt.figure( figsize=(8,8) )
img = plt.imshow( K, interpolation='none', cmap=plt.get_cmap( 'YlOrRd' ) )
plt.show()
Explanation: visualize it as a picture is worth thousand words...
End of explanation |
8,558 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
verify pyEMU null space projection with the freyberg problem
Step1: instaniate pyemu object and drop prior info. Then reorder the jacobian and save as binary. This is needed because the pest utilities require strict order between the control file and jacobian
Step2: Draw some vectors from the prior and write the vectors to par files
Step3: Run pnulpar
Step4: Now for pyemu | Python Code:
%matplotlib inline
import os
import shutil
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pyemu
Explanation: verify pyEMU null space projection with the freyberg problem
End of explanation
mc = pyemu.MonteCarlo(jco="freyberg.jcb",verbose=False,forecasts=[])
mc.drop_prior_information()
jco_ord = mc.jco.get(mc.pst.obs_names,mc.pst.par_names)
ord_base = "freyberg_ord"
jco_ord.to_binary(ord_base + ".jco")
mc.pst.control_data.parsaverun = ' '
mc.pst.write(ord_base+".pst")
nsing = 5
Explanation: instaniate pyemu object and drop prior info. Then reorder the jacobian and save as binary. This is needed because the pest utilities require strict order between the control file and jacobian
End of explanation
# setup the dirs to hold all this stuff
par_dir = "prior_par_draws"
proj_dir = "proj_par_draws"
parfile_base = os.path.join(par_dir,"draw_")
projparfile_base = os.path.join(proj_dir,"draw_")
if os.path.exists(par_dir):
shutil.rmtree(par_dir)
os.mkdir(par_dir)
if os.path.exists(proj_dir):
shutil.rmtree(proj_dir)
os.mkdir(proj_dir)
mc = pyemu.MonteCarlo(jco=ord_base+".jco")
# make some draws
mc.draw(10)
#for i in range(10):
# mc.parensemble.iloc[i,:] = i+1
#write them to files
mc.parensemble.index = [str(i+1) for i in range(mc.parensemble.shape[0])]
mc.parensemble.to_parfiles(parfile_base)
mc.parensemble.shape
Explanation: Draw some vectors from the prior and write the vectors to par files
End of explanation
exe = os.path.join("pnulpar.exe")
args = [ord_base+".pst","y",str(nsing),"y","pnulpar_qhalfx.mat",parfile_base,projparfile_base]
in_file = os.path.join("misc","pnulpar.in")
with open(in_file,'w') as f:
f.write('\n'.join(args)+'\n')
os.system(exe + ' <'+in_file)
pnul_en = pyemu.ParameterEnsemble(mc.pst)
parfiles =[os.path.join(proj_dir,f) for f in os.listdir(proj_dir) if f.endswith(".par")]
pnul_en.read_parfiles(parfiles)
pnul_en.loc[:,"fname"] = pnul_en.index
pnul_en.index = pnul_en.fname.apply(lambda x:str(int(x.split('.')[0].split('_')[-1])))
f = pnul_en.pop("fname")
pnul_en.sort_index(axis=1,inplace=True)
pnul_en.sort_index(axis=0,inplace=True)
pnul_en
Explanation: Run pnulpar
End of explanation
print(mc.parensemble.istransformed)
mc.parensemble._transform()
en = mc.project_parensemble(nsing=nsing,inplace=False)
print(mc.parensemble.istransformed)
#en._back_transform()
en.sort_index(axis=1,inplace=True)
en.sort_index(axis=0,inplace=True)
en
#pnul_en.sort(inplace=True)
#en.sort(inplace=True)
diff = 100.0 * np.abs(pnul_en - en) / en
#diff[diff<1.0] = np.NaN
dmax = diff.max(axis=0)
dmax.sort_index(ascending=False,inplace=True)
dmax.plot(figsize=(10,10))
diff
en.loc[:,"wf6_2"]
pnul_en.loc[:,"wf6_2"]
Explanation: Now for pyemu
End of explanation |
8,559 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitting curve to data
Within this notebook we do some data analytics on historical data to feed some real numbers into the model. Since we assume the consumer data to be resemble a sinus, due to the fact that demand is seasonal, we will focus on fitting data to this kind of curve.
Step1: import data for our model
This is data imported from statline CBS webportal.
Step2: now let fit different consumer groups
Step3: price forming
In order to estimate willingness to sell en willingness to buy we look at historical data over the past view years. We look at the DayAhead market at the TTF. Altough this data does not reflect real consumption necessarily | Python Code:
import pandas as pd
import numpy as np
from scipy.optimize import leastsq
import pylab as plt
N = 1000 # number of data points
t = np.linspace(0, 4*np.pi, N)
data = 3.0*np.sin(t+0.001) + 0.5 + np.random.randn(N) # create artificial data with noise
guess_mean = np.mean(data)
guess_std = 3*np.std(data)/(2**0.5)
guess_phase = 0
# we'll use this to plot our first estimate. This might already be good enough for you
data_first_guess = guess_std*np.sin(t+guess_phase) + guess_mean
# Define the function to optimize, in this case, we want to minimize the difference
# between the actual data and our "guessed" parameters
optimize_func = lambda x: x[0]*np.sin(t+x[1]) + x[2] - data
est_std, est_phase, est_mean = leastsq(optimize_func, [guess_std, guess_phase, guess_mean])[0]
# recreate the fitted curve using the optimized parameters
data_fit = est_std*np.sin(t+est_phase) + est_mean
plt.plot(data, '.')
plt.plot(data_fit, label='after fitting')
plt.plot(data_first_guess, label='first guess')
plt.legend()
plt.show()
Explanation: Fitting curve to data
Within this notebook we do some data analytics on historical data to feed some real numbers into the model. Since we assume the consumer data to be resemble a sinus, due to the fact that demand is seasonal, we will focus on fitting data to this kind of curve.
End of explanation
importfile = 'CBS Statline Gas Usage.xlsx'
df = pd.read_excel(importfile, sheetname='Month', skiprows=1)
df.drop(['Onderwerpen_1', 'Onderwerpen_2', 'Perioden'], axis=1, inplace=True)
#df
# transpose
df = df.transpose()
# provide headers
new_header = df.iloc[0]
df = df[1:]
df.rename(columns = new_header, inplace=True)
#df.drop(['nan'], axis=0, inplace=True)
df
x = range(len(df.index))
df['Via regionale netten'].plot(figsize=(18,5))
plt.xticks(x, df.index, rotation='vertical')
plt.show()
Explanation: import data for our model
This is data imported from statline CBS webportal.
End of explanation
#b = self.base_demand
#m = self.max_demand
#y = b + m * (.5 * (1 + np.cos((x/6)*np.pi)))
#b = 603
#m = 3615
N = 84 # number of data points
t = np.linspace(0, 83, N)
#data = b + m*(.5 * (1 + np.cos((t/6)*np.pi))) + 100*np.random.randn(N) # create artificial data with noise
data = np.array(df['Via regionale netten'].values, dtype=np.float64)
guess_mean = np.mean(data)
guess_std = 2695.9075546 #2*np.std(data)/(2**0.5)
guess_phase = 0
# we'll use this to plot our first estimate. This might already be good enough for you
data_first_guess = guess_mean + guess_std*(.5 * (1 + np.cos((t/6)*np.pi + guess_phase)))
# Define the function to optimize, in this case, we want to minimize the difference
# between the actual data and our "guessed" parameters
optimize_func = lambda x: x[0]*(.5 * (1 + np.cos((t/6)*np.pi+x[1]))) + x[2] - data
est_std, est_phase, est_mean = leastsq(optimize_func, [guess_std, guess_phase, guess_mean])[0]
# recreate the fitted curve using the optimized parameters
data_fit = est_mean + est_std*(.5 * (1 + np.cos((t/6)*np.pi + est_phase)))
plt.plot(data, '.')
plt.plot(data_fit, label='after fitting')
plt.plot(data_first_guess, label='first guess')
plt.legend()
plt.show()
print('Via regionale netten')
print('max_demand: %s' %(est_std))
print('phase_shift: %s' %(est_phase))
print('base_demand: %s' %(est_mean))
#data = b + m*(.5 * (1 + np.cos((t/6)*np.pi))) + 100*np.random.randn(N) # create artificial data with noise
data = np.array(df['Elektriciteitscentrales'].values, dtype=np.float64)
guess_mean = np.mean(data)
guess_std = 3*np.std(data)/(2**0.5)
guess_phase = 0
# we'll use this to plot our first estimate. This might already be good enough for you
data_first_guess = guess_mean + guess_std*(.5 * (1 + np.cos((t/6)*np.pi + guess_phase)))
# Define the function to optimize, in this case, we want to minimize the difference
# between the actual data and our "guessed" parameters
optimize_func = lambda x: x[0]*(.5 * (1 + np.cos((t/6)*np.pi+x[1]))) + x[2] - data
est_std, est_phase, est_mean = leastsq(optimize_func, [guess_std, guess_phase, guess_mean])[0]
# recreate the fitted curve using the optimized parameters
data_fit = est_mean + est_std*(.5 * (1 + np.cos((t/6)*np.pi + est_phase)))
plt.plot(data, '.')
plt.plot(data_fit, label='after fitting')
plt.plot(data_first_guess, label='first guess')
plt.legend()
plt.show()
print('Elektriciteitscentrales')
print('max_demand: %s' %(est_std))
print('phase_shift: %s' %(est_phase))
print('base_demand: %s' %(est_mean))
#data = b + m*(.5 * (1 + np.cos((t/6)*np.pi))) + 100*np.random.randn(N) # create artificial data with noise
data = np.array(df['Overige verbruikers'].values, dtype=np.float64)
guess_mean = np.mean(data)
guess_std = 3*np.std(data)/(2**0.5)
guess_phase = 0
guess_saving = .997
# we'll use this to plot our first estimate. This might already be good enough for you
data_first_guess = (guess_mean + guess_std*(.5 * (1 + np.cos((t/6)*np.pi + guess_phase)))) #* np.power(guess_saving,t)
# Define the function to optimize, in this case, we want to minimize the difference
# between the actual data and our "guessed" parameters
optimize_func = lambda x: x[0]*(.5 * (1 + np.cos((t/6)*np.pi+x[1]))) + x[2] - data
est_std, est_phase, est_mean = leastsq(optimize_func, [guess_std, guess_phase, guess_mean])[0]
# recreate the fitted curve using the optimized parameters
data_fit = est_mean + est_std*(.5 * (1 + np.cos((t/6)*np.pi + est_phase)))
plt.plot(data, '.')
plt.plot(data_fit, label='after fitting')
plt.plot(data_first_guess, label='first guess')
plt.legend()
plt.show()
print('Overige verbruikers')
print('max_demand: %s' %(est_std))
print('phase_shift: %s' %(est_phase))
print('base_demand: %s' %(est_mean))
Explanation: now let fit different consumer groups
End of explanation
inputexcel = 'TTFDA.xlsx'
outputexcel = 'pythonoutput.xlsx'
price = pd.read_excel(inputexcel, sheetname='Sheet1', index_col=0)
quantity = pd.read_excel(inputexcel, sheetname='Sheet2', index_col=0)
price.index = pd.to_datetime(price.index, format="%d-%m-%y")
quantity.index = pd.to_datetime(quantity.index, format="%d-%m-%y")
pq = pd.concat([price, quantity], axis=1, join_axes=[price.index])
pqna = pq.dropna()
year = np.arange(2008,2017,1)
coefficientyear = []
for i in year:
x= pqna['Volume'].sort_index().ix["%s"%i]
y= pqna['Last'].sort_index().ix["%s"%i]
#plot the trendline
plt.plot(x,y,'o')
# calc the trendline
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x),"r--", label="%s"%i)
plt.xlabel("Volume")
plt.ylabel("Price Euro per MWH")
plt.title('%s: y=%.10fx+(%.10f)'%(i,z[0],z[1]))
# plt.savefig('%s.png' %i)
plt.show()
# the line equation:
print("y=%.10fx+(%.10f)"%(z[0],z[1]))
# save the variables in a list
coefficientyear.append([i, z[0], z[1]])
len(year)
Explanation: price forming
In order to estimate willingness to sell en willingness to buy we look at historical data over the past view years. We look at the DayAhead market at the TTF. Altough this data does not reflect real consumption necessarily
End of explanation |
8,560 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic data IO and analysis
First, we need to import all the necessary libraries and set up some environment variables.
Step1: Load the zip file from the web and save it to your hard drive.
Step2: Show contents of the zip file.
Step3: Read csv-formatted data directly from the zip file into pandas DataFrame. Also rename some columns for prettier output.
Step4: Show unique values of the Topic column.
Step5: Leave only those rows that have Expenditures in the column Topic. Next, leave only those that contain PPP in the Indicator Name column values. Finally, create a dictionary with a pair of variable key and its meaningful name.
Step6: Do the same for Attainment among Topic values and slightly more involved subset of Indicator Name. Here we require that it contains both strings, with primary schooling and 15.
Step7: Now show all column names in the primary data set.
Step8: Combine two dictionaries into one.
Step9: Subset the data to include only three interesting columns that we have found above and only for the year 2010.
Step10: Export data to Excel.
Step11: Now suppose we already have the data saved in the Excel file. Let's read it from scratch into pandas DataFrame.
Step12: Let's see how percentage of educated population depends on government expenditures on primary students. Also, save the picture to the pdf file.
Step13: To be more precise we can quantify the effect of expenditures on schooling via simple OLS regression.
Step14: And save the key result to the LaTeX table. | Python Code:
import re
import requests
import zipfile
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import seaborn as sns
import statsmodels.formula.api as sm
sns.set_context('talk')
pd.set_option('float_format', '{:6.2f}'.format)
%matplotlib inline
Explanation: Basic data IO and analysis
First, we need to import all the necessary libraries and set up some environment variables.
End of explanation
url = 'http://databank.worldbank.org/data/download/Edstats_csv.zip'
path = '../data/WorldBank/Edstats_csv.zip'
response = requests.get(url)
with open(path, "wb") as file:
file.write(response.content)
Explanation: Load the zip file from the web and save it to your hard drive.
End of explanation
zf = zipfile.ZipFile(path)
files = zf.namelist()
print(files)
Explanation: Show contents of the zip file.
End of explanation
data = pd.read_csv(zf.open(files[0]))
series = pd.read_csv(zf.open(files[2]))
series.rename(columns={series.columns[0]: 'Series Code'}, inplace=True)
data.rename(columns={data.columns[0]: 'Country Name'}, inplace=True)
print(series.columns)
Explanation: Read csv-formatted data directly from the zip file into pandas DataFrame. Also rename some columns for prettier output.
End of explanation
print(series['Topic'].unique())
Explanation: Show unique values of the Topic column.
End of explanation
subset = series.query("Topic == 'Expenditures'")[['Series Code', 'Indicator Name']]
subset = subset[subset['Indicator Name'].str.contains('PPP')]
print(subset.values)
xvar = {'UIS.XUNIT.PPP.1.FSGOV': 'Expenditure per student'}
Explanation: Leave only those rows that have Expenditures in the column Topic. Next, leave only those that contain PPP in the Indicator Name column values. Finally, create a dictionary with a pair of variable key and its meaningful name.
End of explanation
subset = series.query("Topic == 'Attainment'")[['Series Code', 'Indicator Name']]
subset = subset[subset['Indicator Name'].str.contains('(?=.*with primary schooling)(?=.*15)')]
print(subset.values)
yvar = {'BAR.PRM.CMPT.15UP.ZS': 'Pct with schooling'}
Explanation: Do the same for Attainment among Topic values and slightly more involved subset of Indicator Name. Here we require that it contains both strings, with primary schooling and 15.
End of explanation
print(data.columns)
Explanation: Now show all column names in the primary data set.
End of explanation
renames = xvar.copy()
renames.update(yvar)
print(renames)
Explanation: Combine two dictionaries into one.
End of explanation
cols = ['Country Name', 'Indicator Code', '2010']
data_sub = data.ix[data['Indicator Code'].isin(renames.keys()), cols].dropna()
data_sub.replace({'Indicator Code': renames}, inplace=True)
data_sub.set_index(cols[:2], inplace=True)
data_sub = data_sub[cols[-1]].unstack(cols[1]).dropna()
data_sub.columns.name = 'Indicator'
data_sub.index.name = 'Country'
print(data_sub.head())
Explanation: Subset the data to include only three interesting columns that we have found above and only for the year 2010.
End of explanation
data_sub.to_excel('../data/WorldBank/education.xlsx', sheet_name='data')
Explanation: Export data to Excel.
End of explanation
education = pd.read_excel('../data/WorldBank/education.xlsx', sheet_name='data', index_col=0)
print(education.head())
Explanation: Now suppose we already have the data saved in the Excel file. Let's read it from scratch into pandas DataFrame.
End of explanation
education['Expenditure per student (log)'] = np.log(education['Expenditure per student'])
fig = plt.figure(figsize=(8, 6))
sns.regplot(x='Expenditure per student (log)', y='Pct with schooling',
data=education, ax=fig.gca())
plt.savefig('../plots/education.pdf')
plt.show()
Explanation: Let's see how percentage of educated population depends on government expenditures on primary students. Also, save the picture to the pdf file.
End of explanation
formula = 'Q("Pct with schooling") ~ np.log(Q("Expenditure per student"))'
result = sm.ols(formula=formula, data=education).fit()
print(result.summary())
Explanation: To be more precise we can quantify the effect of expenditures on schooling via simple OLS regression.
End of explanation
out = pd.DataFrame({'Parameter': result.params, 't-stat': result.tvalues})
out.to_latex('../tables/education_ols.tex')
print(out)
Explanation: And save the key result to the LaTeX table.
End of explanation |
8,561 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Projection, Joining, and Sorting
Setup
Step1: Projections
Step2: First, the basics
Step3: You can make a list of columns you want, too, and pass that
Step4: You can also use the explicit projection or select functions
Step5: We can add new columns by using named column expressions
Step6: Adding columns is a shortcut for projection. In Ibis, adding columns always produces a new table reference
Step7: In more complicated projections involving joins, we may need to refer to all of the columns in a table at once. This is how add_column works. We just pass the whole table in the projection
Step8: To use constants in projections, we have to use a special ibis.literal function
Step9: Joins
Ibis attempts to provide good support for all the standard relational joins supported by Impala, Hive, and other relational databases.
inner, outer, left, right joins
semi and anti-joins
To illustrate the joins we'll use the TPC-H tables for now
Step10: region and nation are connected by their respective regionkey columns
Step11: If you have multiple join conditions, either compose them yourself (like filters) or pass a list to the join function
join_exprs = [cond1, cond2, cond3]
joined = table1.inner_join(table2, join_exprs)
Once you've joined tables, you don't necessarily have anything yet. I'll put it in big letters
Joins are declarations of intent
After calling the join function (which validates the join condition, of course), you may perform any number of other operations
Step12: Things like group_by work with unmaterialized joins, too, as you would hope.
Step13: Explicit join materialization
If you're lucky enough to have two table schemas with no overlapping column names (lucky you!), the join can be materialized without having to perform some other relational algebra operation
Step14: Okay, great, now how about the MAD? The only trick here is that we can form an aggregate metric from the two tables, and we then have to join it later. Ibis will not figure out how to join the tables automatically for us.
Step15: This metric is only valid if used in the context of table joined with hourly_mean, so let's do that. Writing down the join condition is simply a matter of writing
Step16: Now let's compute the MAD grouped by string_col
Step17: Sorting
Sorting tables works similarly to the SQL ORDER BY clause. We use the sort_by function and pass one of the following
Step18: For sorting in descending order, you can use the special ibis.desc function | Python Code:
import ibis
import os
hdfs_port = os.environ.get('IBIS_WEBHDFS_PORT', 50070)
hdfs = ibis.hdfs_connect(host='quickstart.cloudera', port=hdfs_port)
con = ibis.impala.connect(host='quickstart.cloudera', database='ibis_testing',
hdfs_client=hdfs)
print('Hello!')
Explanation: Projection, Joining, and Sorting
Setup
End of explanation
table = con.table('functional_alltypes')
table.limit(5)
Explanation: Projections: adding/selecting columns
Projections are the general way for adding new columns to tables, or selecting or removing existing ones.
End of explanation
proj = table['bool_col', 'int_col', 'double_col']
proj.limit(5)
Explanation: First, the basics: selecting columns:
End of explanation
to_select = ['bool_col', 'int_col']
table[to_select].limit(5)
Explanation: You can make a list of columns you want, too, and pass that:
End of explanation
table.select(['int_col', 'double_col']).limit(5)
Explanation: You can also use the explicit projection or select functions
End of explanation
bigger_expr = (table.int_col * 2).name('bigger_ints')
proj2 = table['int_col', bigger_expr]
proj2.limit(5)
Explanation: We can add new columns by using named column expressions
End of explanation
table2 = table.add_column(bigger_expr)
table2.limit(5)
Explanation: Adding columns is a shortcut for projection. In Ibis, adding columns always produces a new table reference
End of explanation
table.select([table, bigger_expr]).limit(5)
Explanation: In more complicated projections involving joins, we may need to refer to all of the columns in a table at once. This is how add_column works. We just pass the whole table in the projection:
End of explanation
foo_constant = ibis.literal(5).name('foo')
table.select([table.bigint_col, foo_constant]).limit(5)
Explanation: To use constants in projections, we have to use a special ibis.literal function
End of explanation
region = con.table('tpch_region')
nation = con.table('tpch_nation')
customer = con.table('tpch_customer')
lineitem = con.table('tpch_lineitem')
Explanation: Joins
Ibis attempts to provide good support for all the standard relational joins supported by Impala, Hive, and other relational databases.
inner, outer, left, right joins
semi and anti-joins
To illustrate the joins we'll use the TPC-H tables for now
End of explanation
join_expr = region.r_regionkey == nation.n_regionkey
joined = region.inner_join(nation, join_expr)
Explanation: region and nation are connected by their respective regionkey columns
End of explanation
table_ref = joined[nation, region.r_name.name('region')]
table_ref.columns
table_ref.limit(5)
agged = table_ref.aggregate([table_ref.n_name.count().name('nrows')], by=['region'])
agged
Explanation: If you have multiple join conditions, either compose them yourself (like filters) or pass a list to the join function
join_exprs = [cond1, cond2, cond3]
joined = table1.inner_join(table2, join_exprs)
Once you've joined tables, you don't necessarily have anything yet. I'll put it in big letters
Joins are declarations of intent
After calling the join function (which validates the join condition, of course), you may perform any number of other operations:
Aggregation
Projection
Filtering
and so forth. Most importantly, depending on your schemas, the joined tables may include overlapping column names that could create a conflict if not addressed directly. Some other systems, like pandas, handle this by applying suffixes to the overlapping column names and computing the fully joined tables immediately. We don't do this.
So, with the above data, suppose we just want the region name and all the nation table data. We can then make a projection on the joined reference:
End of explanation
joined.group_by(region.r_name).size()
Explanation: Things like group_by work with unmaterialized joins, too, as you would hope.
End of explanation
table = con.table('functional_alltypes')
hour_dim = table.timestamp_col.hour().name('hour')
hourly_mean = (table.group_by(hour_dim)
.aggregate([table.double_col.mean().name('avg_double')]))
hourly_mean
Explanation: Explicit join materialization
If you're lucky enough to have two table schemas with no overlapping column names (lucky you!), the join can be materialized without having to perform some other relational algebra operation:
joined = a.inner_join(b, join_expr).materialize()
Note that this is equivalent to doing
joined = a.join(b, join_expr)[a, b]
i.e., joining and then selecting all columns from both joined tables. If there is a name overlap, just like with the equivalent projection, there will be an immediate error.
Writing down join keys
In addition to having explicit comparison expressions as join keys, you can also write down column names, or use expressions referencing the joined tables, e.g.:
joined = a.join(b, [('a_key1', 'b_key2')])
joined2 = a.join(b, [(left_expr, right_expr)])
joined3 = a.join(b, ['common_key'])
These will be compared for equality when performing the join; if you want non-equality conditions in the join, you will have to form those yourself.
Join referential nuances
There's nothing to stop you from doing many joins in succession, and, in fact, with complex schemas it will be to your advantage to build the joined table references for your analysis first, then reuse the objects as you go:
joined_ref = (a.join(b, a.key1 == b.key2)
.join(c, [a.key3 == c.key4, b.key5 == c.key6]))
Note that, at least right now, you need to provide explicit comparison expressions (or tuples of column references) referencing the joined tables.
Aggregating joined table with metrics involving more than one base reference
Let's consider the case similar to the SQL query
SELECT a.key, sum(a.foo - b.bar) AS metric
FROM a
JOIN b
ON a.key = b.key
GROUP BY 1
I'll use a somewhat contrived example using the data we already have to show you what this looks like. Take the functional.alltypes table, and suppose we want to compute the mean absolute deviation (MAD) from the hourly mean of the double_col. Silly, I know, but bear with me.
First, the hourly mean:
End of explanation
mad = (table.double_col - hourly_mean.avg_double).abs().mean().name('MAD')
Explanation: Okay, great, now how about the MAD? The only trick here is that we can form an aggregate metric from the two tables, and we then have to join it later. Ibis will not figure out how to join the tables automatically for us.
End of explanation
join_expr = hour_dim == hourly_mean.hour
Explanation: This metric is only valid if used in the context of table joined with hourly_mean, so let's do that. Writing down the join condition is simply a matter of writing:
End of explanation
result = (table.inner_join(hourly_mean, join_expr)
.group_by(table.string_col)
.aggregate([mad]))
result
Explanation: Now let's compute the MAD grouped by string_col
End of explanation
table = con.table('functional_alltypes')
keys = ['string_col', (table.bigint_col > 40).ifelse('high', 'low').name('bigint_tier')]
metrics = [table.double_col.sum().name('total')]
agged = (table
.filter(table.int_col < 8)
.group_by(keys)
.aggregate(metrics))
sorted_agged = agged.sort_by(['bigint_tier', ('total', False)])
sorted_agged
Explanation: Sorting
Sorting tables works similarly to the SQL ORDER BY clause. We use the sort_by function and pass one of the following:
Column names
Column expressions
One of these, with a False (descending order) or True (ascending order) qualifier
So, to sort by total in ascending order we write:
table.sort_by('total')
or by key then by total in descending order
table.sort_by(['key', ('total', False)])
For descending sort order, there is a convenience function desc which can wrap sort keys
from ibis import desc
table.sort_by(['key', desc(table.total)])
Here's a concrete example involving filters, custom grouping dimension, and sorting
End of explanation
agged.sort_by(ibis.desc('total'))
Explanation: For sorting in descending order, you can use the special ibis.desc function:
End of explanation |
8,562 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
人生苦短,我用python
泰坦尼克数据处理与分析
<img src='https
Step1: 导入数据
Step2: 快速预览
Step3: | 单词 | 翻译
| ---
Step4: 处理空值
Step5: 尝试从性别进行分析
Step6: 通过上面图片可以看出:性别特征对是否生还的影响还是挺大的
从年龄进行分析
Step7: 分析票价
Step8: 可以看出低票价的人的生还率比较低
组合特征
Step9: 隐含特征
Step10: gdp | Python Code:
import pandas as pd
%matplotlib inline
Explanation: 人生苦短,我用python
泰坦尼克数据处理与分析
<img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502440065892&di=51db15bf76374068735a690806ad66a2&imgtype=0&src=http%3A%2F%2Fwww.pp3.cn%2Fuploads%2F201607%2F20160708007.jpg'>
End of explanation
# 如果不知道函数名是什么,可以只敲击函数前几个,然后按tab键,就会有下拉框提示
titanic = pd.read_csv('train.csv')
Explanation: 导入数据
End of explanation
titanic.head()
Explanation: 快速预览
End of explanation
titanic.info()
# 把所有数值类型的数据做一个简单的统计
titanic.describe()
# 统计None值个数
titanic.isnull().sum()
Explanation: | 单词 | 翻译
| ---: | :---
| pclass | 社会阶层(1,精英;2,中层;3,船员/劳苦大众)
| survived | 是否幸存
| name | 名字
| sex | 性别
| age | 年龄
| sibsp | 兄弟姐妹配偶个数 sibling spouse
| parch | 父母儿女个数
| ticket | 船票号
| fare | 船票价钱
| cabin | 船舱
| embarked| 登船口
End of explanation
# 可以填充整个datafram里边的空值, 可以取消注释,实验一下
# titanic.fillna(0)
# 单独选择一列进行控制填充,可以取消注释,实验一下
# titanic.Age.fillna(0)
# 年龄的中位数
titanic.Age.median()
# 按年龄的中位数去填充,此时是返回一个新的Series
# titanic.Age.fillna(titanic.Age.median())
# 直接填充,并不返回新的Series
titanic.Age.fillna(titanic.Age.median(), inplace=True)
# 再次查看Age的空值
titanic.isnull().sum()
Explanation: 处理空值
End of explanation
# 做简单的汇总统计,经常用到
titanic.Sex.value_counts()
# 生还者中,男女的人数
survived = titanic[titanic.Survived==1].Sex.value_counts()
# 未生还者中,男女的人数
dead = titanic[titanic.Survived==0].Sex.value_counts()
df = pd.DataFrame([survived, dead], index=['survived', 'dead'])
df.plot.bar()
# 绘图成功,但是不是我们想要的效果
# 把dataframe转置一下,就是行列替换
df = df.T
df.plot.bar() # df.plot(kind='bar') 等价的
# 仍然不是我们想要的结果
df.plot(kind='bar', stacked=True)
# 男女中生还者的比例情况
df['p_survived'] = df.survived / (df.survived + df.dead)
df['p_dead'] = df.dead / (df.survived + df.dead)
df[['p_survived', 'p_dead']].plot.bar(stacked=True)
Explanation: 尝试从性别进行分析
End of explanation
# 简单统计
# titanic.Age.value_counts()
survived = titanic[titanic.Survived==1].Age
dead = titanic[titanic.Survived==0].Age
df = pd.DataFrame([survived, dead], index=['survived', 'dead'])
df = df.T
df.plot.hist(stacked=True)
# 直方图柱子显示多一点
df.plot.hist(stacked=True, bins=30)
# 中间很高的柱子,是因为我们把空值都替换为了中位数
# 密度图, 更直观一点
df.plot.kde()
# 可以查看年龄的分布,来绝对我们图片横轴的取值范围
titanic.Age.describe()
# 限定范围
df.plot.kde(xlim=(0,80))
age = 16
young = titanic[titanic.Age<=age]['Survived'].value_counts()
old = titanic[titanic.Age>age]['Survived'].value_counts()
df = pd.DataFrame([young, old], index=['young', 'old'])
df.columns = ['dead', 'survived']
df.plot.bar(stacked=True)
# 男女中生还者的比例情况
df['p_survived'] = df.survived / (df.survived + df.dead)
df['p_dead'] = df.dead / (df.survived + df.dead)
df[['p_survived', 'p_dead']].plot.bar(stacked=True)
Explanation: 通过上面图片可以看出:性别特征对是否生还的影响还是挺大的
从年龄进行分析
End of explanation
# 票价跟年龄特征相似
survived = titanic[titanic.Survived==1].Fare
dead = titanic[titanic.Survived==0].Fare
df = pd.DataFrame([survived, dead], index=['survived', 'dead'])
df = df.T
df.plot.kde()
# 设定xlim范围,先查看票价的范围
titanic.Fare.describe()
df.plot(kind='kde', xlim=(0,513))
Explanation: 分析票价
End of explanation
# 比如同时查看年龄和票价对生还率的影响
import matplotlib.pyplot as plt
plt.scatter(titanic[titanic.Survived==0].Age, titanic[titanic.Survived==0].Fare)
# 不美观
ax = plt.subplot()
# 未生还者
age = titanic[titanic.Survived==0].Age
fare = titanic[titanic.Survived==0].Fare
plt.scatter(age, fare, s=20, marker='o', alpha=0.3, linewidths=1, edgecolors='gray')
# 生还者
age = titanic[titanic.Survived==1].Age
fare = titanic[titanic.Survived==1].Fare
plt.scatter(age, fare, s=20, marker='o', alpha=0.3, linewidths=1, edgecolors='gray', c='red')
ax.set_xlabel('age')
ax.set_ylabel('fare')
Explanation: 可以看出低票价的人的生还率比较低
组合特征
End of explanation
titanic.Name.describe()
titanic['title'] = titanic.Name.apply(lambda name: name.split(',')[1].split('.')[0].strip())
s = 'Williams, Mr. Howard Hugh "Harry"'
s.split(',')[-1].split('.')[0].strip()
titanic.title.value_counts()
# 比如有一个人被称为 Mr,而年龄是不知道的,这个时候可以用 所有 Mr 的年龄平均值来替代,而不是用我们之前最简单的所有数据的中位数
Explanation: 隐含特征
End of explanation
# 夜光图,简单用灯光图的亮度来模拟gdp
titanic.head()
titanic['family_size'] = titanic.SibSp + titanic.Parch + 1
titanic.family_size.value_counts()
def func(family_size):
if family_size == 1:
return 'Singleton'
if family_size<=4 and family_size>=2:
return 'SmallFamily'
if family_size > 4:
return 'LargeFamily'
titanic['family_type'] = titanic.family_size.apply(func)
titanic.family_type.value_counts()
Explanation: gdp
End of explanation |
8,563 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: 비정형 텐서
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: 개요
데이터는 다양한 형태로 제공됩니다; 텐서도 마찬가지입니다.
비정형 텐서는 중첩 가변 길이 목록에 해당하는 텐서플로입니다.
다음을 포함하여 균일하지 않은 모양으로 데이터를 쉽게 저장하고 처리할 수 있습니다
Step3: 팩토리 메서드, 변환 메서드 및 값 매핑 연산을 포함하여 비정형 텐서에
고유한 여러 메서드 및 연산도 있습니다.
지원되는 작업 목록은 tf.ragged 패키지 문서를 참조하십시오.
일반 텐서와 마찬가지로, Python 스타일 인덱싱을 사용하여 비정형 텐서의 특정 부분에 접근할 수 있습니다.
자세한 내용은 아래
인덱싱 절을 참조하십시오.
Step4: 일반 텐서와 마찬가지로, 파이썬 산술 및 비교 연산자를 사용하여 요소 별 연산을 수행할 수 있습니다.
자세한 내용은 아래의
오버로드된 연산자 절을 참조하십시오.
Step5: RaggedTensor의 값으로 요소 별 변환을 수행해야하는 경우, 함수와 하나 이상의 매개변수를 갖는 tf.ragged.map_flat_values를 사용할 수 있고, RaggedTensor의 값을 변환할 때 적용할 수 있습니다.
Step6: 비정형 텐서 생성하기
비정형 텐서를 생성하는 가장 간단한 방법은
tf.ragged.constant를 사용하는 것입니다. tf.ragged.constant는 주어진 중첩된 Python 목록에 해당하는 RaggedTensor를
빌드 합니다
Step7: 비정형 텐서는 tf.RaggedTensor.from_value_rowids, tf.RaggedTensor.from_row_lengths 및 tf.RaggedTensor.from_row_splits와
tf.RaggedTensor.from_row_splits와 같은 팩토리 클래스 메서드를 사용하여
플랫 values 텐서와 행 분할 텐서를 쌍을 지어 해당 값을 행으로 분할하는 방법을 표시하는 방식으로도 생성할 수 있습니다.
tf.RaggedTensor.from_value_rowids
각 값이 속하는 행을 알고 있으면 value_rowids 행 분할 텐서를 사용하여 RaggedTensor를 빌드할 수 있습니다
Step8: tf.RaggedTensor.from_row_lengths
각 행의 길이를 알고 있으면 row_lengths 행 분할 텐서를 사용할 수 있습니다
Step9: tf.RaggedTensor.from_row_splits
각 행의 시작과 끝 인덱스를 알고 있다면 row_splits 행 분할 텐서를 사용할 수 있습니다
Step10: 팩토리 메서드의 전체 목록은 tf.RaggedTensor 클래스 문서를 참조하십시오.
비정형 텐서에 저장할 수 있는 것
일반 텐서와 마찬가지로, RaggedTensor의 값은 모두 같은 유형이어야 합니다;
값은 모두 동일한 중첩 깊이 (텐서의 랭크)에
있어야 합니다
Step11: 사용 예시
다음 예제는 RaggedTensor를 사용하여 각 문장의 시작과 끝에 특수 마커를 사용하여
가변 길이 쿼리 배치에 대한 유니그램 및 바이그램 임베딩을 생성하고 결합하는 방법을 보여줍니다.
이 예제에서 사용된 작업에 대한 자세한 내용은
tf.ragged 패키지 설명서를 참조하십시오.
Step12: 비정형 텐서
Step13: tf.RaggedTensor.bounding_shape 메서드를 사용하여 지정된
RaggedTensor에 대한 빈틈이 없는 경계 형태를 찾을 수 있습니다
Step14: 비정형 vs 희소 텐서
비정형텐서는 희소 텐서의 유형이 아니라
불규칙한 형태의 밀집 텐서로 간주되어야 합니다.
예를 들어, 비정형 vs 희소 텐서에 대해 concat,
stack 및 tile과 같은 배열 연산이 어떻게 정의되는지 고려하십시오.
비정형 텐서들을 연결하면 각 행을 결합하여 단일 행을 형성합니다
Step15: 그러나 희소 텐서를 연결하는 것은 다음 예에 표시된 것처럼
해당 밀집 텐서를 연결하는 것과 같습니다. (여기서 Ø는 누락된 값을 나타냅니다.)
Step16: 이 구별이 중요한 이유의 다른 예를 보려면,
tf.reduce_mean과 같은 연산에 대한 “각 행의 평균값”의 정의를 고려하십시오.
비정형 텐서의 경우, 행의 평균값은 행 값을 행 너비로 나눈 값의 합입니다.
그러나 희소 텐서의 경우 행의 평균값은
행 값의 합계롤 희소 텐서의 전체 너비(가장 긴 행의 너비 이상)로
나눈 값입니다.
오버로드된 연산자
RaggedTensor 클래스는 표준 Python 산술 및 비교 연산자를 오버로드하여
기본 요소 별 수학을 쉽게 수행할 수 있습니다
Step17: 오버로드된 연산자는 요소 단위 계산을 수행하므로, 모든
이진 연산에 대한 입력은 동일한 형태이거나, 동일한 형태로 브로드캐스팅 할 수 있어야 합니다.
가장 간단한 확장의 경우, 단일 스칼라가 비정형 텐서의
각 값과 요소 별로 결합됩니다
Step18: 고급 사례에 대한 설명은 브로드캐스팅 절을
참조하십시오.
비정형 텐서는 일반 텐서와 동일한 연산자 세트를 오버로드합니다
Step19: 비정형 2차원으로 3차원 비정형 텐서 인덱싱
Step20: RaggedTensor는 다차원 인덱싱 및 슬라이싱을 지원하며, 한 가지 제한 사항이
있습니다
Step21: 비정형 텐서 평가
즉시 실행
즉시 실행 모드에서는, 비정형 텐서가 즉시 실행됩니다. 포함된 값에
접근하려면 다음을 수행하십시오
Step22: Python 인덱싱을 사용하십시오. 선택한 텐서 조각에 비정형 차원이 없으면,
EagerTensor로 반환됩니다. 그런 다음
numpy()메서드를 사용하여 값에 직접 접근할 수 있습니다.
Step23: tf.RaggedTensor.values 및
tf.RaggedTensor.row_splits 특성 또는
tf.RaggedTensor.row_lengths() 및
tf.RaggedTensor.value_rowids()와 같은 행 분할 메서드를 사용하여
비정형 텐서를 구성 요소로
분해하십시오.
Step24: 브로드캐스팅
브로드캐스팅은 다른 형태의 텐서가 요소 별 연산에 적합한 형태를 갖도록 만드는 프로세스입니다.
브로드캐스팅에 대한 자세한 내용은
다음을 참조하십시오
Step25: 브로드캐스트 하지 않는 형태의 예는 다음과 같습니다
Step26: RaggedTensor 인코딩
비정형텐서는 RaggedTensor 클래스를 사용하여 인코딩됩니다. 내부적으로, 각
RaggedTensor는 다음으로 구성됩니다
Step27: 다수의 비정형 차원
다수의 비정형 차원을 갖는 비정형 텐서는
values 텐서에 대해 중첩된 RaggedTensor를 사용하여 인코딩됩니다. 중첩된 각 RaggedTensor는
단일 비정형 차원을 추가합니다.
Step28: 팩토리 함수 tf.RaggedTensor.from_nested_row_splits는
row_splits 텐서 목록을 제공하여 다수의 비정형 차원으로 RaggedTensor를
직접 생성하는데 사용할 수 있습니다
Step29: 정형한 내부 차원
내부 차원이 정형한 비정형 텐서는
values에 다차원 tf.Tensor를 사용하여 인코딩됩니다.
Step30: 대체 가능한 행 분할 방식
RaggedTensor 클래스는 row_splits를 기본 메커니즘으로 사용하여
값이 행으로 분할되는 방법에 대한 정보를 저장합니다. 그러나,
RaggedTensor는 네 가지 대체 가능한 행 분할 방식을 지원하므로 데이터 형식에 따라 더 편리하게
사용할 수 있습니다.
내부적으로, RaggedTensor는 이러한 추가적인 방식을 사용하여 일부 컨텍스트에서 효율성을
향상시킵니다.
<dl>
<dt>행 길이</dt>
<dd>`row_lengths`는 `[nrows]`형태의 벡터로, 각 행의 길이를
지정합니다.</dd>
<dt>행 시작</dt>
<dd>`row_starts`는 `[nrows]`형태의 벡터로, 각 행의 시작 오프셋을
지정합니다. `row_splits[
Step31: RaggedTensor 클래스는 이러한 각 행 분할 텐서를 생성하는데 사용할 수 있는
메서드를 정의합니다. | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Explanation: Copyright 2018 The TensorFlow Authors.
End of explanation
import math
import tensorflow as tf
Explanation: 비정형 텐서
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/ragged_tensor"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />TensorFlow.org에서 보기</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/guide/ragged_tensor.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />구글 코랩(Colab)에서 실행하기</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ko/guide/ragged_tensor.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />깃허브(GitHub)에서 소스 보기</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ko/guide/ragged_tensor.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />노트북 다운로드</a>
</td>
</table>
Note: 이 문서는 텐서플로 커뮤니티에서 번역했습니다. 커뮤니티 번역 활동의 특성상 정확한 번역과 최신 내용을 반영하기 위해 노력함에도
불구하고 공식 영문 문서의 내용과 일치하지 않을 수 있습니다.
이 번역에 개선할 부분이 있다면
tensorflow/docs-l10n 깃헙 저장소로 풀 리퀘스트를 보내주시기 바랍니다.
문서 번역이나 리뷰에 참여하려면
docs-ko@tensorflow.org로
메일을 보내주시기 바랍니다.
설정
End of explanation
digits = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []])
words = tf.ragged.constant([["So", "long"], ["thanks", "for", "all", "the", "fish"]])
print(tf.add(digits, 3))
print(tf.reduce_mean(digits, axis=1))
print(tf.concat([digits, [[5, 3]]], axis=0))
print(tf.tile(digits, [1, 2]))
print(tf.strings.substr(words, 0, 2))
Explanation: 개요
데이터는 다양한 형태로 제공됩니다; 텐서도 마찬가지입니다.
비정형 텐서는 중첩 가변 길이 목록에 해당하는 텐서플로입니다.
다음을 포함하여 균일하지 않은 모양으로 데이터를 쉽게 저장하고 처리할 수 있습니다:
일련의 영화의 배우들과 같은 가변 길이 기능
문장이나 비디오 클립과 같은 가변 길이 순차적 입력의 배치
절, 단락, 문장 및 단어로 세분화된 텍스트 문서와 같은 계층적 입력
프로토콜 버퍼와 같은 구조화된 입력의 개별 필드
비정형 텐서로 할 수 있는 일
비정형 텐서는 수학 연산 (예 : tf.add 및 tf.reduce_mean),
배열 연산 (예 : tf.concat 및 tf.tile),
문자열 조작 작업 (예 : tf.substr)을 포함하여 수백 가지 이상의 텐서플로 연산에서 지원됩니다
:
End of explanation
print(digits[0]) # 첫 번째 행
print(digits[:, :2]) # 각 행의 처음 두 값
print(digits[:, -2:]) # 각 행의 마지막 두 값
Explanation: 팩토리 메서드, 변환 메서드 및 값 매핑 연산을 포함하여 비정형 텐서에
고유한 여러 메서드 및 연산도 있습니다.
지원되는 작업 목록은 tf.ragged 패키지 문서를 참조하십시오.
일반 텐서와 마찬가지로, Python 스타일 인덱싱을 사용하여 비정형 텐서의 특정 부분에 접근할 수 있습니다.
자세한 내용은 아래
인덱싱 절을 참조하십시오.
End of explanation
print(digits + 3)
print(digits + tf.ragged.constant([[1, 2, 3, 4], [], [5, 6, 7], [8], []]))
Explanation: 일반 텐서와 마찬가지로, 파이썬 산술 및 비교 연산자를 사용하여 요소 별 연산을 수행할 수 있습니다.
자세한 내용은 아래의
오버로드된 연산자 절을 참조하십시오.
End of explanation
times_two_plus_one = lambda x: x * 2 + 1
print(tf.ragged.map_flat_values(times_two_plus_one, digits))
Explanation: RaggedTensor의 값으로 요소 별 변환을 수행해야하는 경우, 함수와 하나 이상의 매개변수를 갖는 tf.ragged.map_flat_values를 사용할 수 있고, RaggedTensor의 값을 변환할 때 적용할 수 있습니다.
End of explanation
sentences = tf.ragged.constant([
["Let's", "build", "some", "ragged", "tensors", "!"],
["We", "can", "use", "tf.ragged.constant", "."]])
print(sentences)
paragraphs = tf.ragged.constant([
[['I', 'have', 'a', 'cat'], ['His', 'name', 'is', 'Mat']],
[['Do', 'you', 'want', 'to', 'come', 'visit'], ["I'm", 'free', 'tomorrow']],
])
print(paragraphs)
Explanation: 비정형 텐서 생성하기
비정형 텐서를 생성하는 가장 간단한 방법은
tf.ragged.constant를 사용하는 것입니다. tf.ragged.constant는 주어진 중첩된 Python 목록에 해당하는 RaggedTensor를
빌드 합니다:
End of explanation
print(tf.RaggedTensor.from_value_rowids(
values=[3, 1, 4, 1, 5, 9, 2, 6],
value_rowids=[0, 0, 0, 0, 2, 2, 2, 3]))
Explanation: 비정형 텐서는 tf.RaggedTensor.from_value_rowids, tf.RaggedTensor.from_row_lengths 및 tf.RaggedTensor.from_row_splits와
tf.RaggedTensor.from_row_splits와 같은 팩토리 클래스 메서드를 사용하여
플랫 values 텐서와 행 분할 텐서를 쌍을 지어 해당 값을 행으로 분할하는 방법을 표시하는 방식으로도 생성할 수 있습니다.
tf.RaggedTensor.from_value_rowids
각 값이 속하는 행을 알고 있으면 value_rowids 행 분할 텐서를 사용하여 RaggedTensor를 빌드할 수 있습니다:
End of explanation
print(tf.RaggedTensor.from_row_lengths(
values=[3, 1, 4, 1, 5, 9, 2, 6],
row_lengths=[4, 0, 3, 1]))
Explanation: tf.RaggedTensor.from_row_lengths
각 행의 길이를 알고 있으면 row_lengths 행 분할 텐서를 사용할 수 있습니다:
End of explanation
print(tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2, 6],
row_splits=[0, 4, 4, 7, 8]))
Explanation: tf.RaggedTensor.from_row_splits
각 행의 시작과 끝 인덱스를 알고 있다면 row_splits 행 분할 텐서를 사용할 수 있습니다:
End of explanation
print(tf.ragged.constant([["Hi"], ["How", "are", "you"]])) # 좋음: 유형=문자열, 랭크=2
print(tf.ragged.constant([[[1, 2], [3]], [[4, 5]]])) # 좋음: 유형=32비트정수, 랭크=3
try:
tf.ragged.constant([["one", "two"], [3, 4]]) # 안좋음: 다수의 유형
except ValueError as exception:
print(exception)
try:
tf.ragged.constant(["A", ["B", "C"]]) # 안좋음: 다중첩 깊이
except ValueError as exception:
print(exception)
Explanation: 팩토리 메서드의 전체 목록은 tf.RaggedTensor 클래스 문서를 참조하십시오.
비정형 텐서에 저장할 수 있는 것
일반 텐서와 마찬가지로, RaggedTensor의 값은 모두 같은 유형이어야 합니다;
값은 모두 동일한 중첩 깊이 (텐서의 랭크)에
있어야 합니다:
End of explanation
queries = tf.ragged.constant([['Who', 'is', 'Dan', 'Smith'],
['Pause'],
['Will', 'it', 'rain', 'later', 'today']])
# 임베딩 테이블 만들기
num_buckets = 1024
embedding_size = 4
embedding_table = tf.Variable(
tf.random.truncated_normal([num_buckets, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
# 각 단어에 대한 임베딩 찾기
word_buckets = tf.strings.to_hash_bucket_fast(queries, num_buckets)
word_embeddings = tf.ragged.map_flat_values(
tf.nn.embedding_lookup, embedding_table, word_buckets) # ①
# 각 문장의 시작과 끝에 마커 추가하기
marker = tf.fill([queries.nrows(), 1], '#')
padded = tf.concat([marker, queries, marker], axis=1) # ②
# 바이그램 빌드 & 임베딩 찾기
bigrams = tf.strings.join([padded[:, :-1],
padded[:, 1:]],
separator='+') # ③
bigram_buckets = tf.strings.to_hash_bucket_fast(bigrams, num_buckets)
bigram_embeddings = tf.ragged.map_flat_values(
tf.nn.embedding_lookup, embedding_table, bigram_buckets) # ④
# 각 문장의 평균 임베딩 찾기
all_embeddings = tf.concat([word_embeddings, bigram_embeddings], axis=1) # ⑤
avg_embedding = tf.reduce_mean(all_embeddings, axis=1) # ⑥
print(avg_embedding)
Explanation: 사용 예시
다음 예제는 RaggedTensor를 사용하여 각 문장의 시작과 끝에 특수 마커를 사용하여
가변 길이 쿼리 배치에 대한 유니그램 및 바이그램 임베딩을 생성하고 결합하는 방법을 보여줍니다.
이 예제에서 사용된 작업에 대한 자세한 내용은
tf.ragged 패키지 설명서를 참조하십시오.
End of explanation
tf.ragged.constant([["Hi"], ["How", "are", "you"]]).shape
Explanation: 비정형 텐서: 정의
비정형 및 정형 차원
비정형 텐서는 슬라이스의 길이가 다를 수 있는 하나 이상의 비정형 크기를 갖는 텐서입니다.
예를 들어,
rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []] 의 내부 (열) 크기는
열 슬라이스(rt[0, :], ..., rt[4, :])의 길이가 다르기 때문에 비정형입니다.
부분의 길이가 모두 같은 차원을 정형차원이라고 합니다.
비정형 텐서의 가장 바깥 쪽 차원은 단일 슬라이스로 구성되므로 슬라이스의 길이가
다를 가능성이 없으므로 항상 균일합니다.
비정형 텐서는 균일한 가장 바깥 쪽 차원에 더하여 균일한 내부 차원을 가질 수도 있습니다.
예를 들어, [num_sentences, (num_words), embedding_size] 형태의 비정형 텐서를 사용하여
각 단어에 대한 단어 임베딩을 일련의 문장으로 저장할 수 있습니다.
여기서 (num_words)의 괄호는 차원이 비정형임을 나타냅니다.
비정형 텐서는 다수의 비정형 차원을 가질 수 있습니다. 예를 들어
모양이 [num_documents, (num_paragraphs), (num_sentences), (num_words)] 인
텐서를 사용하여 일련의 구조화된 텍스트 문서를 저장할 수 있습니다.
(여기서 괄호는 비정형 차원임을 나타냅니다.)
비정형 텐서 형태 제한
비정형 텐서의 형태는 다음과 같은 형식으로 제한됩니다:
단일 정형 차원
하나 이상의 비정형 차원
0 또는 그 이상의 정형 차원
참고: 이러한 제한은 현재 구현의 결과이며
향후 완화될 수 있습니다.
랭크 및 비정형 랭크
비정형 텐서의 총 차원 수를 랭크라고 하고,
비정형 텐서의 비정형 차원 수를 비정형랭크라고 합니다. 그래프 실행 모드 (즉, 비 즉시 실행(non-eager) 모드)에서, 텐서의 비정형 랭크는
생성 시 고정됩니다: 비정형 랭크는 런타임 값에 의존할 수 없으며 다른 세션 실행에 따라
동적으로 변할 수 없습니다.
잠재적으로 비정형인 텐서는
tf.Tensor 또는 tf.RaggedTensor 일 수 있는 값입니다.
tf.Tensor의 비정형 랭크는 0으로 정의됩니다.
비정형 텐서 형태
비정형 텐서의 형태를 설명할 때, 비정형 차원은 괄호로 묶어 표시됩니다.
예를 들어, 위에서 살펴본 것처럼 일련의 문장에서 각 단어에 대한 단어 임베딩을 저장하는
3차원 비정형텐서의 형태는
[num_sentences, (num_words), embedding_size]로 나타낼 수 있습니다.
RaggedTensor.shape 프로퍼티는 비정형 텐서에 대해 크기가 없는 비정형 차원인 tf.TensorShape를 반환합니다:
End of explanation
print(tf.ragged.constant([["Hi"], ["How", "are", "you"]]).bounding_shape())
Explanation: tf.RaggedTensor.bounding_shape 메서드를 사용하여 지정된
RaggedTensor에 대한 빈틈이 없는 경계 형태를 찾을 수 있습니다:
End of explanation
ragged_x = tf.ragged.constant([["John"], ["a", "big", "dog"], ["my", "cat"]])
ragged_y = tf.ragged.constant([["fell", "asleep"], ["barked"], ["is", "fuzzy"]])
print(tf.concat([ragged_x, ragged_y], axis=1))
Explanation: 비정형 vs 희소 텐서
비정형텐서는 희소 텐서의 유형이 아니라
불규칙한 형태의 밀집 텐서로 간주되어야 합니다.
예를 들어, 비정형 vs 희소 텐서에 대해 concat,
stack 및 tile과 같은 배열 연산이 어떻게 정의되는지 고려하십시오.
비정형 텐서들을 연결하면 각 행을 결합하여 단일 행을 형성합니다:
End of explanation
sparse_x = ragged_x.to_sparse()
sparse_y = ragged_y.to_sparse()
sparse_result = tf.sparse.concat(sp_inputs=[sparse_x, sparse_y], axis=1)
print(tf.sparse.to_dense(sparse_result, ''))
Explanation: 그러나 희소 텐서를 연결하는 것은 다음 예에 표시된 것처럼
해당 밀집 텐서를 연결하는 것과 같습니다. (여기서 Ø는 누락된 값을 나타냅니다.):
End of explanation
x = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
y = tf.ragged.constant([[1, 1], [2], [3, 3, 3]])
print(x + y)
Explanation: 이 구별이 중요한 이유의 다른 예를 보려면,
tf.reduce_mean과 같은 연산에 대한 “각 행의 평균값”의 정의를 고려하십시오.
비정형 텐서의 경우, 행의 평균값은 행 값을 행 너비로 나눈 값의 합입니다.
그러나 희소 텐서의 경우 행의 평균값은
행 값의 합계롤 희소 텐서의 전체 너비(가장 긴 행의 너비 이상)로
나눈 값입니다.
오버로드된 연산자
RaggedTensor 클래스는 표준 Python 산술 및 비교 연산자를 오버로드하여
기본 요소 별 수학을 쉽게 수행할 수 있습니다:
End of explanation
x = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
print(x + 3)
Explanation: 오버로드된 연산자는 요소 단위 계산을 수행하므로, 모든
이진 연산에 대한 입력은 동일한 형태이거나, 동일한 형태로 브로드캐스팅 할 수 있어야 합니다.
가장 간단한 확장의 경우, 단일 스칼라가 비정형 텐서의
각 값과 요소 별로 결합됩니다:
End of explanation
queries = tf.ragged.constant(
[['Who', 'is', 'George', 'Washington'],
['What', 'is', 'the', 'weather', 'tomorrow'],
['Goodnight']])
print(queries[1])
print(queries[1, 2]) # 한 단어
print(queries[1:]) # 첫 번째 행을 제외한 모든 단어
print(queries[:, :3]) # 각 쿼리의 처음 세 단어
print(queries[:, -2:]) # 각 쿼리의 마지막 두 단어
Explanation: 고급 사례에 대한 설명은 브로드캐스팅 절을
참조하십시오.
비정형 텐서는 일반 텐서와 동일한 연산자 세트를 오버로드합니다:단항
연산자 -, ~ 및 abs(); 그리고 이항 연산자 +, -, *, /,
//, %, **, &, |, ^, ==, <, <=, > 및 >=.
인덱싱
비정형 텐서는 다차원 인덱싱 및 슬라이싱을 포함하여 Python 스타일 인덱싱을 지원합니다.
다음 예는 2차원 및 3차원 비정형 텐서를 사용한 비정형 텐서 인덱싱을
보여줍니다.
비정형 1차원으로 2차원 비정형 텐서 인덱싱
End of explanation
rt = tf.ragged.constant([[[1, 2, 3], [4]],
[[5], [], [6]],
[[7]],
[[8, 9], [10]]])
print(rt[1]) # 두 번째 행 (2차원 비정형 텐서)
print(rt[3, 0]) # 네 번째 행의 첫 번째 요소 (1차원 텐서)
print(rt[:, 1:3]) # 각 행의 1-3 항목 (3차원 비정형 텐서)
print(rt[:, -1:]) # 각 행의 마지막 항목 (3차원 비정형 텐서)
Explanation: 비정형 2차원으로 3차원 비정형 텐서 인덱싱
End of explanation
ragged_sentences = tf.ragged.constant([
['Hi'], ['Welcome', 'to', 'the', 'fair'], ['Have', 'fun']])
print(ragged_sentences.to_tensor(default_value=''))
print(ragged_sentences.to_sparse())
x = [[1, 3, -1, -1], [2, -1, -1, -1], [4, 5, 8, 9]]
print(tf.RaggedTensor.from_tensor(x, padding=-1))
st = tf.SparseTensor(indices=[[0, 0], [2, 0], [2, 1]],
values=['a', 'b', 'c'],
dense_shape=[3, 3])
print(tf.RaggedTensor.from_sparse(st))
Explanation: RaggedTensor는 다차원 인덱싱 및 슬라이싱을 지원하며, 한 가지 제한 사항이
있습니다: 비정형 차원으로 인덱싱할 수 없습니다. 이 값은
표시된 값이 일부 행에 존재할 수 있지만 다른 행에는 존재하지 않기 때문에 문제가 됩니다.
그러한 경우, 우리가 (1) IndexError를 제기해야 하는지; (2)
기본값을 사용해야 하는지; 또는 (3) 그 값을 스킵하고 시작한 것보다 적은 행을 가진 텐서를 반환해야 하는지
에 대한 여부는 확실하지 않습니다.
Python의 안내 지침
("애매한 상황에서
추측하려고 하지 마십시오" )에 따라, 현재 이 작업을 허용하지
않습니다.
텐서 형 변환
RaggedTensor 클래스는
RaggedTensor와 tf.Tensor 또는 tf.SparseTensors 사이를 변환하는데 사용할 수 있는 메서드를 정의합니다:
End of explanation
rt = tf.ragged.constant([[1, 2], [3, 4, 5], [6], [], [7]])
print(rt.to_list())
Explanation: 비정형 텐서 평가
즉시 실행
즉시 실행 모드에서는, 비정형 텐서가 즉시 실행됩니다. 포함된 값에
접근하려면 다음을 수행하십시오:
비정형 텐서를 Python 목록으로 변환하는
tf.RaggedTensor.to_list()
메서드를 사용하십시오.
End of explanation
print(rt[1].numpy())
Explanation: Python 인덱싱을 사용하십시오. 선택한 텐서 조각에 비정형 차원이 없으면,
EagerTensor로 반환됩니다. 그런 다음
numpy()메서드를 사용하여 값에 직접 접근할 수 있습니다.
End of explanation
print(rt.values)
print(rt.row_splits)
Explanation: tf.RaggedTensor.values 및
tf.RaggedTensor.row_splits 특성 또는
tf.RaggedTensor.row_lengths() 및
tf.RaggedTensor.value_rowids()와 같은 행 분할 메서드를 사용하여
비정형 텐서를 구성 요소로
분해하십시오.
End of explanation
# x (2D ragged): 2 x (num_rows)
# y (scalar)
# 결과 (2D ragged): 2 x (num_rows)
x = tf.ragged.constant([[1, 2], [3]])
y = 3
print(x + y)
# x (2d ragged): 3 x (num_rows)
# y (2d tensor): 3 x 1
# 결과 (2d ragged): 3 x (num_rows)
x = tf.ragged.constant(
[[10, 87, 12],
[19, 53],
[12, 32]])
y = [[1000], [2000], [3000]]
print(x + y)
# x (3d ragged): 2 x (r1) x 2
# y (2d ragged): 1 x 1
# 결과 (3d ragged): 2 x (r1) x 2
x = tf.ragged.constant(
[[[1, 2], [3, 4], [5, 6]],
[[7, 8]]],
ragged_rank=1)
y = tf.constant([[10]])
print(x + y)
# x (3d ragged): 2 x (r1) x (r2) x 1
# y (1d tensor): 3
# 결과 (3d ragged): 2 x (r1) x (r2) x 3
x = tf.ragged.constant(
[
[
[[1], [2]],
[],
[[3]],
[[4]],
],
[
[[5], [6]],
[[7]]
]
],
ragged_rank=2)
y = tf.constant([10, 20, 30])
print(x + y)
Explanation: 브로드캐스팅
브로드캐스팅은 다른 형태의 텐서가 요소 별 연산에 적합한 형태를 갖도록 만드는 프로세스입니다.
브로드캐스팅에 대한 자세한 내용은
다음을 참조하십시오:
Numpy: 브로드캐스팅
tf.broadcast_dynamic_shape
tf.broadcast_to
호환 가능한 형태를 갖도록 두 개의 입력 x 와 y 를 브로드캐스팅하는 기본 단계는
다음과 같습니다:
x 와 y 의 차원 수가 동일하지 않은 경우, 외부 차원
(크기 1)을 차원 수가 동일해질 때까지 추가합니다 .
x 와 y 의 크기가 다른 각 차원에 대해:
차원 d에 x 또는 y의 크기가 1 이면, 다른 입력의 크기와 일치하도록
차원 d에서 값을 반복하십시오.
그렇지 않으면 예외가 발생합니다 (x 와 y 는 브로드캐스트와 호환되지
않습니다).
정형 차원에서 텐서의 크기가 단일 숫자 (해당 차원에서
슬라이스 크기)인 경우; 그리고 비정형 차원에서 텐서의 크기가 슬라이스 길이의 목록인 경우
(해당 차원의 모든 슬라이스에 대해).
브로드캐스팅 예제
End of explanation
# x (2d ragged): 3 x (r1)
# y (2d tensor): 3 x 4 # 뒤의 차원은 일치하지 않습니다.
x = tf.ragged.constant([[1, 2], [3, 4, 5, 6], [7]])
y = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
try:
x + y
except tf.errors.InvalidArgumentError as exception:
print(exception)
# x (2d ragged): 3 x (r1)
# y (2d ragged): 3 x (r2) # 비정형 차원은 일치하지 않습니다.
x = tf.ragged.constant([[1, 2, 3], [4], [5, 6]])
y = tf.ragged.constant([[10, 20], [30, 40], [50]])
try:
x + y
except tf.errors.InvalidArgumentError as exception:
print(exception)
# x (3d ragged): 3 x (r1) x 2
# y (3d ragged): 3 x (r1) x 3 # 뒤의 차원은 일치하지 않습니다.
x = tf.ragged.constant([[[1, 2], [3, 4], [5, 6]],
[[7, 8], [9, 10]]])
y = tf.ragged.constant([[[1, 2, 0], [3, 4, 0], [5, 6, 0]],
[[7, 8, 0], [9, 10, 0]]])
try:
x + y
except tf.errors.InvalidArgumentError as exception:
print(exception)
Explanation: 브로드캐스트 하지 않는 형태의 예는 다음과 같습니다:
End of explanation
rt = tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2],
row_splits=[0, 4, 4, 6, 7])
print(rt)
Explanation: RaggedTensor 인코딩
비정형텐서는 RaggedTensor 클래스를 사용하여 인코딩됩니다. 내부적으로, 각
RaggedTensor는 다음으로 구성됩니다:
가변 길이 행을 병합된 목록으로 연결하는 values
텐서
병합된 값을 행으로 나누는 방법을 나타내는 row_splits 벡터,
특히, 행 rt[i]의 값은 슬라이스
rt.values[rt.row_splits[i]:rt.row_splits[i+1]]에 저장됩니다.
End of explanation
rt = tf.RaggedTensor.from_row_splits(
values=tf.RaggedTensor.from_row_splits(
values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
row_splits=[0, 3, 3, 5, 9, 10]),
row_splits=[0, 1, 1, 5])
print(rt)
print("형태: {}".format(rt.shape))
print("비정형 텐서의 차원 : {}".format(rt.ragged_rank))
Explanation: 다수의 비정형 차원
다수의 비정형 차원을 갖는 비정형 텐서는
values 텐서에 대해 중첩된 RaggedTensor를 사용하여 인코딩됩니다. 중첩된 각 RaggedTensor는
단일 비정형 차원을 추가합니다.
End of explanation
rt = tf.RaggedTensor.from_nested_row_splits(
flat_values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
nested_row_splits=([0, 1, 1, 5], [0, 3, 3, 5, 9, 10]))
print(rt)
Explanation: 팩토리 함수 tf.RaggedTensor.from_nested_row_splits는
row_splits 텐서 목록을 제공하여 다수의 비정형 차원으로 RaggedTensor를
직접 생성하는데 사용할 수 있습니다:
End of explanation
rt = tf.RaggedTensor.from_row_splits(
values=[[1, 3], [0, 0], [1, 3], [5, 3], [3, 3], [1, 2]],
row_splits=[0, 3, 4, 6])
print(rt)
print("형태: {}".format(rt.shape))
print("비정형 텐서의 차원 : {}".format(rt.ragged_rank))
Explanation: 정형한 내부 차원
내부 차원이 정형한 비정형 텐서는
values에 다차원 tf.Tensor를 사용하여 인코딩됩니다.
End of explanation
values = [3, 1, 4, 1, 5, 9, 2, 6]
print(tf.RaggedTensor.from_row_splits(values, row_splits=[0, 4, 4, 7, 8, 8]))
print(tf.RaggedTensor.from_row_lengths(values, row_lengths=[4, 0, 3, 1, 0]))
print(tf.RaggedTensor.from_row_starts(values, row_starts=[0, 4, 4, 7, 8]))
print(tf.RaggedTensor.from_row_limits(values, row_limits=[4, 4, 7, 8, 8]))
print(tf.RaggedTensor.from_value_rowids(
values, value_rowids=[0, 0, 0, 0, 2, 2, 2, 3], nrows=5))
Explanation: 대체 가능한 행 분할 방식
RaggedTensor 클래스는 row_splits를 기본 메커니즘으로 사용하여
값이 행으로 분할되는 방법에 대한 정보를 저장합니다. 그러나,
RaggedTensor는 네 가지 대체 가능한 행 분할 방식을 지원하므로 데이터 형식에 따라 더 편리하게
사용할 수 있습니다.
내부적으로, RaggedTensor는 이러한 추가적인 방식을 사용하여 일부 컨텍스트에서 효율성을
향상시킵니다.
<dl>
<dt>행 길이</dt>
<dd>`row_lengths`는 `[nrows]`형태의 벡터로, 각 행의 길이를
지정합니다.</dd>
<dt>행 시작</dt>
<dd>`row_starts`는 `[nrows]`형태의 벡터로, 각 행의 시작 오프셋을
지정합니다. `row_splits[:-1]`와 같습니다.</dd>
<dt>행 제한</dt>
<dd>`row_limits`는 `[nrows]`형태의 벡터로, 각 행의 정지 오프셋을
지정합니다. `row_splits[1:]`와 같습니다.</dd>
<dt>행 인덱스 및 행 수</dt>
<dd>`value_rowids`는 `[nvals]`모양의 벡터로, 값과 일대일로 대응되며
각 값의 행 인덱스를 지정합니다.
특히, `rt[row]`행은 `value_rowids[j]==row`인 `rt.values[j]`값으로 구성됩니다.
\`nrows`는
`RaggedTensor`의 행 수를 지정하는 정수입니다.
특히, `nrows`는 뒤의 빈 행을 나타내는데
사용됩니다.</dd>
</dl>
예를 들어, 다음과 같이 비정형 텐서는 동일합니다:
End of explanation
rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []])
print(" values: {}".format(rt.values))
print(" row_splits: {}".format(rt.row_splits))
print(" row_lengths: {}".format(rt.row_lengths()))
print(" row_starts: {}".format(rt.row_starts()))
print(" row_limits: {}".format(rt.row_limits()))
print("value_rowids: {}".format(rt.value_rowids()))
Explanation: RaggedTensor 클래스는 이러한 각 행 분할 텐서를 생성하는데 사용할 수 있는
메서드를 정의합니다.
End of explanation |
8,564 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Catalyst Cooperative Jupyter Notebook Template
This notebook lays out a standard format and some best practices for creating interactive / exploratory notebooks which can be relatively easily shared between different PUDL users, and turned into reusable Python modules for integration into our underlying Python packages.
Begin with a narrative outline
Each notebook should start with a brief explanation (in Markdown) explaining the purpose of the analysis, and outlining the different stages / steps which are taken to accomplish the analysis.
As the analysis develops, you can add new sections or details to this section.
Notebooks should be runnable
Insofar as it's possible, another PUDL user who has cloned the repository that the notebook is part of should be able to update their pudl-dev conda environment, open the notebook, and run all cells successfully.
If there are required data or other prerequisites that the notebook cannot manage on its own -- like a file that needs to be downloaded by hand and placed in a particular location -- those steps should be laid out clearly at the beginning of the notebook.
Avoid Troublesome Elements
Don't hardcode passwords or access tokens
Most of our work is done in public Github repositories.
No authentication information should ever appear in a notebook.
These values can be stored in environment variables on your local computer.
Do not hardocde values, especially late in the notebook
If the analysis depends on particular choices of input values, those should be called out explicitly at the beginning of the notebook.
(NB
Step1: Configure Display Parameters
Step2: Use Python Logging facilities
Using a logger from the beginning will make the transition into the PUDL package easier.
Creating a logging handler here will also allow you to see the logging output coming from PUDL and other underlying packages.
Step5: Define Functions
In many cases, the eventual product of a notebook analysis is going to be the creation of new, reusable functions that are integrated into the underlying PUDL code. You should begin the process of accumulating and organizing those functions as soon as you notice repeated patterns in your code.
* Functions should be used to encapsulate any potentially reusable code.
* Functions should be defined immediately after the imports, to avoid accidental dependence on zombie variables that are defined further down in the code
* While they may evolve over time, having brief docstrings explaining what they do will help others understand them.
* If there's a particular type of plot or visualization that is made repeatedly in the notebook, it's good to parameterize and functionalize it here too, so that as you refine the presentation of the data and results, those improvements can be made in a single place, and shown uniformly throughout the notebook.
* As these functions mature and become more general purpose tools, you will probably want to start migrating them into their own local module, under a src directory in the same directory as the notebook. You will want to import this module
Step6: Define Notebook Parameters
If there are overarching parameters which determine the nature of the analysis -- which US states to look at, which utilities are of interest, a particular start and end date -- state those clearly at the beginning of the analysis, so that they can be referred to by the rest of the notebook and easily changed if need be.
* If the analysis depends on local (non-PUDL managed) datasets, define the paths to those data here.
* If there are external URLs or other resource locations that will be accessed, define those here as well.
* This is also where you should create your pudl_settings dictionary and connections to your local PUDL databases
Step7: Load Data
Given the above parameters and functions, it should now be possible to load the required data into local variables for further wrangling, analysis, and visualization.
If the data is not yet present on the machine of the person running the notebook, this step should also acquire the data from its original source, and place it in the appropriate location under <PUDL_IN>/data/local/.
If there are steps which have to be done manually here, put them first so that they fail first if the user hasn't read the instructions, and they can fix the situation before a bunch of other work gets done. Try to minimize the amount of work in the filesystem that has to be done manually though.
If this process takes a little while, don't be shy about producing logging output.
Using the %%time cell magic can also help users understand which pieces of work / data acquisition are hard
Step8: Sanity Check Data
If there's any validation that can be done on the data which you've loaded to flag if/when it is inappropriate for the analysis that follows, do it here. If you find the data is unusable, use assert statements or raise Exceptions to stop the notebook from proceeding, and indicate what the problem is.
Step9: Preliminary Data Wrangling
Once all of the data is loaded and looks like it's in good shape, do any initial wrangling that's specific to this particular analysis. This should mostly make use of the higher level functions which were defined above. If this step takes a while, don't be shy about producing logging outputs.
Step10: Data Analysis and Visualization
Now that you've got the required data in a usable form, you can tell the story of your analysis through a mix of visualizations, and further data wrangling steps.
This narrative should be readable, with figures that have titles, legends, and labeled axes as appropriate so others can understand what you're showing them.
The code should be concise and make use of the parameters and functions which you've defined above when possible. Functions should contain comprehensible chunks of work that make sense as one step in the story of the analysis. | Python Code:
%load_ext autoreload
%autoreload 2
# Standard libraries
import logging
import os
import pathlib
import sys
# 3rd party libraries
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import pandas as pd
import seaborn as sns
import sqlalchemy as sa
# Local libraries
import pudl
Explanation: Catalyst Cooperative Jupyter Notebook Template
This notebook lays out a standard format and some best practices for creating interactive / exploratory notebooks which can be relatively easily shared between different PUDL users, and turned into reusable Python modules for integration into our underlying Python packages.
Begin with a narrative outline
Each notebook should start with a brief explanation (in Markdown) explaining the purpose of the analysis, and outlining the different stages / steps which are taken to accomplish the analysis.
As the analysis develops, you can add new sections or details to this section.
Notebooks should be runnable
Insofar as it's possible, another PUDL user who has cloned the repository that the notebook is part of should be able to update their pudl-dev conda environment, open the notebook, and run all cells successfully.
If there are required data or other prerequisites that the notebook cannot manage on its own -- like a file that needs to be downloaded by hand and placed in a particular location -- those steps should be laid out clearly at the beginning of the notebook.
Avoid Troublesome Elements
Don't hardcode passwords or access tokens
Most of our work is done in public Github repositories.
No authentication information should ever appear in a notebook.
These values can be stored in environment variables on your local computer.
Do not hardocde values, especially late in the notebook
If the analysis depends on particular choices of input values, those should be called out explicitly at the beginning of the notebook.
(NB: We should explore ways to parameterize notebooks, papermill is one tool that does this).
Don't hardcode absolute file paths
If anyone is going to be able to use the notebook, the files it uses will need to be stored somewhere that makes sense on both your and other computers.
We assume that anyone using this template has the PUDL package installed, and has a local PUDL data management environment set up.
* Input data that needs to be stored on disk and accessed via a shared location should be saved under <PUDL_IN>/data/local/<data_source>/.
* Intermediate saved data products (e.g. a pickled result of a computationally intensive process) and results should be saved to a location relative to the notebook, and within the directory hierarchy of the repository that the notebook is part of.
Don't require avoidable long-running computations
Consider persisting to disk the results of computations that take more than a few minutes, if the outputs are small enough to be checked into the repository and shared with other users.
Only require the expensive computation to be run if this pre-computed output is not available.
Don't litter
Don't leave lots of additional code laying around, even commented out, "just in case" you want to look at it again later.
Notebooks need to be relatively linear in the end, even though the thought processes and exploratory analyses that generate them may not be.
Once you have a working analysis, either prune those branches, or encapsulate them as options within functions.
Don't load unneccesary libraries
Only import libraries which are required by the notebook, to avoid unnecessary dependencies.
If your analysis requires a new library that isn't yet part of the shared pudl-dev environment, add it to the devtools/environment.yml file so that others will get it when they update their environment.
Related Resources:
Lots of these guidelines are taken directly from Emily Riederer's post: RMarkdown Driven Development.
For more in depth explanation of the motivations behind this layout, do go check it out!
Import Libraries
Because it's very likely that you will be editing the PUDL Python packages or your own local module under development while working in the notebook, use the %autoreload magic with autoreload level 2 to ensure that any changes you've made in those files are always reflected in the code that's running in the notebook.
Put all import statements at the top of the notebook, so everyone can see what its dependencies are up front, and so that if an import is going to fail, it fails early, before the rest of the notebook is run.
Try to avoid importing individual functions and classes from deep within packages, as it may not be clear to other users where those elements came from, later in the notebook, and also to minimize the chance of namespace collisions.
End of explanation
sns.set()
%matplotlib inline
mpl.rcParams['figure.figsize'] = (10,4)
mpl.rcParams['figure.dpi'] = 150
pd.options.display.max_columns = 100
pd.options.display.max_rows = 100
Explanation: Configure Display Parameters
End of explanation
logger=logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
logger.handlers = [handler]
Explanation: Use Python Logging facilities
Using a logger from the beginning will make the transition into the PUDL package easier.
Creating a logging handler here will also allow you to see the logging output coming from PUDL and other underlying packages.
End of explanation
def mcoe_by_fuel(mcoe_df, fuel_type=None):
Select only MCOE records pertaining to a particular fuel type.
Args:
mcoe_df (pandas.DataFrame): A PUDL MCOE dataframe.
fuel_type (str or None): A string indicating what value of
fuel_type_code_pudl should be selected from the input
dataframe. If None, all fuels are retained.
Returns:
pandas.DataFrame: A dataframe containing MCOE records for only a
single PUDL fuel type code.
out_df = mcoe_df
if fuel_type is not None:
out_df = mcoe_df[mcoe_df.fuel_type_code_pudl==fuel_type]
return out_df
def finite_distplot(df, data_col, wt_col=None, nbins=100, max_val=np.infty):
Plot weighted distribution of values less than a maximum value.
Args:
df (pandas.DataFrame): The dataframe containing the data and
weights to plot.
data_col (str): Label of the column containing the data.
wt_col (str or None): Label of the column to use to weight the data.
If None (the default) data is not weighted.
nbins (int): Number of histogram bins to use.
max_val (float): Maximum data value to allow in data visualized.
Returns:
None
df = df[df[data_col] < max_val]
weights = None
if wt_col is not None:
weights = df[wt_col]
_ = sns.distplot(df[data_col], bins=nbins, hist_kws={"weights": weights})
Explanation: Define Functions
In many cases, the eventual product of a notebook analysis is going to be the creation of new, reusable functions that are integrated into the underlying PUDL code. You should begin the process of accumulating and organizing those functions as soon as you notice repeated patterns in your code.
* Functions should be used to encapsulate any potentially reusable code.
* Functions should be defined immediately after the imports, to avoid accidental dependence on zombie variables that are defined further down in the code
* While they may evolve over time, having brief docstrings explaining what they do will help others understand them.
* If there's a particular type of plot or visualization that is made repeatedly in the notebook, it's good to parameterize and functionalize it here too, so that as you refine the presentation of the data and results, those improvements can be made in a single place, and shown uniformly throughout the notebook.
* As these functions mature and become more general purpose tools, you will probably want to start migrating them into their own local module, under a src directory in the same directory as the notebook. You will want to import this module
End of explanation
pudl_settings = pudl.workspace.setup.get_defaults()
display(pudl_settings)
ferc1_engine = sa.create_engine(pudl_settings['ferc1_db'])
display(ferc1_engine)
pudl_engine = sa.create_engine(pudl_settings['pudl_db'])
display(pudl_engine)
# What granularity should we aggregate MCOE data to?
mcoe_freq = "AS" # Annual
# What date range are we interested in here?
mcoe_start_date = "2015-01-01"
mcoe_end_date = "2018-12-31"
my_new_data_url = "https://mynewdata.website.gov/path/to/new/data.csv"
my_new_datadir = pathlib.Path(pudl_settings["data_dir"]) / "new_data_source"
# Store API keys and other secrets in environment variables
# and read them in here, if needed:
# EPA_API_KEY = os.environ["EIA_API_KEY"]
# BLS_API_KEY = os.environ["BLS_API_KEY"]
Explanation: Define Notebook Parameters
If there are overarching parameters which determine the nature of the analysis -- which US states to look at, which utilities are of interest, a particular start and end date -- state those clearly at the beginning of the analysis, so that they can be referred to by the rest of the notebook and easily changed if need be.
* If the analysis depends on local (non-PUDL managed) datasets, define the paths to those data here.
* If there are external URLs or other resource locations that will be accessed, define those here as well.
* This is also where you should create your pudl_settings dictionary and connections to your local PUDL databases
End of explanation
%%time
pudl_out = pudl.output.pudltabl.PudlTabl(
freq=mcoe_freq,
start_date=mcoe_start_date,
end_date=mcoe_end_date,
pudl_engine=pudl_engine,
)
mcoe_df = pudl_out.mcoe()
Explanation: Load Data
Given the above parameters and functions, it should now be possible to load the required data into local variables for further wrangling, analysis, and visualization.
If the data is not yet present on the machine of the person running the notebook, this step should also acquire the data from its original source, and place it in the appropriate location under <PUDL_IN>/data/local/.
If there are steps which have to be done manually here, put them first so that they fail first if the user hasn't read the instructions, and they can fix the situation before a bunch of other work gets done. Try to minimize the amount of work in the filesystem that has to be done manually though.
If this process takes a little while, don't be shy about producing logging output.
Using the %%time cell magic can also help users understand which pieces of work / data acquisition are hard:
End of explanation
assert mcoe_df.capacity_factor.min() >= 0.0
assert mcoe_df.capacity_factor.max() <= 1.5
mean_hr = mcoe_df[np.isfinite(mcoe_df.heat_rate_mmbtu_mwh)].heat_rate_mmbtu_mwh.mean()
assert mean_hr > 5
assert mean_hr < 20
Explanation: Sanity Check Data
If there's any validation that can be done on the data which you've loaded to flag if/when it is inappropriate for the analysis that follows, do it here. If you find the data is unusable, use assert statements or raise Exceptions to stop the notebook from proceeding, and indicate what the problem is.
End of explanation
mcoe_coal = mcoe_by_fuel(mcoe_df, fuel_type="coal")
mcoe_gas = mcoe_by_fuel(mcoe_df, fuel_type="gas")
Explanation: Preliminary Data Wrangling
Once all of the data is loaded and looks like it's in good shape, do any initial wrangling that's specific to this particular analysis. This should mostly make use of the higher level functions which were defined above. If this step takes a while, don't be shy about producing logging outputs.
End of explanation
coal_ax = finite_distplot(mcoe_coal, "heat_rate_mmbtu_mwh", max_val=20)
plt.title("Coal heat rate distribution");
gas_ax = finite_distplot(mcoe_gas, "heat_rate_mmbtu_mwh", max_val=20)
plt.title("Gas heat rate distribution");
Explanation: Data Analysis and Visualization
Now that you've got the required data in a usable form, you can tell the story of your analysis through a mix of visualizations, and further data wrangling steps.
This narrative should be readable, with figures that have titles, legends, and labeled axes as appropriate so others can understand what you're showing them.
The code should be concise and make use of the parameters and functions which you've defined above when possible. Functions should contain comprehensible chunks of work that make sense as one step in the story of the analysis.
End of explanation |
8,565 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejercicios 4
1 Ejercicio
Escribir una función que indique si dos fichas de dominó encajan o no. Las fichas son recibidas en dos tuplas, por ejemplo
Step1: 2 Ejercicio
Define la función media para calcular la media aritmética de los elementos de una lista pasada como parámetro.
1. Utiliza un bucle for para recorrer la lista y calcular la suma de los elementos y el número de elementos.
2. Inicializa la suma a 0 antes del bucle.
3. Inicializa el número de elementos a 0 antes del bucle.
(Otra forma
Step2: 3 Ejercicio
La función farenToCentig convierte grados Farenheit en grados centígrados.
* Utiliza la función farenToCentig para generar la siguiente tabla de conversión
Step3: 4 Ejercicio
Los 15 primeros números triangulares son | Python Code:
# Sol:
x = (3,2)
y = (5,3)
def encaja(x, y):
if x[0] == y[0]:
print("Encajan en la posición X[0] Y[0]")
elif x[0] == y[1]:
print("Encajan en la posición X[0] Y[1]")
elif x[1] == y[0]:
print("Encajan en la posición X[1] Y[0]")
elif x[1] == y[1]:
print("Encajan en la posición X[1] Y[1]")
else:
print("Las fichas no encajan")
return
encaja(x,y)
Explanation: Ejercicios 4
1 Ejercicio
Escribir una función que indique si dos fichas de dominó encajan o no. Las fichas son recibidas en dos tuplas, por ejemplo: (1,3) y (5,3).
End of explanation
# Sol:
a = list(range(1,400,2))
b = [1,2,4,8,16,32]
def media(a):
for i in a:
i = sum(a) / len(a)
return i
media(a)
Explanation: 2 Ejercicio
Define la función media para calcular la media aritmética de los elementos de una lista pasada como parámetro.
1. Utiliza un bucle for para recorrer la lista y calcular la suma de los elementos y el número de elementos.
2. Inicializa la suma a 0 antes del bucle.
3. Inicializa el número de elementos a 0 antes del bucle.
(Otra forma: Usando las funciones sum y len).
Nota: Comprueba que se obtienen los siguientes resultados:
* media(a) = 200.0
* Si b = [], media(b) = 0
End of explanation
# Sol :
F = list(range(0,130,10))
def farenToCentig(F):
return (F-32)*(5/9)
for i in F:
cent = farenToCentig(i)
conversion = round(cent)
print( '%d ºF = %.1f ºC' % (i,conversion))
Explanation: 3 Ejercicio
La función farenToCentig convierte grados Farenheit en grados centígrados.
* Utiliza la función farenToCentig para generar la siguiente tabla de conversión:
0:º F = -18.0º C
10:º F = -13.0º C
20:º F = -7.0º C
...
100:º F = 37.0º C
110:º F = 43.0º C
120:º F = 48.0º C
Nota:
* Genera la lista de valores $[0, ... , 120]$ con la función range.
* Utiliza un bucle for para calcular los grados centígrados de cada elemento de la lista de valores.
End of explanation
# Sol:
def triang_1(n):
a = []
for i in range(n):
an = i * (i + 1 ) / 2
a.append(an)
return a
def triang_2(n):
a = [0]
for i in range(1,n):
a.append(a[i-1]+i)
return a
def triang_3(n):
return [(i*(i+1)/2) for i in range(n)]
%timeit triang_1(30)
%timeit triang_1(30)
%timeit triang_3(30)
Explanation: 4 Ejercicio
Los 15 primeros números triangulares son:
$$
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105]
$$
Define una función triang_1 que reciba un número entero positivo $n$ como parámetro y genere la lista de los $n$ primeros números triangulares. Resuelve el problema aplicando la fórmula $a_n = n * (n + 1) / 2$.
Define una función triang_2 que reciba un número entero positivo $n$ como parámetro y genere la lista de los $n$ primeros números triangulares. Resuelve el problema aplicando la fórmula $a_n = a_{n-1} + n$.
Utiliza la función %timeit para medir tiempos y evaluar qué función se comporta mejor.
End of explanation |
8,566 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify document publication status
Step4: Document Table of Contents
1. Key Properties
2. Key Properties --> Software Properties
3. Key Properties --> Timestep Framework
4. Key Properties --> Meteorological Forcings
5. Key Properties --> Resolution
6. Key Properties --> Tuning Applied
7. Transport
8. Emissions
9. Concentrations
10. Optical Radiative Properties
11. Optical Radiative Properties --> Absorption
12. Optical Radiative Properties --> Mixtures
13. Optical Radiative Properties --> Impact Of H2o
14. Optical Radiative Properties --> Radiative Scheme
15. Optical Radiative Properties --> Cloud Interactions
16. Model
1. Key Properties
Key properties of the aerosol model
1.1. Model Overview
Is Required
Step5: 1.2. Model Name
Is Required
Step6: 1.3. Scheme Scope
Is Required
Step7: 1.4. Basic Approximations
Is Required
Step8: 1.5. Prognostic Variables Form
Is Required
Step9: 1.6. Number Of Tracers
Is Required
Step10: 1.7. Family Approach
Is Required
Step11: 2. Key Properties --> Software Properties
Software properties of aerosol code
2.1. Repository
Is Required
Step12: 2.2. Code Version
Is Required
Step13: 2.3. Code Languages
Is Required
Step14: 3. Key Properties --> Timestep Framework
Physical properties of seawater in ocean
3.1. Method
Is Required
Step15: 3.2. Split Operator Advection Timestep
Is Required
Step16: 3.3. Split Operator Physical Timestep
Is Required
Step17: 3.4. Integrated Timestep
Is Required
Step18: 3.5. Integrated Scheme Type
Is Required
Step19: 4. Key Properties --> Meteorological Forcings
**
4.1. Variables 3D
Is Required
Step20: 4.2. Variables 2D
Is Required
Step21: 4.3. Frequency
Is Required
Step22: 5. Key Properties --> Resolution
Resolution in the aersosol model grid
5.1. Name
Is Required
Step23: 5.2. Canonical Horizontal Resolution
Is Required
Step24: 5.3. Number Of Horizontal Gridpoints
Is Required
Step25: 5.4. Number Of Vertical Levels
Is Required
Step26: 5.5. Is Adaptive Grid
Is Required
Step27: 6. Key Properties --> Tuning Applied
Tuning methodology for aerosol model
6.1. Description
Is Required
Step28: 6.2. Global Mean Metrics Used
Is Required
Step29: 6.3. Regional Metrics Used
Is Required
Step30: 6.4. Trend Metrics Used
Is Required
Step31: 7. Transport
Aerosol transport
7.1. Overview
Is Required
Step32: 7.2. Scheme
Is Required
Step33: 7.3. Mass Conservation Scheme
Is Required
Step34: 7.4. Convention
Is Required
Step35: 8. Emissions
Atmospheric aerosol emissions
8.1. Overview
Is Required
Step36: 8.2. Method
Is Required
Step37: 8.3. Sources
Is Required
Step38: 8.4. Prescribed Climatology
Is Required
Step39: 8.5. Prescribed Climatology Emitted Species
Is Required
Step40: 8.6. Prescribed Spatially Uniform Emitted Species
Is Required
Step41: 8.7. Interactive Emitted Species
Is Required
Step42: 8.8. Other Emitted Species
Is Required
Step43: 8.9. Other Method Characteristics
Is Required
Step44: 9. Concentrations
Atmospheric aerosol concentrations
9.1. Overview
Is Required
Step45: 9.2. Prescribed Lower Boundary
Is Required
Step46: 9.3. Prescribed Upper Boundary
Is Required
Step47: 9.4. Prescribed Fields Mmr
Is Required
Step48: 9.5. Prescribed Fields Mmr
Is Required
Step49: 10. Optical Radiative Properties
Aerosol optical and radiative properties
10.1. Overview
Is Required
Step50: 11. Optical Radiative Properties --> Absorption
Absortion properties in aerosol scheme
11.1. Black Carbon
Is Required
Step51: 11.2. Dust
Is Required
Step52: 11.3. Organics
Is Required
Step53: 12. Optical Radiative Properties --> Mixtures
**
12.1. External
Is Required
Step54: 12.2. Internal
Is Required
Step55: 12.3. Mixing Rule
Is Required
Step56: 13. Optical Radiative Properties --> Impact Of H2o
**
13.1. Size
Is Required
Step57: 13.2. Internal Mixture
Is Required
Step58: 14. Optical Radiative Properties --> Radiative Scheme
Radiative scheme for aerosol
14.1. Overview
Is Required
Step59: 14.2. Shortwave Bands
Is Required
Step60: 14.3. Longwave Bands
Is Required
Step61: 15. Optical Radiative Properties --> Cloud Interactions
Aerosol-cloud interactions
15.1. Overview
Is Required
Step62: 15.2. Twomey
Is Required
Step63: 15.3. Twomey Minimum Ccn
Is Required
Step64: 15.4. Drizzle
Is Required
Step65: 15.5. Cloud Lifetime
Is Required
Step66: 15.6. Longwave Bands
Is Required
Step67: 16. Model
Aerosol model
16.1. Overview
Is Required
Step68: 16.2. Processes
Is Required
Step69: 16.3. Coupling
Is Required
Step70: 16.4. Gas Phase Precursors
Is Required
Step71: 16.5. Scheme Type
Is Required
Step72: 16.6. Bulk Scheme Species
Is Required | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'dwd', 'sandbox-3', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: DWD
Source ID: SANDBOX-3
Topic: Aerosol
Sub-Topics: Transport, Emissions, Concentrations, Optical Radiative Properties, Model.
Properties: 69 (37 required)
Model descriptions: Model description details
Initialized From: --
Notebook Help: Goto notebook help page
Notebook Initialised: 2018-02-15 16:53:57
Document Setup
IMPORTANT: to be executed each time you run the notebook
End of explanation
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
Explanation: Document Authors
Set document authors
End of explanation
# Set as follows: DOC.set_contributor("name", "email")
# TODO - please enter value(s)
Explanation: Document Contributors
Specify document contributors
End of explanation
# Set publication status:
# 0=do not publish, 1=publish.
DOC.set_publication_status(0)
Explanation: Document Publication
Specify document publication status
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.model_overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: Document Table of Contents
1. Key Properties
2. Key Properties --> Software Properties
3. Key Properties --> Timestep Framework
4. Key Properties --> Meteorological Forcings
5. Key Properties --> Resolution
6. Key Properties --> Tuning Applied
7. Transport
8. Emissions
9. Concentrations
10. Optical Radiative Properties
11. Optical Radiative Properties --> Absorption
12. Optical Radiative Properties --> Mixtures
13. Optical Radiative Properties --> Impact Of H2o
14. Optical Radiative Properties --> Radiative Scheme
15. Optical Radiative Properties --> Cloud Interactions
16. Model
1. Key Properties
Key properties of the aerosol model
1.1. Model Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of aerosol model.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.model_name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 1.2. Model Name
Is Required: TRUE Type: STRING Cardinality: 1.1
Name of aerosol model code
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.scheme_scope')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "troposhere"
# "stratosphere"
# "mesosphere"
# "mesosphere"
# "whole atmosphere"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 1.3. Scheme Scope
Is Required: TRUE Type: ENUM Cardinality: 1.N
Atmospheric domains covered by the aerosol model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.basic_approximations')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 1.4. Basic Approximations
Is Required: TRUE Type: STRING Cardinality: 1.1
Basic approximations made in the aerosol model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.prognostic_variables_form')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "3D mass/volume ratio for aerosols"
# "3D number concenttration for aerosols"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 1.5. Prognostic Variables Form
Is Required: TRUE Type: ENUM Cardinality: 1.N
Prognostic variables in the aerosol model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.number_of_tracers')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 1.6. Number Of Tracers
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Number of tracers in the aerosol model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.family_approach')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 1.7. Family Approach
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Are aerosol calculations generalized into families of species?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.software_properties.repository')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 2. Key Properties --> Software Properties
Software properties of aerosol code
2.1. Repository
Is Required: FALSE Type: STRING Cardinality: 0.1
Location of code for this component.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.software_properties.code_version')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 2.2. Code Version
Is Required: FALSE Type: STRING Cardinality: 0.1
Code version identifier.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.software_properties.code_languages')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 2.3. Code Languages
Is Required: FALSE Type: STRING Cardinality: 0.N
Code language(s).
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.timestep_framework.method')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Uses atmospheric chemistry time stepping"
# "Specific timestepping (operator splitting)"
# "Specific timestepping (integrated)"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 3. Key Properties --> Timestep Framework
Physical properties of seawater in ocean
3.1. Method
Is Required: TRUE Type: ENUM Cardinality: 1.1
Mathematical method deployed to solve the time evolution of the prognostic variables
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.timestep_framework.split_operator_advection_timestep')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 3.2. Split Operator Advection Timestep
Is Required: FALSE Type: INTEGER Cardinality: 0.1
Timestep for aerosol advection (in seconds)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.timestep_framework.split_operator_physical_timestep')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 3.3. Split Operator Physical Timestep
Is Required: FALSE Type: INTEGER Cardinality: 0.1
Timestep for aerosol physics (in seconds).
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.timestep_framework.integrated_timestep')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 3.4. Integrated Timestep
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Timestep for the aerosol model (in seconds)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.timestep_framework.integrated_scheme_type')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Explicit"
# "Implicit"
# "Semi-implicit"
# "Semi-analytic"
# "Impact solver"
# "Back Euler"
# "Newton Raphson"
# "Rosenbrock"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 3.5. Integrated Scheme Type
Is Required: TRUE Type: ENUM Cardinality: 1.1
Specify the type of timestep scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.meteorological_forcings.variables_3D')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 4. Key Properties --> Meteorological Forcings
**
4.1. Variables 3D
Is Required: FALSE Type: STRING Cardinality: 0.1
Three dimensionsal forcing variables, e.g. U, V, W, T, Q, P, conventive mass flux
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.meteorological_forcings.variables_2D')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 4.2. Variables 2D
Is Required: FALSE Type: STRING Cardinality: 0.1
Two dimensionsal forcing variables, e.g. land-sea mask definition
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.meteorological_forcings.frequency')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 4.3. Frequency
Is Required: FALSE Type: INTEGER Cardinality: 0.1
Frequency with which meteological forcings are applied (in seconds).
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.resolution.name')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 5. Key Properties --> Resolution
Resolution in the aersosol model grid
5.1. Name
Is Required: TRUE Type: STRING Cardinality: 1.1
This is a string usually used by the modelling group to describe the resolution of this grid, e.g. ORCA025, N512L180, T512L70 etc.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.resolution.canonical_horizontal_resolution')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 5.2. Canonical Horizontal Resolution
Is Required: FALSE Type: STRING Cardinality: 0.1
Expression quoted for gross comparisons of resolution, eg. 50km or 0.1 degrees etc.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.resolution.number_of_horizontal_gridpoints')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 5.3. Number Of Horizontal Gridpoints
Is Required: FALSE Type: INTEGER Cardinality: 0.1
Total number of horizontal (XY) points (or degrees of freedom) on computational grid.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.resolution.number_of_vertical_levels')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 5.4. Number Of Vertical Levels
Is Required: FALSE Type: INTEGER Cardinality: 0.1
Number of vertical levels resolved on computational grid.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.resolution.is_adaptive_grid')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 5.5. Is Adaptive Grid
Is Required: FALSE Type: BOOLEAN Cardinality: 0.1
Default is False. Set true if grid resolution changes during execution.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.tuning_applied.description')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 6. Key Properties --> Tuning Applied
Tuning methodology for aerosol model
6.1. Description
Is Required: TRUE Type: STRING Cardinality: 1.1
General overview description of tuning: explain and motivate the main targets and metrics retained. &Document the relative weight given to climate performance metrics versus process oriented metrics, &and on the possible conflicts with parameterization level tuning. In particular describe any struggle &with a parameter value that required pushing it to its limits to solve a particular model deficiency.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.tuning_applied.global_mean_metrics_used')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 6.2. Global Mean Metrics Used
Is Required: FALSE Type: STRING Cardinality: 0.N
List set of metrics of the global mean state used in tuning model/component
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.tuning_applied.regional_metrics_used')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 6.3. Regional Metrics Used
Is Required: FALSE Type: STRING Cardinality: 0.N
List of regional metrics of mean state used in tuning model/component
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.key_properties.tuning_applied.trend_metrics_used')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 6.4. Trend Metrics Used
Is Required: FALSE Type: STRING Cardinality: 0.N
List observed trend metrics used in tuning model/component
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.transport.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 7. Transport
Aerosol transport
7.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of transport in atmosperic aerosol model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.transport.scheme')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Uses Atmospheric chemistry transport scheme"
# "Specific transport scheme (eulerian)"
# "Specific transport scheme (semi-lagrangian)"
# "Specific transport scheme (eulerian and semi-lagrangian)"
# "Specific transport scheme (lagrangian)"
# TODO - please enter value(s)
Explanation: 7.2. Scheme
Is Required: TRUE Type: ENUM Cardinality: 1.1
Method for aerosol transport modeling
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.transport.mass_conservation_scheme')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Uses Atmospheric chemistry transport scheme"
# "Mass adjustment"
# "Concentrations positivity"
# "Gradients monotonicity"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 7.3. Mass Conservation Scheme
Is Required: TRUE Type: ENUM Cardinality: 1.N
Method used to ensure mass conservation.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.transport.convention')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Uses Atmospheric chemistry transport scheme"
# "Convective fluxes connected to tracers"
# "Vertical velocities connected to tracers"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 7.4. Convention
Is Required: TRUE Type: ENUM Cardinality: 1.N
Transport by convention
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.emissions.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8. Emissions
Atmospheric aerosol emissions
8.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of emissions in atmosperic aerosol model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.emissions.method')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "None"
# "Prescribed (climatology)"
# "Prescribed CMIP6"
# "Prescribed above surface"
# "Interactive"
# "Interactive above surface"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 8.2. Method
Is Required: TRUE Type: ENUM Cardinality: 1.N
Method used to define aerosol species (several methods allowed because the different species may not use the same method).
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.emissions.sources')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Vegetation"
# "Volcanos"
# "Bare ground"
# "Sea surface"
# "Lightning"
# "Fires"
# "Aircraft"
# "Anthropogenic"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 8.3. Sources
Is Required: FALSE Type: ENUM Cardinality: 0.N
Sources of the aerosol species are taken into account in the emissions scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.emissions.prescribed_climatology')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Constant"
# "Interannual"
# "Annual"
# "Monthly"
# "Daily"
# TODO - please enter value(s)
Explanation: 8.4. Prescribed Climatology
Is Required: FALSE Type: ENUM Cardinality: 0.1
Specify the climatology type for aerosol emissions
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.emissions.prescribed_climatology_emitted_species')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8.5. Prescribed Climatology Emitted Species
Is Required: FALSE Type: STRING Cardinality: 0.1
List of aerosol species emitted and prescribed via a climatology
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.emissions.prescribed_spatially_uniform_emitted_species')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8.6. Prescribed Spatially Uniform Emitted Species
Is Required: FALSE Type: STRING Cardinality: 0.1
List of aerosol species emitted and prescribed as spatially uniform
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.emissions.interactive_emitted_species')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8.7. Interactive Emitted Species
Is Required: FALSE Type: STRING Cardinality: 0.1
List of aerosol species emitted and specified via an interactive method
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.emissions.other_emitted_species')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8.8. Other Emitted Species
Is Required: FALSE Type: STRING Cardinality: 0.1
List of aerosol species emitted and specified via an "other method"
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.emissions.other_method_characteristics')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 8.9. Other Method Characteristics
Is Required: FALSE Type: STRING Cardinality: 0.1
Characteristics of the "other method" used for aerosol emissions
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.concentrations.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9. Concentrations
Atmospheric aerosol concentrations
9.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of concentrations in atmosperic aerosol model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.concentrations.prescribed_lower_boundary')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.2. Prescribed Lower Boundary
Is Required: FALSE Type: STRING Cardinality: 0.1
List of species prescribed at the lower boundary.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.concentrations.prescribed_upper_boundary')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.3. Prescribed Upper Boundary
Is Required: FALSE Type: STRING Cardinality: 0.1
List of species prescribed at the upper boundary.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.concentrations.prescribed_fields_mmr')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.4. Prescribed Fields Mmr
Is Required: FALSE Type: STRING Cardinality: 0.1
List of species prescribed as mass mixing ratios.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.concentrations.prescribed_fields_mmr')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 9.5. Prescribed Fields Mmr
Is Required: FALSE Type: STRING Cardinality: 0.1
List of species prescribed as AOD plus CCNs.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 10. Optical Radiative Properties
Aerosol optical and radiative properties
10.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of optical and radiative properties
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.absorption.black_carbon')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 11. Optical Radiative Properties --> Absorption
Absortion properties in aerosol scheme
11.1. Black Carbon
Is Required: FALSE Type: FLOAT Cardinality: 0.1
Absorption mass coefficient of black carbon at 550nm (if non-absorbing enter 0)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.absorption.dust')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 11.2. Dust
Is Required: FALSE Type: FLOAT Cardinality: 0.1
Absorption mass coefficient of dust at 550nm (if non-absorbing enter 0)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.absorption.organics')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 11.3. Organics
Is Required: FALSE Type: FLOAT Cardinality: 0.1
Absorption mass coefficient of organics at 550nm (if non-absorbing enter 0)
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.mixtures.external')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 12. Optical Radiative Properties --> Mixtures
**
12.1. External
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is there external mixing with respect to chemical composition?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.mixtures.internal')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 12.2. Internal
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is there internal mixing with respect to chemical composition?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.mixtures.mixing_rule')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 12.3. Mixing Rule
Is Required: FALSE Type: STRING Cardinality: 0.1
If there is internal mixing with respect to chemical composition then indicate the mixinrg rule
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.impact_of_h2o.size')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 13. Optical Radiative Properties --> Impact Of H2o
**
13.1. Size
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Does H2O impact size?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.impact_of_h2o.internal_mixture')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 13.2. Internal Mixture
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Does H2O impact internal mixture?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.radiative_scheme.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 14. Optical Radiative Properties --> Radiative Scheme
Radiative scheme for aerosol
14.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of radiative scheme
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.radiative_scheme.shortwave_bands')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 14.2. Shortwave Bands
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Number of shortwave bands
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.radiative_scheme.longwave_bands')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 14.3. Longwave Bands
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Number of longwave bands
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 15. Optical Radiative Properties --> Cloud Interactions
Aerosol-cloud interactions
15.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of aerosol-cloud interactions
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.twomey')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 15.2. Twomey
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Is the Twomey effect included?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.twomey_minimum_ccn')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 15.3. Twomey Minimum Ccn
Is Required: FALSE Type: INTEGER Cardinality: 0.1
If the Twomey effect is included, then what is the minimum CCN number?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.drizzle')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 15.4. Drizzle
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Does the scheme affect drizzle?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.cloud_lifetime')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
Explanation: 15.5. Cloud Lifetime
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Does the scheme affect cloud lifetime?
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.longwave_bands')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# TODO - please enter value(s)
Explanation: 15.6. Longwave Bands
Is Required: TRUE Type: INTEGER Cardinality: 1.1
Number of longwave bands
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.model.overview')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
Explanation: 16. Model
Aerosol model
16.1. Overview
Is Required: TRUE Type: STRING Cardinality: 1.1
Overview of atmosperic aerosol model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.model.processes')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Dry deposition"
# "Sedimentation"
# "Wet deposition (impaction scavenging)"
# "Wet deposition (nucleation scavenging)"
# "Coagulation"
# "Oxidation (gas phase)"
# "Oxidation (in cloud)"
# "Condensation"
# "Ageing"
# "Advection (horizontal)"
# "Advection (vertical)"
# "Heterogeneous chemistry"
# "Nucleation"
# TODO - please enter value(s)
Explanation: 16.2. Processes
Is Required: TRUE Type: ENUM Cardinality: 1.N
Processes included in the Aerosol model.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.model.coupling')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Radiation"
# "Land surface"
# "Heterogeneous chemistry"
# "Clouds"
# "Ocean"
# "Cryosphere"
# "Gas phase chemistry"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 16.3. Coupling
Is Required: FALSE Type: ENUM Cardinality: 0.N
Other model components coupled to the Aerosol model
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.model.gas_phase_precursors')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "DMS"
# "SO2"
# "Ammonia"
# "Iodine"
# "Terpene"
# "Isoprene"
# "VOC"
# "NOx"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 16.4. Gas Phase Precursors
Is Required: TRUE Type: ENUM Cardinality: 1.N
List of gas phase aerosol precursors.
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.model.scheme_type')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Bulk"
# "Modal"
# "Bin"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 16.5. Scheme Type
Is Required: TRUE Type: ENUM Cardinality: 1.N
Type(s) of aerosol scheme used by the aerosols model (potentially multiple: some species may be covered by one type of aerosol scheme and other species covered by another type).
End of explanation
# PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.model.bulk_scheme_species')
# PROPERTY VALUE(S):
# Set as follows: DOC.set_value("value")
# Valid Choices:
# "Sulphate"
# "Nitrate"
# "Sea salt"
# "Dust"
# "Ice"
# "Organic"
# "Black carbon / soot"
# "SOA (secondary organic aerosols)"
# "POM (particulate organic matter)"
# "Polar stratospheric ice"
# "NAT (Nitric acid trihydrate)"
# "NAD (Nitric acid dihydrate)"
# "STS (supercooled ternary solution aerosol particule)"
# "Other: [Please specify]"
# TODO - please enter value(s)
Explanation: 16.6. Bulk Scheme Species
Is Required: TRUE Type: ENUM Cardinality: 1.N
List of species covered by the bulk scheme.
End of explanation |
8,567 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First iteration of modeling, going through several different classification algorithms. Of these, Gradient Boosted Classifier using unscaled data worked the best.
For reference/example only.
Step1: Read in data
We did not share our modeling data, so you will have to create your own. The pipeline tool can help you do this. If you save the results to a csv, masterdf_rrt and masterdf_nonrrt are dataframes with the modeling data for each of the positive and negative classes, respectively.
Step2: Modeling portion
Step3: Logistic Regression
Step4: compare to traditional LR...
Step5: LR & LRCV returned essentially the same results!
Let's rerun LR with scaled data. And then calculate
Step6: Scaled version performs (slightly) better
Random Forest
Step7: SVM (kernel
Step8: LDA
Step9: Gradient Boosting (with partial dependence plots)
Step10: Grid search for best GBC
Step11: Best model so far
Step12: Use 3-D plot to investigate feature interactions for weak partial dependence plots... (weak effect may be masked by stronger interaction with other features) | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import cPickle as pickle
%matplotlib notebook
plt.style.use('ggplot')
from sklearn.preprocessing import StandardScaler
from sklearn.cross_validation import train_test_split, KFold
from sklearn.metrics import confusion_matrix, roc_auc_score, precision_score, recall_score, classification_report
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn.feature_selection import f_classif
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.ensemble.partial_dependence import plot_partial_dependence, partial_dependence
from sklearn.grid_search import GridSearchCV
Explanation: First iteration of modeling, going through several different classification algorithms. Of these, Gradient Boosted Classifier using unscaled data worked the best.
For reference/example only.
End of explanation
masterdf_rrt = pd.read_csv('RRT_modeling_table_13hr_raw.csv')
masterdf_nonrrt = pd.read_csv('NonRRT_modeling_table_13hr_raw.csv')
col_use = ['on_iv', 'bu-nal',
'age', 'sex', 'obese', 'smoker', 'prev_rrt',
'DBP_mean', 'DBP_recent', # take the mean of all the measurements & the most recently observed point
'SBP_mean', 'SBP_recent',
'MAP_mean', 'MAP_recent', # mean arterial pressure
'temp_mean', 'temp_recent',# temperature
'SPO2_mean', 'SPO2_recent',
'RR_mean', 'RR_recent', # respiratory rate
'pulse_mean', 'pulse_recent',
'anticoagulants', 'narcotics', 'narc-ans', #narcotic analgesics
'antipsychotics', 'chemo'
]
colsfornan = ['DBP_mean', 'DBP_recent', # take the mean of all the measurements & the most recently observed point
'SBP_mean', 'SBP_recent',
'MAP_mean', 'MAP_recent', # mean arterial pressure
'temp_mean', 'temp_recent',# temperature
'SPO2_mean', 'SPO2_recent',
'RR_mean', 'RR_recent', # respiratory rate
'pulse_mean', 'pulse_recent']
# take out: rrt_ce_id, encntr_id, event_end_dt_tm, timestart, timeend,
# RASS score, GCS score, HR, CO2, O2
X_rrt = masterdf_rrt[col_use]
# if 'obese' is Nan, then set the patient to be not obese.
obesenanmask = np.where(pd.isnull(X_rrt['obese']))[0]
X_rrt.loc[obesenanmask, 'obese'] = 0
# Write out rows that are not all 0/NaNs across. (if all nans, remove this sample)
X_rrt = X_rrt.loc[np.where(X_rrt.ix[:, colsfornan].sum(axis=1, skipna=True)!=0)[0]]
#reset index
X_rrt = X_rrt.reset_index(drop=True)
# take out: encntr_id, not_rrt_time, timestart, timeend,
# RASS score, GCS score, HR, CO2, O2
X_notrrt = masterdf_nonrrt[col_use]
# if 'obese' is Nan, then set the patient to be not obese.
obesenanmask = np.where(pd.isnull(X_notrrt['obese']))[0]
X_notrrt.loc[obesenanmask, 'obese'] = 0
# Write out rows that are NOT all 0/NaNs across.
X_notrrt = X_notrrt.iloc[np.where(X_notrrt.ix[:, colsfornan].sum(axis=1, skipna=True)!=0)[0]]
#reset index
X_notrrt = X_notrrt.reset_index(drop=True)
# make sure to reset index if haven't previously -- I did not run this before saving processed .p files
X_notrrt = X_notrrt.reset_index(drop=True)
X_rrt = X_rrt.reset_index(drop=True)
# additional for non-rrt: drop samples with lots of NaNs since we have plenty of samples
# DROP THE ROWS WHERE PULSE IS NAN
X_notrrt = X_notrrt.ix[np.where(pd.isnull(X_notrrt['pulse_mean'])!=True)[0]]
X_notrrt = X_notrrt.reset_index(drop=True)
# Do a similar thing for all rows with significant nans:
X_notrrt = X_notrrt.ix[np.where(pd.isnull(X_notrrt['RR_mean'])!=True)[0]]
X_notrrt = X_notrrt.reset_index(drop=True)
X_notrrt = X_notrrt.ix[np.where(pd.isnull(X_notrrt['MAP_mean'])!=True)[0]]
X_notrrt = X_notrrt.reset_index(drop=True)
X_notrrt = X_notrrt.ix[np.where(pd.isnull(X_notrrt['temp_mean'])!=True)[0]]
X_notrrt = X_notrrt.reset_index(drop=True)
X_notrrt = X_notrrt.ix[np.where(pd.isnull(X_notrrt['SPO2_mean'])!=True)[0]]
X_notrrt = X_notrrt.reset_index(drop=True)
# add labels to indicate positive or negative class
X_rrt['label'] = 1
X_notrrt['label'] = 0
# Combine the tables
XY = pd.concat([X_rrt, X_notrrt])
XY = XY.reset_index(drop=True)
y = XY.pop('label')
X = XY
# Fill nans with mean of columns
X = X.fillna(X.mean())
# map genders to 1/0
X['is_male'] = X['sex'].map({'M': 1, 'F': 0})
X.pop('sex')
X.describe().T
y.describe().T
Explanation: Read in data
We did not share our modeling data, so you will have to create your own. The pipeline tool can help you do this. If you save the results to a csv, masterdf_rrt and masterdf_nonrrt are dataframes with the modeling data for each of the positive and negative classes, respectively.
End of explanation
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
len(X_train)
def score_printout(X_test, y_test, fittedModel):
print "AUC-ROC Score of model: ", roc_auc_score(y_test, fittedModel.predict_proba(X_test)[:,1])
print "Precision Score of model: ", precision_score(y_test, fittedModel.predict(X_test))
print "Recall Score of model: ", recall_score(y_test, fittedModel.predict(X_test))
Explanation: Modeling portion
End of explanation
lrCV = LogisticRegressionCV(Cs=10, class_weight=None, cv=5, dual=False,
fit_intercept=True, intercept_scaling=1.0, max_iter=100,
multi_class='ovr', n_jobs=1, penalty='l2', random_state=1,
refit=True, scoring='roc_auc', solver='lbfgs', tol=0.0001, verbose=0)
lrCV.fit(X, y)
lrCV.scores_
# Try different solver
lrCV = LogisticRegressionCV(Cs=5, class_weight=None, cv=5, dual=False,
fit_intercept=True, intercept_scaling=1.0, max_iter=100,
multi_class='ovr', n_jobs=1, penalty='l2', random_state=1,
refit=True, scoring='roc_auc', solver='liblinear', tol=0.0001, verbose=0)
lrCV.fit(X_train, y_train)
lrCV.scores_
lrCV.intercept_
lrCV.n_iter_
lrCV.Cs_
score_printout(X_test, y_test, lrCV)
confusion_matrix(y_test, lrCV.predict(X_test))
Explanation: Logistic Regression
End of explanation
lr = LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=-1,
penalty='l2', random_state=1, solver='liblinear', tol=0.0001,
verbose=0, warm_start=False)
lr.fit(X_train, y_train)
score_printout(X_test, y_test, lr)
print classification_report(y_test, lr.predict(X_test))
confusion_matrix(y_test, lr.predict(X_test))
lr.decision_function(X_test)
lr.coef_
lr.intercept_
Explanation: compare to traditional LR...
End of explanation
Xscaled = StandardScaler().fit_transform(X)
Xs_train, Xs_test, ys_train, ys_test = train_test_split(Xscaled, y, test_size=0.3)
lrs = LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=-1,
penalty='l2', random_state=1, solver='liblinear', tol=0.0001,
verbose=0, warm_start=False)
lrs.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, lrs)
print classification_report(ys_test, lrs.predict(Xs_test))
confusion_matrix(ys_test, lrs.predict(Xs_test))
Explanation: LR & LRCV returned essentially the same results!
Let's rerun LR with scaled data. And then calculate
End of explanation
rfs = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
max_depth=None, max_features='auto', max_leaf_nodes=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,
oob_score=False, random_state=None, verbose=0,
warm_start=False)
rfs.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, rfs)
print classification_report(ys_test, rfs.predict(Xs_test))
confusion_matrix(ys_test, rfs.predict(Xs_test))
rf = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
max_depth=None, max_features='auto', max_leaf_nodes=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,
oob_score=False, random_state=None, verbose=0,
warm_start=False)
rf.fit(X_train, y_train)
score_printout(X_test, y_test, rf)
print classification_report(y_test, rf.predict(X_test))
confusion_matrix(y_test, rf.predict(X_test))
# scaled & unscaled random forest looks very similar.
rfs = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='entropy',
max_depth=None, max_features='auto', max_leaf_nodes=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=-1,
oob_score=False, random_state=None, verbose=0,
warm_start=False)
rfs.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, rfs)
print classification_report(ys_test, rfs.predict(Xs_test))
confusion_matrix(ys_test, rfs.predict(Xs_test))
# Increase # estimators
# Note, turning oob score on makes the result worse...
rfs = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='entropy',
max_depth=None, max_features='auto', max_leaf_nodes=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=-1,
oob_score=False, random_state=None, verbose=0,
warm_start=False)
rfs.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, rfs)
print classification_report(ys_test, rfs.predict(Xs_test))
confusion_matrix(ys_test, rfs.predict(Xs_test))
Explanation: Scaled version performs (slightly) better
Random Forest
End of explanation
svms = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=True, random_state=None, shrinking=True,
tol=0.001, verbose=False)
svms.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, svms)
print classification_report(ys_test, svms.predict(Xs_test))
confusion_matrix(ys_test, svms.predict(Xs_test))
svms = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='poly',
max_iter=-1, probability=True, random_state=None, shrinking=True,
tol=0.001, verbose=False)
svms.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, svms)
print classification_report(ys_test, svms.predict(Xs_test))
confusion_matrix(ys_test, svms.predict(Xs_test))
svms = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='linear',
max_iter=-1, probability=True, random_state=None, shrinking=True,
tol=0.001, verbose=False)
svms.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, svms)
print classification_report(ys_test, svms.predict(Xs_test))
confusion_matrix(ys_test, svms.predict(Xs_test))
svms = SVC(C=100.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=True, random_state=None, shrinking=True,
tol=0.001, verbose=False)
svms.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, svms)
print classification_report(ys_test, svms.predict(Xs_test))
confusion_matrix(ys_test, svms.predict(Xs_test))
Explanation: SVM (kernel: sigmoid does not work, rbf appears best)
End of explanation
ldas = LinearDiscriminantAnalysis(n_components=None, priors=None, shrinkage=None,
solver='svd', store_covariance=False, tol=0.0001)
ldas.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, ldas)
print classification_report(ys_test, ldas.predict(Xs_test))
confusion_matrix(ys_test, ldas.predict(Xs_test))
ldas = LinearDiscriminantAnalysis(n_components=None, priors=None, shrinkage='auto',
solver='eigen', store_covariance=False, tol=0.0001)
ldas.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, ldas)
print classification_report(ys_test, ldas.predict(Xs_test))
confusion_matrix(ys_test, ldas.predict(Xs_test))
Explanation: LDA
End of explanation
gbcs = GradientBoostingClassifier(init=None, learning_rate=0.1, loss='deviance',
max_depth=3, max_features=None, max_leaf_nodes=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=100,
presort='auto', random_state=1, subsample=1.0, verbose=0,
warm_start=False)
gbcs.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, gbcs)
print classification_report(ys_test, gbcs.predict(Xs_test))
confusion_matrix(ys_test, gbcs.predict(Xs_test))
# changed subsampling: Choosing subsample < 1.0 leads to a reduction of variance and an increase in bias.
gbcs = GradientBoostingClassifier(init=None, learning_rate=0.1, loss='deviance',
max_depth=3, max_features=None, max_leaf_nodes=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=100,
presort='auto', random_state=1, subsample=0.75, verbose=0,
warm_start=False)
gbcs.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, gbcs)
print classification_report(ys_test, gbcs.predict(Xs_test))
confusion_matrix(ys_test, gbcs.predict(Xs_test))
# tried changing loss to exponential --> worse.
# change max features to sqrt --> worse.
# upped min_samples_split, from 2 to 3, improved. (other values did not cause improvement)
gbcs = GradientBoostingClassifier(init=None, learning_rate=0.1, loss='deviance',
max_depth=3, max_features=None, max_leaf_nodes=None,
min_samples_leaf=1, min_samples_split=3,
min_weight_fraction_leaf=0.0, n_estimators=100,
presort='auto', random_state=1, subsample=0.75, verbose=0,
warm_start=False)
gbcs.fit(Xs_train, ys_train)
score_printout(Xs_test, ys_test, gbcs)
print classification_report(ys_test, gbcs.predict(Xs_test))
confusion_matrix(ys_test, gbcs.predict(Xs_test))
for i, n in enumerate(X.columns.get_values()):
print i, n
fig, axs = plot_partial_dependence(gbcs, Xs_train, range(0, 6, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
fig, axs = plot_partial_dependence(gbcs, Xs_train, range(6, 12, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
fig, axs = plot_partial_dependence(gbcs, Xs_train, range(12, 18, 1), feature_names=X.columns.get_values(), n_jobs=-1, grid_resolution=100)
fig, axs = plot_partial_dependence(gbcs, Xs_train, range(18, 26, 1), feature_names=X.columns.get_values(), n_jobs=-1, grid_resolution=100)
plt.subplots_adjust(top=0.9)
# GBC without scaling works better than GBC with. Hmm.
gbc = GradientBoostingClassifier(init=None, learning_rate=0.1, loss='deviance',
max_depth=3, max_features=None, max_leaf_nodes=None,
min_samples_leaf=1, min_samples_split=3,
min_weight_fraction_leaf=0.0, n_estimators=100,
presort='auto', random_state=1, subsample=0.75, verbose=0,
warm_start=False)
gbc.fit(X_train, y_train)
score_printout(X_test, y_test, gbc)
print classification_report(y_test, gbc.predict(X_test))
confusion_matrix(y_test, gbc.predict(X_test))
fig, axs = plot_partial_dependence(gbc, X_train, range(0, 6, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
plt.subplots_adjust(top=0.9)
fig, axs = plot_partial_dependence(gbc, X_train, range(6, 12, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
plt.subplots_adjust(top=0.9)
fig, axs = plot_partial_dependence(gbc, X_train, range(12, 18, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
plt.subplots_adjust(top=0.9)
fig, axs = plot_partial_dependence(gbc, X_train, range(18, 26, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
plt.subplots_adjust(top=0.9)
gbcRankedFeatures = sorted(zip(X.columns, gbc.feature_importances_),
key=lambda pair: pair[1],
reverse=True)
def make_feature_importance_plot(featuresAndImportances, numFeatures):
topN = featuresAndImportances[:numFeatures]
labels = [pair[0] for pair in topN]
values = [pair[1] for pair in topN]
ind = np.arange(len(values))
width = 0.35
plt.bar(range(numFeatures), values, width=0.8)
ax = plt.subplot(111)
ax.set_xticks(ind+width)
ax.set_xticklabels(labels, rotation=60, size=12)
plt.xlabel('Feature', size=20)
plt.ylabel('Importance', size=20)
plt.show()
plt.figure()
make_feature_importance_plot(gbcRankedFeatures, 26)
plt.tight_layout()
gbc.feature_importances_
Explanation: Gradient Boosting (with partial dependence plots)
End of explanation
# GBC without scaling works better than GBC with. Hmm.
gbc = GradientBoostingClassifier(init=None, learning_rate=0.1, loss='deviance',
max_depth=3, max_features=None, max_leaf_nodes=None,
min_samples_leaf=1, min_samples_split=3,
min_weight_fraction_leaf=0.0, n_estimators=100,
presort='auto', random_state=1, subsample=0.75, verbose=0,
warm_start=False)
gbc.fit(X_train, y_train)
score_printout(X_test, y_test, gbc)
print classification_report(y_test, gbc.predict(X_test))
confusion_matrix(y_test, gbc.predict(X_test))
paramGrid = {'n_estimators': [100, 200, 300],
'learning_rate': [0.1, 0.5, 0.75, 0.2],
'max_depth': [3, 4, 5, 6],
'min_samples_leaf': [1, 2],
'subsample': [0.75],
'loss': ['deviance'],
'max_features': [None, 'auto']
}
gs = GridSearchCV(GradientBoostingClassifier(),
param_grid=paramGrid,
scoring='roc_auc',
n_jobs=-1,
cv=5,
verbose=10)
gs.fit(X_train, y_train)
gs.best_estimator_
Explanation: Grid search for best GBC
End of explanation
gbcModel = GradientBoostingClassifier(init=None, learning_rate=0.1, loss='deviance',
max_depth=3, max_features='auto', max_leaf_nodes=None,
min_samples_leaf=2, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=200,
presort='auto', random_state=None, subsample=0.75, verbose=0,
warm_start=False)
gbcModel.fit(X_train, y_train)
gbcRankedFeatures = sorted(zip(X.columns, gbcModel.feature_importances_),
key=lambda pair: pair[1],
reverse=True)
def make_feature_importance_plot(featuresAndImportances, numFeatures):
topN = featuresAndImportances[:numFeatures]
labels = [pair[0] for pair in topN]
values = [pair[1] for pair in topN]
ind = np.arange(len(values))
width = 0.35
plt.bar(range(numFeatures), values, width=0.8)
ax = plt.subplot(111)
ax.set_xticks(ind+width)
ax.set_xticklabels(labels, rotation=60, size=12)
plt.xlabel('Feature', size=20)
plt.ylabel('Importance', size=20)
plt.show()
score_printout(X_test, y_test, gbcModel)
print classification_report(y_test, gbcModel.predict(X_test))
confusion_matrix(y_test, gbcModel.predict(X_test))
gbcRankedFeatures = sorted(zip(X.columns, gbcModel.feature_importances_),
key=lambda pair: pair[1],
reverse=True)
plt.figure()
make_feature_importance_plot(gbcRankedFeatures, 15)
plt.tight_layout()
fig, axs = plot_partial_dependence(gbcModel, X_train, range(1, 6, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
plt.subplots_adjust(top=0.9)
fig, axs = plot_partial_dependence(gbcModel, X_train, range(6, 12, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
plt.subplots_adjust(top=0.9)
fig, axs = plot_partial_dependence(gbcModel, X_train, range(6, 8, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
plt.subplots_adjust(top=0.9)
fig, axs = plot_partial_dependence(gbcModel, X_train, range(18, 24, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
plt.subplots_adjust(top=0.9)
fig, axs = plot_partial_dependence(gbcModel, X_train, range(24, 26, 1), feature_names=X.columns.get_values(), n_jobs=3, grid_resolution=50)
plt.subplots_adjust(top=0.9)
Explanation: Best model so far: GBC!
End of explanation
names
from mpl_toolkits.mplot3d import Axes3D
# not quite getting the results I was expecting. Needs work.
fig = plt.figure()
names = X_train.columns
target_feature = (3, 21)
pdp, (x_axis, y_axis) = partial_dependence(gbcModel, target_feature,
X=X_train, grid_resolution=50)
XX, YY = np.meshgrid(x_axis, y_axis)
Z = pdp.T.reshape(XX.shape).T
ax = Axes3D(fig)
surf = ax.plot_surface(XX, YY, Z, rstride=1, cstride=1, cmap=plt.cm.BuPu)
ax.set_xlabel(names[target_feature[0]])
ax.set_ylabel(names[target_feature[1]])
ax.set_zlabel('Partial dependence')
# pretty init view
ax.view_init(elev=22, azim=122)
plt.colorbar(surf)
plt.suptitle('')
plt.subplots_adjust(top=0.9)
plt.show()
Explanation: Use 3-D plot to investigate feature interactions for weak partial dependence plots... (weak effect may be masked by stronger interaction with other features)
End of explanation |
8,568 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
网络科学理论简介
天涯论坛的回帖网络分析
王成军
wangchengjun@nju.edu.cn
计算传播网 http
Step1: Extract @
Step2: @贾也2012-10-297 | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
dtt = []
file_path = '../data/tianya_bbs_threads_network.txt'
with open(file_path, 'r') as f:
for line in f:
pnum, link, time, author_id, author,\
content = line.replace('\n', '').split('\t')
dtt.append([pnum, link, time, author_id, author, content])
len(dtt)
import pandas as pd
dt = pd.DataFrame(dtt)
dt=dt.rename(columns = {0:'page_num', 1:'link', 2:'time', 3:'author',4:'author_name', 5:'reply'})
dt[:5]
# extract date from datetime
date = [i[:10] for i in dt.time]
dt['date'] = pd.to_datetime(date)
dt[:5]
import pandas as pd
df = pd.read_csv('../data/tianya_bbs_threads_list.txt', sep = "\t", header=None)
df=df.rename(columns = {0:'title', 1:'link', 2:'author',3:'author_page', 4:'click', 5:'reply', 6:'time'})
df[:2]
from collections import defaultdict
link_user_dict = defaultdict(list)
for i in range(len(dt)):
link_user_dict[dt.link[i]].append(dt.author[i])
df['user'] = [len(link_user_dict[l]) for l in df.link]
df[:2]
import statsmodels.api as sm
import numpy as np
x = np.log(df.user+1)
y = np.log(df.reply+1)
xx = sm.add_constant(x, prepend=True)
res = sm.OLS(y,xx).fit()
constant,beta = res.params
r2 = res.rsquared
fig = plt.figure(figsize=(8, 4),facecolor='white')
plt.plot(df.user, df.reply, 'rs', label= 'Data')
plt.plot(np.exp(x), np.exp(constant + x*beta),"-", label = 'Fit')
plt.yscale('log');plt.xscale('log')
plt.xlabel(r'$Users$', fontsize = 20)
plt.ylabel(r'$Replies$', fontsize = 20)
plt.text(max(df.user)/300,max(df.reply)/20,
r'$\beta$ = ' + str(round(beta,2)) +'\n' + r'$R^2$ = ' + str(round(r2, 2)))
plt.legend(loc=2,fontsize=10, numpoints=1)
plt.axis('tight')
plt.show()
x = np.log(df.user+1)
y = np.log(df.click+1)
xx = sm.add_constant(x, prepend=True)
res = sm.OLS(y,xx).fit()
constant,beta = res.params
r2 = res.rsquared
fig = plt.figure(figsize=(8, 4),facecolor='white')
plt.plot(df.user, df.click, 'rs', label= 'Data')
plt.plot(np.exp(x), np.exp(constant + x*beta),"-", label = 'Fit')
plt.yscale('log');plt.xscale('log')
plt.xlabel(r'$Users$', fontsize = 20)
plt.ylabel(r'$Clicks$', fontsize = 20)
plt.text(max(df.user)/300,max(df.click)/20,
r'$\beta$ = ' + str(round(beta,2)) +'\n' + r'$R^2$ = ' + str(round(r2, 2)))
plt.legend(loc=2,fontsize=10, numpoints=1)
plt.axis('tight')
plt.show()
# convert str to datetime format
dt.time = pd.to_datetime(dt.time)
dt['month'] = dt.time.dt.month
dt['year'] = dt.time.dt.year
dt['day'] = dt.time.dt.day
type(dt.time[0])
d = dt.year.value_counts()
dd = pd.DataFrame(d)
dd = dd.sort_index(axis=0, ascending=True)
ds = dd.cumsum()
def getDate(dat):
dat_date_str = map(lambda x: str(x) +'-01-01', dat.index)
dat_date = pd.to_datetime(list(dat_date_str))
return dat_date
ds.date = getDate(ds)
dd.date = getDate(dd)
fig = plt.figure(figsize=(12,5))
plt.plot(ds.date, ds.year, 'g-s', label = '$Cumulative\: Number\:of\: Threads$')
plt.plot(dd.date, dd.year, 'r-o', label = '$Yearly\:Number\:of\:Threads$')
#plt.yscale('log')
plt.legend(loc=2,numpoints=1,fontsize=13)
plt.show()
Explanation: 网络科学理论简介
天涯论坛的回帖网络分析
王成军
wangchengjun@nju.edu.cn
计算传播网 http://computational-communication.com
End of explanation
dt.reply[:55]
Explanation: Extract @
End of explanation
import re
tweet = u"//@lilei: dd //@Bob: cc//@Girl: dd//@魏武: \
利益所致 自然念念不忘// @诺什: 吸引优质 客户,摆脱屌丝男!!!//@MarkGreene: 转发微博"
RTpattern = r'''//?@(\w+)'''
for word in re.findall(RTpattern, tweet, re.UNICODE):
print(word)
print(dt.reply[11])
RTpattern = r'''@(\w+)\s'''
re.findall(RTpattern, dt.reply[11], re.UNICODE)
if re.findall(RTpattern, dt.reply[0], re.UNICODE):
print(True)
else:
print(False)
for k, tweet in enumerate(dt.reply[:100]):
# tweet = tweet.decode('utf8')
RTpattern = r'''@(\w+)\s'''
for person in re.findall(RTpattern, tweet, re.UNICODE):
print(k,'\t',dt.author_name[k],'\t', person,'\t\t', tweet[:30])
print(dt.reply[80])
link_author_dict = {}
for i in range(len(df)):
link_author_dict[df.link[i]] =df.author[i]
graph = []
for k, tweet in enumerate(dt.reply):
url = dt.link[k]
RTpattern = r'''@(\w+)\s'''
persons = re.findall(RTpattern, tweet, re.UNICODE)
if persons:
for person in persons:
graph.append([dt.author_name[k], person])
else:
graph.append( [dt.author_name[k], link_author_dict[url]] )
len(graph)
for x, y in graph[:3]:
print(x, y)
import networkx as nx
G = nx.DiGraph()
for x,y in graph:
if x != y:
G.add_edge(x,y)
nx.info(G)
GU=G.to_undirected(reciprocal=True)
graphs = list(nx.connected_component_subgraphs(GU))
import numpy as np
size = []
for i in graphs:
size.append(len(i.nodes()))
len(size), np.max(size)
gs = []
for i in graphs:
if len(i.nodes()) >5:
gs.append(i)
len(gs)
for g in gs:
print(len(g.nodes()))
g_max = gs[1]
len(g_max.nodes())
pos = nx.spring_layout(g_max)
#定义一个布局,此处采用了spectral布局方式,后变还会介绍其它布局方式,注意图形上的区别
nx.draw(g_max,pos,with_labels=False,node_size = 30)
#绘制规则图的图形,with_labels决定节点是非带标签(编号),node_size是节点的直径
plt.show() #显示图形
# with open('../data/tianya_network_120.csv', 'a') as f:
# for x, y in g_max.edges():
# f.write(x + ',' + y + '\n')
Explanation: @贾也2012-10-297:59:00 导语:人人宁波,面朝大海,春暖花开 ........
@兰质薰心2012-10-2908:55:52 楼主好文! 相信政府一定有能力解决好这些...
回复第20楼,@rual_f “我相信官场中,许多官员应该葆有社会正能量” 通篇好文,顶...
End of explanation |
8,569 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers. At the end, you'll get to see your neural network's predictions on the sample images.
Get the Data
Run the following cell to download the CIFAR-10 dataset for python.
Step2: Explore the Data
The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following
Step5: Implement Preprocess Functions
Normalize
In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x.
Step8: One-hot encode
Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to one_hot_encode. Make sure to save the map of encodings outside the function.
Hint
Step10: Randomize Data
As you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset.
Preprocess all the data and save it
Running the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation.
Step12: Check Point
This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
Step17: Build the network
For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project.
Note
Step20: Convolution and Max Pooling Layer
Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling
Step23: Flatten Layer
Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option
Step26: Fully-Connected Layer
Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option
Step29: Output Layer
Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option
Step32: Create Convolutional Model
Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model
Step35: Train the Neural Network
Single Optimization
Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following
Step37: Show Stats
Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy.
Step38: Hyperparameters
Tune the following parameters
Step40: Train on a Single CIFAR-10 Batch
Instead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section.
Step42: Fully Train the Model
Now that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches.
Step45: Checkpoint
The model has been saved to disk.
Test Model
Test your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters. | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset if present
floyd_cifar10_location = '/input/cifar-10/python.tar.gz'
if isfile(floyd_cifar10_location):
tar_gz_path = floyd_cifar10_location
else:
tar_gz_path = 'cifar-10-python.tar.gz'
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_size=None):
self.total = total_size
self.update((block_num - self.last_block) * block_size)
self.last_block = block_num
if not isfile(tar_gz_path):
with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar:
urlretrieve(
'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',
tar_gz_path,
pbar.hook)
if not isdir(cifar10_dataset_folder_path):
with tarfile.open(tar_gz_path) as tar:
tar.extractall()
tar.close()
tests.test_folder_path(cifar10_dataset_folder_path)
Explanation: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers. At the end, you'll get to see your neural network's predictions on the sample images.
Get the Data
Run the following cell to download the CIFAR-10 dataset for python.
End of explanation
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import helper
import numpy as np
# Explore the dataset
batch_id = 4
sample_id = 2
helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)
Explanation: Explore the Data
The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following:
* airplane
* automobile
* bird
* cat
* deer
* dog
* frog
* horse
* ship
* truck
Understanding a dataset is part of making predictions on the data. Play around with the code cell below by changing the batch_id and sample_id. The batch_id is the id for a batch (1-5). The sample_id is the id for a image and label pair in the batch.
Ask yourself "What are all possible labels?", "What is the range of values for the image data?", "Are the labels in order or random?". Answers to questions like these will help you preprocess the data and end up with better predictions.
End of explanation
def normalize(x):
Normalize a list of sample image data in the range of 0 to 1
: x: List of image data. The image shape is (32, 32, 3)
: return: Numpy array of normalize data
# TODO: Implement Function
# return None
a = 0
b = 255
return (x-a)/(b-a)
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_normalize(normalize)
Explanation: Implement Preprocess Functions
Normalize
In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x.
End of explanation
def one_hot_encode(x):
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
# TODO: Implement Function
# return None
y = np.zeros((len(x), 10))
for i in range(len(x)):
y[i,x[i]] = 1
return y
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_one_hot_encode(one_hot_encode)
Explanation: One-hot encode
Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to one_hot_encode. Make sure to save the map of encodings outside the function.
Hint: Don't reinvent the wheel.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
# Preprocess Training, Validation, and Testing Data
helper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode)
Explanation: Randomize Data
As you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset.
Preprocess all the data and save it
Running the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
import pickle
import problem_unittests as tests
import helper
# Load the Preprocessed Validation data
valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb'))
Explanation: Check Point
This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
End of explanation
import tensorflow as tf
# Network Parameters
#n_input = 3072 # MNIST data input (img shape: 28*28)
#n_classes = 10 # MNIST total classes (0-9 digits)
dropout = 0.75 # Dropout, probability to keep units
def neural_net_image_input(image_shape):
Return a Tensor for a bach of image input
: image_shape: Shape of the images
: return: Tensor for image input.
# TODO: Implement Function
# return None
#print(image_shape)
# return tf.placeholder(tf.float32, shape=(32, 32, 3))
return tf.placeholder(tf.float32, shape=[None, image_shape[0], image_shape[1], image_shape[2]], name='x')
def neural_net_label_input(n_classes):
Return a Tensor for a batch of label input
: n_classes: Number of classes
: return: Tensor for label input.
# TODO: Implement Function
#print(n_classes)
return tf.placeholder(tf.float32, [None, n_classes], name='y')
def neural_net_keep_prob_input():
Return a Tensor for keep probability
: return: Tensor for keep probability.
# TODO: Implement Function
return tf.placeholder(tf.float32, None, name='keep_prob')
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tf.reset_default_graph()
tests.test_nn_image_inputs(neural_net_image_input)
tests.test_nn_label_inputs(neural_net_label_input)
tests.test_nn_keep_prob_inputs(neural_net_keep_prob_input)
Explanation: Build the network
For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project.
Note: If you're finding it hard to dedicate enough time for this course each week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages to build each layer, except the layers you build in the "Convolutional and Max Pooling Layer" section. TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup.
However, if you would like to get the most out of this course, try to solve all the problems without using anything from the TF Layers packages. You can still use classes from other packages that happen to have the same name as ones you find in TF Layers! For example, instead of using the TF Layers version of the conv2d class, tf.layers.conv2d, you would want to use the TF Neural Network version of conv2d, tf.nn.conv2d.
Let's begin!
Input
The neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions
* Implement neural_net_image_input
* Return a TF Placeholder
* Set the shape using image_shape with batch size set to None.
* Name the TensorFlow placeholder "x" using the TensorFlow name parameter in the TF Placeholder.
* Implement neural_net_label_input
* Return a TF Placeholder
* Set the shape using n_classes with batch size set to None.
* Name the TensorFlow placeholder "y" using the TensorFlow name parameter in the TF Placeholder.
* Implement neural_net_keep_prob_input
* Return a TF Placeholder for dropout keep probability.
* Name the TensorFlow placeholder "keep_prob" using the TensorFlow name parameter in the TF Placeholder.
These names will be used at the end of the project to load your saved model.
Note: None for shapes in TensorFlow allow for a dynamic size.
End of explanation
from math import sqrt
def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):
Apply convolution then max pooling to x_tensor
:param x_tensor: TensorFlow Tensor
:param conv_num_outputs: Number of outputs for the convolutional layer
:param conv_ksize: kernal size 2-D Tuple for the convolutional layer
:param conv_strides: Stride 2-D Tuple for convolution
:param pool_ksize: kernal size 2-D Tuple for pool
:param pool_strides: Stride 2-D Tuple for pool
: return: A tensor that represents convolution and max pooling of x_tensor
# TODO: Implement Function
#print(x_tensor)
input_channel_depth = int(x_tensor.get_shape()[3])
# The shape of the filter weight is (height, width, input_depth, output_depth)
filter_weights = sqrt(2.0/conv_num_outputs) * tf.Variable(tf.truncated_normal([*conv_ksize, input_channel_depth, conv_num_outputs], dtype=tf.float32))
print(filter_weights)
# The shape of the biases is equal the the number of outputs of the conv layer
filter_biases = tf.Variable(tf.constant(0, shape=[conv_num_outputs], dtype=tf.float32))
layer = tf.nn.conv2d(input=x_tensor, filter=filter_weights, strides=[1, *conv_strides, 1], padding='SAME')
layer += filter_biases
layer = tf.nn.max_pool(layer, [1, *pool_ksize, 1], strides=[1, *pool_strides, 1], padding='SAME')
layer = tf.nn.relu(layer)
return layer
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_con_pool(conv2d_maxpool)
Explanation: Convolution and Max Pooling Layer
Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling:
* Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor.
* Apply a convolution to x_tensor using weight and conv_strides.
* We recommend you use same padding, but you're welcome to use any padding.
* Add bias
* Add a nonlinear activation to the convolution.
* Apply Max Pooling using pool_ksize and pool_strides.
* We recommend you use same padding, but you're welcome to use any padding.
Note: You can't use TensorFlow Layers or TensorFlow Layers (contrib) for this layer, but you can still use TensorFlow's Neural Network package. You may still use the shortcut option for all the other layers.
End of explanation
from numpy import prod
def flatten(x_tensor):
Flatten x_tensor to (Batch Size, Flattened Image Size)
: x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.
: return: A tensor of size (Batch Size, Flattened Image Size).
# TODO: Implement Function
batch_size = x_tensor.get_shape()[0]
#flattened_image_size = x_tensor.get_shape()[1]*x_tensor.get_shape()[2]*x_tensor.get_shape()[3]
#print(flattened_image_size)
#return tf.contrib.layers.flatten(x_tensor,[batch_size,flattened_image_size])
#return tf.reshape(x_tensor, [batch_size,flattened_image_size])
dimension = x_tensor.get_shape().as_list()
#print(prod(dimension[1:]))
return tf.reshape(x_tensor,[-1,prod(dimension[1:])])
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_flatten(flatten)
Explanation: Flatten Layer
Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.
End of explanation
def fully_conn(x_tensor, num_outputs):
Apply a fully connected layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_outputs.
# TODO: Implement Function
# return None
#print(x_tensor)
#print(num_outputs)
shape = x_tensor.get_shape().as_list()[1:]
shape.append(num_outputs)
#print(shape)
weight = tf.Variable(tf.truncated_normal(shape,0,0.1))
bias = tf.Variable(tf.zeros(num_outputs))
return tf.nn.relu(tf.add(tf.matmul(x_tensor,weight), bias))
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_fully_conn(fully_conn)
Explanation: Fully-Connected Layer
Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.
End of explanation
def output(x_tensor, num_outputs):
Apply a output layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_outputs.
# TODO: Implement Function
#return None
shape = x_tensor.get_shape().as_list()[1:]
shape.append(num_outputs)
#print(shape)
weight = tf.Variable(tf.truncated_normal(shape,0,0.01))
bias = tf.Variable(tf.zeros(num_outputs))
return tf.add(tf.matmul(x_tensor,weight), bias)
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_output(output)
Explanation: Output Layer
Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.
Note: Activation, softmax, or cross entropy should not be applied to this.
End of explanation
def conv_net(x, keep_prob):
Create a convolutional neural network model
: x: Placeholder tensor that holds image data.
: keep_prob: Placeholder tensor that hold dropout keep probability.
: return: Tensor that represents logits
# TODO: Apply 1, 2, or 3 Convolution and Max Pool layers
# Play around with different number of outputs, kernel size and stride
# Function Definition from Above:
# conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides)
#print(x)
x_tensor = x
conv_num_outputs = 10
conv_ksize = (4, 4)
conv_strides = (1, 1)
pool_ksize = (8, 8)
pool_strides = (1, 1)
model = conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides)
# Apply some dropout
model = tf.nn.dropout(model, keep_prob)
# TODO: Apply a Flatten Layer
# Function Definition from Above:
model = flatten(model)
# TODO: Apply 1, 2, or 3 Fully Connected Layers
# Play around with different number of outputs
# Function Definition from Above:
num_outputs = 10
model = fully_conn(model, num_outputs)
# TODO: Apply an Output Layer
# Set this to the number of classes
# Function Definition from Above:
model = output(model, num_outputs)
# TODO: return output
return model
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
##############################
## Build the Neural Network ##
##############################
# Remove previous weights, bias, inputs, etc..
tf.reset_default_graph()
# Inputs
x = neural_net_image_input((32, 32, 3))
y = neural_net_label_input(10)
keep_prob = neural_net_keep_prob_input()
# Model
logits = conv_net(x, keep_prob)
# Name logits Tensor, so that is can be loaded from disk after training
logits = tf.identity(logits, name='logits')
# Loss and Optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer = tf.train.AdamOptimizer().minimize(cost)
# Accuracy
correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')
tests.test_conv_net(conv_net)
Explanation: Create Convolutional Model
Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model:
Apply 1, 2, or 3 Convolution and Max Pool layers
Apply a Flatten Layer
Apply 1, 2, or 3 Fully Connected Layers
Apply an Output Layer
Return the output
Apply TensorFlow's Dropout to one or more layers in the model using keep_prob.
End of explanation
def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch):
Optimize the session on a batch of images and labels
: session: Current TensorFlow session
: optimizer: TensorFlow optimizer function
: keep_probability: keep probability
: feature_batch: Batch of Numpy image data
: label_batch: Batch of Numpy label data
# TODO: Implement Function
session.run(optimizer, feed_dict={x:feature_batch, y:label_batch, keep_prob:keep_probability})
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
tests.test_train_nn(train_neural_network)
Explanation: Train the Neural Network
Single Optimization
Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following:
* x for image input
* y for labels
* keep_prob for keep probability for dropout
This function will be called for each batch, so tf.global_variables_initializer() has already been called.
Note: Nothing needs to be returned. This function is only optimizing the neural network.
End of explanation
def print_stats(session, feature_batch, label_batch, cost, accuracy):
Print information about loss and validation accuracy
: session: Current TensorFlow session
: feature_batch: Batch of Numpy image data
: label_batch: Batch of Numpy label data
: cost: TensorFlow cost function
: accuracy: TensorFlow accuracy function
# TODO: Implement Function
#pass
# Loss and Optimizer
#cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
#optimizer = tf.train.AdamOptimizer().minimize(cost)
# Accuracy
#correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
#accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')
#print(cost, accuracy)
loss = session.run(cost, feed_dict={x:feature_batch, y:label_batch, keep_prob:1.0})
valid_acc = sess.run(accuracy, feed_dict={
x: valid_features,
y: valid_labels,
keep_prob: 1.})
print('Loss: {:>10.4f} Validation Accuracy: {:.6f}'.format(
loss,
valid_acc))
Explanation: Show Stats
Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy.
End of explanation
# TODO: Tune Parameters
epochs = 200
batch_size = 256
keep_probability = 0.60
Explanation: Hyperparameters
Tune the following parameters:
* Set epochs to the number of iterations until the network stops learning or start overfitting
* Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory:
* 64
* 128
* 256
* ...
* Set keep_probability to the probability of keeping a node using dropout
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
print('Checking the Training on a Single Batch...')
with tf.Session() as sess:
# Initializing the variables
sess.run(tf.global_variables_initializer())
# Training cycle
for epoch in range(epochs):
batch_i = 1
for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):
train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)
print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='')
print_stats(sess, batch_features, batch_labels, cost, accuracy)
Explanation: Train on a Single CIFAR-10 Batch
Instead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
save_model_path = './image_classification'
print('Training...')
with tf.Session() as sess:
# Initializing the variables
sess.run(tf.global_variables_initializer())
# Training cycle
for epoch in range(epochs):
# Loop over all batches
n_batches = 5
for batch_i in range(1, n_batches + 1):
for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):
train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)
print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='')
print_stats(sess, batch_features, batch_labels, cost, accuracy)
# Save Model
saver = tf.train.Saver()
save_path = saver.save(sess, save_model_path)
Explanation: Fully Train the Model
Now that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches.
End of explanation
DON'T MODIFY ANYTHING IN THIS CELL
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import tensorflow as tf
import pickle
import helper
import random
# Set batch size if not already set
try:
if batch_size:
pass
except NameError:
batch_size = 64
import os
print(os.getcwd())
save_model_path = './image_classification'
n_samples = 4
top_n_predictions = 3
def test_model():
Test the saved model against the test dataset
test_features, test_labels = pickle.load(open('preprocess_training.p', mode='rb'))
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
# Load model
loader = tf.train.import_meta_graph(save_model_path + '.meta')
loader.restore(sess, save_model_path)
# Get Tensors from loaded model
loaded_x = loaded_graph.get_tensor_by_name('x:0')
loaded_y = loaded_graph.get_tensor_by_name('y:0')
loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')
loaded_logits = loaded_graph.get_tensor_by_name('logits:0')
loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0')
# Get accuracy in batches for memory limitations
test_batch_acc_total = 0
test_batch_count = 0
for train_feature_batch, train_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size):
test_batch_acc_total += sess.run(
loaded_acc,
feed_dict={loaded_x: train_feature_batch, loaded_y: train_label_batch, loaded_keep_prob: 1.0})
test_batch_count += 1
print('Testing Accuracy: {}\n'.format(test_batch_acc_total/test_batch_count))
# Print Random Samples
random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples)))
random_test_predictions = sess.run(
tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions),
feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0})
helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions)
test_model()
Explanation: Checkpoint
The model has been saved to disk.
Test Model
Test your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters.
End of explanation |
8,570 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
So I fed the testing data, but when I try to test it with clf.predict() it just gives me an error. So I want it to predict on the data that i give, which is the last close price, the moving averages. However everytime i try something it just gives me an error. Also is there a better way to do this than on pandas. | Problem:
from sklearn import tree
import pandas as pd
import pandas_datareader as web
import numpy as np
df = web.DataReader('goog', 'yahoo', start='2012-5-1', end='2016-5-20')
df['B/S'] = (df['Close'].diff() < 0).astype(int)
closing = (df.loc['2013-02-15':'2016-05-21'])
ma_50 = (df.loc['2013-02-15':'2016-05-21'])
ma_100 = (df.loc['2013-02-15':'2016-05-21'])
ma_200 = (df.loc['2013-02-15':'2016-05-21'])
buy_sell = (df.loc['2013-02-15':'2016-05-21']) # Fixed
close = pd.DataFrame(closing)
ma50 = pd.DataFrame(ma_50)
ma100 = pd.DataFrame(ma_100)
ma200 = pd.DataFrame(ma_200)
buy_sell = pd.DataFrame(buy_sell)
clf = tree.DecisionTreeRegressor()
x = np.concatenate([close, ma50, ma100, ma200], axis=1)
y = buy_sell
clf.fit(x, y)
close_buy1 = close[:-1]
m5 = ma_50[:-1]
m10 = ma_100[:-1]
ma20 = ma_200[:-1]
# b = np.concatenate([close_buy1, m5, m10, ma20], axis=1)
predict = clf.predict(pd.concat([close_buy1, m5, m10, ma20], axis=1)) |
8,571 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explore microfluidic flow rate and pressure according to a defined geometry
Date
Step1: Define some initial conditions (feel free to test others conditions)
Step2: Calculate pressure needed for a given flow rate
Step3: Do the math !
Step4: Important
Step5: Plot | Python Code:
%matplotlib qt
import numpy as np
import matplotlib.pyplot as plt
def calculcate_section_circle(diameter):
return np.pi * ((diameter / 2) ** 2)
def calculcate_section_rectangle(height, width):
return height * width
def calculate_characteristic_length_circle(diameter):
return diameter
def calculate_characteristic_length_rectangle(height, width):
return (2 * height * width) / (height + width)
def calculate_kinematic_viscosity(viscosity, density):
return viscosity / density
def calculate_flow_rate_circle(diameter, viscosity, length, delta_pressure):
return (np.pi * (diameter / 2)**4 * np.abs(delta_pressure)) / (8 * viscosity * length)
def calculate_flow_rate_rectangle(height, width, viscosity, length, delta_pressure):
return (1 - 0.630 * (height / width)) * (((height ** 3) * width * delta_pressure) / (12 * viscosity * length))
def calculate_pressure_circle(diameter, viscosity, length, flow_rate):
return (8 * viscosity * length * flow_rate) / (np.pi * (diameter / 2)**4)
def calculate_pressure_rectangle(height, width, viscosity, length, flow_rate):
return (12 * viscosity * length * flow_rate) / ((1 - 0.630 * (height / width)) * ((height ** 3) * width))
def calculate_flow_velocity(flow_rate, section):
return (flow_rate / section)
def calculate_reynolds_number(kinematic_viscosity, characteristic_length, velocity):
return (velocity * characteristic_length) / kinematic_viscosity
Explanation: Explore microfluidic flow rate and pressure according to a defined geometry
Date : 20/11/2016
Note : Feel free to report any errors/mistakes.
The purpose of this notebook is not to go deep inside the fluid mechanic in microfluidic devices but more trying to develop an intuition of the different physical constants and their order of magnitude at this scale.
<img src="drawing.png" alt="" width="600px"/>
For easier calculations, we assume very simple geometries : rectangle or circle.
Theory
Flow rate
The flow rate depends on the pressure difference, the properties of the fluid and the geometry used. We can apply the Ohm's law to a flow of particles other than electron.
$
\Delta P = RQ
$
Where :
$\Delta P$ is the pressure (analog to the tension $U$).
$R$ is the internal resistance of the system (analog to the Ohm's resistance).
$Q$ is the flow rate, analog to the intensity of the current $I$.
For each type of channels used in the microfluidic system the resistance need to be calculated.
Cylindrical channel
For a Poiseuille flow, we define the resistance ($R$) into a cylindrical channel with :
$
R = \cfrac{8 \eta L}{\pi r⁴}
$
Where :
$R$ is the resistance of the channel (Pa.s/m³)
$r$ is the internal radius of the cylinder
$\eta$ is the dynamic fluid viscosity (Pa.s or N.s/m²)
$L$ is the length of the channel (m)
Then we can define the flow rate $Q$ according to a given pressure $P$.
$
Q = \cfrac{\Delta P}{R} = \cfrac{\pi r⁴}{8 \eta L} |\Delta P|
$
Where :
$\Delta P$ is the difference of pressure (Pa)
$Q$ is the flow rate (m³/s)
Rectangular channel
For a Poiseuille flow, we define the the resistance ($R$) into a rectangular channel with :
$
R \approx \cfrac{12 \eta L}{\Bigl[1 - 0.630 \cfrac{h}{w}\Bigr] h³w}
$
Where :
$R$ is the resistance of the channel (Pa.s/m³)
$h$ is the height of the rectangular channel (m)
$w$ is the width of the rectangular channel (m)
$\eta$ is the dynamic fluid viscosity (Pa.s or N.s/m²)
$L$ is the length of the channel (m)
Then we can define the flow rate $Q$ according to a given pressure $P$.
$
Q = \cfrac{\Delta P}{R} \approx \cfrac{\Bigl[1 - 0.630 \cfrac{h}{w}\Bigr] h³w}{12 \eta L} \Delta P
$
Where :
$\Delta P$ is the difference of pressure (Pa)
$Q$ is the flow rate (m³/s)
Flow velocity
The velocity $V$ is calculated from the flow rate ($Q$) and the section of the channel ($S$):
$V = \cfrac{Q}{S}$
Where :
$V$ is the fluid velocity (m/s)
$Q$ is the flow rate (m³/s)
$S$ is the surface section (m²)
Reynolds number
We define the Reynolds number :
$Re = \cfrac{inertial\; forces}{viscous\; forces} = \cfrac{ρVL}{μ}$
Where :
$ρ$ is the density of the fluid (kg/m³)
$V$ is the velocity of the object relative to the fluid (m/s)
$L$ is a characteristic length (m)
$μ$ is the dynamic viscosity of the fluid (Pa.s or N.s/m²)
We can define the kinematic viscosity of the fluid (m²/s) : $ν = \cfrac{μ}{ρ}$. So :
$Re = \cfrac{ρVL}{μ} = \cfrac{VL}{ν}$
Calculations
Below some functions to help make the calculation of the different equations above.
End of explanation
from ipywidgets import interactive
Explanation: Define some initial conditions (feel free to test others conditions) :
Interactive widgets
End of explanation
# Initial conditions
## Geometry
height = 100e-6 # m (not used for circle)
width = 100e-6 # m (not used for circle)
diameter = 100e-6 # m (not used for rectangle)
shape = "rectangle" # Choose in ["rectangle", "circle"]
length = 20e-3 # m
## Water at 20°C
viscosity = 1.307e-3 # Pa.s or N.s/m²
density = 1e3 # kg/m³
## Flow rate wanted
flow_rate = 20 # ul/min
## Convert flow rate to IU
flow_rate_iu = (flow_rate / 60) * 1e-9
assert height <= width
Explanation: Calculate pressure needed for a given flow rate
End of explanation
if shape == "circle":
section = calculcate_section_circle(diameter)
characteristic_length = calculate_characteristic_length_circle(diameter)
pressure = calculate_pressure_circle(diameter, viscosity, length, flow_rate_iu)
elif shape == "rectangle":
section = calculcate_section_rectangle(height, width)
characteristic_length = calculate_characteristic_length_rectangle(height, width)
pressure = calculate_pressure_rectangle(height, width, viscosity, length, flow_rate_iu)
kinematic_viscosity = calculate_kinematic_viscosity(viscosity, density)
flow_velocity = calculate_flow_velocity(flow_rate_iu, section)
reynolds_number = calculate_reynolds_number(kinematic_viscosity, characteristic_length, flow_velocity)
print("Shape used is '{}'.".format(shape))
print("Flow rate wanted is {} ul/min.".format(flow_rate))
print()
print("Section is {0:.3f} mm².".format(section*1e6))
print("Characteristic length is {0:.0f} μm.".format(characteristic_length*1e6))
print()
print("Kinematic viscosity is {} m²/s.".format(kinematic_viscosity))
print()
print("Pressure {0:.3f} mbar.".format(pressure / 100))
print("Flow velocity is {0:.3f} m/s.".format(flow_velocity))
print()
print("Reynolds number is {0:.6f}.".format(reynolds_number))
if reynolds_number < 2300:
print("Flow regime is laminar.")
elif reynolds_number >= 2300 and reynolds_number < 4000:
print("Flow regime is transitional.")
elif reynolds_number >= 4000:
print("Flow regime is turbulent.")
Explanation: Do the math !
End of explanation
n = 1000
## Geometry
height = np.linspace(50e-6, 0.001, n) # m
width = np.linspace(50e-6, 0.001, n) # m
diameter = np.linspace(50e-6, 0.001, n) # m
length = 20e-3 # m
## Water at 20°C
viscosity = 1.307e-3 # Pa.s or N.s/m²
density = 1e3 # kg/m³
## Flow rate wanted
flow_rate = 20 # ul/min
## Convert flow rate to IU
flow_rate_iu = (flow_rate / 60) * 1e-9
pressure_circle = calculate_pressure_circle(diameter, viscosity, length, flow_rate_iu)
pressure_rectangle = calculate_pressure_rectangle(height, width, viscosity, length, flow_rate_iu)
fig, ax = plt.subplots()
ax.plot(height * 1e6, pressure_rectangle / 100, label="Square Channel", lw=2, alpha=0.8)
ax.plot(diameter * 1e6, pressure_circle / 100, label="Cylindrical Channel", lw=2, alpha=0.8)
ax.set_xlabel("Shape Size (um)")
ax.set_ylabel("Pressure Needed (mbar)")
#ax.set_xscale("log")
ax.set_yscale("log")
ax.legend()
ax.set_title("Pressure needed versus the shape size\nfor a flow rate of {} ul/min".format(flow_rate))
Explanation: Important : Calculation is only valid for laminar flow !
Plot : Shape size against pressure for a given flow rate
End of explanation
n = 1000
## Geometry
height = 100e-6 # m
width = 100e-6 # m
length = 20e-3 # m
## Water at 20°C
viscosity = 1.307e-3 # Pa.s or N.s/m²
density = 1e3 # kg/m³
## Flow rate wanted
flow_rate = np.linspace(1, 500, n) # ul/min
## Convert flow rate to IU
flow_rate_iu = (flow_rate / 60) * 1e-9
pressure_rectangle = calculate_pressure_rectangle(height, width, viscosity, length, flow_rate_iu)
fig, ax = plt.subplots()
ax.plot(flow_rate, pressure_rectangle / 100, label="Square Channel", lw=2, alpha=1.0, color="gray")
ax.set_xlabel("Flow rate wanted (ul/min)")
ax.set_ylabel("Pressure Needed (mbar)")
#ax.set_xscale("log")
ax.set_yscale("log")
ax.set_title("Pressure needed versus the flow rate wanted\nfor a rectangular channel of wxhxL = {}x{}x{} m ".format(height, width, length))
Explanation: Plot : Flow rate against pressure for a given shape size
End of explanation |
8,572 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Sklearn Lasso - Training a Lasso Regression Model
| Python Code::
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_squared_error, mean_absolute_error, max_error, explained_variance_score, mean_absolute_percentage_error
# initialise & fit Lasso regression model with alpha set to 0.5
model = Lasso(alpha=0.5)
model.fit(X_train, y_train)
# create dictionary that contains the feature coefficients
coef = dict(zip(X_train.columns, model.coef_.T))
print(coef)
# make prediction for test data & evaluate performance
y_pred = model.predict(X_test)
print('RMSE:',mean_squared_error(y_test, y_pred, squared = False))
print('MAE:',mean_absolute_error(y_test, y_pred))
print('MAPE:',mean_absolute_percentage_error(y_test, y_pred))
print('Max Error:',max_error(y_test, y_pred))
print('Explained Variance Score:',explained_variance_score(y_test, y_pred))
|
8,573 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Making and manipulating structures with ASE
For preparing and manipulating crystal structures we will be using the ASE Python library. The documentation is rather accessible and even includes a refresher of Python basics. You can read it here, in preparation for the first lab
Step1: Now we verify that our structure indeed has atoms in the right places
Step2: We can make a supercell of this structure by rescaling the cell. Here we use NumPy's matrix capability.
Step3: It is possible to change the position of the first atom directly like this
Step4: Similarly, we can change the type of the first atom by reassigning the atomic number
Step5: Or we can remove an atom altogether to form a vacancy. We simply use the pop() method of Python lists.
Step6: Now let's write the structure to a file so was can visualize what we've done to it. Crystallographic Information File (CIF) format is the most common for periodic structures today, and is understood by most structure visualizers and converters.
Step7: We cans use VESTA to look at the result, or the ASE built-in viewer like so
Step8: To generate a surface slab supercell we can use ASE builder like so, and write it to a file
Step9: You can look at the structure in VESTA and also get the atomic positions and cell information
Step10: In the lab you will need to perform numerical sweeps of several parameters. You can use Numpy
Step11: To plot the results, you can use Matplotlib | Python Code:
from ase.spacegroup import crystal
a = 4.5
Na_unitcell = crystal('Na', [(0,0,0)], spacegroup=229, cellpar=[a, a, a, 90, 90, 90])
print('hello')
Explanation: Making and manipulating structures with ASE
For preparing and manipulating crystal structures we will be using the ASE Python library. The documentation is rather accessible and even includes a refresher of Python basics. You can read it here, in preparation for the first lab: https://wiki.fysik.dtu.dk/ase/python.html.
Here we will learn various functionalities of ASE, particularly how to make crystal structures, generate supercells, remove an atom to form a vacancy, and change an atom’s position.
ASE Atoms object holds all the information about our structure and has methods for manipulating it. Once we finish with the structurem, we will export it to a simple Python dictionary that is then used to generate the LAMMPS data and input files.
First we will create a crystal structure of Na metal. For this we will import the necessary spacegroup tools, so that we don't have to manually set up the cell and coordinates.
End of explanation
Na_unitcell.positions
Na_unitcell.get_chemical_symbols()
Explanation: Now we verify that our structure indeed has atoms in the right places
End of explanation
import numpy
multiplier = numpy.identity(3) * 2
print(multiplier)
from ase.build import make_supercell
Na_supercell = make_supercell(Na_unitcell, multiplier)
Na_supercell.positions
Explanation: We can make a supercell of this structure by rescaling the cell. Here we use NumPy's matrix capability.
End of explanation
Na_supercell.positions[0] = (0.5, 0.5, 0.5)
Explanation: It is possible to change the position of the first atom directly like this:
End of explanation
print(Na_supercell.numbers)
Na_supercell.numbers[0] = 3
Na_supercell.get_chemical_symbols()
Explanation: Similarly, we can change the type of the first atom by reassigning the atomic number
End of explanation
Na_supercell.pop(15)
Explanation: Or we can remove an atom altogether to form a vacancy. We simply use the pop() method of Python lists.
End of explanation
from ase.io import write
write('sc.struct', Na_supercell)
Explanation: Now let's write the structure to a file so was can visualize what we've done to it. Crystallographic Information File (CIF) format is the most common for periodic structures today, and is understood by most structure visualizers and converters.
End of explanation
Na_supercell.edit()
Explanation: We cans use VESTA to look at the result, or the ASE built-in viewer like so:
End of explanation
from ase.build import bcc100
slab = bcc100('Na', size=(2,4,3), vacuum = 10.0)
write('slab.struct', slab)
Explanation: To generate a surface slab supercell we can use ASE builder like so, and write it to a file
End of explanation
slab.positions
slab.cell
slab.edit()
Explanation: You can look at the structure in VESTA and also get the atomic positions and cell information
End of explanation
x = numpy.linspace(-5,5,10)
y = x*x
print(x)
Explanation: In the lab you will need to perform numerical sweeps of several parameters. You can use Numpy
End of explanation
import matplotlib.pyplot as plt
plt.plot(x,y)
plt.show()
Explanation: To plot the results, you can use Matplotlib
End of explanation |
8,574 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Numerical Problem Solving TX00BY09-3007
Assignment
Step1: Exercise 04
Given equation system
$$10.0x_1 + 2.0x_2 − x_3 = 27.0$$
$$−3.0x_1 − 6.0x_2 + 2.0x_3 = −61.5$$
$$x_1 + x_2 + 5.0x_3 = −21.5$$
(a) Solve by Gaussian elimination<br />
(b) Substitute your solutions into the original equations in order to
check answers.
In order to solve the given problems, we first need to create a function for Gaussian elimination. For that, I am using the function created in class.
Step2: Create variables for the exercise 4a and call function <i>gaussian(a, b)</i>
Step3: For exercise 4b we need to create a function to confirm the results by substituting valous in the original equation.
Step4: Exercise 06
Solve the equations Ax = b by Gauss elimination, where
$$A =
\begin{pmatrix}
0.0 & 0.0 & 2.0 & 1.0 & 2.0 \
0.0 & 1.0 & 0.0 & 2.0 & -1.0 \
1.0 & 2.0 & 0.0 & -2.0 & 0.0 \
0.0 & 0.0 & 0.0 & -1.0 & 1.0 \
0.0 & 1.0 & -1.0 & 1.0 & -1.0
\end{pmatrix}
$$
and
$$b =
\begin{pmatrix}
1.0 \
1.0 \
-4.0 \
-2.0 \
-1.0
\end{pmatrix}$$
Hint
Step5: How do we know if the values are correct? We can solve the equation by using the numpy.linalg package and dot function to get the dot-product of the matrix. | Python Code:
# Import required libraries
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import *
from numpy import *
Explanation: Introduction to Numerical Problem Solving TX00BY09-3007
Assignment: 04 Graphical analysis<br />
Description: From the exercises 04, solve the problems 4 and 6 by using Python. Attach your solutions as a jupyter Notebook here.<br />
Author: Joonas Forsberg<br />
This document has been prepared for the fourth assignment for the course "Introduction to Numerical Problem Solving". It contains code examples and explanations for the written code. In addition, I've included reasoning behind the behavior where acceptable.<br />
End of explanation
def gaussian(a, b):
# Copy variables
a = a.copy()
b = b.copy()
n = len(b)
x = zeros(n)
# Step 1: Forward elimination
for k in range(0, n - 1):
# Pivot the rows
r = argmax(abs(a[k:, k])) + k
if r != k:
temp = a[k, :].copy()
a[k, :] = a[r, :]
a[r, :] = temp
temp = b[k].copy()
b[k] = b[r]
b[r] = temp
for i in range(k + 1, n):
factor = a[i, k] / a[k, k]
for j in range(n):
a[i, j] = a[i, j] - factor * a[k, j]
b[i] = b[i] - factor * b[k]
# Step 2: Backward substitution
x[n - 1] = b[n - 1] / a[n - 1, n - 1]
for i in range(n - 2, -1, -1):
sum = b[i]
for j in range(i + 1, n):
sum = sum - a[i, j] * x[j]
x[i] = sum / a[i, i]
return (x)
Explanation: Exercise 04
Given equation system
$$10.0x_1 + 2.0x_2 − x_3 = 27.0$$
$$−3.0x_1 − 6.0x_2 + 2.0x_3 = −61.5$$
$$x_1 + x_2 + 5.0x_3 = −21.5$$
(a) Solve by Gaussian elimination<br />
(b) Substitute your solutions into the original equations in order to
check answers.
In order to solve the given problems, we first need to create a function for Gaussian elimination. For that, I am using the function created in class.
End of explanation
a = np.array(([10.0, 2.0, -1.0], [-3.0, -6.0, 2.0], [1.0, 1.0, 5.0]))
b = np.array(([27.0, -61.5, -21.5]))
result = gaussian(a, b)
Explanation: Create variables for the exercise 4a and call function <i>gaussian(a, b)</i>
End of explanation
def confirm_gaussian(result_array):
# Build the equations
e1 = a[0][0] * result_array[0] + a[0][1] * result_array[1] - result_array[2]
e2 = a[1][0] * result_array[0] + a[1][1] * result_array[1] + (a[1][2] * result_array[2])
e3 = a[2][0] * result_array[0] + a[2][1] * result_array[1] + (a[2][2] * result_array[2])
# Check results
if e1 == b[0] and e2 == b[1] and e3 == b[2]:
return True
else:
return False
if(confirm_gaussian(array(result)) == True):
print("The equations are correct!")
else:
print("Equations don't match! :(")
Explanation: For exercise 4b we need to create a function to confirm the results by substituting valous in the original equation.
End of explanation
a = np.array(([0.0, 0.0, 2.0, 1.0, 2.0], [0.0, 1.0, 0.0, 2.0, -1.0], [1.0, 2.0, 0.0, -2.0, 0.0], [0.0, 0.0, 0.0, -1.0, 1.0], [0.0, 1.0, -1.0, 1.0, -1.0]))
b = np.array(([1.0, 1.0, -4.0, -2.0, -1.0]))
result = gaussian(a,b)
print(result)
Explanation: Exercise 06
Solve the equations Ax = b by Gauss elimination, where
$$A =
\begin{pmatrix}
0.0 & 0.0 & 2.0 & 1.0 & 2.0 \
0.0 & 1.0 & 0.0 & 2.0 & -1.0 \
1.0 & 2.0 & 0.0 & -2.0 & 0.0 \
0.0 & 0.0 & 0.0 & -1.0 & 1.0 \
0.0 & 1.0 & -1.0 & 1.0 & -1.0
\end{pmatrix}
$$
and
$$b =
\begin{pmatrix}
1.0 \
1.0 \
-4.0 \
-2.0 \
-1.0
\end{pmatrix}$$
Hint: You need to reorder the equations before solving.
We can solve the exercise by using the gaussian function. Reordering the equation is done by pivoting the rows.
End of explanation
from numpy.linalg import *
x = dot(inv(a,), b)
# Check if the arrays match by using the all() method
if result.all() == x.all():
print("Correct!")
else:
print("Incorrect!")
Explanation: How do we know if the values are correct? We can solve the equation by using the numpy.linalg package and dot function to get the dot-product of the matrix.
End of explanation |
8,575 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
가우시안 정규 분포
가우시안 정규 분포(Gaussian normal distribution), 혹은 그냥 간단히 정규 분포라고 부르는 분포는 자연 현상에서 나타나는 숫자를 확률 모형으로 모형화할 때 가장 많이 사용되는 확률 모형이다.
정규 분포는 평균 $\mu$와 분산 $\sigma^2$ 이라는 두 개의 모수만으로 정의되며 확률 밀도 함수(pdf
Step1: pdf 메서드를 사용하면 확률 밀도 함수(pmf
Step2: 시뮬레이션을 통해 샘플을 얻으려면 rvs 메서드를 사용한다.
Step3: Q-Q 플롯
정규 분포는 여러가지 연속 확률 분포 중에서도 가장 유용한 특성을 지니며 널리 사용되는 확률 분포이다. 따라서 어떤 확률 변수의 분포가 정규 분포인지 아닌지 확인하는 것은 정규 분포 검정(normality test)은 가장 중요한 통계적 분석 중의 하나이다. 그러나 구체적인 정규 분포 검정을 사용하기에 앞서 시작적으로 간단하게 정규 분포를 확인하는 Q-Q 플롯을 사용할 수 있다.
Q-Q(Quantile-Quantile) 플롯은 분석하고자 하는 샘플의 분포과 정규 분포의 분포 형태를 비교하는 시각적 도구이다. Q-Q 플롯은 동일 분위수에 해당하는 정상 분포의 값과 주어진 분포의 값을 한 쌍으로 만들어 스캐터 플롯(scatter plot)으로 그린 것이다. Q-Q 플롯을 그리는 구체적인 방법은 다음과 같다.
대상 샘플을 크기에 따라 정렬(sort)한다.
각 샘플의 분위수(quantile number)를 구한다.
각 샘플의 분위수와 일치하는 분위수를 가지는 정규 분포 값을 구한다.
대상 샘플과 정규 분포 값을 하나의 쌍으로 생각하여 2차원 공간에 하나의 점(point)으로 그린다.
모든 샘플에 대해 2부터 4까지의 과정을 반복하여 스캐터 플롯과 유사한 형태의 플롯을 완성한다.
비교를 위한 45도 직선을 그린다.
SciPy 패키지의 stats 서브 패키지는 Q-Q 플롯을 계산하고 그리기 위한 probplot 명령을 제공한다.
http
Step4: 정규 분포를 따르지 않는 데이터 샘플을 Q-Q 플롯으로 그리면 다음과 같이 직선이 아닌 휘어진 형태로 나타난다.
Step5: 중심 극한 정리
실세계에서 발생하는 현상 중 많은 것들이 정규 분포로 모형화 가능하다. 그 이유 중의 하나는 다음과 같은 중심 극한 정리(Central Limit Theorem)이다. 중심 극한 정리는 어떤 분포를 따르는 확류 변수든 간에 해당 확률 변수가 복수인 경우 그 합은 정규 분포와 비슥한 분포를 이루는 현상을 말한다.
좀 더 수학적인 용어로 쓰면 다음과 같다.
$X_1, X_2, \ldots, X_n$가 기댓값이 $\mu$이고 분산이 $\sigma^2$으로 동일한 분포이며 서로 독립인 확률 변수들이라고 하자.
이 값들의 합
$$ S_n = X_1+\cdots+X_n $$
도 마찬가지로 확률 변수이다. 이 확률 변수 $S_n$의 분포는 $n$이 증가할 수록 다음과 같은 정규 분포에 수렴한다.
$$ \dfrac{S_n}{\sqrt{n}} \xrightarrow{d}\ N(\mu,\;\sigma^2) $$
시뮬레이션을 사용하여 중심 극한 정리가 성립하는지 살펴보도록 하자. | Python Code:
mu = 0
std = 1
rv = sp.stats.norm(mu, std)
rv
Explanation: 가우시안 정규 분포
가우시안 정규 분포(Gaussian normal distribution), 혹은 그냥 간단히 정규 분포라고 부르는 분포는 자연 현상에서 나타나는 숫자를 확률 모형으로 모형화할 때 가장 많이 사용되는 확률 모형이다.
정규 분포는 평균 $\mu$와 분산 $\sigma^2$ 이라는 두 개의 모수만으로 정의되며 확률 밀도 함수(pdf: probability density function)는 다음과 같은 수식을 가진다.
$$ \mathcal{N}(x; \mu, \sigma^2) = \dfrac{1}{\sqrt{2\pi\sigma^2}} \exp \left(-\dfrac{(x-\mu)^2}{2\sigma^2}\right) $$
정규 분포 중에서도 평균이 1이고 분산이 1인($\mu=1$, $\sigma^2=1$) 정규 분포를 표준 정규 분포(standard normal distribution)라고 한다.
SciPy를 사용한 정규 분포의 시뮬레이션
Scipy의 stats 서브 패키지에 있는 norm 클래스는 정규 분포에 대한 클래스이다. loc 인수로 평균을 설정하고 scale 인수로 표준 편차를 설정한다.
End of explanation
xx = np.linspace(-5, 5, 100)
plt.plot(xx, rv.pdf(xx))
plt.ylabel("p(x)")
plt.title("pdf of normal distribution")
plt.show()
Explanation: pdf 메서드를 사용하면 확률 밀도 함수(pmf: probability density function)를 계산할 수 있다.
End of explanation
np.random.seed(0)
x = rv.rvs(100)
x
sns.distplot(x, kde=False, fit=sp.stats.norm)
plt.show()
Explanation: 시뮬레이션을 통해 샘플을 얻으려면 rvs 메서드를 사용한다.
End of explanation
np.random.seed(0)
x = np.random.randn(100)
plt.figure(figsize=(7,7))
sp.stats.probplot(x, plot=plt)
plt.axis("equal")
plt.show()
Explanation: Q-Q 플롯
정규 분포는 여러가지 연속 확률 분포 중에서도 가장 유용한 특성을 지니며 널리 사용되는 확률 분포이다. 따라서 어떤 확률 변수의 분포가 정규 분포인지 아닌지 확인하는 것은 정규 분포 검정(normality test)은 가장 중요한 통계적 분석 중의 하나이다. 그러나 구체적인 정규 분포 검정을 사용하기에 앞서 시작적으로 간단하게 정규 분포를 확인하는 Q-Q 플롯을 사용할 수 있다.
Q-Q(Quantile-Quantile) 플롯은 분석하고자 하는 샘플의 분포과 정규 분포의 분포 형태를 비교하는 시각적 도구이다. Q-Q 플롯은 동일 분위수에 해당하는 정상 분포의 값과 주어진 분포의 값을 한 쌍으로 만들어 스캐터 플롯(scatter plot)으로 그린 것이다. Q-Q 플롯을 그리는 구체적인 방법은 다음과 같다.
대상 샘플을 크기에 따라 정렬(sort)한다.
각 샘플의 분위수(quantile number)를 구한다.
각 샘플의 분위수와 일치하는 분위수를 가지는 정규 분포 값을 구한다.
대상 샘플과 정규 분포 값을 하나의 쌍으로 생각하여 2차원 공간에 하나의 점(point)으로 그린다.
모든 샘플에 대해 2부터 4까지의 과정을 반복하여 스캐터 플롯과 유사한 형태의 플롯을 완성한다.
비교를 위한 45도 직선을 그린다.
SciPy 패키지의 stats 서브 패키지는 Q-Q 플롯을 계산하고 그리기 위한 probplot 명령을 제공한다.
http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.probplot.html
probplot은 기본적으로 인수로 보낸 데이터 샘플에 대한 Q-Q 정보만을 반환하고 챠트는 그리지 않는다. 만약 차트를 그리고 싶다면 plot 인수에 matplotlib.pylab 모듈 객체 혹은 Axes 클래스 객체를 넘겨주어야 한다.
정규 분포를 따르는 데이터 샘플을 Q-Q 플롯으로 그리면 다음과 같이 직선의 형태로 나타난다.
End of explanation
np.random.seed(0)
x = np.random.rand(100)
plt.figure(figsize=(7,7))
sp.stats.probplot(x, plot=plt)
plt.ylim(-0.5, 1.5)
plt.show()
Explanation: 정규 분포를 따르지 않는 데이터 샘플을 Q-Q 플롯으로 그리면 다음과 같이 직선이 아닌 휘어진 형태로 나타난다.
End of explanation
xx = np.linspace(-2, 2, 100)
plt.figure(figsize=(6,9))
for i, N in enumerate([1, 2, 10]):
X = np.random.rand(1000, N) - 0.5
S = X.sum(axis=1)/np.sqrt(N)
plt.subplot(3, 2, 2*i+1)
sns.distplot(S, bins=10, kde=False, norm_hist=True)
plt.xlim(-2, 2)
plt.yticks([])
plt.subplot(3, 2, 2*i+2)
sp.stats.probplot(S, plot=plt)
plt.tight_layout()
plt.show()
Explanation: 중심 극한 정리
실세계에서 발생하는 현상 중 많은 것들이 정규 분포로 모형화 가능하다. 그 이유 중의 하나는 다음과 같은 중심 극한 정리(Central Limit Theorem)이다. 중심 극한 정리는 어떤 분포를 따르는 확류 변수든 간에 해당 확률 변수가 복수인 경우 그 합은 정규 분포와 비슥한 분포를 이루는 현상을 말한다.
좀 더 수학적인 용어로 쓰면 다음과 같다.
$X_1, X_2, \ldots, X_n$가 기댓값이 $\mu$이고 분산이 $\sigma^2$으로 동일한 분포이며 서로 독립인 확률 변수들이라고 하자.
이 값들의 합
$$ S_n = X_1+\cdots+X_n $$
도 마찬가지로 확률 변수이다. 이 확률 변수 $S_n$의 분포는 $n$이 증가할 수록 다음과 같은 정규 분포에 수렴한다.
$$ \dfrac{S_n}{\sqrt{n}} \xrightarrow{d}\ N(\mu,\;\sigma^2) $$
시뮬레이션을 사용하여 중심 극한 정리가 성립하는지 살펴보도록 하자.
End of explanation |
8,576 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
sklearn构建管道
sklearn支持使用管道(Pipeline)连接多个sklearn中的模型类实例,但要求过程中的模型类对象带transform方法的且最后一个需要是分类器,回归器或者同样是带transform方法的模型类对象.
带transform方法的类对象叫做转换器,可以使用sklearn.preprocessing.FunctionTransformer自定义.
Step1: 管道通常用在将向量化(vectorizer) => 转换器(transformer) => 分类器(classifier) 过程封装为一个连贯的过程.
例
Step2: 评估性能 | Python Code:
import numpy as np
from sklearn.preprocessing import FunctionTransformer
transformer = FunctionTransformer(np.log1p)
X = np.array([[0, 1], [2, 3]])
transformer.transform(X)
Explanation: sklearn构建管道
sklearn支持使用管道(Pipeline)连接多个sklearn中的模型类实例,但要求过程中的模型类对象带transform方法的且最后一个需要是分类器,回归器或者同样是带transform方法的模型类对象.
带transform方法的类对象叫做转换器,可以使用sklearn.preprocessing.FunctionTransformer自定义.
End of explanation
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.datasets import fetch_20newsgroups
categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']
twenty_train = fetch_20newsgroups(subset='train',categories=categories, shuffle=True, random_state=42)
text_clf = Pipeline([('vect', CountVectorizer()),# 分词并向量化
('tfidf', TfidfTransformer()), # tfidf算法提取关键字
('clf', MultinomialNB())]) # 分类器
text_clf.fit(twenty_train.data, twenty_train.target)
Explanation: 管道通常用在将向量化(vectorizer) => 转换器(transformer) => 分类器(classifier) 过程封装为一个连贯的过程.
例:以fetch_20newsgroups数据为例做贝叶斯分类器模型
End of explanation
import numpy as np
twenty_test = fetch_20newsgroups(subset='test',categories=categories, shuffle=True, random_state=42)
docs_test = twenty_test.data
predicted = text_clf.predict(docs_test)
np.mean(predicted == twenty_test.target)
Explanation: 评估性能
End of explanation |
8,577 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Metric Learning with the Shogun Machine Learning Toolbox
Building up the intuition to understand LMNN
First of all, let us introduce LMNN through a simple example. For this purpose, we will be using the following two-dimensional toy data set
Step1: That is, there are eight feature vectors where each of them belongs to one out of three different classes (identified by either 0, 1, or 2). Let us have a look at this data
Step2: In the figure above, we can see that two of the classes are represented by two points that are, for each of these classes, very close to each other. The third class, however, has four points that are close to each other with respect to the y-axis, but spread along the x-axis.
If we were to apply kNN (k-nearest neighbors) in a data set like this, we would expect quite some errors using the standard Euclidean distance. This is due to the fact that the spread of the data is not similar amongst the feature dimensions. The following piece of code plots an ellipse on top of the data set. The ellipse in this case is in fact a circunference that helps to visualize how the Euclidean distance weights equally both feature dimensions.
Step3: A possible workaround to improve the performance of kNN in a data set like this would be to input to the kNN routine a distance measure. For instance, in the example above a good distance measure would give more weight to the y-direction than to the x-direction to account for the large spread along the x-axis. Nonetheless, it would be nicer (and, in fact, much more useful in practice) if this distance could be learnt automatically from the data at hand. Actually, LMNN is based upon this principle
Step4: Secondly, perform LMNN training
Step5: LMNN is an iterative algorithm. The argument given to train represents the initial state of the solution. By default, if no argument is given, then LMNN uses PCA to obtain this initial value.
Step6: Beyond the main idea | Python Code:
%pylab inline
x = numpy.array([[0,0],[-1,0.1],[0.3,-0.05],[0.7,0.3],[-0.2,-0.6],[-0.15,-0.63],[-0.25,0.55],[-0.28,0.67]])
y = numpy.array([0,0,0,0,1,1,2,2])
Explanation: Metric Learning with the Shogun Machine Learning Toolbox
Building up the intuition to understand LMNN
First of all, let us introduce LMNN through a simple example. For this purpose, we will be using the following two-dimensional toy data set:
End of explanation
def plot_data(features,labels,axis,alpha=1.0):
# separate features according to their class
X0,X1,X2 = features[labels==0], features[labels==1], features[labels==2]
# class 0 data
axis.plot(X0[:,0], X0[:,1], 'o', color='green', markersize=12, alpha=alpha)
# class 1 data
axis.plot(X1[:,0], X1[:,1], 'o', color='red', markersize=12, alpha=alpha)
# class 2 data
axis.plot(X2[:,0], X2[:,1], 'o', color='blue', markersize=12, alpha=alpha)
# set axes limits
axis.set_xlim(-1.5,1.5)
axis.set_ylim(-1.5,1.5)
axis.set_aspect('equal')
axis.set_xlabel('x')
axis.set_ylabel('y')
figure,axis = pyplot.subplots(1,1)
plot_data(x,y,axis)
axis.set_title('Toy data set')
pyplot.show()
Explanation: That is, there are eight feature vectors where each of them belongs to one out of three different classes (identified by either 0, 1, or 2). Let us have a look at this data:
End of explanation
def make_covariance_ellipse(covariance):
import matplotlib.patches as patches
import scipy.linalg as linalg
# the ellipse is centered at (0,0)
mean = numpy.array([0,0])
# eigenvalue decomposition of the covariance matrix (w are eigenvalues and v eigenvectors),
# keeping only the real part
w,v = linalg.eigh(covariance)
# normalize the eigenvector corresponding to the largest eigenvalue
u = v[0]/linalg.norm(v[0])
# angle in degrees
angle = 180.0/numpy.pi*numpy.arctan(u[1]/u[0])
# fill Gaussian ellipse at 2 standard deviation
ellipse = patches.Ellipse(mean, 2*w[0]**0.5, 2*w[1]**0.5, 180+angle, color='orange', alpha=0.3)
return ellipse
# represent the Euclidean distance
figure,axis = pyplot.subplots(1,1)
plot_data(x,y,axis)
ellipse = make_covariance_ellipse(numpy.eye(2))
axis.add_artist(ellipse)
axis.set_title('Euclidean distance')
pyplot.show()
Explanation: In the figure above, we can see that two of the classes are represented by two points that are, for each of these classes, very close to each other. The third class, however, has four points that are close to each other with respect to the y-axis, but spread along the x-axis.
If we were to apply kNN (k-nearest neighbors) in a data set like this, we would expect quite some errors using the standard Euclidean distance. This is due to the fact that the spread of the data is not similar amongst the feature dimensions. The following piece of code plots an ellipse on top of the data set. The ellipse in this case is in fact a circunference that helps to visualize how the Euclidean distance weights equally both feature dimensions.
End of explanation
x.T.shape
from modshogun import RealFeatures, MulticlassLabels
features = RealFeatures(x.T)
labels = MulticlassLabels(y.astype(numpy.float64))
Explanation: A possible workaround to improve the performance of kNN in a data set like this would be to input to the kNN routine a distance measure. For instance, in the example above a good distance measure would give more weight to the y-direction than to the x-direction to account for the large spread along the x-axis. Nonetheless, it would be nicer (and, in fact, much more useful in practice) if this distance could be learnt automatically from the data at hand. Actually, LMNN is based upon this principle: given a number of neighbours k, find the Mahalanobis distance measure which maximizes kNN accuracy (using the given value for k) in a training data set. As we usually do in machine learning, under the assumption that the training data is an accurate enough representation of the underlying process, the distance learnt will not only perform well in the training data, but also have good generalization properties.
Now, let us use the LMNN class implemented in Shogun to find the distance and plot its associated ellipse. If everything goes well, we will see that the new ellipse only overlaps with the data points of the green class.
First, we need to wrap the data into Shogun's feature and label objects:
End of explanation
from modshogun import LMNN
# number of target neighbours per example
k = 1
lmnn = LMNN(features,labels,k)
# set an initial transform as a start point of the optimization
init_transform = numpy.eye(2)
lmnn.set_maxiter(5000)
lmnn.train(init_transform)
Explanation: Secondly, perform LMNN training:
End of explanation
# get the linear transform from LMNN
L = lmnn.get_linear_transform()
# square the linear transform to obtain the Mahalanobis distance matrix
M = numpy.matrix(numpy.dot(L.T,L))
# represent the distance given by LMNN
figure,axis = pyplot.subplots(1,1)
plot_data(x,y,axis)
ellipse = make_covariance_ellipse(M.I)
axis.add_artist(ellipse)
axis.set_title('LMNN distance')
pyplot.show()
Explanation: LMNN is an iterative algorithm. The argument given to train represents the initial state of the solution. By default, if no argument is given, then LMNN uses PCA to obtain this initial value.
End of explanation
# project original data using L
lx = numpy.dot(L,x.T)
# represent the data in the projected space
figure,axis = pyplot.subplots(1,2, figsize=(10,5))
plot_data(lx.T,y,axis[0])
ellipse0 = make_covariance_ellipse(numpy.eye(2))
axis[0].add_artist(ellipse0)
axis[0].set_title('LMNN\'s linear transform')
ellipse1 = make_covariance_ellipse(numpy.eye(2))
plot_data(x,y,axis[1],1)
axis[1].add_artist(ellipse1)
axis[1].set_title('original')
statistics = lmnn.get_statistics()
pyplot.plot(statistics.obj.get())
pyplot.grid(True)
pyplot.xlabel('Number of iterations')
pyplot.ylabel('LMNN objective')
Explanation: Beyond the main idea
End of explanation |
8,578 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
解释器模式(Interpret Pattern)
1 代码
要开发一个自动识别谱子的吉他模拟器,达到录入谱即可按照谱发声的效果。除了发声设备外(假设已完成),最重要的就是读谱和译谱能力了。分析其需求,整个过程大致上分可以分为两部分:根据规则翻译谱的内容;根据翻译的内容演奏。我们用一个解释器模型来完成这个功能。
Step1: PlayContext类为谱的内容,这里仅含一个字段,没有方法。Expression即表达式,里面仅含两个方法,interpret负责转译谱,execute则负责演奏;NormGuitar类覆写execute,以吉他 的方式演奏。
业务场景如下: | Python Code:
class PlayContext():
play_text = None
class Expression():
def interpret(self, context):
if len(context.play_text) == 0:
return
else:
play_segs=context.play_text.split(" ")
for play_seg in play_segs:
pos=0
for ele in play_seg:
if ele.isalpha():
pos+=1
continue
break
play_chord = play_seg[0:pos]
play_value = play_seg[pos:]
self.execute(play_chord,play_value)
def execute(self,play_key,play_value):
pass
class NormGuitar(Expression):
def execute(self, key, value):
print ("Normal Guitar Playing--Chord:%s Play Tune:%s"%(key,value))
Explanation: 解释器模式(Interpret Pattern)
1 代码
要开发一个自动识别谱子的吉他模拟器,达到录入谱即可按照谱发声的效果。除了发声设备外(假设已完成),最重要的就是读谱和译谱能力了。分析其需求,整个过程大致上分可以分为两部分:根据规则翻译谱的内容;根据翻译的内容演奏。我们用一个解释器模型来完成这个功能。
End of explanation
context = PlayContext()
context.play_text = "C53231323 Em43231323 F43231323 G63231323"
guitar=NormGuitar()
guitar.interpret(context)
Explanation: PlayContext类为谱的内容,这里仅含一个字段,没有方法。Expression即表达式,里面仅含两个方法,interpret负责转译谱,execute则负责演奏;NormGuitar类覆写execute,以吉他 的方式演奏。
业务场景如下:
End of explanation |
8,579 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling TRISO Particles
OpenMC includes a few convenience functions for generationing TRISO particle locations and placing them in a lattice. To be clear, this capability is not a stochastic geometry capability like that included in MCNP. It's also important to note that OpenMC does not use delta tracking, which would normally speed up calculations in geometries with tons of surfaces and cells. However, the computational burden can be eased by placing TRISO particles in a lattice.
Step1: Let's first start by creating materials that will be used in our TRISO particles and the background material.
Step2: To actually create individual TRISO particles, we first need to create a universe that will be used within each particle. The reason we use the same universe for each TRISO particle is to reduce the total number of cells/surfaces needed which can substantially improve performance over using unique cells/surfaces in each.
Step3: Next, we need a region to pack the TRISO particles in. We will use a 1 cm x 1 cm x 1 cm box centered at the origin.
Step4: Now we need to randomly select locations for the TRISO particles. In this example, we will select locations at random within the box with a packing fraction of 30%. Note that pack_spheres can handle up to the theoretical maximum of 60% (it will just be slow).
Step5: Now that we have the locations of the TRISO particles determined and a universe that can be used for each particle, we can create the TRISO particles.
Step6: Each TRISO object actually is a Cell, in fact; we can look at the properties of the TRISO just as we would a cell
Step7: Let's confirm that all our TRISO particles are within the box.
Step8: We can also look at what the actual packing fraction turned out to be
Step9: Now that we have our TRISO particles created, we need to place them in a lattice to provide optimal tracking performance in OpenMC. We can use the box we created above to place the lattice in. Actually creating a lattice containing TRISO particles can be done with the model.create_triso_lattice() function. This function requires that we give it a list of TRISO particles, the lower-left coordinates of the lattice, the pitch of each lattice cell, the overall shape of the lattice (number of cells in each direction), and a background material.
Step10: Now we can set the fill of our box cell to be the lattice
Step11: Finally, let's take a look at our geometry by putting the box in a universe and plotting it. We're going to use the Fortran-side plotter since it's much faster.
Step12: If we plot the universe by material rather than by cell, we can see that the entire background is just graphite. | Python Code:
%matplotlib inline
from math import pi
import numpy as np
import matplotlib.pyplot as plt
import openmc
import openmc.model
Explanation: Modeling TRISO Particles
OpenMC includes a few convenience functions for generationing TRISO particle locations and placing them in a lattice. To be clear, this capability is not a stochastic geometry capability like that included in MCNP. It's also important to note that OpenMC does not use delta tracking, which would normally speed up calculations in geometries with tons of surfaces and cells. However, the computational burden can be eased by placing TRISO particles in a lattice.
End of explanation
fuel = openmc.Material(name='Fuel')
fuel.set_density('g/cm3', 10.5)
fuel.add_nuclide('U235', 4.6716e-02)
fuel.add_nuclide('U238', 2.8697e-01)
fuel.add_nuclide('O16', 5.0000e-01)
fuel.add_element('C', 1.6667e-01)
buff = openmc.Material(name='Buffer')
buff.set_density('g/cm3', 1.0)
buff.add_element('C', 1.0)
buff.add_s_alpha_beta('c_Graphite')
PyC1 = openmc.Material(name='PyC1')
PyC1.set_density('g/cm3', 1.9)
PyC1.add_element('C', 1.0)
PyC1.add_s_alpha_beta('c_Graphite')
PyC2 = openmc.Material(name='PyC2')
PyC2.set_density('g/cm3', 1.87)
PyC2.add_element('C', 1.0)
PyC2.add_s_alpha_beta('c_Graphite')
SiC = openmc.Material(name='SiC')
SiC.set_density('g/cm3', 3.2)
SiC.add_element('C', 0.5)
SiC.add_element('Si', 0.5)
graphite = openmc.Material()
graphite.set_density('g/cm3', 1.1995)
graphite.add_element('C', 1.0)
graphite.add_s_alpha_beta('c_Graphite')
Explanation: Let's first start by creating materials that will be used in our TRISO particles and the background material.
End of explanation
# Create TRISO universe
spheres = [openmc.Sphere(r=1e-4*r)
for r in [215., 315., 350., 385.]]
cells = [openmc.Cell(fill=fuel, region=-spheres[0]),
openmc.Cell(fill=buff, region=+spheres[0] & -spheres[1]),
openmc.Cell(fill=PyC1, region=+spheres[1] & -spheres[2]),
openmc.Cell(fill=SiC, region=+spheres[2] & -spheres[3]),
openmc.Cell(fill=PyC2, region=+spheres[3])]
triso_univ = openmc.Universe(cells=cells)
Explanation: To actually create individual TRISO particles, we first need to create a universe that will be used within each particle. The reason we use the same universe for each TRISO particle is to reduce the total number of cells/surfaces needed which can substantially improve performance over using unique cells/surfaces in each.
End of explanation
min_x = openmc.XPlane(x0=-0.5, boundary_type='reflective')
max_x = openmc.XPlane(x0=0.5, boundary_type='reflective')
min_y = openmc.YPlane(y0=-0.5, boundary_type='reflective')
max_y = openmc.YPlane(y0=0.5, boundary_type='reflective')
min_z = openmc.ZPlane(z0=-0.5, boundary_type='reflective')
max_z = openmc.ZPlane(z0=0.5, boundary_type='reflective')
region = +min_x & -max_x & +min_y & -max_y & +min_z & -max_z
Explanation: Next, we need a region to pack the TRISO particles in. We will use a 1 cm x 1 cm x 1 cm box centered at the origin.
End of explanation
outer_radius = 425.*1e-4
centers = openmc.model.pack_spheres(radius=outer_radius, region=region, pf=0.3)
Explanation: Now we need to randomly select locations for the TRISO particles. In this example, we will select locations at random within the box with a packing fraction of 30%. Note that pack_spheres can handle up to the theoretical maximum of 60% (it will just be slow).
End of explanation
trisos = [openmc.model.TRISO(outer_radius, triso_univ, center) for center in centers]
Explanation: Now that we have the locations of the TRISO particles determined and a universe that can be used for each particle, we can create the TRISO particles.
End of explanation
print(trisos[0])
Explanation: Each TRISO object actually is a Cell, in fact; we can look at the properties of the TRISO just as we would a cell:
End of explanation
centers = np.vstack([triso.center for triso in trisos])
print(centers.min(axis=0))
print(centers.max(axis=0))
Explanation: Let's confirm that all our TRISO particles are within the box.
End of explanation
len(trisos)*4/3*pi*outer_radius**3
Explanation: We can also look at what the actual packing fraction turned out to be:
End of explanation
box = openmc.Cell(region=region)
lower_left, upper_right = box.region.bounding_box
shape = (3, 3, 3)
pitch = (upper_right - lower_left)/shape
lattice = openmc.model.create_triso_lattice(
trisos, lower_left, pitch, shape, graphite)
Explanation: Now that we have our TRISO particles created, we need to place them in a lattice to provide optimal tracking performance in OpenMC. We can use the box we created above to place the lattice in. Actually creating a lattice containing TRISO particles can be done with the model.create_triso_lattice() function. This function requires that we give it a list of TRISO particles, the lower-left coordinates of the lattice, the pitch of each lattice cell, the overall shape of the lattice (number of cells in each direction), and a background material.
End of explanation
box.fill = lattice
Explanation: Now we can set the fill of our box cell to be the lattice:
End of explanation
universe = openmc.Universe(cells=[box])
geometry = openmc.Geometry(universe)
geometry.export_to_xml()
materials = list(geometry.get_all_materials().values())
openmc.Materials(materials).export_to_xml()
settings = openmc.Settings()
settings.run_mode = 'plot'
settings.export_to_xml()
plot = openmc.Plot.from_geometry(geometry)
plot.to_ipython_image()
Explanation: Finally, let's take a look at our geometry by putting the box in a universe and plotting it. We're going to use the Fortran-side plotter since it's much faster.
End of explanation
plot.color_by = 'material'
plot.colors = {graphite: 'gray'}
plot.to_ipython_image()
Explanation: If we plot the universe by material rather than by cell, we can see that the entire background is just graphite.
End of explanation |
8,580 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring hddm
Step1: Quick-Start Tutorial
As found in the hddm repo README file - see https
Step2: Notes on MCMC sampling
Step3: print_stats() is literally just a printer - it doesn't return a data structure. Could parse this info in a nice python data structure? | Python Code:
%matplotlib inline
Explanation: Exploring hddm
End of explanation
import hddm
# Load csv data - converted to numpy array
data = hddm.load_csv('../examples/hddm_simple.csv')
# Create hddm model object
model = hddm.HDDM(data, depends_on={'v': 'difficulty'})
# Markov chain Monte Carlo sampling
model.sample(2000, burn=20)
Explanation: Quick-Start Tutorial
As found in the hddm repo README file - see https://github.com/hddm-devs/hddm
End of explanation
# Model fitted parameters & summary stats
model.print_stats()
model.print_stats().__class__
Explanation: Notes on MCMC sampling:
End of explanation
# Fit posterior RT distributions
model.plot_posteriors()
# Plot theoretical RT distributions
model.plot_posterior_predictive()
Explanation: print_stats() is literally just a printer - it doesn't return a data structure. Could parse this info in a nice python data structure?
End of explanation |
8,581 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class Coding Lab
Step1: If you look through the output, you'll see a factorial name. Let's see if it's a function we can use
Step2: It says it's a built-in function, and requies an integer value (which it referrs to as x, but that value is arbitrary) as an argument. Let's call the function and see if it works
Step3: 1.1 You Code
Call the factorial function with an input argument of 4. What is the output?
Step4: Using functions to print things awesome in Juypter
Until this point we've used the boring print() function for our output. Let's do better. In the IPython.display module there are two functions display() and HTML(). The display() function outputs a Python object to the Jupyter notebook. The HTML() function creates a Python object from HTML Markup as a string.
For example this prints Hello in Heading 1.
Step5: Let's keep the example going by writing two of our own functions to print a title and print text as normal, respectively.
Execute this code
Step6: Now let's use these two functions in a familiar program, along with interact_manual() to make the inputs as awesome as the outputs!
Step7: Get Down with OPC (Other People's Code)
Now that we know a bit about Packages, Modules, and Functions let me expand your horizons a bit. There's a whole world of Python code out there that you can use, and it's what makes Python the powerful and popular programming language that it is today. All you need to do to use it is read!
For example. Let's say I want to print some emojis in Python. I might search the Python Package Index https
Step8: Once the package is installed we can use it. Learning how to use it is just a matter of reading the documentation and trying things out. There are no short-cuts here! For example
Step9: 1.2 You Code
Write a python program to print the bacon, ice cream, and thumbs-down emojis on a single line.
Step10: Let's get back to credit cards....
Now that we know a bit about Packages, Modules, and Functions let's attempt to write our first function. Let's tackle the easier of our two credit card related problems
Step11: IMPORTANT Make sure to test your code by running it 5 times. You should test issuer and also the "Invalid Card" case.
Introducing the Write - Refactor - Test - Rewrite approach
It would be nice to re-write this code to use a function. This can seem daunting / confusing for beginner programmers, which is why we teach the Write - Refactor - Test - Rewrite approach. In this approach you write the ENTIRE PROGRAM and then REWRITE IT to use functions. Yes, it's inefficient, but until you get comfotable thinking "functions first" its the best way to modularize your code with functions. Here's the approach
Step12: Step 3
Step13: Step 4
Step14: Functions are abstractions. Abstractions are good.
Step on the accellerator and the car goes. How does it work? Who cares, it's an abstraction! Functions are the same way. Don't believe me. Consider the Luhn Check Algorithm
Step15: Is that a credit card number or the ramblings of a madman?
In order to test the checkLuhn() function you need some credit card numbers. (Don't look at me... you ain't gettin' mine!!!!) Not to worry, the internet has you covered. The website
Step16: Putting it all together
Finally let's use all the functions we wrote/used in this lab to make a really cool program to validate creditcard numbers. Tools we will use
Step17: Metacognition
Rate your comfort level with this week's material so far.
1 ==> I don't understand this at all yet and need extra help. If you choose this please try to articulate that which you do not understand to the best of your ability in the questions and comments section below.
2 ==> I can do this with help or guidance from other people or resources. If you choose this level, please indicate HOW this person helped you in the questions and comments section below.
3 ==> I can do this on my own without any help.
4 ==> I can do this on my own and can explain/teach how to do it to others.
--== Double-Click Here then Enter a Number 1 through 4 Below This Line ==--
Questions And Comments
Record any questions or comments you have about this lab that you would like to discuss in your recitation. It is expected you will have questions if you did not complete the code sections correctly. Learning how to articulate what you do not understand is an important skill of critical thinking. Write them down here so that you remember to ask them in your recitation. We expect you will take responsilbity for your learning and ask questions in class.
--== Double-click Here then Enter Your Questions Below this Line ==-- | Python Code:
import math
dir(math)
Explanation: Class Coding Lab: Functions
The goals of this lab are to help you to understand:
How to use Python's built-in functions in the standard library.
How to write user-defined functions
How to use other people's code.
The benefits of user-defined functions to code reuse and simplicity.
How to create a program to use functions to solve a complex idea
We will demonstrate these through the following example:
The Credit Card Problem
If you're going to do commerce on the web, you're going to support credit cards. But how do you know if a given number is valid? And how do you know which network issued the card?
Example: Is 5300023581452982 a valid credit card number?Is it? Visa? MasterCard, Discover? or American Express?
While eventually the card number is validated when you attempt to post a transaction, there's a lot of reasons why you might want to know its valid before the transaction takes place. The most common being just trying to catch an honest key-entry mistake made by your site visitor.
So there are two things we'd like to figure out, for any "potential" card number:
Who is the issuing network? Visa, MasterCard, Discover or American Express.
IS the number potentially valid (as opposed to a made up series of digits)?
What does this have to do with functions?
If we get this code to work, it seems like it might be useful to re-use it in several other programs we may write in the future. We can do this by writing the code as a function. Think of a function as an independent program its own inputs and output. The program is defined under a name so that we can use it simply by calling its name.
Example: n = int("50") the function int() takes the string "50" as input and converts it to an int value 50 which is then stored in the value n.
When you create these credit card functions, we might want to re-use them by placing them in a Module which is a file with a collection of functions in it. Furthermore we can take a group of related modules and place them together in a Python Package. You install packages on your computer with the pip command.
Built-In Functions
Let's start by checking out the built-in functions in Python's math library. We use the dir() function to list the names of the math library:
End of explanation
help(math.factorial)
Explanation: If you look through the output, you'll see a factorial name. Let's see if it's a function we can use:
End of explanation
math.factorial(5) #this is an example of "calling" the function with input 5. The output should be 120
math.factorial(0) # here we call the same function with input 0. The output should be 1.
Explanation: It says it's a built-in function, and requies an integer value (which it referrs to as x, but that value is arbitrary) as an argument. Let's call the function and see if it works:
End of explanation
#TODO write code here.
Explanation: 1.1 You Code
Call the factorial function with an input argument of 4. What is the output?
End of explanation
from IPython.display import display, HTML
from ipywidgets import interact_manual
print("Exciting:")
display(HTML("<h1>He<font color='red'>ll</font>o</h1>"))
print("Boring:")
print("Hello")
Explanation: Using functions to print things awesome in Juypter
Until this point we've used the boring print() function for our output. Let's do better. In the IPython.display module there are two functions display() and HTML(). The display() function outputs a Python object to the Jupyter notebook. The HTML() function creates a Python object from HTML Markup as a string.
For example this prints Hello in Heading 1.
End of explanation
def print_title(text):
'''
This prints text to IPython.display as H1
'''
return display(HTML("<H1>" + text + "</H1>"))
def print_normal(text):
'''
this prints text to IPython.display as normal text
'''
return display(HTML(text))
Explanation: Let's keep the example going by writing two of our own functions to print a title and print text as normal, respectively.
Execute this code:
End of explanation
print_title("Area of a Rectangle")
@interact_manual(length=(0,25),width=(0,25))
def area(length, width):
area = length * width
print_normal(f"The area is {area}.")
Explanation: Now let's use these two functions in a familiar program, along with interact_manual() to make the inputs as awesome as the outputs!
End of explanation
!pip install emoji
Explanation: Get Down with OPC (Other People's Code)
Now that we know a bit about Packages, Modules, and Functions let me expand your horizons a bit. There's a whole world of Python code out there that you can use, and it's what makes Python the powerful and popular programming language that it is today. All you need to do to use it is read!
For example. Let's say I want to print some emojis in Python. I might search the Python Package Index https://pypi.org/ for some modules to try.
For example this one: https://pypi.org/project/emoji/
Let's take it for a spin!
Installing with pip
First we need to install the package with the pip utility. This runs from the command line, so to execute pip within our notebook we use the bang ! operator.
This downloads the package and installs it into your Python environment, so that you can import it.
End of explanation
# TODO: Run this
import emoji
print(emoji.emojize('Python is :thumbs_up:'))
print(emoji.emojize('But I thought this :lab_coat: was supposed to be about :credit_card: ??'))
Explanation: Once the package is installed we can use it. Learning how to use it is just a matter of reading the documentation and trying things out. There are no short-cuts here! For example:
End of explanation
## TODO: Write your code here
Explanation: 1.2 You Code
Write a python program to print the bacon, ice cream, and thumbs-down emojis on a single line.
End of explanation
## TODO: Debug this code
card = input("Enter a credit card: ")
digit = card[0]
if digit == '5':
issuer = "Visa"
elif digit == '5':
issuer == "Mastercard"
elif digit = '6':
issuer == "Discover"
elif digit == '3'
issuer = "American Express"
else:
issuer = "Invalid"
print(issuer)
Explanation: Let's get back to credit cards....
Now that we know a bit about Packages, Modules, and Functions let's attempt to write our first function. Let's tackle the easier of our two credit card related problems:
Who is the issuing network? Visa, MasterCard, Discover or American Express.
This problem can be solved by looking at the first digit of the card number:
"4" ==> "Visa"
"5" ==> "MasterCard"
"6" ==> "Discover"
"3" ==> "American Express"
So for card number 5300023581452982 the issuer is "MasterCard".
It should be easy to write a program to solve this problem. Here's the algorithm:
input credit card number into variable card
get the first digit of the card number (eg. digit = card[0])
if digit equals "4"
the card issuer "Visa"
elif digit equals "5"
the card issuer "MasterCard"
elif digit equals "6"
the card issuer is "Discover"
elif digit equals "3"
the card issues is "American Express"
else
the issuer is "Invalid"
print issuer
1.3 You Code
Debug this code so that it prints the correct issuer based on the first card
End of explanation
def CardIssuer(card):
## TODO write code here they should be the same as lines 3-13 from the code above
# the last line in the function should return the output
return issuer
Explanation: IMPORTANT Make sure to test your code by running it 5 times. You should test issuer and also the "Invalid Card" case.
Introducing the Write - Refactor - Test - Rewrite approach
It would be nice to re-write this code to use a function. This can seem daunting / confusing for beginner programmers, which is why we teach the Write - Refactor - Test - Rewrite approach. In this approach you write the ENTIRE PROGRAM and then REWRITE IT to use functions. Yes, it's inefficient, but until you get comfotable thinking "functions first" its the best way to modularize your code with functions. Here's the approach:
Write the code
Refactor (change the code around) to use a function
Test the function by calling it
Rewrite the original code to use the new function.
We already did step 1: Write so let's move on to:
1.4 You Code: refactor
Let's strip the logic out of the above code to accomplish the task of the function:
Send into the function as input a credit card number as a str
Return back from the function as output the issuer of the card as a str
To help you out we've written the function stub for you all you need to do is write the function body code.
End of explanation
# Testing the CardIssuer() function
print("WHEN card='40123456789' We EXPECT CardIssuer(card) = Visa ACTUAL", CardIssuer("40123456789"))
print("WHEN card='50123456789' We EXPECT CardIssuer(card) = MasterCard ACTUAL", CardIssuer("50123456789"))
## TODO: You write the remaining 3 tests, you can copy the lines and edit the values accordingly
Explanation: Step 3: Test
You wrote the function, but how do you know it works? The short answer is unless you write code to test your function you're simply guessing!
Testing our function is as simple as calling the function with input values where WE KNOW WHAT TO EXPECT from the output. We then compare that to the ACTUAL value from the called function. If they are the same, then we know the function is working as expected!
Here are some examples:
WHEN card='40123456789' We EXPECT CardIssuer(card) to return Visa
WHEN card='50123456789' We EXPECT CardIssuer(card) to return MasterCard
WHEN card='60123456789' We EXPECT CardIssuer(card) to return Discover
WHEN card='30123456789' We EXPECT CardIssuer(card) to return American Express
WHEN card='90123456789' We EXPECT CardIssuer(card) to return Invalid Card
1.5 You Code: Tests
Write the tests based on the examples:
End of explanation
# TODO Re-write the program here, calling our function.
Explanation: Step 4: Rewrite
The final step is to re-write the original program, but use the function instead. The algorithm becomes
input credit card number into variable card
call the CardIssuer function with card as input, issuer as output
print issuer
1.6 You Code
Re-write the program. It should be 3 lines of code:
input card
call issuer function
print issuer
End of explanation
# Todo: execute this code
def checkLuhn(card):
''' This Luhn algorithm was adopted from the pseudocode here: https://en.wikipedia.org/wiki/Luhn_algorithm'''
total = 0
length = len(card)
parity = length % 2
for i in range(length):
digit = int(card[i])
if i%2 == parity:
digit = digit * 2
if digit > 9:
digit = digit -9
total = total + digit
return total % 10 == 0
Explanation: Functions are abstractions. Abstractions are good.
Step on the accellerator and the car goes. How does it work? Who cares, it's an abstraction! Functions are the same way. Don't believe me. Consider the Luhn Check Algorithm: https://en.wikipedia.org/wiki/Luhn_algorithm
This nifty little algorithm is used to verify that a sequence of digits is possibly a credit card number (as opposed to just a sequence of numbers). It uses a verfication approach called a checksum to as it uses a formula to figure out the validity.
Here's the function which given a card will let you know if it passes the Luhn check:
End of explanation
#TODO Write your two tests here
print("when card = 5443713204330437, Expec checkLuhn(card) = True, Actual=", checkLuhn('5443713204330437'))
print("when card = 5111111111111111, Expec checkLuhn(card) = False, Actual=", checkLuhn('5111111111111111'))
Explanation: Is that a credit card number or the ramblings of a madman?
In order to test the checkLuhn() function you need some credit card numbers. (Don't look at me... you ain't gettin' mine!!!!) Not to worry, the internet has you covered. The website: http://www.getcreditcardnumbers.com/ is not some mysterious site on the dark web. It's a site for generating "test" credit card numbers. You can't buy anything with these numbers, but they will pass the Luhn test.
Grab a couple of numbers and test the Luhn function as we did with the CardIssuer() function. Write at least to tests like these ones:
WHEN card='5443713204330437' We EXPECT checkLuhn(card) to return True
WHEN card='5111111111111111' We EXPECT checkLuhn(card) to return False
End of explanation
## TODO Write code here
Explanation: Putting it all together
Finally let's use all the functions we wrote/used in this lab to make a really cool program to validate creditcard numbers. Tools we will use:
interact_manual() to transform the creditcard input into a textbox
cardIssuer() to see if the card is a Visa, MC, Discover, Amex.
checkLuhn() to see if the card number passes the Lhun check
print_title() to display the title
print_normal() to display the output
emoji.emojize() to draw a thumbs up (passed Lhun check) or thumbs down (did not pass Lhun check).
Here's the Algorithm:
```
print the title "credit card validator"
write an interact function with card as input
get the card issuer
if the card passes lhun check
use thumbs up emoji
else
use thumbs down emoji
print in normal text the emoji icon and the card issuer
```
1.7 You Code
End of explanation
# run this code to turn in your work!
from coursetools.submission import Submission
Submission().submit()
Explanation: Metacognition
Rate your comfort level with this week's material so far.
1 ==> I don't understand this at all yet and need extra help. If you choose this please try to articulate that which you do not understand to the best of your ability in the questions and comments section below.
2 ==> I can do this with help or guidance from other people or resources. If you choose this level, please indicate HOW this person helped you in the questions and comments section below.
3 ==> I can do this on my own without any help.
4 ==> I can do this on my own and can explain/teach how to do it to others.
--== Double-Click Here then Enter a Number 1 through 4 Below This Line ==--
Questions And Comments
Record any questions or comments you have about this lab that you would like to discuss in your recitation. It is expected you will have questions if you did not complete the code sections correctly. Learning how to articulate what you do not understand is an important skill of critical thinking. Write them down here so that you remember to ask them in your recitation. We expect you will take responsilbity for your learning and ask questions in class.
--== Double-click Here then Enter Your Questions Below this Line ==--
End of explanation |
8,582 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TimML Notebook 3
Inhomogeneities
Consider a two-aquifer system that contains one inhomogeneity. Inside the inhomogeneity the transmissivity
of the top aquifer is much lower and the transmissivity of the bottom aquifer is much higher than outside the
inhomogeneity. Aquifer properties are given in Table 1 and the inhomogeneity data is given in table 2. There is a uniform gradient of 0.002 in Southeastern
direction.
Table 1
Step1: Questions
Exercise 3a
What are the leakage factors of the background aquifer and the inhomogeneity?
Step2: Exercise 3b
Make a contour plot of both aquifers.
Step3: Exercise 3c
Create a 20-year capture zone for the well, starting the pathlines halfway the top aquifer. First create a contour plot with a cross-section below it.
Step4: Exercise 3d
Change the elevation of the bottom of aquifer 1 from -30 to -20 inside inhomogeneity 1 (you need to recreate the model). Make a
contour plot with a cross-section below it and start some pathlines from $x=-200$, $y=700$. (note that the cross-section
shows the elevation layers in the background aquifer, not the inhomogeneity). Note that the pathlines jump when they enter and
exit inhomogeneity 1. This is caused by the jump in the base. It meets all continuity conditions and is an
approximation of the smooth change in elevation that occurs over a distance of approximately one aquifer
thickness from the boundary.
Step5: TO DO
Step6: Two inhomogeneities
A second inhomogeneity is added, which shares part of its boundary with the first inhomogeneity. The aquifer properties for the inhomogeneity are provided in table 3. Inside this second inhomogeneity, the transmissivity of both the bottom aquifer and the resistance of the leaky layer are reduced. The input is now somewhat complicated. First the data of the two inhomgeneities is entered. Second, analytic elements are placed along the boundary of the inhomogeneity with MakeInhomPolySide.
This routine places line elements along a string of points, but it requires that the
aquifer data is the same on the left and right sides of the line. Hence, for this case we need to break the boundary up
in three sections | Python Code:
%matplotlib inline
from timml import *
from pylab import *
figsize = (8, 8)
ml = ModelMaq(kaq=[10, 20], z=[20, 0, -10, -30], c=[4000])
xy1 = [(0, 600), (-100, 400), (-100, 200), (100, 100), (300, 100), (500, 100),
(700, 300), (700, 500), (600, 700), (400, 700), (200, 600)]
p1 = PolygonInhomMaq(ml, xy=xy1,
kaq=[2, 80], z=[20, 0, -10, -30], c=[500],
topboundary='conf', order=3, ndeg=2)
rf = Constant(ml, xr=1000, yr=0, hr=40)
uf = Uflow(ml, slope=0.002, angle=-45)
w = Well(ml, xw=400, yw=400, Qw=500, rw=0.2, layers=0)
ml.solve()
Explanation: TimML Notebook 3
Inhomogeneities
Consider a two-aquifer system that contains one inhomogeneity. Inside the inhomogeneity the transmissivity
of the top aquifer is much lower and the transmissivity of the bottom aquifer is much higher than outside the
inhomogeneity. Aquifer properties are given in Table 1 and the inhomogeneity data is given in table 2. There is a uniform gradient of 0.002 in Southeastern
direction.
Table 1: Aquifer data
|Layer | $k$ (m/d) | $z_b$ (m) | $z_t$ | $c$ (days) |
|------------:|-----------|-----------|-------|------------|
|Aquifer 0 | 10 | 0 | 20 | |
|Leaky Layer 1| | -10 | 0 | 4000 |
|Aquifer 1 | 20 | -30 | 10 | |
Table 2: Inhomogeneity 1 data
|Layer | $k$ (m/d) | $z_b$ (m) | $z_t$ | $c$ (days) |
|:-----------:|----------:|----------:|------:|-----------:|
|Aquifer 0 | 2 | 0 | 20 | - |
|Leaky Layer 1| - | -10 | 0 | 500 |
|Aquifer 1 | 80 | -30 | -10 | - |
A layout of the nodes of the inhomogeneity are shown in Fig. 1 (inhomogeneity 2 will be added
later on). A well is located in the top aquifer inside inhomogeneity 1 (the black dot).
<img src="figs/inhomogeneity_exercise3.png"> </img>
Figure 1: Layout of elements for exercise 3. A well is located inside inhomogeneity 1. Inhomogeneity 2 is added in the second part of the exercise.
End of explanation
print('Leakage factor of the background aquifer is:', ml.aq.lab)
print('Leakage factor of the inhomogeneity is:', p1.lab)
Explanation: Questions
Exercise 3a
What are the leakage factors of the background aquifer and the inhomogeneity?
End of explanation
ml.contour(win=[-200, 800, 0, 800], ngr=50, layers=[0, 1], levels=50, labels=1, decimals=2, figsize=figsize)
ml.contour(win=[-1200, 1800, -1000, 1800], ngr=50, layers=[0, 1], levels=50, labels=1, decimals=2, figsize=figsize)
htop = ml.headalongline(linspace(101, 499, 100), 100 + 0.001 * ones(100))
hbot = ml.headalongline(linspace(101, 499, 100), 100 - 0.001 * ones(100))
figure()
plot(linspace(101, 499, 100), htop[0])
plot(linspace(101, 499, 100), hbot[0])
qtop = zeros(100)
qbot = zeros(100)
layer = 1
x = linspace(101, 499, 100)
for i in range(100):
qx, qy = ml.disvec(x[i], 100 + 0.001)
qtop[i] = qy[layer]
qx, qy = ml.disvec(x[i], 100 - 0.001)
qbot[i] = qy[layer]
figure()
plot(x, qtop)
plot(x, qbot)
Explanation: Exercise 3b
Make a contour plot of both aquifers.
End of explanation
ml.plot(win=[-200, 800, 0, 800], orientation='both', figsize=figsize)
w.plotcapzone(hstepmax=50, nt=20, zstart=10, tmax=20 * 365.25, orientation='both')
Explanation: Exercise 3c
Create a 20-year capture zone for the well, starting the pathlines halfway the top aquifer. First create a contour plot with a cross-section below it.
End of explanation
ml = ModelMaq(kaq=[10, 20], z=[20, 0, -10, -30], c=[4000])
xy1 = [(0, 600), (-100, 400), (-100, 200), (100, 100), (300, 100), (500, 100),
(700, 300), (700, 500), (600, 700), (400, 700), (200, 600)]
p1 = PolygonInhomMaq(ml, xy=xy1,
kaq=[2, 80], z=[20, 0, -10, -40], c=[500],
topboundary='conf', order=5, ndeg=3)
rf = Constant(ml, xr=1000, yr=0, hr=40)
uf = Uflow(ml, slope=0.002, angle=-45)
w = Well(ml, xw=400, yw=400, Qw=500, rw=0.2, layers=0)
ml.solve()
Explanation: Exercise 3d
Change the elevation of the bottom of aquifer 1 from -30 to -20 inside inhomogeneity 1 (you need to recreate the model). Make a
contour plot with a cross-section below it and start some pathlines from $x=-200$, $y=700$. (note that the cross-section
shows the elevation layers in the background aquifer, not the inhomogeneity). Note that the pathlines jump when they enter and
exit inhomogeneity 1. This is caused by the jump in the base. It meets all continuity conditions and is an
approximation of the smooth change in elevation that occurs over a distance of approximately one aquifer
thickness from the boundary.
End of explanation
ml.plot(win=[-200, 800, 0, 800], orientation='both', figsize=figsize)
ml.tracelines(-200 * np.ones(2), 700 * np.ones(2), [-25, -15], hstepmax=25, orientation='both')
Explanation: TO DO: ADD AQUIFER TOP/BOTTOM JUMP
End of explanation
ml = ModelMaq(kaq=[10, 20], z=[20, 0, -10, -30], c=[4000])
xy1 = [(0, 600), (-100, 400), (-100, 200), (100, 100), (300, 100), (500, 100),
(700, 300), (700, 500), (600, 700), (400, 700), (200, 600)]
p1 = PolygonInhomMaq(ml, xy=xy1,
kaq=[2, 80], z=[20, 0, -10, -30], c=[500],
topboundary='conf', order=4, ndeg=2)
xy2 = [(0, 600), (200, 600), (400, 700), (400, 900), (200, 1100), (0, 1000), (-100, 800)]
p2 = PolygonInhomMaq(ml, xy=xy2,
kaq=[2, 8], z=[20, 0, -10, -30], c=[50],
topboundary='conf', order=4, ndeg=2)
rf = Constant(ml, xr=1000, yr=0, hr=40)
uf = Uflow(ml, slope=0.002, angle=-45)
w = Well(ml, xw=400, yw=400, Qw=500, rw=0.2, layers=0)
ml.solve()
ml.contour(win=[-200, 1000, 0, 1200], ngr=50, layers=[0, 1],
levels=20, figsize=figsize)
Explanation: Two inhomogeneities
A second inhomogeneity is added, which shares part of its boundary with the first inhomogeneity. The aquifer properties for the inhomogeneity are provided in table 3. Inside this second inhomogeneity, the transmissivity of both the bottom aquifer and the resistance of the leaky layer are reduced. The input is now somewhat complicated. First the data of the two inhomgeneities is entered. Second, analytic elements are placed along the boundary of the inhomogeneity with MakeInhomPolySide.
This routine places line elements along a string of points, but it requires that the
aquifer data is the same on the left and right sides of the line. Hence, for this case we need to break the boundary up
in three sections: One section with the background aquifer on one side and inhom1 on the other, one section
with the background aquifer on one side and inhom2 on the other, and one section with inhom1 on one side
and inhom2 on the other. The input file is a bit longer
Table 3: Inhomogeneity 2 data
|Layer | $k$ (m/d) | $z_b$ (m) | $z_t$ | $c$ (days) |
|------------:|----------:|----------:|------:|-----------:|
|Aquifer 0 | 2 | -20 | 0 | - |
|Leaky Layer 1| - | -40 | -20 | 50 |
|Aquifer 1 | 8 | -80 | -40 | - |
End of explanation |
8,583 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Datenanalyse-4
Step1: A tutorial on statistical-learning for scientific data processing
Step2: Nearest Neighbour
Step3: Model selection
Step4: Unsupervised Clustering
Step5: Maschinelles Lernen mit Text | Python Code:
from sklearn import datasets
iris = datasets.load_iris()
digits = datasets.load_digits()
iris.data[10]
iris.target
print(digits.data)
digits.target
digits.images[0]
from sklearn import svm
clf = svm.SVC(gamma=0.001, C=100.)
clf.fit(digits.data[:-1], digits.target[:-1])
clf.predict(digits.data[-1])
from sklearn import svm
from sklearn import datasets
clf = svm.SVC()
iris = datasets.load_iris()
X, y = iris.data, iris.target
clf.fit(X, y)
import pickle
s = pickle.dumps(clf)
clf2 = pickle.loads(s)
clf2.predict(X[0])
y[0]
from sklearn.externals import joblib
joblib.dump(clf, 'filename.pkl')
clf = joblib.load('filename.pkl')
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Datenanalyse-4:-Maschinelles-Lernen" data-toc-modified-id="Datenanalyse-4:-Maschinelles-Lernen-1"><span class="toc-item-num">1 </span>Datenanalyse 4: Maschinelles Lernen</a></div><div class="lev1 toc-item"><a href="#An-introduction-to-machine-learning-with-scikit-learn" data-toc-modified-id="An-introduction-to-machine-learning-with-scikit-learn-2"><span class="toc-item-num">2 </span>An introduction to machine learning with scikit-learn</a></div><div class="lev1 toc-item"><a href="#A-tutorial-on-statistical-learning-for-scientific-data-processing" data-toc-modified-id="A-tutorial-on-statistical-learning-for-scientific-data-processing-3"><span class="toc-item-num">3 </span>A tutorial on statistical-learning for scientific data processing</a></div><div class="lev3 toc-item"><a href="#Nearest-Neighbour" data-toc-modified-id="Nearest-Neighbour-301"><span class="toc-item-num">3.0.1 </span>Nearest Neighbour</a></div><div class="lev3 toc-item"><a href="#Model-selection" data-toc-modified-id="Model-selection-302"><span class="toc-item-num">3.0.2 </span>Model selection</a></div><div class="lev3 toc-item"><a href="#Unsupervised-Clustering" data-toc-modified-id="Unsupervised-Clustering-303"><span class="toc-item-num">3.0.3 </span>Unsupervised Clustering</a></div><div class="lev2 toc-item"><a href="#Maschinelles-Lernen-mit-Text" data-toc-modified-id="Maschinelles-Lernen-mit-Text-31"><span class="toc-item-num">3.1 </span>Maschinelles Lernen mit Text</a></div>
## Datenanalyse 4: Maschinelles Lernen
Das Folgende sind Ausschnitte aus dem <a href="http://scikit-learn.org/stable/tutorial/index.html">Tutorial für scikit-learn</a>.
## An introduction to machine learning with scikit-learn
End of explanation
from sklearn import datasets
iris = datasets.load_iris()
data = iris.data
data.shape
digits = datasets.load_digits()
digits.images.shape
import pylab as pl
pl.imshow(digits.images[-1], cmap=pl.cm.gray_r)
pl.show()
data = digits.images.reshape((digits.images.shape[0], -1))
Explanation: A tutorial on statistical-learning for scientific data processing
End of explanation
import numpy as np
from sklearn import datasets
iris = datasets.load_iris()
iris_X = iris.data
iris_y = iris.target
np.unique(iris_y)
# Split iris data in train and test data
# A random permutation, to split the data randomly
np.random.seed(0)
indices = np.random.permutation(len(iris_X))
iris_X_train = iris_X[indices[:-10]]
iris_y_train = iris_y[indices[:-10]]
iris_X_test = iris_X[indices[-10:]]
iris_y_test = iris_y[indices[-10:]]
# Create and fit a nearest-neighbor classifier
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(iris_X_train, iris_y_train)
knn.predict(iris_X_test)
iris_y_test
diabetes = datasets.load_diabetes()
diabetes_X_train = diabetes.data[:-20]
diabetes_X_test = diabetes.data[-20:]
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
from sklearn import linear_model
regr = linear_model.LinearRegression()
regr.fit(diabetes_X_train, diabetes_y_train)
print(regr.coef_)
np.mean((regr.predict(diabetes_X_test)-diabetes_y_test)**2)
regr.score(diabetes_X_test, diabetes_y_test)
X = np.c_[ .5, 1].T
y = [.5, 1]
test = np.c_[ 0, 2].T
regr = linear_model.LinearRegression()
import pylab as pl
pl.figure()
np.random.seed(0)
for _ in range(6):
this_X = .1*np.random.normal(size=(2, 1)) + X
regr.fit(this_X, y)
pl.plot(test, regr.predict(test))
pl.scatter(this_X, y, s=3)
pl.show()
regr = linear_model.Ridge(alpha=.1)
pl.figure()
np.random.seed(0)
for _ in range(6):
this_X = .1*np.random.normal(size=(2, 1)) + X
regr.fit(this_X, y)
pl.plot(test, regr.predict(test))
pl.scatter(this_X, y, s=3)
pl.show()
alphas = np.logspace(-4, -1, 6)
from __future__ import print_function
print([regr.set_params(alpha=alpha
).fit(diabetes_X_train, diabetes_y_train,
).score(diabetes_X_test, diabetes_y_test) for alpha in alphas])
regr = linear_model.Lasso()
scores = [regr.set_params(alpha=alpha
).fit(diabetes_X_train, diabetes_y_train
).score(diabetes_X_test, diabetes_y_test)
for alpha in alphas]
best_alpha = alphas[scores.index(max(scores))]
regr.alpha = best_alpha
regr.fit(diabetes_X_train, diabetes_y_train)
print(regr.coef_)
logistic = linear_model.LogisticRegression(C=1e5)
logistic.fit(iris_X_train, iris_y_train)
from sklearn import svm
svc = svm.SVC(kernel='linear')
svc.fit(iris_X_train, iris_y_train)
svc = svm.SVC(kernel='rbf')
Explanation: Nearest Neighbour
End of explanation
from sklearn import datasets, svm
digits = datasets.load_digits()
X_digits = digits.data
y_digits = digits.target
svc = svm.SVC(C=1, kernel='linear')
svc.fit(X_digits[:-100], y_digits[:-100]).score(X_digits[-100:], y_digits[-100:])
import numpy as np
X_folds = np.array_split(X_digits, 3)
y_folds = np.array_split(y_digits, 3)
scores = list()
for k in range(3):
# We use 'list' to copy, in order to 'pop' later on
X_train = list(X_folds)
X_test = X_train.pop(k)
X_train = np.concatenate(X_train)
y_train = list(y_folds)
y_test = y_train.pop(k)
y_train = np.concatenate(y_train)
scores.append(svc.fit(X_train, y_train).score(X_test, y_test))
print(scores)
from sklearn import cross_validation
k_fold = cross_validation.KFold(n=6, n_folds=3)
for train_indices, test_indices in k_fold:
print('Train: %s | test: %s' % (train_indices, test_indices))
>>> kfold = cross_validation.KFold(len(X_digits), n_folds=3)
>>> [svc.fit(X_digits[train], y_digits[train]).score(X_digits[test], y_digits[test])
... for train, test in kfold]
cross_validation.cross_val_score(svc, X_digits, y_digits, cv=kfold, n_jobs=-1)
>>> from sklearn.grid_search import GridSearchCV
>>> gammas = np.logspace(-6, -1, 10)
>>> clf = GridSearchCV(estimator=svc, param_grid=dict(gamma=gammas),
... n_jobs=-1)
>>> clf.fit(X_digits[:1000], y_digits[:1000])
>>> clf.best_score_
clf.best_estimator_.gamma == 1e-6
>>> # Prediction performance on test set is not as good as on train set
>>> clf.score(X_digits[1000:], y_digits[1000:])
cross_validation.cross_val_score(clf, X_digits, y_digits)
>>> from sklearn import linear_model, datasets
>>> lasso = linear_model.LassoCV()
>>> diabetes = datasets.load_diabetes()
>>> X_diabetes = diabetes.data
>>> y_diabetes = diabetes.target
>>> lasso.fit(X_diabetes, y_diabetes)
>>> # The estimator chose automatically its lambda:
>>> lasso.alpha_
Explanation: Model selection
End of explanation
>>> from sklearn import cluster, datasets
>>> iris = datasets.load_iris()
>>> X_iris = iris.data
>>> y_iris = iris.target
>>> k_means = cluster.KMeans(n_clusters=3)
>>> k_means.fit(X_iris)
print(k_means.labels_[::10])
print(y_iris[::10])
>>> import scipy as sp
>>> try:
... lena = sp.lena()
... except AttributeError:
... from scipy import misc
... lena = misc.lena()
>>> X = lena.reshape((-1, 1)) # We need an (n_sample, n_feature) array
>>> k_means = cluster.KMeans(n_clusters=5, n_init=1)
>>> k_means.fit(X)
>>> values = k_means.cluster_centers_.squeeze()
>>> labels = k_means.labels_
>>> lena_compressed = np.choose(labels, values)
>>> lena_compressed.shape = lena.shape
from sklearn.feature_extraction.image import grid_to_graph
from sklearn.cluster import AgglomerativeClustering
###############################################################################
# Generate data
lena = sp.misc.lena()
# Downsample the image by a factor of 4
lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + lena[1::2, 1::2]
X = np.reshape(lena, (-1, 1))
###############################################################################
# Define the structure A of the data. Pixels connected to their neighbors.
connectivity = grid_to_graph(*lena.shape)
###############################################################################
# Compute clustering
print("Compute structured hierarchical clustering...")
n_clusters = 15 # number of regions
ward = AgglomerativeClustering(n_clusters=n_clusters,
linkage='ward', connectivity=connectivity).fit(X)
label = np.reshape(ward.labels_, lena.shape)
print("Number of pixels: ", label.size)
print("Number of clusters: ", np.unique(label).size)
>>> digits = datasets.load_digits()
>>> images = digits.images
>>> X = np.reshape(images, (len(images), -1))
>>> connectivity = grid_to_graph(*images[0].shape)
>>> agglo = cluster.FeatureAgglomeration(connectivity=connectivity,
... n_clusters=32)
>>> agglo.fit(X)
>>> X_reduced = agglo.transform(X)
>>> X_approx = agglo.inverse_transform(X_reduced)
>>> images_approx = np.reshape(X_approx, images.shape)
>>> # Create a signal with only 2 useful dimensions
>>> x1 = np.random.normal(size=100)
>>> x2 = np.random.normal(size=100)
>>> x3 = x1 + x2
>>> X = np.c_[x1, x2, x3]
>>> from sklearn import decomposition
>>> pca = decomposition.PCA()
>>> pca.fit(X)
print(pca.explained_variance_)
# As we can see, only the 2 first components are useful
>>> pca.n_components = 2
>>> X_reduced = pca.fit_transform(X)
>>> X_reduced.shape
>>> # Generate sample data
>>> time = np.linspace(0, 10, 2000)
>>> s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal
>>> s2 = np.sign(np.sin(3 * time)) # Signal 2 : square signal
>>> S = np.c_[s1, s2]
>>> S += 0.2 * np.random.normal(size=S.shape) # Add noise
>>> S /= S.std(axis=0) # Standardize data
>>> # Mix data
>>> A = np.array([[1, 1], [0.5, 2]]) # Mixing matrix
>>> X = np.dot(S, A.T) # Generate observations
>>> # Compute ICA
>>> ica = decomposition.FastICA()
>>> S_ = ica.fit_transform(X) # Get the estimated sources
>>> A_ = ica.mixing_.T
>>> np.allclose(X, np.dot(S_, A_) + ica.mean_)
Explanation: Unsupervised Clustering
End of explanation
categories = ['alt.atheism', 'soc.religion.christian',
'comp.graphics', 'sci.med']
from sklearn.datasets import fetch_20newsgroups
twenty_train = fetch_20newsgroups(subset='train',
categories=categories, shuffle=True, random_state=42)
twenty_train.target_names
len(twenty_train.data)
len(twenty_train.filenames)
print(twenty_train.target_names[twenty_train.target[0]])
twenty_train.target[:10]
for t in twenty_train.target[:10]:
print(twenty_train.target_names[t])
from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(twenty_train.data)
X_train_counts.shape
count_vect.vocabulary_.get(u'algorithm')
from sklearn.feature_extraction.text import TfidfTransformer
tfidf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts)
X_train_tf = tfidf_transformer.transform(X_train_counts)
X_train_tf.shape
from sklearn.naive_bayes import MultinomialNB
clf = MultinomialNB().fit(X_train_tf, twenty_train.target)
docs_new = ['God is love', 'OpenGL on the GPU is fast']
X_new_counts = count_vect.transform(docs_new)
X_new_tfidf = tfidf_transformer.transform(X_new_counts)
predicted = clf.predict(X_new_tfidf)
for doc, category in zip(docs_new, predicted):
print('%r => %s' % (doc, twenty_train.target_names[category]))
from sklearn.pipeline import Pipeline
text_clf = Pipeline([('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', MultinomialNB()),])
text_clf = text_clf.fit(twenty_train.data, twenty_train.target)
import numpy as np
twenty_test = fetch_20newsgroups(subset='test',
categories=categories, shuffle=True, random_state=42)
docs_test = twenty_test.data
predicted = text_clf.predict(docs_test)
np.mean(predicted == twenty_test.target)
from sklearn.linear_model import SGDClassifier
text_clf = Pipeline([('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', SGDClassifier(loss='hinge', penalty='l2',
alpha=1e-3, n_iter=5)),])
_ = text_clf.fit(twenty_train.data, twenty_train.target)
predicted = text_clf.predict(docs_test)
np.mean(predicted == twenty_test.target)
from sklearn import metrics
print(metrics.classification_report(twenty_test.target, predicted,
target_names=twenty_test.target_names))
from sklearn.grid_search import GridSearchCV
parameters = {'vect__ngram_range': [(1, 1), (1, 2)],
'tfidf__use_idf': (True, False),
'clf__alpha': (1e-2, 1e-3),}
gs_clf = GridSearchCV(text_clf, parameters, n_jobs=-1)
gs_clf = gs_clf.fit(twenty_train.data[:400], twenty_train.target[:400])
twenty_train.target_names[gs_clf.predict(['God is love'])]
best_parameters, score, _ = max(gs_clf.grid_scores_, key=lambda x: x[1])
for param_name in sorted(parameters.keys()):
print("%s: %r" % (param_name, best_parameters[param_name]))
score
Explanation: Maschinelles Lernen mit Text
End of explanation |
8,584 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Spark SQL via PySpark
Goals
Step1: What is a SparkSession?
It is the driver process that controls a spark application
A SparkSession instance is responsible for executing the driver program’s commands (code) across executors (in a cluster) to complete a given task.
You can have as many SparkSessions as you want in a single Spark application.
How do I create a SparkSession?
You can use the SparkSession class attribute called Builder.
The class attribute builder allows you to run some of the following functions
Step2: Check the SparkSession variable
Step3: What is a Dataframe?
In Spark, a dataframe is the most common Structured API, and it is used to represent data in a table format with rows and columns.
Think of a dataframe as a spreadsheet with headers. The difference is that one Spark Dataframe can be distributed across several computers due to its large size or high computation requirements for faster analysis.
The list of column names from a dataframe with its respective data types is called the schema
Is a Spark Dataframe the same as a Python Pandas Dataframe?
A Python dataframe sits on one computer whereas a Spark Dataframe, once again, can be distributed across several computers.
PySpark allows the conversion from Python Pandas dataframes to Spark dataframes.
Create your first Dataframe
Let's create our first dataframe by using range and toDF functions.
* One column named numbers
* 10 rows containing numbers from 0-9
range(start, end=None, step=1, numPartitions=None)
* Create a DataFrame with single pyspark.sql.types.LongType column named id, containing elements in a range from start to end (exclusive) with step value step.
toDF(*cols)
* Returns a new class
Step4: Create another Dataframe
createDataFrame(data, schema=None, samplingRatio=None, verifySchema=True)
Creates a DataFrame from an RDD, a list or a pandas.DataFrame.
When schema is a list of column names, the type of each column will be inferred from data.
When schema is None, it will try to infer the schema (column names and types) from data, which should be an RDD of Row, or namedtuple, or dict.
Step5: Check the Dataframe schema
We are going to do apply a concept called schema inference which lets spark takes its best guess at figuring out the schema.
Spark reads part of the dataframe and then tries to parse the types of data in each row.
You can also define a strict schema when you read in data which does not let Spark guess. This is recommended for production use cases.
schema
* Returns the schema of this DataFrame as a pyspark.sql.types.StructType.
Step6: printSchema()
* Prints out the schema in the tree format
Step7: Access Dataframe Columns
select(*cols)
* Projects a set of expressions and returns a new DataFrame.
Access Dataframes's columns by attribute (df.name)
Step8: Access Dataframe's columns by indexing (df['name']).
* According to Sparks documentation, the indexing form is the recommended one because it is future proof and won’t break with column names that are also attributes on the DataFrame class.
Step9: Filter Dataframe
filter(condition)
* Filters rows using the given condition.
Select dogs that are older than 4 years
Step10: Group Dataframe
groupBy(*cols)
* Groups the DataFrame using the specified columns, so we can run aggregation on them. See GroupedData for all the available aggregate functions.
group dogs and count them by their age
Step11: Run SQL queries on your Dataframe
createOrReplaceTempView(name)
* Creates or replaces a local temporary view with this DataFrame.
* The lifetime of this temporary table is tied to the SparkSession that was used to create this DataFrame.
Register the current Dataframe as a SQL temporary view | Python Code:
from pyspark.sql import SparkSession
Explanation: Introduction to Spark SQL via PySpark
Goals:
Get familiarized with the basics of Spark SQL and PySpark
Learn to create a SparkSession
Verify if Jupyter can talk to Spark Master
References:
* https://spark.apache.org/docs/latest/api/python/pyspark.html
* https://spark.apache.org/docs/latest/sql-getting-started.html
* https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.SparkSession
* https://jaceklaskowski.gitbooks.io/mastering-spark-sql/
* http://people.csail.mit.edu/matei/papers/2015/sigmod_spark_sql.pdf
What is Spark SQL?
It is a Spark module that leverages Sparks functional programming APIs to allow SQL relational processing tasks on (semi)structured data.
Spark SQL provides Spark with more information about the structure of both the data and the computation being performed
What is PySpark?
PySpark is the Python API for Spark.
How do I start using Pyspark and SparkSQL?
Start by importing the PySpark SQL SparkSession Class and creating a SparkSession instance .
A SparkSession class is considered the entry point to programming Spark with the Dataset and DataFrame API.
A SparkSession can be used create DataFrames, register DataFrames as tables, execute SQL over tables, cache tables, and read parquet files.
Import SparkSession Class
End of explanation
spark = SparkSession.builder \
.appName("Python Spark SQL basic example") \
.master("spark://helk-spark-master:7077") \
.enableHiveSupport() \
.getOrCreate()
Explanation: What is a SparkSession?
It is the driver process that controls a spark application
A SparkSession instance is responsible for executing the driver program’s commands (code) across executors (in a cluster) to complete a given task.
You can have as many SparkSessions as you want in a single Spark application.
How do I create a SparkSession?
You can use the SparkSession class attribute called Builder.
The class attribute builder allows you to run some of the following functions:
appName: Sets a name for the application
master: URL for the Spark master (Local or Spark standalone cluster)
enableHiveSupport: Enables Hive support, including connectivity to a persistent Hive metastore, support for Hive serdes, and Hive user-defined functions.
getOrCreate:Gets an existing SparkSession or, if there is no existing one, creates a new one based on the options set in this builder.
Create a SparkSession instance
Define a spark variable
Pass values to the appName and master functions
For the master function, we are going to use the HELK's Spark Master container (helk-spark-master)
End of explanation
spark
Explanation: Check the SparkSession variable
End of explanation
first_df = spark.range(10).toDF("numbers")
first_df.show()
Explanation: What is a Dataframe?
In Spark, a dataframe is the most common Structured API, and it is used to represent data in a table format with rows and columns.
Think of a dataframe as a spreadsheet with headers. The difference is that one Spark Dataframe can be distributed across several computers due to its large size or high computation requirements for faster analysis.
The list of column names from a dataframe with its respective data types is called the schema
Is a Spark Dataframe the same as a Python Pandas Dataframe?
A Python dataframe sits on one computer whereas a Spark Dataframe, once again, can be distributed across several computers.
PySpark allows the conversion from Python Pandas dataframes to Spark dataframes.
Create your first Dataframe
Let's create our first dataframe by using range and toDF functions.
* One column named numbers
* 10 rows containing numbers from 0-9
range(start, end=None, step=1, numPartitions=None)
* Create a DataFrame with single pyspark.sql.types.LongType column named id, containing elements in a range from start to end (exclusive) with step value step.
toDF(*cols)
* Returns a new class:DataFrame that with new specified column names
End of explanation
dog_data=[['Pedro','Doberman',3],['Clementine','Golden Retriever',8],['Norah','Great Dane',6]\
,['Mabel','Austrailian Shepherd',1],['Bear','Maltese',4],['Bill','Great Dane',10]]
dog_df=spark.createDataFrame(dog_data, ['name','breed','age'])
dog_df.show()
Explanation: Create another Dataframe
createDataFrame(data, schema=None, samplingRatio=None, verifySchema=True)
Creates a DataFrame from an RDD, a list or a pandas.DataFrame.
When schema is a list of column names, the type of each column will be inferred from data.
When schema is None, it will try to infer the schema (column names and types) from data, which should be an RDD of Row, or namedtuple, or dict.
End of explanation
dog_df.schema
Explanation: Check the Dataframe schema
We are going to do apply a concept called schema inference which lets spark takes its best guess at figuring out the schema.
Spark reads part of the dataframe and then tries to parse the types of data in each row.
You can also define a strict schema when you read in data which does not let Spark guess. This is recommended for production use cases.
schema
* Returns the schema of this DataFrame as a pyspark.sql.types.StructType.
End of explanation
dog_df.printSchema()
Explanation: printSchema()
* Prints out the schema in the tree format
End of explanation
dog_df.select("name").show()
Explanation: Access Dataframe Columns
select(*cols)
* Projects a set of expressions and returns a new DataFrame.
Access Dataframes's columns by attribute (df.name):
End of explanation
dog_df.select(dog_df["name"]).show()
Explanation: Access Dataframe's columns by indexing (df['name']).
* According to Sparks documentation, the indexing form is the recommended one because it is future proof and won’t break with column names that are also attributes on the DataFrame class.
End of explanation
dog_df.filter(dog_df["age"] > 4).show()
Explanation: Filter Dataframe
filter(condition)
* Filters rows using the given condition.
Select dogs that are older than 4 years
End of explanation
dog_df.groupBy(dog_df["age"]).count().show()
Explanation: Group Dataframe
groupBy(*cols)
* Groups the DataFrame using the specified columns, so we can run aggregation on them. See GroupedData for all the available aggregate functions.
group dogs and count them by their age
End of explanation
dog_df.createOrReplaceTempView("dogs")
sql_dog_df = spark.sql("SELECT * FROM dogs")
sql_dog_df.show()
sql_dog_df = spark.sql("SELECT * FROM dogs WHERE name='Pedro'")
sql_dog_df.show()
Explanation: Run SQL queries on your Dataframe
createOrReplaceTempView(name)
* Creates or replaces a local temporary view with this DataFrame.
* The lifetime of this temporary table is tied to the SparkSession that was used to create this DataFrame.
Register the current Dataframe as a SQL temporary view
End of explanation |
8,585 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RPartVariables
This script runs repeated cross-validation as a search for suitable parameter values for RPart.
It has been re-run for all data-sets and the plotted results for each were considered. It was determined
that the default parameters had the best overall performance in terms of medial survival time.
Step1: Load data
Step2: Helper methods
Step3: Default and possible values
Step4: Winner is determined by looking at median survival time.
Step5: Choose a data set
Step6: Run comparison of parameters
Step7: Get some plottable results
Let's see how the parameters perform
Step8: Plot results | Python Code:
# import stuffs
%matplotlib inline
import numpy as np
import pandas as pd
from pyplotthemes import get_savefig, classictheme as plt
from lifelines.utils import k_fold_cross_validation
plt.latex = True
Explanation: RPartVariables
This script runs repeated cross-validation as a search for suitable parameter values for RPart.
It has been re-run for all data-sets and the plotted results for each were considered. It was determined
that the default parameters had the best overall performance in terms of medial survival time.
End of explanation
from datasets import get_nwtco, get_colon, get_lung, get_pbc, get_flchain
# Values of (trn, test)
datasets = {}
# Add the data sets
for name, getter in zip(["pbc", "lung", "colon", "nwtco", "flchain"],
[get_pbc, get_lung, get_colon, get_nwtco, get_flchain]):
trn = getter(norm_in=True, norm_out=False, training=True)
datasets[name] = trn
cens = (trn.iloc[:, 1] == 0)
censcount = np.sum(cens) / trn.shape[0]
print(name, "censed:", censcount)
Explanation: Load data
End of explanation
from pysurvival.rpart import RPartModel
from stats import surv_area
from lifelines.estimation import KaplanMeierFitter, median_survival_times
def score(T_actual, labels, E_actual):
'''
Return a score based on grouping
'''
scores = []
labels = labels.ravel()
for g in ['high', 'mid', 'low']:
members = labels == g
if np.sum(members) > 0:
kmf = KaplanMeierFitter()
kmf.fit(T_actual[members],
E_actual[members],
label='{}'.format(g))
# Last survival time
if np.sum(E_actual[members]) > 0:
lasttime = np.max(T_actual[members][E_actual[members] == 1])
else:
lasttime = np.nan
# End survival rate, median survival time, member count, last event
subscore = (kmf.survival_function_.iloc[-1, 0],
median_survival_times(kmf.survival_function_),
np.sum(members),
lasttime)
else:
# Rpart might fail in this respect
subscore = (np.nan, np.nan, np.sum(members), np.nan)
scores.append(subscore)
return scores
# Use for validation - should this be negative??
def high_median_time(T_actual, labels, E_actual):
members = (labels == 'high').ravel()
if np.sum(members) > 0:
kmf = KaplanMeierFitter()
kmf.fit(T_actual[members],
E_actual[members])
return median_survival_times(kmf.survival_function_)
else:
return np.nan
def area(T_actual, labels, E_actual):
mem = (labels == 'high').ravel()
if np.any(mem):
high_area = surv_area(T_actual[mem], E_actual[mem])
else:
high_area = np.nan
mem = (labels == 'low').ravel()
if np.any(mem):
low_area = surv_area(T_actual[mem], E_actual[mem])
else:
low_area = np.nan
return [low_area, high_area]
Explanation: Helper methods
End of explanation
default_values = dict(highlim=0.1,
lowlim=0.1,
minsplit=20,
minbucket=None,
xval=3,
cp=0.01)
possible_values = dict(cp=[0.01, 0.05, 0.1],
xval=[0, 3, 5, 7, 10],
minsplit=[1, 5, 10, 20, 50])
# Update values as we go along
#try:
# current_values
#except NameError:
current_values = default_values.copy()
print(current_values)
Explanation: Default and possible values
End of explanation
def get_winning_value(values, repeat_results, current_val):
winner = 0, 0
for i, x in enumerate(values):
mres = np.median(np.array(repeat_results)[:, i, :])
# For stability
if mres > winner[0] or (x == current_val and mres >= winner[0]):
winner = mres, x
return winner[1]
Explanation: Winner is determined by looking at median survival time.
End of explanation
d = datasets['colon']
durcol = d.columns[0]
eventcol = d.columns[1]
Explanation: Choose a data set
End of explanation
print("Starting values")
for k, v in current_values.items():
print(" ", k, "=", v)
# Repeat all variables
n = 1score
k = 3
repcount = 0
stable = False
while repcount < 4 and not stable:
repcount += 1
print(repcount)
stable = True
for key, values in sorted(possible_values.items()):
print(key)
models = []
for x in values:
kwargs = current_values.copy()
kwargs[key] = x
model = RPartModel(**kwargs)
model.var_label = key
model.var_value = x
models.append(model)
# Train and test
repeat_results = []
for rep in range(n):
result = k_fold_cross_validation(models, d, durcol, eventcol,
k=k,
evaluation_measure=high_median_time,
predictor='predict_classes')
repeat_results.append(result)
# See who won
winval = get_winning_value(values, repeat_results, current_values[key])
if winval != current_values[key]:
stable = False
print(key, current_values[key], "->", winval)
current_values[key] = winval
print("\nValues optimized after", repcount, "iterations")
for k, v in current_values.items():
print(" ", k, "=", v)
# Just print results from above
print("\nValues optimized after", repcount, "iterations")
for k, v in current_values.items():
print(" ", k, "=", v)
Explanation: Run comparison of parameters
End of explanation
#netcount = 6
models = []
# Try different epoch counts
key = 'minsplit'
for x in possible_values[key]:
kwargs = current_values.copy()
kwargs[key] = x
e = RPartModel(**kwargs)
e.var_label = key
e.var_value = x
models.append(e)
n = 10
k = 3
# Repeated cross-validation
repeat_results = []
for rep in range(n):
print("n =", rep)
# Training
#result = k_fold_cross_validation(models, d, durcol, eventcol, k=k, evaluation_measure=logscore, predictor='get_log')
# Validation
result = k_fold_cross_validation(models, d, durcol, eventcol, k=k,
evaluation_measure=area,
predictor='predict_classes')
repeat_results.append(result)
#repeat_results
Explanation: Get some plottable results
Let's see how the parameters perform
End of explanation
def plot_score_multiple(repeat_results, models):
boxes = []
labels = []
var_label = None
for i, m in enumerate(models):
labels.append(str(m.var_value))
var_label = m.var_label
vals = []
for result in repeat_results:
for kscore in result[i]:
vals.append(kscore[1])
boxes.append(vals)
plt.figure()
plt.boxplot(boxes, labels=labels, vert=False, colors=plt.colors[:len(models)])
plt.ylabel(var_label)
plt.title("Cross-validation: n={} k={}".format(n, k))
plt.xlabel("Something..")
#plt.gca().set_xscale('log')
plot_score_multiple(repeat_results, models)
def plot_score(repeat_results, models):
boxes = []
labels = []
var_label = None
# Makes no sense for low here for many datasets...
for i, m in enumerate(models):
labels.append(str(m.var_value))
var_label = m.var_label
vals = []
for result in repeat_results:
vals.extend(result[i])
boxes.append(vals)
plt.figure()
plt.boxplot(boxes, labels=labels, vert=False, colors=plt.colors[:len(models)])
plt.ylabel(var_label)
plt.title("Cross-validation: n={} k={}".format(n, k))
plt.xlabel("Median survival time (max={:.0f})".format(d[durcol].max()))
#plt.gca().set_xscale('log')
plot_score(repeat_results, models)
Explanation: Plot results
End of explanation |
8,586 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get Data
Step1: Basic Heat map
Step2: Heat map with axes
Step3: Non Uniform Heat map
Step4: Alignment of the data with respect to the grid
For a N-by-N matrix, N+1 points along the row or the column are assumed to be end points.
Step5: By default, for N points along any dimension, data aligns to the start of the rectangles in the grid.
The grid extends infinitely in the other direction. By default, the grid extends infintely
towards the bottom and the right.
Step6: By changing the row_align and column_align properties, the grid can extend in the opposite direction
Step7: For N+1 points on any direction, the grid extends infintely in both directions
Step8: Changing opacity and stroke
Step9: Selections on the grid map
Selection on the GridHeatMap works similar to excel. Clicking on a cell selects the cell, and deselects the previous selection. Using the Ctrl key allows multiple cells to be selected, while the Shift key selects the range from the last cell in the selection to the current cell.
Step10: The selected trait of a GridHeatMap contains a list of lists, with each sub-list containing the row and column index of a selected cell.
Step11: Registering on_element_click event handler | Python Code:
np.random.seed(0)
data = np.random.randn(10, 10)
Explanation: Get Data
End of explanation
col_sc = ColorScale()
grid_map = GridHeatMap(color=data, scales={'color': col_sc})
Figure(marks=[grid_map], padding_y=0.0)
grid_map.display_format = '.2f'
grid_map.font_style={'font-size': '12px', 'fill':'black', 'font-weight': 'bold'}
grid_map.display_format = None
Explanation: Basic Heat map
End of explanation
x_sc, y_sc, col_sc = OrdinalScale(), OrdinalScale(reverse=True), ColorScale()
grid_map = GridHeatMap(color=data, scales={'column': x_sc, 'row': y_sc, 'color': col_sc})
ax_x, ax_y = Axis(scale=x_sc), Axis(scale=y_sc, orientation='vertical')
Figure(marks=[grid_map], axes=[ax_x, ax_y], padding_y=0.0)
Explanation: Heat map with axes
End of explanation
x_sc, y_sc, col_sc = LinearScale(), LinearScale(reverse=True), ColorScale()
ax_x = Axis(scale=x_sc)
ax_y = Axis(scale=y_sc, orientation='vertical')
## The data along the rows is not uniform. Hence the 5th row(from top) of the map
## is twice the height of the remaining rows.
row_data = np.arange(10)
row_data[5:] = np.arange(6, 11)
column_data = np.arange(10, 20)
grid_map = GridHeatMap(row=row_data, column=column_data, color=data,
scales={'row': y_sc, 'column': x_sc, 'color': col_sc})
Figure(marks=[grid_map], padding_y=0.0, axes=[ax_x, ax_y])
print(row_data.shape)
print(column_data.shape)
print(data.shape)
Explanation: Non Uniform Heat map
End of explanation
x_sc, y_sc, col_sc = LinearScale(), LinearScale(reverse=True), ColorScale()
ax_x = Axis(scale=x_sc)
ax_y = Axis(scale=y_sc, orientation='vertical')
row_data = np.arange(11)
column_data = np.arange(10, 21)
grid_map = GridHeatMap(row=row_data, column=column_data, color=data,
scales={'row': y_sc, 'column': x_sc, 'color': col_sc})
Figure(marks=[grid_map], padding_y=0.0, axes=[ax_x, ax_y])
Explanation: Alignment of the data with respect to the grid
For a N-by-N matrix, N+1 points along the row or the column are assumed to be end points.
End of explanation
x_sc, y_sc, col_sc = LinearScale(), LinearScale(reverse=True, max=15), ColorScale()
ax_x = Axis(scale=x_sc)
ax_y = Axis(scale=y_sc, orientation='vertical')
row_data = np.arange(10)
column_data = np.arange(10, 20)
grid_map = GridHeatMap(row=row_data, column=column_data, color=data,
scales={'row': y_sc, 'column': x_sc, 'color': col_sc})
Figure(marks=[grid_map], padding_y=0.0, axes=[ax_x, ax_y])
Explanation: By default, for N points along any dimension, data aligns to the start of the rectangles in the grid.
The grid extends infinitely in the other direction. By default, the grid extends infintely
towards the bottom and the right.
End of explanation
x_sc, y_sc, col_sc = LinearScale(), LinearScale(reverse=True, min=-5, max=15), ColorScale()
ax_x = Axis(scale=x_sc)
ax_y = Axis(scale=y_sc, orientation='vertical')
row_data = np.arange(10)
column_data = np.arange(10, 20)
grid_map = GridHeatMap(row=row_data, column=column_data, color=data,
scales={'row': y_sc, 'column': x_sc, 'color': col_sc},
row_align='end')
Figure(marks=[grid_map], padding_y=0.0, axes=[ax_x, ax_y])
Explanation: By changing the row_align and column_align properties, the grid can extend in the opposite direction
End of explanation
x_sc, y_sc, col_sc = LinearScale(), LinearScale(reverse=True, min=-5, max=15), ColorScale()
ax_x = Axis(scale=x_sc)
ax_y = Axis(scale=y_sc, orientation='vertical')
row_data = np.arange(9)
column_data = np.arange(10, 20)
grid_map = GridHeatMap(row=row_data, column=column_data, color=data,
scales={'row': y_sc, 'column': x_sc, 'color': col_sc}, row_align='end')
Figure(marks=[grid_map], padding_y=0.0, axes=[ax_x, ax_y])
Explanation: For N+1 points on any direction, the grid extends infintely in both directions
End of explanation
col_sc = ColorScale()
grid_map = GridHeatMap(color=data, scales={'color': col_sc}, opacity=0.3, stroke='white')
Figure(marks=[grid_map], padding_y=0.0)
Explanation: Changing opacity and stroke
End of explanation
data = np.random.randn(10, 10)
col_sc = ColorScale()
grid_map = GridHeatMap(color=data, scales={'color': col_sc}, interactions={'click':'select'},
selected_style={'opacity': '1.0'}, unselected_style={'opacity': 0.4})
Figure(marks=[grid_map], padding_y=0.0)
Explanation: Selections on the grid map
Selection on the GridHeatMap works similar to excel. Clicking on a cell selects the cell, and deselects the previous selection. Using the Ctrl key allows multiple cells to be selected, while the Shift key selects the range from the last cell in the selection to the current cell.
End of explanation
grid_map.selected
Explanation: The selected trait of a GridHeatMap contains a list of lists, with each sub-list containing the row and column index of a selected cell.
End of explanation
import numpy as np
from IPython.display import display
from bqplot import *
np.random.seed(0)
data = np.random.randn(10, 10)
col_sc = ColorScale()
grid_map = GridHeatMap(color=data, scales={'color': col_sc},
interactions={'click': 'select'},
selected_style={'stroke': 'blue', 'stroke-width': 3})
figure=Figure(marks=[grid_map], padding_y=0.0)
from ipywidgets import Output
out = Output()
@out.capture()
def print_event(self, target):
print(target)
# test
print_event(1, 'test output')
grid_map.on_element_click(print_event)
display(figure)
display(out)
Explanation: Registering on_element_click event handler
End of explanation |
8,587 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Causal Effect
Import and settings
In this example, we need to import numpy, pandas, and graphviz in addition to lingam.
Step1: Utility function
We define a utility function to draw the directed acyclic graph.
Step2: Test data
We use 'Auto MPG Data Set' (http
Step3: Causal Discovery
To run causal discovery, we create a DirectLiNGAM object and call the fit method.
Step4: Prediction Model
We create the linear regression model.
Step5: Identification of Feature with Greatest Causal Influence on Prediction
To identify of the feature having the greatest intervention effect on the prediction, we create a CausalEffect object and call the estimate_effects_on_prediction method.
Step6: Estimation of Optimal Intervention
To estimate of the intervention such that the expectation of the prediction of the post-intervention observations is equal or close to a specified value, we use estimate_optimal_intervention method of CausalEffect. | Python Code:
import numpy as np
import pandas as pd
import graphviz
import lingam
print([np.__version__, pd.__version__, graphviz.__version__, lingam.__version__])
np.set_printoptions(precision=3, suppress=True)
np.random.seed(0)
Explanation: Causal Effect
Import and settings
In this example, we need to import numpy, pandas, and graphviz in addition to lingam.
End of explanation
def make_graph(adjacency_matrix, labels=None):
idx = np.abs(adjacency_matrix) > 0.01
dirs = np.where(idx)
d = graphviz.Digraph(engine='dot')
names = labels if labels else [f'x{i}' for i in range(len(adjacency_matrix))]
for to, from_, coef in zip(dirs[0], dirs[1], adjacency_matrix[idx]):
d.edge(names[from_], names[to], label=f'{coef:.2f}')
return d
Explanation: Utility function
We define a utility function to draw the directed acyclic graph.
End of explanation
X = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data-original',
delim_whitespace=True, header=None,
names = ['mpg', 'cylinders', 'displacement',
'horsepower', 'weight', 'acceleration',
'model year', 'origin', 'car name'])
X.dropna(inplace=True)
X.drop(['model year', 'origin', 'car name'], axis=1, inplace=True)
print(X.shape)
X.head()
Explanation: Test data
We use 'Auto MPG Data Set' (http://archive.ics.uci.edu/ml/datasets/Auto+MPG)
End of explanation
model = lingam.DirectLiNGAM()
model.fit(X)
labels = [f'{i}. {col}' for i, col in enumerate(X.columns)]
make_graph(model.adjacency_matrix_, labels)
Explanation: Causal Discovery
To run causal discovery, we create a DirectLiNGAM object and call the fit method.
End of explanation
from sklearn.linear_model import LassoCV
target = 0 # mpg
features = [i for i in range(X.shape[1]) if i != target]
reg = LassoCV(cv=5, random_state=0)
reg.fit(X.iloc[:, features], X.iloc[:, target])
Explanation: Prediction Model
We create the linear regression model.
End of explanation
ce = lingam.CausalEffect(model)
effects = ce.estimate_effects_on_prediction(X, target, reg)
df_effects = pd.DataFrame()
df_effects['feature'] = X.columns
df_effects['effect_plus'] = effects[:, 0]
df_effects['effect_minus'] = effects[:, 1]
df_effects
max_index = np.unravel_index(np.argmax(effects), effects.shape)
print(X.columns[max_index[0]])
Explanation: Identification of Feature with Greatest Causal Influence on Prediction
To identify of the feature having the greatest intervention effect on the prediction, we create a CausalEffect object and call the estimate_effects_on_prediction method.
End of explanation
# mpg = 15
c = ce.estimate_optimal_intervention(X, target, reg, 1, 15)
print(f'Optimal intervention: {c:.3f}')
# mpg = 21
c = ce.estimate_optimal_intervention(X, target, reg, 1, 21)
print(f'Optimal intervention: {c:.3f}')
# mpg = 30
c = ce.estimate_optimal_intervention(X, target, reg, 1, 30)
print(f'Optimal intervention: {c:.3f}')
Explanation: Estimation of Optimal Intervention
To estimate of the intervention such that the expectation of the prediction of the post-intervention observations is equal or close to a specified value, we use estimate_optimal_intervention method of CausalEffect.
End of explanation |
8,588 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Car Evaluation Database
Car Evaluation Database was derived from a simple hierarchical decision model originally developed for the demonstration of DEX (M. Bohanec, V. Rajkovic
Step1: Diplaying the top 5 tuples of car data set using head function
Step2: Describing the Data Set
Step3: The Car Evaluation Dataset contains 1728 tuple values and 7 attributes
Step4: From the table we can understand that the dataset has following properties
Step5: Displaying the top 5 tuples after mapping to numeric values.
Step6: Exploring the Data Set
Plotting Pie charts for all the six attributes in the data set to get the data distribution.<br />
We use the subplots method of mathplotlib to represent the different graphs in a figure.
Later show method of matplotlib library is used to display the data distribution charts.
Step7: From the pie charts we can infer that all the values in each categories of each attribute are equally distributed.
Plotting histogram for car class to know the class distribution
Step8: From the above graph we can observe that there are more number of unccountable cars ie., 62.5% of unccountable cars, 22.7% of accountable cars, 7.5% of good cars and 7.3% of very good cars. This shows us that most of the cars bought come under unaccountable class.
Pair Plot
Pair plotting between all the attributes in the data set which describes the relation among attributes. | Python Code:
# Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set(color_codes=True)
# Reading Dataset
df = pd.read_csv("car.data",sep=',',header=None, names=['buying','maintenance','doors','persons','luggage','safety','carClass'])
Explanation: Car Evaluation Database
Car Evaluation Database was derived from a simple hierarchical decision model originally developed for the demonstration of DEX (M. Bohanec, V. Rajkovic: Expert system for decision making. Sistemica 1(1), pp. 145-157, 1990.). This model evaluates cars into four classifiers(unaccountable, accountable, good, very good) according to the following attributes(buying, maintenance, doors, persons, luggage, safety).
Importing libraries(numpy, pandas, matplotlib, seaborn) and loading the car data into df variable
End of explanation
df.head()
Explanation: Diplaying the top 5 tuples of car data set using head function
End of explanation
# shape is used to get the details of number of features
print(df.shape)
Explanation: Describing the Data Set
End of explanation
# Decribing the data set.
df.describe()
Explanation: The Car Evaluation Dataset contains 1728 tuple values and 7 attributes
End of explanation
# Converting text values to numeric values
df['buying'] = df.buying.map({'vhigh':3,'high':2,'med':1,'low':0})
df['maintenance'] = df.maintenance.map({'vhigh':3,'high':2,'med':1,'low':0})
df['doors'] = df.doors.map({'2':2,'3':3,'4':4,'5more':5})
df['persons'] = df.persons.map({'2':2,'4':4,'more':5})
df['luggage'] = df.luggage.map({'small':0,'med':1,'big':2})
df['safety'] = df.safety.map({'low':0,'med':1,'high':2})
df['carClass'] = df.carClass.map({'unacc':0,'acc':1,'good':2,'vgood':3})
Explanation: From the table we can understand that the dataset has following properties:<br />
-> The data set does not have missing values as all the attributes has the same no of tuples(from count). <br />
-> The unique value gives the no of distinct values available for each category.<br />
-> The top value gives the category values which appears maximum no of times.<br />
-> The freq value gives the frequency of the top category value<br />
There are some text values in our data set,replacing them by numeric values would be handy in visualising the data and it also increases the computational performance. As we have to compare every text with the available categories, in order to avoid this(higher computation) we have converted the categories into numeric values as the list indices are numerics.<br />
Considering an example of buying feature which has four categories(low, med, high, vhigh). In order to find the frequency of each category it takes four comparisions for each text, so inorder to avoid these comparisions we convert these text to numerics(0, 1, 2, 3). Now we can directly increment the value in the list up on this numeric index
End of explanation
df.head()
Explanation: Displaying the top 5 tuples after mapping to numeric values.
End of explanation
fig,axes = plt.subplots(nrows=2, ncols=3)
ax0, ax1, ax2, ax3, ax4, ax5 = axes.flatten()
# Ploting Pie chart for 'Buying' feature with its category distribution
list0 = [0,0,0,0]
for i in df['buying']:
list0[i]= list0[i]+1
# print list0
labels0 = 'low','med','high','vhigh'
explode0 = (0, 0, 0, 0.1)
ax0.pie(list0, explode=explode0, labels=labels0, autopct='%1.1f%%',
shadow=True, startangle=90)
ax0.set_title('Car : Buying category')
# Ploting Pie chart for 'Maintenace' feature with its category distribution
list1 = [0,0,0,0]
for i in df['maintenance']:
list1[i]= list1[i]+1
# print list1
labels1 = 'low','med','high','vhigh'
explode1 = (0, 0, 0, 0.1)
ax1.pie(list1, explode=explode1, labels=labels1, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.set_title('Car : Maintenance category')
# Ploting Pie chart for 'doors' feature with the category distribution
list2 = [0,0,0,0]
for i in df['doors']:
list2[i-2]= list2[i-2]+1
# print list2
labels2 = '2','3','4','5more'
explode2 = (0, 0, 0, 0.1)
ax2.pie(list2, explode=explode2, labels=labels2, autopct='%1.1f%%',
shadow=True, startangle=90)
ax2.set_title('Car : Door category')
# Ploting Pie chart for 'persons' feature with the category distribution
list3 = [0,0,0]
for i in df['persons']:
if i==2:
i=0
elif i==4:
i=1
else:
i=2
list3[i]= list3[i]+1
# print list3
labels3 = '2','4','more'
explode3 = (0, 0, 0.1)
ax3.pie(list3, explode=explode3, labels=labels3, autopct='%1.1f%%',
shadow=True, startangle=90)
ax3.set_title('Car : Persons category')
# Ploting Pie chart for 'luggage' feature with the category distribution
list4 = [0,0,0]
for i in df['luggage']:
list4[i]= list4[i]+1
# print list4
labels4 = 'small','med','big'
explode4 = (0, 0, 0.1)
ax4.pie(list4, explode=explode4, labels=labels4, autopct='%1.1f%%',
shadow=True, startangle=90)
ax4.set_title('Car : Luggage category')
# Ploting Pie chart for 'safety' feature with the category distribution
list5 = [0,0,0]
for i in df['safety']:
list5[i]= list5[i]+1
# print list5
labels5 = 'low','med','high'
explode5 = (0, 0, 0.1)
ax5.pie(list5, explode=explode5, labels=labels5, autopct='%1.1f%%',
shadow=True, startangle=90)
ax5.set_title('Car : Safety category')
fig.tight_layout()
plt.show()
Explanation: Exploring the Data Set
Plotting Pie charts for all the six attributes in the data set to get the data distribution.<br />
We use the subplots method of mathplotlib to represent the different graphs in a figure.
Later show method of matplotlib library is used to display the data distribution charts.
End of explanation
# Ploting Pie chart for 'Buying' feature with its category distribution
list6 = [0,0,0,0]
for i in df['carClass']:
list0[i]= list0[i]+1
# print list6
labels0 = 'unacc','acc','good','vgood'
explode0 = (0, 0, 0, 0.1)
plt.pie(list0, explode=explode0, labels=labels0, autopct='%1.1f%%',
shadow=False, startangle=90)
plt.title('Car : Buying category')
plt.show()
Explanation: From the pie charts we can infer that all the values in each categories of each attribute are equally distributed.
Plotting histogram for car class to know the class distribution
End of explanation
# pairplot method of Seaborn is used to represent the plots for each pair of attributes
sns.pairplot(df, hue='carClass',palette="husl",markers=["o", "s", "D","v"])
Explanation: From the above graph we can observe that there are more number of unccountable cars ie., 62.5% of unccountable cars, 22.7% of accountable cars, 7.5% of good cars and 7.3% of very good cars. This shows us that most of the cars bought come under unaccountable class.
Pair Plot
Pair plotting between all the attributes in the data set which describes the relation among attributes.
End of explanation |
8,589 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 class="alert alert-info">Download Data <small> <i class="icon-download"></i> Get All Available MAF Files from TCGA Data Portal</small></h1>
Step1: <div class='alert alert-warning' style='width
Step2: Download most recent files from MAF dashboard
Step3: Use BeutifulSoup to parse out all of the links in the table
Step4: Download all of the MAFs by following the links
This takes a while, as I'm downloading all of the data.
I read in the table first to count the number of comment lines and a second time to actuall load the data.
Yes there is likely a more efficient way to do this, but I'm waiting on https
Step5: Reduce MAF down to most usefull columns
Step6: Get gene by patient mutation count matrix and save | Python Code:
import NotebookImport
from Imports import *
from bs4 import BeautifulSoup
from urllib2 import HTTPError
Explanation: <h1 class="alert alert-info">Download Data <small> <i class="icon-download"></i> Get All Available MAF Files from TCGA Data Portal</small></h1>
End of explanation
PATH_TO_CACERT = '/cellar/users/agross/cacert.pem'
Explanation: <div class='alert alert-warning' style='width:600px; font-size:16px'>
<h1>GLOBAL VARIABLE WARNING</h1>
Here I download updated clinical data from the TCGA Data Portal.
This is a secure site which uses HTTPS. I had to give it a path
to my ca-cert for the download to work.
Download a copy of a generic cacert.pem [here](http://curl.haxx.se/ca/cacert.pem).
</div>
End of explanation
out_path = OUT_PATH + '/MAFs_new_2/'
if not os.path.isdir(out_path):
os.makedirs(out_path)
maf_dashboard = 'https://confluence.broadinstitute.org/display/GDAC/MAF+Dashboard'
!curl --cacert $PATH_TO_CACERT $maf_dashboard -o tmp.html
Explanation: Download most recent files from MAF dashboard
End of explanation
f = open('tmp.html', 'rb').read()
soup = BeautifulSoup(f)
r = [l.get('href') for l in soup.find_all('a')
if l.get('href') != None
and '.maf' in l.get('href')]
Explanation: Use BeutifulSoup to parse out all of the links in the table
End of explanation
t = pd.read_table(f, nrows=10, sep='not_real_term', header=None, squeeze=True,
engine='python')
cols = ['Hugo_Symbol', 'NCBI_Build', 'Chromosome', 'Start_position',
'End_position', 'Strand', 'Reference_Allele',
'Tumor_Seq_Allele1', 'Tumor_Seq_Allele2',
'Tumor_Sample_Barcode', 'Protein_Change',
'Variant_Classification','Variant_Type']
maf = {}
for f in r:
try:
t = pd.read_table(f, nrows=10, sep='not_real_term', header=None,
squeeze=True,
engine='python')
skip = t.apply(lambda s: s.startswith('#'))
skip = list(skip[skip==True].index)
h = pd.read_table(f, header=0, index_col=None, skiprows=skip,
engine='python', nrows=0)
cc = list(h.columns.intersection(cols))
maf[f] = pd.read_table(f, header=0, index_col=None,
skiprows=skip,
engine='c',
usecols=cc)
except HTTPError:
print f
m2 = pd.concat(maf)
m3 = m2.dropna(axis=1, how='all')
Explanation: Download all of the MAFs by following the links
This takes a while, as I'm downloading all of the data.
I read in the table first to count the number of comment lines and a second time to actuall load the data.
Yes there is likely a more efficient way to do this, but I'm waiting on https://github.com/pydata/pandas/issues/2685
End of explanation
m4 = m3[cols]
m4 = m4.reset_index()
#m4.index = map(lambda s: s.split('/')[-1], m4.index)
m4 = m4.drop_duplicates(subset=['Hugo_Symbol','Tumor_Sample_Barcode','Start_position'])
m4 = m4.reset_index()
m4.to_csv(out_path + 'mega_maf.csv')
Explanation: Reduce MAF down to most usefull columns
End of explanation
m5 = m4.ix[m4.Variant_Classification != 'Silent']
cc = m5.groupby(['Hugo_Symbol','Tumor_Sample_Barcode']).size()
cc = cc.reset_index()
cc.to_csv(out_path + 'meta.csv')
cc.shape
Explanation: Get gene by patient mutation count matrix and save
End of explanation |
8,590 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate since we can include information about the sequence of words. Here we'll use a dataset of movie reviews, accompanied by labels.
The architecture for this network is shown below.
<img src="assets/network_diagram.png" width=400px>
Here, we'll pass in words to an embedding layer. We need an embedding layer because we have tens of thousands of words, so we'll need a more efficient representation for our input data than one-hot encoded vectors. You should have seen this before from the word2vec lesson. You can actually train up an embedding with word2vec and use it here. But it's good enough to just have an embedding layer and let the network learn the embedding table on it's own.
From the embedding layer, the new representations will be passed to LSTM cells. These will add recurrent connections to the network so we can include information about the sequence of words in the data. Finally, the LSTM cells will go to a sigmoid output layer here. We're using the sigmoid because we're trying to predict if this text has positive or negative sentiment. The output layer will just be a single unit then, with a sigmoid activation function.
We don't care about the sigmoid outputs except for the very last one, we can ignore the rest. We'll calculate the cost from the output of the last step and the training label.
Step1: Data preprocessing
The first step when building a neural network model is getting your data into the proper form to feed into the network. Since we're using embedding layers, we'll need to encode each word with an integer. We'll also want to clean it up a bit.
You can see an example of the reviews data above. We'll want to get rid of those periods. Also, you might notice that the reviews are delimited with newlines \n. To deal with those, I'm going to split the text into each review using \n as the delimiter. Then I can combined all the reviews back together into one big string.
First, let's remove all punctuation. Then get all the text without the newlines and split it into individual words.
Step2: Encoding the words
The embedding lookup requires that we pass in integers to our network. The easiest way to do this is to create dictionaries that map the words in the vocabulary to integers. Then we can convert each of our reviews into integers so they can be passed into the network.
Exercise
Step3: Encoding the labels
Our labels are "positive" or "negative". To use these labels in our network, we need to convert them to 0 and 1.
Exercise
Step4: Okay, a couple issues here. We seem to have one review with zero length. And, the maximum review length is way too many steps for our RNN. Let's truncate to 200 steps. For reviews shorter than 200, we'll pad with 0s. For reviews longer than 200, we can truncate them to the first 200 characters.
Exercise
Step5: Exercise
Step6: Training, Validation, Test
With our data in nice shape, we'll split it into training, validation, and test sets.
Exercise
Step7: With train, validation, and text fractions of 0.8, 0.1, 0.1, the final shapes should look like
Step8: For the network itself, we'll be passing in our 200 element long review vectors. Each batch will be batch_size vectors. We'll also be using dropout on the LSTM layer, so we'll make a placeholder for the keep probability.
Exercise
Step9: Embedding
Now we'll add an embedding layer. We need to do this because there are 74000 words in our vocabulary. It is massively inefficient to one-hot encode our classes here. You should remember dealing with this problem from the word2vec lesson. Instead of one-hot encoding, we can have an embedding layer and use that layer as a lookup table. You could train an embedding layer using word2vec, then load it here. But, it's fine to just make a new layer and let the network learn the weights.
Exercise
Step10: LSTM cell
<img src="assets/network_diagram.png" width=400px>
Next, we'll create our LSTM cells to use in the recurrent network (TensorFlow documentation). Here we are just defining what the cells look like. This isn't actually building the graph, just defining the type of cells we want in our graph.
To create a basic LSTM cell for the graph, you'll want to use tf.contrib.rnn.BasicLSTMCell. Looking at the function documentation
Step11: RNN forward pass
<img src="assets/network_diagram.png" width=400px>
Now we need to actually run the data through the RNN nodes. You can use tf.nn.dynamic_rnn to do this. You'd pass in the RNN cell you created (our multiple layered LSTM cell for instance), and the inputs to the network.
outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, initial_state=initial_state)
Above I created an initial state, initial_state, to pass to the RNN. This is the cell state that is passed between the hidden layers in successive time steps. tf.nn.dynamic_rnn takes care of most of the work for us. We pass in our cell and the input to the cell, then it does the unrolling and everything else for us. It returns outputs for each time step and the final_state of the hidden layer.
Exercise
Step12: Output
We only care about the final output, we'll be using that as our sentiment prediction. So we need to grab the last output with outputs[
Step13: Validation accuracy
Here we can add a few nodes to calculate the accuracy which we'll use in the validation pass.
Step14: Batching
This is a simple function for returning batches from our data. First it removes data such that we only have full batches. Then it iterates through the x and y arrays and returns slices out of those arrays with size [batch_size].
Step15: Training
Below is the typical training code. If you want to do this yourself, feel free to delete all this code and implement it yourself. Before you run this, make sure the checkpoints directory exists.
Step16: Testing | Python Code:
import numpy as np
import tensorflow as tf
with open('../sentiment_network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment_network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
Explanation: Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate since we can include information about the sequence of words. Here we'll use a dataset of movie reviews, accompanied by labels.
The architecture for this network is shown below.
<img src="assets/network_diagram.png" width=400px>
Here, we'll pass in words to an embedding layer. We need an embedding layer because we have tens of thousands of words, so we'll need a more efficient representation for our input data than one-hot encoded vectors. You should have seen this before from the word2vec lesson. You can actually train up an embedding with word2vec and use it here. But it's good enough to just have an embedding layer and let the network learn the embedding table on it's own.
From the embedding layer, the new representations will be passed to LSTM cells. These will add recurrent connections to the network so we can include information about the sequence of words in the data. Finally, the LSTM cells will go to a sigmoid output layer here. We're using the sigmoid because we're trying to predict if this text has positive or negative sentiment. The output layer will just be a single unit then, with a sigmoid activation function.
We don't care about the sigmoid outputs except for the very last one, we can ignore the rest. We'll calculate the cost from the output of the last step and the training label.
End of explanation
from string import punctuation
all_text = ''.join([c for c in reviews if c not in punctuation])
reviews = all_text.split('\n')
all_text = ' '.join(reviews)
words = all_text.split()
all_text[:2000]
words[:100]
Explanation: Data preprocessing
The first step when building a neural network model is getting your data into the proper form to feed into the network. Since we're using embedding layers, we'll need to encode each word with an integer. We'll also want to clean it up a bit.
You can see an example of the reviews data above. We'll want to get rid of those periods. Also, you might notice that the reviews are delimited with newlines \n. To deal with those, I'm going to split the text into each review using \n as the delimiter. Then I can combined all the reviews back together into one big string.
First, let's remove all punctuation. Then get all the text without the newlines and split it into individual words.
End of explanation
from collections import Counter
counts = Counter(words)
vocab = sorted(counts, key=counts.get, reverse=True)
vocab_to_int = {word: ii for ii, word in enumerate(vocab, 1)}
reviews_ints = []
for each in reviews:
reviews_ints.append([vocab_to_int[word] for word in each.split()])
Explanation: Encoding the words
The embedding lookup requires that we pass in integers to our network. The easiest way to do this is to create dictionaries that map the words in the vocabulary to integers. Then we can convert each of our reviews into integers so they can be passed into the network.
Exercise: Now you're going to encode the words with integers. Build a dictionary that maps words to integers. Later we're going to pad our input vectors with zeros, so make sure the integers start at 1, not 0.
Also, convert the reviews to integers and store the reviews in a new list called reviews_ints.
End of explanation
labels = labels.split('\n')
labels = np.array([1 if each == 'positive' else 0 for each in labels])
review_lens = Counter([len(x) for x in reviews_ints])
print("Zero-length reviews: {}".format(review_lens[0]))
print("Maximum review length: {}".format(max(review_lens)))
Explanation: Encoding the labels
Our labels are "positive" or "negative". To use these labels in our network, we need to convert them to 0 and 1.
Exercise: Convert labels from positive and negative to 1 and 0, respectively.
End of explanation
# Filter out that review with 0 length
reviews_ints = [each for each in reviews_ints if len(each) > 0]
Explanation: Okay, a couple issues here. We seem to have one review with zero length. And, the maximum review length is way too many steps for our RNN. Let's truncate to 200 steps. For reviews shorter than 200, we'll pad with 0s. For reviews longer than 200, we can truncate them to the first 200 characters.
Exercise: First, remove the review with zero length from the reviews_ints list.
End of explanation
seq_len = 200
features = np.zeros((len(reviews), seq_len), dtype=int)
for i, row in enumerate(reviews_ints):
features[i, -len(row):] = np.array(row)[:seq_len]
features[:10,:100]
Explanation: Exercise: Now, create an array features that contains the data we'll pass to the network. The data should come from review_ints, since we want to feed integers to the network. Each row should be 200 elements long. For reviews shorter than 200 words, left pad with 0s. That is, if the review is ['best', 'movie', 'ever'], [117, 18, 128] as integers, the row will look like [0, 0, 0, ..., 0, 117, 18, 128]. For reviews longer than 200, use on the first 200 words as the feature vector.
This isn't trivial and there are a bunch of ways to do this. But, if you're going to be building your own deep learning networks, you're going to have to get used to preparing your data.
End of explanation
split_frac = 0.8
split_idx = int(len(features)*0.8)
train_x, val_x = features[:split_idx], features[split_idx:]
train_y, val_y = labels[:split_idx], labels[split_idx:]
test_idx = int(len(val_x)*0.5)
val_x, test_x = val_x[:test_idx], val_x[test_idx:]
val_y, test_y = val_y[:test_idx], val_y[test_idx:]
print("\t\t\tFeature Shapes:")
print("Train set: \t\t{}".format(train_x.shape),
"\nValidation set: \t{}".format(val_x.shape),
"\nTest set: \t\t{}".format(test_x.shape))
Explanation: Training, Validation, Test
With our data in nice shape, we'll split it into training, validation, and test sets.
Exercise: Create the training, validation, and test sets here. You'll need to create sets for the features and the labels, train_x and train_y for example. Define a split fraction, split_frac as the fraction of data to keep in the training set. Usually this is set to 0.8 or 0.9. The rest of the data will be split in half to create the validation and testing data.
End of explanation
lstm_size = 256
lstm_layers = 1
batch_size = 500
learning_rate = 0.001
Explanation: With train, validation, and text fractions of 0.8, 0.1, 0.1, the final shapes should look like:
Feature Shapes:
Train set: (20000, 200)
Validation set: (2500, 200)
Test set: (2501, 200)
Build the graph
Here, we'll build the graph. First up, defining the hyperparameters.
lstm_size: Number of units in the hidden layers in the LSTM cells. Usually larger is better performance wise. Common values are 128, 256, 512, etc.
lstm_layers: Number of LSTM layers in the network. I'd start with 1, then add more if I'm underfitting.
batch_size: The number of reviews to feed the network in one training pass. Typically this should be set as high as you can go without running out of memory.
learning_rate: Learning rate
End of explanation
n_words = len(vocab)
# Create the graph object
graph = tf.Graph()
# Add nodes to the graph
with graph.as_default():
inputs_ = tf.placeholder(tf.int32, [None, None], name='inputs')
labels_ = tf.placeholder(tf.int32, [None, None], name='labels')
keep_prob = tf.placeholder(tf.float32, name='keep_prob')
Explanation: For the network itself, we'll be passing in our 200 element long review vectors. Each batch will be batch_size vectors. We'll also be using dropout on the LSTM layer, so we'll make a placeholder for the keep probability.
Exercise: Create the inputs_, labels_, and drop out keep_prob placeholders using tf.placeholder. labels_ needs to be two-dimensional to work with some functions later. Since keep_prob is a scalar (a 0-dimensional tensor), you shouldn't provide a size to tf.placeholder.
End of explanation
# Size of the embedding vectors (number of units in the embedding layer)
embed_size = 300
with graph.as_default():
embedding = tf.Variable(tf.random_uniform((n_words, embed_size), -1, 1))
embed = tf.nn.embedding_lookup(embedding, inputs_)
Explanation: Embedding
Now we'll add an embedding layer. We need to do this because there are 74000 words in our vocabulary. It is massively inefficient to one-hot encode our classes here. You should remember dealing with this problem from the word2vec lesson. Instead of one-hot encoding, we can have an embedding layer and use that layer as a lookup table. You could train an embedding layer using word2vec, then load it here. But, it's fine to just make a new layer and let the network learn the weights.
Exercise: Create the embedding lookup matrix as a tf.Variable. Use that embedding matrix to get the embedded vectors to pass to the LSTM cell with tf.nn.embedding_lookup. This function takes the embedding matrix and an input tensor, such as the review vectors. Then, it'll return another tensor with the embedded vectors. So, if the embedding layer as 200 units, the function will return a tensor with size [batch_size, 200].
End of explanation
with graph.as_default():
# Your basic LSTM cell
lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
# Add dropout to the cell
drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
# Stack up multiple LSTM layers, for deep learning
cell = tf.contrib.rnn.MultiRNNCell([drop] * lstm_layers)
# Getting an initial state of all zeros
initial_state = cell.zero_state(batch_size, tf.float32)
Explanation: LSTM cell
<img src="assets/network_diagram.png" width=400px>
Next, we'll create our LSTM cells to use in the recurrent network (TensorFlow documentation). Here we are just defining what the cells look like. This isn't actually building the graph, just defining the type of cells we want in our graph.
To create a basic LSTM cell for the graph, you'll want to use tf.contrib.rnn.BasicLSTMCell. Looking at the function documentation:
tf.contrib.rnn.BasicLSTMCell(num_units, forget_bias=1.0, input_size=None, state_is_tuple=True, activation=<function tanh at 0x109f1ef28>)
you can see it takes a parameter called num_units, the number of units in the cell, called lstm_size in this code. So then, you can write something like
lstm = tf.contrib.rnn.BasicLSTMCell(num_units)
to create an LSTM cell with num_units. Next, you can add dropout to the cell with tf.contrib.rnn.DropoutWrapper. This just wraps the cell in another cell, but with dropout added to the inputs and/or outputs. It's a really convenient way to make your network better with almost no effort! So you'd do something like
drop = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=keep_prob)
Most of the time, you're network will have better performance with more layers. That's sort of the magic of deep learning, adding more layers allows the network to learn really complex relationships. Again, there is a simple way to create multiple layers of LSTM cells with tf.contrib.rnn.MultiRNNCell:
cell = tf.contrib.rnn.MultiRNNCell([drop] * lstm_layers)
Here, [drop] * lstm_layers creates a list of cells (drop) that is lstm_layers long. The MultiRNNCell wrapper builds this into multiple layers of RNN cells, one for each cell in the list.
So the final cell you're using in the network is actually multiple (or just one) LSTM cells with dropout. But it all works the same from an achitectural viewpoint, just a more complicated graph in the cell.
Exercise: Below, use tf.contrib.rnn.BasicLSTMCell to create an LSTM cell. Then, add drop out to it with tf.contrib.rnn.DropoutWrapper. Finally, create multiple LSTM layers with tf.contrib.rnn.MultiRNNCell.
Here is a tutorial on building RNNs that will help you out.
End of explanation
with graph.as_default():
outputs, final_state = tf.nn.dynamic_rnn(cell, embed,
initial_state=initial_state)
Explanation: RNN forward pass
<img src="assets/network_diagram.png" width=400px>
Now we need to actually run the data through the RNN nodes. You can use tf.nn.dynamic_rnn to do this. You'd pass in the RNN cell you created (our multiple layered LSTM cell for instance), and the inputs to the network.
outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, initial_state=initial_state)
Above I created an initial state, initial_state, to pass to the RNN. This is the cell state that is passed between the hidden layers in successive time steps. tf.nn.dynamic_rnn takes care of most of the work for us. We pass in our cell and the input to the cell, then it does the unrolling and everything else for us. It returns outputs for each time step and the final_state of the hidden layer.
Exercise: Use tf.nn.dynamic_rnn to add the forward pass through the RNN. Remember that we're actually passing in vectors from the embedding layer, embed.
End of explanation
with graph.as_default():
predictions = tf.contrib.layers.fully_connected(outputs[:, -1], 1, activation_fn=tf.sigmoid)
cost = tf.losses.mean_squared_error(labels_, predictions)
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
Explanation: Output
We only care about the final output, we'll be using that as our sentiment prediction. So we need to grab the last output with outputs[:, -1], the calculate the cost from that and labels_.
End of explanation
with graph.as_default():
correct_pred = tf.equal(tf.cast(tf.round(predictions), tf.int32), labels_)
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
Explanation: Validation accuracy
Here we can add a few nodes to calculate the accuracy which we'll use in the validation pass.
End of explanation
def get_batches(x, y, batch_size=100):
n_batches = len(x)//batch_size
x, y = x[:n_batches*batch_size], y[:n_batches*batch_size]
for ii in range(0, len(x), batch_size):
yield x[ii:ii+batch_size], y[ii:ii+batch_size]
Explanation: Batching
This is a simple function for returning batches from our data. First it removes data such that we only have full batches. Then it iterates through the x and y arrays and returns slices out of those arrays with size [batch_size].
End of explanation
epochs = 10
with graph.as_default():
saver = tf.train.Saver()
with tf.Session(graph=graph) as sess:
sess.run(tf.global_variables_initializer())
iteration = 1
for e in range(epochs):
state = sess.run(initial_state)
for ii, (x, y) in enumerate(get_batches(train_x, train_y, batch_size), 1):
feed = {inputs_: x,
labels_: y[:, None],
keep_prob: 0.5,
initial_state: state}
loss, state, _ = sess.run([cost, final_state, optimizer], feed_dict=feed)
if iteration%5==0:
print("Epoch: {}/{}".format(e, epochs),
"Iteration: {}".format(iteration),
"Train loss: {:.3f}".format(loss))
if iteration%25==0:
val_acc = []
val_state = sess.run(cell.zero_state(batch_size, tf.float32))
for x, y in get_batches(val_x, val_y, batch_size):
feed = {inputs_: x,
labels_: y[:, None],
keep_prob: 1,
initial_state: val_state}
batch_acc, val_state = sess.run([accuracy, final_state], feed_dict=feed)
val_acc.append(batch_acc)
print("Val acc: {:.3f}".format(np.mean(val_acc)))
iteration +=1
saver.save(sess, "checkpoints/sentiment.ckpt")
Explanation: Training
Below is the typical training code. If you want to do this yourself, feel free to delete all this code and implement it yourself. Before you run this, make sure the checkpoints directory exists.
End of explanation
test_acc = []
with tf.Session(graph=graph) as sess:
saver.restore(sess, tf.train.latest_checkpoint('/output/checkpoints'))
test_state = sess.run(cell.zero_state(batch_size, tf.float32))
for ii, (x, y) in enumerate(get_batches(test_x, test_y, batch_size), 1):
feed = {inputs_: x,
labels_: y[:, None],
keep_prob: 1,
initial_state: test_state}
batch_acc, test_state = sess.run([accuracy, final_state], feed_dict=feed)
test_acc.append(batch_acc)
print("Test accuracy: {:.3f}".format(np.mean(test_acc)))
Explanation: Testing
End of explanation |
8,591 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: 第2章 関数近似(補間)
教科書第2章に載っているアルゴリズムを実装していきます。
各種ライブラリのインポート・後で使う汎用関数を定義
Step4: 式(2.5)の実装
n+1個の点列を入力し、逆行列を解いて、補間多項式を求め、n次補間多項式の係数行列[a_0, a_1, ..., a_n]を返す
INPUT
points
Step5: 式(2.7)の実装
補間多項式を変形した式から、逆行列の計算をすることなく、ラグランジュの補間多項式を求める
ただし、今回は補間多項式の係数行列を返すのではなく、具体的なxの値のリストに対して、補間値のリストを生成して返す
INPUT
points | Python Code:
#!/usr/bin/python
#-*- encoding: utf-8 -*-
Copyright (c) 2015 @myuuuuun
https://github.com/myuuuuun/NumericalCalculation
This software is released under the MIT License.
%matplotlib inline
from __future__ import division, print_function
import math
import numpy as np
import functools
import sys
import types
import matplotlib.pyplot as plt
EPSIRON = 1.0e-8
係数行列[a_0, a_1, ..., a_n] から、n次多項式 a_0 + a_1 * x + ... + a_n * x^n
を生成して返す(関数を返す)
def make_polynomial(a_matrix):
def __func__(x):
f = 0
for n, a_i in enumerate(a_matrix):
f += a_i * pow(x, n)
return f
return __func__
グラフを描画し、その上に元々与えられていた点列を重ねてプロットする
INPUT:
points: 与えられた点列のリスト[[x_0, f_0], [x_1, f_1], ..., [x_n, f_n]]
x_list: 近似曲線を描写するxの範囲・密度
f_list: 上のxに対応するfの値
def points_on_func(points, x_list, f_list, **kwargs):
title = kwargs.get('title', "Given Points and Interpolation Curve")
xlim = kwargs.get('xlim', False)
ylim = kwargs.get('ylim', False)
fig, ax = plt.subplots()
plt.title(title)
plt.plot(x_list, f_list, color='b', linewidth=1, label="Interpolation Curve")
points_x = [point[0] for point in points]
points_y = [point[1] for point in points]
plt.plot(points_x, points_y, 'o', color='r', label="Given Points")
plt.xlabel("x")
plt.ylabel("f")
if xlim:
ax.set_xlim(xlim)
if ylim:
ax.set_ylim(ylim)
plt.legend()
plt.show()
Explanation: 第2章 関数近似(補間)
教科書第2章に載っているアルゴリズムを実装していきます。
各種ライブラリのインポート・後で使う汎用関数を定義
End of explanation
def lagrange(points):
# 次元数
dim = len(points) - 1
# matrix Xをもとめる(ヴァンデルモンドの行列式)
x_matrix = np.array([[pow(point[0], j) for j in range(dim + 1)] for point in points])
# matrix Fをもとめる
f_matrix = np.array([point[1] for point in points])
# 線形方程式 X * A = F を解く
a_matrix = np.linalg.solve(x_matrix, f_matrix)
return a_matrix
# lagrange()で求めた補間多項式と、元の点列をプロットしてみる
# 与えられた点列のリスト
points = [[1, 1], [2, 2], [3, 1], [4, 1], [5, 3]]
# ラグランジュの補間多項式の係数行列を求める
a_matrix = lagrange(points)
# 係数行列を多項式に変換
func_lagrange = make_polynomial(a_matrix)
# 0から8まで、0.1刻みでxとfの値のセットを求める
x_list = np.arange(0, 8, 0.1)
f_list = func_lagrange(x_list)
# プロットする
points_on_func(points, x_list, f_list)
Explanation: 式(2.5)の実装
n+1個の点列を入力し、逆行列を解いて、補間多項式を求め、n次補間多項式の係数行列[a_0, a_1, ..., a_n]を返す
INPUT
points: n+1個の点列[[x_0, f_0], [x_1, f_1], ..., [x_n, f_n]]
OUTPUT
n次補間多項式の係数行列[a_0, a_1, ..., a_n]を返す
End of explanation
def lagrange2(points, x_list=np.arange(-5, 5, 0.1)):
dim = len(points) - 1
f_list = []
for x in x_list:
L = 0
for i in range(dim + 1):
Li = 1
for j in range(dim + 1):
if j != i:
Li *= (x - points[j][0]) / (points[i][0] - points[j][0])
Li *= points[i][1]
L += Li
f_list.append(L)
return f_list
points = [[1, 1], [2, 2], [3, 1], [4, 1], [5, 3]]
a_matrix = lagrange2(points, np.arange(0, 8, 0.1))
points_on_func(points, np.arange(0, 8, 0.1), a_matrix)
Explanation: 式(2.7)の実装
補間多項式を変形した式から、逆行列の計算をすることなく、ラグランジュの補間多項式を求める
ただし、今回は補間多項式の係数行列を返すのではなく、具体的なxの値のリストに対して、補間値のリストを生成して返す
INPUT
points: 与えられた点列を入力
x_list: 補間値を求めたいxのリストを入力
OUTPUT
f_list: x_listの各要素に対する補間値のリスト
End of explanation |
8,592 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Uncertainty analysis of a 2-D slice model
Possible paper titles
Step1: Model set-up
Subsequently, we will use a model from the "Atlas of Structural Geophysics" as an example model.
Step2: BUG!!!!
Note
Step3: We now define the parameter uncertainties
Step4: And, in a next step, perform the model sampling
Step5: Save the model data for later re-use (e.g. to extend the data set)
Step6: Use hspace to calculate joint entropies
Adjusted notebook
Step7: Calculation of cell information entropy
(Include note on
Step8: We now visualise the cell information entropy, shown in Fig. (). We can here clearly identify uncertain regions within this model section. It is interesting to note that we can mostly still identify the distinct layer boundaries in the fuzzy areas of uncertainty around their borders (note
Step9: Here again an example of single models (adjust to visualise and probably include something like a "table plot" of multiple images for a paper!)
Step10: And here the "mean" lithologies (note
Step11: And here a bit more meaningful
Step12: Idea
Step13: Try own "entropy colormap"
Step14: For comparison again
Step15: And the difference, for clarity
Step16: Clearly, the highset reduction is in the area around the borehole, but interestingly, the uncertianty in other areas is also reduced! Note specifically the reduction of uncertainties in the two neighbouring fold hinges.
Let's check some other positions (and drilling "depths")
Step17: We also just include one timing step to estimate the approximate simualtion time
Step18: Intersting! Only a local reduction around the drilling position, however
Step19: Check deep "drilling" at pos 60
Step20: Interesting! And now both combined
Step21: We can see that now only a part on the left remains with significant uncertainties. So, let's "drill" into this, as well | Python Code:
from IPython.core.display import HTML
css_file = 'pynoddy.css'
HTML(open(css_file, "r").read())
%matplotlib inline
# here the usual imports. If any of the imports fails,
# make sure that pynoddy is installed
# properly, ideally with 'python setup.py develop'
# or 'python setup.py install'
import sys, os
import matplotlib.pyplot as plt
import numpy as np
# adjust some settings for matplotlib
from matplotlib import rcParams
# print rcParams
rcParams['font.size'] = 15
# determine path of repository to set paths corretly below
repo_path = os.path.realpath('../..')
sys.path.append('../..')
import pynoddy
import importlib
importlib.reload(pynoddy)
import pynoddy.history
import pynoddy.experiment
importlib.reload(pynoddy.experiment)
rcParams.update({'font.size': 15})
pynoddy.history.NoddyHistory(history="typeb.his")
Explanation: Uncertainty analysis of a 2-D slice model
Possible paper titles:
Posterior analysis of geological models/ geophysical inversions? with information theory
...with measures from information theory
...with information theoretic measures
...with information measures
...with information
Ensemble analysis...
Posterior and ensemble analysis...
(Note: reference to posterior analysis, e.g. in Tarantola paper!)
Include:
Analysis of pynoddy models:
simple example of graben (because the uncertainty reduction is so counter-intuitive),
and maybe more complex example of folding structure?
Analysis of object modelling results? (i.e. the typical "Stanford channels"? but: only two outcomes, so not so meaningful... better example?)
Analysis of posterior ensemble from geophysical inversion (Greenstone model? Other examples from Mark & Mark?)
Journal? Math. Geo? Tectonophysics (note: relevance to strucural geological models!)
Include theory: error bounds on information measures!
End of explanation
# from pynoddy.experiment import monte_carlo
model_url = 'http://tectonique.net/asg/ch3/ch3_7/his/typeb.his'
ue = pynoddy.experiment.Experiment(history="typeb.his")
ue.change_cube_size(100)
sec = ue.get_section('y')
tmp = open("typeb.his").readlines()
Explanation: Model set-up
Subsequently, we will use a model from the "Atlas of Structural Geophysics" as an example model.
End of explanation
sec.block.shape
ue.plot_section('y')
plt.imshow(sec.block[:,50,:].transpose(), origin = 'lower left', interpolation = 'none')
tmp = sec.block[:,50,:]
tmp.shape
ue.set_random_seed(12345)
ue.info(events_only = True)
Explanation: BUG!!!!
Note: there is either a bug in pynoddy or in Noddy itself: but the slice plotting method fails: actually, not a slice is computed but the entire model (and the extent is also not correct!). Check with Mark in course of paper prep!
End of explanation
param_stats = [{'event' : 2,
'parameter': 'Amplitude',
'stdev': 100.0,
'type': 'normal'},
{'event' : 2,
'parameter': 'Wavelength',
'stdev': 500.0,
'type': 'normal'},
{'event' : 2,
'parameter': 'X',
'stdev': 500.0,
'type': 'normal'}]
ue.set_parameter_statistics(param_stats)
Explanation: We now define the parameter uncertainties:
End of explanation
ue.set_random_seed(112358)
# perfrom random sampling
resolution = 100
sec = ue.get_section('y')
tmp = sec.block[:,50,:]
n_draws = 5000
model_sections = np.empty((n_draws, tmp.shape[0], tmp.shape[1]))
for i in range(n_draws):
ue.random_draw()
tmp_sec = ue.get_section('y', resolution = resolution,
remove_tmp_files = True)
model_sections[i,:,:] = tmp_sec.block[:,50,:]
Explanation: And, in a next step, perform the model sampling:
End of explanation
import pickle
f_out = open("model_sections_5k2.pkl", 'wb')
pickle.dump(model_sections, f_out)
f_in = open("model_sections_5k2.pkl", 'rb')
model_sections = pickle.load(f_in)
Explanation: Save the model data for later re-use (e.g. to extend the data set):
End of explanation
sys.path.append('/Users/flow/git/hspace')
import hspace.measures
importlib.reload(hspace.measures)
model_sections.shape
Explanation: Use hspace to calculate joint entropies
Adjusted notebook: use hspace-package to calculate information theoretic measures
End of explanation
hspace.measures.joint_entropy(model_sections[:,50,:], [0,1])
h = np.empty_like(model_sections[0,:,:])
for i in range(100):
for j in range(40):
h[i,j] = hspace.measures.joint_entropy(model_sections[:,i,j])
h[50,30]
Explanation: Calculation of cell information entropy
(Include note on: theory of entropy calculation)
(Include in this paper: estimates on error bounds?)
Here now the function to calculate entropy from a data array in general. What we will need to do later is to pass all results at a single position as a "data array" and we can then estimate the information entropy at this position.
This function already expects a sorted array as an input and then uses the (ultra-fast) switchpoint method to calculate entropy:
The algorithm works on the simple idea that we do not explicitly require the single outputs at each location, but only the relative probability values. This may not matter too much for single entropy estimates (uni-variate), but it will matter a lot for multivariate cases, because we do not need to check all possible outcomes! Note that all outcomes with zero probability are simply not considered in the sorting algorithm (and they do not play any role in the calculation of the entropy, anyway), and that's exactly what we want to have!
In this new version, we use the implementation the hspace package:
End of explanation
plt.imshow(h.transpose(), origin = 'lower left',
cmap = 'gray', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
Explanation: We now visualise the cell information entropy, shown in Fig. (). We can here clearly identify uncertain regions within this model section. It is interesting to note that we can mostly still identify the distinct layer boundaries in the fuzzy areas of uncertainty around their borders (note: highlight in Figure!). However, additional aspects of uncertainty are now introduced: (a) the uncertainty about the x-position of the folds (see parameters: event 2, parameter x) is now clearly visible, and (b) uncertianties now seem to concentrate on the fold hinges. However, this is not so clear in the left part of the model, where the fold hing seems to be the least uncertain part. (check why: is this where the fold is actually fixed (even though still uncertain). My current interpretation: the fold location is fixed somewhere near this point, and so the wavelength uncertainty does not play a significant role. Furthermore, the fold is quite "open" at this position (i.e.: low angle between hinges) and therefore lateral shifts do not play a significant role.
End of explanation
plt.imshow(model_sections[70,:,:].transpose(), origin = 'lower left', interpolation = 'none')
Explanation: Here again an example of single models (adjust to visualise and probably include something like a "table plot" of multiple images for a paper!):
End of explanation
plt.imshow(np.mean(model_sections, axis = 0).transpose(), origin = 'lower left', interpolation = 'none')
Explanation: And here the "mean" lithologies (note: not really a distinct meaning, simply showing the average litho ids - could be somehow interpreted as characteristic functions, though...).
End of explanation
# step 1: estimate probabilities (note: unfortunate workaround with ones multiplication,
# there may be a better way, but this is somehow a recurring problem of implicit
# array flattening in numpy)
litho_id = 4
prob = np.sum(np.ones_like(model_sections) * (model_sections == litho_id), axis = 0) / model_sections.shape[0]
plt.imshow(prob.transpose(),
origin = 'lower left',
interpolation = 'none',
cmap = 'gray_r')
plt.colorbar(orientation = 'horizontal')
Explanation: And here a bit more meaningful: the analysis of single layer probabilities:
End of explanation
importlib.reload(hspace.measures)
dx = 15
xvals = np.ones(dx, dtype=int) * 20
yvals = np.arange(11,11+dx, dtype=int)
pos = np.vstack([xvals, yvals])
hspace.measures.joint_entropy(model_sections, pos.T)
# now: define position of "drill":
nx = 10
xvals = np.ones(nx, dtype=int) * 60
yvals = np.arange(39,39-nx, -1, dtype=int)
pos = np.vstack([xvals, yvals]).T
# determine joint entropy of drill_locs:
h_joint_drill = hspace.measures.joint_entropy(model_sections, pos)
# generate conditional entropies for entire section:
h_cond_drill = np.zeros_like(h)
for i in range(100):
for j in range(40):
# add new position to positions vector:
pos_all = np.vstack([pos, np.array([i,j])])
# determine joint entropy
h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all)
# subtract joint entropy of drill locs to obtain conditional entropy
h_cond_drill[i,j] = h_joint_loc - h_joint_drill
plt.imshow(h_cond_drill.transpose(), origin = 'lower left',
cmap = 'gray', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,100])
plt.ylim([0,40])
Explanation: Idea: also include a "new" consideration: where to collect information to reduce uncertainty of a single layer? Could be identified by reducing layer fuzziness, for example!
Or: what are most likely positions/ locations of a specific unit, given collected information?
<div class="alert alert-warning">
<b>More ideas:</b>
<ul>
<li>General methods to create simple representations in 1-D, 2-D?
<li>Automatic probability plots (note: simple in 1-D, but also for slices in 2-D?) => Compare visualisations in previous notebooks!
</ul>
</div>
Analysis of multivariate condtional entropy
Later also:
"opposite" question, i.e.: if we would like to resolve uncertainty in a specific region: where to look best?
"complete" uncertainty (i.e.: joint entropy!)
greedy search for best spots for uncertainty reduction, simple (cell-wise), complex (related to potential drilling positions)
further ideas for "greedy search" to reduce uncertainties in a specific "search region" (i.e.: expected location of a deposit, etc.):
start with cell with highest (multivariate) mutual information
rank cells with highest I due to their own mutual information with other cells, which are not part of a defined "search region"
for simple, cell-wise: describe similarity to mapping! Maybe even a field example with data from Belgium? But this is still one or two MSc theses away...)
For the joint entropy analysis, we now use the new lexicographic (correct term?) sorting algorithm, implemented in the module hspace:
End of explanation
h_max = np.max(h)
plt.imshow(h_cond_drill.transpose(), origin = 'lower left',
cmap = 'viridis', interpolation = 'none', vmax=h_max)
plt.colorbar(orientation = 'horizontal')
# half-step contour lines
contour_levels = np.log2(np.arange(1., n_max + 0.001, .5))
plt.contour(h_cond_drill.transpose(), contour_levels, colors = 'gray')
# superpose 1-step contour lines
contour_levels = np.log2(np.arange(1., n_max + 0.001, 1.))
plt.contour(h_cond_drill.transpose(), contour_levels, colors = 'white')
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
Explanation: Try own "entropy colormap":
End of explanation
plt.imshow(h.transpose(), origin = 'lower left',
cmap = 'viridis', interpolation = 'none', vmax=h_max)
plt.colorbar(orientation = 'horizontal')
# half-step contour lines
contour_levels = np.log2(np.arange(1., n_max + 0.001, .5))
plt.contour(h.transpose(), contour_levels, colors = 'gray')
# superpose 1-step contour lines
contour_levels = np.log2(np.arange(1., n_max + 0.001, 1.))
plt.contour(h.transpose(), contour_levels, colors = 'white')
Explanation: For comparison again: the entropy of the initial model:
End of explanation
plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left',
cmap = 'viridis', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
Explanation: And the difference, for clarity:
End of explanation
# define position of "drill":
nx = 10
xvals = np.ones(nx, dtype=int) * 20
yvals = np.arange(39,39-nx, -1, dtype=int)
pos = np.vstack([xvals, yvals]).T
# determine joint entropy of drill_locs:
h_joint_drill = hspace.measures.joint_entropy(model_sections, pos)
Explanation: Clearly, the highset reduction is in the area around the borehole, but interestingly, the uncertianty in other areas is also reduced! Note specifically the reduction of uncertainties in the two neighbouring fold hinges.
Let's check some other positions (and drilling "depths"):
End of explanation
%%timeit
pos_all = np.vstack([pos, np.array([50,20])])
h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all)
# esimated total time:
ttime = 100 * 40 * 0.000271
print("Estimated total time: %.3f seconds or %.3f minutes" % (ttime, ttime/60.))
# generate conditional entropies for entire section:
h_cond_drill = np.zeros_like(h)
for i in range(100):
for j in range(40):
# add position to locations
pos_all = np.vstack([pos, np.array([i,j])])
h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all)
# subtract joint entropy of drill locs to obtain conditional entropy
h_cond_drill[i,j] = h_joint_loc - h_joint_drill
plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left',
cmap = 'RdBu', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
Explanation: We also just include one timing step to estimate the approximate simualtion time:
End of explanation
# define position of "drill":
nx = 30
xvals = np.ones(nx, dtype=int) * 20
yvals = np.arange(39,39-nx, -1, dtype=int)
pos = np.vstack([xvals, yvals]).T
# determine joint entropy of drill_locs:
h_joint_drill = hspace.measures.joint_entropy(model_sections, pos)
# generate conditional entropies for entire section:
h_cond_drill = np.zeros_like(h)
for i in range(100):
for j in range(40):
# add position to locations
pos_all = np.vstack([pos, np.array([i,j])])
h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all)
# subtract joint entropy of drill locs to obtain conditional entropy
h_cond_drill[i,j] = h_joint_loc - h_joint_drill
plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left',
cmap = 'RdBu', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
plt.imshow(h.transpose(), origin = 'lower left',
cmap = 'gray', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left',
cmap = 'RdBu', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
Explanation: Intersting! Only a local reduction around the drilling position, however: extending to the deeper layers, as well! Why?
Drill deeper:
End of explanation
# define position of "drill":
nx = 30
xvals = np.ones(nx, dtype=int) * 60
yvals = np.arange(39,39-nx, -1, dtype=int)
pos = np.vstack([xvals, yvals]).T
# determine joint entropy of drill_locs:
h_joint_drill = hspace.measures.joint_entropy(model_sections, pos)
# generate conditional entropies for entire section:
h_cond_drill = np.zeros_like(h)
for i in range(100):
for j in range(40):
# add position to locations
pos_all = np.vstack([pos, np.array([i,j])])
h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all)
# subtract joint entropy of drill locs to obtain conditional entropy
h_cond_drill[i,j] = h_joint_loc - h_joint_drill
plt.imshow(h_cond_drill.transpose(), origin = 'lower left',
cmap = 'gray', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left',
cmap = 'RdBu', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
Explanation: Check deep "drilling" at pos 60
End of explanation
# define position of "drill":
nx = 30
xvals = np.hstack([np.ones(nx, dtype=int) * 60, np.ones(nx, dtype=int) * 30])
yvals = np.hstack([np.arange(39,39-nx, -1, dtype=int), np.arange(39,39-nx, -1, dtype=int)])
pos = np.vstack([xvals, yvals]).T
# determine joint entropy of drill_locs:
h_joint_drill = hspace.measures.joint_entropy(model_sections, pos)
%%timeit
h_joint_loc = hspace.measures.joint_entropy(model_sections, pos)
# esimated total time:
ttime = 100 * 40 * 0.0002
print("Estimated total time: %.3f seconds or %.3f minutes" % (ttime, ttime/60.))
# generate conditional entropies for entire section:
h_cond_drill = np.zeros_like(h)
for i in range(100):
for j in range(40):
# add position to locations
pos_all = np.vstack([pos, np.array([i,j])])
h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all)
# subtract joint entropy of drill locs to obtain conditional entropy
h_cond_drill[i,j] = h_joint_loc - h_joint_drill
plt.imshow(h_cond_drill.transpose(), origin = 'lower left',
cmap = 'gray', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left',
cmap = 'RdBu', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
Explanation: Interesting! And now both combined:
End of explanation
# define position of "drill":
nx = 30
xvals = np.hstack([np.ones(nx, dtype=int) * 60,
np.ones(nx, dtype=int) * 30,
np.ones(nx, dtype=int) * 5])
yvals = np.hstack([np.arange(39,39-nx, -1, dtype=int),
np.arange(39,39-nx, -1, dtype=int),
np.arange(39,39-nx, -1, dtype=int)])
pos = np.vstack([xvals, yvals]).T
# determine joint entropy of drill_locs:
h_joint_drill = hspace.measures.joint_entropy(model_sections, pos)
# generate conditional entropies for entire section:
h_cond_drill = np.zeros_like(h)
for i in range(100):
for j in range(40):
# add position to locations
pos_all = np.vstack([pos, np.array([i,j])])
h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all)
# subtract joint entropy of drill locs to obtain conditional entropy
h_cond_drill[i,j] = h_joint_loc - h_joint_drill
plt.imshow(h_cond_drill.transpose(), origin = 'lower left',
cmap = 'gray', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left',
cmap = 'RdBu', interpolation = 'none')
plt.colorbar(orientation = 'horizontal')
# plot drilling positions above it:
plt.plot(pos[:,0], pos[:,1], 'ws')
plt.xlim([0,99])
plt.ylim([0,39])
Explanation: We can see that now only a part on the left remains with significant uncertainties. So, let's "drill" into this, as well:
End of explanation |
8,593 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Booleans
Step1: Python truth value testing
Any object can be tested for truth value
Truth value testing is used in flow control or in Boolean operations
All objects are evaluated as True except
Step2: Python boolean operands
Step3: Flow Control
Let's start with the conditional execution
Step4: REMEMBER
Step5: Let's see the ternary operator
Step6: Time for the while loop
Step7: What about the for loop?
Step8: Let's see how to interact with loops iterations
Step9: break statement halts a loop execution (inside while or for)
Only affects the closer inner (or smallest enclosing) loop
Step10: continue statement halts current iteration (inside while or for)
loops continue its normal execution
Step11: else clause after a loop is executed if all iterations were run without break statement called
Step12: pass statement is Python's noop (does nothing)
Let's check exception handling
Step13: Let's see another construction
Step14: Not pythonic, too much code for only three real lines
Step15: Where is the file closed? What happens if an exception is raised?
Python context managers
Encapsulate common patterns used wrapping code blocks where real runs the program logic
Usually try/except/finally patterns
Several uses
Step16: Short code, right?
Step17: What about now?
Step18: List comprehension is faster than standard loops (low level C optimizations)
However, built-in functions are still faster (see Functional and iterables tools module)
There is also dict comprehension (2.7 or higher) | Python Code:
# Let's declare some bools
spam = True
print spam
print type(spam)
eggs = False
print eggs
print type(eggs)
Explanation: Booleans
End of explanation
# Let's try boolean operations
print True or True
print True or False
print False or True # Boolean or. Short-circuited, so it only evaluates the second argument if the first one is False
print True and True
print True and False
print False and True # Boolean or. Short-circuited, so it only evaluates the second argument if the first one is True
print not True
print not False
# So, if all objects can be tested for truth, let's try something different
spam = [1.2345, 7, "x"]
eggs = ("a", 0x07, True)
fooo = "aeiou"
print spam or eggs
# Did you expect it to print True?
print fooo or []
print "" or eggs
print spam and eggs
print fooo and ()
print [] and eggs
print not spam
print not ""
print spam and eggs or "abcd" and False
print (spam and eggs) or ("abcd" and False)
print spam and (eggs or "abcd") and False
print spam and (eggs or "abcd" and False)
Explanation: Python truth value testing
Any object can be tested for truth value
Truth value testing is used in flow control or in Boolean operations
All objects are evaluated as True except:
None (aka. null)
False
Zero of any numeric type: 0, 0L, 0.0, 0j, 0x0, 00
Any empty sequence or mapping: '', [], (), {}
Instances of user-defined classes implementing nonzero or len method
and returning 0 or False
End of explanation
spam = 2
eggs = 2.5
print spam == 2 # equal
print spam != eggs # not equal
print spam >= eggs # greater than or equal
print spam > eggs # strictly greater than
print spam <= eggs # less than or equal
print spam < eggs # strictly less than
print spam is 2 # object identity, useful to compare with None (discussed latter)
print spam is not None # negated object identity
Explanation: Python boolean operands:
ALWAYS return one of the incoming arguments!
x or y => if x is false, then y, else x
x and y => if x is false, then x, else y
not x => if x is false, then True, else False
They are short-circuited, so second argument is not always evaluated
Can take any object type as arguments
Even function calls, so boolean operands are used for flow control
Parentheses may be used to change order of boolean operands or comparissons
What about comparisons?
End of explanation
spam = [1, 2, 3] # True
eggs = "" # False
if spam:
print "spam is True"
else:
print "spam is False"
print "outside the conditional" # Notice that theres is no closing fi statement
if spam:
print "spam is True"
else:
print "spam is False"
print "still inside the conditional"
Explanation: Flow Control
Let's start with the conditional execution
End of explanation
if eggs:
print "eggs is True"
elif spam:
print "eggs is False and spam is True"
else:
print "eggs and spam are False"
if eggs:
print "eggs is True"
elif max(spam) > 5:
print "eggs is False and second condition is True"
elif len(spam) == 3 and not eggs is None:
print "third condition is true"
else:
print "everything is False"
Explanation: REMEMBER:
Indentation is Python's way of grouping statements!!
Typically four spaces per indentation level
No curly brackets { } or semicolons ; used anywhere
This enforces a more readable code
End of explanation
spam = [1, 2, 3] # True
eggs = "" # False
print "first option" if spam else "second option"
print "first option" if eggs else "second option"
print "first option" if eggs else "second option" if spam else "last option" # We can even concatenate them
print "first option" if eggs else ("second option" if spam else "last option")
Explanation: Let's see the ternary operator
End of explanation
spam = [1, 2, 3]
while len(spam) > 0:
print spam.pop(0)
spam = [1, 2, 3]
idx = 0
while idx < len(spam):
print spam[idx]
idx += 1
Explanation: Time for the while loop
End of explanation
spam = [1, 2, 3]
for item in spam: # The for loop only iterates over the items of a sequence
print item
spam = [1, 2, 3]
for item in spam[::-1]: # As we saw, slicing may be slow. Keep it in mind
print item
eggs = "eggs"
for letter in eggs: # It can loop over characters of a string
print letter
spam = {"one": 1,
"two": 2,
"three": 3}
for key in spam: # Or even it can interate through a dictionary
print spam[key] # Note that it iterates over the keys of the dictionary
Explanation: What about the for loop?
End of explanation
spam = [1, 2, 3]
for item in spam:
if item == 2:
break
print item
Explanation: Let's see how to interact with loops iterations
End of explanation
# A bit more complicated example
spam = ["one", "two", "three"]
for item in spam: # This loop is never broken
for letter in item:
if letter in "wh": # Check if letter is either 'w' or 'h'
break # Break only the immediate inner loop
print letter
print # It prints a break line (empty line)
# A bit different example
spam = ["one", "two", "three"]
for item in spam:
for letter in item:
if letter in "whe": # Check if letter is either 'w', 'h' or 'e'
continue # Halt only current iteration, but continue the loop
print letter
print
Explanation: break statement halts a loop execution (inside while or for)
Only affects the closer inner (or smallest enclosing) loop
End of explanation
spam = [1, 2, 3, 4, 5, 6, 7, 8]
eggs = 5
while len(spam) > 0:
value = spam.pop()
if value == eggs:
print "Value found:", value
break
else: # Note that else has the same indentation than while
print "The right value was not found"
spam = [1, 2, 3, 4, 6, 7, 8]
eggs = 5
while len(spam) > 0:
value = spam.pop()
if value == eggs:
print "Value found:", value
break
else:
print "The right value was not found"
Explanation: continue statement halts current iteration (inside while or for)
loops continue its normal execution
End of explanation
spam = [1, 2, 3]
for item in spam:
pass
Explanation: else clause after a loop is executed if all iterations were run without break statement called
End of explanation
spam = [1, 2, 3]
try:
print spam[5]
except: # Use try and except to capture exceptions
print "Failed"
spam = {"one": 1, "two": 2, "three": 3}
try:
print spam[5]
except IndexError as e: # Inside the except clause 'e' will contain the exception instance
print "IndexError", e
except KeyError as e: # Use several except clauses for different types of exceptions
print "KeyError", e
try:
print 65 + "spam"
except (IndexError, KeyError) as e: # Or even group exception types
print "Index or Key Error", e
except TypeError as e:
print "TypeError", e
try:
print 65 + 2
except (IndexError, KeyError), e:
print "Index or Key Error", e
except TypeError, e:
print "TypeError", e
else:
print "No exception" # Use else clause to run code in case no exception was raised
try:
print 65 + "spam"
raise AttributeError # Use 'raise' to launch yourself exceptions
except (IndexError, KeyError), e:
print "Index or Key Error", e
except TypeError, e:
print "TypeError", e
else:
print "No exception"
finally:
print "Finally we clean up" # Use finally clause to ALWAYS execute clean up code
try:
print 65 + 2
except (IndexError, KeyError), e:
print "Index or Key Error", e
raise # Use 'raise' without arguments to relaunch the exception
except TypeError, e:
print "TypeError", e
else:
print "No exception"
finally:
print "Finally we clean up" # Use finally clause to ALWAYS execute clean up code
Explanation: pass statement is Python's noop (does nothing)
Let's check exception handling
End of explanation
try:
f = open("tmp_file.txt", "a")
except:
print "Exception opening file"
else:
try:
f.write("I'm writing to a file...\n")
except:
print "Can not write to a file"
finally:
f.close()
Explanation: Let's see another construction
End of explanation
try:
with open("tmp_file.txt", "a") as f:
f.write("I'm writing to a file...\n")
except:
print "Can not open file for writing"
Explanation: Not pythonic, too much code for only three real lines
End of explanation
spam = [0, 1, 2, 3, 4]
eggs = [0, 10, 20, 30]
fooo = []
for s in spam:
for e in eggs:
if s > 1 and e > 1:
fooo.append(s * e)
print fooo
Explanation: Where is the file closed? What happens if an exception is raised?
Python context managers
Encapsulate common patterns used wrapping code blocks where real runs the program logic
Usually try/except/finally patterns
Several uses:
Automatic cleanup, closing files or network or DB connections when exiting the context block
Set temporary environment, like enable/disable logging, timing, profiling...
Use the 'with' and optionally the 'as' statements to open a context manager
It is automatically closed when code execution goes outside the block
Comprehension
End of explanation
spam = [0, 1, 2, 3, 4]
eggs = [0, 10, 20, 30]
fooo = [s * e for s in spam for e in eggs if s > 1 and e > 1]
print fooo
Explanation: Short code, right?
End of explanation
fooo = [s * s for s in spam] # This is the most basic list comprehension construction
print fooo
fooo = [s * s for s in spam if s > 1] # We can add 'if' clauses
print fooo
spam = [1, 2, 3, 4]
eggs = [0, -1, -2, -3]
fooo = [l.upper() * (s + e) for s in spam
for e in eggs
for l in "SpaM aNd eGgs aNd stuFf"
if (s + e) >= 1
if l.islower()
if ord(l) % 2 == 0] # We can add lots of 'for' and 'if' clauses
print fooo
spam = [1, 2, 3, 4]
eggs = [10, 20, 30, 40]
fooo = [[s * e for s in spam] for e in eggs] # It is possible to nest list comprehensions
print fooo
Explanation: What about now?
End of explanation
spam = ['monday', 'tuesday',
'wednesday', 'thursday',
'friday']
fooo = {s: len(s) for s in spam} # The syntax is a merge of list comprehension and dicts
print fooo
spam = [(0, 'monday'), (1, 'tuesday'),
(2, 'wednesday'), (3, 'thursday'),
(4, 'friday')]
fooo = {s: idx for idx, s in spam} # Tuple unpacking is useful here
print fooo
spam = ['monday', 'tuesday',
'wednesday', 'thursday',
'friday']
fooo = {s: len(s) for s in spam if s[0] in "tm"} # Ofc, you can add more 'for' and 'if' clauses
print fooo
Explanation: List comprehension is faster than standard loops (low level C optimizations)
However, built-in functions are still faster (see Functional and iterables tools module)
There is also dict comprehension (2.7 or higher)
End of explanation |
8,594 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solving a Laplace problem with Dirichlet boundary conditions
Background
Laplace problem inside the unit sphere with Dirichlet boundary conditions. Let $\Omega$ be the unit sphere with boundary $\Gamma$. Let $\nu$ be the outward pointing normal on $\Gamma$. The PDE and boundary conditions are given by
\begin{align}
\Delta u &= 0&&\text{in }\Omega,\
u &= f&&\text{on }\Gamma.
\end{align}
The boundary data is a source $\hat{u}$ located at the point $(0.9,0,0)$.
$$
\hat{u}(\mathbf x)=\frac{1}{4\pi\sqrt{(x-0.9)^2+y^2+z^2}}.
$$
For this example, we will use a direct integral equation of the first kind. Let
$$
g(\mathbf x,\mathbf y) = \frac{1}{4\pi |\mathbf x-\mathbf y|}
$$
be the Green's function for Laplace in three dimensions. From Green's representation theorem, it follows that every harmonic function $u$ in $\Omega$ satisfies
$$
u(\mathbf x) = \int_{\Gamma} g(\mathbf x,\mathbf y)\frac{\partial u(\mathbf y)}{\partial \nu(\mathbf{y})}\mathrm{d}\mathbf y-\int_{\Gamma}\frac{\partial g(\mathbf x,\mathbf y)}{\partial \nu(\mathbf{y})}u(\mathbf y)\mathrm{d}\mathbf y,~\mathbf x\in\Omega\setminus\Gamma
$$
or equivalantly
$$
u(\mathbf x) = \left[\mathcal{V}\frac{\partial u(\mathbf y)}{\partial \nu(\mathbf{y})}\right] (\mathbf{x}) - \left[\mathcal{K}u\right] (\mathbf{x}),~\mathbf x\in\Omega\setminus\Gamma,
$$
where $\mathcal{V}$ and $\mathcal{K}$ are the <a href='https
Step1: We next define a mesh or grid. For this problem, we will use the built-in function sphere that defines a simple spherical grid. Details of other available grids can be found in the <a href='https
Step2: We now define the <a href='https
Step3: We can now define the <a href='https
Step4: We now define the <a href='https
Step5: We next assemble the right-hand side of the boundary integral equation, given by
$$
(\tfrac12\mathsf{Id}+\mathsf{K})u.
$$
We use implemented operators algebra to define right-hand side.
Step6: We now <a href='https
Step7: We now want to provide a simple plot of the solution in the $(x,y)$ plane for $z=0$. We first define points at which to plot the solution.
Step8: The variable points now contains in its columns the coordinates of the evaluation points. We can now use Green's representation theorem to evaluate the solution on these points. Note in particular the last line of the following code. It is a direct implementation of Green's representation theorem.
Step9: We now plot the 2D slice of the solution. For a full three dimensional visualization, Bempp can <a href='https | Python Code:
import bempp.api
import numpy as np
Explanation: Solving a Laplace problem with Dirichlet boundary conditions
Background
Laplace problem inside the unit sphere with Dirichlet boundary conditions. Let $\Omega$ be the unit sphere with boundary $\Gamma$. Let $\nu$ be the outward pointing normal on $\Gamma$. The PDE and boundary conditions are given by
\begin{align}
\Delta u &= 0&&\text{in }\Omega,\
u &= f&&\text{on }\Gamma.
\end{align}
The boundary data is a source $\hat{u}$ located at the point $(0.9,0,0)$.
$$
\hat{u}(\mathbf x)=\frac{1}{4\pi\sqrt{(x-0.9)^2+y^2+z^2}}.
$$
For this example, we will use a direct integral equation of the first kind. Let
$$
g(\mathbf x,\mathbf y) = \frac{1}{4\pi |\mathbf x-\mathbf y|}
$$
be the Green's function for Laplace in three dimensions. From Green's representation theorem, it follows that every harmonic function $u$ in $\Omega$ satisfies
$$
u(\mathbf x) = \int_{\Gamma} g(\mathbf x,\mathbf y)\frac{\partial u(\mathbf y)}{\partial \nu(\mathbf{y})}\mathrm{d}\mathbf y-\int_{\Gamma}\frac{\partial g(\mathbf x,\mathbf y)}{\partial \nu(\mathbf{y})}u(\mathbf y)\mathrm{d}\mathbf y,~\mathbf x\in\Omega\setminus\Gamma
$$
or equivalantly
$$
u(\mathbf x) = \left[\mathcal{V}\frac{\partial u(\mathbf y)}{\partial \nu(\mathbf{y})}\right] (\mathbf{x}) - \left[\mathcal{K}u\right] (\mathbf{x}),~\mathbf x\in\Omega\setminus\Gamma,
$$
where $\mathcal{V}$ and $\mathcal{K}$ are the <a href='https://bempp.com/2017/07/11/available_operators/'>single and double layer potential operators</a>.
Taking the limit $\mathbf x\rightarrow \Gamma$ we obtain the boundary integral equation
$$
\left[\mathsf{V}\frac{\partial u}{\partial n}\right] (\mathbf x)=\left[(\tfrac12\mathsf{Id}+\mathsf{K})u\right] (\mathbf x),~\mathbf x\in\Gamma.
$$
Here, $\mathsf{V}$ and $\mathsf{K}$ are the <a href='https://bempp.com/2017/07/11/available_operators/'>single and double layer boundary operators</a>.
This equation is the target equation that we will solve with respect to unknown norrmal derivative on the boundary $\frac{\partial u}{\partial n}$.
When we get normal derivative on the boundary
$$
\frac{\partial u}{\partial n}
$$
we can use Green representation theorem to compute $u(x)$ in any points inside the domain $\Omega$.
Implementation
We now demonstrate how to solve this problem with Bempp. We begin by importing Bempp and NumPy.
End of explanation
grid = bempp.api.shapes.sphere(h=0.1)
Explanation: We next define a mesh or grid. For this problem, we will use the built-in function sphere that defines a simple spherical grid. Details of other available grids can be found in the <a href='https://bempp.com/2017/07/06/grids-in-bempp'>grids tutorial</a>.
End of explanation
dp0_space = bempp.api.function_space(grid, "DP", 0)
p1_space = bempp.api.function_space(grid, "P", 1)
Explanation: We now define the <a href='https://bempp.com/2017/07/11/function-spaces/'>spaces</a>.
We will use two spaces:
- the space of continuous, piecewise linear functions
- the space of piecewise constant functions.
The space of piecewise constant functions has the right smoothness for the unknown Neumann data.
We will use continuous, piecewise linear functions to represent the known Dirichlet data.
End of explanation
identity = bempp.api.operators.boundary.sparse.identity(
p1_space, p1_space, dp0_space)
dlp = bempp.api.operators.boundary.laplace.double_layer(
p1_space, p1_space, dp0_space)
slp = bempp.api.operators.boundary.laplace.single_layer(
dp0_space, p1_space, dp0_space)
Explanation: We can now define the <a href='https://bempp.com/2017/07/11/operators/'>operators</a>. We need the identity, single layer, and double layer boundary operator.
End of explanation
def dirichlet_data(x, n, domain_index, result):
result[0] = 1./(4 * np.pi * ((x[0] - .9)**2 + x[1]**2 + x[2]**2)**(0.5))
dirichlet_fun = bempp.api.GridFunction(p1_space, fun=dirichlet_data)
Explanation: We now define the <a href='https://bempp.com/2017/07/11/grid-functions/'>GridFunction object</a> on the sphere grid that represents the Dirichlet data.
End of explanation
rhs = (.5 * identity + dlp) * dirichlet_fun
Explanation: We next assemble the right-hand side of the boundary integral equation, given by
$$
(\tfrac12\mathsf{Id}+\mathsf{K})u.
$$
We use implemented operators algebra to define right-hand side.
End of explanation
neumann_fun, info = bempp.api.linalg.cg(slp, rhs, tol=1E-3)
Explanation: We now <a href='https://bempp.com/2017/07/12/solving-linear-systems/'>solve the linear system</a> using a conjugate gradient (CG) method.
End of explanation
n_grid_points = 150
plot_grid = np.mgrid[-1:1:n_grid_points*1j, -1:1:n_grid_points*1j]
points = np.vstack((plot_grid[0].ravel(),
plot_grid[1].ravel(),
np.zeros(plot_grid[0].size)))
Explanation: We now want to provide a simple plot of the solution in the $(x,y)$ plane for $z=0$. We first define points at which to plot the solution.
End of explanation
slp_pot = bempp.api.operators.potential.laplace.single_layer(
dp0_space, points)
dlp_pot = bempp.api.operators.potential.laplace.double_layer(
p1_space, points)
u_evaluated = slp_pot * neumann_fun - dlp_pot * dirichlet_fun
Explanation: The variable points now contains in its columns the coordinates of the evaluation points. We can now use Green's representation theorem to evaluate the solution on these points. Note in particular the last line of the following code. It is a direct implementation of Green's representation theorem.
End of explanation
%matplotlib inline
import matplotlib
matplotlib.rcParams['figure.figsize'] = (5.0, 4.0)
from matplotlib import pylab as plt
# Filter out solution values that are associated with points outside the unit circle.
u_evaluated = u_evaluated.reshape((n_grid_points, n_grid_points))
radius = np.sqrt(plot_grid[0]**2 + plot_grid[1]**2)
u_evaluated[radius>1] = np.nan
plt.imshow(np.log(np.abs(u_evaluated.T)), extent=(-1,1,-1,1))
plt.title('Computed solution')
plt.colorbar()
Explanation: We now plot the 2D slice of the solution. For a full three dimensional visualization, Bempp can <a href='https://bempp.com/2017/07/12/import-and-export-of-gmsh-files/'>export the data to Gmsh</a>. Since the solution decays quickly, we use a logarithmic plot.
End of explanation |
8,595 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 3
Step1: And the script to compute those files can be found here
Step2: Now let's start with the ANTs normalization workflow!
Imports
First, we need to import all modules we later want to use.
Step3: Experiment parameters
It's always a good idea to specify all parameters that might change between experiments at the beginning of your script.
Step4: Specify Nodes
Initiate all the different interfaces (represented as nodes) that you want to use in your workflow.
Step5: Specify input & output stream
Specify where the input data can be found & where and how to save the output data.
Step6: Specify Workflow
Create a workflow and connect the interface nodes and the I/O stream to each other.
Step7: Visualize the workflow
It always helps to visualize your workflow.
Step8: Run the Workflow
Now that everything is ready, we can run the ANTs normalization workflow. Change n_procs to the number of jobs/cores you want to use.
Step9: Normalization with SPM12
The normalization with SPM12 is rather straight forward. The only thing we need to do is run the Normalize12 module. So let's start!
Imports
First, we need to import all modules we later want to use.
Step10: Experiment parameters
It's always a good idea to specify all parameters that might change between experiments at the beginning of your script.
Step11: Specify Nodes
Initiate all the different interfaces (represented as nodes) that you want to use in your workflow.
Step12: Specify input & output stream
Specify where the input data can be found & where and how to save the output data.
Step13: Specify Workflow
Create a workflow and connect the interface nodes and the I/O stream to each other.
Step14: Visualize the workflow
It always helps to visualize your workflow.
Step15: Run the Workflow
Now that everything is ready, we can run the SPM normalization workflow. Change n_procs to the number of jobs/cores you want to use.
Step16: Comparison between ANTs and SPM normalization
Now that we ran the normalization with ANTs and SPM, let us compare their output.
Step17: First, let's compare the normalization of the anatomical images
Step18: And what about the contrast images? | Python Code:
!tree /data/antsdir/sub-0*/
Explanation: Example 3: Normalize data to MNI template
This example covers the normalization of data. Some people prefer to normalize the data during the preprocessing, just before smoothing. I prefer to do the 1st-level analysis completely in subject space and only normalize the contrasts for the 2nd-level analysis.
For the current example, we will take the computed 1st-level contrasts from the previous experiment (again once done with fwhm=4mm and fwhm=8mm) and normalize them into MNI-space. To show two different approaches, we will do the normalization once with SPM and once with ANTs.
Normalization with ANTs
The normalization with ANTs requires that you first compute the transformation matrix that would bring the anatomical images of each subject into template space. Depending on your system this might take a few hours per subject. To facilitate this step, I've already computed the transformation matrix.
The data for it can be found under:
End of explanation
%load /data/antsdir/script_ANTS_registration.py
Explanation: And the script to compute those files can be found here:
End of explanation
from os.path import join as opj
from nipype.interfaces.ants import ApplyTransforms
from nipype.interfaces.utility import IdentityInterface
from nipype.interfaces.io import SelectFiles, DataSink
from nipype.pipeline.engine import Workflow, Node, MapNode
from nipype.interfaces.fsl import Info
Explanation: Now let's start with the ANTs normalization workflow!
Imports
First, we need to import all modules we later want to use.
End of explanation
experiment_dir = '/output'
output_dir = 'datasink'
working_dir = 'workingdir'
# list of subject identifiers
subject_list = ['sub-01', 'sub-02', 'sub-03', 'sub-04', 'sub-05']
# list of session identifiers
session_list = ['run-1', 'run-2']
# Smoothing widths used during preprocessing
fwhm = [4, 8]
# Template to normalize to
template = Info.standard_image('MNI152_T1_2mm.nii.gz')
Explanation: Experiment parameters
It's always a good idea to specify all parameters that might change between experiments at the beginning of your script.
End of explanation
# Apply Transformation - applies the normalization matrix to contrast images
apply2con = MapNode(ApplyTransforms(args='--float',
input_image_type=3,
interpolation='Linear',
invert_transform_flags=[False],
num_threads=1,
reference_image=template,
terminal_output='file'),
name='apply2con', iterfield=['input_image'])
Explanation: Specify Nodes
Initiate all the different interfaces (represented as nodes) that you want to use in your workflow.
End of explanation
# Infosource - a function free node to iterate over the list of subject names
infosource = Node(IdentityInterface(fields=['subject_id', 'fwhm_id']),
name="infosource")
infosource.iterables = [('subject_id', subject_list),
('fwhm_id', fwhm)]
# SelectFiles - to grab the data (alternativ to DataGrabber)
templates = {'con': opj(output_dir, '1stLevel',
'{subject_id}_fwhm{fwhm_id}', '???_00??.nii'),
'transform': opj('../data', 'antsdir', '{subject_id}',
'transformComposite.h5')}
selectfiles = Node(SelectFiles(templates,
base_directory=experiment_dir,
sort_filelist=True),
name="selectfiles")
# Datasink - creates output folder for important outputs
datasink = Node(DataSink(base_directory=experiment_dir,
container=output_dir),
name="datasink")
# Use the following DataSink output substitutions
substitutions = [('_subject_id_', '')]
subjFolders = [('_fwhm_id_%s%s' % (f, sub), '%s_fwhm%s' % (sub, f))
for f in fwhm
for sub in subject_list]
subjFolders += [('_apply2con%s/' % (i), '') for i in range(7)]
substitutions.extend(subjFolders)
datasink.inputs.substitutions = substitutions
Explanation: Specify input & output stream
Specify where the input data can be found & where and how to save the output data.
End of explanation
# Initiation of the ANTs normalization workflow
antsflow = Workflow(name='antsflow')
antsflow.base_dir = opj(experiment_dir, working_dir)
# Connect up the ANTs normalization components
antsflow.connect([(infosource, selectfiles, [('subject_id', 'subject_id'),
('fwhm_id', 'fwhm_id')]),
(selectfiles, apply2con, [('con', 'input_image'),
('transform', 'transforms')]),
(apply2con, datasink, [('output_image', 'norm_ants.@con')]),
])
Explanation: Specify Workflow
Create a workflow and connect the interface nodes and the I/O stream to each other.
End of explanation
# Create ANTs normalization graph
antsflow.write_graph(graph2use='colored', format='png', simple_form=True)
# Visualize the graph
from IPython.display import Image
Image(filename=opj(antsflow.base_dir, 'antsflow', 'graph.dot.png'))
Explanation: Visualize the workflow
It always helps to visualize your workflow.
End of explanation
antsflow.run('MultiProc', plugin_args={'n_procs': 4})
Explanation: Run the Workflow
Now that everything is ready, we can run the ANTs normalization workflow. Change n_procs to the number of jobs/cores you want to use.
End of explanation
from os.path import join as opj
from nipype.interfaces.spm import Normalize12
from nipype.interfaces.utility import IdentityInterface
from nipype.interfaces.io import SelectFiles, DataSink
from nipype.algorithms.misc import Gunzip
from nipype.pipeline.engine import Workflow, Node
Explanation: Normalization with SPM12
The normalization with SPM12 is rather straight forward. The only thing we need to do is run the Normalize12 module. So let's start!
Imports
First, we need to import all modules we later want to use.
End of explanation
experiment_dir = '/output'
output_dir = 'datasink'
working_dir = 'workingdir'
# list of subject identifiers
subject_list = ['sub-01', 'sub-02', 'sub-03', 'sub-04', 'sub-05']
# list of session identifiers
session_list = ['run-1', 'run-2']
# Smoothing withds used during preprocessing
fwhm = [4, 8]
# Template to normalize to
template = '/opt/spm12/spm12_mcr/spm12/tpm/TPM.nii'
Explanation: Experiment parameters
It's always a good idea to specify all parameters that might change between experiments at the beginning of your script.
End of explanation
# Gunzip - unzip the contrast image
gunzip = Node(Gunzip(), name="gunzip")
# Normalize - normalizes functional and structural images to the MNI template
normalize = Node(Normalize12(jobtype='estwrite',
tpm=template,
write_voxel_sizes=[2, 2, 2]),
name="normalize")
Explanation: Specify Nodes
Initiate all the different interfaces (represented as nodes) that you want to use in your workflow.
End of explanation
# Infosource - a function free node to iterate over the list of subject names
infosource = Node(IdentityInterface(fields=['subject_id', 'fwhm_id']),
name="infosource")
infosource.iterables = [('subject_id', subject_list),
('fwhm_id', fwhm)]
# SelectFiles - to grab the data (alternativ to DataGrabber)
templates = {'con': opj(output_dir, '1stLevel',
'{subject_id}_fwhm{fwhm_id}', '???_00??.nii'),
'anat': opj('../data', 'ds102', '{subject_id}', 'anat',
'{subject_id}_T1w.nii.gz')}
selectfiles = Node(SelectFiles(templates,
base_directory=experiment_dir,
sort_filelist=True),
name="selectfiles")
# Datasink - creates output folder for important outputs
datasink = Node(DataSink(base_directory=experiment_dir,
container=output_dir),
name="datasink")
# Use the following DataSink output substitutions
substitutions = [('_subject_id_', '')]
subjFolders = [('_fwhm_id_%s%s' % (f, sub), '%s_fwhm%s' % (sub, f))
for f in fwhm
for sub in subject_list]
substitutions.extend(subjFolders)
datasink.inputs.substitutions = substitutions
Explanation: Specify input & output stream
Specify where the input data can be found & where and how to save the output data.
End of explanation
# Specify Normalization-Workflow & Connect Nodes
spmflow = Workflow(name='spmflow')
spmflow.base_dir = opj(experiment_dir, working_dir)
# Connect up SPM normalization components
spmflow.connect([(infosource, selectfiles, [('subject_id', 'subject_id'),
('fwhm_id', 'fwhm_id')]),
(selectfiles, normalize, [('con', 'apply_to_files')]),
(selectfiles, gunzip, [('anat', 'in_file')]),
(gunzip, normalize, [('out_file', 'image_to_align')]),
(normalize, datasink, [('normalized_files', 'norm_spm.@files'),
('normalized_image', 'norm_spm.@image'),
]),
])
Explanation: Specify Workflow
Create a workflow and connect the interface nodes and the I/O stream to each other.
End of explanation
# Create SPM normalization graph
spmflow.write_graph(graph2use='colored', format='png', simple_form=True)
# Visualize the graph
from IPython.display import Image
Image(filename=opj(spmflow.base_dir, 'spmflow', 'graph.dot.png'))
Explanation: Visualize the workflow
It always helps to visualize your workflow.
End of explanation
spmflow.run('MultiProc', plugin_args={'n_procs': 4})
Explanation: Run the Workflow
Now that everything is ready, we can run the SPM normalization workflow. Change n_procs to the number of jobs/cores you want to use.
End of explanation
%pylab inline
from nilearn.plotting import plot_stat_map
anatimg = '/usr/share/fsl/data/standard/MNI152_T1_2mm.nii.gz'
Explanation: Comparison between ANTs and SPM normalization
Now that we ran the normalization with ANTs and SPM, let us compare their output.
End of explanation
plot_stat_map(
'/data/antsdir/sub-01/transform_Warped.nii.gz', title='anatomy - ANTs',
bg_img=anatimg, threshold=200, display_mode='ortho', cut_coords=(-50, 0, -10))
plot_stat_map(
'/output/datasink/norm_spm/sub-01_fwhm4/wsub-01_T1w.nii', title='anatomy - SPM',
bg_img=anatimg, threshold=200, display_mode='ortho', cut_coords=(-50, 0, -10))
Explanation: First, let's compare the normalization of the anatomical images:
End of explanation
plot_stat_map(
'/output/datasink/norm_ants/sub-01_fwhm8/con_0001_trans.nii', title='contrast1 - fwhm=8 - ANTs',
bg_img=anatimg, threshold=3, display_mode='ortho', cut_coords=(-50, 0, -10))
plot_stat_map(
'/output/datasink/norm_spm/sub-01_fwhm8/wcon_0001.nii', title='contrast1 - fwhm=8 - SPM',
bg_img=anatimg, threshold=3, display_mode='ortho', cut_coords=(-50, 0, -10))
Explanation: And what about the contrast images?
End of explanation |
8,596 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
>>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) | Problem:
import numpy as np
a = np.arange(12).reshape(3, 4)
del_col = np.array([1, 2, 4, 5])
mask = (del_col <= a.shape[1])
del_col = del_col[mask] - 1
result = np.delete(a, del_col, axis=1) |
8,597 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let's see if we can get Aaron's delay network to recognize two different patterns that are multidimensional. We want patterns where you need information from both dimensions, so let's do phase-shifted sign waves.
Step1: Now let's create a network that represents a rolling window in time (Aaron's "delay network"). The process determines what sort of pattern the network will be optimized for -- here we just go with white noise of a maximum of 3Hz. theta determines how big the rolling window is -- here we use 0.5 seconds.
Step2: Now we need to create the training data for decoding out of the rolling window. Our patterns are larger than the rolling window, so to create our training data we will take our patterns, shift them, and cut them down to the right size. In order to then give that to nengo, we also need to project from the window's space to the internal representation space (using the inv_basis).
The target array is the desired output value for each of the slices of the pattern in eval_points. We'll use 1 for pattern1 and -1 for pattern2.
Step3: Now we can create a connection optimized to do this decoding
Step4: Let's try feeding in those two patterns and see what the response is
Step5: Yay it works! Still a pretty hight rmse, though. Can we improve that?
One possible problem is that the data used for the output connection is assuming that the delay network does a perfect job. What if we instead train it based on the real data coming out of the delay network? This is basically just making our eval_points a bit more realistic.
Step6: That's some improvement! What else can we do?
The pool Ensemble is pretty high-dimensional, and for some high-dimensional functions, it's useful to get a better encoder distribution. So, let's use feedback alignment to find better encoders
Step7: That looks like it should improve things! How well does it do? | Python Code:
s_pattern = 4000 # number of data points in the pattern
t = np.arange(s_pattern)*0.001 # time points for the elements in the pattern
D = 2
pattern1 = np.vstack([np.sin(t*np.pi), np.cos(t*np.pi)]).T
pattern2 = np.vstack([np.sin(t*np.pi), -np.sin(t*np.pi)]).T
plt.subplot(1, 2, 1)
plt.plot(t, pattern1)
plt.title('pattern 1')
plt.subplot(1, 2, 2)
plt.plot(t, pattern2)
plt.title('pattern 2')
plt.show()
Explanation: Let's see if we can get Aaron's delay network to recognize two different patterns that are multidimensional. We want patterns where you need information from both dimensions, so let's do phase-shifted sign waves.
End of explanation
net = nengo.Network()
with net:
process = nengo.processes.WhiteSignal(period=100., high=3., y0=0)
rw = []
for i in range(D):
rw.append(nengolib.networks.RollingWindow(theta=0.5, n_neurons=3000, process=process, neuron_type=nengo.LIFRate()))
Explanation: Now let's create a network that represents a rolling window in time (Aaron's "delay network"). The process determines what sort of pattern the network will be optimized for -- here we just go with white noise of a maximum of 3Hz. theta determines how big the rolling window is -- here we use 0.5 seconds.
End of explanation
s_window = 500
t_window = np.linspace(0, 1, s_window)
inv_basis = rw[0].inverse_basis(t_window)
eval_points = []
target = []
for i in range(s_pattern):
eval_points.append(np.dot(inv_basis, np.roll(pattern1, i)[:s_window]).T)
eval_points.append(np.dot(inv_basis, np.roll(pattern2, i)[:s_window]).T)
target.append([1])
target.append([-1])
eval_points = np.array(eval_points).reshape(len(eval_points), -1)
Explanation: Now we need to create the training data for decoding out of the rolling window. Our patterns are larger than the rolling window, so to create our training data we will take our patterns, shift them, and cut them down to the right size. In order to then give that to nengo, we also need to project from the window's space to the internal representation space (using the inv_basis).
The target array is the desired output value for each of the slices of the pattern in eval_points. We'll use 1 for pattern1 and -1 for pattern2.
End of explanation
with net:
pool = nengo.Ensemble(n_neurons=3000, dimensions=eval_points.shape[1],
neuron_type=nengo.LIFRate(), seed=1)
start = 0
for r in rw:
nengo.Connection(r.state, pool[start:start+r.state.size_out])
start += r.state.size_out
result = nengo.Node(None, size_in=1)
dec_conn = nengo.Connection(pool, result,
eval_points=eval_points, scale_eval_points=False,
function=target, synapse=0.1)
Explanation: Now we can create a connection optimized to do this decoding
End of explanation
model = nengo.Network()
model.networks.append(net)
with model:
offsets = [-np.pi/2, np.pi]
def stim_func(t):
offset = offsets[int(t/5) % len(offsets)]
return np.sin(t*np.pi), np.sin(t*np.pi+offset)
ideal_results = [1.0, -1.0]
def ideal_func(t):
return ideal_results[int(t/5) % len(ideal_results)]
ideal_result = nengo.Node(ideal_func)
stim = nengo.Node(stim_func)
for i in range(D):
nengo.Connection(stim[i], rw[i].input, synapse=None)
p_result = nengo.Probe(result)
p_stim = nengo.Probe(stim)
p_pool = nengo.Probe(pool)
p_ideal = nengo.Probe(ideal_result)
sim = nengo.Simulator(model)
sim.run(10)
plt.plot(sim.trange(), sim.data[p_stim], label='input')
plt.plot(sim.trange(), sim.data[p_result], label='output (rmse:%1.3f)' % np.sqrt(np.mean((sim.data[p_ideal]-sim.data[p_result])**2)))
plt.legend(loc='best')
Explanation: Let's try feeding in those two patterns and see what the response is
End of explanation
model = nengo.Network()
model.networks.append(net)
with model:
offsets = [-np.pi/2, np.pi]
def stim_func(t):
offset = offsets[int(t/5) % len(offsets)]
return np.sin(t*np.pi), np.sin(t*np.pi+offset)
stim = nengo.Node(stim_func)
for i in range(D):
nengo.Connection(stim[i], rw[i].input, synapse=None)
result2 = nengo.Node(None, size_in=1)
nengo.Connection(pool, result2, eval_points=sim.data[p_pool], function=sim.data[p_ideal], scale_eval_points=False)
p_result = nengo.Probe(result)
p_result2 = nengo.Probe(result2)
p_stim = nengo.Probe(stim)
sim2 = nengo.Simulator(model)
sim2.run(10)
plt.plot(sim2.trange(), sim2.data[p_stim], label='input')
plt.plot(sim2.trange(), sim2.data[p_result], label='output (rmse:%1.3f)' % np.sqrt(np.mean((sim.data[p_ideal]-sim2.data[p_result])**2)))
plt.plot(sim2.trange(), sim2.data[p_result2], label='trained (rmse:%1.3f)' % np.sqrt(np.mean((sim.data[p_ideal]-sim2.data[p_result2])**2)))
plt.legend(loc='best')
Explanation: Yay it works! Still a pretty hight rmse, though. Can we improve that?
One possible problem is that the data used for the output connection is assuming that the delay network does a perfect job. What if we instead train it based on the real data coming out of the delay network? This is basically just making our eval_points a bit more realistic.
End of explanation
model = nengo.Network()
model.networks.append(net)
with model:
result2 = nengo.Node(None, size_in=1)
conn = nengo.Connection(pool, result2, eval_points=sim.data[p_pool], function=sim.data[p_ideal], scale_eval_points=False)
import nengo_encoder_learning
error = nengo_encoder_learning.improve(conn, learning_rate=1e-2, steps=10)
plt.plot(error)
Explanation: That's some improvement! What else can we do?
The pool Ensemble is pretty high-dimensional, and for some high-dimensional functions, it's useful to get a better encoder distribution. So, let's use feedback alignment to find better encoders:
End of explanation
model = nengo.Network()
model.networks.append(net)
with model:
offsets = [-np.pi/2, np.pi]
def stim_func(t):
offset = offsets[int(t/5) % len(offsets)]
return np.sin(t*np.pi), np.sin(t*np.pi+offset)
stim = nengo.Node(stim_func)
for i in range(D):
nengo.Connection(stim[i], rw[i].input, synapse=None)
result2 = nengo.Node(None, size_in=1)
nengo.Connection(pool, result2, eval_points=sim.data[p_pool], function=sim.data[p_ideal], scale_eval_points=False)
p_result = nengo.Probe(result)
p_result2 = nengo.Probe(result2)
p_stim = nengo.Probe(stim)
sim2 = nengo.Simulator(model)
sim2.run(10)
plt.plot(sim2.trange(), sim2.data[p_stim], label='input')
plt.plot(sim2.trange(), sim2.data[p_result], label='output (rmse:%1.3f)' % np.sqrt(np.mean((sim.data[p_ideal]-sim2.data[p_result])**2)))
plt.plot(sim2.trange(), sim2.data[p_result2], label='trained (rmse:%1.3f)' % np.sqrt(np.mean((sim.data[p_ideal]-sim2.data[p_result2])**2)))
plt.legend(loc='best')
Explanation: That looks like it should improve things! How well does it do?
End of explanation |
8,598 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PMOD Grove PIR Motion Sensor
This example shows how to use the Grove PIR motion sensor.
This demo requires the Grove PIR motion sensor and PYNQ Grove Adapter.
1. Download overlay
Download the overlay. Instantiate Grove PIR object.
In this example, the Grove PIR sensor is assumed to be connected to G1 on the PYNQ Grove Adapter. The Grove Adapter is connected to PMODA interface on board.
Step1: 2. Detect motion
We can now start the motion detection loop.
When the cell below is executed, the LED will keep flashing until the PIR detects some movement.
Step2: 3. Clean-up
Delete objects. | Python Code:
from time import sleep
from pynq import Overlay
from pynq.board import LED
from pynq.iop import Grove_PIR
from pynq.iop import PMODA
from pynq.iop import PMOD_GROVE_G1
ol1 = Overlay("base.bit")
ol1.download()
pir = Grove_PIR(PMODA,PMOD_GROVE_G1)
Explanation: PMOD Grove PIR Motion Sensor
This example shows how to use the Grove PIR motion sensor.
This demo requires the Grove PIR motion sensor and PYNQ Grove Adapter.
1. Download overlay
Download the overlay. Instantiate Grove PIR object.
In this example, the Grove PIR sensor is assumed to be connected to G1 on the PYNQ Grove Adapter. The Grove Adapter is connected to PMODA interface on board.
End of explanation
led = LED(0)
led.on()
if pir.read()==0:
print("Starting detection...")
while True:
led.on()
sleep(0.1)
led.off()
sleep(0.1)
if pir.read()==1:
print("Detected a motion.")
break
print("Ending detection...")
Explanation: 2. Detect motion
We can now start the motion detection loop.
When the cell below is executed, the LED will keep flashing until the PIR detects some movement.
End of explanation
del pir
del led
del ol1
Explanation: 3. Clean-up
Delete objects.
End of explanation |
8,599 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 3 lecture notes
Exercise 2 review - common mistakes
Including directories in paths
If you create a file in a lower directory, then want to modify, move, or delete it, you have to use the directory to refer to it.
Step1: ">" vs ">>"
Both ">" and ">>" redirect output from the screen to a file. Both will create new files if none yet exists. Only ">" will overwrite an existing file; ">>" will append to an existing file.
Step2: lower|sort|uniq or sort|lower|uniq
Order matters! Consider the text from exercise-02.
Step3: Among the set of three functions
Step4: More about grep
grep is a lot more powerful than what you've seen so far. More than anything else, it's commonly used to find text within files. For example, to find lines with "Romeo" in Romeo and Juliet
Step5: There are many, many options, such as case-insensitivity
Step6: Another useful one is to print line numbers for matching lines
Step7: We can also negate certain terms - show non-matches.
Step8: And one more useful tip is to match more than one thing
Step9: Wildcards with "*"
Sometimes you need to perform a task with a set of files that share a characteristic like a file extension. The shell lessons had examples with .pdb files. This is common.
The * (asterisk, or just "star") is a wildcard, which matches zero-to-many characters.
Step10: The ? (question mark) is a wildcard that matches exactly one character.
Step11: The difference is subtle - these two would have worked interchangeably on the above. But note
Step12: See the difference? The * can match more than one character; ? only matches one.
Writing Python filters
Starting with the samplefilter.py filter, let's write some of our own.
Step13: Working with GNU Parallel
GNU Parallel is an easy to use but very powerful tool with a lot of options. You can use it to process a lot of data easily and it can also make a big mess in a hurry. For more examples, see the tutorial page.
Let's start with something we've seen before
Step14: That's 25,875 lines and 218,062 words in the texts of Romeo and Juliet and Little Women.
We can split them up into word counts one at a time like we did in exercise-02
Step15: Note that I've wrapped lines around by using the \ character. To me, this looks easier to read - you can see each step of the pipeline one at a time. The \ only means "this shell line continues on the next line". The | still acts as the pipe.
Let's look at a second book, Little Women. We'll add time to get a sense of how long it takes.
Step16: It looks like Little Women is much longer, which makes sense - it's a novel, not a play. More text!
To compare the two directly
Step17: We can run through both files at once by giving both file names to grep
Step18: Do those numbers look right?
Let's take a closer look at what's going on.
Step19: Aha! grep is not-so-helpfully including the second filename on the lines matched from the second file, but not on the first. That's why the counts are off.
There's probably an option to tell grep not to do that. But let's try something completely different.
First, let's break the step into the data parallel piece. For which part of this pipeline is completely data parallel?
Step20: See what we did there? We parallelized the data, then brought it back together for the rest of the pipeline.
Let's try it on a much bigger dataset. (Note that we're unzipping into a new directory with unzip -d.) | Python Code:
!mkdir mydirectory
!ls > mydirectory/myfiles.txt
!rm myfiles.txt
!rm mydirectory/myfiles.txt
!ls mydirectory
Explanation: Week 3 lecture notes
Exercise 2 review - common mistakes
Including directories in paths
If you create a file in a lower directory, then want to modify, move, or delete it, you have to use the directory to refer to it.
End of explanation
!date > datefile.txt
!cat datefile.txt
!date > datefile.txt
!cat datefile.txt
!date >> datefile.txt
!date >> datefile.txt
!cat datefile.txt
Explanation: ">" vs ">>"
Both ">" and ">>" redirect output from the screen to a file. Both will create new files if none yet exists. Only ">" will overwrite an existing file; ">>" will append to an existing file.
End of explanation
!wget https://github.com/gwsb-istm-6212-fall-2016/syllabus-and-schedule/raw/master/exercises/pg2500.txt
!grep -oE '\w{{2,}}' pg2500.txt | grep -v '^[0-9]' | uniq -c | head
Explanation: lower|sort|uniq or sort|lower|uniq
Order matters! Consider the text from exercise-02.
End of explanation
!grep -oE '\w{{2,}}' pg2500.txt | grep -v '^[0-9]' | uniq -c | tr '[:upper:]' '[:lower:]' | sort | head
!grep -oE '\w{{2,}}' pg2500.txt | grep -v '^[0-9]' | uniq -c | sort | tr '[:upper:]' '[:lower:]' | head
!grep -oE '\w{{2,}}' pg2500.txt | grep -v '^[0-9]' | sort | tr '[:upper:]' '[:lower:]' | uniq -c | head
!grep -oE '\w{{2,}}' pg2500.txt | grep -v '^[0-9]' | sort | uniq -c | tr '[:upper:]' '[:lower:]' | head
!grep -oE '\w{{2,}}' pg2500.txt | grep -v '^[0-9]' | tr '[:upper:]' '[:lower:]' | sort | uniq -c | head
!grep -oE '\w{{2,}}' pg2500.txt | grep -v '^[0-9]' | tr '[:upper:]' '[:lower:]' | uniq -c | sort | head
Explanation: Among the set of three functions: {uniq, lower, sort} there are six orderings. Which produce correct results, and why?
uniq, lower, sort
uniq, sort, lower
sort, lower, uniq
sort, uniq, lower
lower, sort, uniq
lower, uniq, sort
End of explanation
!grep Romeo romeo.txt | head
Explanation: More about grep
grep is a lot more powerful than what you've seen so far. More than anything else, it's commonly used to find text within files. For example, to find lines with "Romeo" in Romeo and Juliet:
End of explanation
!grep -i what romeo.txt | head
Explanation: There are many, many options, such as case-insensitivity:
End of explanation
!grep -n Juliet romeo.txt | head
Explanation: Another useful one is to print line numbers for matching lines:
End of explanation
!grep -n Juliet romeo.txt | grep -v Romeo | head
Explanation: We can also negate certain terms - show non-matches.
End of explanation
!grep "Romeo\|Juliet" romeo.txt | head
Explanation: And one more useful tip is to match more than one thing:
End of explanation
!ls *.txt
Explanation: Wildcards with "*"
Sometimes you need to perform a task with a set of files that share a characteristic like a file extension. The shell lessons had examples with .pdb files. This is common.
The * (asterisk, or just "star") is a wildcard, which matches zero-to-many characters.
End of explanation
!cp romeo.txt womeo.txt
!ls ?omeo.txt
!ls wome?.txt
Explanation: The ? (question mark) is a wildcard that matches exactly one character.
End of explanation
!ls wo*.txt
!ls wo?.txt
Explanation: The difference is subtle - these two would have worked interchangeably on the above. But note:
End of explanation
!chmod +x simplefilter.py
!head pg2500.txt | ./simplefilter.py
!cp simplefilter.py lower.py
!head pg2500.txt | ./lower.py
Explanation: See the difference? The * can match more than one character; ? only matches one.
Writing Python filters
Starting with the samplefilter.py filter, let's write some of our own.
End of explanation
!wc *.txt
Explanation: Working with GNU Parallel
GNU Parallel is an easy to use but very powerful tool with a lot of options. You can use it to process a lot of data easily and it can also make a big mess in a hurry. For more examples, see the tutorial page.
Let's start with something we've seen before: splitting a text file up and counting its unique words.
End of explanation
!grep -oE '\w{{2,}}' romeo.txt \
| tr '[:upper:]' '[:lower:]' \
| sort \
| uniq -c \
| sort -rn \
| head -10
Explanation: That's 25,875 lines and 218,062 words in the texts of Romeo and Juliet and Little Women.
We can split them up into word counts one at a time like we did in exercise-02:
End of explanation
!time grep -oE '\w{{2,}}' women.txt \
| tr '[:upper:]' '[:lower:]' \
| sort \
| uniq -c \
| sort -rn \
| head -10
Explanation: Note that I've wrapped lines around by using the \ character. To me, this looks easier to read - you can see each step of the pipeline one at a time. The \ only means "this shell line continues on the next line". The | still acts as the pipe.
Let's look at a second book, Little Women. We'll add time to get a sense of how long it takes.
End of explanation
!wc *.txt
Explanation: It looks like Little Women is much longer, which makes sense - it's a novel, not a play. More text!
To compare the two directly:
End of explanation
!time grep -oE '\w{{2,}}' romeo.txt women.txt \
| tr '[:upper:]' '[:lower:]' \
| sort \
| uniq -c \
| sort -rn \
| head -10
Explanation: We can run through both files at once by giving both file names to grep:
End of explanation
!time grep -oE '\w{{2,}}' romeo.txt women.txt \
| tr '[:upper:]' '[:lower:]' \
| sort \
| uniq -c \
| grep "and" \
| tail -10
Explanation: Do those numbers look right?
Let's take a closer look at what's going on.
End of explanation
!time ls *.txt \
| parallel -j+0 "grep -oE '\w{2,}' {} | tr '[:upper:]' '[:lower:]' >> all-words.txt"
!time sort all-words.txt \
| uniq -c \
| sort -rn \
| head -10
Explanation: Aha! grep is not-so-helpfully including the second filename on the lines matched from the second file, but not on the first. That's why the counts are off.
There's probably an option to tell grep not to do that. But let's try something completely different.
First, let's break the step into the data parallel piece. For which part of this pipeline is completely data parallel?
End of explanation
!unzip -d many-texts texts.zip
!ls -l many-texts | wc -l
!wc many-texts/*.txt
!time ls many-texts/*.txt \
| parallel --eta -j+0 "grep -oE '\w{2,}' {} | tr '[:upper:]' '[:lower:]' >> many-texts/all-words.txt"
!time sort many-texts/all-words.txt \
| uniq -c \
| sort -rn \
| head -10
Explanation: See what we did there? We parallelized the data, then brought it back together for the rest of the pipeline.
Let's try it on a much bigger dataset. (Note that we're unzipping into a new directory with unzip -d.)
End of explanation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.