text stringlengths 2.5k 6.39M | kind stringclasses 3 values |
|---|---|
# Лекция 7. Разреженные матрицы и прямые методы для решения больших разреженных систем
## План на сегодняшнюю лекцию
- Плотные неструктурированные матрицы и распределённое хранение
- Разреженные матрицы и форматы их представления
- Быстрая реализация умножения разреженной матрицы на вектор
- Метод Гаусса для разреженных матриц: упорядоченность
- Заполнение и графы: сепараторы
- Лапласиан графа
## Плотные матрицы большой размерности
- Если размер матрицы очень большой, то она не помещается в память
- Возможные способы работы с такими матрицами
- Если матрица **структурирована**, например блочно Тёплицева с Тёплицевыми блоками (в следующих лекциях), тогда возможно сжатое хранение
- Для неструктурированных матриц помогает **распределённая память**
- MPI для обработки распределённо хранимых матриц
### Распределённая память и MPI
- Разбиваем матрицу на блоки и храним их на различных машинах
- Каждая машина имеет своё собственное адресное пространство и не может повредить данные на других машинах
- В этом случае машины передают друг другу данные для агрегирования результата вычислений
- [MPI (Message Passing Interface)](https://en.wikipedia.org/wiki/Message_Passing_Interface) – стандарт в параллельных вычислениях с распределённой памятью
### Пример: умножение матрицы на вектор
- Предположим, вы хотите посчитать произведение $Ax$ и матрица $A$ не помещается в памяти
- В этом случае вы можете разбить матрицу на блоки и поместить их на разные машины
- Возможные стратегии:
- Одномерное деление на блоки использует только строки
- Двумерное деление на блоки использует и строки и столбцы
#### Пример одномерного деления на блоки
<img src="./1d_block.jpg">
#### Общее время вычисления произведения матрицы на вектор для одномерного разбиения на блоки
- Каждая машина хранит $n / p $ полных строк и $n / p$ элементов вектора $x$
- Общее число операций $n^2 / p$
- Общее время для отправки и записи данных $t_s \log p + t_w n$, где $t_s$ – единица времени на отправку и $t_w$ – единица времени на запись
#### Пример двумерного деления на блоки
<img src="./2d_block.png" width=400>
#### Общее время вычисления умножения матрицы на вектор с использованием двумерного разбиения на блоки
- Каждая машина хранит блок размера $n / \sqrt{p} $ и $n / \sqrt{p}$ элементов вектора
- Общее число операций $n^2 / p$
- Общее время для отправки и записи данных примерно равно $t_s \log p + t_w (n/\sqrt{p}) \log p$, где $t_s$ – единица времени на отправку и $t_w$ – единица времени на запись
### Пакеты с поддержкой распределённого хранения данных
- [ScaLAPACK](http://www.netlib.org/scalapack/)
- [Trilinos](https://trilinos.org/)
В Python вы можете использовать [mpi4py](https://mpi4py.readthedocs.io/en/stable/) для параллельной реализации ваших алгоритмов.
- PyTorch поддерживает распределённое обучение и хранение данных, см подробности [тут](https://pytorch.org/tutorials/intermediate/dist_tuto.html)
### Резюме про работу с большими плотными неструктурированными матрицами
- Распределённое хранение матриц
- MPI
- Пакеты, которые используют блочные вычисления
- Различные подходы к блочным вычислениям
## Разреженные матрицы
- Ограничением в решении задач линейной алгебры с плотными матрицами является память, требуемая для хранения плотных матриц, $N^2$ элементов.
- Разреженные матрицы, где большинство элементов нулевые позволяют по крайней мере хранить их в памяти.
- Основные вопросы: можем ли мы решать следующие задачи для разреженных матриц?
- решение линейных систем
- вычисление собственных значений и собственных векторов
- вычисление матричных функций
## Приложения разреженных матриц
Разреженные матрицы возникают в следующих областях:
- математическое моделирование и решение уравнений в частных производных
- обработка графов, например анализ социальных сетей
- рекомендательные системы
- в целом там, где отношения между объектами "разрежены".
### Разреженные матрицы помогают в вычислительной теории графов
- Графы представляют в виде матриц смежности, которые чаще всего разрежены
- Численное решение задач теории графов сводится к операциям с этими разреженными матрицами
- Кластеризация графа и выделение сообществ
- Ранжирование
- Случайные блуждатели
- И другие....
- Пример: возможно, самый большой доступный граф гиперссылок содержит 3.5 миллиарда веб-страниц и 128 миллиардов гиперссылок, больше подробностей см. [тут](http://webdatacommons.org/hyperlinkgraph/)
- Различные графы среднего размера для тестирования ваших алгоритмов доступны в [Stanford Large Network Dataset Collection](https://snap.stanford.edu/data/)
### Florida sparse matrix collection
- Большое количество разреженных матриц из различных приложений вы можете найти в [Florida sparse matrix collection](http://www.cise.ufl.edu/research/sparse/matrices/).
```
from IPython.display import IFrame
IFrame('http://yifanhu.net/GALLERY/GRAPHS/search.html', 500, 500)
```
### Разреженные матрицы и глубокое обучение
- DNN имеют очень много параметров
- Некоторые из них могут быть избыточными
- Как уменьшить число параметров без серьёзной потери в точности?
- [Sparse variational dropout method](https://github.com/ars-ashuha/variational-dropout-sparsifies-dnn) даёт существенно разреженные фильтры в DNN почти без потери точности!
## Построение разреженных матриц
- Мы можем генерировать разреженные матрицы с помощью пакета **scipy.sparse**
- Можно задать матрицы очень большого размера
Полезные функции при создании разреженных матриц:
- для созданий диагональной матрицы с заданными диагоналями ```spdiags```
- Кронекерово произведение (определение будет далее) разреженных матриц ```kron```
- также арифметические операции для разреженных матриц перегружены
### Кронекерово произведение
Для матриц $A\in\mathbb{R}^{n\times m}$ и $B\in\mathbb{R}^{l\times k}$ Кронекерово произведение определяется как блочная матрица следующего вида
$$
A\otimes B = \begin{bmatrix}a_{11}B & \dots & a_{1m}B \\ \vdots & \ddots & \vdots \\ a_{n1}B & \dots & a_{nm}B\end{bmatrix}\in\mathbb{R}^{nl\times mk}.
$$
Основные свойства:
- билинейность
- $(A\otimes B) (C\otimes D) = AC \otimes BD$
- Пусть $\mathrm{vec}(X)$ оператор векторизации матрицы по столбцам. Тогда
$\mathrm{vec}(AXB) = (B^T \otimes A) \mathrm{vec}(X).$
```
import numpy as np
import scipy as sp
import scipy.sparse
from scipy.sparse import csc_matrix, csr_matrix
import matplotlib.pyplot as plt
import scipy.linalg
import scipy.sparse.linalg
%matplotlib inline
n = 5
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
e = sp.sparse.eye(n)
A = sp.sparse.kron(lp1, e) + sp.sparse.kron(e, lp1)
A = csc_matrix(A)
plt.spy(A, aspect='equal', marker='.', markersize=5)
```
### Шаблон разреженности
- Команда ```spy``` рисует шаблон разреженности данной матрицы: пиксель $(i, j)$ отображается на рисунке, если соответствующий элемент матрицы ненулевой.
- Шаблон разреженности действительно очень важен для понимания сложности алгоритмов линейной алгебры для разреженных матриц.
- Зачастую шаблона разреженности достаточно для анализа того, насколько "сложно" работать с этой матрицей.
### Определение разреженных матриц
- Разреженные матрицы – это матрицы, такие что количество ненулевых элементов в них существенно меньше общего числа элементов в матрице.
- Из-за этого вы можете выполнять базовые операции линейной алгебры (прежде всего решать линейные системы) гораздо быстрее по сравнению с использованием плотных матриц.
## Что нам необходимо, чтобы увидеть, как это работает
- **Вопрос 1:** Как хранить разреженные матрицы в памяти?
- **Вопрос 2:** Как умножить разреженную матрицу на вектор быстро?
- **Вопрос 3:** Как быстро решать линейные системы с разреженными матрицами?
### Хранение разреженных матриц
Существет много форматов хранения разреженных матриц, наиболее важные:
- COO (координатный формат)
- LIL (список списков)
- CSR (compressed sparse row)
- CSC (compressed sparse column)
- блочные варианты
В ```scipy``` представлены конструкторы для каждого из этих форматов, например
```scipy.sparse.lil_matrix(A)```.
#### Координатный формат (COO)
- Простейший формат хранения разреженной матрицы – координатный.
- В этом формате разреженная матрица – это набор индексов и значений в этих индексах.
```python
i, j, val
```
где ```i, j``` массивы индексов, ```val``` массив элементов матрицы. <br>
- Таким образом, нам нужно хранить $3\cdot$**nnz** элементов, где **nnz** обозначает число ненулевых элементов в матрице.
**Q:** Что хорошего и что плохого в использовании такого формата?
#### Основные недостатки
- Он неоптимален по памяти (почему?)
- Он неоптимален для умножения матрицы на вектор (почему?)
- Он неоптимален для удаления элемента (почему?)
Первые два недостатка решены в формате CSR.
**Q**: какой формат решает третий недостаток?
#### Compressed sparse row (CSR)
В формате CSR матрица хранится также с помощью трёх массивов, но других:
```python
ia, ja, sa
```
где:
- **ia** (начало строк) массив целых чисел длины $n+1$
- **ja** (индексы столбцов) массив целых чисел длины **nnz**
- **sa** (элементы матрицы) массив действительных чисел длины **nnz**
<img src="https://www.karlrupp.net/wp-content/uploads/2016/02/csr_storage_sparse_marix.png" width=60% />
Итак, всего необходимо хранить $2\cdot{\bf nnz} + n+1$ элементов.
### Разреженные матрицы в PyTorch и Tensorflow
- PyTorch поддерживает разреженные матрицы в формате COO
- Неполная поддержка вычисления градиентов в операциях с такими матрицами, список и обсуждение см. [тут](https://github.com/pytorch/pytorch/issues/9674)
- Tensorflow также поддерживает разреженные матрицы в COO формате
- Список поддерживаемых операций приведён [здесь](https://www.tensorflow.org/api_docs/python/tf/sparse) и поддержка вычисления градиентов также ограничена
### CSR формат позволяет быстро умножить разреженную матрицу на вектор (SpMV)
```python
for i in range(n):
for k in range(ia[i]:ia[i+1]):
y[i] += sa[k] * x[ja[k]]
```
```
import numpy as np
import scipy as sp
import scipy.sparse
import scipy.sparse.linalg
from scipy.sparse import csc_matrix, csr_matrix, coo_matrix
import matplotlib.pyplot as plt
%matplotlib inline
n = 1000
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
e = sp.sparse.eye(n)
A = sp.sparse.kron(lp1, e) + sp.sparse.kron(e, lp1)
A = csr_matrix(A)
rhs = np.ones(n * n)
B = coo_matrix(A)
%timeit A.dot(rhs)
%timeit B.dot(rhs)
```
Видно, что **CSR** быстрее, и чем менее структурирован шаблон разреженности, тем выше выигрыш в скорости.
### Разреженные матрицы и эффективность
- Использование разреженных матриц приводит к уменьшению сложности
- Но они не очень подходят для параллельных/GPU реализаций
- Они не показывают максимальную эффективность из-за случайного доступа к данным.
- Обычно, пиковая производительность порядка $10\%-15\%$ считается хорошей.
### Вспомним как измеряется эффективность операций
- Стандартный способ измерения эффективности операций линейной алгебры – это использование **flops** (число опраций с плавающей точкой в секунду)
- Измерим эффективность умножения матрицы на вектор в случае плотной и разреженной матрицы
```
import numpy as np
import time
n = 4000
a = np.random.randn(n, n)
v = np.random.randn(n)
t = time.time()
np.dot(a, v)
t = time.time() - t
print('Time: {0: 3.1e}, Efficiency: {1: 3.1e} Gflops'.\
format(t, ((2 * n ** 2)/t) / 10 ** 9))
n = 4000
ex = np.ones(n);
a = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
rhs = np.random.randn(n)
t = time.time()
a.dot(rhs)
t = time.time() - t
print('Time: {0: 3.1e}, Efficiency: {1: 3.1e} Gflops'.\
format(t, (3 * n) / t / 10 ** 9))
```
### Случайный доступ к данным и промахи в обращении к кешу
- Сначала все элементы матрицы и вектора хранятся в оперативной памяти (RAM – Random Access Memory)
- Если вы хотите вычислить произведение матрицы на вектор, часть элементов матрицы и вектора перемещаются в кеш (быстрой памяти малого объёма), см. [лекцию об алгоритме Штрассена и умножении матриц](https://github.com/amkatrutsa/nla2020_ozon/blob/master/lectures/lecture4/lecture4.ipynb)
- После этого CPU берёт данные из кеша, обрабатывает их и возвращает результат снова в кеш
- Если CPU требуются данные, которых ещё нет в кеше, это называется промах в обращении к кешу (cache miss)
- Если случается промах в обращении к кешу, необходимые данные перемещаются из оперативной памяти в кеш
**Q**: что если в кеше нет свободного места?
- Чем больше промахов в обращении к кешу, тем медленнее выполняются вычисления
### План кеша и LRU
<img src="./cache_scheme.png" width="500">
#### Умножение матрицы в CSR формате на вектор
```python
for i in range(n):
for k in range(ia[i]:ia[i+1]):
y[i] += sa[k] * x[ja[k]]
```
- Какая часть операций приводит к промахам в обращении к кешу?
- Как эту проблему можно решить?
### Переупорядочивание уменьшает количество промахов в обращении к кешу
- Если ```ja``` хранит последовательно элементы, тогда они могут быть перемещены в кеш одновременно и количество промахов в обращении к кешу уменьшится
- Так происходит, когда разреженная матрица является **ленточной** или хотя бы блочно-диагональной
- Мы можем превратить данную разреженную матрицу в ленточную или блочно-диагональную с помощью *перестановок*
- Пусть $P$ матрица перестановок строк матрицы и $Q$ матрица перестановок столбцов матрицы
- $A_1 = PAQ$ – матрица с шириной ленты меньшей, чем у матрицы $A$
- $y = Ax \to \tilde{y} = A_1 \tilde{x}$, где $\tilde{x} = Q^{\top}x$ и $\tilde{y} = Py$
- [Separated block diagonal form](http://albert-jan.yzelman.net/PDFs/yzelman09-rev.pdf) призван минимизировать количество промахов в обращении к кешу
- Он также может быть расширен на двумерный случай, где разделяются не только строки, но и столбцы
#### Пример
- SBD в одномерном случае
<img src="./sbd.png" width="400">
## Методы решения линейных систем с разреженными матрицами
- Прямые методы
- LU разложение
- Различные методы переупорядочивания для минимизации заполнения факторов
- Крыловские методы
```
n = 10
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
e = sp.sparse.eye(n)
A = sp.sparse.kron(lp1, e) + sp.sparse.kron(e, lp1)
A = csr_matrix(A)
rhs = np.ones(n * n)
sol = sp.sparse.linalg.spsolve(A, rhs)
_, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(sol)
ax1.set_title('Not reshaped solution')
ax2.contourf(sol.reshape((n, n), order='f'))
ax2.set_title('Reshaped solution')
```
## LU разложение разреженной матрицы
- Почему разреженная линейная система может быть решена быстрее, чем плотная? С помощью какого метода?
- В LU разложении матрицы $A$ факторы $L$ и $U$ могут быть также разреженными:
$$A = L U$$
- А решение линейной системы с разреженной треугольной матрицей может быть вычислено очень быстро.
<font color='red'> Заметим, что обратная матрица от разреженной матрицы НЕ разрежена! </font>
```
n = 7
ex = np.ones(n);
a = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
b = np.array(np.linalg.inv(a.toarray()))
print(a.toarray())
print(b)
```
## А факторы...
- $L$ и $U$ обычно разрежены
- В случае трёхдиагональной матрицы они даже бидиагональны!
```
from scipy.sparse.linalg import splu
T = splu(a.tocsc(), permc_spec="NATURAL")
plt.spy(T.L)
```
Отметим, что ```splu``` со значением параметра ```permc_spec``` по умолчанию даёт перестановку, которая не даёт бидиагональные факторы:
```
from scipy.sparse.linalg import splu
T = splu(a.tocsc())
plt.spy(T.L)
print(T.perm_c)
```
## Двумерный случай
В двумерном случае всё гораздо хуже:
```
n = 20
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
e = sp.sparse.eye(n)
A = sp.sparse.kron(lp1, e) + sp.sparse.kron(e, lp1)
A = csc_matrix(A)
T = scipy.sparse.linalg.spilu(A)
plt.spy(T.L, marker='.', color='k', markersize=8)
```
Для правильной перестановки в двумерном случае число ненулевых элементов в $L$ растёт как $\mathcal{O}(N \log N)$. Однако сложность равна $\mathcal{O}(N^{3/2})$.
## Разреженные матрицы и теория графов
- Число ненулей в факторах из LU разложения тесно связано с теорией графов.
- Пакет ``networkx`` можно использовать для визуализации графов, имея только матрицу смежности.
```
import networkx as nx
n = 10
ex = np.ones(n);
lp1 = sp.sparse.spdiags(np.vstack((ex, -2*ex, ex)), [-1, 0, 1], n, n, 'csr');
e = sp.sparse.eye(n)
A = sp.sparse.kron(lp1, e) + sp.sparse.kron(e, lp1)
A = csc_matrix(A)
G = nx.Graph(A)
nx.draw(G, pos=nx.spectral_layout(G), node_size=10)
```
## Заполнение (fill-in)
- Заполнение матрицы – это элементы, которые были **нулями**, но стали **ненулями** в процессе выполнения алгоритма.
- Заполнение может быть различным для различных перестановок. Итак, до того как делать факторизацию матрицы нам необходимо переупорядочить её элементы так, чтобы заполнение факторов было наименьшим.
**Пример**
$$A = \begin{bmatrix} * & * & * & * & *\\ * & * & 0 & 0 & 0 \\ * & 0 & * & 0 & 0 \\ * & 0 & 0& * & 0 \\ * & 0 & 0& 0 & * \end{bmatrix} $$
- Если мы исключаем элементы сверху вниз, тогда мы получим плотную матрицу.
- Однако мы можем сохранить разреженность, если исключение будет проводиться снизу вверх.
- Подробности на следующих слайдах
## Метод Гаусса для разреженных матриц
- Дана матрица $A$ такая что $A=A^*>0$.
- Вычислим её разложение Холецкого $A = LL^*$.
Фактор $L$ может быть плотным даже если $A$ разреженная:
$$
\begin{bmatrix} * & * & * & * \\ * & * & & \\ * & & * & \\ * & & & * \end{bmatrix} =
\begin{bmatrix} * & & & \\ * & * & & \\ * & * & * & \\ * & * & * & * \end{bmatrix}
\begin{bmatrix} * & * & * & * \\ & * & * & * \\ & & * & * \\ & & & * \end{bmatrix}
$$
**Q**: как сделать факторы разреженными, то есть минимизировать заполнение?
## Метод Гаусса и перестановка
- Нам нужно найти перестановку индексов такую что факторы будут разреженными, то есть мы будем вычислять разложение Холецкого для матрицы $PAP^\top$, где $P$ – матрица перестановки.
- Для примера с предыдущего слайда
$$
P \begin{bmatrix} * & * & * & * \\ * & * & & \\ * & & * & \\ * & & & * \end{bmatrix} P^\top =
\begin{bmatrix} * & & & * \\ & * & & * \\ & & * & * \\ * & * & * & * \end{bmatrix} =
\begin{bmatrix} * & & & \\ & * & & \\ & & * & \\ * & * & * & * \end{bmatrix}
\begin{bmatrix} * & & & * \\ & * & & * \\ & & * & * \\ & & & * \end{bmatrix}
$$
где
$$
P = \begin{bmatrix} & & & 1 \\ & & 1 & \\ & 1 & & \\ 1 & & & \end{bmatrix}
$$
- Такая форма матрицы даёт разреженные факторы в LU разложении
```
import numpy as np
import scipy.sparse as spsp
import scipy.sparse.linalg as spsplin
import scipy.linalg as splin
import matplotlib.pyplot as plt
%matplotlib inline
A = spsp.coo_matrix((np.random.randn(10), ([0, 0, 0, 0, 1, 1, 2, 2, 3, 3],
[0, 1, 2, 3, 0, 1, 0, 2, 0, 3])))
print("Original matrix")
plt.spy(A)
plt.show()
lu = spsplin.splu(A.tocsc(), permc_spec="NATURAL")
print("L factor")
plt.spy(lu.L)
plt.show()
print("U factor")
plt.spy(lu.U)
plt.show()
print("Column permutation:", lu.perm_c)
print("Row permutation:", lu.perm_r)
```
### Блочный случай
$$
PAP^\top = \begin{bmatrix} A_{11} & & A_{13} \\ & A_{22} & A_{23} \\ A_{31} & A_{32} & A_{33}\end{bmatrix}
$$
тогда
$$
PAP^\top = \begin{bmatrix} A_{11} & 0 & 0 \\ 0 & A_{22} & 0 \\ A_{31} & A_{32} & A_{33} - A_{31}A_{11}^{-1} A_{13} - A_{32}A_{22}^{-1}A_{23} \end{bmatrix} \begin{bmatrix} I & 0 & A_{11}^{-1}A_{13} \\ 0 & I & A_{22}^{-1}A_{23} \\ 0 & 0 & I\end{bmatrix}
$$
- Блок $ A_{33} - A_{31}A_{11}^{-1} A_{13} - A_{32}A_{22}^{-1}A_{23}$ является дополнением по Шуру для блочно-диагональной матрицы $\begin{bmatrix} A_{11} & 0 \\ 0 & A_{22} \end{bmatrix}$
- Мы свели задачу к решению меньших линейных систем с матрицами $A_{11}$ и $A_{22}$
### Как найти перестановку?
- Основная идея взята из теории графов
- Разреженную матрицы можно рассматривать как **матрицу смежности** некоторого графа: вершины $(i, j)$ связаны ребром, если соответствующий элемент матрицы не ноль.
### Пример
Графы для матрицы $\begin{bmatrix} * & * & * & * \\ * & * & & \\ * & & * & \\ * & & & * \end{bmatrix}$ и для матрицы $\begin{bmatrix} * & & & * \\ & * & & * \\ & & * & * \\ * & * & * & * \end{bmatrix}$ имеют следующий вид:
<img src="./graph_dense.png" width=300 align="center"> и <img src="./graph_sparse.png" width=300 align="center">
* Почему вторая упорядоченность лучше, чем первая?
### Сепаратор графа
**Определение.** Сепаратором графа $G$ называется множество вершин $S$, таких что их удаление оставляет как минимум две связные компоненты.
Сепаратор $S$ даёт следующий метод нумерации вершин графа $G$:
- Найти сепаратор $S$, удаление которого оставляет связные компоненты $T_1$, $T_2$, $\ldots$, $T_k$
- Номера вершин в $S$ от $N − |S| + 1$ до $N$
- Рекурсивно, номера вершин в каждой компоненте:
- в $T_1$ от $1$ до $|T_1|$
- в $T_2$ от $|T_1| + 1$ до $|T_1| + |T_2|$
- и так далее
- Если компонента достаточно мала, то нумерация внутри этой компоненты произвольная
### Сепаратор и структура матрицы: пример
Сепаратор для матрицы двумерного лапласиана
$$
A_{2D} = I \otimes A_{1D} + A_{1D} \otimes I, \quad A_{1D} = \mathrm{tridiag}(-1, 2, -1),
$$
имеет следующий вид
<img src='./separator.png' width=300> </img>
Если мы пронумеруем сначала индексы в $\alpha$, затем в $\beta$, и наконец индексы в сепараторе $\sigma$ получим следующую матрицу
$$
PAP^\top = \begin{bmatrix} A_{\alpha\alpha} & & A_{\alpha\sigma} \\ & A_{\beta\beta} & A_{\beta\sigma} \\ A_{\sigma\alpha} & A_{\sigma\beta} & A_{\sigma\sigma}\end{bmatrix},
$$
которая имеет подходящую структуру.
- Таким образом, задача поиска перестановки была сведена к задаче поиска сепаратора графа!
### Nested dissection
- Для блоков $A_{\alpha\alpha}$, $A_{\beta\beta}$ можем продолжить разбиение рекурсивно
- После завершения рекурсии нужно исключить блоки $A_{\sigma\alpha}$ и $A_{\sigma\beta}$.
- Это делает блок в положении $A_{\sigma\sigma}\in\mathbb{R}^{n\times n}$ **плотным**.
- Вычисление разложения Холецкого этого блока стоит $\mathcal{O}(n^3) = \mathcal{O}(N^{3/2})$, где $N = n^2$ – общее число вершин.
- В итоге сложность $\mathcal{O}(N^{3/2})$
## Пакеты для nested dissection
- MUltifrontal Massively Parallel sparse direct Solver ([MUMPS](http://mumps.enseeiht.fr/))
- [Pardiso](https://www.pardiso-project.org/)
- [Umfpack как часть пакета SuiteSparse](http://faculty.cse.tamu.edu/davis/suitesparse.html)
У них есть интефейс для C/C++, Fortran и Matlab
### Резюме про nested dissection
- Нумерация свелась к поиску сепаратора
- Подход разделяй и властвуй
- Рекурсивно продолжается на два (или более) подмножества вершин после разделения
- В теории nested dissection даёт оптимальную сложность (почему?)
- На практике этот метод лучше других только на очень больших задачах
## Сепараторы на практике
- Вычисление сепаратора – это **нетривиальная задача!**
- Построение методов разбиения графа было активной сферой научных исследований долгие годы
Существующие подходы:
- Спектральное разбиение (использует собственные векторы **Лапласиана графа**) – подробности далее
- Геометрическое разбиение (для сеток с заданными координатами вершин) [обзор и анализ](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.31.4886&rep=rep1&type=pdf)
- Итеративные перестановки ([(Kernighan-Lin, 1970)](http://xilinx.asia/_hdl/4/eda.ee.ucla.edu/EE201A-04Spring/kl.pdf), [(Fiduccia-Matheysses, 1982](https://dl.acm.org/citation.cfm?id=809204))
- Поиск в ширину [(Lipton, Tarjan 1979)](http://www.cs.princeton.edu/courses/archive/fall06/cos528/handouts/sepplanar.pdf)
- Многоуровневая рекурсивная бисекция (наиболее практичная эвристика) ([обзор](https://people.csail.mit.edu/jshun/6886-s18/lectures/lecture13-1.pdf) и [статья](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.499.4130&rep=rep1&type=pdf)). Пакет для подобного рода разбиений называется METIS, написан на C, и доступен [здесь](http://glaros.dtc.umn.edu/gkhome/views/metis)
## Спектральное разбиение графа
- Идея спектрального разбиения восходит к работам Мирослава Фидлера, который изучал связность графов ([статья](https://dml.cz/bitstream/handle/10338.dmlcz/101168/CzechMathJ_23-1973-2_11.pdf)).
- Нам нужно разбить вершинеы графа на 2 множества
- Рассмотрим метки вершин +1/-1 и **функцию потерь**
$$E_c(x) = \sum_{j} \sum_{i \in N(j)} (x_i - x_j)^2, \quad N(j) \text{ обозначает множество соседей вершины } j. $$
Нам нужно сбалансированное разбиение, поэтому
$$\sum_i x_i = 0 \quad \Longleftrightarrow \quad x^\top e = 0, \quad e = \begin{bmatrix}1 & \dots & 1\end{bmatrix}^\top,$$
и поскольку мы ввели метки +1/-1, то выполнено
$$\sum_i x^2_i = n \quad \Longleftrightarrow \quad \|x\|_2^2 = n.$$
## Лапласиан графа
Функция потерь $E_c$ может быть записана в виде (проверьте почему)
$$E_c = (Lx, x)$$
где $L$ – **Лапласиан графа**, который определяется как симметричная матрица с элементами
$$L_{ii} = \mbox{степень вершины $i$},$$
$$L_{ij} = -1, \quad \mbox{если $i \ne j$ и существует ребро},$$
и $0$ иначе.
- Строчные суммы в матрице $L$ равны нулю, поэтому существует собственное значение $0$, которое даёт собственный вектор из всех 1.
- Собственные значения неотрицательны (почему?).
## Разбиение как задача оптимизации
- Минимизация $E_c$ с упомянутыми ограничениями приводит к разбиению, которое минимизирует число вершин в сепараторе, но сохраняет разбиение сбалансированным
- Теперь мы запишем релаксацию целочисленной задачи квадратичного программирования в форме непрерывной задачи квадратичного программирования
$$E_c(x) = (Lx, x)\to \min_{\substack{x^\top e =0, \\ \|x\|_2^2 = n}}$$
## Вектор Фидлера
- Решение этой задачи минимизации – собственный вектор матрицы $L$, соответствующий **второму** минимальному собственному значению (он называется вектором Фидлера)
- В самом деле,
$$
\min_{\substack{x^\top e =0, \\ \|x\|_2^2 = n}} (Lx, x) = n \cdot \min_{{x^\top e =0}} \frac{(Lx, x)}{(x, x)} = n \cdot \min_{{x^\top e =0}} R(x), \quad R(x) \text{ отношение Релея}
$$
- Поскольку $e$ – собственный вектор, соответствующий наименьшему собственному значению, то на подпространстве $x^\top e =0$ мы получим второе минимальное собственное значение.
- Знак $x_i$ обозначает разбиение графа.
- Осталось понять, как вычислить этот вектор. Мы знаем про степенной метод, но он ищет собственный вектор для максимального по модулю собственного значения.
- Итерационные методы для задачи на собственные значения будут рассмотрены далее в курсе...
```
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import networkx as nx
kn = nx.read_gml('karate.gml')
print("Number of vertices = {}".format(kn.number_of_nodes()))
print("Number of edges = {}".format(kn.number_of_edges()))
nx.draw_networkx(kn, node_color="red") #Draw the graph
Laplacian = nx.laplacian_matrix(kn).asfptype()
plt.spy(Laplacian, markersize=5)
plt.title("Graph laplacian")
plt.axis("off")
plt.show()
eigval, eigvec = spsplin.eigsh(Laplacian, k=2, which="SM")
print("The 2 smallest eigenvalues =", eigval)
plt.scatter(np.arange(len(eigvec[:, 1])), np.sign(eigvec[:, 1]))
plt.show()
print("Sum of elements in Fiedler vector = {}".format(np.sum(eigvec[:, 1].real)))
nx.draw_networkx(kn, node_color=np.sign(eigvec[:, 1]))
```
### Резюме по примеру использования спектрального разбиения графа
- Мы вызвали функцию из SciPy для поиска фиксированного числа собственных векторов и собственных значений, которые минимальны (возможны другие опции)
- Детали методов, которые реализованы в этих функциях, обсудим уже скоро
- Вектор Фидлера даёт простой способ разбиения графа
- Для разбиения графа на большее количество частей следует использовать собственные векторы Лапласиана как векторы признаков и запустить какой-нибудь алгоритм кластеризации, например $k$-means
### Вектор Фидлера и алгебраическая связность графа
**Определение.** Алгебраическая связность графа – это второе наименьшее собственное значение матрицы Лапласиана графа.
**Утверждение.** Алгебраическая связность графа больше 0 тогда и только тогда, когда граф связный.
## Minimal degree orderings
- Идея в том, чтобы исклоючить строки и/или столбцы с малым числом ненулей, обновить заполнение и повторить.
- Эффективная реализация является отдельной задачей (добавление/удаление элементов).
- На практике часто лучше всего для задач среднего размера
- SciPy [использует](https://docs.scipy.org/doc/scipy-1.3.0/reference/generated/scipy.sparse.linalg.splu.html) этот подход для различных матриц ($A^{\top}A$, $A + A^{\top}$)
## Главное в сегодняшней лекции
- Плотные матрицы большого размера и распределённые вычисления
- Разреженные матрицы, приложения и форматы их хранения
- Эффективные способы умножения разреженной матрицы на вектор
- LU разложение разреженной матрицы: заполнение и перестановки строк
- Минимизация заполнения: сепараторы и разбиение графа
- Nested dissection
- Спектральное разбиение графа: Лапласиан графа и вектор Фидлера
```
from IPython.core.display import HTML
def css_styling():
styles = open("./styles/custom.css", "r").read()
return HTML(styles)
css_styling()
```
| github_jupyter |
# The stereology module
The main purpose of stereology is to extract quantitative information from microscope images relating two-dimensional measures obtained on sections to three-dimensional parameters defining the structure. The aim of stereology is not to reconstruct the 3D geometry of the material (as in tomography) but to estimate a particular 3D feature. In this case, we aim to approximate the actual (3D) grain size distribution from the apparent (2D) grain size distribution obtained in sections.
GrainSizeTools script includes two stereological methods: 1) the Saltykov, and 2) the two-step methods. Before looking at its functionalities, applications and limitations, let's import the example dataset.
```
# Load the script first (change the path to GrainSizeTools_script.py accordingly!)
%run C:/Users/marco/Documents/GitHub/GrainSizeTools/grain_size_tools/GrainSizeTools_script.py
# Import the example dataset
filepath = 'C:/Users/marco/Documents/GitHub/GrainSizeTools/grain_size_tools/DATA/data_set.txt'
dataset = pd.read_csv(filepath, sep='\t')
dataset['diameters'] = 2 * np.sqrt(dataset['Area'] / np.pi) # estimate ECD
```
## The Saltykov method
> **What is it?**
>
> It is a stereological method that approximates the actual grain size distribution from the histogram of the apparent grain size distribution. The method is distribution-free, meaning that no assumption is made upon the type of statistical distribution, making the method very versatile.
>
> **What do I use it for?**
>
> Its main use (in geosciences) is to estimate the volume fraction of a specific range of grain sizes.
>
> **What are its limitations?**
>
> The method presents several limitations for its use in rocks
>
> - It assumes that grains are non-touching spheres uniformly distributed in a matrix (e.g. bubbles within a piece of glass). This never holds for polycrystalline rocks. To apply the method, the grains should be at least approximately equiaxed, which is normally fulfilled in recrystallized grains.
> - Due to the use of the histogram, the number of classes determines the accuracy and success of the method. There is a trade-off here because the smaller the number of classes, the better the numerical stability of the method, but the worse the approximation of the targeted distribution and vice versa. The issue is that no method exists to find an optimal number of classes and this has to be set by the user. The use of the histogram also implies that we cannot obtain a complete description of the grain size distribution.
> - The method lacks a formulation for estimating errors during the unfolding procedure.
> - You cannot obtain an estimate of the actual average grain size (3D) as individual data is lost when using the histogram (i.e. The Saltykov method reconstructs the 3D histogram, not every apparent diameter in the actual one as this is mathematically impossible).
>
TODO: explain the details of the method
```
fig1, (ax1, ax2) = stereology.Saltykov(dataset['diameters'], numbins=11, calc_vol=50)
fig1.savefig("saltykov_plot.png", dpi=150)
```
Now let's assume that we want to use the class densities estimated by Saltykov's method to calculate the specific volume of each or one of the classes. We have two options here.
```
stereology.Saltykov?
```
The input parameter ``text_file`` allows you to save a text file with the data in tabular format, you only have to declare the name of the file and the file type, either txt or csv (as in the function documentation example). Alternatively, you can use the Saltykov function to directly return the density and the midpoint values of the classes as follows:
```
mid_points, densities = stereology.Saltykov(dataset['diameters'], numbins=11, return_data=True)
print(densities)
```
As you may notice, these density values do not add up to 1 or 100.
```
np.sum(densities)
```
This is because the script normalized the frequencies of the different classes so that the integral over the range (not the sum) is one (see FAQs for an explanation on this). If you want to calculate the relative proportion for each class you must multiply the value of the densities by the bin size. After doing this, you can check that the relative densities sum one (i.e. they are proportions relative to one).
```
corrected_densities = densities * 14.236
np.sum(corrected_densities)
```
So for example if you have a volume of rock of say 100 cm2 and you want to estimate what proportion of that volume is occupied by each grain size class/range, you could estimate it as follows:
```
# I use np.around to round the values
np.around(corrected_densities * 100, 2)
```
## The two-step method
> **What is it?**
>
> It is a stereological method that approximates the actual grain size distribution. The method is distribution-dependent, meaning that it is assumed that the distribution of grain sizes follows a lognormal distribution. The method fit a lognormal distribution on top of the Saltykov output, hence the name two-step method.
>
> **What do I use it for?**
>
> Its main use is to estimate the shape of the lognormal distribution, the average grain size (3D), and the volume fraction of a specific range of grain sizes (not yet implemented).
>
> **What are its limitations?**
>
> The method is partially based on the Saltykov method and therefore inherits some of its limitations. The method however do not require to define a specific number of classes.
```
fig2, ax = stereology.calc_shape(dataset['diameters'])
fig2.savefig("2step_plot.png", dpi=150)
```
| github_jupyter |
# Convolutional Neural Network
### Author: Ivan Bongiorni, Data Scientist at GfK.
[LinkedIn profile](https://www.linkedin.com/in/ivan-bongiorni-b8a583164/)
In this Notebook I will implement a **basic CNN in TensorFlow 2.0**. I will use the famous **Fashion MNIST** dataset, [published by Zalando](https://github.com/zalandoresearch/fashion-mnist) and made [available on Kaggle](https://www.kaggle.com/zalando-research/fashionmnist). Images come already preprocessed in 28 x 28 black and white format.
It is a multiclass classification task on the following labels:
0. T-shirt/top
1. Trouser
2. Pullover
3. Dress
4. Coat
5. Sandal
6. Shirt
7. Sneaker
8. Bag
9. Ankle boot

Summary:
0. Import data + Dataprep
0. CNN architecture
0. Training with Mini Batch Gradient Descent
0. Test
```
# Import necessary modules
import numpy as np
import pandas as pd
import tensorflow as tf
print(tf.__version__)
from sklearn.utils import shuffle
from matplotlib import pyplot as plt
import seaborn
```
# 0. Import data + Dataprep
The dataset comes already divided in 60k and 10k Train and Test images. I will now import Training data, and leave Test for later. In order to dataprep image data, I need to reshape the pixel into `(, 28, 28, 1)` arrays; the 1 at the end represents the channel: 1 for black and white images, 3 (red, green, blue) for colored images. Pixel data are also scaled to the `[0, 1]` interval.
```
df = pd.read_csv('fashion-mnist_train.csv')
# extract labels, one-hot encode them
label = df.label
label = pd.get_dummies(label)
label = label.values
label = label.astype(np.float32)
df.drop('label', axis = 1, inplace = True)
df = df.values
df = df.astype(np.float32)
# reshape and scale data
df = df.reshape((len(df), 28, 28, 1))
df = df / 255.
```
# 1. CNN architecture
I will feed images into a set of **convolutional** and **max-pooling layers**:
- Conv layers are meant to extract relevant informations from pixel data. A number of *filters* scroll through the image, learning the most relevant informations to extract.
- Max-Pool layers instead are meant to drastically reduce the number of pixel data. For each (2, 2) window size, Max-Pool will save only the pixel with the highest activation value. Max-Pool is meant to make the model lighter by removing the least relevant observations, at the cost of course of loosing a lot of data!
Since I'm focused on the implementation, rather than on the theory behind it, please refer to [this good article](https://towardsdatascience.com/types-of-convolutions-in-deep-learning-717013397f4d) on how Conv and Max-Pool work in practice. If you are a die-hard, check [this awesome page from a CNN Stanford Course](http://cs231n.github.io/convolutional-networks/?source=post_page---------------------------#overview).
Con and Max-Pool will extract and reduce the size of the input, so that the following feed-forward part could process it. The first convolutional layer requires a specification of the input shape, corresponding to the shape of each image.
Since it's a multiclass classification tasks, softmax activation must be placed at the output layer in order to transform the Network's output into a probability distribution over the ten target categories.
```
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten, Dense, BatchNormalization, Dropout
from tensorflow.keras.activations import relu, elu, softmax
CNN = Sequential([
Conv2D(32, kernel_size = (3, 3), activation = elu,
kernel_initializer = 'he_normal', input_shape = (28, 28, 1)),
MaxPool2D((2, 2)),
Conv2D(64, kernel_size = (3, 3), kernel_initializer = 'he_normal', activation = elu),
BatchNormalization(),
Conv2D(128, kernel_size = (3, 3), kernel_initializer = 'he_normal', activation = elu),
BatchNormalization(),
Dropout(0.2),
Flatten(),
Dense(400, activation = elu),
BatchNormalization(),
Dropout(0.2),
Dense(400, activation = elu),
BatchNormalization(),
Dropout(0.2),
Dense(10, activation = softmax)
])
CNN.summary()
```
# 2. Training with Mini Batch Gradient Descent
The training part is no different from mini batch gradient descent training of feed-forward classifiers. I wrote [a Notebook on this technique](https://github.com/IvanBongiorni/TensorFlow2.0_Tutorial/blob/master/TensorFlow2.0_02_MiniBatch_Gradient_Descent.ipynb) in which I explain it in more detail.
Assuming you already know how it works, I will define a function to fetch mini batches into the Network and process with training in eager execution.
```
@tf.function
def fetch_batch(X, y, batch_size, epoch):
start = epoch*batch_size
X_batch = X[start:start+batch_size, :, :]
y_batch = y[start:start+batch_size, :]
return X_batch, y_batch
# To measure execution time
import time
start = time.time()
```
There is one big difference with respect to previous training exercises. Since this Network has a high number of parameters (approx 4.4 million) it will require comparatively longer training times. For this reason, I will measure training not just in *epochs*, but also in *cycles*.
At each training cycle, I will shuffle the dataset and feed it into the Network in mini batches until it's completed. At the following cycle, I will reshuffle the data using a different random seed and repeat the process. (What I called cycles are nothing but Keras' "epochs".)
Using 50 cycles and batches of size 120 on a 60.000 images dataset, I will be able to train my CNN for an overall number of 25.000 epochs.
```
from tensorflow.keras.losses import CategoricalCrossentropy
from tensorflow.keras.metrics import CategoricalAccuracy
loss = tf.keras.losses.CategoricalCrossentropy()
accuracy = tf.keras.metrics.CategoricalAccuracy()
optimizer = tf.optimizers.Adam(learning_rate = 0.0001)
### TRAINING
cycles = 50
batch_size = 120
loss_history = []
accuracy_history = []
for cycle in range(cycles):
df, label = shuffle(df, label, random_state = cycle**2)
for epoch in range(len(df) // batch_size):
X_batch, y_batch = fetch_batch(df, label, batch_size, epoch)
with tf.GradientTape() as tape:
current_loss = loss(CNN(X_batch), y_batch)
gradients = tape.gradient(current_loss, CNN.trainable_variables)
optimizer.apply_gradients(zip(gradients, CNN.trainable_variables))
loss_history.append(current_loss.numpy())
current_accuracy = accuracy(CNN(X_batch), y_batch).numpy()
accuracy_history.append(current_accuracy)
accuracy.reset_states()
print(str(cycle + 1) + '.\tTraining Loss: ' + str(current_loss.numpy())
+ ',\tAccuracy: ' + str(current_accuracy))
#
print('\nTraining complete.')
print('Final Loss: ' + str(current_loss.numpy()) + '. Final accuracy: ' + str(current_accuracy))
end = time.time()
print(end - start) # around 3.5 hours :(
plt.figure(figsize = (15, 4)) # adjust figures size
plt.subplots_adjust(wspace=0.2) # adjust distance
from scipy.signal import savgol_filter
# loss plot
plt.subplot(1, 2, 1)
plt.plot(loss_history)
plt.plot(savgol_filter(loss_history, len(loss_history)//3, 3))
plt.title('Loss')
plt.xlabel('epochs')
plt.ylabel('Categorical Cross-Entropy')
# accuracy plot
plt.subplot(1, 2, 2)
plt.plot(accuracy_history)
plt.plot(savgol_filter(accuracy_history, len(loss_history)//3, 3))
plt.title('Accuracy')
plt.xlabel('epochs')
plt.ylabel('Accuracy')
plt.show()
```
# 3. Test
Let's now test the model on the Test set. I will repeat the dataprep part on it:
```
# Dataprep Test data
test = pd.read_csv('fashion-mnist_test.csv')
test_label = pd.get_dummies(test.label)
test_label = test_label.values
test_label = test_label.astype(np.float32)
test.drop('label', axis = 1, inplace = True)
test = test.values
test = test.astype(np.float32)
test = test / 255.
test = test.reshape((len(test), 28, 28, 1))
prediction = CNN.predict(test)
prediction = np.argmax(prediction, axis=1)
test_label = np.argmax(test_label, axis=1) # reverse one-hot encoding
from sklearn.metrics import confusion_matrix
CM = confusion_matrix(prediction, test_label)
print(CM)
print('\nTest Accuracy: ' + str(np.sum(np.diag(CM)) / np.sum(CM)))
seaborn.heatmap(CM, annot=True)
plt.show()
```
My Convolutional Neural Network classified 91.7% of Test data correctly. The confusion matrix showed that category no. 6 (Shirt) has been misclassified the most. The next goal is to correct it; one possible solution would be to increase regularization, another to build an ensemble of models.
Thanks for coming thus far. In the next Notebooks I will implement more advanced Convolutional models, among other things.
| github_jupyter |
# quant-econ Solutions: Modeling Career Choice
Solutions for http://quant-econ.net/py/career.html
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from quantecon import DiscreteRV, compute_fixed_point
from career import CareerWorkerProblem
```
## Exercise 1
Simulate job / career paths.
In reading the code, recall that `optimal_policy[i, j]` = policy at
$(\theta_i, \epsilon_j)$ = either 1, 2 or 3; meaning 'stay put', 'new job' and
'new life'.
```
wp = CareerWorkerProblem()
v_init = np.ones((wp.N, wp.N))*100
v = compute_fixed_point(wp.bellman_operator, v_init, verbose=False)
optimal_policy = wp.get_greedy(v)
F = DiscreteRV(wp.F_probs)
G = DiscreteRV(wp.G_probs)
def gen_path(T=20):
i = j = 0
theta_index = []
epsilon_index = []
for t in range(T):
if optimal_policy[i, j] == 1: # Stay put
pass
elif optimal_policy[i, j] == 2: # New job
j = int(G.draw())
else: # New life
i, j = int(F.draw()), int(G.draw())
theta_index.append(i)
epsilon_index.append(j)
return wp.theta[theta_index], wp.epsilon[epsilon_index]
theta_path, epsilon_path = gen_path()
fig, axes = plt.subplots(2, 1, figsize=(10, 8))
for ax in axes:
ax.plot(epsilon_path, label='epsilon')
ax.plot(theta_path, label='theta')
ax.legend(loc='lower right')
plt.show()
```
## Exercise 2
The median for the original parameterization can be computed as follows
```
wp = CareerWorkerProblem()
v_init = np.ones((wp.N, wp.N))*100
v = compute_fixed_point(wp.bellman_operator, v_init)
optimal_policy = wp.get_greedy(v)
F = DiscreteRV(wp.F_probs)
G = DiscreteRV(wp.G_probs)
def gen_first_passage_time():
t = 0
i = j = 0
while 1:
if optimal_policy[i, j] == 1: # Stay put
return t
elif optimal_policy[i, j] == 2: # New job
j = int(G.draw())
else: # New life
i, j = int(F.draw()), int(G.draw())
t += 1
M = 25000 # Number of samples
samples = np.empty(M)
for i in range(M):
samples[i] = gen_first_passage_time()
print(np.median(samples))
```
To compute the median with $\beta=0.99$ instead of the default value $\beta=0.95$,
replace `wp = CareerWorkerProblem()` with `wp = CareerWorkerProblem(beta=0.99)`
The medians are subject to randomness, but should be about 7 and 11
respectively. Not surprisingly, more patient workers will wait longer to settle down to their final job
## Exercise 3
Here’s the code to reproduce the original figure
```
from matplotlib import cm
wp = CareerWorkerProblem()
v_init = np.ones((wp.N, wp.N))*100
v = compute_fixed_point(wp.bellman_operator, v_init)
optimal_policy = wp.get_greedy(v)
fig, ax = plt.subplots(figsize=(6,6))
tg, eg = np.meshgrid(wp.theta, wp.epsilon)
lvls=(0.5, 1.5, 2.5, 3.5)
ax.contourf(tg, eg, optimal_policy.T, levels=lvls, cmap=cm.winter, alpha=0.5)
ax.contour(tg, eg, optimal_policy.T, colors='k', levels=lvls, linewidths=2)
ax.set_xlabel('theta', fontsize=14)
ax.set_ylabel('epsilon', fontsize=14)
ax.text(1.8, 2.5, 'new life', fontsize=14)
ax.text(4.5, 2.5, 'new job', fontsize=14, rotation='vertical')
ax.text(4.0, 4.5, 'stay put', fontsize=14)
```
Now we want to set `G_a = G_b = 100` and generate a new figure with these parameters.
To do this replace:
wp = CareerWorkerProblem()
with:
wp = CareerWorkerProblem(G_a=100, G_b=100)
In the new figure, you will see that the region for which the worker will stay put has grown because the distribution for $\epsilon$ has become more concentrated around the mean, making high-paying jobs less realistic
| github_jupyter |
# Regularization
Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that **overfitting can be a serious problem**, if the training dataset is not big enough. Sure it does well on the training set, but the learned network **doesn't generalize to new examples** that it has never seen!
**You will learn to:** Use regularization in your deep learning models.
Let's first import the packages you are going to use.
```
# import packages
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
import sklearn
import sklearn.datasets
import scipy.io
from testCases import *
%matplotlib inline
plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
```
**Problem Statement**: You have just been hired as an AI expert by the French Football Corporation. They would like you to recommend positions where France's goal keeper should kick the ball so that the French team's players can then hit it with their head.
<img src="images/field_kiank.png" style="width:600px;height:350px;">
<caption><center> <u> **Figure 1** </u>: **Football field**<br> The goal keeper kicks the ball in the air, the players of each team are fighting to hit the ball with their head </center></caption>
They give you the following 2D dataset from France's past 10 games.
```
train_X, train_Y, test_X, test_Y = load_2D_dataset()
```
Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head after the French goal keeper has shot the ball from the left side of the football field.
- If the dot is blue, it means the French player managed to hit the ball with his/her head
- If the dot is red, it means the other team's player hit the ball with their head
**Your goal**: Use a deep learning model to find the positions on the field where the goalkeeper should kick the ball.
**Analysis of the dataset**: This dataset is a little noisy, but it looks like a diagonal line separating the upper left half (blue) from the lower right half (red) would work well.
You will first try a non-regularized model. Then you'll learn how to regularize it and decide which model you will choose to solve the French Football Corporation's problem.
## 1 - Non-regularized model
You will use the following neural network (already implemented for you below). This model can be used:
- in *regularization mode* -- by setting the `lambd` input to a non-zero value. We use "`lambd`" instead of "`lambda`" because "`lambda`" is a reserved keyword in Python.
- in *dropout mode* -- by setting the `keep_prob` to a value less than one
You will first try the model without any regularization. Then, you will implement:
- *L2 regularization* -- functions: "`compute_cost_with_regularization()`" and "`backward_propagation_with_regularization()`"
- *Dropout* -- functions: "`forward_propagation_with_dropout()`" and "`backward_propagation_with_dropout()`"
In each part, you will run this model with the correct inputs so that it calls the functions you've implemented. Take a look at the code below to familiarize yourself with the model.
```
def model(X, Y, learning_rate = 0.3, num_iterations = 30000, print_cost = True, lambd = 0, keep_prob = 1):
"""
Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (output size, number of examples)
learning_rate -- learning rate of the optimization
num_iterations -- number of iterations of the optimization loop
print_cost -- If True, print the cost every 10000 iterations
lambd -- regularization hyperparameter, scalar
keep_prob - probability of keeping a neuron active during drop-out, scalar.
Returns:
parameters -- parameters learned by the model. They can then be used to predict.
"""
grads = {}
costs = [] # to keep track of the cost
m = X.shape[1] # number of examples
layers_dims = [X.shape[0], 20, 3, 1]
# Initialize parameters dictionary.
parameters = initialize_parameters(layers_dims)
# Loop (gradient descent)
for i in range(0, num_iterations):
# Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID.
if keep_prob == 1:
a3, cache = forward_propagation(X, parameters)
elif keep_prob < 1:
a3, cache = forward_propagation_with_dropout(X, parameters, keep_prob)
# Cost function
if lambd == 0:
cost = compute_cost(a3, Y)
else:
cost = compute_cost_with_regularization(a3, Y, parameters, lambd)
# Backward propagation.
assert(lambd==0 or keep_prob==1) # it is possible to use both L2 regularization and dropout,
# but this assignment will only explore one at a time
if lambd == 0 and keep_prob == 1:
grads = backward_propagation(X, Y, cache)
elif lambd != 0:
grads = backward_propagation_with_regularization(X, Y, cache, lambd)
elif keep_prob < 1:
grads = backward_propagation_with_dropout(X, Y, cache, keep_prob)
# Update parameters.
parameters = update_parameters(parameters, grads, learning_rate)
# Print the loss every 10000 iterations
if print_cost and i % 10000 == 0:
print("Cost after iteration {}: {}".format(i, cost))
if print_cost and i % 1000 == 0:
costs.append(cost)
# plot the cost
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (x1,000)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
```
Let's train the model without any regularization, and observe the accuracy on the train/test sets.
```
parameters = model(train_X, train_Y)
print ("On the training set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters)
```
The train accuracy is 94.8% while the test accuracy is 91.5%. This is the **baseline model** (you will observe the impact of regularization on this model). Run the following code to plot the decision boundary of your model.
```
plt.title("Model without regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
```
The non-regularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting.
## 2 - L2 Regularization
The standard way to avoid overfitting is called **L2 regularization**. It consists of appropriately modifying your cost function, from:
$$J = -\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} \tag{1}$$
To:
$$J_{regularized} = \small \underbrace{-\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} }_\text{cross-entropy cost} + \underbrace{\frac{1}{m} \frac{\lambda}{2} \sum\limits_l\sum\limits_k\sum\limits_j W_{k,j}^{[l]2} }_\text{L2 regularization cost} \tag{2}$$
Let's modify your cost and observe the consequences.
**Exercise**: Implement `compute_cost_with_regularization()` which computes the cost given by formula (2). To calculate $\sum\limits_k\sum\limits_j W_{k,j}^{[l]2}$ , use :
```python
np.sum(np.square(Wl))
```
Note that you have to do this for $W^{[1]}$, $W^{[2]}$ and $W^{[3]}$, then sum the three terms and multiply by $ \frac{1}{m} \frac{\lambda}{2} $.
```
# GRADED FUNCTION: compute_cost_with_regularization
def compute_cost_with_regularization(A3, Y, parameters, lambd):
"""
Implement the cost function with L2 regularization. See formula (2) above.
Arguments:
A3 -- post-activation, output of forward propagation, of shape (output size, number of examples)
Y -- "true" labels vector, of shape (output size, number of examples)
parameters -- python dictionary containing parameters of the model
Returns:
cost - value of the regularized loss function (formula (2))
"""
m = Y.shape[1]
W1 = parameters["W1"]
W2 = parameters["W2"]
W3 = parameters["W3"]
cross_entropy_cost = compute_cost(A3, Y) # This gives you the cross-entropy part of the cost
### START CODE HERE ### (approx. 1 line)
L2_regularization_cost = (lambd/(2*m)) * (np.sum(np.square(W1)) + np.sum(np.square(W2)) + np.sum(np.square(W3)))
### END CODER HERE ###
cost = cross_entropy_cost + L2_regularization_cost
return cost
A3, Y_assess, parameters = compute_cost_with_regularization_test_case()
print("cost = " + str(compute_cost_with_regularization(A3, Y_assess, parameters, lambd = 0.1)))
```
**Expected Output**:
<table>
<tr>
<td>
**cost**
</td>
<td>
1.78648594516
</td>
</tr>
</table>
Of course, because you changed the cost, you have to change backward propagation as well! All the gradients have to be computed with respect to this new cost.
**Exercise**: Implement the changes needed in backward propagation to take into account regularization. The changes only concern dW1, dW2 and dW3. For each, you have to add the regularization term's gradient ($\frac{d}{dW} ( \frac{1}{2}\frac{\lambda}{m} W^2) = \frac{\lambda}{m} W$).
```
# GRADED FUNCTION: backward_propagation_with_regularization
def backward_propagation_with_regularization(X, Y, cache, lambd):
"""
Implements the backward propagation of our baseline model to which we added an L2 regularization.
Arguments:
X -- input dataset, of shape (input size, number of examples)
Y -- "true" labels vector, of shape (output size, number of examples)
cache -- cache output from forward_propagation()
lambd -- regularization hyperparameter, scalar
Returns:
gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
"""
m = X.shape[1]
(Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache
dZ3 = A3 - Y
### START CODE HERE ### (approx. 1 line)
dW3 = 1./m * np.dot(dZ3, A2.T) + lambd/m * W3
### END CODE HERE ###
db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)
dA2 = np.dot(W3.T, dZ3)
dZ2 = np.multiply(dA2, np.int64(A2 > 0))
### START CODE HERE ### (approx. 1 line)
dW2 = 1./m * np.dot(dZ2, A1.T) + lambd/m * W2
### END CODE HERE ###
db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)
dA1 = np.dot(W2.T, dZ2)
dZ1 = np.multiply(dA1, np.int64(A1 > 0))
### START CODE HERE ### (approx. 1 line)
dW1 = 1./m * np.dot(dZ1, X.T) + lambd/m * W1
### END CODE HERE ###
db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)
gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2,
"dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1,
"dZ1": dZ1, "dW1": dW1, "db1": db1}
return gradients
X_assess, Y_assess, cache = backward_propagation_with_regularization_test_case()
grads = backward_propagation_with_regularization(X_assess, Y_assess, cache, lambd = 0.7)
print ("dW1 = "+ str(grads["dW1"]))
print ("dW2 = "+ str(grads["dW2"]))
print ("dW3 = "+ str(grads["dW3"]))
```
**Expected Output**:
<table>
<tr>
<td>
**dW1**
</td>
<td>
[[-0.25604646 0.12298827 -0.28297129]
[-0.17706303 0.34536094 -0.4410571 ]]
</td>
</tr>
<tr>
<td>
**dW2**
</td>
<td>
[[ 0.79276486 0.85133918]
[-0.0957219 -0.01720463]
[-0.13100772 -0.03750433]]
</td>
</tr>
<tr>
<td>
**dW3**
</td>
<td>
[[-1.77691347 -0.11832879 -0.09397446]]
</td>
</tr>
</table>
Let's now run the model with L2 regularization $(\lambda = 0.7)$. The `model()` function will call:
- `compute_cost_with_regularization` instead of `compute_cost`
- `backward_propagation_with_regularization` instead of `backward_propagation`
```
parameters = model(train_X, train_Y, lambd = 0.7)
print ("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters)
```
Congrats, the test set accuracy increased to 93%. You have saved the French football team!
You are not overfitting the training data anymore. Let's plot the decision boundary.
```
plt.title("Model with L2-regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
```
**Observations**:
- The value of $\lambda$ is a hyperparameter that you can tune using a dev set.
- L2 regularization makes your decision boundary smoother. If $\lambda$ is too large, it is also possible to "oversmooth", resulting in a model with high bias.
**What is L2-regularization actually doing?**:
L2-regularization relies on the assumption that a model with small weights is simpler than a model with large weights. Thus, by penalizing the square values of the weights in the cost function you drive all the weights to smaller values. It becomes too costly for the cost to have large weights! This leads to a smoother model in which the output changes more slowly as the input changes.
<font color='blue'>
**What you should remember** -- the implications of L2-regularization on:
- The cost computation:
- A regularization term is added to the cost
- The backpropagation function:
- There are extra terms in the gradients with respect to weight matrices
- Weights end up smaller ("weight decay"):
- Weights are pushed to smaller values.
## 3 - Dropout
Finally, **dropout** is a widely used regularization technique that is specific to deep learning.
**It randomly shuts down some neurons in each iteration.** Watch these two videos to see what this means!
<!--
To understand drop-out, consider this conversation with a friend:
- Friend: "Why do you need all these neurons to train your network and classify images?".
- You: "Because each neuron contains a weight and can learn specific features/details/shape of an image. The more neurons I have, the more featurse my model learns!"
- Friend: "I see, but are you sure that your neurons are learning different features and not all the same features?"
- You: "Good point... Neurons in the same layer actually don't talk to each other. It should be definitly possible that they learn the same image features/shapes/forms/details... which would be redundant. There should be a solution."
!-->
<center>
<video width="620" height="440" src="images/dropout1_kiank.mp4" type="video/mp4" controls>
</video>
</center>
<br>
<caption><center> <u> Figure 2 </u>: Drop-out on the second hidden layer. <br> At each iteration, you shut down (= set to zero) each neuron of a layer with probability $1 - keep\_prob$ or keep it with probability $keep\_prob$ (50% here). The dropped neurons don't contribute to the training in both the forward and backward propagations of the iteration. </center></caption>
<center>
<video width="620" height="440" src="images/dropout2_kiank.mp4" type="video/mp4" controls>
</video>
</center>
<caption><center> <u> Figure 3 </u>: Drop-out on the first and third hidden layers. <br> $1^{st}$ layer: we shut down on average 40% of the neurons. $3^{rd}$ layer: we shut down on average 20% of the neurons. </center></caption>
When you shut some neurons down, you actually modify your model. The idea behind drop-out is that at each iteration, you train a different model that uses only a subset of your neurons. With dropout, your neurons thus become less sensitive to the activation of one other specific neuron, because that other neuron might be shut down at any time.
### 3.1 - Forward propagation with dropout
**Exercise**: Implement the forward propagation with dropout. You are using a 3 layer neural network, and will add dropout to the first and second hidden layers. We will not apply dropout to the input layer or output layer.
**Instructions**:
You would like to shut down some neurons in the first and second layers. To do that, you are going to carry out 4 Steps:
1. In lecture, we dicussed creating a variable $d^{[1]}$ with the same shape as $a^{[1]}$ using `np.random.rand()` to randomly get numbers between 0 and 1. Here, you will use a vectorized implementation, so create a random matrix $D^{[1]} = [d^{[1](1)} d^{[1](2)} ... d^{[1](m)}] $ of the same dimension as $A^{[1]}$.
2. Set each entry of $D^{[1]}$ to be 0 with probability (`1-keep_prob`) or 1 with probability (`keep_prob`), by thresholding values in $D^{[1]}$ appropriately. Hint: to set all the entries of a matrix X to 0 (if entry is less than 0.5) or 1 (if entry is more than 0.5) you would do: `X = (X < 0.5)`. Note that 0 and 1 are respectively equivalent to False and True.
3. Set $A^{[1]}$ to $A^{[1]} * D^{[1]}$. (You are shutting down some neurons). You can think of $D^{[1]}$ as a mask, so that when it is multiplied with another matrix, it shuts down some of the values.
4. Divide $A^{[1]}$ by `keep_prob`. By doing this you are assuring that the result of the cost will still have the same expected value as without drop-out. (This technique is also called inverted dropout.)
```
# GRADED FUNCTION: forward_propagation_with_dropout
def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5):
"""
Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
Arguments:
X -- input dataset, of shape (2, number of examples)
parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":
W1 -- weight matrix of shape (20, 2)
b1 -- bias vector of shape (20, 1)
W2 -- weight matrix of shape (3, 20)
b2 -- bias vector of shape (3, 1)
W3 -- weight matrix of shape (1, 3)
b3 -- bias vector of shape (1, 1)
keep_prob - probability of keeping a neuron active during drop-out, scalar
Returns:
A3 -- last activation value, output of the forward propagation, of shape (1,1)
cache -- tuple, information stored for computing the backward propagation
"""
np.random.seed(1)
# retrieve parameters
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
W3 = parameters["W3"]
b3 = parameters["b3"]
# LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID
Z1 = np.dot(W1, X) + b1
A1 = relu(Z1)
### START CODE HERE ### (approx. 4 lines) # Steps 1-4 below correspond to the Steps 1-4 described above.
D1 = np.random.rand(A1.shape[0], A1.shape[1]) # Step 1: initialize matrix D1 = np.random.rand(..., ...)
D1 = D1 < keep_prob # Step 2: convert entries of D1 to 0 or 1 (using keep_prob as the threshold)
A1 = A1*D1 # Step 3: shut down some neurons of A1
A1 = A1/keep_prob # Step 4: scale the value of neurons that haven't been shut down
### END CODE HERE ###
Z2 = np.dot(W2, A1) + b2
A2 = relu(Z2)
### START CODE HERE ### (approx. 4 lines)
D2 = np.random.rand(A2.shape[0],A2.shape[1]) # Step 1: initialize matrix D2 = np.random.rand(..., ...)
D2 = (D2 < keep_prob)
# Step 2: convert entries of D2 to 0 or 1 (using keep_prob as the threshold)
A2 = A2*D2 # Step 3: shut down some neurons of A2
A2 = A2/keep_prob # Step 4: scale the value of neurons that haven't been shut down
### END CODE HERE ###
Z3 = np.dot(W3, A2) + b3
A3 = sigmoid(Z3)
cache = (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3)
return A3, cache
X_assess, parameters = forward_propagation_with_dropout_test_case()
A3, cache = forward_propagation_with_dropout(X_assess, parameters, keep_prob = 0.7)
print ("A3 = " + str(A3))
```
**Expected Output**:
<table>
<tr>
<td>
**A3**
</td>
<td>
[[ 0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]
</td>
</tr>
</table>
### 3.2 - Backward propagation with dropout
**Exercise**: Implement the backward propagation with dropout. As before, you are training a 3 layer network. Add dropout to the first and second hidden layers, using the masks $D^{[1]}$ and $D^{[2]}$ stored in the cache.
**Instruction**:
Backpropagation with dropout is actually quite easy. You will have to carry out 2 Steps:
1. You had previously shut down some neurons during forward propagation, by applying a mask $D^{[1]}$ to `A1`. In backpropagation, you will have to shut down the same neurons, by reapplying the same mask $D^{[1]}$ to `dA1`.
2. During forward propagation, you had divided `A1` by `keep_prob`. In backpropagation, you'll therefore have to divide `dA1` by `keep_prob` again (the calculus interpretation is that if $A^{[1]}$ is scaled by `keep_prob`, then its derivative $dA^{[1]}$ is also scaled by the same `keep_prob`).
```
# GRADED FUNCTION: backward_propagation_with_dropout
def backward_propagation_with_dropout(X, Y, cache, keep_prob):
"""
Implements the backward propagation of our baseline model to which we added dropout.
Arguments:
X -- input dataset, of shape (2, number of examples)
Y -- "true" labels vector, of shape (output size, number of examples)
cache -- cache output from forward_propagation_with_dropout()
keep_prob - probability of keeping a neuron active during drop-out, scalar
Returns:
gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
"""
m = X.shape[1]
(Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3) = cache
dZ3 = A3 - Y
dW3 = 1./m * np.dot(dZ3, A2.T)
db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)
dA2 = np.dot(W3.T, dZ3)
### START CODE HERE ### (≈ 2 lines of code)
dA2 = dA2*D2 # Step 1: Apply mask D2 to shut down the same neurons as during the forward propagation
dA2 = dA2/keep_prob # Step 2: Scale the value of neurons that haven't been shut down
### END CODE HERE ###
dZ2 = np.multiply(dA2, np.int64(A2 > 0))
dW2 = 1./m * np.dot(dZ2, A1.T)
db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)
dA1 = np.dot(W2.T, dZ2)
### START CODE HERE ### (≈ 2 lines of code)
dA1 = dA1*D1 # Step 1: Apply mask D1 to shut down the same neurons as during the forward propagation
dA1 = dA1/keep_prob # Step 2: Scale the value of neurons that haven't been shut down
### END CODE HERE ###
dZ1 = np.multiply(dA1, np.int64(A1 > 0))
dW1 = 1./m * np.dot(dZ1, X.T)
db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)
gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2,
"dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1,
"dZ1": dZ1, "dW1": dW1, "db1": db1}
return gradients
X_assess, Y_assess, cache = backward_propagation_with_dropout_test_case()
gradients = backward_propagation_with_dropout(X_assess, Y_assess, cache, keep_prob = 0.8)
print ("dA1 = " + str(gradients["dA1"]))
print ("dA2 = " + str(gradients["dA2"]))
```
**Expected Output**:
<table>
<tr>
<td>
**dA1**
</td>
<td>
[[ 0.36544439 0. -0.00188233 0. -0.17408748]
[ 0.65515713 0. -0.00337459 0. -0. ]]
</td>
</tr>
<tr>
<td>
**dA2**
</td>
<td>
[[ 0.58180856 0. -0.00299679 0. -0.27715731]
[ 0. 0.53159854 -0. 0.53159854 -0.34089673]
[ 0. 0. -0.00292733 0. -0. ]]
</td>
</tr>
</table>
Let's now run the model with dropout (`keep_prob = 0.86`). It means at every iteration you shut down each neurons of layer 1 and 2 with 24% probability. The function `model()` will now call:
- `forward_propagation_with_dropout` instead of `forward_propagation`.
- `backward_propagation_with_dropout` instead of `backward_propagation`.
```
parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3)
print ("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters)
```
Dropout works great! The test accuracy has increased again (to 95%)! Your model is not overfitting the training set and does a great job on the test set. The French football team will be forever grateful to you!
Run the code below to plot the decision boundary.
```
plt.title("Model with dropout")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
```
**Note**:
- A **common mistake** when using dropout is to use it both in training and testing. You should use dropout (randomly eliminate nodes) only in training.
- Deep learning frameworks like [tensorflow](https://www.tensorflow.org/api_docs/python/tf/nn/dropout), [PaddlePaddle](http://doc.paddlepaddle.org/release_doc/0.9.0/doc/ui/api/trainer_config_helpers/attrs.html), [keras](https://keras.io/layers/core/#dropout) or [caffe](http://caffe.berkeleyvision.org/tutorial/layers/dropout.html) come with a dropout layer implementation. Don't stress - you will soon learn some of these frameworks.
<font color='blue'>
**What you should remember about dropout:**
- Dropout is a regularization technique.
- You only use dropout during training. Don't use dropout (randomly eliminate nodes) during test time.
- Apply dropout both during forward and backward propagation.
- During training time, divide each dropout layer by keep_prob to keep the same expected value for the activations. For example, if keep_prob is 0.5, then we will on average shut down half the nodes, so the output will be scaled by 0.5 since only the remaining half are contributing to the solution. Dividing by 0.5 is equivalent to multiplying by 2. Hence, the output now has the same expected value. You can check that this works even when keep_prob is other values than 0.5.
## 4 - Conclusions
**Here are the results of our three models**:
<table>
<tr>
<td>
**model**
</td>
<td>
**train accuracy**
</td>
<td>
**test accuracy**
</td>
</tr>
<td>
3-layer NN without regularization
</td>
<td>
95%
</td>
<td>
91.5%
</td>
<tr>
<td>
3-layer NN with L2-regularization
</td>
<td>
94%
</td>
<td>
93%
</td>
</tr>
<tr>
<td>
3-layer NN with dropout
</td>
<td>
93%
</td>
<td>
95%
</td>
</tr>
</table>
Note that regularization hurts training set performance! This is because it limits the ability of the network to overfit to the training set. But since it ultimately gives better test accuracy, it is helping your system.
Congratulations for finishing this assignment! And also for revolutionizing French football. :-)
<font color='blue'>
**What we want you to remember from this notebook**:
- Regularization will help you reduce overfitting.
- Regularization will drive your weights to lower values.
- L2 regularization and Dropout are two very effective regularization techniques.
| github_jupyter |
# Table of Contents
* [1c. Fixed flux spinodal decomposition on a T shaped domain](#1c.-Fixed-flux-spinodal-decomposition-on-a-T-shaped-domain)
* [Use Binder For Live Examples](#Use-Binder-For-Live-Examples)
* [Define $f_0$](#Define-$f_0$)
* [Define the Equation](#Define-the-Equation)
* [Solve the Equation](#Solve-the-Equation)
* [Run the Example Locally](#Run-the-Example-Locally)
* [Movie of Evolution](#Movie-of-Evolution)
# 1c. Fixed flux spinodal decomposition on a T shaped domain
## Use Binder For Live Examples
[](http://mybinder.org/repo/wd15/fipy-hackathon1)
The free energy is 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 $$
In FiPy we write the evolution equation as
$$ \frac{\partial c}{\partial t} = \nabla \cdot \left[
D \left( c \right) \left( \frac{ \partial^2 f_0 }{ \partial c^2} \nabla c - \kappa \nabla \nabla^2 c \right)
\right] $$
Let's start by calculating $ \frac{ \partial^2 f_0 }{ \partial c^2} $ using sympy. It's easy for this case, but useful in the general case for taking care of difficult book keeping in phase field problems.
```
%matplotlib inline
import sympy
import fipy as fp
import numpy as np
A, c, c_m, B, c_alpha, c_beta = sympy.symbols("A c_var c_m B c_alpha c_beta")
f_0 = - A / 2 * (c - c_m)**2 + B / 4 * (c - c_m)**4 + c_alpha / 4 * (c - c_alpha)**4 + c_beta / 4 * (c - c_beta)**4
print f_0
sympy.diff(f_0, c, 2)
```
The first step in implementing any problem in FiPy is to define the mesh. For [Problem 1a]({{ site.baseurl }}/hackathons/hackathon1/problems.ipynb/#1.a-Square-Periodic) the solution domain is just a square domain, but the boundary conditions are periodic, so a `PeriodicGrid2D` object is used. No other boundary conditions are required.
```
mesh = fp.Grid2D(dx=0.5, dy=0.5, nx=40, ny=200) + (fp.Grid2D(dx=0.5, dy=0.5, nx=200, ny=40) + [[-40],[100]])
```
The next step is to define the parameters and create a solution variable.
```
c_alpha = 0.05
c_beta = 0.95
A = 2.0
kappa = 2.0
c_m = (c_alpha + c_beta) / 2.
B = A / (c_alpha - c_m)**2
D = D_alpha = D_beta = 2. / (c_beta - c_alpha)
c_0 = 0.45
q = np.sqrt((2., 3.))
epsilon = 0.01
c_var = fp.CellVariable(mesh=mesh, name=r"$c$", hasOld=True)
```
Now we need to define the initial conditions given by,
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) $$
```
r = np.array((mesh.x, mesh.y))
c_var[:] = c_0 + epsilon * np.cos((q[:, None] * r).sum(0))
viewer = fp.Viewer(c_var)
```
## Define $f_0$
To define the equation with FiPy first define `f_0` in terms of FiPy. Recall `f_0` from above calculated using Sympy. Here we use the string representation and set it equal to `f_0_var` using the `exec` command.
```
out = sympy.diff(f_0, c, 2)
exec "f_0_var = " + repr(out)
#f_0_var = -A + 3*B*(c_var - c_m)**2 + 3*c_alpha*(c_var - c_alpha)**2 + 3*c_beta*(c_var - c_beta)**2
f_0_var
```
## Define the Equation
```
eqn = fp.TransientTerm(coeff=1.) == fp.DiffusionTerm(D * f_0_var) - fp.DiffusionTerm((D, kappa))
eqn
```
## Solve the Equation
To solve the equation a simple time stepping scheme is used which is decreased or increased based on whether the residual decreases or increases. A time step is recalculated if the required tolerance is not reached.
```
elapsed = 0.0
steps = 0
dt = 0.01
total_sweeps = 2
tolerance = 1e-1
total_steps = 10
c_var[:] = c_0 + epsilon * np.cos((q[:, None] * r).sum(0))
c_var.updateOld()
from fipy.solvers.pysparse import LinearLUSolver as Solver
solver = Solver()
while steps < total_steps:
res0 = eqn.sweep(c_var, dt=dt, solver=solver)
for sweeps in range(total_sweeps):
res = eqn.sweep(c_var, dt=dt, solver=solver)
if res < res0 * tolerance:
steps += 1
elapsed += dt
dt *= 1.1
c_var.updateOld()
else:
dt *= 0.8
c_var[:] = c_var.old
viewer.plot()
print 'elapsed_time:',elapsed
```
## Run the Example Locally
The following cell will dumpy a file called `fipy_hackathon1c.py` to the local file system to be run. The images are saved out at each time step.
```
%%writefile fipy_hackathon_1c.py
import fipy as fp
import numpy as np
mesh = fp.Grid2D(dx=0.5, dy=0.5, nx=40, ny=200) + (fp.Grid2D(dx=0.5, dy=0.5, nx=200, ny=40) + [[-40],[100]])
c_alpha = 0.05
c_beta = 0.95
A = 2.0
kappa = 2.0
c_m = (c_alpha + c_beta) / 2.
B = A / (c_alpha - c_m)**2
D = D_alpha = D_beta = 2. / (c_beta - c_alpha)
c_0 = 0.45
q = np.sqrt((2., 3.))
epsilon = 0.01
c_var = fp.CellVariable(mesh=mesh, name=r"$c$", hasOld=True)
r = np.array((mesh.x, mesh.y))
c_var[:] = c_0 + epsilon * np.cos((q[:, None] * r).sum(0))
f_0_var = -A + 3*B*(c_var - c_m)**2 + 3*c_alpha*(c_var - c_alpha)**2 + 3*c_beta*(c_var - c_beta)**2
eqn = fp.TransientTerm(coeff=1.) == fp.DiffusionTerm(D * f_0_var) - fp.DiffusionTerm((D, kappa))
elapsed = 0.0
steps = 0
dt = 0.01
total_sweeps = 2
tolerance = 1e-1
total_steps = 600
c_var[:] = c_0 + epsilon * np.cos((q[:, None] * r).sum(0))
c_var.updateOld()
from fipy.solvers.pysparse import LinearLUSolver as Solver
solver = Solver()
viewer = fp.Viewer(c_var)
while steps < total_steps:
res0 = eqn.sweep(c_var, dt=dt, solver=solver)
for sweeps in range(total_sweeps):
res = eqn.sweep(c_var, dt=dt, solver=solver)
print ' '
print 'steps',steps
print 'res',res
print 'sweeps',sweeps
print 'dt',dt
if res < res0 * tolerance:
steps += 1
elapsed += dt
dt *= 1.1
if steps % 1 == 0:
viewer.plot('image{0}.png'.format(steps))
c_var.updateOld()
else:
dt *= 0.8
c_var[:] = c_var.old
```
## Movie of Evolution
The movie of the evolution for 600 steps.
The movie was generated with the output files of the form `image*.png` using the following commands,
$ rename 's/\d+/sprintf("%05d",$&)/e' image*
$ ffmpeg -f image2 -r 6 -i 'image%05d.png' output.mp4
```
from IPython.display import YouTubeVideo
scale = 1.5
YouTubeVideo('aZk38E7OxcQ', width=420 * scale, height=315 * scale, rel=0)
```
| github_jupyter |
# IMPORTS
```
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
```
# READ THE DATA
```
data = pd.read_csv('./input/laptops.csv', encoding='latin-1')
data.head(10)
```
# MAIN EDA BLOCK
```
print(f'Data Shape\nRows: {data.shape[0]}\nColumns: {data.shape[1]}')
print('=' * 30)
data.info()
data.describe()
data['Product'] = data['Product'].str.split('(').apply(lambda x: x[0])
data['CPu_Speed'] = data['Cpu'].str.split(' ').apply(lambda x: x[-1]).str.replace('GHz', '')
data['Cpu_Vender'] = data['Cpu'].str.split(' ').apply(lambda x: x[0])
data['Cpu_Type'] = data['Cpu'].str.split(' ').apply(lambda x: x[1:4] if x[1]=='Celeron' and 'Pentium' and 'Xeon' else (x[1:3] if (x[1]=='Core' or x[0]=='AMD') else x[0]))
data['Cpu_Type'] = data['Cpu_Type'].apply(lambda x: ' '.join(x))
data['Cpu_Type']
data.head(10)
split_mem = data['Memory'].str.split(' ', 1, expand=True)
data['Storage_Type'] = split_mem[1]
data['Memory'] = split_mem[0]
data['Memory'].unique()
data.head(10)
data['Ram'] = data['Ram'].str.replace('GB', '')
df_mem = data['Memory'].str.split('(\d+)', expand=True)
data['Memory'] = pd.to_numeric(df_mem[1])
data.rename(columns={'Memory': 'Memory (GB or TB)'}, inplace=True)
def mem(x):
if x == 1:
return 1024
elif x == 2:
return 2048
data['Memory (GB or TB)'] = data['Memory (GB or TB)'].apply(lambda x: 1024 if x==1 else x)
data['Memory (GB or TB)'] = data['Memory (GB or TB)'].apply(lambda x: 2048 if x==2 else x)
data.rename(columns={'Memory (GB or TB)': 'Storage (GB)'}, inplace=True)
data.head(10)
data['Weight'] = data['Weight'].str.replace('kg', '')
data.head(10)
gpu_distr_list = data['Gpu'].str.split(' ')
data['Gpu_Vender'] = data['Gpu'].str.split(' ').apply(lambda x: x[0])
data['Gpu_Type'] = data['Gpu'].str.split(' ').apply(lambda x: x[1:])
data['Gpu_Type'] = data['Gpu_Type'].apply(lambda x: ' '.join(x))
data.head(10)
data['Touchscreen'] = data['ScreenResolution'].apply(lambda x: 1 if 'Touchscreen' in x else 0)
data['Ips'] = data['ScreenResolution'].apply(lambda x: 1 if 'IPS' in x else 0)
def cat_os(op_s):
if op_s =='Windows 10' or op_s == 'Windows 7' or op_s == 'Windows 10 S':
return 'Windows'
elif op_s =='macOS' or op_s == 'Mac OS X':
return 'Mac'
else:
return 'Other/No OS/Linux'
data['OpSys'] = data['OpSys'].apply(cat_os)
data = data.reindex(columns=["Company", "TypeName", "Inches", "Touchscreen",
"Ips", "Cpu_Vender", "Cpu_Type","Ram", "Storage (GB)",
"Storage Type", "Gpu_Vender", "Gpu_Type", "Weight", "OpSys", "Price_euros" ])
data.head(10)
data['Ram'] = data['Ram'].astype('int')
data['Storage (GB)'] = data['Storage (GB)'].astype('int')
data['Weight'] = data['Weight'].astype('float')
data.info()
sns.set(rc={'figure.figsize': (9,5)})
data['Company'].value_counts().plot(kind='bar')
sns.barplot(x=data['Company'], y=data['Price_euros'])
data['TypeName'].value_counts().plot(kind='bar')
sns.barplot(x=data['TypeName'], y=data['Price_euros'])
cpu_distr = data['Cpu_Type'].value_counts()[:10].reset_index()
cpu_distr
sns.barplot(x=cpu_distr['index'], y=cpu_distr['Cpu_Type'], hue='Cpu_Vender', data=data)
gpu_distr = data['Gpu_Type'].value_counts()[:10].reset_index()
gpu_distr
sns.barplot(x=gpu_distr['index'], y=gpu_distr['Gpu_Type'], hue='Gpu_Vender', data=data)
sns.barplot(x=data['OpSys'], y=data['Price_euros'])
corr_data = data.corr()
corr_data['Price_euros'].sort_values(ascending=False)
sns.heatmap(data.corr(), annot=True)
X = data.drop(columns=['Price_euros'])
y = np.log(data['Price_euros'])
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=42)
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import r2_score, mean_absolute_error
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, ExtraTreesRegressor
from xgboost import XGBRegressor
from sklearn.ensemble import VotingRegressor, StackingRegressor
step1 = ColumnTransformer(transformers=[
('col_inf', OneHotEncoder(sparse=False, handle_unknown='ignore'), [0,1,5,6,9,10,11,13])
],remainder='passthrough')
rf = RandomForestRegressor(n_estimators=350, random_state=3, max_samples=0.5, max_features=0.75, max_depth=15)
gbdt = GradientBoostingRegressor(n_estimators=100, max_features=0.5)
xgb = XGBRegressor(n_estimators=25, learning_rate=0.3, max_depth=5)
et = ExtraTreesRegressor(n_estimators=100, random_state=3, max_samples=0.5, max_features=0.75, max_depth=10)
step2 = VotingRegressor([('rf', rf), ('gbdt', gbdt), ('xgb', xgb), ('et', et)], weights=[5,1,1,1])
pipe = Pipeline([
('step1', step1),
('step2', step2)])
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
print('R2 score', r2_score(y_test, y_pred))
print('MAE', mean_absolute_error(y_test, y_pred))
```
| github_jupyter |
# Visualizing invasive and non-invasive EEG data
[Liberty Hamilton, PhD](https://csd.utexas.edu/research/hamilton-lab)
Assistant Professor, University of Texas at Austin
Department of Speech, Language, and Hearing Sciences
and Department of Neurology, Dell Medical School
Welcome! In this notebook we will be discussing how to look at time series electrophysiological 🧠 data that is recorded noninvasively at the scalp (scalp electroencephalography or EEG), or invasively in patients who are undergoing surgical treatment for epilepsy (sometimes called intracranial EEG or iEEG, also called stereo EEG/sEEG, or electrocorticography/ECoG).
### Python libraries you will be using in this tutorial:
* MNE-python
* matplotlib
* numpy

MNE-python is open source python software for exploring and analyzing human neurophysiological data (EEG/MEG/iEEG).
### What you will learn to do
* Load some sample EEG data
* Load some sample intracranial EEG data
* Plot the raw EEG data/iEEG data
* Plot the power spectrum of your data
* Epoch data according to specific task conditions (sentences)
* Plot all epochs and averaged evoked activity
* Plot average evoked activity in response to specific task conditions (ERPs)
* Plot by channel as well as averaging across channels
* Plot EEG activity at specific time points on the scalp (topomaps)
* Customize your plots
### Other Resources:
* [MNE-python tutorials](https://mne.tools/stable/auto_tutorials/index.html) -- This has many additional resources above and beyond that also include how to preprocess your data, remove artifacts, and more!
<a id="basics1"></a>
# 1. The basics: loading in your data
```
!pip install matplotlib==3.2
import mne # This is the mne library
import numpy as np # This gives us the power of numpy, which is just generally useful for array manipulation
%matplotlib inline
from matplotlib import pyplot as plt
from matplotlib import cm
datasets = {'ecog': '/home/jovyan/data/we_eeg_viz_data/ecog/sub-S0006/S0006_ecog_hg.fif',
'eeg': '/home/jovyan/data/we_eeg_viz_data/eeg/sub-MT0002/MT0002-eeg.fif'}
event_files = {'ecog': '/home/jovyan/data/we_eeg_viz_data/ecog/sub-S0006/S0006_eve.txt',
'eeg': '/home/jovyan/data/we_eeg_viz_data/eeg/sub-MT0002/MT0002_eve.txt'}
stim_file = '/home/jovyan/data/we_eeg_viz_data/stimulus_list.csv'
# Get some information about the stimuli (here, the names of the sound files that were played)
ev_names=np.genfromtxt(stim_file, skip_header=1, delimiter=',',dtype=np.str, usecols=[1],encoding='utf-8')
ev_nums=np.genfromtxt(stim_file, skip_header=1, delimiter=',',dtype=np.int, usecols=[0], encoding='utf-8')
event_id = dict()
for i, ev_name in enumerate(ev_names):
event_id[ev_name] = ev_nums[i]
```
## 1.1. Choose which dataset to look at (start with EEG)
For the purposes of this tutorial, we'll be looking at some scalp EEG and intracranial EEG datasets from my lab. Participants provided written informed consent for participation in our research. These data were collected from two distinct participants listening to sentences from the [TIMIT acoustic-phonetic corpus](https://catalog.ldc.upenn.edu/LDC93S1). This is a database of English sentences spoken by multiple talkers from throughout the United States, and has been used in speech recognition research, neuroscience research, and more!
The list of stimuli is in the `stimulus_list.csv` file. Each stimulus starts with either a "f" or a "m" to indicate a female or male talker. The rest of the alphanumeric string has to do with other characteristics of the talkers that we won't go into here. The stimulus timings have been provided for you in the event files (ending with the suffix `_eve.txt`. We'll talk about those more later.
### EEG Data
The EEG data was recorded with a 64-channel [BrainVision ActiCHamp](https://www.brainproducts.com/productdetails.php?id=74) system. These data are part of an ongoing project in our lab and are unpublished. You can find similar (larger) datasets from [Broderick et al.](https://datadryad.org/stash/dataset/doi:10.5061/dryad.070jc), or Bradley Voytek's lab has a list of [Open Electrophysiology datasets](https://github.com/openlists/ElectrophysiologyData).
### The ECoG Data
The ECoG data was recorded from 106 electrodes across multiple regions of the brain while our participant listened to TIMIT sentences. This is a smaller subset of sentences than the EEG dataset and so is a bit faster to load. The areas we recorded from are labeled according to a clinical montage. For iEEG and ECoG datasets, these names are rarely standardized, so it can be hard to know exactly what is what without additional information. Here, each channel is named according to the general location of the electrode probe to which it belongs.
| Device | General location |
|---|---|
| RAST | Right anterior superior temporal |
| RMST | Right middle superior temporal |
| RPST | Right posterior superior temporal |
| RPPST | Right posterior parietal/superior temporal |
| RAIF | Right anterior insula |
| RPI | Right posterior insula |
| ROF | Right orbitofrontal |
| RAC | Right anterior cingulate |
```
data_type = 'eeg' # Can choose from 'eeg' or 'ecog'
```
## 1.2. Load the data
This next command loads the data from our fif file of interest. The `preload=True` flag means that the data will be loaded (necessary for some operations). If `preload=False`, you can still perform some aspects of this tutorial, and this is a great option if you have a large dataset and would like to look at some of the header information and metadata before you start to analyze it.
```
raw = mne.io.read_raw_fif(datasets[data_type], preload=True)
```
There is a lot of useful information in the info structure. For example, we can get the sampling frequency (`raw.info['sfreq']`), the channel names (`raw.info['ch_names']`), the channel types and locations (in `raw.info['chs']`), and whether any filtering operations have been performed already (`raw.info['highpass']` and `raw.info['lowpass']` show the cut-offs for the data).
```
print(raw.info)
sampling_freq = raw.info['sfreq']
nchans = raw.info['nchan']
print('The sampling frequency of our data is %d'%(sampling_freq))
print('Here is our list of %d channels: '%nchans)
print(raw.ch_names)
eeg_colors = {'eeg': 'k', 'eog': 'steelblue'}
fig = raw.plot(show=False, color=eeg_colors, scalings='auto');
fig.set_figwidth(8)
fig.set_figheight(4)
```
<a id="plots2"></a>
# 2. Let's make some plots!
MNE-python makes creating some plots *super easy*, which is great for data quality checking, exploration, and eventually manuscript figure generation. For example, one might wish to plot the power spectral density (PSD), which
## 2.2. Power spectral density
```
raw.plot_psd();
```
## 2.3. Sensor positions (for EEG)
For EEG, MNE-python also has convenient functions for showing the location of the sensors used. Here, we have a 64-channel montage. You can also use this information to help interpret some of your plots if you're plotting a single channel or a group of channels.
For ECoG, we will not be plotting sensors in this way. If you would like read more about that process, please see [this tutorial](https://mne.tools/stable/auto_tutorials/misc/plot_ecog.html). You can also check out [Noah Benson's session](https://neurohackademy.org/course/introduction-to-the-geometry-and-structure-of-the-human-brain/) (happening in parallel with this tutorial!) for plotting 3D brains.
```
if data_type == 'eeg':
raw.plot_sensors(kind='topomap',show_names=True);
```
Ok, awesome! So now we know where the sensors are, how densely they tile the space, and what their names are. *Knowledge = Power!*
So what if we wanted to look at the power spectral density plot we saw above by channel? We can use `plot_psd_topo` for that! There are also customizable options for playing with the colors.
```
if data_type == 'eeg':
raw.plot_psd_topo(fig_facecolor='w', axis_facecolor='w', color='k');
```
Finally, this one works for both EEG and ECoG. Here we are looking at the power spectral density plot again, but taking the average across trials and showing +/- 1 standard deviation from the mean across channels.
```
raw.plot_psd(area_mode='std', average=True);
```
Finally, we can plot these same figures using a narrower frequency range, and looking at a smaller set of channels using `picks`. For `plot_psd` and other functions, `picks` is a list of integer indices corresponding to your channels of interest. You can choose these by their number, or you can use the convenient `mne.pick_channels` function to choose them by name. For example, in EEG, we often see strong responses to auditory stimuli at the top of the head, so here we will restrict our EEG channels to a few at the top of the head at the midline. For ECoG, we are more likely to see responses to auditory stimuli in temporal lobe electrodes (potentially RPPST, RPST, RMST, RAST), so we'll try those.
```
if data_type == 'eeg':
picks = mne.pick_channels(raw.ch_names, include=['Pz','CPz','Cz','FCz','Fz','C1','C2','FC1','FC2','CP1','CP2'])
elif data_type == 'ecog':
picks = mne.pick_channels(raw.ch_names, include=['RPPST9','RPPST10','RPPST11'])
raw.plot_psd(picks = picks, fmin=1, fmax=raw.info['sfreq']/2, xscale='log');
```
## Plotting responses to events
Ok, so this is all well and good. We can plot our raw data, the power spectrum, and the locations of the sensors. But what if we care about responses to the stimuli we described above? What if we want to look at responses to specific sentences, or the average response across all sentences, or something else? How can we determine which EEG sensors or ECoG electrodes respond to the speech stimuli?
Enter.... *Epoching!* MNE-python gives you a very convenient way of rearranging your data according to events of interest. These can actually even be found automatically from a stimulus channel, if you have one (using [`mne.find_events`](https://mne.tools/stable/generated/mne.find_events.html)), which we won't use here because we already have the timings from another procedure. You can also find other types of epochs, like those based on EMG or [eye movements (EOG)](https://mne.tools/stable/generated/mne.preprocessing.find_eog_events.html).
Here, we will load our event files (ending with `_eve.txt`). These contain information about the start sample, stop sample, and event ID for each stimulus. Each row in the file is one stimulus. The timings are in samples rather than in seconds, so if you are creating these on your own, pay attention to your sampling rate (in `raw.info['sfreq']`).
```
# Load some events. The format of these is start sample, end sample, and event ID.
events = mne.read_events(event_files[data_type])
print(events)
num_events = len(events)
unique_stimuli = np.unique(np.array(events)[:,2])
num_unique = len(unique_stimuli)
print('There are %d total events, corresponding to %d unique stimuli'%(num_events, num_unique))
```
## Epochs
Great. So now that we have the events, we will "epoch" our data, which basically uses these timings to split up our data into trials of a given length. We will also set some parameters for data rejection to get rid of noisy trials.
```
# Set some rejection criteria. This will be based on the peak-to-peak
# amplitude of your data.
if data_type=='eeg':
reject = {'eeg': 60e-6} # Higher than peak to peak amplitude of 60 µV will be rejected
scalings = None
units = None
elif data_type=='ecog':
reject = {'ecog': 10} # Higher than Z-score of 10 will be rejected
scalings = {'ecog': 1} # Don't rescale these as if they should be in µV
units = {'ecog': 'Z-score'}
tmin = -0.2
tmax = 1.0
epochs = mne.Epochs(raw, events, tmin=tmin, tmax=tmax, baseline=(None, 0), reject=reject, verbose=True)
```
So what's in this epochs data structure? If we look at it, we can see that we have an entry for each event ID, and we can see how many times that stimulus was played. You can also see whether baseline correction was done and for what time period, and whether any data was rejected.
```
epochs
```
Now, you could decide at this point that you just want to work with the data directly as a numpy array. Luckily, that's super easy to do! We can just call `get_data()` on our epochs data structure, and this will output a matrix of `[events x channels x time points]`. If you do not limit the channel type, you will get all of them (including any EOG, stimulus channels, or other non-EEG/ECoG channels).
```
ep_data = epochs.get_data()
print(ep_data.shape)
```
## Plotting Epoched data
Ok... so we are getting ahead of ourselves. MNE-python provides a lot of ways to plot our data so that we don't have to deal with writing functions to do this ourselves! For example, if we'd like to plot the EEG/ECoG for all of the single trials we just loaded, along with an average across all of these trials (and channels of interest), we can do that easily with `epochs.plot_image()`.
```
epochs.plot_image(combine='mean', scalings=scalings, units=units)
```
As before, we can choose specific channels to look at instead of looking at all of them at once. For which method do you think this would make the most difference? Why?
```
if data_type == 'eeg':
picks = mne.pick_channels(raw.ch_names, include=['Fz','FCz','Cz','CPz','Pz'])
elif data_type == 'ecog':
picks = mne.pick_channels(raw.ch_names, include=['RPPST9','RPPST10','RPPST11'])
epochs.plot_image(picks = picks, combine='mean', scalings=scalings, units=units)
```
We can also sort the trials, if we would like. This can be very convenient if you have reaction times or some other portion of the trial where reordering would make sense. Here, we'll just pick a channel and order by the mean activity within each trial.
```
if data_type == 'eeg':
picks = mne.pick_channels(raw.ch_names, include=['CP6'])
elif data_type == 'ecog':
picks = mne.pick_channels(raw.ch_names, include=['RPPST2'])
# Get the data as a numpy array
eps_data = epochs.get_data()
# Sort the data
new_order = eps_data[:,picks[0],:].mean(1).argsort(0)
epochs.plot_image(picks=picks, order=new_order, scalings=scalings, units=units)
```
## Other ways to view epoched data
For EEG, another way to view these epochs by trial is using the scalp topography information. This allows us to quickly assess differences across the scalp in response to the stimuli. What do you notice about the responses?
```
if data_type == 'eeg':
epochs.plot_topo_image(vmin=-30, vmax=30, fig_facecolor='w',font_color='k');
```
## Comparing epochs of different trial types
So far we have just shown averages of activity across many different sentences. However, as mentioned above, the sentences come from multiple male and female talkers. So -- one quick split we could try is just to compare the responses to female vs. male talkers. This is relatively simple with the TIMIT stimuli because their file name starts with "f" or "m" to indicate this.
```
# Make lists of the event ID numbers corresponding to "f" and "m" sentences
f_evs = []
m_evs = []
for k in event_id.keys():
if k[0] == 'f':
f_evs.append(event_id[k])
elif k[0] == 'm':
m_evs.append(event_id[k])
print(unique_stimuli)
f_evs_new = [v for v in f_evs if v in unique_stimuli]
m_evs_new = [v for v in m_evs if v in unique_stimuli]
# Epoch the data separately for "f" and "m" epochs
f_epochs = mne.Epochs(raw, events, event_id=f_evs_new, tmin=tmin, tmax=tmax, reject=reject)
m_epochs = mne.Epochs(raw, events, event_id=m_evs_new, tmin=tmin, tmax=tmax, reject=reject)
```
Now we can plot the epochs just as we did above.
```
f_epochs.plot_image(combine='mean', show=False, scalings=scalings, units=units)
m_epochs.plot_image(combine='mean', show=False, scalings=scalings, units=units)
```
Cool! So now we have a separate plot for the "f" and "m" talkers. However, it's not super convenient to compare the traces this way... we kind of want them on the same axis. MNE easily allows us to do this too! Instead of using the epochs, we can create `evoked` data structures, which are averaged epochs. You can [read more about evoked data structures here](https://mne.tools/dev/auto_tutorials/evoked/plot_10_evoked_overview.html).
## Compare evoked data
```
evokeds = {'female': f_epochs.average(), 'male': m_epochs.average()}
mne.viz.plot_compare_evokeds(evokeds, show_sensors='upper right',picks=picks);
```
If we actually want errorbars on this plot, we need to do this a bit differently. We can use the `iter_evoked()` method on our epochs structures to create a dictionary of conditions for which we will plot our comparisons with `plot_compare_evokeds`.
```
evokeds = {'f':list(f_epochs.iter_evoked()), 'm':list(m_epochs.iter_evoked())}
mne.viz.plot_compare_evokeds(evokeds, picks=picks);
```
## Plotting scalp topography
For EEG, another common plot you may see is a topographic map showing activity (or other data like p-values, or differences between conditions). In this example, we'll show the activity at -0.2, 0, 0.1, 0.2, 0.3, and 1 second. You can also of course choose just one time to look at.
```
if data_type == 'eeg':
times=[tmin, 0, 0.1, 0.2, 0.3, tmax]
epochs.average().plot_topomap(times, ch_type='eeg', cmap='PRGn', res=32,
outlines='skirt', time_unit='s');
```
We can also plot arbitrary data using `mne.viz.plot_topomap`, and passing in a vector of data matching the number of EEG channels, and `raw.info` to give specifics on those channel locations.
```
if data_type == 'eeg':
chans = mne.pick_types(raw.info, eeg=True)
data = np.random.randn(len(chans),)
plt.figure()
mne.viz.plot_topomap(data, raw.info, show=True)
```
We can even animate these topo maps! This won't work well in jupyterhub, but feel free to try on your own!
```
if data_type == 'eeg':
fig,anim=epochs.average().animate_topomap(blit=False, times=np.linspace(tmin, tmax, 100))
```
## A few more fancy EEG plots
If we want to get especially fancy, we can also use `plot_joint` with our evoked data (or averaged epoched data, as shown below). This allows us to combine the ERPs for individual channels with topographic maps at time points that we specify. Pretty awesome!
```
if data_type == 'eeg':
epochs.average().plot_joint(picks='eeg', times=[0.1, 0.2, 0.3])
```
# What if I need more control? - matplotlib alternatives
If you feel you need more specific control over your plots, it's easy to get the data into a usable format for plotting with matplotlib. You can export both the raw and epoched data using the `get_data()` function, which will allow you to save your data as a numpy array `[ntrials x nchannels x ntimepoints]`.
Then, you can do whatever you want with the data! Throw it into matplotlib, use seaborn, or whatever your heart desires!
```
if data_type == 'eeg':
picks = mne.pick_channels(raw.ch_names, include=['Fz','FCz','Cz','CPz','Pz'])
elif data_type == 'ecog':
picks = mne.pick_channels(raw.ch_names, include=['RPPST9','RPPST10','RPPST11'])
f_data = f_epochs.get_data(picks=picks)
m_data = m_epochs.get_data(picks=picks)
times = f_epochs.times
print(f_data.shape)
```
## Plot evoked data with errorbars
We can recreate some similar plots to those in MNE-python with some of the matplotlib functions. Here we'll create something similar to what was plotted in `plot_compare_evokeds`.
```
def plot_errorbar(x, ydata, label=None, axlines=True, alpha=0.5, **kwargs):
'''
Plot the mean +/- standard error of ydata.
Inputs:
x : vector of x values
ydata : matrix of your data (this will be averaged along the 0th dimension)
label : A string containing the label for this plot
axlines : [bool], whether to draw the horizontal and vertical axes
alpha: opacity of the standard error area
'''
ymean = ydata.mean(0)
ystderr = ydata.std(0)/np.sqrt(ydata.shape[0])
plt.plot(x, ydata.mean(0), label=label, **kwargs)
plt.fill_between(x, ymean+ystderr, ymean-ystderr, alpha=alpha, **kwargs)
if axlines:
plt.axvline(0, color='k', linestyle='--')
plt.axhline(0, color='k', linestyle='--')
plt.gca().set_xlim([x.min(), x.max()])
plt.figure()
plot_errorbar(times, f_data.mean(0), label='female')
plot_errorbar(times, m_data.mean(0), label='male')
plt.xlabel('Time (s)')
plt.ylabel('Z-scored high gamma')
plt.legend()
```
## ECoG Exercise:
1. If you wanted to look at each ECoG electrode individually to find which ones have responses to the speech data, how would you do this?
2. Can you plot the comparison between "f" and "m" trials for each electrode as a subplot (try using `plt.subplot()` from `matplotlib`)
```
# Get the data for f trials
# Get the data for m trials
# Loop through each channel, and create a set of subplots for each
```
# Hooray, the End!
You did it! Go forth and use MNE-python in your own projects, or even contribute to the code! 🧠
| github_jupyter |
# MDN-transformer with examples
- What kind of data can be predicted by a mixture density network Transformer?
- Continuous sequential data
- Drawing data and RoboJam Touch Screem would be good examples for this, continuous values yield high resolution in 2d space.
# 1. Kanji Generation
- Firstly, let's try modelling some drawing data for Kanji writing using an MDN-Transformer.
- This work is inspired by previous work "MDN-RNN for Kanji Generation", hardmaru's Kanji tutorial and the original Sketch-RNN repository:
- http://blog.otoro.net/2015/12/28/recurrent-net-dreams-up-fake-chinese-characters-in-vector-format-with-tensorflow/
- https://github.com/hardmaru/sketch-rnn
- The idea is to learn how to draw kanji characters from a dataset of vector representations.
- This means learning how to move a pen in 2D space.
- The data consists of a sequence of pen movements (loations in 2D) and whether the pen is up or down.
- In this example, we will use one 3D MDN to model everything!
We will end up with a system that will continue writing Kanji given a short sequence, like this:
```
# Setup and modules
import sys
!{sys.executable} -m pip install keras-mdn-layer
!{sys.executable} -m pip install tensorflow
!{sys.executable} -m pip install tensorflow-probability
!{sys.executable} -m pip install matplotlib
!{sys.executable} -m pip install pandas
!{sys.executable} -m pip install svgwrite
import mdn
import numpy as np
import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
%matplotlib notebook
# Only for GPU use:
gpus = tf.config.list_physical_devices('GPU')
if gpus:
try:
# Currently, memory growth needs to be the same across GPUs
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
logical_gpus = tf.config.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
except RuntimeError as e:
# Memory growth must be set before GPUs have been initialized
print(e)
```
### Download and process the data set
```
# Train from David Ha's Kanji dataset from Sketch-RNN: https://github.com/hardmaru/sketch-rnn-datasets
# Other datasets in "Sketch 3" format should also work.
import urllib.request
url = 'https://github.com/hardmaru/sketch-rnn-datasets/raw/master/kanji/kanji.rdp25.npz'
urllib.request.urlretrieve(url, './kanji.rdp25.npz')
```
### Dataset
Includes about 11000 handwritten kanji characters divied into training, validation, and testing sets.
```
with np.load('./kanji.rdp25.npz', allow_pickle=True) as data:
train_set = data['train']
valid_set = data['valid']
test_set = data['test']
print("Training kanji:", len(train_set))
print("Validation kanji:", len(valid_set))
print("Testing kanji:", len(test_set))
# Functions for slicing up data
def slice_sequence_examples(sequence, num_steps):
xs = []
for i in range(len(sequence) - num_steps - 1):
example = sequence[i: i + num_steps]
xs.append(example)
return xs
def seq_to_singleton_format(examples):
xs = []
ys = []
for ex in examples:
xs.append(ex[:SEQ_LEN])
ys.append(ex)
return xs, ys
# Functions for making the data set
def format_dataset(x, y):
return ({
"input": x,
"target": y[:, :-1, :],
}, y[:, 1:, :])
def make_dataset(X, y):
dataset = tf.data.Dataset.from_tensor_slices((X, y))
dataset = dataset.batch(batch_size)
dataset = dataset.map(format_dataset)
return dataset.shuffle(2048).prefetch(16).cache()
# Data shapes
NUM_FEATS = 3
SEQ_LEN = 20
gap_len = 1
batch_size = 128
# Prepare training data as X and Y.
slices = []
for seq in train_set:
slices += slice_sequence_examples(seq, SEQ_LEN+gap_len)
X, y = seq_to_singleton_format(slices)
X = np.array(X)
y = np.array(y)
train_ds = make_dataset(X, y)
print("Number of training examples:")
print("X:", X.shape)
print("y:", y.shape)
print(train_ds)
```
### Constructing the MDN Transformer
Our MDN Transformer has the following settings:
- an embedding layer with positional embedding
- a transformer encoder
- a transformer decoder
- a three-dimensional mixture layer with 10 mixtures
- train for sequence length ___
- training for ___ epochs with a batch size of ___
Here's a diagram:
```
class PositionalEmbedding(layers.Layer):
def __init__(self, sequence_length, input_dim, output_dim, **kwargs):
super().__init__(**kwargs)
self.token_embeddings = layers.Dense(output_dim)
self.position_embeddings = layers.Embedding(
input_dim=sequence_length, output_dim=output_dim)
self.sequence_length = sequence_length
self.input_dim = input_dim
self.output_dim = output_dim
def call(self, inputs, padding_mask=None):
length = inputs.shape[1]
positions = tf.range(start=0, limit=length, delta=1)
embedded_tokens = self.token_embeddings(inputs)
embedded_positions = self.position_embeddings(positions)
return embedded_tokens + embedded_positions
def get_config(self):
config = super().get_config()
config.update({
"output_dim": self.output_dim,
"sequence_length": self.sequence_length,
"input_dim": self.input_dim,
})
return config
class TransformerEncoder(layers.Layer):
def __init__(self, embed_dim, dense_dim, num_heads, **kwargs):
super().__init__(**kwargs)
self.embed_dim = embed_dim
self.dense_dim = dense_dim
self.num_heads = num_heads
self.attention = layers.MultiHeadAttention(
num_heads=num_heads, key_dim=embed_dim)
self.dense_proj = keras.Sequential(
[layers.Dense(dense_dim, activation="relu"),
layers.Dense(embed_dim),]
)
self.layernorm_1 = layers.LayerNormalization()
self.layernorm_2 = layers.LayerNormalization()
def call(self, inputs, mask=None):
attention_output = self.attention(inputs, inputs, attention_mask=mask)
proj_input = self.layernorm_1(inputs + attention_output)
proj_output = self.dense_proj(proj_input)
return self.layernorm_2(proj_input + proj_output)
def get_config(self):
config = super().get_config()
config.update({
"embed_dim": self.embed_dim,
"num_heads": self.num_heads,
"dense_dim": self.dense_dim,
})
return config
class TransformerDecoder(layers.Layer):
def __init__(self, embed_dim, dense_dim, num_heads, **kwargs):
super().__init__(**kwargs)
self.embed_dim = embed_dim
self.dense_dim = dense_dim
self.num_heads = num_heads
self.attention_1 = layers.MultiHeadAttention(
num_heads=num_heads, key_dim=embed_dim)
self.attention_2 = layers.MultiHeadAttention(
num_heads=num_heads, key_dim=embed_dim)
self.dense_proj = keras.Sequential(
[layers.Dense(dense_dim, activation="relu"),
layers.Dense(embed_dim),]
)
self.layernorm_1 = layers.LayerNormalization()
self.layernorm_2 = layers.LayerNormalization()
self.layernorm_3 = layers.LayerNormalization()
self.supports_masking = True
def get_causal_attention_mask(self, inputs):
input_shape = tf.shape(inputs)
batch_size, sequence_length = input_shape[0], input_shape[1]
i = tf.range(sequence_length)[:, tf.newaxis]
j = tf.range(sequence_length)
mask = tf.cast(i >= j, dtype="int32")
mask = tf.reshape(mask, (1, input_shape[1], input_shape[1]))
mult = tf.concat(
[tf.expand_dims(batch_size, -1),
tf.constant([1, 1], dtype=tf.int32)], axis=0)
return tf.tile(mask, mult)
def call(self, inputs, encoder_outputs, padding_mask=None):
causal_mask = self.get_causal_attention_mask(inputs)
attention_output_1 = self.attention_1(
query=inputs,
value=inputs,
key=inputs,
attention_mask=causal_mask)
attention_output_1 = self.layernorm_1(inputs + attention_output_1)
if padding_mask==None:
attention_output_2 = self.attention_2(
query=attention_output_1,
value=encoder_outputs,
key=encoder_outputs)
else:
attention_output_2 = self.attention_2(
query=attention_output_1,
value=encoder_outputs,
key=encoder_outputs,
attention_mask=padding_mask)
attention_output_2 = self.layernorm_2(
attention_output_1 + attention_output_2)
proj_output = self.dense_proj(attention_output_2)
return self.layernorm_3(attention_output_2 + proj_output)
def get_config(self):
config = super().get_config()
config.update({
"embed_dim": self.embed_dim,
"num_heads": self.num_heads,
"dense_dim": self.dense_dim,
})
return config
# Training Hyperparameters:
input_dim = 3
sequence_length = 20
target_length = 20
embed_dim = 256
dense_dim = 128
num_heads = 2
output_dim = 3
number_mixtures = 10
EPOCHS = 20
SEED = 2345 # set random seed for reproducibility
random.seed(SEED)
np.random.seed(SEED)
encoder_inputs = keras.Input(shape=(sequence_length, input_dim), dtype="float64", name="input")
x = PositionalEmbedding(sequence_length, input_dim, embed_dim)(encoder_inputs)
encoder_outputs = TransformerEncoder(embed_dim, dense_dim, num_heads)(x)
print(encoder_outputs.shape)
# encoder_outputs2 = TransformerEncoder(embed_dim, dense_dim, num_heads)(encoder_outputs)
decoder_inputs = keras.Input(shape=(target_length, input_dim), dtype="float64", name="target")
x = PositionalEmbedding(target_length, input_dim, embed_dim)(decoder_inputs)
x = TransformerDecoder(embed_dim, dense_dim, num_heads)(x, encoder_outputs)
# x = TransformerDecoder(embed_dim, dense_dim, num_heads)(x, encoder_outputs2)
x = layers.Dropout(0.2)(x)
decoder_outputs = layers.Dense(input_dim, activation="softmax")(x)
outputs = mdn.MDN(output_dim, number_mixtures) (decoder_outputs)
model = keras.Model([encoder_inputs, decoder_inputs], outputs)
model.compile(loss=mdn.get_mixture_loss_func(output_dim,number_mixtures),
optimizer=keras.optimizers.Adam())
model.summary()
callbacks = [
keras.callbacks.ModelCheckpoint("full_transformer.keras",
save_best_only=True)
]
history=model.fit(train_ds, batch_size=batch_size, epochs=EPOCHS, callbacks=callbacks)
!mkdir -p saved_model
model.save('my_model_100_128_256_128_2_02')
# print(f"Test acc: {model.evaluate(int_test_ds)[1]:.3f}")
plt.figure()
plt.plot(history.history['loss'])
plt.show()
ls saved_model/my_model6
model = keras.models.load_model('saved_model/my_model6')
```
## Generating drawings
First need some helper functions to view the output.
```
def zero_start_position():
"""A zeroed out start position with pen down"""
out = np.zeros((1, 1, 3), dtype=np.float32)
out[0, 0, 2] = 1 # set pen down.
return out
def generate_sketch(model, start_pos, num_points=100):
return None
def cutoff_stroke(x):
return np.greater(x,0.5) * 1.0
def plot_sketch(sketch_array):
"""Plot a sketch quickly to see what it looks like."""
sketch_df = pd.DataFrame({'x':sketch_array.T[0],'y':sketch_array.T[1],'z':sketch_array.T[2]})
sketch_df.x = sketch_df.x.cumsum()
sketch_df.y = -1 * sketch_df.y.cumsum()
# Do the plot
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(111)
#ax1.scatter(sketch_df.x,sketch_df.y,marker='o', c='r', alpha=1.0)
# Need to do something with sketch_df.z
ax1.plot(sketch_df.x,sketch_df.y,'r-')
plt.show()
```
## SVG Drawing Function
Here's Hardmaru's Drawing Functions from _write-rnn-tensorflow_. Big hat tip to Hardmaru for this!
Here's the source: https://github.com/hardmaru/write-rnn-tensorflow/blob/master/utils.py
```
import svgwrite
from IPython.display import SVG, display
def get_bounds(data, factor):
min_x = 0
max_x = 0
min_y = 0
max_y = 0
abs_x = 0
abs_y = 0
for i in range(len(data)):
x = float(data[i, 0]) / factor
y = float(data[i, 1]) / factor
abs_x += x
abs_y += y
min_x = min(min_x, abs_x)
min_y = min(min_y, abs_y)
max_x = max(max_x, abs_x)
max_y = max(max_y, abs_y)
return (min_x, max_x, min_y, max_y)
def draw_strokes(data, factor=1, svg_filename='sample.svg'):
min_x, max_x, min_y, max_y = get_bounds(data, factor)
dims = (50 + max_x - min_x, 50 + max_y - min_y)
dwg = svgwrite.Drawing(svg_filename, size=dims)
dwg.add(dwg.rect(insert=(0, 0), size=dims, fill='white'))
lift_pen = 1
abs_x = 25 - min_x
abs_y = 25 - min_y
p = "M%s,%s " % (abs_x, abs_y)
command = "m"
for i in range(len(data)):
if (lift_pen == 1):
command = "m"
elif (command != "l"):
command = "l"
else:
command = ""
x = float(data[i, 0]) / factor
y = float(data[i, 1]) / factor
lift_pen = data[i, 2]
p += command + str(x) + "," + str(y) + " "
the_color = "black"
stroke_width = 1
dwg.add(dwg.path(p).stroke(the_color, stroke_width).fill("none"))
dwg.save()
display(SVG(dwg.tostring()))
original = valid_set[0]
x0 = np.array([valid_set[0][:SEQ_LEN]])
y0 = x0
# y0 = np.array([valid_set[0][:(SEQ_LEN+9)]])
# Predict a character and plot the result.
pi_temperature = 3 # seems to work well with rather high temperature (2.5)
sigma_temp = 0.1 # seems to work well with low temp
### Generation using one example from validation set as
p = x0
sketch = p
for i in range(100):
params = model.predict([p, p])
out = mdn.sample_from_output(params[0][49], output_dim, number_mixtures, temp=pi_temperature, sigma_temp=sigma_temp)
p = np.concatenate((p[:,1:],np.array([out])), axis=1)
sketch = np.concatenate((sketch, np.array([out])), axis=1)
sketch.T[2] = cutoff_stroke(sketch.T[2])
draw_strokes(sketch[0], factor=0.5)
draw_strokes(x0[0], factor=0.5)
```
| github_jupyter |
### Imports
```
import pandas as pd
import numpy as np
#Python Standard Libs Imports
import json
import urllib2
import sys
from datetime import datetime
from os.path import isfile, join, splitext
from glob import glob
#Imports to enable visualizations
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
```
### Functions
#### Basic Functions
#### OTP Functions
#### Analysis Functions
### Main Code
#### Reading itinerary alternatives data
```
all_itineraries = pd.read_csv('/local/tarciso/data/its/itineraries/all_itineraries.csv', parse_dates=['planned_start_time','actual_start_time','exec_start_time'])
all_itineraries.head()
all_itineraries.dtypes
len(all_itineraries)
len(all_itineraries.user_trip_id.unique())
```
#### Adding metadata for further analysis
```
def get_trip_len_bucket(trip_duration):
if (trip_duration < 10):
return '<10'
elif (trip_duration < 20):
return '10-20'
elif (trip_duration < 30):
return '20-30'
elif (trip_duration < 40):
return '30-40'
elif (trip_duration < 50):
return '40-50'
elif (trip_duration >= 50):
return '50+'
else:
return 'NA'
def get_day_type(trip_start_time):
trip_weekday = trip_start_time.weekday()
if ((trip_weekday == 0) | (trip_weekday == 4)):
return 'MON/FRI'
elif ((trip_weekday > 0) & (trip_weekday < 4)):
return 'TUE/WED/THU'
elif (trip_weekday > 4):
return 'SAT/SUN'
else:
return 'NA'
all_itineraries['trip_length_bucket'] = all_itineraries['exec_duration_mins'].apply(get_trip_len_bucket)
all_itineraries['hour_of_day'] = all_itineraries['exec_start_time'].dt.hour
period_of_day_list = [('hour_of_day', [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]),
('period_of_day', ['very_late_night','very_late_night','very_late_night','very_late_night','early_morning','early_morning','early_morning','morning','morning','morning','morning','midday','midday','midday','afternoon','afternoon','afternoon','evening','evening','evening','night','night','late_night','late_night'])]
period_of_day_df = pd.DataFrame.from_items(period_of_day_list)
period_of_day_df.period_of_day = period_of_day_df.period_of_day.astype('category', ordered=True)
all_itineraries = all_itineraries.merge(period_of_day_df, how='inner', on='hour_of_day')
all_itineraries['weekday'] = all_itineraries['exec_start_time'].apply(lambda x: x.weekday() < 5)
all_itineraries['day_type'] = all_itineraries['exec_start_time'].apply(get_day_type)
all_itineraries
```
#### Filtering trips for whose executed itineraries there is no schedule information
```
def filter_trips_alternatives(trips_alternatives):
min_trip_dur = 10
max_trip_dur = 50
max_trip_start_diff = 20
return trips_alternatives[(trips_alternatives['actual_duration_mins'] >= min_trip_dur) & (trips_alternatives['actual_duration_mins'] <= max_trip_dur)] \
.assign(start_diff = lambda x: np.absolute(x['exec_start_time'] - x['actual_start_time'])/pd.Timedelta(minutes=1)) \
[lambda x: x['start_diff'] <= 20]
def filter_trips_with_insufficient_alternatives(trips_alternatives):
num_trips_alternatives = trips_alternatives.groupby(['date','user_trip_id']).size().reset_index(name='num_alternatives')
trips_with_executed_alternative = trips_alternatives[trips_alternatives['itinerary_id'] == 0][['date','user_trip_id']]
return trips_alternatives.merge(trips_with_executed_alternative, on=['date','user_trip_id'], how='inner') \
.merge(num_trips_alternatives, on=['date','user_trip_id'], how='inner') \
[lambda x: x['num_alternatives'] > 1] \
.sort_values(['user_trip_id','itinerary_id'])
clean_itineraries = filter_trips_with_insufficient_alternatives(filter_trips_alternatives(all_itineraries))
clean_itineraries.head()
sns.distplot(clean_itineraries['start_diff'])
len(clean_itineraries)
len(clean_itineraries.user_trip_id.unique())
exec_itineraries_with_scheduled_info = all_itineraries[(all_itineraries['itinerary_id'] == 0) & (pd.notnull(all_itineraries['planned_duration_mins']))][['date','user_trip_id']]
clean_itineraries2 = filter_trips_with_insufficient_alternatives(filter_trips_alternatives(all_itineraries.merge(exec_itineraries_with_scheduled_info, on=['date','user_trip_id'], how='inner')))
clean_itineraries2.head()
len(clean_itineraries2)
len(clean_itineraries2.user_trip_id.unique())
```
## Compute Inefficiency Metrics

```
def select_best_itineraries(trips_itineraries,metric_name):
return trips_itineraries.sort_values([metric_name]) \
.groupby(['date','user_trip_id']) \
.nth(0) \
.reset_index()
```
### Observed Inefficiency
```
#Choose best itinerary for each trip by selecting the ones with lower actual duration
best_trips_itineraries = select_best_itineraries(clean_itineraries,'actual_duration_mins')
best_trips_itineraries.head()
trips_inefficiency = best_trips_itineraries \
.assign(dur_diff = lambda x: x['exec_duration_mins'] - x['actual_duration_mins']) \
.assign(observed_inef = lambda x: x['dur_diff']/x['exec_duration_mins'])
trips_inefficiency.head(10)
sns.distplot(trips_inefficiency.observed_inef)
sns.violinplot(trips_inefficiency.observed_inef)
pos_trips_inefficiency = trips_inefficiency[trips_inefficiency['dur_diff'] > 1]
pos_trips_inefficiency.head()
```
#### Number of Trips with/without improvent per Trip Length Bucket
```
trips_per_length = trips_inefficiency.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length
trips_per_length_improved = pos_trips_inefficiency.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length_improved
sns.set_style("whitegrid")
#Plot 1 - background - "total" (top) series
ax = sns.barplot(x = trips_per_length.trip_length_bucket, y = trips_per_length.total, color = "#66c2a5")
#Plot 2 - overlay - "bottom" series
bottom_plot = sns.barplot(x = trips_per_length_improved.trip_length_bucket, y = trips_per_length_improved.total, color = "#fc8d62")
bottom_plot.set(xlabel='Trip Length (minutes)',ylabel='Number of Trips')
topbar = plt.Rectangle((0,0),1,1,fc="#66c2a5", edgecolor = 'none')
bottombar = plt.Rectangle((0,0),1,1,fc='#fc8d62', edgecolor = 'none')
l = plt.legend([bottombar, topbar], ['Not Optimal', 'Optimal'], bbox_to_anchor=(0, 1.2), loc=2, ncol = 2, prop={'size':10})
l.draw_frame(False)
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/trip_length_by_optimality.pdf', bbox_inches='tight')
```
#### Per Trip Length Bucket
```
trip_len_order=['10-20','20-30','30-40','40-50']
ax = sns.boxplot(x='observed_inef',y='trip_length_bucket', orient='h', data=pos_trips_inefficiency, order=trip_len_order, color='#fc8d62')
ax.set(xlabel='Inefficiency (%)',ylabel='Trip Length')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_trip_length.pdf', bbox_inches='tight')
```
#### Per Period of Day
```
period_of_day_order = ['very_late_night','early_morning','morning','midday','afternoon','evening','night','late_night']
ax = sns.boxplot(x='observed_inef',y='period_of_day', data=pos_trips_inefficiency, order=period_of_day_order, color='#fc8d62')
ax.set(xlabel='Inefficiency (%)',ylabel='Period of Day')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tight')
```
#### Per Weekday/Weekend
```
ax = sns.barplot(x='trip_length_bucket',y='observed_inef', hue='weekday', data=pos_trips_inefficiency, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tight')
```
#### Per Day Type
```
ax = sns.barplot(x='trip_length_bucket',y='observed_inef', hue='day_type', data=pos_trips_inefficiency, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tight')
```
### Schedule Inefficiency
```
shortest_planned_itineraries = select_best_itineraries(clean_itineraries[pd.notnull(clean_itineraries['planned_duration_mins'])],'planned_duration_mins') \
[['date','user_trip_id','planned_duration_mins','actual_duration_mins']] \
.rename(index=str,columns={'planned_duration_mins':'shortest_scheduled_planned_duration',
'actual_duration_mins':'shortest_scheduled_observed_duration'})
shortest_planned_itineraries.head()
sched_inef = best_trips_itineraries \
.rename(index=str,columns={'actual_duration_mins':'shortest_observed_duration'}) \
.merge(shortest_planned_itineraries, on=['date','user_trip_id'], how='inner') \
.assign(sched_dur_diff = lambda x: x['shortest_scheduled_observed_duration'] - x['shortest_observed_duration']) \
.assign(sched_inef = lambda x: x['sched_dur_diff']/x['shortest_scheduled_observed_duration'])
sched_inef.head()
sns.distplot(sched_inef.sched_inef)
sns.violinplot(sched_inef.sched_inef)
pos_sched_inef = sched_inef[sched_inef['sched_dur_diff'] > 1]
sns.distplot(pos_sched_inef.sched_inef)
```
#### Number of Trips with/without improvent per Trip Length Bucket
```
trips_per_length = sched_inef.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length
trips_per_length_improved = pos_sched_inef.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length_improved
sns.set_style("whitegrid")
#Plot 1 - background - "total" (top) series
ax = sns.barplot(x = trips_per_length.trip_length_bucket, y = trips_per_length.total, color = "#66c2a5")
#Plot 2 - overlay - "bottom" series
bottom_plot = sns.barplot(x = trips_per_length_improved.trip_length_bucket, y = trips_per_length_improved.total, color = "#fc8d62")
bottom_plot.set(xlabel='Trip Length (minutes)',ylabel='Number of Trips')
topbar = plt.Rectangle((0,0),1,1,fc="#66c2a5", edgecolor = 'none')
bottombar = plt.Rectangle((0,0),1,1,fc='#fc8d62', edgecolor = 'none')
l = plt.legend([bottombar, topbar], ['Not Optimal', 'Optimal'], bbox_to_anchor=(0, 1.2), loc=2, ncol = 2, prop={'size':10})
l.draw_frame(False)
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/trip_length_by_optimality.pdf', bbox_inches='tight')
```
#### Per Trip Length Bucket
```
trip_len_order=['10-20','20-30','30-40','40-50']
ax = sns.boxplot(x='sched_inef',y='trip_length_bucket', orient='h', data=pos_sched_inef, order=trip_len_order, color='#fc8d62')
ax.set(xlabel='Schedule Inefficiency (%)',ylabel='Trip Length')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_trip_length.pdf', bbox_inches='tight')
```
#### Per Period of Day
```
period_of_day_order = ['very_late_night','early_morning','morning','midday','afternoon','evening','night','late_night']
ax = sns.boxplot(x='sched_inef',y='period_of_day', data=pos_sched_inef, order=period_of_day_order, color='#fc8d62')
ax.set(xlabel='Schedule Inefficiency (%)',ylabel='Period of Day')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tight')
```
#### Per Weekday/Weekend
```
ax = sns.barplot(x='trip_length_bucket',y='sched_inef', hue='weekday', data=pos_sched_inef, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Schedule Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tight')
```
#### Per Day Type
```
ax = sns.barplot(x='trip_length_bucket',y='sched_inef', hue='day_type', data=pos_sched_inef, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Schedule Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tight')
```
### User choice plan inefficiency
```
best_scheduled_itineraries = select_best_itineraries(clean_itineraries2,'planned_duration_mins') \
[['date','user_trip_id','planned_duration_mins']] \
.rename(index=str,columns={'planned_duration_mins':'best_planned_duration_mins'})
best_scheduled_itineraries.head()
plan_inef = clean_itineraries2.merge(best_scheduled_itineraries, on=['date','user_trip_id'], how='inner') \
[lambda x: x['itinerary_id'] == 0] \
.assign(plan_dur_diff = lambda x: x['planned_duration_mins'] - x['best_planned_duration_mins']) \
.assign(plan_inef = lambda x: x['plan_dur_diff']/x['planned_duration_mins'])
sns.distplot(plan_inef.plan_inef)
pos_plan_inef = plan_inef[plan_inef['plan_dur_diff'] > 1]
sns.distplot(pos_plan_inef.plan_inef)
```
#### Number of Trips with/without improvent per Trip Length Bucket
```
trips_per_length = plan_inef.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length
trips_per_length_improved = pos_plan_inef.groupby('trip_length_bucket').size().reset_index(name='total')
trips_per_length_improved
sns.set_style("whitegrid")
#Plot 1 - background - "total" (top) series
ax = sns.barplot(x = trips_per_length.trip_length_bucket, y = trips_per_length.total, color = "#66c2a5")
#Plot 2 - overlay - "bottom" series
bottom_plot = sns.barplot(x = trips_per_length_improved.trip_length_bucket, y = trips_per_length_improved.total, color = "#fc8d62")
bottom_plot.set(xlabel='Trip Length (minutes)',ylabel='Number of Trips')
topbar = plt.Rectangle((0,0),1,1,fc="#66c2a5", edgecolor = 'none')
bottombar = plt.Rectangle((0,0),1,1,fc='#fc8d62', edgecolor = 'none')
l = plt.legend([bottombar, topbar], ['Not Optimal', 'Optimal'], bbox_to_anchor=(0, 1.2), loc=2, ncol = 2, prop={'size':10})
l.draw_frame(False)
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/trip_length_by_optimality.pdf', bbox_inches='tight')
```
#### Per Trip Length Bucket
```
trip_len_order=['10-20','20-30','30-40','40-50']
ax = sns.boxplot(x='plan_inef',y='trip_length_bucket', orient='h', data=pos_plan_inef, order=trip_len_order, color='#fc8d62')
ax.set(xlabel='Plan Inefficiency (%)',ylabel='Trip Length')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_trip_length.pdf', bbox_inches='tight')
```
#### Per Period of Day
```
period_of_day_order = ['very_late_night','early_morning','morning','midday','afternoon','evening','night','late_night']
ax = sns.boxplot(x='plan_inef',y='period_of_day', data=pos_plan_inef, order=period_of_day_order, color='#fc8d62')
ax.set(xlabel='Plan Inefficiency (%)',ylabel='Period of Day')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tight')
```
#### Per Weekday/Weekend
```
ax = sns.barplot(x='trip_length_bucket',y='plan_inef', hue='weekday', data=pos_plan_inef, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Plan Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tight')
```
#### Per Day Type
```
ax = sns.barplot(x='trip_length_bucket',y='plan_inef', hue='day_type', data=pos_plan_inef, color='#fc8d62')
ax.set(xlabel='Trip Length',ylabel='Plan Inefficiency (%)')
fig = ax.get_figure()
fig.set_size_inches(4.5, 3)
#fig.savefig('/local/tarciso/masters/data/results/imp_capacity_per_day_period.pdf', bbox_inches='tight')
```
#### System Schedule Deviation
$$
\begin{equation*}
{Oe - Op}
\end{equation*}
$$
```
sched_deviation = clean_itineraries[clean_itineraries['itinerary_id'] > 0] \
.assign(sched_dev = lambda x: x['actual_duration_mins'] - x['planned_duration_mins'])
sched_deviation.head()
sns.distplot(sched_deviation.sched_dev)
```
#### User stop waiting time offset
$$
\begin{equation*}
{start(Oe) - start(Op)}
\end{equation*}
$$
```
user_boarding_timediff = clean_itineraries[clean_itineraries['itinerary_id'] > 0] \
.assign(boarding_timediff = lambda x: (x['actual_start_time'] - x['planned_start_time'])/pd.Timedelta(minutes=1))
user_boarding_timediff.head()
sns.distplot(user_boarding_timediff.boarding_timediff)
```
| github_jupyter |
```
import os
import h5py
import numpy as np
# -- local --
from feasibgs import util as UT
from feasibgs import catalogs as Cat
from feasibgs import forwardmodel as FM
import matplotlib as mpl
import matplotlib.pyplot as pl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['font.family'] = 'serif'
mpl.rcParams['axes.linewidth'] = 1.5
mpl.rcParams['axes.xmargin'] = 1
mpl.rcParams['xtick.labelsize'] = 'x-large'
mpl.rcParams['xtick.major.size'] = 5
mpl.rcParams['xtick.major.width'] = 1.5
mpl.rcParams['ytick.labelsize'] = 'x-large'
mpl.rcParams['ytick.major.size'] = 5
mpl.rcParams['ytick.major.width'] = 1.5
mpl.rcParams['legend.frameon'] = False
%matplotlib inline
cata = Cat.GamaLegacy()
gleg = cata.Read()
r_mag = UT.flux2mag(gleg['legacy-photo']['apflux_r'][:,1], method='log')
float(np.sum(np.isfinite(r_mag)))/float(len(r_mag))
no_rmag = np.invert(np.isfinite(r_mag))
fig = plt.figure()
sub = fig.add_subplot(111)
_ = sub.hist(gleg['gama-photo']['modelmag_r'], color='C0', histtype='stepfilled', range=(16, 21), bins=40)
_ = sub.hist(gleg['gama-photo']['modelmag_r'][no_rmag], color='C1', histtype='stepfilled', range=(16, 21), bins=40)
sub.set_xlabel(r'$r$ band model magnitude', fontsize=20)
sub.set_xlim([16., 21.])
fig = plt.figure()
sub = fig.add_subplot(111)
_ = sub.hist(gleg['gama-photo']['modelmag_r'], color='C0', histtype='stepfilled', range=(16, 21), bins=40, normed=True)
_ = sub.hist(gleg['gama-photo']['modelmag_r'][no_rmag], color='C1', histtype='stepfilled', range=(16, 21), bins=40, normed=True)
sub.set_xlabel(r'$r$ band model magnitude', fontsize=20)
sub.set_xlim([16., 21.])
fig = plt.figure()
sub = fig.add_subplot(111)
sub.scatter(gleg['gama-photo']['modelmag_r'], r_mag, s=2, c='k')
sub.scatter(gleg['gama-photo']['modelmag_r'], UT.flux2mag(gleg['legacy-photo']['apflux_r'][:,1]), s=1, c='C0')
sub.plot([0., 25.], [0., 25.], c='C1', lw=1, ls='--')
sub.set_xlabel('$r$-band model magnitude', fontsize=20)
sub.set_xlim([13, 21])
sub.set_ylabel('$r$-band apflux magnitude', fontsize=20)
sub.set_ylim([15, 25])
fig = plt.figure()
sub = fig.add_subplot(111)
sub.scatter(gleg['gama-photo']['modelmag_r'], UT.flux2mag(gleg['legacy-photo']['flux_r']), s=2, c='C0',
label='Legacy flux')
sub.scatter(gleg['gama-photo']['modelmag_r'], r_mag, s=0.5, c='C1',
label='Legacy apflux (fiber)')
sub.plot([0., 25.], [0., 25.], c='k', lw=1, ls='--')
sub.legend(loc='upper left', markerscale=5, handletextpad=0., prop={'size':15})
sub.set_xlabel('$r$-band GAMA model magnitude', fontsize=20)
sub.set_xlim([13, 20])
sub.set_ylabel('$r$-band Legacy photometry', fontsize=20)
sub.set_ylim([13, 23])
```
| github_jupyter |
# Multi-Layer Perceptron, MNIST
---
In this notebook, we will train an MLP to classify images from the [MNIST database](http://yann.lecun.com/exdb/mnist/) hand-written digit database.
The process will be broken down into the following steps:
>1. Load and visualize the data
2. Define a neural network
3. Train the model
4. Evaluate the performance of our trained model on a test dataset!
Before we begin, we have to import the necessary libraries for working with data and PyTorch.
```
# import libraries
import torch
import numpy as np
```
---
## Load and Visualize the [Data](http://pytorch.org/docs/stable/torchvision/datasets.html)
Downloading may take a few moments, and you should see your progress as the data is loading. You may also choose to change the `batch_size` if you want to load more data at a time.
This cell will create DataLoaders for each of our datasets.
```
# The MNIST datasets are hosted on yann.lecun.com that has moved under CloudFlare protection
# Run this script to enable the datasets download
# Reference: https://github.com/pytorch/vision/issues/1938
from six.moves import urllib
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib.request.install_opener(opener)
from torchvision import datasets
import torchvision.transforms as transforms
# number of subprocesses to use for data loading
num_workers = 0
# how many samples per batch to load
batch_size = 20
# convert data to torch.FloatTensor
transform = transforms.ToTensor()
# choose the training and test datasets
train_data = datasets.MNIST(root='data', train=True,
download=True, transform=transform)
test_data = datasets.MNIST(root='data', train=False,
download=True, transform=transform)
# prepare data loaders
train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,
num_workers=num_workers)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size,
num_workers=num_workers)
```
### Visualize a Batch of Training Data
The first step in a classification task is to take a look at the data, make sure it is loaded in correctly, then make any initial observations about patterns in that data.
```
import matplotlib.pyplot as plt
%matplotlib inline
# obtain one batch of training images
dataiter = iter(train_loader)
images, labels = dataiter.next()
images = images.numpy()
# plot the images in the batch, along with the corresponding labels
fig = plt.figure(figsize=(25, 4))
for idx in np.arange(20):
ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])
ax.imshow(np.squeeze(images[idx]), cmap='gray')
# print out the correct label for each image
# .item() gets the value contained in a Tensor
ax.set_title(str(labels[idx].item()))
```
### View an Image in More Detail
```
img = np.squeeze(images[1])
fig = plt.figure(figsize = (12,12))
ax = fig.add_subplot(111)
ax.imshow(img, cmap='gray')
width, height = img.shape
thresh = img.max()/2.5
for x in range(width):
for y in range(height):
val = round(img[x][y],2) if img[x][y] !=0 else 0
ax.annotate(str(val), xy=(y,x),
horizontalalignment='center',
verticalalignment='center',
color='white' if img[x][y]<thresh else 'black')
```
---
## Define the Network [Architecture](http://pytorch.org/docs/stable/nn.html)
The architecture will be responsible for seeing as input a 784-dim Tensor of pixel values for each image, and producing a Tensor of length 10 (our number of classes) that indicates the class scores for an input image. This particular example uses two hidden layers and dropout to avoid overfitting.
```
import torch.nn as nn
import torch.nn.functional as F
## TODO: Define the NN architecture
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# linear layer (784 -> 1 hidden node)
self.fc1 = nn.Linear(28 * 28, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 128)
self.fc4 = nn.Linear(128, 10)
self.dropout = nn.Dropout(0.2)
def forward(self, x):
# flatten image input
x = x.view(-1, 28 * 28)
# add hidden layer, with relu activation function
x = F.relu(self.fc1(x))
x = self.dropout(x)
x = F.relu(self.fc2(x))
x = self.dropout(x)
x = F.relu(self.fc3(x))
x = self.dropout(x)
return self.fc4(x)
# initialize the NN
model = Net()
print(model)
```
### Specify [Loss Function](http://pytorch.org/docs/stable/nn.html#loss-functions) and [Optimizer](http://pytorch.org/docs/stable/optim.html)
It's recommended that you use cross-entropy loss for classification. If you look at the documentation (linked above), you can see that PyTorch's cross entropy function applies a softmax funtion to the output layer *and* then calculates the log loss.
```
## TODO: Specify loss and optimization functions
# specify loss function
criterion = nn.CrossEntropyLoss()
# specify optimizer
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
```
---
## Train the Network
The steps for training/learning from a batch of data are described in the comments below:
1. Clear the gradients of all optimized variables
2. Forward pass: compute predicted outputs by passing inputs to the model
3. Calculate the loss
4. Backward pass: compute gradient of the loss with respect to model parameters
5. Perform a single optimization step (parameter update)
6. Update average training loss
The following loop trains for 30 epochs; feel free to change this number. For now, we suggest somewhere between 20-50 epochs. As you train, take a look at how the values for the training loss decrease over time. We want it to decrease while also avoiding overfitting the training data.
```
# number of epochs to train the model
n_epochs = 30 # suggest training between 20-50 epochs
model.train() # prep model for training
for epoch in range(n_epochs):
# monitor training loss
train_loss = 0.0
###################
# train the model #
###################
for data, target in train_loader:
# clear the gradients of all optimized variables
optimizer.zero_grad()
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the loss
loss = criterion(output, target)
# backward pass: compute gradient of the loss with respect to model parameters
loss.backward()
# perform a single optimization step (parameter update)
optimizer.step()
# update running training loss
train_loss += loss.item()*data.size(0)
# print training statistics
# calculate average loss over an epoch
train_loss = train_loss/len(train_loader.dataset)
print('Epoch: {} \tTraining Loss: {:.6f}'.format(
epoch+1,
train_loss
))
```
---
## Test the Trained Network
Finally, we test our best model on previously unseen **test data** and evaluate it's performance. Testing on unseen data is a good way to check that our model generalizes well. It may also be useful to be granular in this analysis and take a look at how this model performs on each class as well as looking at its overall loss and accuracy.
#### `model.eval()`
`model.eval(`) will set all the layers in your model to evaluation mode. This affects layers like dropout layers that turn "off" nodes during training with some probability, but should allow every node to be "on" for evaluation!
```
# initialize lists to monitor test loss and accuracy
test_loss = 0.0
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
model.eval() # prep model for *evaluation*
for data, target in test_loader:
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the loss
loss = criterion(output, target)
# update test loss
test_loss += loss.item()*data.size(0)
# convert output probabilities to predicted class
_, pred = torch.max(output, 1)
# compare predictions to true label
correct = np.squeeze(pred.eq(target.data.view_as(pred)))
# calculate test accuracy for each object class
for i in range(batch_size):
label = target.data[i]
class_correct[label] += correct[i].item()
class_total[label] += 1
# calculate and print avg test loss
test_loss = test_loss/len(test_loader.dataset)
print('Test Loss: {:.6f}\n'.format(test_loss))
for i in range(10):
if class_total[i] > 0:
print('Test Accuracy of %5s: %2d%% (%2d/%2d)' % (
str(i), 100 * class_correct[i] / class_total[i],
class_correct[i], class_total[i]))
else:
print('Test Accuracy of %5s: N/A (no training examples)' % (classes[i]))
print('\nTest Accuracy (Overall): %2d%% (%2d/%2d)' % (
100. * np.sum(class_correct) / np.sum(class_total),
np.sum(class_correct), np.sum(class_total)))
```
### Visualize Sample Test Results
This cell displays test images and their labels in this format: `predicted (ground-truth)`. The text will be green for accurately classified examples and red for incorrect predictions.
```
# obtain one batch of test images
dataiter = iter(test_loader)
images, labels = dataiter.next()
# get sample outputs
output = model(images)
# convert output probabilities to predicted class
_, preds = torch.max(output, 1)
# prep images for display
images = images.numpy()
# plot the images in the batch, along with predicted and true labels
fig = plt.figure(figsize=(25, 4))
for idx in np.arange(20):
ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])
ax.imshow(np.squeeze(images[idx]), cmap='gray')
ax.set_title("{} ({})".format(str(preds[idx].item()), str(labels[idx].item())),
color=("green" if preds[idx]==labels[idx] else "red"))
```
| github_jupyter |
```
import pandas as pd
import os
import s3fs # for reading from S3FileSystem
import json
%matplotlib inline
import matplotlib.pyplot as plt
import torch.nn as nn
import torch
import torch.utils.model_zoo as model_zoo
import numpy as np
import torchvision.models as models # To get ResNet18
# From - https://github.com/cfotache/pytorch_imageclassifier/blob/master/PyTorch_Image_Inference.ipynb
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms
from PIL import Image
from torch.autograd import Variable
from torch.utils.data.sampler import SubsetRandomSampler
```
# Prepare the Model
```
SAGEMAKER_PATH = r'/home/ec2-user/SageMaker'
MODEL_PATH = os.path.join(SAGEMAKER_PATH, r'sidewalk-cv-assets19/pytorch_pretrained/models/20e_slid_win_no_feats_r18.pt')
os.path.exists(MODEL_PATH)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
# Use PyTorch's ResNet18
# https://stackoverflow.com/questions/53612835/size-mismatch-for-fc-bias-and-fc-weight-in-pytorch
model = models.resnet18(num_classes=5)
model.to(device)
model.load_state_dict(torch.load(MODEL_PATH))
model.eval()
```
# Prep Data
```
# From Galen
test_transforms = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# the dataset loads the files into pytorch vectors
#image_dataset = TwoFileFolder(dir_containing_crops, meta_to_tensor_version=2, transform=data_transform)
# the dataloader takes these vectors and batches them together for parallelization, increasing performance
#dataloader = torch.utils.data.DataLoader(image_dataset, batch_size=4, shuffle=True, num_workers=4)
# this is the number of additional features provided by the dataset
#len_ex_feats = image_dataset.len_ex_feats
#dataset_size = len(image_dataset)
# Load in the data
data_dir = 'images'
data = datasets.ImageFolder(data_dir, transform=test_transforms)
classes = data.classes
!ls -a images
!rm -f -r images/.ipynb_checkpoints/
# Examine the classes based on folders...
# Need to make sure that we don't get a .ipynb_checkpoints as a folder
# Discussion here - https://forums.fast.ai/t/how-to-remove-ipynb-checkpoint/8532/19
classes
num = 10
indices = list(range(len(data)))
print(indices)
np.random.shuffle(indices)
idx = indices[:num]
test_transforms = transforms.Compose([transforms.Resize(224),
transforms.ToTensor(),
])
#sampler = SubsetRandomSampler(idx)
loader = torch.utils.data.DataLoader(data, batch_size=num)
dataiter = iter(loader)
images, labels = dataiter.next()
len(images)
# Look at the first image
images[0]
len(labels)
labels
```
# Execute Inference on 2 Sample Images
```
# Note on how to make sure the model and the input tensors are both on cuda device (gpu)
# https://discuss.pytorch.org/t/runtimeerror-input-type-torch-cuda-floattensor-and-weight-type-torch-floattensor-should-be-the-same/21782/6
def predict_image(image, model):
image_tensor = test_transforms(image).float()
image_tensor = image_tensor.unsqueeze_(0)
input = Variable(image_tensor)
input = input.to(device)
output = model(input)
index = output.data.cpu().numpy().argmax()
return index, output
to_pil = transforms.ToPILImage()
#images, labels = get_random_images(5)
fig=plt.figure(figsize=(10,10))
for ii in range(len(images)):
image = to_pil(images[ii])
index, output = predict_image(image, model)
print(f'index: {index}')
print(f'output: {output}')
sub = fig.add_subplot(1, len(images), ii+1)
res = int(labels[ii]) == index
sub.set_title(str(classes[index]) + ":" + str(res))
plt.axis('off')
plt.imshow(image)
plt.show()
res
```
# Comments and Questions
What's the order of the labels (and how I should order the folders for the input data?)
This file implies that there are different orders
https://github.com/ProjectSidewalk/sidewalk-cv-assets19/blob/master/GSVutils/sliding_window.py
```label_from_int = ('Curb Cut', 'Missing Cut', 'Obstruction', 'Sfc Problem')
pytorch_label_from_int = ('Missing Cut', "Null", 'Obstruction', "Curb Cut", "Sfc Problem")```
| github_jupyter |
```
from google.colab import drive
drive.mount('/content/drive')
path = '/content/drive/MyDrive/Research/AAAI/dataset1/second_layer_without_entropy/'
import numpy as np
import pandas as pd
import torch
import torchvision
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from matplotlib import pyplot as plt
%matplotlib inline
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
```
# Generate dataset
```
np.random.seed(12)
y = np.random.randint(0,10,5000)
idx= []
for i in range(10):
print(i,sum(y==i))
idx.append(y==i)
x = np.zeros((5000,2))
np.random.seed(12)
x[idx[0],:] = np.random.multivariate_normal(mean = [4,6.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[0]))
x[idx[1],:] = np.random.multivariate_normal(mean = [5.5,6],cov=[[0.01,0],[0,0.01]],size=sum(idx[1]))
x[idx[2],:] = np.random.multivariate_normal(mean = [4.5,4.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[2]))
x[idx[3],:] = np.random.multivariate_normal(mean = [3,3.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[3]))
x[idx[4],:] = np.random.multivariate_normal(mean = [2.5,5.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[4]))
x[idx[5],:] = np.random.multivariate_normal(mean = [3.5,8],cov=[[0.01,0],[0,0.01]],size=sum(idx[5]))
x[idx[6],:] = np.random.multivariate_normal(mean = [5.5,8],cov=[[0.01,0],[0,0.01]],size=sum(idx[6]))
x[idx[7],:] = np.random.multivariate_normal(mean = [7,6.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[7]))
x[idx[8],:] = np.random.multivariate_normal(mean = [6.5,4.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[8]))
x[idx[9],:] = np.random.multivariate_normal(mean = [5,3],cov=[[0.01,0],[0,0.01]],size=sum(idx[9]))
color = ['#1F77B4','orange', 'g','brown']
name = [1,2,3,0]
for i in range(10):
if i==3:
plt.scatter(x[idx[i],0],x[idx[i],1],c=color[3],label="D_"+str(name[i]))
elif i>=4:
plt.scatter(x[idx[i],0],x[idx[i],1],c=color[3])
else:
plt.scatter(x[idx[i],0],x[idx[i],1],c=color[i],label="D_"+str(name[i]))
plt.legend()
x[idx[0]][0], x[idx[5]][5]
desired_num = 6000
mosaic_list_of_images =[]
mosaic_label = []
fore_idx=[]
for j in range(desired_num):
np.random.seed(j)
fg_class = np.random.randint(0,3)
fg_idx = np.random.randint(0,9)
a = []
for i in range(9):
if i == fg_idx:
b = np.random.choice(np.where(idx[fg_class]==True)[0],size=1)
a.append(x[b])
# print("foreground "+str(fg_class)+" present at " + str(fg_idx))
else:
bg_class = np.random.randint(3,10)
b = np.random.choice(np.where(idx[bg_class]==True)[0],size=1)
a.append(x[b])
# print("background "+str(bg_class)+" present at " + str(i))
a = np.concatenate(a,axis=0)
mosaic_list_of_images.append(a)
mosaic_label.append(fg_class)
fore_idx.append(fg_idx)
len(mosaic_list_of_images), mosaic_list_of_images[0]
```
# load mosaic data
```
class MosaicDataset(Dataset):
"""MosaicDataset dataset."""
def __init__(self, mosaic_list, mosaic_label,fore_idx):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.mosaic = mosaic_list
self.label = mosaic_label
self.fore_idx = fore_idx
def __len__(self):
return len(self.label)
def __getitem__(self, idx):
return self.mosaic[idx] , self.label[idx] , self.fore_idx[idx]
batch = 250
msd1 = MosaicDataset(mosaic_list_of_images[0:3000], mosaic_label[0:3000] , fore_idx[0:3000])
train_loader = DataLoader( msd1 ,batch_size= batch ,shuffle=True)
batch = 250
msd2 = MosaicDataset(mosaic_list_of_images[3000:6000], mosaic_label[3000:6000] , fore_idx[3000:6000])
test_loader = DataLoader( msd2 ,batch_size= batch ,shuffle=True)
```
# models
```
class Focus_deep(nn.Module):
'''
deep focus network averaged at zeroth layer
input : elemental data
'''
def __init__(self,inputs,output,K,d):
super(Focus_deep,self).__init__()
self.inputs = inputs
self.output = output
self.K = K
self.d = d
self.linear1 = nn.Linear(self.inputs,50, bias=False) #,self.output)
self.linear2 = nn.Linear(50,50 , bias=False)
self.linear3 = nn.Linear(50,self.output, bias=False)
torch.nn.init.xavier_normal_(self.linear1.weight)
torch.nn.init.xavier_normal_(self.linear2.weight)
torch.nn.init.xavier_normal_(self.linear3.weight)
def forward(self,z):
batch = z.shape[0]
x = torch.zeros([batch,self.K],dtype=torch.float64)
y = torch.zeros([batch,50], dtype=torch.float64) # number of features of output
features = torch.zeros([batch,self.K,50],dtype=torch.float64)
x,y = x.to("cuda"),y.to("cuda")
features = features.to("cuda")
for i in range(self.K):
alp,ftrs = self.helper(z[:,i] ) # self.d*i:self.d*i+self.d
x[:,i] = alp[:,0]
features[:,i] = ftrs
x = F.softmax(x,dim=1) # alphas
for i in range(self.K):
x1 = x[:,i]
y = y+torch.mul(x1[:,None],features[:,i]) # self.d*i:self.d*i+self.d
return y , x
def helper(self,x):
x = self.linear1(x)
x = F.relu(x)
x = self.linear2(x)
x1 = F.tanh(x)
x = F.relu(x)
x = self.linear3(x)
#print(x1.shape)
return x,x1
class Classification_deep(nn.Module):
'''
input : elemental data
deep classification module data averaged at zeroth layer
'''
def __init__(self,inputs,output):
super(Classification_deep,self).__init__()
self.inputs = inputs
self.output = output
self.linear1 = nn.Linear(self.inputs,50)
#self.linear2 = nn.Linear(6,12)
self.linear2 = nn.Linear(50,self.output)
torch.nn.init.xavier_normal_(self.linear1.weight)
torch.nn.init.zeros_(self.linear1.bias)
torch.nn.init.xavier_normal_(self.linear2.weight)
torch.nn.init.zeros_(self.linear2.bias)
def forward(self,x):
x = F.relu(self.linear1(x))
#x = F.relu(self.linear2(x))
x = self.linear2(x)
return x
# torch.manual_seed(12)
# focus_net = Focus_deep(2,1,9,2).double()
# focus_net = focus_net.to("cuda")
# focus_net.linear2.weight.shape,focus_net.linear3.weight.shape
# focus_net.linear2.weight.data[25:,:] = focus_net.linear2.weight.data[:25,:] #torch.nn.Parameter(torch.tensor([last_layer]) )
# (focus_net.linear2.weight[:25,:]== focus_net.linear2.weight[25:,:] )
# focus_net.linear3.weight.data[:,25:] = -focus_net.linear3.weight.data[:,:25] #torch.nn.Parameter(torch.tensor([last_layer]) )
# focus_net.linear3.weight
# focus_net.helper( torch.randn((5,2,2)).double().to("cuda") )
def calculate_attn_loss(dataloader,what,where,criter):
what.eval()
where.eval()
r_loss = 0
alphas = []
lbls = []
pred = []
fidices = []
with torch.no_grad():
for i, data in enumerate(dataloader, 0):
inputs, labels,fidx = data
lbls.append(labels)
fidices.append(fidx)
inputs = inputs.double()
inputs, labels = inputs.to("cuda"),labels.to("cuda")
avg,alpha = where(inputs)
outputs = what(avg)
_, predicted = torch.max(outputs.data, 1)
pred.append(predicted.cpu().numpy())
alphas.append(alpha.cpu().numpy())
loss = criter(outputs, labels)
r_loss += loss.item()
alphas = np.concatenate(alphas,axis=0)
pred = np.concatenate(pred,axis=0)
lbls = np.concatenate(lbls,axis=0)
fidices = np.concatenate(fidices,axis=0)
#print(alphas.shape,pred.shape,lbls.shape,fidices.shape)
analysis = analyse_data(alphas,lbls,pred,fidices)
return r_loss/i,analysis
def analyse_data(alphas,lbls,predicted,f_idx):
'''
analysis data is created here
'''
batch = len(predicted)
amth,alth,ftpt,ffpt,ftpf,ffpf = 0,0,0,0,0,0
for j in range (batch):
focus = np.argmax(alphas[j])
if(alphas[j][focus] >= 0.5):
amth +=1
else:
alth +=1
if(focus == f_idx[j] and predicted[j] == lbls[j]):
ftpt += 1
elif(focus != f_idx[j] and predicted[j] == lbls[j]):
ffpt +=1
elif(focus == f_idx[j] and predicted[j] != lbls[j]):
ftpf +=1
elif(focus != f_idx[j] and predicted[j] != lbls[j]):
ffpf +=1
#print(sum(predicted==lbls),ftpt+ffpt)
return [ftpt,ffpt,ftpf,ffpf,amth,alth]
```
# training
```
number_runs = 10
FTPT_analysis = pd.DataFrame(columns = ["FTPT","FFPT", "FTPF","FFPF"])
full_analysis= []
for n in range(number_runs):
print("--"*40)
# instantiate focus and classification Model
torch.manual_seed(n)
where = Focus_deep(2,1,9,2).double()
where.linear2.weight.data[25:,:] = where.linear2.weight.data[:25,:]
where.linear3.weight.data[:,25:] = -where.linear3.weight.data[:,:25]
where = where.double().to("cuda")
ex,_ = where.helper( torch.randn((5,2,2)).double().to("cuda"))
print(ex)
torch.manual_seed(n)
what = Classification_deep(50,3).double()
where = where.to("cuda")
what = what.to("cuda")
# instantiate optimizer
optimizer_where = optim.Adam(where.parameters(),lr =0.001)#,momentum=0.9)
optimizer_what = optim.Adam(what.parameters(), lr=0.001)#,momentum=0.9)
criterion = nn.CrossEntropyLoss()
acti = []
analysis_data = []
loss_curi = []
epochs = 2000
# calculate zeroth epoch loss and FTPT values
running_loss,anlys_data = calculate_attn_loss(train_loader,what,where,criterion)
loss_curi.append(running_loss)
analysis_data.append(anlys_data)
print('epoch: [%d ] loss: %.3f' %(0,running_loss))
# training starts
for epoch in range(epochs): # loop over the dataset multiple times
ep_lossi = []
running_loss = 0.0
what.train()
where.train()
for i, data in enumerate(train_loader, 0):
# get the inputs
inputs, labels,_ = data
inputs = inputs.double()
inputs, labels = inputs.to("cuda"),labels.to("cuda")
# zero the parameter gradients
optimizer_where.zero_grad()
optimizer_what.zero_grad()
# forward + backward + optimize
avg, alpha = where(inputs)
outputs = what(avg)
loss = criterion(outputs, labels)
# print statistics
running_loss += loss.item()
loss.backward()
optimizer_where.step()
optimizer_what.step()
running_loss,anls_data = calculate_attn_loss(train_loader,what,where,criterion)
analysis_data.append(anls_data)
if(epoch % 200==0):
print('epoch: [%d] loss: %.3f' %(epoch + 1,running_loss))
loss_curi.append(running_loss) #loss per epoch
if running_loss<=0.01:
break
print('Finished Training run ' +str(n)+' at epoch: ',epoch)
analysis_data = np.array(analysis_data)
FTPT_analysis.loc[n] = analysis_data[-1,:4]/30
full_analysis.append((epoch, analysis_data))
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels,_ = data
images = images.double()
images, labels = images.to("cuda"), labels.to("cuda")
avg, alpha = where(images)
outputs = what(avg)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 3000 test images: %f %%' % ( 100 * correct / total))
print(np.mean(np.array(FTPT_analysis),axis=0))
FTPT_analysis
FTPT_analysis[FTPT_analysis['FTPT']+FTPT_analysis['FFPT'] > 90 ]
print(np.mean(np.array(FTPT_analysis[FTPT_analysis['FTPT']+FTPT_analysis['FFPT'] > 90 ]),axis=0))
cnt=1
for epoch, analysis_data in full_analysis:
analysis_data = np.array(analysis_data)
# print("="*20+"run ",cnt,"="*20)
plt.figure(figsize=(6,5))
plt.plot(np.arange(0,epoch+2,1),analysis_data[:,0]/30,label="FTPT")
plt.plot(np.arange(0,epoch+2,1),analysis_data[:,1]/30,label="FFPT")
plt.plot(np.arange(0,epoch+2,1),analysis_data[:,2]/30,label="FTPF")
plt.plot(np.arange(0,epoch+2,1),analysis_data[:,3]/30,label="FFPF")
plt.title("Training trends for run "+str(cnt))
plt.grid()
# plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.legend()
plt.xlabel("epochs", fontsize=14, fontweight = 'bold')
plt.ylabel("percentage train data", fontsize=14, fontweight = 'bold')
plt.savefig(path + "run"+str(cnt)+".png",bbox_inches="tight")
plt.savefig(path + "run"+str(cnt)+".pdf",bbox_inches="tight")
cnt+=1
FTPT_analysis.to_csv(path+"synthetic_zeroth.csv",index=False)
```
| github_jupyter |
```
class Solution:
def numberOfSubstrings(self, s: str) -> int:
letters = {'a', 'b', 'c'}
N = len(s)
count = 0
for gap in range(3, N + 1):
for start in range(N - gap + 1):
sub_str = s[start:start + gap]
if set(sub_str) == letters:
count += 1
return count
from collections import Counter
class Solution:
def numberOfSubstrings(self, s: str) -> int:
def count_letter(ct):
if ct['a'] and ct['b'] and ct['c']:
return True
return False
count = 0
for i in range(len(s)):
ctr = Counter(s[:len(s) - i])
for j in range(i + 1):
if j != 0:
start_idx = j - 1
end_idx = len(s) + start_idx - i
ctr[s[start_idx]] -= 1
ctr[s[end_idx]] += 1
if count_letter(ctr):
count += 1
return count
class Solution:
def numberOfSubstrings(self, s: str) -> int:
a, b, c = 0, 0, 0
ans, i, n = 0, 0, len(s)
for j, letter in enumerate(s):
if letter == 'a':
a += 1
elif letter == 'b':
b += 1
else:
c += 1
while a and b and c:
ans += n - j
print(n - j, n, j)
if s[i] == 'a':
a -= 1
elif s[i] == 'b':
b -= 1
else:
c -= 1
i += 1
return ans
solution = Solution()
solution.numberOfSubstrings('abcbb')
a = {'a', 'c', 'b'}
b = {'a', 'b', 'c'}
print(a == b)
class Solution:
def numberOfSubstrings(self, s: str) -> int:
a = b = c = 0 # counter for letter a/b/c
ans, i, n = 0, 0, len(s) # i: slow pointer
for j, letter in enumerate(s): # j: fast pointer
if letter == 'a': a += 1 # increment a/b/c accordingly
elif letter == 'b': b += 1
else: c += 1
while a > 0 and b > 0 and c > 0: # if all of a/b/c are contained, move slow pointer
ans += n-j # count possible substr, if a substr ends at j, then there are n-j substrs to the right that are containing all a/b/c
if s[i] == 'a': a -= 1 # decrement counter accordingly
elif s[i] == 'b': b -= 1
else: c -= 1
i += 1 # move slow pointer
return ans
```
| github_jupyter |
# Parse Java Methods
----
(C) Maxim Gansert, 2020, Mindscan Engineering
```
import sys
sys.path.insert(0,'../src')
import os
import datetime
from com.github.c2nes.javalang import tokenizer, parser, ast
from de.mindscan.fluentgenesis.dataprocessing.method_extractor import tokenize_file, extract_allmethods_from_compilation_unit
from de.mindscan.fluentgenesis.bpe.bpe_model import BPEModel
from de.mindscan.fluentgenesis.bpe.bpe_encoder_decoder import SimpleBPEEncoder
from de.mindscan.fluentgenesis.dataprocessing.method_dataset import MethodDataset
def split_methodbody_into_multiple_lines(method_body):
result = []
current_line_number = -1
current_line_tokens = []
for token in method_body:
token_line = token.position[0]
if token_line != current_line_number:
current_line_number = token_line
if len(current_line_tokens) != 0:
result.append(current_line_tokens)
current_line_tokens = []
current_line_tokens.append(token.value)
pass
if len(current_line_tokens) !=0:
result.append(current_line_tokens)
pass
return result
def process_source_file(dataset_directory, source_file_path, encoder, dataset):
# derive the full source file path
full_source_file_path = os.path.join( dataset_directory, source_file_path);
# Work on the source file
java_tokenlist = tokenize_file(full_source_file_path)
parsed_compilation_unit = parser.parse(java_tokenlist)
# collect file names, line numbers, method names, class names etc
all_methods_per_source = extract_allmethods_from_compilation_unit(parsed_compilation_unit, java_tokenlist)
for single_method in all_methods_per_source:
try:
method_name = single_method['method_name']
method_class_name = single_method['class_name']
method_body = single_method['method_body']
multi_line_body = split_methodbody_into_multiple_lines(method_body)
one_line = [item for sublist in multi_line_body for item in sublist]
print(one_line)
# encode body code and methodnames using the bpe-vocabulary
bpe_encoded_methodname = encoder.encode( [ method_name ] )
bpe_encoded_methodbody_ml = encoder.encode_multi_line( multi_line_body )
# do some calculations on the tokens and on the java code, so selection of smaller datasets is possible
bpe_encoded_method_name_length = len(bpe_encoded_methodname)
bpe_encoded_method_body_length = sum([len(line) for line in bpe_encoded_methodbody_ml])
# save this into dataset
method_data = {
"source_file_path": source_file_path,
"method_class_name": method_class_name,
"method_name": method_name,
"encoded_method_name_length": bpe_encoded_method_name_length,
"encoded_method_name": bpe_encoded_methodname,
"encoded_method_body_length": bpe_encoded_method_body_length,
"encoded_method_body": bpe_encoded_methodbody_ml,
"method_body": method_body
}
dataset.add_method_data( method_data )
except:
# ignore problematic method
pass
model = BPEModel("16K-full", "../src/de/mindscan/fluentgenesis/bpe/")
model.load_hparams()
dataset_directory = 'D:\\Downloads\\Big-Code-excerpt\\'
model_vocabulary = model.load_tokens()
model_bpe_data = model.load_bpe_pairs()
encoder = SimpleBPEEncoder(model_vocabulary, model_bpe_data)
method_dataset = MethodDataset(dataset_name='parseMethodPythonNotebook1.jsonl')
method_dataset.prepareNewDataset(dataset_directory)
process_source_file(dataset_directory,'wordhash/WordMap.java' ,encoder, method_dataset )
method_dataset.finish()
```
| github_jupyter |
```
%matplotlib inline
from matplotlib import pyplot as plt
plt.rcParams['figure.figsize'] = (10, 8)
import seaborn as sns
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import collections
from sklearn.model_selection import GridSearchCV
from sklearn import preprocessing
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import pickle
cmp_df = pd.DataFrame(columns=['ID', 'TITLE', 'CMP_TYPE_CUSTOMER', 'CMP_TYPE_PARTNER'])
cmp_df
data_train = pd.read_csv('data/dataframe.csv', sep=';', index_col='ID')
data_test = pd.read_csv('data/dataframe.csv', sep=';', index_col='ID')
data_train
title_df = pd.DataFrame(data_train['TITLE'])
title_df.head()
data_train = data_train.drop(columns=['TITLE'], axis=1)
data_test = data_test.drop(columns=['TITLE'], axis=1)
data_test.describe(include='all').T
fig = plt.figure(figsize=(25, 15))
cols = 5
rows = np.ceil(float(data_train.shape[1]) / cols)
for i, column in enumerate(data_train.columns):
ax = fig.add_subplot(rows, cols, i + 1)
ax.set_title(column)
if data_train.dtypes[column] == np.object:
data_train[column].value_counts().plot(kind="bar", axes=ax)
else:
data_train[column].hist(axes=ax)
plt.xticks(rotation="vertical")
plt.subplots_adjust(hspace=0.7, wspace=0.2)
X_train=data_train.drop(['target'], axis=1)
y_train = data_train['target']
X_test=data_test.drop(['target'], axis=1)
y_test = data_test['target']
tree = DecisionTreeClassifier(criterion = "entropy", max_depth = 3, random_state = 17)
tree.fit(X = X_train, y = y_train)
tree_predictions = tree.predict(X = X_test) # Ваш код здесь
tree_predictions
accuracy_score = tree.score(X = X_test, y = y_test)
print(accuracy_score)
rf = RandomForestClassifier(criterion="entropy", random_state = 17, n_estimators=200,
max_depth=4, max_features=0.15 ,n_jobs=-1)
rf.fit(X = X_train, y = y_train) # Ваш код здесь
forest_predictions = rf.predict(X = X_test)
print(forest_predictions)
accuracy_score = rf.score(X = X_test, y = y_test)
print(accuracy_score)
pickle.dump(rf, open('random_forest.sav', 'wb'))
model = pickle.load(open('random_forest.sav', 'rb'))
predict = model.predict(X=X_test)
predict
title_df = title_df.reset_index(drop=True)
predict = pd.Series(predict).rename('PREDICT')
predict = predict.rename('PREDICT')
result_df = pd.concat([title_df, predict], axis=1)
result_df
```
--------------------------------------------------------------------------------------------------------------------------------
```
forest_params = {'max_depth': range(4, 21),
'max_features': range(7, 45),
'random_state': range(1, 100)}
locally_best_forest = GridSearchCV(rf, forest_params, n_jobs=-1)
locally_best_forest.fit(X = X_train, y = y_train)
print("Best params:", locally_best_forest.best_params_)
print("Best cross validaton score", locally_best_forest.best_score_)
tuned_forest_predictions = locally_best_forest.predict(X = X_test) # Ваш код здесь
accuracy_score = locally_best_forest.score(X = X_test, y = y_test)
print(accuracy_score)
tuned_forest_predictions
```
| github_jupyter |
The first thing we need to do is to download the dataset from Kaggle. We use the [Enron dataset](https://www.kaggle.com/wcukierski/enron-email-dataset), which is the biggest public email dataset available.
To do so we will use GDrive and download the dataset within a Drive folder to be used by Colab.
```
from google.colab import drive
drive.mount('/content/gdrive')
import os
os.environ['KAGGLE_CONFIG_DIR'] = "/content/gdrive/My Drive/Kaggle"
%cd /content/gdrive/My Drive/Kaggle
```
We can download the dataset from Kaggle and save it in the GDrive folder. This needs to be done only the first time.
```
# !kaggle datasets download -d wcukierski/enron-email-dataset
# unzipping the zip files
# !unzip \*.zip
```
Now we are finally ready to start working with the dataset, accessible as a CSV file called `emails.csv`.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import email
import re
if not 'emails_df' in locals():
emails_df = pd.read_csv('./emails.csv')
# Use only a subpart of the whole dataset to avoid exceeding RAM
# emails_df = emails_df[:10000]
print(emails_df.shape)
emails_df.head()
print(emails_df['message'][0])
# Convert to message objects from the message strings
messages = list(map(email.message_from_string, emails_df['message']))
def get_text_from_email(msg):
parts = []
for part in msg.walk():
if part.get_content_type() == 'text/plain':
parts.append( part.get_payload() )
text = ''.join(parts)
return text
emails = pd.DataFrame()
# Parse content from emails
emails['content'] = list(map(get_text_from_email, messages))
import gc
# Remove variables from memory
del messages
del emails_df
gc.collect()
def normalize_text(text):
text = text.lower()
# creating a space between a word and the punctuation following it to separate words
# and compact repetition of punctuation
# eg: "he is a boy.." => "he is a boy ."
text = re.sub(r'([.,!?]+)', r" \1 ", text)
# replacing everything with space except (a-z, A-Z, ".", "?", "!", ",", "'")
text = re.sub(r"[^a-zA-Z?.!,']+", " ", text)
# Compact spaces
text = re.sub(r'[" "]+', " ", text)
# Remove forwarded messages
text = text.split('forwarded by')[0]
text = text.strip()
return text
emails['content'] = list(map(normalize_text, emails['content']))
# Drop samples with empty content text after normalization
emails['content'].replace('', np.nan, inplace=True)
emails.dropna(subset=['content'], inplace=True)
pd.set_option('max_colwidth', -1)
emails.head(50)
```
In the original paper, the dataset is built with 8billion emails where the context is provided by the email date, subject and previous message if the user is replying. Unfortunately, in the Enron dataset it's not possible to build the reply relationship between emails. In order thus to generate the context of a sentence, we train the sequence-to-sequence model to predict the sentence completion from pairs of split sentences.
For instance, the sentence `here is our forecast` is split in the following pairs within the dataset:
```
[
('<start> here is <end>', '<start> our forecast <end>'),
('<start> here is our <end>', '<start> forecast <end>')
]
```
```
# Skip long sentences, which increase maximum length a lot when padding
# and make the number of parameters to train explode
SENTENCE_MAX_WORDS = 20
def generate_dataset (emails):
contents = emails['content']
output = []
vocabulary_sentences = []
for content in contents:
# Skip emails longer than one sentence
if (len(content) > SENTENCE_MAX_WORDS * 5):
continue
sentences = content.split(' . ')
for sentence in sentences:
# Remove user names from start or end of sentence. This is just an heuristic
# but it's more efficient than compiling the list of names and removing all of them
sentence = re.sub("(^\w+\s,\s)|(\s,\s\w+$)", "", sentence)
words = sentence.split(' ')
if ((len(words) > SENTENCE_MAX_WORDS) or (len(words) < 2)):
continue
vocabulary_sentences.append('<start> ' + sentence + ' <end>')
for i in range(1, len(words) - 1):
input_data = '<start> ' + ' '.join(words[:i+1]) + ' <end>'
output_data = '<start> ' + ' '.join(words[i+1:]) + ' <end>'
data = (input_data, output_data)
output.append(data)
return output, vocabulary_sentences
pairs, vocabulary_sentences = generate_dataset(emails)
print(len(pairs))
print(len(vocabulary_sentences))
print(*pairs[:10], sep='\n')
print(*vocabulary_sentences[:10], sep='\n')
```
This is where the fun begins. The dataset is finally available and we start working on the analysis by using [Keras](https://keras.io/) and [TensorFlow](https://www.tensorflow.org/).
```
import tensorflow as tf
from tensorflow import keras
np.random.seed(42)
```
We need to transform the text corpora into sequences of integers (each integer being the index of a token in a dictionary) by using keras `Tokenizer`. We also limit to the 10k most frequent words, deleting uncommon words from sentences.
Normally we would use two tokenizers, one for the input strings and a different one for the output text, but in this case we are predicting the same vocabulary in both cases. All the words in the output texts are available also in the input texts because of how dataset pairs are generated.
Also since we will apply the "teacher forcing" technique during training, we need both the target data and the (target + 1 timestep) data.
```
vocab_max_size = 10000
def tokenize(text):
tokenizer = keras.preprocessing.text.Tokenizer(filters='', num_words=vocab_max_size)
tokenizer.fit_on_texts(text)
return tokenizer
input = [pair[0] for pair in pairs]
output = [pair[1] for pair in pairs]
tokenizer = tokenize(vocabulary_sentences)
encoder_input = tokenizer.texts_to_sequences(input)
decoder_input = tokenizer.texts_to_sequences(output)
decoder_target = [
[decoder_input[seqN][tokenI + 1]
for tokenI in range(len(decoder_input[seqN]) - 1)]
for seqN in range(len(decoder_input))]
# Convert to np.array
encoder_input = np.array(encoder_input)
decoder_input = np.array(decoder_input)
decoder_target = np.array(decoder_target)
from sklearn.model_selection import train_test_split
encoder_input_train, encoder_input_test, decoder_input_train, decoder_input_test, decoder_target_train, decoder_target_test = train_test_split(encoder_input, decoder_input, decoder_target, test_size=0.2)
print(encoder_input_train.shape, encoder_input_test.shape)
print(decoder_input_train.shape, decoder_input_test.shape)
print(decoder_target_train.shape, decoder_target_test.shape)
def max_length(t):
return max(len(i) for i in t)
max_length_in = max_length(encoder_input)
max_length_out = max_length(decoder_input)
encoder_input_train = keras.preprocessing.sequence.pad_sequences(encoder_input_train, maxlen=max_length_in, padding="post")
decoder_input_train = keras.preprocessing.sequence.pad_sequences(decoder_input_train, maxlen=max_length_out, padding="post")
decoder_target_train = keras.preprocessing.sequence.pad_sequences(decoder_target_train, maxlen=max_length_out, padding="post")
encoder_input_test = keras.preprocessing.sequence.pad_sequences(encoder_input_test, maxlen=max_length_in, padding="post")
decoder_input_test = keras.preprocessing.sequence.pad_sequences(decoder_input_test, maxlen=max_length_out, padding="post")
decoder_target_test = keras.preprocessing.sequence.pad_sequences(decoder_target_test, maxlen=max_length_out, padding="post")
print(max_length_in, max_length_out)
# Shuffle the data in unison
p = np.random.permutation(len(encoder_input_train))
encoder_input_train = encoder_input_train[p]
decoder_input_train = decoder_input_train[p]
decoder_target_train = decoder_target_train[p]
q = np.random.permutation(len(encoder_input_test))
encoder_input_test = encoder_input_test[q]
decoder_input_test = decoder_input_test[q]
decoder_target_test = decoder_target_test[q]
import math
batch_size = 128
vocab_size = vocab_max_size if len(tokenizer.word_index) > vocab_max_size else len(tokenizer.word_index)
# Rule of thumb of embedding size: vocab_size ** 0.25
# https://stackoverflow.com/questions/48479915/what-is-the-preferred-ratio-between-the-vocabulary-size-and-embedding-dimension
embedding_dim = math.ceil(vocab_size ** 0.25)
latent_dim = 192 # Latent dimensionality of the encoding space.
print(vocab_size, embedding_dim)
```
Here we define the RNN models. We start with the Encoder-Decoder model used in training which leverages the "teacher forcing technique". Therefore, it will receive as input `encoder_input` and `decoder_input` datasets.
Then the second model is represented by the inference Decoder which will receive as input the encoded states of the input sequence and the predicted token of the previous time step.
Both models use GRU units to preserve the context state, which have been shown to be more accurate than LSTM units and simpler to use since they have only one state.
```
# GRU Encoder
encoder_in_layer = keras.layers.Input(shape=(max_length_in,))
encoder_embedding = keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim)
encoder_bi_gru = keras.layers.Bidirectional(keras.layers.GRU(units=latent_dim, return_sequences=True, return_state=True))
# Discard the encoder output and use hidden states (h) and memory cells states (c)
# for forward (f) and backward (b) layer
encoder_out, fstate_h, bstate_h = encoder_bi_gru(encoder_embedding(encoder_in_layer))
state_h = keras.layers.Concatenate()([fstate_h, bstate_h])
# GRUDecoder
decoder_in_layer = keras.layers.Input(shape=(None,))
decoder_embedding = keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim)
decoder_gru = keras.layers.GRU(units=latent_dim * 2, return_sequences=True, return_state=True)
# Discard internal states in training, keep only the output sequence
decoder_gru_out, _ = decoder_gru(decoder_embedding(decoder_in_layer), initial_state=state_h)
decoder_dense_1 = keras.layers.Dense(128, activation="relu")
decoder_dense = keras.layers.Dense(vocab_size, activation="softmax")
decoder_out_layer = decoder_dense(keras.layers.Dropout(rate=0.2)(decoder_dense_1(keras.layers.Dropout(rate=0.2)(decoder_gru_out))))
# Define the model that uses the Encoder and the Decoder
model = keras.models.Model([encoder_in_layer, decoder_in_layer], decoder_out_layer)
def perplexity(y_true, y_pred):
return keras.backend.exp(keras.backend.mean(keras.backend.sparse_categorical_crossentropy(y_true, y_pred)))
model.compile(optimizer='adam', loss="sparse_categorical_crossentropy", metrics=[perplexity])
model.summary()
keras.utils.plot_model(model, "encoder-decoder.png", show_shapes=True)
epochs = 10
history = model.fit([encoder_input_train, decoder_input_train], decoder_target_train,
batch_size=batch_size,
epochs=epochs,
validation_split=0.2)
def plot_history(history):
plt.plot(history.history['loss'], label="Training loss")
plt.plot(history.history['val_loss'], label="Validation loss")
plt.legend()
plot_history(history)
scores = model.evaluate([encoder_input_test[:1000], decoder_input_test[:1000]], decoder_target_test[:1000])
print("%s: %.2f" % (model.metrics_names[1], scores[1]))
# Inference Decoder
encoder_model = keras.models.Model(encoder_in_layer, state_h)
state_input_h = keras.layers.Input(shape=(latent_dim * 2,))
inf_decoder_out, decoder_h = decoder_gru(decoder_embedding(decoder_in_layer), initial_state=state_input_h)
inf_decoder_out = decoder_dense(decoder_dense_1(inf_decoder_out))
inf_model = keras.models.Model(inputs=[decoder_in_layer, state_input_h],
outputs=[inf_decoder_out, decoder_h])
keras.utils.plot_model(encoder_model, "encoder-model.png", show_shapes=True)
keras.utils.plot_model(inf_model, "inference-model.png", show_shapes=True)
def tokenize_text(text):
text = '<start> ' + text.lower() + ' <end>'
text_tensor = tokenizer.texts_to_sequences([text])
text_tensor = keras.preprocessing.sequence.pad_sequences(text_tensor, maxlen=max_length_in, padding="post")
return text_tensor
# Reversed map from a tokenizer index to a word
index_to_word = dict(map(reversed, tokenizer.word_index.items()))
# Given an input string, an encoder model (infenc_model) and a decoder model (infmodel),
def decode_sequence(input_tensor):
# Encode the input as state vectors.
state = encoder_model.predict(input_tensor)
target_seq = np.zeros((1, 1))
target_seq[0, 0] = tokenizer.word_index['<start>']
curr_word = "<start>"
decoded_sentence = ''
i = 0
while curr_word != "<end>" and i < (max_length_out - 1):
output_tokens, h = inf_model.predict([target_seq, state])
curr_token = np.argmax(output_tokens[0, 0])
if (curr_token == 0):
break;
curr_word = index_to_word[curr_token]
decoded_sentence += ' ' + curr_word
target_seq[0, 0] = curr_token
state = h
i += 1
return decoded_sentence
def tokens_to_seq(tokens):
words = list(map(lambda token: index_to_word[token] if token != 0 else '', tokens))
return ' '.join(words)
```
Let's test the inference model with some inputs.
```
texts = [
'here is',
'have a',
'please review',
'please call me',
'thanks for',
'let me',
'Let me know',
'Let me know if you',
'this sounds',
'is this call going to',
'can you get',
'is it okay',
'it should',
'call if there\'s',
'gave her a',
'i will let',
'i will be',
'may i get a copy of all the',
'how is our trade',
'this looks like a',
'i am fine with the changes',
'please be sure this'
]
output = list(map(lambda text: (text, decode_sequence(tokenize_text(text))), texts))
output_df = pd.DataFrame(output, columns=["input", "output"])
output_df.head(len(output))
```
The predicted outputs are actually quite good. The grammar is correct and have a logical sense. Some predictions also show that the predictions are personalized based on the Enron dataset, for instance in the case of `here is - the latest version of the presentation`.
The `please review - the attached outage report` also shows personalized prediction. This is consistent with the goal the task.
Save the Tokenizer and the Keras model for usage within the browser.
```
import json
with open( 'word_dict-final.json' , 'w' ) as file:
json.dump( tokenizer.word_index , file)
encoder_model.save('./encoder-model-final.h5')
inf_model.save('./inf-model-final.h5')
```
| github_jupyter |
## 1. The brief
<p>Imagine working for a digital marketing agency, and the agency is approached by a massive online retailer of furniture. They want to test our skills at creating large campaigns for all of their website. We are tasked with creating a prototype set of keywords for search campaigns for their sofas section. The client says that they want us to generate keywords for the following products: </p>
<ul>
<li>sofas</li>
<li>convertible sofas</li>
<li>love seats</li>
<li>recliners</li>
<li>sofa beds</li>
</ul>
<p><strong>The brief</strong>: The client is generally a low-cost retailer, offering many promotions and discounts. We will need to focus on such keywords. We will also need to move away from luxury keywords and topics, as we are targeting price-sensitive customers. Because we are going to be tight on budget, it would be good to focus on a tightly targeted set of keywords and make sure they are all set to exact and phrase match.</p>
<p>Based on the brief above we will first need to generate a list of words, that together with the products given above would make for good keywords. Here are some examples:</p>
<ul>
<li>Products: sofas, recliners</li>
<li>Words: buy, prices</li>
</ul>
<p>The resulting keywords: 'buy sofas', 'sofas buy', 'buy recliners', 'recliners buy',
'prices sofas', 'sofas prices', 'prices recliners', 'recliners prices'.</p>
<p>As a final result, we want to have a DataFrame that looks like this: </p>
<table>
<thead>
<tr>
<th>Campaign</th>
<th>Ad Group</th>
<th>Keyword</th>
<th>Criterion Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>Campaign1</td>
<td>AdGroup_1</td>
<td>keyword 1a</td>
<td>Exact</td>
</tr>
<tr>
<td>Campaign1</td>
<td>AdGroup_1</td>
<td>keyword 1a</td>
<td>Phrase</td>
</tr>
<tr>
<td>Campaign1</td>
<td>AdGroup_1</td>
<td>keyword 1b</td>
<td>Exact</td>
</tr>
<tr>
<td>Campaign1</td>
<td>AdGroup_1</td>
<td>keyword 1b</td>
<td>Phrase</td>
</tr>
<tr>
<td>Campaign1</td>
<td>AdGroup_2</td>
<td>keyword 2a</td>
<td>Exact</td>
</tr>
<tr>
<td>Campaign1</td>
<td>AdGroup_2</td>
<td>keyword 2a</td>
<td>Phrase</td>
</tr>
</tbody>
</table>
<p>The first step is to come up with a list of words that users might use to express their desire in buying low-cost sofas.</p>
```
# List of words to pair with products
words = ['buy', 'discount', 'promotion', 'cheap', 'offer', 'purchase', 'sale']
# Print list of words
print(words)
```
## 2. Combine the words with the product names
<p>Imagining all the possible combinations of keywords can be stressful! But not for us, because we are keyword ninjas! We know how to translate campaign briefs into Python data structures and can imagine the resulting DataFrames that we need to create.</p>
<p>Now that we have brainstormed the words that work well with the brief that we received, it is now time to combine them with the product names to generate meaningful search keywords. We want to combine every word with every product once before, and once after, as seen in the example above.</p>
<p>As a quick reminder, for the product 'recliners' and the words 'buy' and 'price' for example, we would want to generate the following combinations: </p>
<p>buy recliners<br>
recliners buy<br>
price recliners<br>
recliners price<br>
... </p>
<p>and so on for all the words and products that we have.</p>
```
products = ['sofas', 'convertible sofas', 'love seats', 'recliners', 'sofa beds']
# Create an empty list
keywords_list = []
# Loop through products
for product in products:
# Loop through words
for word in words:
# Append combinations
keywords_list.append([product, product + ' ' + word])
keywords_list.append([product, word + ' ' + product])
# Inspect keyword list
print(keywords_list)
```
## 3. Convert the list of lists into a DataFrame
<p>Now we want to convert this list of lists into a DataFrame so we can easily manipulate it and manage the final output.</p>
```
# Load library
# ... YOUR CODE FOR TASK 3 ...
import pandas as pd
# Create a DataFrame from list
keywords_df = pd.DataFrame.from_records(keywords_list)
# Print the keywords DataFrame to explore it
# ... YOUR CODE FOR TASK 3 ...
print(keywords_df.head())
```
## 4. Rename the columns of the DataFrame
<p>Before we can upload this table of keywords, we will need to give the columns meaningful names. If we inspect the DataFrame we just created above, we can see that the columns are currently named <code>0</code> and <code>1</code>. <code>Ad Group</code> (example: "sofas") and <code>Keyword</code> (example: "sofas buy") are much more appropriate names.</p>
```
# Rename the columns of the DataFrame
keywords_df.columns = ['Ad Group', 'Keyword']
```
## 5. Add a campaign column
<p>Now we need to add some additional information to our DataFrame.
We need a new column called <code>Campaign</code> for the campaign name. We want campaign names to be descriptive of our group of keywords and products, so let's call this campaign 'SEM_Sofas'.</p>
```
# Add a campaign column
# ... YOUR CODE FOR TASK 5 ...
keywords_df['Campaign'] = 'SEM_Sofas'
```
## 6. Create the match type column
<p>There are different keyword match types. One is exact match, which is for matching the exact term or are close variations of that exact term. Another match type is broad match, which means ads may show on searches that include misspellings, synonyms, related searches, and other relevant variations.</p>
<p>Straight from Google's AdWords <a href="https://support.google.com/google-ads/answer/2497836?hl=en">documentation</a>:</p>
<blockquote>
<p>In general, the broader the match type, the more traffic potential that keyword will have, since your ads may be triggered more often. Conversely, a narrower match type means that your ads may show less often—but when they do, they’re likely to be more related to someone’s search.</p>
</blockquote>
<p>Since the client is tight on budget, we want to make sure all the keywords are in exact match at the beginning.</p>
```
# Add a criterion type column
# ... YOUR CODE FOR TASK 6 ...
keywords_df['Criterion Type'] = 'Exact'
```
## 7. Duplicate all the keywords into 'phrase' match
<p>The great thing about exact match is that it is very specific, and we can control the process very well. The tradeoff, however, is that: </p>
<ol>
<li>The search volume for exact match is lower than other match types</li>
<li>We can't possibly think of all the ways in which people search, and so, we are probably missing out on some high-quality keywords.</li>
</ol>
<p>So it's good to use another match called <em>phrase match</em> as a discovery mechanism to allow our ads to be triggered by keywords that include our exact match keywords, together with anything before (or after) them.</p>
<p>Later on, when we launch the campaign, we can explore with modified broad match, broad match, and negative match types, for better visibility and control of our campaigns.</p>
```
# Make a copy of the keywords DataFrame
keywords_phrase = keywords_df.copy()
# Change criterion type match to phrase
# ... YOUR CODE FOR TASK 7 ...
keywords_phrase['Criterion Type'] = 'Phrase'
# Append the DataFrames
keywords_df_final = keywords_df.append(keywords_phrase)
```
## 8. Save and summarize!
<p>To upload our campaign, we need to save it as a CSV file. Then we will be able to import it to AdWords editor or BingAds editor. There is also the option of pasting the data into the editor if we want, but having easy access to the saved data is great so let's save to a CSV file!</p>
<p>To wrap up our campaign work, it is good to look at a summary of our campaign structure. We can do that by grouping by ad group and criterion type and counting by keyword.</p>
```
# Save the final keywords to a CSV file
# ... YOUR CODE FOR TASK 8 ...
keywords_df_final.to_csv('keywords.csv', index=False)
# View a summary of our campaign work
summary = keywords_df_final.groupby(['Ad Group', 'Criterion Type'])['Keyword'].count()
print(summary)
```
| github_jupyter |
# LSTM - Long Short Term Memory
- From [v1] Lecture 60
- LSTM, another variation of RNN
## Study Links
- [An empirical exploration of recurrent network architectures](https://dl.acm.org/citation.cfm?id=3045367)
- https://dblp.uni-trier.de/db/journals/corr/corr1506.html
- [A Critical Review of Recurrent Neural Networks for Sequence Learning](https://arxiv.org/pdf/1506.00019.pdf)
- [Deep Learning](https://web.cs.hacettepe.edu.tr/~aykut/classes/spring2018/cmp784/slides/lec7-recurrent-neural-nets.pdf)
## Problems with Vanilla RNN
- The component of the gradient in directions that correspond to long-term dependencies is [small](https://dl.acm.org/citation.cfm?id=3045118.3045367)
- From state $t$ to state $0$
- The components of the gradient in directions that correspond to short-term dependencies are large
- As a result, RNNs can easily learn the short-term but not the long-term dependencies
## LSTM
- In LSTM network, the network is the same as a standard RNN, except that the summation units in the hidden layer are replaced by memory blocks
- This will be done in $\large s_t$
- The multiplicative gates allow LSTM memory cells to store and access information over periods of time, thereby mitigating the [vanishing gradient problem](https://dblp.uni-trier.de/db/journals/corr/corr1506.html)
- LSTM will have multiple gates that allows cells to keep some information or loose some information
- By doing this we want to acheive the long term dependency in the network
- At the same time, solving the problem of Vanishing Gradient Problem [37]
- Along with the hidden state vector $\large h_t$, LSTM maintains a memory vector $\large C_t$
- $\large \large h_{t} = \text{tanh} \left(Uh_{t-1}+ W {x_{t}} \right)$ going to be replaced with $\large C_t$
- $\large C_t$ is going to tell us how to condition the values of $\large U$, so that _vanishing gradient problem disappears_
- At each time step, the LSTM can choose to read from, write to, or reset the cell using explicit gating mechanisms
- A small computer kind of logic exist inside, which is able to read, write and reset operations, so that $\large h$ values are very well conditioned
- LSTM computes well behaved gradients by controlling the values using the gates
## LSTM Cell
- See [Recurrent Neural Networks (RNN) and Long Short-Term Memory (LSTM)](https://www.youtube.com/watch?v=WCUNPb-5EYI&list=PLVZqlMpoM6kaJX_2lLKjEhWI0NlqHfqzp&index=5&t=0s) and [A friendly introduction to Recurrent Neural Networks](https://www.youtube.com/watch?v=UNmqTiOnRfg) to get very good intuition of how LSTM works
- Below diagram shows how does a LSTM Cell look like
- $\large h_t$ is replaced by this cell
- The operations depicted in below diagram are performed during Forward Pass

- $\large C_t$ $\Rightarrow$ Previous memory state
- $\large C_t$ is a vector
- $\large h_t$ $\Rightarrow$ Previous state of the hidden unit
- $\large W$ $Rightarrpw$ denotes the weight vector
- $\large q_t$ $\Rightarrow$ netsum of Input vector with weight vector $\large W$
- $\large f_t$ $\Rightarrow$ is the forget gate, computed using vector $\large W_f$, having a $Sigmoid$ as activation function
- $\large i_t$ $\Rightarrow$ is the input cell, computed using vector $\large W_i$, having a $Sigmoid$ as activation function
- $\large \widetilde{C_t}$ $\Rightarrow$ new computed memory, computed using vector $\large W_{\widetilde{C_t}}$, having a $tanh$ activation function
- $\large O_t$is the output gate, computed using vector $\large W_{O_t}$, having a $Sigmoid$ activation function
- $\large \otimes$ refers to element wise multiplication
- $\large \oplus$ refers to element wise addition
## LSTM - Forward Pass

| github_jupyter |
# US Treasury Interest Rates / Yield Curve Data
---
A look at the US Treasury yield curve, according to interest rates published by the US Treasury.
```
import pandas as pd
import altair as alt
import numpy as np
url = 'https://www.treasury.gov/resource-center/data-chart-center/interest-rates/pages/TextView.aspx?data=yieldYear&year={year}'
def fetchRates(year):
df = pd.read_html(url.format(year=year), skiprows=0, attrs={ "class": "t-chart" })[0]
df['Date'] = pd.to_datetime(df.Date)
return df.set_index('Date').resample('1m').last().reset_index()
fetchTsRates = lambda years: pd.concat(map(fetchRates, years))
#fetchRates(2019).head()
```
## How do the interest rates look for the past 4 years (by instrument)?
```
years = range(2016, 2022)
fields = ['Date', '3 mo', '1 yr', '2 yr', '7 yr', '10 yr']
dfm = fetchTsRates(years)[fields].melt(id_vars='Date', var_name='Maturity')
alt.Chart(dfm).mark_line().encode(
alt.X('Date:T', axis=alt.Axis(title='')),
alt.Y('value:Q',
axis=alt.Axis(title='Interest Rate [%]'),
scale=alt.Scale(domain=[np.floor(dfm['value'].apply(float).min()), np.ceil(dfm['value'].apply(float).max())])),
alt.Color('Maturity:N', sort=fields[1:]),
tooltip=[alt.Tooltip('Date:T', format='%b %Y'), alt.Tooltip('Maturity:N'), alt.Tooltip('value:Q')]
).properties(
title='U.S. Treasury Yields from {y1} to {y2}'.format(y1=min(years), y2=max(years)),
height=450,
width=700,
background='white'
)
```
### Same chart as above, just a different mix of instruments
```
years = range(2016, 2022)
fields = ['Date', '6 mo', '2 yr', '3 yr', '10 yr', '30 yr']
dfm = fetchTsRates(years)[fields].melt(id_vars='Date', var_name='Maturity')
c = alt.Chart(dfm).mark_line().encode(
alt.X('Date:T', axis=alt.Axis(title='')),
alt.Y('value:Q',
axis=alt.Axis(title='Interest Rate [%]'),
scale=alt.Scale(domain=[np.floor(dfm['value'].apply(float).min()), np.ceil(dfm['value'].apply(float).max())])),
alt.Color('Maturity:N', sort=fields[1:]),
tooltip=[alt.Tooltip('Date:T', format='%b %Y'), alt.Tooltip('Maturity:N'), alt.Tooltip('value:Q')]
).properties(
title='U.S. Treasury Yields from {y1} to {y2}'.format(y1=min(years), y2=max(years)),
height=450,
width=700,
background='white'
)
c.save('us-treasury-rates.png')
c.display()
```
## How did that chart look for the 4 years before 2008?
```
years = range(2004, 2010)
fields = ['Date', '6 mo', '2 yr', '3 yr', '10 yr', '30 yr']
dfm2 = fetchTsRates(years)[fields].melt(id_vars='Date', var_name='Maturity')
alt.Chart(dfm2).mark_line().encode(
alt.X('Date:T', axis=alt.Axis(title='', format='%b %Y')),
alt.Y('value:Q',
axis=alt.Axis(title='Interest Rate [%]'),
scale=alt.Scale(domain=[np.floor(dfm2['value'].apply(float).min()), np.ceil(dfm2['value'].apply(float).max())])),
alt.Color('Maturity:N', sort=fields[1:]),
tooltip=[alt.Tooltip('Date:T', format='%b %Y'), alt.Tooltip('Maturity:N'), alt.Tooltip('value:Q')]
).properties(
title='U.S. Treasury Yields from {y1} to {y2}'.format(y1=min(years), y2=max(years)),
height=450,
width=700,
background='white'
)
year = 2019
alt.Chart(fetchRates(year).melt(id_vars='Date', var_name='Maturity')).mark_line().encode(
alt.X('Date:T', axis=alt.Axis(title='')),
alt.Y('value:Q', axis=alt.Axis(title='Interest Rate [%]'), scale=alt.Scale(zero=False)),
alt.Color('Maturity:N',
sort=['1 mo', '2 mo', '3 mo', '6 mo', '1 yr', '2 yr', '3 yr', '5 yr', '7 yr', '10 yr', '20 yr', '30 yr']),
tooltip=[alt.Tooltip('Date:T', format='%b %Y'), alt.Tooltip('Maturity:N'), alt.Tooltip('value:Q')]
).properties(
title='U.S. Treasury Yields for {year}'.format(year=year),
height=450,
width=700
).interactive()
year = 2007
alt.Chart(fetchRates(year).melt(id_vars='Date', var_name='Maturity')).mark_line().encode(
alt.X('Date:T', axis=alt.Axis(title='')),
alt.Y('value:Q', axis=alt.Axis(title='Interest Rate [%]'), scale=alt.Scale(zero=False)),
alt.Color('Maturity:N',
sort=['1 mo', '2 mo', '3 mo', '6 mo', '1 yr', '2 yr', '3 yr', '5 yr', '7 yr', '10 yr', '20 yr', '30 yr']),
tooltip=[alt.Tooltip('Date:T', format='%b %Y'), alt.Tooltip('Maturity:N'), alt.Tooltip('value:Q')]
).properties(
title='U.S. Treasury Yields for {year}'.format(year=year),
height=450,
width=700
).interactive()
year = 1996
alt.Chart(fetchRates(year).melt(id_vars='Date', var_name='Maturity')).mark_line().encode(
alt.X('Date:T', axis=alt.Axis(title='')),
alt.Y('value:Q', axis=alt.Axis(title='Interest Rate [%]'), scale=alt.Scale(zero=False)),
alt.Color('Maturity:N'),
tooltip=[alt.Tooltip('Date:T', format='%b %Y'), alt.Tooltip('Maturity:N'), alt.Tooltip('value:Q')]
).properties(
title='U.S. Treasury Yields for {year}'.format(year=year),
height=450,
width=700
).interactive()
```
## Visualizing the "yield curve" of US Treasuries
```
years = range(2004, 2009)
instruments = {
0.25: '3 Month T-bill',
0.5: '6 Month T-bill',
2: '2 Year Note',
10: '10 Year Note',
30: '30 Year Bond'
}
fieldsToYears = {'3 mo': 0.25, '6 mo': 0.5, '2 yr': 2, '10 yr': 10, '30 yr': 30}
fields = [i for i in fieldsToYears.keys()]
dfm2 = fetchTsRates(years)[fields + ['Date']].melt(id_vars='Date', var_name='Maturity')
dfm2["Year"] = dfm2.Date.apply(lambda v: v.year)
alt.Chart(dfm2.groupby(["Maturity", "Year"]).agg({ "value": "mean" }).reset_index()).mark_line().encode(
alt.X('Maturity:O', axis=alt.Axis(title='Maturity', labelAngle=0), sort=fields),
alt.Y('value:Q', axis=alt.Axis(title='Interest Rate [%]')),
alt.Color('Year:N'),
tooltip=[alt.Tooltip('Date:T', format='%b %Y'), alt.Tooltip('Maturity:N'), alt.Tooltip('value:Q')]
).properties(
title='U.S. Treasury Yield comparison [{y1} to {y2}]'.format(y1=min(years), y2=max(years)),
height=450,
width=700
)
years = range(2016, 2022)
instruments = {
0.25: '3 Month T-bill',
0.5: '6 Month T-bill',
2: '2 Year Note',
10: '10 Year Note',
30: '30 Year Bond'
}
fieldsToYears = {'3 mo': 0.25, '6 mo': 0.5, '2 yr': 2, '10 yr': 10, '30 yr': 30}
fields = [i for i in fieldsToYears.keys()]
dfm2 = fetchTsRates(years)[fields + ['Date']].melt(id_vars='Date', var_name='Maturity')
dfm2["Year"] = dfm2.Date.apply(lambda v: v.year)
alt.Chart(dfm2.groupby(["Maturity", "Year"]).agg({ "value": "mean" }).reset_index()).mark_line().encode(
alt.X('Maturity:O', axis=alt.Axis(title='Maturity', labelAngle=0), sort=fields),
alt.Y('value:Q', axis=alt.Axis(title='Interest Rate [%]')),
alt.Color('Year:N'),
tooltip=[alt.Tooltip('Date:T', format='%b %Y'), alt.Tooltip('Maturity:N'), alt.Tooltip('value:Q')]
).properties(
title='Yearly Average U.S. Treasury Yield comparison [{y1} to {y2}]'.format(y1=min(years), y2=max(years)),
height=450,
width=700
)
```
| github_jupyter |
This notebook is part of the $\omega radlib$ documentation: https://docs.wradlib.org.
Copyright (c) $\omega radlib$ developers.
Distributed under the MIT License. See LICENSE.txt for more info.
# Supported radar data formats
The binary encoding of many radar products is a major obstacle for many potential radar users. Often, decoder software is not easily available. In case formats are documented, the implementation of decoders is a major programming effort. This tutorial provides an overview of the data formats currently supported by $\omega radlib$. We seek to continuously enhance the range of supported formats, so this document is only a snapshot. If you need a specific file format to be supported by $\omega radlib$, please [raise an issue](https://github.com/wradlib/wradlib/issues/new) of type *enhancement*. You can provide support by adding documents which help to decode the format, e.g. format reference documents or software code in other languages for decoding the format.
At the moment, *supported format* means that the radar format can be read and further processed by wradlib. Normally, wradlib will return a numpy array of data values and a dictionary of metadata - if the file contains any.
<div class="alert alert-warning">
**Note** <br>
Due to recent developments in major data science packages (eg. [xarray](https://xarray.pydata.org)) wradlib supports as of version 1.10 reading of ``ODIM``, ``GAMIC`` and ``CfRadial`` (1 and 2) datasets into an `xarray` based data structure. Output to ``ODIM_H5`` and ``CfRadial2`` like data files as well as standard netCDF4 data files is easily possible.
</div>
In the following, we will provide an overview of file formats which can be currently read by $\omega radlib$.
Reading weather radar files is done via the [wradlib.io](https://docs.wradlib.org/en/latest/io.html) module. There you will find a complete function reference.
```
import wradlib as wrl
import warnings
#warnings.filterwarnings('ignore')
import matplotlib.pyplot as pl
import numpy as np
try:
get_ipython().magic("matplotlib inline")
except:
pl.ion()
```
## German Weather Service: DX format
The German Weather Service uses the DX file format to encode local radar sweeps. DX data are in polar coordinates. The naming convention is as follows: <pre>raa00-dx_<location-id>-<YYMMDDHHMM>-<location-abreviation>---bin</pre> or <pre>raa00-dx_<location-id>-<YYYYMMDDHHMM>-<location-abreviation>---bin</pre>
[Read and plot DX radar data from DWD](wradlib_reading_dx.ipynb) provides an extensive introduction into working with DX data. For now, we would just like to know how to read the data:
```
fpath = 'dx/raa00-dx_10908-0806021655-fbg---bin.gz'
f = wrl.util.get_wradlib_data_file(fpath)
data, metadata = wrl.io.read_dx(f)
```
Here, ``data`` is a two dimensional array of shape (number of azimuth angles, number of range gates). This means that the number of rows of the array corresponds to the number of azimuth angles of the radar sweep while the number of columns corresponds to the number of range gates per ray.
```
print(data.shape)
print(metadata.keys())
fig = pl.figure(figsize=(10, 10))
ax, im = wrl.vis.plot_ppi(data, fig=fig, proj='cg')
```
## German Weather Service: RADOLAN (quantitative) composit
The quantitative composite format of the DWD (German Weather Service) was established in the course of the [RADOLAN project](https://www.dwd.de/DE/leistungen/radolan/radolan.html). Most quantitative composite products from the DWD are distributed in this format, e.g. the R-series (RX, RY, RH, RW, ...), the S-series (SQ, SH, SF, ...), and the E-series (European quantitative composite, e.g. EZ, EH, EB). Please see the [composite format description](https://www.dwd.de/DE/leistungen/radolan/radolan_info/radolan_radvor_op_komposit_format_pdf.pdf?__blob=publicationFile&v=5) for a full reference and a full table of products (unfortunately only in German language). An extensive section covering many RADOLAN aspects is here: [RADOLAN](../radolan.ipynb)
Currently, the RADOLAN composites have a spatial resolution of 1km x 1km, with the national composits (R- and S-series) being 900 x 900 grids, and the European composits 1500 x 1400 grids. The projection is [polar-stereographic](../radolan/radolan_grid.ipynb#Polar-Stereographic-Projection). The products can be read by the following function:
<div class="alert alert-warning">
**Note** <br>
Since $\omega radlib$ version 1.10 a ``RADOLAN`` reader [wradlib.io.radolan.open_radolan_dataset()](https://docs.wradlib.org/en/latest/generated/wradlib.io.radolan.open_radolan_dataset.html) based on [Xarray](https://xarray.pydata.org) is available. Please read the more indepth notebook [wradlib_radolan_backend](wradlib_radolan_backend.ipynb).
</div>
```
fpath = 'radolan/misc/raa01-rw_10000-1408102050-dwd---bin.gz'
f = wrl.util.get_wradlib_data_file(fpath)
data, metadata = wrl.io.read_radolan_composite(f)
```
Here, ``data`` is a two dimensional integer array of shape (number of rows, number of columns). Different product types might need different levels of postprocessing, e.g. if the product contains rain rates or accumulations, you will normally have to divide data by factor 10. ``metadata`` is again a dictionary which provides metadata from the files header section, e.g. using the keys *producttype*, *datetime*, *intervalseconds*, *nodataflag*.
```
print(data.shape)
print(metadata.keys())
```
Masking the NoData (or missing) values can be done by:
```
maskeddata = np.ma.masked_equal(data,
metadata["nodataflag"])
fig = pl.figure(figsize=(10, 8))
# get coordinates
radolan_grid_xy = wrl.georef.get_radolan_grid(900, 900)
x = radolan_grid_xy[:, :, 0]
y = radolan_grid_xy[:, :, 1]
# create quick plot with colorbar and title
pl.figure(figsize=(10, 8))
pl.pcolormesh(x, y, maskeddata)
```
## HDF5
### OPERA HDF5 (ODIM_H5)
[HDF5](https://www.hdfgroup.org/solutions/hdf5/) is a data model, library, and file format for storing and managing data. The [OPERA program](https://www.eumetnet.eu/activities/observations-programme/current-activities/opera/) developed a convention (or information model) on how to store and exchange radar data in hdf5 format. It is based on the work of [COST Action 717](https://e-services.cost.eu/files/domain_files/METEO/Action_717/final_report/final_report-717.pdf) and is used e.g. in real-time operations in the Nordic European countries. The OPERA Data and Information Model (ODIM) is documented e.g. in this [report](https://www.eol.ucar.edu/system/files/OPERA_2008_03_WP2.1b_ODIM_H5_v2.1.pdf). Make use of these documents in order to understand the organization of OPERA hdf5 files!
<div class="alert alert-warning">
**Note** <br>
Since $\omega radlib$ version 1.10 an ``Odim_H5`` reader [wradlib.io.open_odim_dataset()](https://docs.wradlib.org/en/latest/generated/wradlib.io.hdf.open_odim_dataset.html) based on [Xarray](https://xarray.pydata.org) is available. Please read the more indepth notebook [wradlib_odim_backend](wradlib_odim_backend.ipynb).
Former `xarray`-based implementations will be deprecated in future versions.
</div>
The hierarchical nature of HDF5 can be described as being similar to directories, files, and links on a hard-drive. Actual metadata are stored as so-called *attributes*, and these attributes are organized together in so-called *groups*. Binary data are stored as so-called *datasets*. As for ODIM_H5, the ``root`` (or top level) group contains three groups of metadata: these are called ``what`` (object, information model version, and date/time information), ``where`` (geographical information), and ``how`` (quality and optional/recommended metadata). For a very simple product, e.g. a CAPPI, the data is organized in a group called ``dataset1`` which contains another group called ``data1`` where the actual binary data are found in ``data``. In analogy with a file system on a hard-disk, the HDF5 file containing this simple product is organized like this:
```
/
/what
/where
/how
/dataset1
/dataset1/data1
/dataset1/data1/data
```
The philosophy behind the $\omega radlib$ interface to OPERA's data model is very straightforward: $\omega radlib$ simply translates the complete file structure to *one* dictionary and returns this dictionary to the user. Thus, the potential complexity of the stored data is kept and it is left to the user how to proceed with this data. The keys of the output dictionary are strings that correspond to the "directory trees" shown above. Each key ending with ``/data`` points to a Dataset (i.e. a numpy array of data). Each key ending with ``/what``, ``/where`` or ``/how`` points to another dictionary of metadata. The entire output can be obtained by:
```
fpath = 'hdf5/knmi_polar_volume.h5'
f = wrl.util.get_wradlib_data_file(fpath)
fcontent = wrl.io.read_opera_hdf5(f)
```
The user should inspect the output obtained from his or her hdf5 file in order to see how access those items which should be further processed. In order to get a readable overview of the output dictionary, one can use the pretty printing module:
```
# which keyswords can be used to access the content?
print(fcontent.keys())
# print the entire content including values of data and metadata
# (numpy arrays will not be entirely printed)
print(fcontent['dataset1/data1/data'])
```
Please note that in order to experiment with such datasets, you can download hdf5 sample data from the [OPERA](https://www.eumetnet.eu/activities/observations-programme/current-activities/opera/) or use the example data provided with the [wradlib-data](https://github.com/wradlib/wradlib-data/) repository.
```
fig = pl.figure(figsize=(10, 10))
im = wrl.vis.plot_ppi(fcontent['dataset1/data1/data'], fig=fig, proj='cg')
```
### GAMIC HDF5
GAMIC refers to the commercial [GAMIC Enigma MURAN software](https://www.gamic.com) which exports data in hdf5 format. The concept is quite similar to the above [OPERA HDF5 (ODIM_H5)](#OPERA-HDF5-(ODIM_H5)) format.
<div class="alert alert-warning">
**Note** <br>
Since $\omega radlib$ version 1.10 an ``GAMIC`` reader [wradlib.io.hdf.open_gamic_dataset()](https://docs.wradlib.org/en/latest/generated/wradlib.io.hdf.open_gamic_dataset.html) based on [Xarray](https://xarray.pydata.org) is available. Please read the more indepth notebook [wradlib_gamic_backend](wradlib_gamic_backend.ipynb).
Former `xarray`-based implementations will be deprecated in future versions.
</div>
Such a file (typical ending: *.mvol*) can be read by:
```
fpath = 'hdf5/2014-08-10--182000.ppi.mvol'
f = wrl.util.get_wradlib_data_file(fpath)
data, metadata = wrl.io.read_gamic_hdf5(f)
```
While metadata represents the usual dictionary of metadata, the data variable is a dictionary which might contain several numpy arrays with the keywords of the dictionary indicating different moments.
```
print(metadata.keys())
print(metadata['VOL'])
print(metadata['SCAN0'].keys())
print(data['SCAN0'].keys())
print(data['SCAN0']['PHIDP'].keys())
print(data['SCAN0']['PHIDP']['data'].shape)
fig = pl.figure(figsize=(10, 10))
im = wrl.vis.plot_ppi(data['SCAN0']['ZH']['data'], fig=fig, proj='cg')
```
### Generic HDF5
This is a generic hdf5 reader, which will read any hdf5 structure.
```
fpath = 'hdf5/2014-08-10--182000.ppi.mvol'
f = wrl.util.get_wradlib_data_file(fpath)
fcontent = wrl.io.read_generic_hdf5(f)
print(fcontent.keys())
print(fcontent['where'])
print(fcontent['how'])
print(fcontent['scan0/moment_3'].keys())
print(fcontent['scan0/moment_3']['attrs'])
print(fcontent['scan0/moment_3']['data'].shape)
fig = pl.figure(figsize=(10, 10))
im = wrl.vis.plot_ppi(fcontent['scan0/moment_3']['data'], fig=fig, proj='cg')
```
## NetCDF
The NetCDF format also claims to be self-describing. However, as for all such formats, the developers of netCDF also admit that "[...] the mere use of netCDF is not sufficient to make data self-describing and meaningful to both humans and machines [...]" (see [here](https://www.unidata.ucar.edu/software/netcdf/documentation/historic/netcdf/Conventions.html). Different radar operators or data distributors will use different naming conventions and data hierarchies (i.e. "data models") that the reading program might need to know about.
$\omega radlib$ provides two solutions to address this challenge. The first one ignores the concept of data models and just pulls all data and metadata from a NetCDF file ([wradlib.io.read_generic_netcdf()](https://docs.wradlib.org/en/latest/generated/wradlib.io.netcdf.read_generic_netcdf.html). The second is designed for a specific data model used by the EDGE software ([wradlib.io.read_edge_netcdf()](https://docs.wradlib.org/en/latest/generated/wradlib.io.netcdf.read_edge_netcdf.html)).
<div class="alert alert-warning">
**Note** <br>
Since $\omega radlib$ version 1.10 a ``Cf/Radial1`` reader [wradlib.io.xarray.open_cfradial1_dataset()](https://docs.wradlib.org/en/latest/generated/wradlib.io.netcdf.open_cfradial1_dataset.html) and a ``Cf/Radial2`` reader [wradlib.io.xarray.open_cfradial2_dataset()](https://docs.wradlib.org/en/latest/generated/wradlib.io.netcdf.open_cfradial2_dataset.html) for CF versions 1.X and 2 based on [Xarray](https://xarray.pydata.org/en/stable/) are available. Please read the more indepth notebooks [wradlib_cfradial1_backend](wradlib_cfradial1_backend.ipynb) and [wradlib_cfradial2_backend](wradlib_cfradial2_backend.ipynb).
</div>
### Generic NetCDF reader (includes CfRadial)
$\omega radlib$ provides a function that will virtually read any NetCDF file irrespective of the data model: [wradlib.io.read_generic_netcdf()](https://docs.wradlib.org/en/latest/generated/wradlib.io.netcdf.read_generic_netcdf.html). It is built upon Python's [netcdf4](https://unidata.github.io/netcdf4-python/) library. [wradlib.io.read_generic_netcdf()](https://docs.wradlib.org/en/latest/generated/wradlib.io.netcdf.read_generic_netcdf.html) will return only one object, a dictionary, that contains all the contents of the NetCDF file corresponding to the original file structure. This includes all the metadata, as well as the so called "dimensions" (describing the dimensions of the actual data arrays) and the "variables" which will contains the actual data. Users can use this dictionary at will in order to query data and metadata; however, they should make sure to consider the documentation of the corresponding data model. [wradlib.io.read_generic_netcdf()](https://docs.wradlib.org/en/latest/generated/wradlib.io.netcdf.read_generic_netcdf.html) has been shown to work with a lot of different data models, most notably **CfRadial** (see [here](https://ncar.github.io/CfRadial/) for details). A typical call to [wradlib.io.read_generic_netcdf()](https://docs.wradlib.org/en/latest/generated/wradlib.io.netcdf.read_generic_netcdf.html) would look like:
```
fpath = 'netcdf/example_cfradial_ppi.nc'
f = wrl.util.get_wradlib_data_file(fpath)
outdict = wrl.io.read_generic_netcdf(f)
for key in outdict.keys():
print(key)
```
Please see [this example notebook](wradlib_generic_netcdf_example.ipynb) to get started.
### EDGE NetCDF
EDGE is a commercial software for radar control and data analysis provided by the Enterprise Electronics Corporation. It allows for netCDF data export. The resulting files can be read by [wradlib.io.read_generic_netcdf()](https://docs.wradlib.org/en/latest/generated/wradlib.io.netcdf.read_generic_netcdf.html), but $\omega radlib$ also provides a specific function, [wradlib.io.read_edge_netcdf()](https://docs.wradlib.org/en/latest/generated/wradlib.io.netcdf.read_edge_netcdf.html) to return metadata and data as seperate objects:
```
fpath = 'netcdf/edge_netcdf.nc'
f = wrl.util.get_wradlib_data_file(fpath)
data, metadata = wrl.io.read_edge_netcdf(f)
print(data.shape)
print(metadata.keys())
```
## Gematronik Rainbow
Rainbow refers to the commercial [RAINBOW®5 APPLICATION SOFTWARE](https://www.leonardogermany.com/en/products/rainbow-5) which exports data in an XML flavour, which due to binary data blobs violates XML standard. Gematronik provided python code for implementing this reader in $\omega radlib$, which is very much appreciated.
The philosophy behind the $\omega radlib$ interface to Gematroniks data model is very straightforward: $\omega radlib$ simply translates the complete xml file structure to *one* dictionary and returns this dictionary to the user. Thus, the potential complexity of the stored data is kept and it is left to the user how to proceed with this data. The keys of the output dictionary are strings that correspond to the "xml nodes" and "xml attributes". Each ``data`` key points to a Dataset (i.e. a numpy array of data). Such a file (typical ending: *.vol* or *.azi*) can be read by:
```
fpath = 'rainbow/2013070308340000dBuZ.azi'
f = wrl.util.get_wradlib_data_file(fpath)
fcontent = wrl.io.read_rainbow(f)
```
The user should inspect the output obtained from his or her Rainbow file in order to see how access those items which should be further processed. In order to get a readable overview of the output dictionary, one can use the pretty printing module:
```
# which keyswords can be used to access the content?
print(fcontent.keys())
# print the entire content including values of data and metadata
# (numpy arrays will not be entirely printed)
print(fcontent['volume']['sensorinfo'])
```
You can check this [example notebook](wradlib_load_rainbow_example.ipynb) for getting a first impression.
## Vaisala Sigmet IRIS
[IRIS](https://www.vaisala.com/en/products/instruments-sensors-and-other-measurement-devices/weather-radar-products/iris-focus) refers to the commercial Vaisala Sigmet **I**nteractive **R**adar **I**nformation **S**ystem. The Vaisala Sigmet Digital Receivers export data in a [well documented](ftp://ftp.sigmet.com/outgoing/manuals/IRIS_Programmers_Manual.pdf) binary format.
The philosophy behind the $\omega radlib$ interface to the IRIS data model is very straightforward: $\omega radlib$ simply translates the complete binary file structure to *one* dictionary and returns this dictionary to the user. Thus, the potential complexity of the stored data is kept and it is left to the user how to proceed with this data. The keys of the output dictionary are strings that correspond to the Sigmet Data Structures.
<div class="alert alert-warning">
**Note** <br>
Since $\omega radlib$ version 1.12 an ``IRIS`` reader [wradlib.io.iris.open_iris_dataset()](https://docs.wradlib.org/en/latest/generated/wradlib.io.iris.open_iris_dataset.html) based on [Xarray](https://xarray.pydata.org) is available. Please read the more indepth notebook [wradlib_iris_backend](wradlib_iris_backend.ipynb).
At the same time the reader has changed with respect to performance. So the ray metadata is only read once per sweep and is only included once in the output of `read_iris`. Currently we keep backwards compatibility, but this behaviour is deprecated and will be changed in a future version. See the two examples below.
</div>
Such a file (typical ending: *.RAWXXXX) can be read by:
```
fpath = 'sigmet/cor-main131125105503.RAW2049'
f = wrl.util.get_wradlib_data_file(fpath)
fcontent = wrl.io.read_iris(f, keep_old_sweep_data=False)
# which keywords can be used to access the content?
print(fcontent.keys())
# print the entire content including values of data and
# metadata of the first sweep
# (numpy arrays will not be entirely printed)
print(fcontent['data'][1].keys())
print()
print(fcontent['data'][1]['ingest_data_hdrs'].keys())
print(fcontent['data'][1]['ingest_data_hdrs']['DB_DBZ'])
print()
print(fcontent['data'][1]['sweep_data'].keys())
print(fcontent['data'][1]['sweep_data']['DB_DBZ'])
fig = pl.figure(figsize=(10, 10))
swp = fcontent['data'][1]['sweep_data']
ax, im = wrl.vis.plot_ppi(swp["DB_DBZ"], fig=fig, proj='cg')
fpath = 'sigmet/cor-main131125105503.RAW2049'
f = wrl.util.get_wradlib_data_file(fpath)
fcontent = wrl.io.read_iris(f, keep_old_sweep_data=True)
# which keywords can be used to access the content?
print(fcontent.keys())
# print the entire content including values of data and
# metadata of the first sweep
# (numpy arrays will not be entirely printed)
print(fcontent['data'][1].keys())
print()
print(fcontent['data'][1]['ingest_data_hdrs'].keys())
print(fcontent['data'][1]['ingest_data_hdrs']['DB_DBZ'])
print()
print(fcontent['data'][1]['sweep_data'].keys())
print(fcontent['data'][1]['sweep_data']['DB_DBZ'])
fig = pl.figure(figsize=(10, 10))
swp = fcontent['data'][1]['sweep_data']
ax, im = wrl.vis.plot_ppi(swp["DB_DBZ"]["data"], fig=fig, proj='cg')
```
## OPERA BUFR
**WARNING** $\omega radlib$ does currently not support the BUFR format!
The Binary Universal Form for the Representation of meteorological data (BUFR) is a binary data format maintained by the World Meteorological Organization (WMO).
The BUFR format was adopted by [OPERA](https://www.eumetnet.eu/activities/observations-programme/current-activities/opera/) for the representation of weather radar data.
A BUFR file consists of a set of *descriptors* which contain all the relevant metadata and a data section.
The *descriptors* are identified as a tuple of three integers. The meaning of these tupels is described in the so-called BUFR tables. There are generic BUFR tables provided by the WMO, but it is also possible to define so called *local tables* - which was done by the OPERA consortium for the purpose of radar data representation.
If you want to use BUFR files together with $\omega radlib$, we recommend that you check out the [OPERA webpage](https://www.eumetnet.eu/activities/observations-programme/current-activities/opera/) where you will find software for BUFR decoding. In particular, you might want to check out [this tool](https://eumetnet.eu/wp-content/uploads/2017/04/bufr_opera_mf.zip) which seems to support the conversion of OPERA BUFR files to ODIM_H5 (which is supported by $\omega radlib$). However, you have to build it yourself.
It would be great if someone could add a tutorial on how to use OPERA BUFR software together with $\omega radlib$!
| github_jupyter |
```
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import torch
import matplotlib.pyplot as plt
import torchvision
import csv
import glob
import cv2
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from random import shuffle
import glob
#from torchsummary import summary
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory
import os
print(os.listdir("../input"))
%matplotlib inline
# Any results you write to the current directory are saved as output.
#classes = ('plane', 'car', 'bird', 'cat',
# 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 50, 5)
self.pool1 = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(50, 100, 7)
self.pool2 = nn.MaxPool2d(2,2)
self.fc1 = nn.Linear(100 * 12 * 12, 120)
self.fc2 = nn.Linear(120, 100)
self.fc3 = nn.Linear(100, 2)
def forward(self, x):
x = self.pool1(F.relu(self.conv1(x)))
x = self.pool2(F.relu(self.conv2(x)))
x = x.view(-1, 100 * 12 * 12)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.sigmoid(self.fc3(x))
return x
net = Net()
print(net)
'''
#alternate way to create a list of file name and labels
import numpy as np
import os
PATH = '../input/'
fnames = np.array([f'train/{f}' for f in sorted(os.listdir(f'{PATH}train'))])
labels = np.array([(0 if 'cat' in fname else 1) for fname in fnames])
print(fnames[0:100] , labels[0:100])
'''
shuffle_data = True # shuffle the addresses before saving
cat_dog_train_path = '../input/train/*.jpg'
# read addresses and labels from the 'train' folder
addrs = glob.glob(cat_dog_train_path)
labels = [ [1,0] if 'cat' in addr else [0,1] for addr in addrs] # 1 = Cat, 0 = Dog
# to shuffle data
if shuffle_data:
c = list(zip(addrs, labels))
shuffle(c)
addrs, labels = zip(*c)
print(labels[0:10])
# Divide the hata into 60% train, 20% validation, and 20% test
train_addrs = addrs[0:int(0.6*len(addrs))]
train_labels = labels[0:int(0.6*len(labels))]
#train_addrs.size
val_addrs = addrs[int(0.6*len(addrs)):int(0.8*len(addrs))]
val_labels = labels[int(0.6*len(addrs)):int(0.8*len(addrs))]
test_addrs = addrs[int(0.8*len(addrs)):]
test_labels = labels[int(0.8*len(labels)):]
# loop over train addresses
train_data = []
for i in range(len(train_addrs[:1000])):
# print how many images are saved every 10 images
if i % 1000 == 0 and i > 1:
print ('Train data: {}/{}'.format(i, len(train_addrs)))
# read an image and resize to (64, 64)
# cv2 load images as BGR, convert it to RGB
addr = train_addrs[i]
img = cv2.imread(addr)
img = cv2.resize(img, (64, 64), interpolation=cv2.INTER_CUBIC)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
train_data.append([np.array(img), np.array(train_labels[i])])
shuffle(train_data)
np.save('train_data.npy', train_data)
# loop over test addresses
#creating test data
test_data = []
for i in range(len(test_addrs[:1000])):
# print how many images are saved every 1000 images
if i % 1000 == 0 and i > 1:
print ('Test data: {}/{}'.format(i, len(test_addrs)))
# read an image and resize to (64, 64)
# cv2 load images as BGR, convert it to RGB
addr = test_addrs[i]
img = cv2.imread(addr)
img = cv2.resize(img, (64, 64), interpolation=cv2.INTER_CUBIC)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
test_data.append([np.array(img), np.array(labels[i])])
shuffle(test_data)
np.save('test_data.npy', test_data)
# loop over val addresses
val_data = []
for i in range(len(val_addrs[:1000])):
# print how many images are saved every 1000 images
if i % 1000 == 0 and i > 1:
print ('Val data: {}/{}'.format(i, len(val_addrs)))
# read an image and resize to (64, 64)
# cv2 load images as BGR, convert it to RGB
addr = val_addrs[i]
img = cv2.imread(addr)
img = cv2.resize(img, (64, 64), interpolation=cv2.INTER_CUBIC)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
val_data.append([np.array(img), np.array(labels[i])])
shuffle(val_data)
np.save('val_data.npy', val_data)
#print(val_data[1])
from torch.autograd import Variable
X = np.array([i[0] for i in train_data]).reshape(-1,64,64,3)
X = Variable(torch.Tensor(X))
X = X.reshape(-1,64,64,3)
X = X.permute(0,3,1,2)
print(X.shape)
#Y = Variable(torch.Tensor(Y))
Y = np.array([i[1] for i in train_data])
target = Variable(torch.Tensor(Y))
target = target.type(torch.LongTensor)
print(target.shape)
#print(target)
criterian = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr = 0.0001, momentum = 0.9)
for epoch in range(100):
running_loss = 0.0
optimizer.zero_grad() #zero the parameter gradients
output = net(X)
loss = criterian(output, torch.max(target, 1)[1])
loss.backward()
optimizer.step()
running_loss += loss.item()
print(epoch, ':', running_loss)
test = np.array([i[0] for i in test_data]).reshape(-1,64,64,3)
test = Variable(torch.Tensor(test))
test = test.reshape(-1,64,64,3)
test = test.permute(0,3,1,2)
print(test.shape)
#Y = Variable(torch.Tensor(Y))
tlabels = np.array([i[1] for i in test_data])
tlabels = Variable(torch.Tensor(tlabels))
tlabels = tlabels.type(torch.long)
print(tlabels.shape)
print(tlabels)
correct = 0
total = 0
with torch.no_grad():
for data in zip(X,target):
images, labels = data
images = images.reshape(1,3,64,64)
outputs = net(images)
_, predicted = torch.max(outputs, 1)
#total += labels.size(0)
if((predicted == 0 and labels[0] == 1) or (predicted == 1 and labels[1]==1) ):
correct+=1
#correct += (predicted == labels).sum().item()
#print(outputs,labels)
total = X.shape[0]
print('Train accuracy of the network on the' + str(total) + 'train images: %f %%' % (
100 * (correct*1.0) / total) )
print(correct, total)
correct = 0
total = 0
with torch.no_grad():
for data in zip(test,tlabels):
images, labels = data
images = images.reshape(1,3,64,64)
outputs = net(images)
_, predicted = torch.max(outputs, 1)
#total += labels.size(0)
if((predicted == 0 and labels[0] == 1) or (predicted == 1 and labels[1]==1) ):
correct += 1
total = test.shape[0]
print('Test accuracy of the network on the ' + str(total) + ' test images: %f %%' % (
100 * (correct*1.0) / total) )
print(correct, total)
```
| github_jupyter |
# Exercices
With each exercice will teach you one aspect of deep learning. The process of machine learning can be decompose in 7 steps :
* Data preparation
* Model definition
* Model training
* Model evaluation
* Hyperparameter tuning
* Prediction
## 3 - Model training
- 3.1 Metrics : evaluate model
- 3.2 Loss function (mean square error, cross entropy)
- 3.3 Optimizer function (stochastic gradient descent)
- 3.4 Batch size, epoch number
### Load dataset
```
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
data_path = './data'
#trans = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (1.0,))])
trans = transforms.Compose([transforms.Resize((32, 32)), transforms.ToTensor()])
# if not exist, download mnist dataset
train_set = dset.MNIST(root=data_path, train=True, transform=trans, download=True)
test_set = dset.MNIST(root=data_path, train=False, transform=trans, download=True)
batch = 4
data_train_loader = DataLoader(train_set, batch_size=batch, shuffle=True, num_workers=8)
data_test_loader = DataLoader(test_set, batch_size=batch, num_workers=8)
classes = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
```
### Define the network architecture
```
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 5x5 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# If the size is a square you can only specify a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
leNet = Net()
print(leNet)
```
### Define loss criterion and optimizer
```
import torch.optim as optim
criterion = nn.MSELoss()
optimizer = optim.SGD(leNet.parameters(), lr=0.01)
```
### Training loop
```
for epoch in range(3): # loop over the dataset multiple times
leNet.train()
running_loss = 0.0
for i, (images, labels) in enumerate(data_train_loader):
optimizer.zero_grad()
output = leNet(images)
# align vectors labels <=> outputs
label_vect = torch.zeros(4, 10, dtype=torch.float)
for j in range(0, len(labels)):
label_vect[j, labels[j]] = 1.0
loss = criterion(output, label_vect)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
print('[{:d}] loss: {:.5f}'.format(epoch + 1, running_loss / (batch*len(data_train_loader))))
print('Finished Training')
```
### Test the model
```
import matplotlib.pyplot as plt
import numpy as np
def imshow(images, labels):
npimg = images.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.title("Ground Truth: {}".format(labels))
import torchvision
dataiter = iter(data_test_loader)
images, labels = dataiter.next()
# print images
imshow(torchvision.utils.make_grid(images), labels)
outputs = leNet(images)
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))
```
### Saving leNet
```
torch.save({
'epoch': 1,
'model_state_dict': leNet.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss,
}, 'checkpoint-MKTD-pytorch-3.last')
```
| github_jupyter |
```
%run setup.ipynb
from scipy.stats import dirichlet
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
import traceback
import logging
logger = logging.getLogger('ag1000g-phase2')
logger.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
#generate counts
Fpos = 2422652
Spos = 2422651
callset = phase2_ar1.callset_pass_biallelic['2L']
g = allel.GenotypeChunkedArray(callset['calldata']['genotype'])
pos = allel.SortedIndex(callset['variants']['POS'])
df_meta = pd.read_csv('../phase2.AR1/samples/samples.meta.txt', sep='\t')
Fb = pos.values == Fpos
Sb = pos.values == Spos
def het_pop(pop):
FSb = Fb + Sb
popbool = np.array(df_meta.population == pop)
popg = g.compress(popbool, axis=1)
popgr = popg.compress(FSb, axis=0)
a = np.asarray(popgr.to_n_alt())
return a
gagam = het_pop('GAgam')
cagam = het_pop('CMgam')
np.save('../data/gabon_n_alt.npy', gagam)
np.save('../data/cameroon_n_alt.npy', cagam)
def run_fs_het_analysis(path, ns=1_000_000):
ac = np.load(path).T
logger.info(f"Loaded {path}")
# assuming col1 is F, col2 is S
assert ac.sum(axis=1).max() == 2
tot_alleles = ac.shape[0] * 2
n_samples = ac.shape[0]
logger.info(f"{n_samples} samples found")
wt_alleles = tot_alleles - ac.sum()
wt_alleles
f_alleles = ac[:, 0].sum()
s_alleles = ac[:, 1].sum()
alpha = [1 + wt_alleles, 1 + f_alleles, 1 + s_alleles]
logger.info(f"Dirichlet alpha set to {alpha}")
diric = dirichlet(alpha)
wt, f, s = diric.mean()
logger.info(
f"Mean of dirichlet- wt: {wt:.2f}, f:{f:.2f}, s:{s:.2f}")
# this is what we observed
is_het = (ac[:, 0] == ac[:, 1]) & (ac.sum(axis=1) == 2)
tot_fs_hets = is_het.sum()
logger.info(
f"In the AC data we observe {tot_fs_hets} F-S hets")
logger.info(f"Beginning monte carlo analysis, n={ns}")
# draw 1m dirichlet observations of allele frequency
v = np.random.dirichlet(alpha, size=ns)
# for each of the 1m, sample n_samples,
# and count how many "F/S" hets we observe
o = np.zeros(ns, dtype="int")
for i in range(v.shape[0]):
x = np.random.multinomial(2, v[i], size=n_samples)
o[i] = np.sum((x[:, 1] == 1) & (x[:, 2] == 1))
fig, ax = plt.subplots(figsize=(4, 4))
bins = np.arange(0, max(o.max(), tot_fs_hets) + 5, 1)
count, bins, patches = ax.hist(
o, bins=bins, density=True)
ymin, ymax = ax.get_ylim()
ax.vlines([tot_fs_hets], ymin=ymin, ymax=ymax)
sns.despine(ax=ax)
grt = tot_fs_hets >= o
les = tot_fs_hets <= o
logger.info(
"{:.3f} of simulated values are greater than or equal to the observed".format(
1 - np.mean(grt)))
logger.info(
"{:.3f} of simulated values are less than or equal to the observed".format(
1 - np.mean(les)))
run_fs_het_analysis("../data/gabon_n_alt.npy")
run_fs_het_analysis("../data/cameroon_n_alt.npy")
```
| github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/FeatureCollection/column_statistics_by_group.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/FeatureCollection/column_statistics_by_group.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td>
<td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=FeatureCollection/column_statistics_by_group.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/FeatureCollection/column_statistics_by_group.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td>
</table>
## Install Earth Engine API
Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`.
The following script checks if the geehydro package has been installed. If not, it will install geehydro, which automatically install its dependencies, including earthengine-api and folium.
```
import subprocess
try:
import geehydro
except ImportError:
print('geehydro package not installed. Installing ...')
subprocess.check_call(["python", '-m', 'pip', 'install', 'geehydro'])
```
Import libraries
```
import ee
import folium
import geehydro
```
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once.
```
try:
ee.Initialize()
except Exception as e:
ee.Authenticate()
ee.Initialize()
```
## Create an interactive map
This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function.
The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`.
```
Map = folium.Map(location=[40, -100], zoom_start=4)
Map.setOptions('HYBRID')
```
## Add Earth Engine Python script
```
# Load a collection of US census blocks.
blocks = ee.FeatureCollection('TIGER/2010/Blocks')
# Compute sums of the specified properties, grouped by state code.
sums = blocks \
.filter(ee.Filter.And(
ee.Filter.neq('pop10', {}),
ee.Filter.neq('housing10', {}))) \
.reduceColumns(**{
'selectors': ['pop10', 'housing10', 'statefp10'],
'reducer': ee.Reducer.sum().repeat(2).group(**{
'groupField': 2,
'groupName': 'state-code',
})
})
# Print the resultant Dictionary.
print(sums.getInfo())
```
## Display Earth Engine data layers
```
Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map
```
| github_jupyter |
# <div align="center">BERT (Bidirectional Encoder Representations from Transformers) Explained: State of the art language model for NLP</div>
---------------------------------------------------------------------
<img src='asset/9_6/main.png'>
you can Find me on Github:
> ###### [ GitHub](https://github.com/lev1khachatryan)
BERT (Bidirectional Encoder Representations from Transformers) is a recent paper published by researchers at Google AI Language. It has caused a stir in the Machine Learning community by presenting state-of-the-art results in a wide variety of NLP tasks, including Question Answering (SQuAD v1.1), Natural Language Inference (MNLI), and others.
BERT’s key technical innovation is applying the bidirectional training of Transformer, a popular attention model, to language modelling. This is in contrast to previous efforts which looked at a text sequence either from left to right or combined left-to-right and right-to-left training. The paper’s results show that a language model which is bidirectionally trained can have a deeper sense of language context and flow than single-direction language models. In the paper, the researchers detail a novel technique named ***Masked LM (MLM)*** which allows bidirectional training in models in which it was previously impossible.
# <div align="center">Background</div>
---------------------------------------------------------------------
In the field of computer vision, researchers have repeatedly shown the value of transfer learning — pre-training a neural network model on a known task, for instance ImageNet, and then performing fine-tuning — using the trained neural network as the basis of a new purpose-specific model. In recent years, researchers have been showing that a similar technique can be useful in many natural language tasks.
A different approach, which is also popular in NLP tasks and exemplified in the recent ELMo paper, is feature-based training. In this approach, a pre-trained neural network produces word embeddings which are then used as features in NLP models.
# <div align="center">How BERT works</div>
---------------------------------------------------------------------
BERT makes use of ***Transformer***, an attention mechanism that learns contextual relations between words (or sub-words) in a text. In its vanilla form, ***Transformer includes two separate mechanisms*** — an ***encoder*** that reads the text input and a ***decoder*** that produces a prediction for the task. Since BERT’s goal is to generate a language model, only the encoder mechanism is necessary. The detailed workings of Transformer are described in a paper by Google.
***As opposed to directional models, which read the text input sequentially (left-to-right or right-to-left), the Transformer encoder reads the entire sequence of words at once. Therefore it is considered bidirectional, though it would be more accurate to say that it’s non-directional. This characteristic allows the model to learn the context of a word based on all of its surroundings (left and right of the word).***
The chart below is a high-level description of the Transformer encoder. The input is a sequence of tokens, which are first embedded into vectors and then processed in the neural network. The output is a sequence of vectors of size H, in which each vector corresponds to an input token with the same index.
When training language models, there is a challenge of defining a prediction goal. Many models predict the next word in a sequence (e.g. “The child came home from ... ”), a directional approach which inherently limits context learning. To overcome this challenge, BERT uses two training strategies:
# <div align="center">Masked LM (MLM)</div>
---------------------------------------------------------------------
Before feeding word sequences into BERT, 15% of the words in each sequence are replaced with a ***MASK*** token. The model then attempts to predict the original value of the masked words, based on the context provided by the other, non-masked, words in the sequence. In technical terms, the prediction of the output words requires:
* Adding a classification layer on top of the encoder output.
* Multiplying the output vectors by the embedding matrix, transforming them into the vocabulary dimension.
* Calculating the probability of each word in the vocabulary with softmax.
<img src='asset/9_6/1.png'>
The BERT loss function takes into consideration only the prediction of the masked values and ignores the prediction of the non-masked words. As a consequence, the model converges slower than directional models, a characteristic which is offset by its increased context awareness.
***Note:*** In practice, the BERT implementation is slightly more elaborate and doesn’t replace all of the 15% masked words:
Training the language model in BERT is done by predicting 15% of the tokens in the input, that were randomly picked. These tokens are pre-processed as follows – 80% are replaced with a **MASK** token, 10% with a random word, and 10% use the original word. The intuition that led the authors to pick this approach is as follows:
* If we used [MASK] 100% of the time the model wouldn’t necessarily produce good token representations for non-masked words. The non-masked tokens were still used for context, but the model was optimized for predicting masked words.
* If we used [MASK] 90% of the time and random words 10% of the time, this would teach the model that the observed word is never correct.
* If we used [MASK] 90% of the time and kept the same word 10% of the time, then the model could just trivially copy the non-contextual embedding
# <div align="center">Next Sentence Prediction (NSP)</div>
---------------------------------------------------------------------
In the BERT training process, the model receives pairs of sentences as input and learns to predict if the second sentence in the pair is the subsequent sentence in the original document. During training, 50% of the inputs are a pair in which the second sentence is the subsequent sentence in the original document, while in the other 50% a random sentence from the corpus is chosen as the second sentence. The assumption is that the random sentence will be disconnected from the first sentence.
To help the model distinguish between the two sentences in training, the input is processed in the following way before entering the model:
* A [CLS] token is inserted at the beginning of the first sentence and a [SEP] token is inserted at the end of each sentence.
* A sentence embedding indicating Sentence A or Sentence B is added to each token. Sentence embeddings are similar in concept to token embeddings with a vocabulary of 2.
* A positional embedding is added to each token to indicate its position in the sequence. The concept and implementation of positional embedding are presented in the Transformer paper.
<img src='asset/9_6/2.png'>
To predict if the second sentence is indeed connected to the first, the following steps are performed:
* The entire input sequence goes through the Transformer model.
* The output of the [CLS] token is transformed into a 2×1 shaped vector, using a simple classification layer (learned matrices of weights and biases).
* Calculating the probability of IsNextSequence with softmax.
When training the BERT model, Masked LM and Next Sentence Prediction are trained together, with the goal of minimizing the combined loss function of the two strategies.
# <div align="center">How to use BERT (Fine-tuning)</div>
---------------------------------------------------------------------
Using BERT for a specific task is relatively straightforward:
BERT can be used for a wide variety of language tasks, while only adding a small layer to the core model:
* Classification tasks such as sentiment analysis are done similarly to Next Sentence classification, by adding a classification layer on top of the Transformer output for the [CLS] token.
* In Question Answering tasks (e.g. SQuAD v1.1), the software receives a question regarding a text sequence and is required to mark the answer in the sequence. Using BERT, a Q&A model can be trained by learning two extra vectors that mark the beginning and the end of the answer.
* In Named Entity Recognition (NER), the software receives a text sequence and is required to mark the various types of entities (Person, Organization, Date, etc) that appear in the text. Using BERT, a NER model can be trained by feeding the output vector of each token into a classification layer that predicts the NER label.
In the fine-tuning training, most hyper-parameters stay the same as in BERT training, and the paper gives specific guidance (Section 3.5) on the hyper-parameters that require tuning. The BERT team has used this technique to achieve state-of-the-art results on a wide variety of challenging natural language tasks, detailed in Section 4 of the paper.
# <div align="center">Takeaways</div>
---------------------------------------------------------------------
* Model size matters, even at huge scale. BERT_large, with 345 million parameters, is the largest model of its kind. It is demonstrably superior on small-scale tasks to BERT_base, which uses the same architecture with “only” 110 million parameters.
* With enough training data, more training steps == higher accuracy. For instance, on the MNLI task, the BERT_base accuracy improves by 1.0% when trained on 1M steps (128,000 words batch size) compared to 500K steps with the same batch size.
* BERT’s bidirectional approach (MLM) converges slower than left-to-right approaches (because only 15% of words are predicted in each batch) but bidirectional training still outperforms left-to-right training after a small number of pre-training steps.
<img src='asset/9_6/3.png'>
# <div align="center">Conclusion</div>
---------------------------------------------------------------------
BERT is undoubtedly a breakthrough in the use of Machine Learning for Natural Language Processing. The fact that it’s approachable and allows fast fine-tuning will likely allow a wide range of practical applications in the future. In this summary, we attempted to describe the main ideas of the paper while not drowning in excessive technical details. For those wishing for a deeper dive, we highly recommend reading the full article and ancillary articles referenced in it. Another useful reference is the BERT source code and models, which cover 103 languages and were generously released as open source by the research team.
| github_jupyter |
# Real World Example:
### AI, Machine Learning & Data Science
---
# What is the Value for your Business?
- By seeing acutal examples you'll be empowered to ask the right questions (and get fair help from consultants, startups, or data analytics companies)
- This will help you make the correct decisions for your business
# Demystify
This is a real world example of how you'd solve a Machine Learning prediciton problem.
**Common Machine Learning Use Cases in Companies:**
- Discover churn risk of customers
- Predict optimal price levels (investments / retail)
- Predict future revenues
- Build recommendation systems
- Customer value scoring
- Fraud detection
- Customer insights (characteristics)
- Predict sentiment of text / client feedback
- Object detecton in images
- etc etc...
## Why Python?
Python is general purpose and can do Software development, Web development, AI. Python has experienced incredible growth over the last couple of years.
<img src='https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2017/09/growth_major_languages-1-1400x1200.png' width=400px></img>
Source: https://stackoverflow.blog/2017/09/06/incredible-growth-python/
# Everything is free!
The best software today is open source and it's also enterprise-ready. Anyone can download and use them for free (even for business purposes).
**Examples of great, free AI libraries:**
* Anaconda
* Google's TensorFlow
* Scikit-learn
* Pandas
* Keras
* Matplotlib
* SQL
* Spark
* Numpy
## State-of-the-Art algorithms
No matter what algorithm you want to use (Linear Regression, Random Forests, Neural Networks, or Deep Learning), **all of the latest methods are implemented optimized for Python**.
## Big Data
Python code can run on any computer. Therefore, you can scale your computations and utilize for example cloud resources to run big data jobs.
**Great tools for Big Data:**
- Spark
- Databricks
- Hadoop / MapReduce
- Kafka
- Amazon EC2
- Amazon S3
# Note on data collection
- Collect all the data you can! (storage is cheap)
---
----
# Real world example of AI: Titanic Analysis
Titanic notebook is open source. All of our material is online. Anyone can developt sophisticated AI programs and solutions.
___
## The difficult part is never to implement the algorithm
The hard part of a machine learning problem is to get data into the right format so you can solve the problem. We'll illustrate this below.
___

# __Titanic Survivor Analysis__
**Sources:**
* **Training + explanations**: https://www.kaggle.com/c/titanic
___
___
# Understanding the connections between passanger information and survival rate
The sinking of the RMS Titanic is one of the most infamous shipwrecks in history. On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. This sensational tragedy shocked the international community and led to better safety regulations for ships.
One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others.
### **Our task is to train a machine learning model on a data set consisting of 891 samples of people who were onboard of the Titanic. And then, be able to predict if the passengers survived or not.**
# Import packages
```
# No warnings
import warnings
warnings.filterwarnings('ignore') # Filter out warnings
# data analysis and wrangling
import pandas as pd
import numpy as np
# visualization
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
# machine learning
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB # Gaussian Naive Bays
from sklearn.linear_model import Perceptron
from sklearn.tree import DecisionTreeClassifier
import xgboost as xgb
from plot_distribution import plot_distribution
plt.rcParams['figure.figsize'] = (9, 5)
```
### Load Data
```
df = pd.read_csv('data/train.csv')
```
<a id='sec3'></a>
___
## Part 2: Exploring the Data
**Data descriptions**
<img src="data/Titanic_Variable.png">
```
# preview the data
df.head(3)
# General data statistics
df.describe()
```
### Histograms
```
df.hist(figsize=(13,10));
# Balanced data set?
y_numbers = df['Survived'].map({0:'Deceased',1:'Survived'}).value_counts()
y_numbers
# Imbalanced data set, our classifiers have to outperform 62 % accuracy
y_numbers[1] / y_numbers[0]
```
> #### __Interesting Fact:__
> Third Class passengers were the first to board, with First and Second Class passengers following up to an hour before departure.
> Third Class passengers were inspected for ailments and physical impairments that might lead to their being refused entry to the United States, while First Class passengers were personally greeted by Captain Smith.
```
# Analysis of survival rate for the socioeconmic classes?
df[['Pclass', 'Survived']].groupby(['Pclass'], as_index=True) \
.mean().sort_values(by='Survived', ascending=False)
```
___
> #### __Brief Remarks Regarding the Data__
> * `PassengerId` is a random number (incrementing index) and thus does not contain any valuable information.
> * `Survived, Passenger Class, Age, Siblings Spouses, Parents Children` and `Fare` are numerical values (no need to transform them) -- but, we might want to group them (i.e. create categorical variables).
> * `Sex, Embarked` are categorical features that we need to map to integer values. `Name, Ticket` and `Cabin` might also contain valuable information.
___
```
df.head(1)
```
### Dropping Unnecessary data
__Note:__ It is important to remove variables that convey information already captured by some other variable. Doing so removes the correlation, while also diminishing potential overfit.
```
# Drop columns 'Ticket', 'Cabin', 'Fare' need to do it
# for both test and training
df = df.drop(['PassengerId','Ticket', 'Cabin','Fare'], axis=1)
```
<a id='sec4'></a>
____
## Part 3: Transforming the data
### 3.1 _The Title of the person can be used to predict survival_
```
# List example titles in Name column
df.Name
# Create column called Title
df['Title'] = df['Name'].str.extract(' ([A-Za-z]+)\.', expand=False)
# Double check that our titles makes sense (by comparing to sex)
pd.crosstab(df['Title'], df['Sex'])
# Map rare titles to one group
df['Title'] = df['Title'].\
replace(['Lady', 'Countess','Capt', 'Col', 'Don', 'Dr',\
'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
df['Title'] = df['Title'].replace('Mlle', 'Miss') #Mademoiselle
df['Title'] = df['Title'].replace('Ms', 'Miss')
df['Title'] = df['Title'].replace('Mme', 'Mrs') #Madame
# We now have more logical (contemporary) titles, and fewer groups
# See if we can get some insights
df[['Title', 'Survived']].groupby(['Title']).mean()
# We can plot the survival chance for each title
sns.countplot(x='Survived', hue="Title", data=df, order=[1,0])
plt.xticks(range(2),['Survived','Deceased']);
# Title dummy mapping: Map titles to binary dummy columns
binary_encoded = pd.get_dummies(df.Title)
df[binary_encoded.columns] = binary_encoded
# Remove unique variables for analysis (Title is generally bound to Name, so it's also dropped)
df = df.drop(['Name', 'Title'], axis=1)
df.head()
```
### Map Gender column to binary (male = 0, female = 1) categories
```
# convert categorical variable to numeric
df['Sex'] = df['Sex']. \
map( {'female': 1, 'male': 0} ).astype(int)
df.head()
```
### Handle missing values for age
```
df.Age = df.Age.fillna(df.Age.median())
```
### Split age into bands and look at survival rates
```
# Age bands
df['AgeBand'] = pd.cut(df['Age'], 5)
df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False)\
.mean().sort_values(by='AgeBand', ascending=True)
```
### Suvival probability against age
```
# Plot the relative survival rate distributions against Age of passangers
# subsetted by the gender
plot_distribution( df , var = 'Age' , target = 'Survived' ,\
row = 'Sex' )
# Recall: {'male': 0, 'female': 1}
# Change Age column to
# map Age ranges (AgeBands) to ordinal integer numbers
df.loc[ df['Age'] <= 16, 'Age'] = 0
df.loc[(df['Age'] > 16) & (df['Age'] <= 32), 'Age'] = 1
df.loc[(df['Age'] > 32) & (df['Age'] <= 48), 'Age'] = 2
df.loc[(df['Age'] > 48) & (df['Age'] <= 64), 'Age'] = 3
df.loc[ df['Age'] > 64, 'Age']=4
df = df.drop(['AgeBand'], axis=1)
df.head()
# Note we could just run
# df['Age'] = pd.cut(df['Age'], 5,labels=[0,1,2,3,4])
```
### Travel Party Size
How did the number of people the person traveled with impact the chance of survival?
```
# SibSp = Number of Sibling / Spouses
# Parch = Parents / Children
df['FamilySize'] = df['SibSp'] + df['Parch'] + 1
# Survival chance against FamilySize
df[['FamilySize', 'Survived']].groupby(['FamilySize'], as_index=True) \
.mean().sort_values(by='Survived', ascending=False)
# Plot it, 1 is survived
sns.countplot(x='Survived', hue="FamilySize", data=df, order=[1,0]);
# Create binary variable if the person was alone or not
df['IsAlone'] = 0
df.loc[df['FamilySize'] == 1, 'IsAlone'] = 1
df[['IsAlone', 'Survived']].groupby(['IsAlone'], as_index=True).mean()
# We will only use the binary IsAlone feature for further analysis
df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1, inplace=True)
df.head()
```
# Feature construction
```
# We can also create new features based on intuitive combinations
# Here is an example when we say that the age times socioclass is a determinant factor
df['Age*Class'] = df.Age.values * df.Pclass.values
df.loc[:, ['Age*Class', 'Age', 'Pclass']].head()
```
## Port the person embarked from
Let's see how that influences chance of survival
<img src= "data/images/titanic_voyage_map.png">
>___
```
# Fill NaN 'Embarked' Values in the dfs
freq_port = df['Embarked'].dropna().mode()[0]
df['Embarked'] = df['Embarked'].fillna(freq_port)
# Plot it, 1 is survived
sns.countplot(x='Survived', hue="Embarked", data=df, order=[1,0]);
df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=True) \
.mean().sort_values(by='Survived', ascending=False)
# Create categorical dummy variables for Embarked values
binary_encoded = pd.get_dummies(df.Embarked)
df[binary_encoded.columns] = binary_encoded
df.drop('Embarked', axis=1, inplace=True)
df.head()
```
### Finished -- Preprocessing Complete!
```
# All features are approximately on the same scale
# no need for feature engineering / normalization
df.head(7)
```
### Sanity Check: View the correlation between features
```
# Uncorrelated features are generally more powerful predictors
colormap = plt.cm.viridis
plt.figure(figsize=(12,12))
plt.title('Pearson Correlation of Features', y=1.05, size=15)
sns.heatmap(df.corr().round(2)\
,linewidths=0.1,vmax=1.0, square=True, cmap=colormap, \
linecolor='white', annot=True);
```
<a id='sec5'></a>
___
### Machine Learning, Prediction and Artifical Intelligence
Now we will use Machine Learning algorithms in order to predict if the person survived.
**We will choose the best model from:**
1. Logistic Regression
2. K-Nearest Neighbors (KNN)
3. Support Vector Machines (SVM)
4. Perceptron
5. XGBoost
6. Random Forest
7. Neural Network (Deep Learning)
### Setup Training and Validation Sets
```
X = df.drop("Survived", axis=1) # Training & Validation data
Y = df["Survived"] # Response / Target Variable
print(X.shape, Y.shape)
# Split training set so that we validate on 20% of the data
# Note that our algorithms will never have seen the validation
np.random.seed(1337) # set random seed for reproducibility
from sklearn.model_selection import train_test_split
X_train, X_val, Y_train, Y_val = \
train_test_split(X, Y, test_size=0.2)
print('Training Samples:', X_train.shape, Y_train.shape)
print('Validation Samples:', X_val.shape, Y_val.shape)
```
___
> ## General ML workflow
> 1. Create Model Object
> 2. Train the Model
> 3. Predict on _unseen_ data
> 4. Evaluate accuracy.
___
## Compare Different Prediciton Models
### 1. Logistic Regression
```
logreg = LogisticRegression() # create
logreg.fit(X_train, Y_train) # train
acc_log_2 = logreg.score(X_val, Y_val) # predict & evaluate
print('Logistic Regression accuracy:',\
str(round(acc_log_2*100,2)),'%')
```
### 2. K-Nearest Neighbour
```
knn = KNeighborsClassifier(n_neighbors = 5) # instantiate
knn.fit(X_train, Y_train) # fit
acc_knn = knn.score(X_val, Y_val) # predict + evaluate
print('K-Nearest Neighbors labeling accuracy:', str(round(acc_knn*100,2)),'%')
```
### 3. Support Vector Machine
```
# Support Vector Machines Classifier (non-linear kernel)
svc = SVC() # instantiate
svc.fit(X_train, Y_train) # fit
acc_svc = svc.score(X_val, Y_val) # predict + evaluate
print('Support Vector Machines labeling accuracy:', str(round(acc_svc*100,2)),'%')
```
### 4. Perceptron
```
perceptron = Perceptron() # instantiate
perceptron.fit(X_train, Y_train) # fit
acc_perceptron = perceptron.score(X_val, Y_val) # predict + evalaute
print('Perceptron labeling accuracy:', str(round(acc_perceptron*100,2)),'%')
```
### 5. Gradient Boosting
```
# XGBoost, same API as scikit-learn
gradboost = xgb.XGBClassifier(n_estimators=1000) # instantiate
gradboost.fit(X_train, Y_train) # fit
acc_xgboost = gradboost.score(X_val, Y_val) # predict + evalute
print('XGBoost labeling accuracy:', str(round(acc_xgboost*100,2)),'%')
```
### 6. Random Forest
```
# Random Forest
random_forest = RandomForestClassifier(n_estimators=500) # instantiate
random_forest.fit(X_train, Y_train) # fit
acc_rf = random_forest.score(X_val, Y_val) # predict + evaluate
print('Random Forest labeling accuracy:', str(round(acc_rf*100,2)),'%')
```
### 7. Neural Networks (Deep Learning)
```
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add( Dense(units=300, activation='relu', input_shape=(13,) ))
model.add( Dense(units=100, activation='relu'))
model.add( Dense(units=50, activation='relu'))
model.add( Dense(units=1, activation='sigmoid') )
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
model.fit(X_train, Y_train, epochs = 50, batch_size= 50)
# # Evaluate the model Accuracy on test set
print('Neural Network accuracy:',str(round(model.evaluate(X_val, Y_val, batch_size=50,verbose=False)[1]*100,2)),'%')
```
### Importance scores in the random forest model
```
# Look at importnace of features for random forest
def plot_model_var_imp( model , X , y ):
imp = pd.DataFrame(
model.feature_importances_ ,
columns = [ 'Importance' ] ,
index = X.columns
)
imp = imp.sort_values( [ 'Importance' ] , ascending = True )
imp[ : 10 ].plot( kind = 'barh' )
print ('Training accuracy Random Forest:',model.score( X , y ))
plot_model_var_imp(random_forest, X_train, Y_train)
```
<a id='sec6'></a>
___
## Appendix I:
#### Why are our models maxing out at around 80%?
#### __John Jacob Astor__
<img src= "data/images/john-jacob-astor.jpg">
John Jacob Astor perished in the disaster even though our model predicted he would survive. Astor was the wealthiest person on the Titanic -- his ticket fare was valued at over 35,000 USD in 2016 -- it seems likely that he would have been among of the approximatelly 35 percent of men in first class to survive. However, this was not the case: although his pregnant wife survived, John Jacob Astor’s body was recovered a week later, along with a gold watch, a diamond ring with three stones, and no less than 92,481 USD (2016 value) in cash.
<br >
#### __Olaus Jorgensen Abelseth__
<img src= "data/images/olaus-jorgensen-abelseth.jpg">
Avelseth was a 25-year-old Norwegian sailor, a man in 3rd class, and not expected to survive by classifier. However, once the ship sank, he survived by swimming for 20 minutes in the frigid North Atlantic water before joining other survivors on a waterlogged collapsible boat.
Abelseth got married three years later, settled down as a farmer in North Dakota, had 4 kids, and died in 1980 at the age of 94.
<br >
### __Key Takeaway__
As engineers and business professionals we are trained to answer the question 'what could we do to improve on an 80 percent average'. These data points represent real people. Each time our model was wrong we should be glad -- in such misclasifications we will likely find incredible stories of human nature and courage triumphing over extremely difficult odds.
__It is important to never lose sight of the human element when analyzing data that deals with people.__
<a id='sec7'></a>
___
## Appendix II: Resources and references to material we won't cover in detail
> * **Gradient Boosting:** http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/
> * **Jupyter Notebook (tutorial):** https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook
> * **K-Nearest Neighbors (KNN):** https://towardsdatascience.com/introduction-to-k-nearest-neighbors-3b534bb11d26
> * **Logistic Regression:** https://towardsdatascience.com/5-reasons-logistic-regression-should-be-the-first-thing-you-learn-when-become-a-data-scientist-fcaae46605c4
> * **Naive Bayes:** http://scikit-learn.org/stable/modules/naive_bayes.html
> * **Perceptron:** http://aass.oru.se/~lilien/ml/seminars/2007_02_01b-Janecek-Perceptron.pdf
> * **Random Forest:** https://medium.com/@williamkoehrsen/random-forest-simple-explanation-377895a60d2d
> * **Support Vector Machines (SVM):** https://towardsdatascience.com/https-medium-com-pupalerushikesh-svm-f4b42800e989
<br>
___
___

| github_jupyter |
## Neural Networks in PyMC3 estimated with Variational Inference
(c) 2016 by Thomas Wiecki
## Current trends in Machine Learning
There are currently three big trends in machine learning: **Probabilistic Programming**, **Deep Learning** and "**Big Data**". Inside of PP, a lot of innovation is in making things scale using **Variational Inference**. In this blog post, I will show how to use **Variational Inference** in [PyMC3](http://pymc-devs.github.io/pymc3/) to fit a simple Bayesian Neural Network. I will also discuss how bridging Probabilistic Programming and Deep Learning can open up very interesting avenues to explore in future research.
### Probabilistic Programming at scale
**Probabilistic Programming** allows very flexible creation of custom probabilistic models and is mainly concerned with **insight** and learning from your data. The approach is inherently **Bayesian** so we can specify **priors** to inform and constrain our models and get uncertainty estimation in form of a **posterior** distribution. Using [MCMC sampling algorithms](http://twiecki.github.io/blog/2015/11/10/mcmc-sampling/) we can draw samples from this posterior to very flexibly estimate these models. [PyMC3](http://pymc-devs.github.io/pymc3/) and [Stan](http://mc-stan.org/) are the current state-of-the-art tools to consruct and estimate these models. One major drawback of sampling, however, is that it's often very slow, especially for high-dimensional models. That's why more recently, **variational inference** algorithms have been developed that are almost as flexible as MCMC but much faster. Instead of drawing samples from the posterior, these algorithms instead fit a distribution (e.g. normal) to the posterior turning a sampling problem into and optimization problem. [ADVI](http://arxiv.org/abs/1506.03431) -- Automatic Differentation Variational Inference -- is implemented in [PyMC3](http://pymc-devs.github.io/pymc3/) and [Stan](http://mc-stan.org/), as well as a new package called [Edward](https://github.com/blei-lab/edward/) which is mainly concerned with Variational Inference.
Unfortunately, when it comes traditional ML problems like classification or (non-linear) regression, Probabilistic Programming often plays second fiddle (in terms of accuracy and scalability) to more algorithmic approaches like [ensemble learning](https://en.wikipedia.org/wiki/Ensemble_learning) (e.g. [random forests](https://en.wikipedia.org/wiki/Random_forest) or [gradient boosted regression trees](https://en.wikipedia.org/wiki/Boosting_(machine_learning)).
### Deep Learning
Now in its third renaissance, deep learning has been making headlines repeatadly by dominating almost any object recognition benchmark, [kicking ass at Atari games](https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf), and [beating the world-champion Lee Sedol at Go](http://www.nature.com/nature/journal/v529/n7587/full/nature16961.html). From a statistical point, Neural Networks are extremely good non-linear function approximators and representation learners. While mostly known for classification, they have been extended to unsupervised learning with [AutoEncoders](https://arxiv.org/abs/1312.6114) and in all sorts of other interesting ways (e.g. [Recurrent Networks](https://en.wikipedia.org/wiki/Recurrent_neural_network), or [MDNs](http://cbonnett.github.io/MDN_EDWARD_KERAS_TF.html) to estimate multimodal distributions). Why do they work so well? No one really knows as the statistical properties are still not fully understood.
A large part of the innoviation in deep learning is the ability to train these extremely complex models. This rests on several pillars:
* Speed: facilitating the GPU allowed for much faster processing.
* Software: frameworks like [Theano](http://deeplearning.net/software/theano/) and [TensorFlow](https://www.tensorflow.org/) allow flexible creation of abstract models that can then be optimized and compiled to CPU or GPU.
* Learning algorithms: training on sub-sets of the data -- stochastic gradient descent -- allows us to train these models on massive amounts of data. Techniques like drop-out avoid overfitting.
* Architectural: A lot of innovation comes from changing the input layers, like for convolutional neural nets, or the output layers, like for [MDNs](http://cbonnett.github.io/MDN_EDWARD_KERAS_TF.html).
### Bridging Deep Learning and Probabilistic Programming
On one hand we Probabilistic Programming which allows us to build rather small and focused models in a very principled and well-understood way to gain insight into our data; on the other hand we have deep learning which uses many heuristics to train huge and highly complex models that are amazing at prediction. Recent innovations in variational inference allow probabilistic programming to scale model complexity as well as data size. We are thus at the cusp of being able to combine these two approaches to hopefully unlock new innovations in Machine Learning. For more motivation, see also [Dustin Tran's](https://twitter.com/dustinvtran) recent [blog post](http://dustintran.com/blog/a-quick-update-edward-and-some-motivations/).
While this would allow Probabilistic Programming to be applied to a much wider set of interesting problems, I believe this bridging also holds great promise for innovations in Deep Learning. Some ideas are:
* **Uncertainty in predictions**: As we will see below, the Bayesian Neural Network informs us about the uncertainty in its predictions. I think uncertainty is an underappreciated concept in Machine Learning as it's clearly important for real-world applications. But it could also be useful in training. For example, we could train the model specifically on samples it is most uncertain about.
* **Uncertainty in representations**: We also get uncertainty estimates of our weights which could inform us about the stability of the learned representations of the network.
* **Regularization with priors**: Weights are often L2-regularized to avoid overfitting, this very naturally becomes a Gaussian prior for the weight coefficients. We could, however, imagine all kinds of other priors, like spike-and-slab to enforce sparsity (this would be more like using the L1-norm).
* **Transfer learning with informed priors**: If we wanted to train a network on a new object recognition data set, we could bootstrap the learning by placing informed priors centered around weights retrieved from other pre-trained networks, like [GoogLeNet](https://arxiv.org/abs/1409.4842).
* **Hierarchical Neural Networks**: A very powerful approach in Probabilistic Programming is hierarchical modeling that allows pooling of things that were learned on sub-groups to the overall population (see my tutorial on [Hierarchical Linear Regression in PyMC3](http://twiecki.github.io/blog/2014/03/17/bayesian-glms-3/)). Applied to Neural Networks, in hierarchical data sets, we could train individual neural nets to specialize on sub-groups while still being informed about representations of the overall population. For example, imagine a network trained to classify car models from pictures of cars. We could train a hierarchical neural network where a sub-neural network is trained to tell apart models from only a single manufacturer. The intuition being that all cars from a certain manufactures share certain similarities so it would make sense to train individual networks that specialize on brands. However, due to the individual networks being connected at a higher layer, they would still share information with the other specialized sub-networks about features that are useful to all brands. Interestingly, different layers of the network could be informed by various levels of the hierarchy -- e.g. early layers that extract visual lines could be identical in all sub-networks while the higher-order representations would be different. The hierarchical model would learn all that from the data.
* **Other hybrid architectures**: We can more freely build all kinds of neural networks. For example, Bayesian non-parametrics could be used to flexibly adjust the size and shape of the hidden layers to optimally scale the network architecture to the problem at hand during training. Currently, this requires costly hyper-parameter optimization and a lot of tribal knowledge.
## Bayesian Neural Networks in PyMC3
### Generating data
First, lets generate some toy data -- a simple binary classification problem that's not linearly separable.
```
%matplotlib inline
import pymc3 as pm
import theano.tensor as T
import theano
import sklearn
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
from sklearn import datasets
from sklearn.preprocessing import scale
from sklearn.cross_validation import train_test_split
from sklearn.datasets import make_moons
X, Y = make_moons(noise=0.2, random_state=0, n_samples=1000)
X = scale(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.5)
fig, ax = plt.subplots()
ax.scatter(X[Y==0, 0], X[Y==0, 1], label='Class 0')
ax.scatter(X[Y==1, 0], X[Y==1, 1], color='r', label='Class 1')
sns.despine(); ax.legend()
ax.set(xlabel='X', ylabel='Y', title='Toy binary classification data set');
```
### Model specification
A neural network is quite simple. The basic unit is a [perceptron](https://en.wikipedia.org/wiki/Perceptron) which is nothing more than [logistic regression](http://pymc-devs.github.io/pymc3/notebooks/posterior_predictive.html#Prediction). We use many of these in parallel and then stack them up to get hidden layers. Here we will use 2 hidden layers with 5 neurons each which is sufficient for such a simple problem.
```
# Trick: Turn inputs and outputs into shared variables.
# It's still the same thing, but we can later change the values of the shared variable
# (to switch in the test-data later) and pymc3 will just use the new data.
# Kind-of like a pointer we can redirect.
# For more info, see: http://deeplearning.net/software/theano/library/compile/shared.html
ann_input = theano.shared(X_train)
ann_output = theano.shared(Y_train)
n_hidden = 5
# Initialize random weights between each layer
init_1 = np.random.randn(X.shape[1], n_hidden)
init_2 = np.random.randn(n_hidden, n_hidden)
init_out = np.random.randn(n_hidden)
with pm.Model() as neural_network:
# Weights from input to hidden layer
weights_in_1 = pm.Normal('w_in_1', 0, sd=1,
shape=(X.shape[1], n_hidden),
testval=init_1)
# Weights from 1st to 2nd layer
weights_1_2 = pm.Normal('w_1_2', 0, sd=1,
shape=(n_hidden, n_hidden),
testval=init_2)
# Weights from hidden layer to output
weights_2_out = pm.Normal('w_2_out', 0, sd=1,
shape=(n_hidden,),
testval=init_out)
# Build neural-network using tanh activation function
act_1 = T.tanh(T.dot(ann_input,
weights_in_1))
act_2 = T.tanh(T.dot(act_1,
weights_1_2))
act_out = T.nnet.sigmoid(T.dot(act_2,
weights_2_out))
# Binary classification -> Bernoulli likelihood
out = pm.Bernoulli('out',
act_out,
observed=ann_output)
```
That's not so bad. The `Normal` priors help regularize the weights. Usually we would add a constant `b` to the inputs but I omitted it here to keep the code cleaner.
### Variational Inference: Scaling model complexity
We could now just run a MCMC sampler like [`NUTS`](http://pymc-devs.github.io/pymc3/api.html#nuts) which works pretty well in this case but as I already mentioned, this will become very slow as we scale our model up to deeper architectures with more layers.
Instead, we will use the brand-new [ADVI](http://pymc-devs.github.io/pymc3/api.html#advi) variational inference algorithm which was recently added to `PyMC3`. This is much faster and will scale better. Note, that this is a mean-field approximation so we ignore correlations in the posterior.
```
%%time
with neural_network:
# Run ADVI which returns posterior means, standard deviations, and the evidence lower bound (ELBO)
v_params = pm.variational.advi(n=50000)
```
< 40 seconds on my older laptop. That's pretty good considering that NUTS is having a really hard time. Further below we make this even faster. To make it really fly, we probably want to run the Neural Network on the GPU.
As samples are more convenient to work with, we can very quickly draw samples from the variational posterior using `sample_vp()` (this is just sampling from Normal distributions, so not at all the same like MCMC):
```
with neural_network:
trace = pm.variational.sample_vp(v_params, draws=5000)
```
Plotting the objective function (ELBO) we can see that the optimization slowly improves the fit over time.
```
plt.plot(v_params.elbo_vals)
plt.ylabel('ELBO')
plt.xlabel('iteration')
```
Now that we trained our model, lets predict on the hold-out set using a posterior predictive check (PPC). We use [`sample_ppc()`](http://pymc-devs.github.io/pymc3/api.html#pymc3.sampling.sample_ppc) to generate new data (in this case class predictions) from the posterior (sampled from the variational estimation).
```
# Replace shared variables with testing set
ann_input.set_value(X_test)
ann_output.set_value(Y_test)
# Creater posterior predictive samples
ppc = pm.sample_ppc(trace, model=neural_network, samples=500)
# Use probability of > 0.5 to assume prediction of class 1
pred = ppc['out'].mean(axis=0) > 0.5
fig, ax = plt.subplots()
ax.scatter(X_test[pred==0, 0], X_test[pred==0, 1])
ax.scatter(X_test[pred==1, 0], X_test[pred==1, 1], color='r')
sns.despine()
ax.set(title='Predicted labels in testing set', xlabel='X', ylabel='Y');
plt.savefig("nn-0.png",dpi=400)
print('Accuracy = {}%'.format((Y_test == pred).mean() * 100))
```
Hey, our neural network did all right!
## Lets look at what the classifier has learned
For this, we evaluate the class probability predictions on a grid over the whole input space.
```
grid = np.mgrid[-3:3:100j,-3:3:100j]
grid_2d = grid.reshape(2, -1).T
X, Y = grid
dummy_out = np.ones(grid.shape[1], dtype=np.int8)
ann_input.set_value(grid_2d)
ann_output.set_value(dummy_out)
# Creater posterior predictive samples
ppc = pm.sample_ppc(trace, model=neural_network, samples=500)
```
### Probability surface
```
cmap = sns.diverging_palette(250, 12, s=85, l=25, as_cmap=True)
fig, ax = plt.subplots(figsize=(10, 6))
contour = ax.contourf(X, Y, ppc['out'].mean(axis=0).reshape(100, 100), cmap=cmap)
ax.scatter(X_test[pred==0, 0], X_test[pred==0, 1])
ax.scatter(X_test[pred==1, 0], X_test[pred==1, 1], color='r')
cbar = plt.colorbar(contour, ax=ax)
_ = ax.set(xlim=(-3, 3), ylim=(-3, 3), xlabel='X', ylabel='Y');
cbar.ax.set_ylabel('Posterior predictive mean probability of class label = 0');
plt.savefig("nn-1.png",dpi=400)
```
### Uncertainty in predicted value
So far, everything I showed we could have done with a non-Bayesian Neural Network. The mean of the posterior predictive for each class-label should be identical to maximum likelihood predicted values. However, we can also look at the standard deviation of the posterior predictive to get a sense for the uncertainty in our predictions. Here is what that looks like:
```
cmap = sns.cubehelix_palette(light=1, as_cmap=True)
fig, ax = plt.subplots(figsize=(10, 6))
contour = ax.contourf(X, Y, ppc['out'].std(axis=0).reshape(100, 100), cmap=cmap)
ax.scatter(X_test[pred==0, 0], X_test[pred==0, 1])
ax.scatter(X_test[pred==1, 0], X_test[pred==1, 1], color='r')
cbar = plt.colorbar(contour, ax=ax)
_ = ax.set(xlim=(-3, 3), ylim=(-3, 3), xlabel='X', ylabel='Y');
cbar.ax.set_ylabel('Uncertainty (posterior predictive standard deviation)');
plt.savefig("nn-2.png",dpi=400)
```
We can see that very close to the decision boundary, our uncertainty as to which label to predict is highest. You can imagine that associating predictions with uncertainty is a critical property for many applications like health care. To further maximize accuracy, we might want to train the model primarily on samples from that high-uncertainty region.
## Mini-batch ADVI: Scaling data size
So far, we have trained our model on all data at once. Obviously this won't scale to something like ImageNet. Moreover, training on mini-batches of data (stochastic gradient descent) avoids local minima and can lead to faster convergence.
Fortunately, ADVI can be run on mini-batches as well. It just requires some setting up:
```
from six.moves import zip
# Set back to original data to retrain
ann_input.set_value(X_train)
ann_output.set_value(Y_train)
# Tensors and RV that will be using mini-batches
minibatch_tensors = [ann_input, ann_output]
minibatch_RVs = [out]
# Generator that returns mini-batches in each iteration
def create_minibatch(data):
rng = np.random.RandomState(0)
while True:
# Return random data samples of set size 100 each iteration
ixs = rng.randint(len(data), size=50)
yield data[ixs]
minibatches = zip(
create_minibatch(X_train),
create_minibatch(Y_train),
)
total_size = len(Y_train)
```
While the above might look a bit daunting, I really like the design. Especially the fact that you define a generator allows for great flexibility. In principle, we could just pool from a database there and not have to keep all the data in RAM.
Lets pass those to `advi_minibatch()`:
```
%%time
with neural_network:
# Run advi_minibatch
v_params = pm.variational.advi_minibatch(
n=50000, minibatch_tensors=minibatch_tensors,
minibatch_RVs=minibatch_RVs, minibatches=minibatches,
total_size=total_size, learning_rate=1e-2, epsilon=1.0
)
with neural_network:
trace = pm.variational.sample_vp(v_params, draws=5000)
plt.plot(v_params.elbo_vals)
plt.ylabel('ELBO')
plt.xlabel('iteration')
sns.despine()
```
As you can see, mini-batch ADVI's running time is much lower. It also seems to converge faster.
For fun, we can also look at the trace. The point is that we also get uncertainty of our Neural Network weights.
```
pm.traceplot(trace);
```
## Summary
Hopefully this blog post demonstrated a very powerful new inference algorithm available in [PyMC3](http://pymc-devs.github.io/pymc3/): [ADVI](http://pymc-devs.github.io/pymc3/api.html#advi). I also think bridging the gap between Probabilistic Programming and Deep Learning can open up many new avenues for innovation in this space, as discussed above. Specifically, a hierarchical neural network sounds pretty bad-ass. These are really exciting times.
## Next steps
[`Theano`](http://deeplearning.net/software/theano/), which is used by `PyMC3` as its computational backend, was mainly developed for estimating neural networks and there are great libraries like [`Lasagne`](https://github.com/Lasagne/Lasagne) that build on top of `Theano` to make construction of the most common neural network architectures easy. Ideally, we wouldn't have to build the models by hand as I did above, but use the convenient syntax of `Lasagne` to construct the architecture, define our priors, and run ADVI.
While we haven't successfully run `PyMC3` on the GPU yet, it should be fairly straight forward (this is what `Theano` does after all) and further reduce the running time significantly. If you know some `Theano`, this would be a great area for contributions!
You might also argue that the above network isn't really deep, but note that we could easily extend it to have more layers, including convolutional ones to train on more challenging data sets.
I also presented some of this work at PyData London, view the video below:
<iframe width="560" height="315" src="https://www.youtube.com/embed/LlzVlqVzeD8" frameborder="0" allowfullscreen></iframe>
Finally, you can download this NB [here](https://github.com/twiecki/WhileMyMCMCGentlySamples/blob/master/content/downloads/notebooks/bayesian_neural_network.ipynb). Leave a comment below, and [follow me on twitter](https://twitter.com/twiecki).
## Acknowledgements
[Taku Yoshioka](https://github.com/taku-y) did a lot of work on ADVI in PyMC3, including the mini-batch implementation as well as the sampling from the variational posterior. I'd also like to the thank the Stan guys (specifically Alp Kucukelbir and Daniel Lee) for deriving ADVI and teaching us about it. Thanks also to Chris Fonnesbeck, Andrew Campbell, Taku Yoshioka, and Peadar Coyle for useful comments on an earlier draft.
| github_jupyter |
# 1.1 Getting started
## Prerequisites
### Installation
This tutorial requires **signac**, so make sure to install the package before starting.
The easiest way to do so is using conda:
```$ conda config --add channels conda-forge```
```$ conda install signac```
or pip:
```pip install signac --user```
Please refer to the [documentation](https://docs.signac.io/en/latest/installation.html#installation) for detailed instructions on how to install signac.
After successful installation, the following cell should execute without error:
```
import signac
```
We start by removing all data which might be left-over from previous executions of this tutorial.
```
%rm -rf projects/tutorial/workspace
```
## A minimal example
For this tutorial we want to compute the volume of an ideal gas as a function of its pressure and thermal energy using the ideal gas equation
$p V = N kT$, where
$N$ refers to the system size, $p$ to the pressure, $kT$ to the thermal energy and $V$ is the volume of the system.
```
def V_idg(N, kT, p):
return N * kT / p
```
We can execute the complete study in just a few lines of code.
First, we initialize the project directory and get a project handle:
```
import signac
project = signac.init_project(name="TutorialProject", root="projects/tutorial")
```
We iterate over the variable of interest *p* and construct a complete state point *sp* which contains all the meta data associated with our data.
In this simple example the meta data is very compact, but in principle the state point may be highly complex.
Next, we obtain a *job* handle and store the result of the calculation within the *job document*.
The *job document* is a persistent dictionary for storage of simple key-value pairs.
Here, we exploit that the state point dictionary *sp* can easily be passed into the `V_idg()` function using the [keyword expansion syntax](https://docs.python.org/dev/tutorial/controlflow.html#keyword-arguments) (`**sp`).
```
for p in 0.1, 1.0, 10.0:
sp = {"p": p, "kT": 1.0, "N": 1000}
job = project.open_job(sp)
job.document["V"] = V_idg(**sp)
```
We can then examine our results by iterating over the data space:
```
for job in project:
print(job.sp.p, job.document["V"])
```
That's it.
...
Ok, there's more...
Let's have a closer look at the individual components.
## The Basics
The **signac** data management framework assists the user in managing the data space of individual *projects*.
All data related to one or multiple projects is stored in a *workspace*, which by default is a directory called `workspace` within the project's root directory.
```
print(project.root_directory())
print(project.workspace())
```
The core idea is to tightly couple state points, unique sets of parameters, with their associated data.
In general, the parameter space needs to contain all parameters that will affect our data.
For the ideal gas that is a 3-dimensional space spanned by the thermal energy *kT*, the pressure *p* and the system size *N*.
These are the **input parameters** for our calculations, while the calculated volume *V* is the **output data**.
In terms of **signac** this relationship is represented by an instance of `Job`.
We use the `open_job()` method to get a *job handle* for a specific set of input parameters.
```
job = project.open_job({"p": 1.0, "kT": 1.0, "N": 1000})
```
The *job* handle tightly couples our input parameters (*p*, *kT*, *N*) with the storage location of the output data.
You can inspect both the input parameters and the storage location explicitly:
```
print(job.statepoint())
print(job.workspace())
```
For convenience, a job's *state point* may also be accessed via the short-hand `sp` attribute.
For example, to access the pressure value `p` we can use either of the two following expressions:
```
print(job.statepoint()["p"])
print(job.sp.p)
```
Each *job* has a **unique id** representing the state point.
This means opening a job with the exact same input parameters is guaranteed to have the **exact same id**.
```
job2 = project.open_job({"kT": 1.0, "N": 1000, "p": 1.0})
print(job.id, job2.id)
```
The *job id* is used to uniquely identify data associated with a specific state point.
Think of the *job* as a container that is used to store all data associated with the state point.
For example, it should be safe to assume that all files that are stored within the job's workspace directory are tightly coupled to the job's statepoint.
```
print(job.workspace())
```
Let's store the volume calculated for each state point in a file called `V.txt` within the job's workspace.
```
import os
fn_out = os.path.join(job.workspace(), "V.txt")
with open(fn_out, "w") as file:
V = V_idg(**job.statepoint())
file.write(str(V) + "\n")
```
Because this is such a common pattern, **signac** signac allows you to short-cut this with the `job.fn()` method.
```
with open(job.fn("V.txt"), "w") as file:
V = V_idg(**job.statepoint())
file.write(str(V) + "\n")
```
Sometimes it is easier to temporarily switch the *current working directory* while storing data for a specific job.
For this purpose, we can use the `Job` object as [context manager](https://docs.python.org/3/reference/compound_stmts.html#with).
This means that we switch into the workspace directory associated with the job after entering, and switch back into the original working directory after exiting.
```
with job:
with open("V.txt", "w") as file:
file.write(str(V) + "\n")
```
Another alternative to store light-weight data is the *job document* as shown in the minimal example.
The *job document* is a persistent JSON storage file for simple key-value pairs.
```
job.document["V"] = V_idg(**job.statepoint())
print(job.statepoint(), job.document)
```
Since we are usually interested in more than one state point, the standard operation is to iterate over all variable(s) of interest, construct the full state point, get the associated job handle, and then either just initialize the job or perform the full operation.
```
for pressure in 0.1, 1.0, 10.0:
statepoint = {"p": pressure, "kT": 1.0, "N": 1000}
job = project.open_job(statepoint)
job.document["V"] = V_idg(**job.statepoint())
```
Let's verify our result by inspecting the data.
```
for job in project:
print(job.statepoint(), job.document)
```
Those are the basics for using **signac** for data management.
The [next section](signac_102_Exploring_Data.ipynb) demonstrates how to explore an existing data space.
| github_jupyter |
<a href="https://colab.research.google.com/github/DJCordhose/ml-workshop/blob/master/notebooks/tf-intro/2020-01-rnn-basics.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Sequences Basics
Example, some code and a lot of inspiration taken from: https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/
```
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (20, 8)
try:
# %tensorflow_version only exists in Colab.
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
print(tf.__version__)
```
## Univariate Sequences
just one variable per time step
### Challenge
We have a known series of events, possibly in time and you want to know what is the next event. Like this
[10, 20, 30, 40, 50, 60, 70, 80, 90]
```
# univariate data preparation
import numpy as np
# split a univariate sequence into samples
def split_sequence(sequence, n_steps):
X, y = list(), list()
for i in range(len(sequence)):
# find the end of this pattern
end_ix = i + n_steps
# check if we are beyond the sequence
if end_ix > len(sequence)-1:
break
# gather input and output parts of the pattern
seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
X.append(seq_x)
y.append(seq_y)
return np.array(X), np.array(y)
#@title Prediction from n past steps
# https://colab.research.google.com/notebooks/forms.ipynb
n_steps = 3 #@param {type:"slider", min:1, max:10, step:1}
# define input sequence
raw_seq = [10, 20, 30, 40, 50, 60, 70, 80, 90]
# split into samples
X, y = split_sequence(raw_seq, n_steps)
# summarize the data
list(zip(X, y))
X
```
### Converting shapes
* one of the most frequent, yet most tedious steps
* match between what you have and what an interface needs
* expected input of RNN: 3D tensor with shape (samples, timesteps, input_dim)
* we have: (samples, timesteps)
* reshape on np arrays can do all that
```
# reshape from [samples, timesteps] into [samples, timesteps, features]
n_features = 1
X = X.reshape((X.shape[0], X.shape[1], n_features))
X
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense, LSTM, GRU, SimpleRNN, Bidirectional
from tensorflow.keras.models import Sequential, Model
model = Sequential()
model.add(SimpleRNN(units=50, activation='relu', input_shape=(n_steps, n_features), name="RNN_Input"))
model.add(Dense(units=1, name="Linear_Output"))
model.compile(optimizer='adam', loss='mse')
model.summary()
EPOCHS = 1000
%time history = model.fit(X, y, epochs=EPOCHS, verbose=0)
loss = model.evaluate(X, y, verbose=0)
loss
import matplotlib.pyplot as plt
plt.yscale('log')
plt.ylabel("loss")
plt.xlabel("epochs")
plt.plot(history.history['loss']);
```
### Let's try this on a few examples
```
# this does not look too bad
X_sample = np.array([[10, 20, 30], [70, 80, 90]]).astype(np.float32)
X_sample = X_sample.reshape((X_sample.shape[0], X_sample.shape[1], n_features))
X_sample
y_pred = model.predict(X_sample)
y_pred
def predict(model, samples, n_features=1):
input = np.array(samples).astype(np.float32)
input = input.reshape((input.shape[0], input.shape[1], n_features))
y_pred = model.predict(input)
return y_pred
# do not look too close, though
predict(model, [[100, 110, 120], [200, 210, 220], [200, 300, 400]])
```
## Exercise
* go through the notebook as it is
* Try to improve the model
* Change the number of values used as input
* Change activation function
* More nodes? less nodes?
* What else might help improving the results?
# STOP HERE
### Input and output of an RNN layer
```
# https://keras.io/layers/recurrent/
# input: (samples, timesteps, input_dim)
# output: (samples, units)
# let's have a look at the actual output for an example
rnn_layer = model.get_layer("RNN_Input")
model_stub = Model(inputs = model.input, outputs = rnn_layer.output)
hidden = predict(model_stub, [[10, 20, 30]])
hidden.shape, hidden
```
#### What do we see?
* each unit (50) has a single output
* as a sidenote you nicely see the RELU nature of the output
* so the timesteps of the input are lost
* we are only looking at the final output
* still with each timestep, the layer does produce a unique output we could potentially use
### We need to look into RNNs a bit more deeply now
#### RNNs - Networks with Loops
<img src='https://djcordhose.github.io/ai/img/nlp/colah/RNN-rolled.png' height=200>
http://colah.github.io/posts/2015-08-Understanding-LSTMs/
#### Unrolling the loop
<img src='https://djcordhose.github.io/ai/img/nlp/colah/RNN-unrolled.png'>
http://colah.github.io/posts/2015-08-Understanding-LSTMs/
#### Simple RNN internals
<img src='https://djcordhose.github.io/ai/img/nlp/fchollet_rnn.png'>
## $output_t = \tanh(W input_t + U output_{t-1} + b)$
From Deep Learning with Python, Chapter 6, François Chollet, Manning: https://livebook.manning.com/#!/book/deep-learning-with-python/chapter-6/129
#### Activation functions
<img src='https://djcordhose.github.io/ai/img/sigmoid-activation.png' height=200>
Sigmoid compressing between 0 and 1
<img src='https://djcordhose.github.io/ai/img/tanh-activation.png' height=200>
Hyperbolic tangent, like sigmoind, but compressing between -1 and 1, thus allowing for negative values as well
```
```
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
!nvidia-smi
from argparse import Namespace
import sys
import os
home = os.environ['HOME']
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
print(os.environ['CUDA_VISIBLE_DEVICES'])
os.chdir(f'{home}/pycharm/automl')
# os.chdir(f'{home}/pycharm/automl/search_policies/rnn')
sys.path.append(f'{home}/pycharm/nasbench')
sys.path.append(f'{home}/pycharm/automl')
import torch
import torch.nn as nn
import utils
from image_dataloader import load_dataset
from search_policies.cnn.search_space.nasbench101.nasbench_api_v2 import NASBench_v2
from search_policies.cnn.search_space.nasbench101.util import load_nasbench_checkpoint, transfer_model_key_to_search_key, nasbench_zero_padding_load_state_dict_pre_hook
from search_policies.cnn.procedures.train_search_procedure import darts_model_validation
from search_policies.cnn.search_space.nasbench101.model_search import NasBenchNetSearch
utils.torch_random_seed(10)
print('loading cifar ...')
train_queue, valid_queue, test_queue = load_dataset()
print("loading Nasbench dataset...")
nasbench = NASBench_v2('data/nasbench/nasbench_only108.tfrecord', only_hash=True)
sanity_check = True
# load one model and
MODEL_FOLDER='/home/yukaiche/pycharm/automl/experiments/reproduce-nasbench/rank_100002-arch_97a390a2cb02fdfbc505f6ac44a37228-eval-runid-0'
CKPT_PATH=MODEL_FOLDER + '/checkpoint.pt'
model_folder = MODEL_FOLDER
ckpt_path = CKPT_PATH
print("load model and test ...")
hash = model_folder.split('arch_')[1].split('-eval')[0]
print('model_hash ', hash)
spec = nasbench.hash_to_model_spec(hash)
print('model spec', spec)
# model, ckpt = load_nasbench_checkpoint(ckpt_path, spec, legacy=True)
from search_policies.cnn.cnn_search_configs import build_default_args
# def project the weights
default_args = build_default_args()
default_args.model_spec = spec
spec = nasbench.hash_to_model_spec(hash)
model, ckpt = load_nasbench_checkpoint(ckpt_path, spec, legacy=True)
model = model.cuda()
model.eval()
model_search = NasBenchNetSearch(args=default_args)
model_search.eval()
model_search = model_search.cuda()
source_dict = model.state_dict()
target_dict = model_search.state_dict()
# Checking the loaded model state dict.
if sanity_check:
for ind, k in enumerate(source_dict.keys()):
if ind > 5:
break
print(k, ((source_dict[k] - target_dict[k]).sum()))
trans_dict = dict()
for k in model.state_dict().keys():
kk = transfer_model_key_to_search_key(k, spec)
if kk not in model_search.state_dict().keys():
print('not found ', kk)
continue
# if sanity_check:
# print(f'map {k}', source_dict[k].size())
# print(f'to {kk}' ,target_dict[kk].size())
trans_dict[kk] = source_dict[k]
padded_dict = nasbench_zero_padding_load_state_dict_pre_hook(trans_dict, model_search.state_dict())
if sanity_check:
target_dict = model_search.state_dict()
for ind, k in enumerate(padded_dict.keys()):
if ind > 5:
break
print(k)
print((padded_dict[k] - target_dict[k]).sum().item())
print((ckpt['model_state'][k] - target_dict[k]).sum().item())
# print((padded_dict[k][trans_dict[k].size()[0]] - trans_dict[k]).sum())
# loaded the padded dict and test the results.
model_search.load_state_dict(padded_dict)
model_search = model_search.change_model_spec(spec)
model_search = model_search.eval()
res = darts_model_validation(test_queue, model, nn.CrossEntropyLoss(),Namespace(debug=False, report_freq=50))
print('original model evaluation on test split', res)
search_res = darts_model_validation(test_queue, model_search, nn.CrossEntropyLoss(),Namespace(debug=False, report_freq=50))
print('Reload to NasBenchSearch, evaluation results ' ,search_res)
# results get worse after padding to original node. Somethings goes wrong.
# Further sanity checking, by loading part of the model and continue.
# print(model.stacks['stack0']['module0'].vertex_ops.keys())
# print(spec.ops)
# m0 = model.stacks['stack0']['module0']
# print([k for k in m0.state_dict().keys() if 'vertex_1' not in k and 'proj' not in k ])
# # print([k for k in m0.state_dict().keys() if 'vertex_1' not in k and 'proj' not in k ])
# load_keys = sorted([transfer_model_key_to_search_key(k, spec) for k in k1])
# train_param_keys = sorted(train_param_keys)
# # for a1, a2 in zip(load_keys, train_param_keys):
# # print(a1)
# # print(a2)
# for a1 in load_keys:
# if a1 not in train_param_keys:
# print(a1)
# print(len(load_keys), len(train_param_keys))
model.eval()
model_search.load_state_dict(padded_dict)
model_search.eval()
# This debugs the entire network's output.
img, lab = iter(test_queue).__next__()
img = img.cuda()
lab = lab.cuda()
bz = 32
with torch.no_grad():
m1 = model.forward_debug(img[:bz, :, : ,:])
m2 = model_search.forward_debug(img[:bz, :, :, :])
for ind,(a,b) in enumerate(zip(m1, m2)):
print(ind, (a - b).sum().item())
# model_search.stem[1].eval()
# model.stem[1].eval()
# m1stem_out = model.stem(img)
# model_search.stem.load_state_dict(model.stem.state_dict())
# m2stem_out = model_search.stem(img)
# for k, v in model.stem.state_dict().items():
# print(k, (v - model_search.stem.state_dict()[k]).sum().item())
# print((m1stem_out - m2stem_out).sum().item())
s1input = m1[0].cuda()
m1stack = model.stacks['stack0']['module0']
m2stack = model_search.stacks['stack0']['module0']
print(m1stack.__class__.__name__)
print(m2stack.__class__.__name__)
print((m1stack(s1input) - m2stack(s1input)).sum().item())
m1out = m1stack.forward_debug(s1input)
m2out = m2stack.forward_debug(s1input)
# Cell level, not true after 1 iters
for k, v in m1out.items():
print(k, (v - m2out[k]).sum().item())
print(m1stack.execution_order.items())
# vertex level
m1vertex = m1stack.vertex_ops['vertex_1']
m2vertex = m2stack.vertex_ops['vertex_1']
print('vertex_1 difference', (m1vertex([s1input,]) - m2vertex([s1input,])).sum().item())
print(m1vertex)
print(m2vertex)
# inside vertex level, proj_ops and vertex_op
m1_proj = m1vertex.proj_ops[0](s1input)
m1_out = m1vertex.op(m1_proj)
m2_proj = m2vertex.current_proj_ops[0](s1input)
m2_out = m2vertex.current_op(m2_proj)
print('after v1 proj diff',(m1_proj - m2_proj).sum().item())
print('after v1 diff',(m1_out - m2_out).sum().item())
# proj level
m1projop = m1vertex.proj_ops[0]
m2projop = m2vertex.current_proj_ops[0]
print(m1projop)
print(m2projop)
print(m1projop[1].training)
print(m2projop.bn.training)
# m2vertex.train()
model_search.eval()
print(m1projop[1].training)
print(m2projop.bn.training)
import glob
model_lists = glob.glob('/home/yukaiche/pycharm/automl/experiments/reproduce-nasbench/*')
print(model_lists)
for model_folder in model_lists:
if len(glob.glob(model_folder + '/checkpoint.pt')) > 0:
hash = model_folder.split('arch_')[1].split('-eval')[0]
rank = model_folder.split('rank_')[1].split('-arch')[0]
print(rank, hash)
```
| github_jupyter |
SOP036 - Install kubectl command line interface
===============================================
Steps
-----
### Common functions
Define helper functions used in this notebook.
```
# Define `run` function for transient fault handling, suggestions on error, and scrolling updates on Windows
import sys
import os
import re
import json
import platform
import shlex
import shutil
import datetime
from subprocess import Popen, PIPE
from IPython.display import Markdown
retry_hints = {} # Output in stderr known to be transient, therefore automatically retry
error_hints = {} # Output in stderr where a known SOP/TSG exists which will be HINTed for further help
install_hint = {} # The SOP to help install the executable if it cannot be found
first_run = True
rules = None
debug_logging = False
def run(cmd, return_output=False, no_output=False, retry_count=0, base64_decode=False, return_as_json=False):
"""Run shell command, stream stdout, print stderr and optionally return output
NOTES:
1. Commands that need this kind of ' quoting on Windows e.g.:
kubectl get nodes -o jsonpath={.items[?(@.metadata.annotations.pv-candidate=='data-pool')].metadata.name}
Need to actually pass in as '"':
kubectl get nodes -o jsonpath={.items[?(@.metadata.annotations.pv-candidate=='"'data-pool'"')].metadata.name}
The ' quote approach, although correct when pasting into Windows cmd, will hang at the line:
`iter(p.stdout.readline, b'')`
The shlex.split call does the right thing for each platform, just use the '"' pattern for a '
"""
MAX_RETRIES = 5
output = ""
retry = False
global first_run
global rules
if first_run:
first_run = False
rules = load_rules()
# When running `azdata sql query` on Windows, replace any \n in """ strings, with " ", otherwise we see:
#
# ('HY090', '[HY090] [Microsoft][ODBC Driver Manager] Invalid string or buffer length (0) (SQLExecDirectW)')
#
if platform.system() == "Windows" and cmd.startswith("azdata sql query"):
cmd = cmd.replace("\n", " ")
# shlex.split is required on bash and for Windows paths with spaces
#
cmd_actual = shlex.split(cmd)
# Store this (i.e. kubectl, python etc.) to support binary context aware error_hints and retries
#
user_provided_exe_name = cmd_actual[0].lower()
# When running python, use the python in the ADS sandbox ({sys.executable})
#
if cmd.startswith("python "):
cmd_actual[0] = cmd_actual[0].replace("python", sys.executable)
# On Mac, when ADS is not launched from terminal, LC_ALL may not be set, which causes pip installs to fail
# with:
#
# UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 4969: ordinal not in range(128)
#
# Setting it to a default value of "en_US.UTF-8" enables pip install to complete
#
if platform.system() == "Darwin" and "LC_ALL" not in os.environ:
os.environ["LC_ALL"] = "en_US.UTF-8"
# When running `kubectl`, if AZDATA_OPENSHIFT is set, use `oc`
#
if cmd.startswith("kubectl ") and "AZDATA_OPENSHIFT" in os.environ:
cmd_actual[0] = cmd_actual[0].replace("kubectl", "oc")
# To aid supportability, determine which binary file will actually be executed on the machine
#
which_binary = None
# Special case for CURL on Windows. The version of CURL in Windows System32 does not work to
# get JWT tokens, it returns "(56) Failure when receiving data from the peer". If another instance
# of CURL exists on the machine use that one. (Unfortunately the curl.exe in System32 is almost
# always the first curl.exe in the path, and it can't be uninstalled from System32, so here we
# look for the 2nd installation of CURL in the path)
if platform.system() == "Windows" and cmd.startswith("curl "):
path = os.getenv('PATH')
for p in path.split(os.path.pathsep):
p = os.path.join(p, "curl.exe")
if os.path.exists(p) and os.access(p, os.X_OK):
if p.lower().find("system32") == -1:
cmd_actual[0] = p
which_binary = p
break
# Find the path based location (shutil.which) of the executable that will be run (and display it to aid supportability), this
# seems to be required for .msi installs of azdata.cmd/az.cmd. (otherwise Popen returns FileNotFound)
#
# NOTE: Bash needs cmd to be the list of the space separated values hence shlex.split.
#
if which_binary == None:
which_binary = shutil.which(cmd_actual[0])
# Display an install HINT, so the user can click on a SOP to install the missing binary
#
if which_binary == None:
if user_provided_exe_name in install_hint and install_hint[user_provided_exe_name] is not None:
display(Markdown(f'HINT: Use [{install_hint[user_provided_exe_name][0]}]({install_hint[user_provided_exe_name][1]}) to resolve this issue.'))
raise FileNotFoundError(f"Executable '{cmd_actual[0]}' not found in path (where/which)")
else:
cmd_actual[0] = which_binary
start_time = datetime.datetime.now().replace(microsecond=0)
print(f"START: {cmd} @ {start_time} ({datetime.datetime.utcnow().replace(microsecond=0)} UTC)")
print(f" using: {which_binary} ({platform.system()} {platform.release()} on {platform.machine()})")
print(f" cwd: {os.getcwd()}")
# Command-line tools such as CURL and AZDATA HDFS commands output
# scrolling progress bars, which causes Jupyter to hang forever, to
# workaround this, use no_output=True
#
# Work around a infinite hang when a notebook generates a non-zero return code, break out, and do not wait
#
wait = True
try:
if no_output:
p = Popen(cmd_actual)
else:
p = Popen(cmd_actual, stdout=PIPE, stderr=PIPE, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
line = line.decode()
if return_output:
output = output + line
else:
if cmd.startswith("azdata notebook run"): # Hyperlink the .ipynb file
regex = re.compile(' "(.*)"\: "(.*)"')
match = regex.match(line)
if match:
if match.group(1).find("HTML") != -1:
display(Markdown(f' - "{match.group(1)}": "{match.group(2)}"'))
else:
display(Markdown(f' - "{match.group(1)}": "[{match.group(2)}]({match.group(2)})"'))
wait = False
break # otherwise infinite hang, have not worked out why yet.
else:
print(line, end='')
if rules is not None:
apply_expert_rules(line)
if wait:
p.wait()
except FileNotFoundError as e:
if install_hint is not None:
display(Markdown(f'HINT: Use {install_hint} to resolve this issue.'))
raise FileNotFoundError(f"Executable '{cmd_actual[0]}' not found in path (where/which)") from e
exit_code_workaround = 0 # WORKAROUND: azdata hangs on exception from notebook on p.wait()
if not no_output:
for line in iter(p.stderr.readline, b''):
try:
line_decoded = line.decode()
except UnicodeDecodeError:
# NOTE: Sometimes we get characters back that cannot be decoded(), e.g.
#
# \xa0
#
# For example see this in the response from `az group create`:
#
# ERROR: Get Token request returned http error: 400 and server
# response: {"error":"invalid_grant",# "error_description":"AADSTS700082:
# The refresh token has expired due to inactivity.\xa0The token was
# issued on 2018-10-25T23:35:11.9832872Z
#
# which generates the exception:
#
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 179: invalid start byte
#
print("WARNING: Unable to decode stderr line, printing raw bytes:")
print(line)
line_decoded = ""
pass
else:
# azdata emits a single empty line to stderr when doing an hdfs cp, don't
# print this empty "ERR:" as it confuses.
#
if line_decoded == "":
continue
print(f"STDERR: {line_decoded}", end='')
if line_decoded.startswith("An exception has occurred") or line_decoded.startswith("ERROR: An error occurred while executing the following cell"):
exit_code_workaround = 1
# inject HINTs to next TSG/SOP based on output in stderr
#
if user_provided_exe_name in error_hints:
for error_hint in error_hints[user_provided_exe_name]:
if line_decoded.find(error_hint[0]) != -1:
display(Markdown(f'HINT: Use [{error_hint[1]}]({error_hint[2]}) to resolve this issue.'))
# apply expert rules (to run follow-on notebooks), based on output
#
if rules is not None:
apply_expert_rules(line_decoded)
# Verify if a transient error, if so automatically retry (recursive)
#
if user_provided_exe_name in retry_hints:
for retry_hint in retry_hints[user_provided_exe_name]:
if line_decoded.find(retry_hint) != -1:
if retry_count < MAX_RETRIES:
print(f"RETRY: {retry_count} (due to: {retry_hint})")
retry_count = retry_count + 1
output = run(cmd, return_output=return_output, retry_count=retry_count)
if return_output:
if base64_decode:
import base64
return base64.b64decode(output).decode('utf-8')
else:
return output
elapsed = datetime.datetime.now().replace(microsecond=0) - start_time
# WORKAROUND: We avoid infinite hang above in the `azdata notebook run` failure case, by inferring success (from stdout output), so
# don't wait here, if success known above
#
if wait:
if p.returncode != 0:
raise SystemExit(f'Shell command:\n\n\t{cmd} ({elapsed}s elapsed)\n\nreturned non-zero exit code: {str(p.returncode)}.\n')
else:
if exit_code_workaround !=0 :
raise SystemExit(f'Shell command:\n\n\t{cmd} ({elapsed}s elapsed)\n\nreturned non-zero exit code: {str(exit_code_workaround)}.\n')
print(f'\nSUCCESS: {elapsed}s elapsed.\n')
if return_output:
if base64_decode:
import base64
return base64.b64decode(output).decode('utf-8')
else:
return output
def load_json(filename):
"""Load a json file from disk and return the contents"""
with open(filename, encoding="utf8") as json_file:
return json.load(json_file)
def load_rules():
"""Load any 'expert rules' from the metadata of this notebook (.ipynb) that should be applied to the stderr of the running executable"""
# Load this notebook as json to get access to the expert rules in the notebook metadata.
#
try:
j = load_json("sop036-install-kubectl.ipynb")
except:
pass # If the user has renamed the book, we can't load ourself. NOTE: Is there a way in Jupyter, to know your own filename?
else:
if "metadata" in j and \
"azdata" in j["metadata"] and \
"expert" in j["metadata"]["azdata"] and \
"expanded_rules" in j["metadata"]["azdata"]["expert"]:
rules = j["metadata"]["azdata"]["expert"]["expanded_rules"]
rules.sort() # Sort rules, so they run in priority order (the [0] element). Lowest value first.
# print (f"EXPERT: There are {len(rules)} rules to evaluate.")
return rules
def apply_expert_rules(line):
"""Determine if the stderr line passed in, matches the regular expressions for any of the 'expert rules', if so
inject a 'HINT' to the follow-on SOP/TSG to run"""
global rules
for rule in rules:
notebook = rule[1]
cell_type = rule[2]
output_type = rule[3] # i.e. stream or error
output_type_name = rule[4] # i.e. ename or name
output_type_value = rule[5] # i.e. SystemExit or stdout
details_name = rule[6] # i.e. evalue or text
expression = rule[7].replace("\\*", "*") # Something escaped *, and put a \ in front of it!
if debug_logging:
print(f"EXPERT: If rule '{expression}' satisfied', run '{notebook}'.")
if re.match(expression, line, re.DOTALL):
if debug_logging:
print("EXPERT: MATCH: name = value: '{0}' = '{1}' matched expression '{2}', therefore HINT '{4}'".format(output_type_name, output_type_value, expression, notebook))
match_found = True
display(Markdown(f'HINT: Use [{notebook}]({notebook}) to resolve this issue.'))
```
### Install Kubernetes CLI
To get the latest version number for `kubectl` for Windows, open this
file:
- https://storage.googleapis.com/kubernetes-release/release/stable.txt
NOTE: For Windows, `kubectl.exe` is installed in the folder containing
the `python.exe` (`sys.executable`), which will be in the path for
notebooks run in ADS.
```
import os
import sys
import platform
from pathlib import Path
if platform.system() == "Darwin":
run('brew update')
run('brew install kubernetes-cli')
elif platform.system() == "Windows":
path = Path(sys.executable)
cwd = os.getcwd()
os.chdir(path.parent)
run('curl -L https://storage.googleapis.com/kubernetes-release/release/v1.17.0/bin/windows/amd64/kubectl.exe -o kubectl.exe')
os.chdir(cwd)
elif platform.system() == "Linux":
run('sudo apt-get update')
run('sudo apt-get install -y kubectl')
else:
raise SystemExit(f"Platform '{platform.system()}' is not recognized, must be 'Darwin', 'Windows' or 'Linux'")
print('Notebook execution complete.')
```
| github_jupyter |
```
"""
A randomly connected network learning a sequence
This example contains a reservoir network of 500 neurons.
400 neurons are excitatory and 100 neurons are inhibitory.
The weights are initialized randomly, based on a log-normal distribution.
The network activity is stimulated with three different inputs (A, B, C).
The inputs are given in i a row (A -> B -> C -> A -> ...)
The experiment is defined in 'pelenet/experiments/sequence.py' file.
A log file, parameters, and plot figures are stored in the 'log' folder for every run of the simulation.
NOTE: The main README file contains some more information about the structure of pelenet
"""
# Load pelenet modules
from pelenet.utils import Utils
from pelenet.experiments.sequence import SequenceExperiment
# Official modules
import numpy as np
import matplotlib.pyplot as plt
# Overwrite default parameters (pelenet/parameters/ and pelenet/experiments/sequence.py)
parameters = {
# Experiment
'seed': 1, # Random seed
'trials': 10, # Number of trials
'stepsPerTrial': 60, # Number of simulation steps for every trial
# Neurons
'refractoryDelay': 2, # Refactory period
'voltageTau': 100, # Voltage time constant
'currentTau': 5, # Current time constant
'thresholdMant': 1200, # Spiking threshold for membrane potential
# Network
'reservoirExSize': 400, # Number of excitatory neurons
'reservoirConnPerNeuron': 35, # Number of connections per neuron
'isLearningRule': True, # Apply a learning rule
'learningRule': '2^-2*x1*y0 - 2^-2*y1*x0 + 2^-4*x1*y1*y0 - 2^-3*y0*w*w', # Defines the learning rule
# Input
'inputIsSequence': True, # Activates sequence input
'inputSequenceSize': 3, # Number of input clusters in sequence
'inputSteps': 20, # Number of steps the trace input should drive the network
'inputGenSpikeProb': 0.8, # Probability of spike for the generator
'inputNumTargetNeurons': 40, # Number of neurons activated by the input
# Probes
'isExSpikeProbe': True, # Probe excitatory spikes
'isInSpikeProbe': True, # Probe inhibitory spikes
'isWeightProbe': True # Probe weight matrix at the end of the simulation
}
# Initilizes the experiment, also initializes the log
# Creating a new object results in a new log entry in the 'log' folder
# The name is optional, it is extended to the folder in the log directory
exp = SequenceExperiment(name='random-network-sequence-learning', parameters=parameters)
# Instantiate the utils singleton
utils = Utils.instance()
# Build the network, in this function the weight matrix, inputs, probes, etc. are defined and created
exp.build()
# Run the network simulation, afterwards the probes are postprocessed to nice arrays
exp.run()
# Weight matrix before learning (randomly initialized)
exp.net.plot.initialExWeightMatrix()
# Plot distribution of weights
exp.net.plot.initialExWeightDistribution(figsize=(12,3))
# Plot spike trains of the excitatory (red) and inhibitory (blue) neurons
exp.net.plot.reservoirSpikeTrain(figsize=(12,6), to=600)
# Weight matrix after learning
exp.net.plot.trainedExWeightMatrix()
# Sorted weight matrix after learning
supportMask = utils.getSupportWeightsMask(exp.net.trainedWeightsExex)
exp.net.plot.weightsSortedBySupport(supportMask)
```
| github_jupyter |
# Basics
```
print("Hello World!")
# This is comment!
bread=10
print(bread)
bread=input()
bread
43+5
'43'+5
```
**Find out the reason behind the above error.**
**Tip**: Copy the error and search in [Google](https://www.google.com/).
```
8
8+3
```
### Data Types
Integers: -2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers: -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25
Strings: 'a', 'aa', 'aaa', 'Hello!', '11 cats'
**Math Operations**
```
#Addition
2+3
#Subtraction
8-3
#Multiplication
2*4
#Division
42/10
# Exponent
2**4
#Modulus/Remainder
42%10
#Floored Quotient
42//10
```
**Note**: The precedence rule is BODMAS.
The ** operator is evaluated first; the *, /, //, and % operators are evaluated next, from left to right; and the + and - operators are evaluated last (also from left to right). You can use parentheses to override the usual precedence if you need to.
```
2 + 3 * 6
(2 + 3) * 6
48565878 * 578453
2 ** 8
23 / 7
23 // 7
23 % 7
#extra spaces? no problem
#python is chill :P
2 + 2
(5 - 1) * ((7 + 1) / (3 - 1))
```
#### Explanation

```
5 +
42 + 5 + * 2
```
The operations applicable for integers are also applicable for floating numbers too.
```
bread=10
bread
print(bread)
butter=3
bread+butter
print(bread+butter)
bread=bread+2
bread
bread++
```
**Note**: Coding in python is entirely different from c/cpp.
### Strings
```
msg='Hello'
msg
print(msg)
msg='Goodbye'
print(msg)
len(msg)
print(len(msg))
msg+1
msg+'1'
msg+str(1)
```
### Variable Names
**Valid** ✔️
balance
currentBalance
current_balance
_spam
SPAM
account4
----
**Invalid** ❌
'hello' (special characters like ' are not allowed)
current-balance (hyphens are not allowed)
4account (can’t begin with a number)
42 (can’t begin with a number)
current balance (spaces are not allowed)
total_$um (special characters like $ are not allowed)
```
#INPUT: Hi! :)
msg=input()
print(msg)
print(type(msg))
#INPUT: 12
msg=input()
print(msg)
print(type(msg))
#integer input
#INPUT : 12
msg=int(input())
print(msg)
print(type(msg))
#change the datatype
msg=str(msg)
print(msg)
print(type(msg))
print(int(msg)+1)
print(float(msg)+1)
print(int(7.7))
print(int(7.7) + 1)
```
Please understand this small program
```
print('Hello world!')
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
```
## Task 1
Write a program for polling booth. It should ask a name, his age and ask for vote (NDA/UPA).
# Flow Control
```
print(True, False)
print(1,0)
```
### Operators
```
#equal to
2==3
#not equal to
2!=3
#greater than
2>3
#less than
2<3
#less/greater than equal to
print(2>=3)
print(2<=3)
1==True
print('hello' == 'hello')
print('hello' == 'Hello')
True!=False
42==42.0
42=='42'
bread=21
bread>10
```
### Binary and Boolean Operations
```
True and True
False or False
not False
```
### Conditional Statements
```
if(4<5):
print("Yo!")
bread=int(input())
if(bread>10):
print("I have 10+ bread")
elif(bread==10):
print("I have exactly 10 bread")
else:
print("I have less than 10 bread")
if(True):
print("This is how you overide a conditional statement.")
if(False):
print("This will not print anything.")
if(input()):
print("This will print anything.")
```
You may be wondering why the above code worked. It worked because `input()` always take the input as *string* format not *boolen* format.
You can convert it into *boolean* by modifying it as `bool(input())`
```
bread=12
if(bread):
print("Every value other than 0 is considered as True")
bread=0
if(bread):
print("I told you already. :P")
```
## Taks 2
Implement this following flowchart
Take the initial values as
```python
name='Dracula'
age=4000
```

### Loops
### `while`
```
bread=0
while(bread<5):
print("need more bread")
bread=bread+1
"""
while True:
print("This is an infinite loop!!")
"""
```
Please have a look at the below code and understand it.
```
name = ''
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')
```
The above code will ask your input again and again until you give `your name` as input. You can build infinite loops accordingly.
The below code is a re-written version of the above. You can control infinite loops with valid `break` statements.
```
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
```
The keyword `continue` skips all the statements which are below itself. Look at the following
```
bread=0
while(bread<5):
print("bread added")
bread=bread+1
if(bread<3):
print("I am hungry.")
continue
print("I need more bread.")
```
### `for`
```
for i in range(3):
print("I need "+str(i)+" bread.")
#sum of n natural numbers program
total=0
n=int(input("Enter the n: "))
for i in range(n+1):
total=total+i
print(total)
```
**Note**: You can actually use a `while` loop to do the same thing as a `for` loop; `for` loops are just more concise.
`starting`, `stopping` and `stepping` arguments in `for` loop
```
for i in range(0,10):
print(i)
for i in range(0,10,3):
print(i)
```
## Task 3
Write a program for polling booth. It should ask a name, his age and ask for vote (NDA/UPA/Others). It should verify your age too. You need to ask for vote untill you see no voters left. Have seperate counters for the parties and increase the counter accordingly.
# Importing Modules
Python comes with many set of modules which can be used. Each module is a Python program that contains a related group of functions that can be embedded in your programs. For example, the math module has mathematics-related functions, the random module has random number–related functions, and so on.
Before you can use the functions in a module, you must import the module with an import statement.
```
#importing a module normally
import random
for i in range(5):
print(random.randint(1, 10))
#importing a module using an object
import random as rd
for i in range(5):
print(rd.randint(1, 10))
#importing one function from that module
#here, other functions of that module doesn't work
from random import randint
for i in range(5):
print(randint(1, 10))
#importing one function using an object
from random import randint as ri
for i in range(5):
print(ri(1, 10))
#importing all functions from that module
from random import *
for i in range(5):
print(randint(1, 10))
```
# Functions
```
def getBread():
print("bread!")
print("bread!!!")
getBread()
getBread()
getBread()
def getBread(number):
print("I want "+str(number)+" bread.")
getBread(3)
getBread(5)
getBread(8)
getBread()
```
**Error**: python is not like C/C++. You can define only one funtion with one name. You cannot differentiate with arguments.
```
def makeItEven(n):
return n*2
result=makeItEven(3)
print(result)
result=makeItEven(2)
print(result)
def makeItEven(n):
return n*2
print(makeItEven(3))
print(makeItEven(2))
```
`None` represents absence of any value.
```
def getNothing():
return
getNothing()
print(getNothing())
def getNone():
return None
getNone()
print(getNone())
```
**Fact**: Behind the scenes, Python adds return `None` to the end of any function definition with no return statement. This is similar to how a `while` or `for` loop implicitly ends with a continue statement.
### Scope (Global and Local)
```
def getDosa():
dosa=8
getDosa()
print(dosa)
```
**Error**: The above error is because the variable `dosa` is defined only fro the `getDosa` function and out of the defined scope, a variable cannot be used.
```
dosa=3
def getDosa():
print("dosa=",dosa)
getDosa()
print(dosa)
dosa=3
def getDosa():
dosa=8
print("dosa=",dosa)
getDosa()
print("dosa=",dosa)
def getDosa():
global dosa
dosa=8
print("dosa=",dosa)
getDosa()
print("dosa=",dosa)
def getDosa():
print("dosa=",dosa)
dosa=8 #1
dosa=3 #2
getDosa()
print("dosa=",dosa)
```
**Error**: This error happens because Python sees that there is an assignment statement for `dosa` in the `getDosa` function #1 and therefore considers `dosa` to be local. But because `print("dosa=",dosa)` is executed before `dosa` is assigned anything, the local variable `dosa` doesn’t exist. Python will not fall back to using the global `dosa` variable #2.
### Error Handling
```
def divideBy(n):
return 4/n
print(divideBy(4))
print(divideBy(1))
print(divideBy(0))
```
**Note**: The division by zero is not possible, so it raised error. Instead of stopping the program abruptly, we can handle the error (using `try-except`) such that an error message is displayed and the program finished the execution without any interruption.
```
def divideBy(n):
try:
return 4/n
except ZeroDivisionError:
print("Invalid argument.")
print(divideBy(4))
print(divideBy(1))
print(divideBy(0))
def divideBy(n):
return 4/n
try:
print(divideBy(4))
print(divideBy(1))
print(divideBy(0))
except ZeroDivisionError:
print("Invalid argument.")
```
## Task-4
Implement the following scenario. It is *Guess the number* game. (need to be be the exact similar)
```
I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess.
15
Your guess is too low.
Take a guess.
17
Your guess is too high.
Take a guess.
16
Good job! You guessed my number in 4 guesses!
```
## Task-5
### The Collatz Sequence
Write a function named `collatz()` that has one parameter named number. If number is even, then collatz() should print `number // 2` and return this value. If number is odd, then collatz() should print and `return 3 * number + 1`.
*Hint*: An integer number is even if `number % 2 == 0`, and it’s odd if `number % 2 == 1`.
## Task-6
### The Input Sequence
Add `try-except` statements to the previous project to detect whether the user types in a noninteger string. Normally, the `int()` function will raise a `ValueError` error if it is passed a noninteger string, as in `int('puppy')`. In the `except` clause, print a message to the user saying they must enter an integer.
| github_jupyter |
# Google form analysis visualizations
## Table of Contents
['Google form analysis' functions checks](#funcchecks)
['Google form analysis' functions tinkering](#functinkering)
```
%run "../Functions/1. Google form analysis.ipynb"
```
## 'Google form analysis' functions checks
<a id=funcchecks />
## 'Google form analysis' functions tinkering
<a id=functinkering />
```
binarizedAnswers = plotBasicStats(getSurveysOfBiologists(gform), 'non biologists', includeUndefined = True)
gform.loc[:, [localplayerguidkey, 'Temporality']].groupby('Temporality').count()
#sample = gform.copy()
samples = [
[gform.copy(), 'complete set'],
[gform[gform['Language'] == 'en'], 'English'],
[gform[gform['Language'] == 'fr'], 'French'],
[gform[gform['What is your gender?'] == 'Female'], 'female'],
[gform[gform['What is your gender?'] == 'Male'], 'male'],
[getSurveysOfUsersWhoAnsweredBoth(gform), 'answered both'],
[getSurveysOfUsersWhoAnsweredBoth(gform[gform['Language'] == 'en']), 'answered both, en'],
[getSurveysOfUsersWhoAnsweredBoth(gform[gform['Language'] == 'fr']), 'answered both, fr'],
[getSurveysOfUsersWhoAnsweredBoth(gform[gform['What is your gender?'] == 'Female']), 'answered both, female'],
[getSurveysOfUsersWhoAnsweredBoth(gform[gform['What is your gender?'] == 'Male']), 'answered both, male'],
]
_progress = FloatProgress(min=0, max=len(samples))
display(_progress)
includeAll = False
includeBefore = True
includeAfter = True
includeUndefined = False
includeProgress = True
includeRelativeProgress = False
for sample, title in samples:
## basic stats:
### mean score
### median score
### std
## sample can be: all, those who answered both before and after,
## those who played between date1 and date2, ...
#def plotBasicStats(sample, title, includeAll, includeBefore, includeAfter, includeUndefined, includeProgress, includeRelativeProgress):
stepsPerInclude = 2
includeCount = np.sum([includeAll, includeBefore, includeAfter, includeUndefined, includeProgress])
stepsCount = stepsPerInclude*includeCount + 3
#print("stepsPerInclude=" + str(stepsPerInclude))
#print("includeCount=" + str(includeCount))
#print("stepsCount=" + str(stepsCount))
__progress = FloatProgress(min=0, max=stepsCount)
display(__progress)
sampleBefore = sample[sample['Temporality'] == 'before']
sampleAfter = sample[sample['Temporality'] == 'after']
sampleUndefined = sample[sample['Temporality'] == 'undefined']
#uniqueBefore = sampleBefore[localplayerguidkey]
#uniqueAfter =
#uniqueUndefined =
scientificQuestions = correctAnswers.copy()
allQuestions = correctAnswers + demographicAnswers
categories = ['all', 'before', 'after', 'undefined', 'progress', 'rel. progress']
data = {}
sciBinarized = pd.DataFrame()
allBinarized = pd.DataFrame()
scoresAll = pd.DataFrame()
sciBinarizedBefore = pd.DataFrame()
allBinarizedBefore = pd.DataFrame()
scoresBefore = pd.DataFrame()
sciBinarizedAfter = pd.DataFrame()
allBinarizedAfter = pd.DataFrame()
scoresAfter = pd.DataFrame()
sciBinarizedUndefined = pd.DataFrame()
allBinarizedUndefined = pd.DataFrame()
scoresUndefined = pd.DataFrame()
scoresProgress = pd.DataFrame()
## basic stats:
### mean score
### median score
### std
if includeAll:
sciBinarized = getAllBinarized( _source = scientificQuestions, _form = sample)
__progress.value += 1
allBinarized = getAllBinarized( _source = allQuestions, _form = sample)
__progress.value += 1
scoresAll = pd.Series(np.dot(sciBinarized, np.ones(sciBinarized.shape[1])))
data[categories[0]] = createStatSet(scoresAll, sample[localplayerguidkey])
if includeBefore or includeProgress:
sciBinarizedBefore = getAllBinarized( _source = scientificQuestions, _form = sampleBefore)
__progress.value += 1
allBinarizedBefore = getAllBinarized( _source = allQuestions, _form = sampleBefore)
__progress.value += 1
scoresBefore = pd.Series(np.dot(sciBinarizedBefore, np.ones(sciBinarizedBefore.shape[1])))
temporaryStatSetBefore = createStatSet(scoresBefore, sampleBefore[localplayerguidkey])
if includeBefore:
data[categories[1]] = temporaryStatSetBefore
if includeAfter or includeProgress:
sciBinarizedAfter = getAllBinarized( _source = scientificQuestions, _form = sampleAfter)
__progress.value += 1
allBinarizedAfter = getAllBinarized( _source = allQuestions, _form = sampleAfter)
__progress.value += 1
scoresAfter = pd.Series(np.dot(sciBinarizedAfter, np.ones(sciBinarizedAfter.shape[1])))
temporaryStatSetAfter = createStatSet(scoresAfter, sampleAfter[localplayerguidkey])
if includeAfter:
data[categories[2]] = temporaryStatSetAfter
if includeUndefined:
sciBinarizedUndefined = getAllBinarized( _source = scientificQuestions, _form = sampleUndefined)
__progress.value += 1
allBinarizedUndefined = getAllBinarized( _source = allQuestions, _form = sampleUndefined)
__progress.value += 1
scoresUndefined = pd.Series(np.dot(sciBinarizedUndefined, np.ones(sciBinarizedUndefined.shape[1])))
data[categories[3]] = createStatSet(scoresUndefined, sampleUndefined[localplayerguidkey])
if includeProgress:
data[categories[4]] = {
'count' : min(temporaryStatSetAfter['count'], temporaryStatSetBefore['count']),
'unique' : min(temporaryStatSetAfter['unique'], temporaryStatSetBefore['unique']),
'median' : temporaryStatSetAfter['median']-temporaryStatSetBefore['median'],
'mean' : temporaryStatSetAfter['mean']-temporaryStatSetBefore['mean'],
'std' : temporaryStatSetAfter['std']-temporaryStatSetBefore['std'],
}
__progress.value += 2
result = pd.DataFrame(data)
__progress.value += 1
print(title)
print(result)
if (includeBefore and includeAfter) or includeProgress:
if (len(scoresBefore) > 2 and len(scoresAfter) > 2):
ttest = ttest_ind(scoresBefore, scoresAfter)
print("t test: statistic=" + repr(ttest.statistic) + " pvalue=" + repr(ttest.pvalue))
print()
## percentage correct
### percentage correct - max 5 columns
percentagePerQuestionAll = pd.DataFrame()
percentagePerQuestionBefore = pd.DataFrame()
percentagePerQuestionAfter = pd.DataFrame()
percentagePerQuestionUndefined = pd.DataFrame()
percentagePerQuestionProgress = pd.DataFrame()
tables = []
if includeAll:
percentagePerQuestionAll = getPercentagePerQuestion(allBinarized)
tables.append([percentagePerQuestionAll, categories[0]])
if includeBefore or includeProgress:
percentagePerQuestionBefore = getPercentagePerQuestion(allBinarizedBefore)
if includeBefore:
tables.append([percentagePerQuestionBefore, categories[1]])
if includeAfter or includeProgress:
percentagePerQuestionAfter = getPercentagePerQuestion(allBinarizedAfter)
if includeAfter:
tables.append([percentagePerQuestionAfter, categories[2]])
if includeUndefined:
percentagePerQuestionUndefined = getPercentagePerQuestion(allBinarizedUndefined)
tables.append([percentagePerQuestionUndefined, categories[3]])
if includeProgress or includeRelativeProgress:
percentagePerQuestionProgress = percentagePerQuestionAfter - percentagePerQuestionBefore
if includeProgress:
tables.append([percentagePerQuestionProgress, categories[4]])
if includeRelativeProgress:
# use temporaryStatSetAfter['count'], temporaryStatSetBefore['count']?
percentagePerQuestionProgress2 = percentagePerQuestionProgress.copy()
for index in range(0,len(percentagePerQuestionProgress.index)):
if (0 == percentagePerQuestionBefore.iloc[index,0]):
percentagePerQuestionProgress2.iloc[index,0] = 0
else:
percentagePerQuestionProgress2.iloc[index,0] = \
percentagePerQuestionProgress.iloc[index,0]/percentagePerQuestionBefore.iloc[index,0]
tables.append([percentagePerQuestionProgress2, categories[5]])
__progress.value += 1
graphTitle = '% correct: '
toConcat = []
for table,category in tables:
concat = (len(table.values) > 0)
for elt in table.iloc[:,0].values:
if np.isnan(elt):
concat = False
break
if(concat):
graphTitle = graphTitle + category + ' '
toConcat.append(table)
if (len(toConcat) > 0):
percentagePerQuestionConcatenated = pd.concat(
toConcat
, axis=1)
if(len(title) > 0):
graphTitle = graphTitle + ' - ' + title
_fig = plt.figure(figsize=(20,20))
_ax1 = plt.subplot(111)
_ax1.set_title(graphTitle)
sns.heatmap(percentagePerQuestionConcatenated.round().astype(int),ax=_ax1,cmap=plt.cm.jet,square=True,annot=True,fmt='d')
__progress.value += 1
### percentage cross correct
### percentage cross correct, conditionnally
if(__progress.value != stepsCount):
print("__progress.value=" + str(__progress.value) + " != stepsCount=" + str(stepsCount))
_progress.value += 1
if(_progress.value != len(samples)):
print("__progress.value=" + str(__progress.value) + " != len(samples)=" + str(len(samples)))
# sciBinarized, sciBinarizedBefore, sciBinarizedAfter, sciBinarizedUndefined, \
# allBinarized, allBinarizedBefore, allBinarizedAfter, allBinarizedUndefined
ttest = ttest_ind(scoresBefore, scoresAfter)
type(scoresBefore), len(scoresBefore),\
type(scoresAfter), len(scoresAfter),\
ttest
type(tables)
sciBinarized = getAllBinarized( _source = scientificQuestions, _form = sample)
series = pd.Series(np.dot(sciBinarized, np.ones(sciBinarized.shape[1])))
#ids = pd.Series()
ids = sample[localplayerguidkey]
#def createStatSet(series, ids):
if(0 == len(ids)):
ids = series.index
result = {
'count' : len(ids),
'unique' : len(ids.unique()),
'median' : series.median(),
'mean' : series.mean(),
'std' : series.std()}
result
## percentage correct
### percentage correct - 3 columns
### percentage cross correct
### percentage cross correct, conditionnally
#_binarized = allBinarized
#_binarized = allBinarizedUndefined
_binarized = allBinarizedBefore
#def getPercentagePerQuestion(_binarized):
totalPerQuestionDF = pd.DataFrame(data=np.dot(np.ones(_binarized.shape[0]), _binarized), index=_binarized.columns)
percentagePerQuestion = totalPerQuestionDF*100 / _binarized.shape[0]
percentagePerQuestion
#totalPerQuestion = np.dot(np.ones(allSciBinarized.shape[0]), allSciBinarized)
#totalPerQuestion.shape
totalPerQuestionSci = np.dot(np.ones(sciBinarized.shape[0]), sciBinarized)
totalPerQuestionAll = np.dot(np.ones(allBinarized.shape[0]), allBinarized)
percentagePerQuestionAll = getPercentagePerQuestion(allBinarized)
percentagePerQuestionBefore = getPercentagePerQuestion(allBinarizedBefore)
percentagePerQuestionAfter = getPercentagePerQuestion(allBinarizedAfter)
percentagePerQuestionUndefined = getPercentagePerQuestion(allBinarizedUndefined)
percentagePerQuestionConcatenated = pd.concat(
[
percentagePerQuestionAll,
percentagePerQuestionBefore,
percentagePerQuestionAfter,
percentagePerQuestionUndefined,
]
, axis=1)
_fig = plt.figure(figsize=(20,20))
_ax1 = plt.subplot(111)
_ax1.set_title('percentage correct per question: all, before, after, undefined')
sns.heatmap(percentagePerQuestionConcatenated.round().astype(int),ax=_ax1,cmap=plt.cm.jet,square=True,annot=True,fmt='d')
samples = [gform, gform[gform['Language'] == 'en'], gform[gform['Language'] == 'fr'],
getSurveysOfUsersWhoAnsweredBoth(gform),
getSurveysOfUsersWhoAnsweredBoth(gform[gform['Language'] == 'en']),
getSurveysOfUsersWhoAnsweredBoth(gform[gform['Language'] == 'fr'])]
for sample in samples:
sciBinarized, sciBinarizedBefore, sciBinarizedAfter, sciBinarizedUndefined, \
allBinarized, allBinarizedBefore, allBinarizedAfter, allBinarizedUndefined = plotBasicStats(sample)
```
### abandoned algorithms
```
#totalPerQuestion = np.dot(np.ones(sciBinarized.shape[0]), sciBinarized)
#totalPerQuestion.shape
totalPerQuestionSci = np.dot(np.ones(sciBinarized.shape[0]), sciBinarized)
totalPerQuestionAll = np.dot(np.ones(allBinarized.shape[0]), allBinarized)
totalPerQuestionDFAll = pd.DataFrame(data=np.dot(np.ones(allBinarized.shape[0]), allBinarized), index=allBinarized.columns)
percentagePerQuestionAll = totalPerQuestionDFAll*100 / allBinarized.shape[0]
#totalPerQuestionDF
#percentagePerQuestion
#before
totalPerQuestionDFBefore = pd.DataFrame(
data=np.dot(np.ones(allBinarizedBefore.shape[0]), allBinarizedBefore), index=allBinarizedBefore.columns
)
percentagePerQuestionBefore = totalPerQuestionDFBefore*100 / allBinarizedBefore.shape[0]
#after
totalPerQuestionDFAfter = pd.DataFrame(
data=np.dot(np.ones(allBinarizedAfter.shape[0]), allBinarizedAfter), index=allBinarizedAfter.columns
)
percentagePerQuestionAfter = totalPerQuestionDFAfter*100 / allBinarizedAfter.shape[0]
_fig = plt.figure(figsize=(20,20))
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)
ax2.get_yaxis().set_visible(False)
ax3.get_yaxis().set_visible(False)
sns.heatmap(percentagePerQuestionAll.round().astype(int),ax=ax1,cmap=plt.cm.jet,square=True,annot=True,fmt='d', cbar=False)
sns.heatmap(percentagePerQuestionBefore.round().astype(int),ax=ax2,cmap=plt.cm.jet,square=True,annot=True,fmt='d', cbar=False)
sns.heatmap(percentagePerQuestionAfter.round().astype(int),ax=ax3,cmap=plt.cm.jet,square=True,annot=True,fmt='d', cbar=True)
ax1.set_title('percentage correct per question - all')
ax2.set_title('percentage correct per question - before')
ax3.set_title('percentage correct per question - after')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
_fig.tight_layout()
_fig = plt.figure(figsize=(20,20))
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)
ax2.get_yaxis().set_visible(False)
ax3.get_yaxis().set_visible(False)
sns.heatmap(percentagePerQuestionAll.round().astype(int),ax=ax1,cmap=plt.cm.jet,square=True,annot=True,fmt='d', cbar=False)
sns.heatmap(percentagePerQuestionBefore.round().astype(int),ax=ax2,cmap=plt.cm.jet,square=True,annot=True,fmt='d', cbar=False)
sns.heatmap(percentagePerQuestionAfter.round().astype(int),ax=ax3,cmap=plt.cm.jet,square=True,annot=True,fmt='d', cbar=True)
ax1.set_title('percentage correct per question - all')
ax2.set_title('percentage correct per question - before')
ax3.set_title('percentage correct per question - after')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
_fig.tight_layout()
_fig = plt.figure(figsize=(20,20))
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)
ax2.get_yaxis().set_visible(False)
ax3.get_yaxis().set_visible(False)
sns.heatmap(percentagePerQuestionAll.round().astype(int),ax=ax1,cmap=plt.cm.jet,square=True,annot=True,fmt='d', cbar=False)
sns.heatmap(percentagePerQuestionBefore.round().astype(int),ax=ax2,cmap=plt.cm.jet,square=True,annot=True,fmt='d', cbar=False)
sns.heatmap(percentagePerQuestionAfter.round().astype(int),ax=ax3,cmap=plt.cm.jet,square=True,annot=True,fmt='d', cbar=True)
ax1.set_title('percentage correct per question - all')
ax2.set_title('percentage correct per question - before')
ax3.set_title('percentage correct per question - after')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
_fig.tight_layout()
percentagePerQuestionConcatenated = pd.concat([
percentagePerQuestionAll,
percentagePerQuestionBefore,
percentagePerQuestionAfter]
, axis=1)
_fig = plt.figure(figsize=(20,20))
_ax1 = plt.subplot(111)
_ax1.set_title('percentage correct per question: all, before, after')
sns.heatmap(percentagePerQuestionConcatenated.round().astype(int),ax=_ax1,cmap=plt.cm.jet,square=True,annot=True,fmt='d')
```
### sample getters tinkering
```
##### getRMAfter / Before tinkering
#def getRMAfters(sample):
afters = sample[sample['Temporality'] == 'after']
#def getRMBefores(sample):
befores = sample[sample['Temporality'] == 'before']
QPlayed1 = 'Have you ever played an older version of Hero.Coli before?'
QPlayed2 = 'Have you played the current version of Hero.Coli?'
QPlayed3 = 'Have you played the arcade cabinet version of Hero.Coli?'
QPlayed4 = 'Have you played the Android version of Hero.Coli?'
```
#### set operators
```
# equality tests
#(sample1.columns == sample2.columns).all()
#sample1.columns.duplicated().any() or sample2.columns.duplicated().any()
#pd.concat([sample1, sample2], axis=1).columns.duplicated().any()
```
##### getUnionQuestionnaires tinkering
```
sample1 = befores
sample2 = afters
#def getUnionQuestionnaires(sample1, sample2):
if (not (sample1.columns == sample2.columns).all()):
print("warning: parameter columns are not the same")
result = pd.concat([sample1, sample2]).drop_duplicates()
```
##### getIntersectionQuestionnaires tinkering
```
sample1 = befores[:15]
sample2 = befores[10:]
#def getIntersectionQuestionnaires(sample1, sample2):
if (not (sample1.columns == sample2.columns).all()):
print("warning: parameter columns are not the same")
result = pd.merge(sample1, sample2, how = 'inner').drop_duplicates()
```
##### getIntersectionUsersSurveys tinkering
```
sample1 = befores
sample2 = afters
# get sample1 and sample2 rows where users are common to sample1 and sample2
#def getIntersectionUsersSurveys(sample1, sample2):
result1 = sample1[sample1[localplayerguidkey].isin(sample2[localplayerguidkey])]
result2 = sample2[sample2[localplayerguidkey].isin(sample1[localplayerguidkey])]
result = getUnionQuestionnaires(result1,result2)
len(sample1), len(sample2), len(result)
```
##### getGFormBefores tinkering
```
sample = gform
# returns users who declared that they have never played the game, whatever platform
# previousPlayPositives is defined in '../Static data/English localization.ipynb'
#def getGFormBefores(sample):
befores = sample[
~sample[QPlayed1].isin(previousPlayPositives)
& ~sample[QPlayed2].isin(previousPlayPositives)
& ~sample[QPlayed3].isin(previousPlayPositives)
& ~sample[QPlayed4].isin(previousPlayPositives)
]
len(befores)
```
##### getGFormAfters tinkering
```
sample = gform
# returns users who declared that they have already played the game, whatever platform
# previousPlayPositives is defined in '../Static data/English localization.ipynb'
#def getGFormAfters(sample):
afters = sample[
sample[QPlayed1].isin(previousPlayPositives)
| sample[QPlayed2].isin(previousPlayPositives)
| sample[QPlayed3].isin(previousPlayPositives)
| sample[QPlayed4].isin(previousPlayPositives)
]
len(afters)
```
##### getGFormTemporality tinkering
```
_GFUserId = getSurveysOfBiologists(gform)[localplayerguidkey].iloc[3]
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
sample = gform
answerTemporalities[1]
#while result != 'after':
_GFUserId = getRandomGFormGUID()
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
# returns an element of answerTemporalities
# previousPlayPositives is defined in '../Static data/English localization.ipynb'
#def getGFormRowGFormTemporality(_gformRow):
result = answerTemporalities[2]
if (_gformRow[QPlayed1] in previousPlayPositives)\
or (_gformRow[QPlayed2] in previousPlayPositives)\
or (_gformRow[QPlayed3] in previousPlayPositives)\
or (_gformRow[QPlayed4] in previousPlayPositives):
result = answerTemporalities[1]
else:
result = answerTemporalities[0]
result
```
#### getSurveysOfUsersWhoAnsweredBoth tinkering
```
sample = gform
gfMode = True
rmMode = False
#def getSurveysOfUsersWhoAnsweredBoth(sample, gfMode = True, rmMode = False):
befores = sample
afters = sample
if gfMode:
befores = getGFormBefores(befores)
afters = getGFormAfters(afters)
if rmMode:
befores = getRMBefores(befores)
afters = getRMAfters(afters)
result = getIntersectionUsersSurveys(befores, afters)
((len(getGFormBefores(sample)),\
len(getRMBefores(sample)),\
len(befores)),\
(len(getGFormAfters(sample)),\
len(getRMAfters(sample)),\
len(afters)),\
len(result)),\
\
((getUniqueUserCount(getGFormBefores(sample)),\
getUniqueUserCount(getRMBefores(sample)),\
getUniqueUserCount(befores)),\
(getUniqueUserCount(getGFormAfters(sample)),\
getUniqueUserCount(getRMAfters(sample)),\
getUniqueUserCount(afters)),\
getUniqueUserCount(result))
len(getSurveysOfUsersWhoAnsweredBoth(gform, gfMode = True, rmMode = True)[localplayerguidkey])
```
#### getSurveysThatAnswered tinkering
```
sample = gform
#_GFUserId = getSurveysOfBiologists(gform)[localplayerguidkey].iloc[1]
#sample = gform[gform[localplayerguidkey] == _GFUserId]
hardPolicy = True
questionsAndPositiveAnswers = [[Q6BioEdu, biologyStudyPositives],
[Q8SynBio, yesNoIdontknowPositives],
[Q9BioBricks, yesNoIdontknowPositives]]
#def getSurveysThatAnswered(sample, questionsAndPositiveAnswers, hardPolicy = True):
filterSeries = []
if hardPolicy:
filterSeries = pd.Series(True, sample.index)
for question, positiveAnswers in questionsAndPositiveAnswers:
filterSeries = filterSeries & (sample[question].isin(positiveAnswers))
else:
filterSeries = pd.Series(False, sample.index)
for question, positiveAnswers in questionsAndPositiveAnswers:
filterSeries = filterSeries | (sample[question].isin(positiveAnswers))
result = sample[filterSeries]
```
#### getSurveysOfBiologists tinkering
```
sample = gform
hardPolicy = True
#def getSurveysOfBiologists(sample, hardPolicy = True):
Q6BioEdu = 'How long have you studied biology?' #biologyStudyPositives
#irrelevant QInterest 'Are you interested in biology?' #biologyInterestPositives
Q8SynBio = 'Before playing Hero.Coli, had you ever heard about synthetic biology?' #yesNoIdontknowPositives
Q9BioBricks = 'Before playing Hero.Coli, had you ever heard about BioBricks?' #yesNoIdontknowPositives
questionsAndPositiveAnswers = [[Q6BioEdu, biologyStudyPositives],
[Q8SynBio, yesNoIdontknowPositives],
[Q9BioBricks, yesNoIdontknowPositives]]
result = getSurveysThatAnswered(sample, questionsAndPositiveAnswers, hardPolicy)
print(len(result) > 0)
gform.index
len(result)
_GFUserId = getSurveysOfBiologists(gform)[localplayerguidkey].iloc[0]
sample = gform[gform[localplayerguidkey] == _GFUserId]
len(getSurveysOfBiologists(sample)) > 0
```
#### getSurveysOfGamers tinkering
```
sample = gform
hardPolicy = True
#def getSurveysOfGamers(sample, hardPolicy = True):
Q2Interest = 'Are you interested in video games?' #interestPositives
Q3Play = 'Do you play video games?' #frequencyPositives
questionsAndPositiveAnswers = [[Q2Interest, interestPositives], [Q3Play, frequencyPositives]]
result = getSurveysThatAnswered(sample, questionsAndPositiveAnswers, hardPolicy)
len(result)
type(filterSeries)
len(afters[afters[QPlayed1].isin(previousPlayPositives)
| afters[QPlayed2].isin(previousPlayPositives)
| afters[QPlayed3].isin(previousPlayPositives)
| afters[QPlayed4].isin(previousPlayPositives)
]),\
len(afters[afters[QPlayed1].isin(previousPlayPositives)]),\
len(afters[afters[QPlayed2].isin(previousPlayPositives)]),\
len(afters[afters[QPlayed3].isin(previousPlayPositives)]),\
len(afters[afters[QPlayed4].isin(previousPlayPositives)])
```
#### getSurveysWithMatchingAnswers tinkering
```
_GFUserId = getSurveysOfBiologists(gform)[localplayerguidkey].iloc[2]
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
sample = gform
sample = gform
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
hardPolicy = False
Q4 = 'How old are you?'
Q5 = 'What is your gender?'
Q2Interest = 'Are you interested in video games?'
Q3Play = 'Do you play video games?'
Q6BioEdu = 'How long have you studied biology?'
Q7BioInterest = 'Are you interested in biology?'
Q8SynBio = 'Before playing Hero.Coli, had you ever heard about synthetic biology?'
Q9BioBricks = 'Before playing Hero.Coli, had you ever heard about BioBricks?'
Q42 = 'Language'
strictList = [Q4, Q5]
extendedList = [Q2Interest, Q3Play, Q6BioEdu, Q8SynBio, Q9BioBricks, Q42]
#def getSurveysWithMatchingAnswers(sample, _gformRow, strictList, extendedList = [], hardPolicy = False):
questions = strictList
if (hardPolicy):
questions += extendedList
questionsAndPositiveAnswers = []
for q in questions:
questionsAndPositiveAnswers.append([q, [_gformRow[q]]])
getSurveysThatAnswered(sample, questionsAndPositiveAnswers, True)
```
#### getMatchingDemographics tinkering
```
sample = gform
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
hardPolicy = True
#def getMatchingDemographics(sample, _gformRow, hardPolicy = False):
# age and gender
Q4 = 'How old are you?'
Q5 = 'What is your gender?'
# interests, hobbies, and knowledge - evaluation may vary after playing
Q2Interest = 'Are you interested in video games?'
Q3Play = 'Do you play video games?'
Q6BioEdu = 'How long have you studied biology?'
Q7BioInterest = 'Are you interested in biology?'
Q8SynBio = 'Before playing Hero.Coli, had you ever heard about synthetic biology?'
Q9BioBricks = 'Before playing Hero.Coli, had you ever heard about BioBricks?'
# language may vary: players may have missed the opportunity to set it, or may want to try and change it
Q42 = 'Language'
getSurveysWithMatchingAnswers(
sample,
_gformRow, [Q4, Q5],
extendedList = [Q2Interest, Q3Play, Q6BioEdu, Q8SynBio, Q9BioBricks, Q42],
hardPolicy = hardPolicy
)
questionsAndPositiveAnswers
```
#### getGFormRowCorrection tinkering
```
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
_source = correctAnswers
#def getGFormRowCorrection( _gformRow, _source = correctAnswers):
result = _gformRow.copy()
if(len(_gformRow) == 0):
print("this gform row is empty")
else:
result = pd.Series(index = _gformRow.index, data = np.full(len(_gformRow), np.nan))
for question in result.index:
_correctAnswers = _source.loc[question]
if(len(_correctAnswers) > 0):
result.loc[question] = False
for _correctAnswer in _correctAnswers:
if str(_gformRow.loc[question]).startswith(str(_correctAnswer)):
result.loc[question] = True
break
result
```
#### getGFormRowScore tinkering
```
_gformRow = gform[gform[localplayerguidkey] == _GFUserId].iloc[0]
_source = correctAnswers
#def getGFormRowScore( _gformRow, _source = correctAnswers):
correction = getGFormRowCorrection( _gformRow, _source = _source)
_counts = correction.value_counts()
_thisScore = 0
if(True in _counts):
_thisScore = _counts[True]
_thisScore
```
#### getGFormDataPreview tinkering
```
_GFUserId = getSurveysOfBiologists(gform)[localplayerguidkey].iloc[2]
sample = gform
# for per-gform, manual analysis
#def getGFormDataPreview(_GFUserId, sample):
gforms = gform[gform[localplayerguidkey] == _GFUserId]
result = {}
for _ilocIndex in range(0, len(gforms)):
gformsIndex = gforms.index[_ilocIndex]
currentGForm = gforms.iloc[_ilocIndex]
subresult = {}
subresult['date'] = currentGForm['Timestamp']
subresult['temporality RM'] = currentGForm['Temporality']
subresult['temporality GF'] = getGFormRowGFormTemporality(currentGForm)
subresult['score'] = getGFormRowScore(currentGForm)
subresult['genderAge'] = [currentGForm['What is your gender?'], currentGForm['How old are you?']]
# search for other users with similar demographics
matchingDemographics = getMatchingDemographics(sample, currentGForm)
matchingDemographicsIds = []
#print(type(matchingDemographics))
#print(matchingDemographics.index)
for matchesIndex in matchingDemographics.index:
matchingDemographicsIds.append([matchesIndex, matchingDemographics.loc[matchesIndex, localplayerguidkey]])
subresult['demographic matches'] = matchingDemographicsIds
result['survey' + str(_ilocIndex)] = subresult
print(result)
for match in result['survey0']['demographic matches']:
print(match[0])
```
| github_jupyter |
```
from xml.etree import ElementTree
from xml.dom import minidom
from xml.etree.ElementTree import Element, SubElement, Comment, indent
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, encoding="ISO-8859-1")
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
import numpy as np
import os
valve_start = 1
hyb_start = 51
reg_start = 1
num_rounds = 14
data_type = 'U'
valve_ids = np.arange(valve_start, valve_start + num_rounds)
hyb_ids = np.arange(hyb_start, hyb_start + num_rounds)
reg_names = [f'{data_type}{_i}' for _i in np.arange(reg_start, reg_start + num_rounds)]
source_folder = r'D:\Pu\20220102-CTP11-1000_CTP12-DNA_from_1229'
#target_drive = r'\\KOLMOGOROV\Chromatin_NAS_4'
target_drive = r'\\10.245.74.158\Chromatin_NAS_1'
# imaging protocol
imaging_protocol = r'Zscan_750_647_561_s50_n250_10Hz'
# reference imaging protocol
add_ref_hyb = False
ref_imaging_protocol = r'Zscan_750_647_561_405_s50_n250_10Hz'
ref_hyb = 0
# bleach protocol
bleach = True
bleach_protocol = r'Bleach_750_647_s5'
cmd_seq = Element('command_sequence')
if add_ref_hyb:
# add hyb 0
# comments
comment = Comment(f"Hyb 0")
cmd_seq.append(comment)
# flow imaging buffer
imaging = SubElement(cmd_seq, 'valve_protocol')
imaging.text = f"Flow Imaging Buffer"
# change directory
change_dir = SubElement(cmd_seq, 'change_directory')
change_dir.text = os.path.join(source_folder, f"H0C1")
# wakeup
wakeup = SubElement(cmd_seq, 'wakeup')
wakeup.text = "5000"
# imaging loop
_im_p = ref_imaging_protocol
loop = SubElement(cmd_seq, 'loop', name='Position Loop Zscan', increment="name")
loop_item = SubElement(loop, 'item', name=_im_p)
loop_item.text = " "
# delay time
delay = SubElement(cmd_seq, 'delay')
delay.text = "2000"
# copy folder
copy_dir = SubElement(cmd_seq, 'copy_directory')
source_dir = SubElement(copy_dir, 'source_path')
source_dir.text = change_dir.text
target_dir = SubElement(copy_dir, 'target_path')
target_dir.text = os.path.join(target_drive,
os.path.basename(os.path.dirname(source_dir.text)),
os.path.basename(source_dir.text))
del_source = SubElement(copy_dir, 'delete_source')
del_source.text = "True"
for _i, (_vid, _hid, _rname) in enumerate(zip(valve_ids, hyb_ids, reg_names)):
# select protocol
_im_p = imaging_protocol
# TCEP
tcep = SubElement(cmd_seq, 'valve_protocol')
tcep.text = "Flow TCEP"
# wash tcep
tcep_wash = SubElement(cmd_seq, 'valve_protocol')
tcep_wash.text = "Flow Wash Buffer"
# comments
comment = Comment(f"Hyb {_hid} with {_vid} for {_rname}")
cmd_seq.append(comment)
# flow adaptor
adt = SubElement(cmd_seq, 'valve_protocol')
adt.text = f"Hybridize {_vid}"
if bleach:
# delay time
delay = SubElement(cmd_seq, 'delay')
delay.text = "3000"
# change directory
bleach_change_dir = SubElement(cmd_seq, 'change_directory')
bleach_change_dir.text = os.path.join(source_folder, f"Bleach")
# wakeup
bleach_wakeup = SubElement(cmd_seq, 'wakeup')
bleach_wakeup.text = "5000"
# imaging loop
bleach_loop = SubElement(cmd_seq, 'loop', name='Position Loop Zscan', increment="name")
bleach_loop_item = SubElement(bleach_loop, 'item', name=bleach_protocol)
bleach_loop_item.text = " "
# delay time
delay = SubElement(cmd_seq, 'delay')
delay.text = "3000"
else:
# delay time
adt_incubation = SubElement(cmd_seq, 'valve_protocol')
adt_incubation.text = f"Incubate 10min"
# wash
wash = SubElement(cmd_seq, 'valve_protocol')
wash.text = "Flow Wash Buffer"
# readouts
readouts = SubElement(cmd_seq, 'valve_protocol')
readouts.text = "Flow RNA common readouts"
# incubate readouts
readout_incubation = SubElement(cmd_seq, 'valve_protocol')
readout_incubation.text = f"Incubate 10min"
# wash readouts
readout_wash = SubElement(cmd_seq, 'valve_protocol')
readout_wash.text = f"Flow Wash Buffer"
# flow imaging buffer
imaging = SubElement(cmd_seq, 'valve_protocol')
imaging.text = f"Flow Imaging Buffer"
# change directory
change_dir = SubElement(cmd_seq, 'change_directory')
change_dir.text = os.path.join(source_folder, f"H{_hid}{_rname.upper()}")
# wakeup
wakeup = SubElement(cmd_seq, 'wakeup')
wakeup.text = "5000"
# imaging loop
loop = SubElement(cmd_seq, 'loop', name='Position Loop Zscan', increment="name")
loop_item = SubElement(loop, 'item', name=_im_p)
loop_item.text = " "
# delay time
delay = SubElement(cmd_seq, 'delay')
delay.text = "2000"
# copy folder
copy_dir = SubElement(cmd_seq, 'copy_directory')
source_dir = SubElement(copy_dir, 'source_path')
source_dir.text = change_dir.text#cmd_seq.findall('change_directory')[-1].text
target_dir = SubElement(copy_dir, 'target_path')
target_dir.text = os.path.join(target_drive,
os.path.basename(os.path.dirname(source_dir.text)),
os.path.basename(source_dir.text))
del_source = SubElement(copy_dir, 'delete_source')
del_source.text = "True"
# empty line
indent(target_dir)
final_str = prettify(cmd_seq)
print( final_str )
```
# save this xml
```
save_filename = os.path.join(source_folder, f"generated_dave_H{hyb_start}-{hyb_start+num_rounds-1}.txt")
with open(save_filename, 'w') as _output_handle:
print(save_filename)
_output_handle.write(final_str)
```
| github_jupyter |
# Import Libraries
```
import sys
import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.decomposition import PCA
from sklearn import random_projection
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import fbeta_score, roc_curve, auc
from sklearn import svm
import pprint
sys.path.insert(0, '../../scripts/modeling_toolbox/')
# load the autoreload extension
%load_ext autoreload
# Set extension to reload modules every time before executing code
%autoreload 2
from metric_processor import MetricProcessor
import evaluation
%matplotlib inline
```
# Data preparation
```
features = ['dimension',
'size',
'temporal_dct-mean',
'temporal_gaussian_mse-mean',
'temporal_gaussian_difference-mean',
'temporal_threshold_gaussian_difference-mean'
]
path = '../../machine_learning/cloud_functions/data-large.csv'
metric_processor = MetricProcessor(features,'UL', path, reduced=False, bins=0)
df = metric_processor.read_and_process_data()
df.shape
display(df.head())
# We remove the low bitrates since we are only focused on tampering attacks. The rotation attacks are also
# removed since they will be detected by the pre-verifier just by checking output dimensions
df = df[~(df['attack'].str.contains('low_bitrate')) & ~(df['attack'].str.contains('rotate'))]
df.head()
(X_train, X_test, X_attacks), (df_train, df_test, df_attacks) = metric_processor.split_test_and_train(df)
print('Shape of train: {}'.format(X_train.shape))
print('Shape of test: {}'.format(X_test.shape))
print('Shape of attacks: {}'.format(X_attacks.shape))
```
The train and test are **only** composed by legit assets
```
# Scaling the data
ss = StandardScaler()
x_train = ss.fit_transform(X_train)
x_test = ss.transform(X_test)
x_attacks = ss.transform(X_attacks)
```
# One Class SVM
```
# Train the model
OCSVM = svm.OneClassSVM(kernel='rbf',gamma='auto', nu=0.01, cache_size=5000)
OCSVM.fit(x_train)
fb, area, tnr, tpr_train, tpr_test = evaluation.unsupervised_evaluation(OCSVM, x_train, x_test, x_attacks)
# Show global results of classification
print('TNR: {}\nTPR_test: {}\nTPR_train: {}\n'.format(tnr, tpr_test, tpr_train))
print('F20: {}\nAUC: {}'.format(fb, area))
# Show mean distances to the decision function. A negative distance means that the data is classified as
# an attack
train_scores = OCSVM.decision_function(x_train)
test_scores = OCSVM.decision_function(x_test)
attack_scores = OCSVM.decision_function(x_attacks)
print('Mean score values:\n-Train: {}\n-Test: {}\n-Attacks: {}'.format(np.mean(train_scores),
np.mean(test_scores),
np.mean(attack_scores)))
train_preds = OCSVM.predict(x_train)
test_preds = OCSVM.predict(x_test)
attack_preds = OCSVM.predict(x_attacks)
df_train['dist_to_dec_funct'] = train_scores
df_test['dist_to_dec_funct'] = test_scores
df_attacks['dist_to_dec_funct'] = attack_scores
df_train['prediction'] = train_preds
df_test['prediction'] = test_preds
df_attacks['prediction'] = attack_preds
```
# Report
```
# Zoom in in the mean distances of the test set to the decision function by resolution. Percentiles, standard
# deviation, min and max values are shown too.
display(df_test[['dist_to_dec_funct', 'dimension']].groupby('dimension').describe())
# Zoom in in the mean distances of the attack set to the decision function by resolution. Percentiles, standard
# deviation, min and max values are shown too.
display(df_attacks[['dist_to_dec_funct', 'dimension']].groupby('dimension').describe())
# Zoom in in the mean distances of the test set to the decision function by attack type. Percentiles, standard
# deviation, min and max values are shown too.
df_attacks['attack_'] = df_attacks['attack'].apply(lambda x: x[x.find('p') + 2:])
display(df_attacks[['dist_to_dec_funct', 'attack_']].groupby(['attack_']).describe())
resolutions = sorted(df_attacks['dimension'].unique())
pp = pprint.PrettyPrinter()
# Accuracy of the test set by resolution
results = {}
for res in resolutions:
selection = df_test[df_test['dimension'] == res]
count = sum(selection['prediction'] == 1)
results[res] = count/len(selection)
pp.pprint(results)
# Accuracy on the attack set by resolution
results = {}
for res in resolutions:
selection = df_attacks[df_attacks['dimension'] == res]
count = sum(selection['prediction'] == -1)
results[res] = count/len(selection)
pp.pprint(results)
attacks = df_attacks['attack_'].unique()
# Accuracy on the attack set by attack type
results = {}
for attk in attacks:
selection = df_attacks[df_attacks['attack_'] == attk]
count = sum(selection['prediction'] == -1)
results[attk] = count/len(selection)
pp.pprint(results)
# Accuracy on the attack set by attack type
results = {}
for res in resolutions:
results[res] = {}
for attk in attacks:
selection = df_attacks[(df_attacks['attack_'] == attk) & (df_attacks['dimension'] == res)]
count = sum(selection['prediction'] == -1)
results[res][attk] = count/len(selection)
pp.pprint(results)
```
| github_jupyter |
# Random Signals and LTI-Systems
*This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).*
## Measurement of Acoustic Impulse Responses
The propagation of sound from one position (e.g. transmitter) to another (e.g. receiver) conforms reasonable well to the properties of a linear time-invariant (LTI) system. Consequently, the impulse response $h[k]$ characterizes the propagation of sound between theses two positions. Impulse responses have various applications in acoustics. For instance as [head-related impulse responses](https://en.wikipedia.org/wiki/Head-related_transfer_function) (HRIRs) or room impulse responses (RIRs) for the characterization of room acoustics.
The following example demonstrates how an acoustic impulse response can be estimated with [correlation-based system identification techniques](correlation_functions.ipynb#System-Identification) using the soundcard of a computer. The module [`sounddevice`](http://python-sounddevice.readthedocs.org/) provides access to the soundcard via [`portaudio`](http://www.portaudio.com/).
```
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sig
import sounddevice as sd
```
### Generation of the Measurement Signal
We generate white noise with a uniform distribution between $\pm 0.5$ as the excitation signal $x[k]$
```
fs = 44100 # sampling rate
T = 5 # length of the measurement signal in sec
Tr = 2 # length of the expected system response in sec
x = np.random.uniform(-.5, .5, size=T*fs)
```
### Playback of Measurement Signal and Recording of Room Response
The measurement signal $x[k]$ is played through the output of the soundcard and the response $y[k]$ is captured synchronously by the input of the soundcard. The length of the played/captured signal has to be of equal length when using the soundcard. The measurement signal $x[k]$ is zero-padded so that the captured signal $y[k]$ includes the complete system response.
Be sure not to overdrive the speaker and the microphone by keeping the input level well below 0 dB.
```
x = np.concatenate((x, np.zeros(Tr*fs)))
y = sd.playrec(x, fs, channels=1)
sd.wait()
y = np.squeeze(y)
print('Playback level: ', 20*np.log10(max(x)), ' dB')
print('Input level: ', 20*np.log10(max(y)), ' dB')
```
### Estimation of the Acoustic Impulse Response
The acoustic impulse response is estimated by cross-correlation $\varphi_{yx}[\kappa]$ of the output with the input signal. Since the cross-correlation function (CCF) for finite-length signals is given as $\varphi_{yx}[\kappa] = \frac{1}{K} \cdot y[\kappa] * x[-\kappa]$, the computation of the CCF can be speeded up with the fast convolution method.
```
h = 1/len(y) * sig.fftconvolve(y, x[::-1], mode='full')
h = h[fs*(T+Tr):fs*(T+2*Tr)]
plt.figure(figsize=(10, 5))
t = 1/fs * np.arange(len(h))
plt.plot(t, h)
plt.axis([0.0, 1.0, -1.1*np.max(np.abs(h)), 1.1*np.max(np.abs(h))])
plt.xlabel(r'$t$ in s')
plt.ylabel(r'$\hat{h}[k]$')
```
**Copyright**
This notebook is provided as [Open Educational Resource](https://en.wikipedia.org/wiki/Open_educational_resources). Feel free to use the notebook for your own purposes. The text is licensed under [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/), the code of the IPython examples under the [MIT license](https://opensource.org/licenses/MIT). Please attribute the work as follows: *Sascha Spors, Digital Signal Processing - Lecture notes featuring computational examples*.
| github_jupyter |
## TCLab Function Help

#### Connect/Disconnect
```lab = tclab.TCLab()``` Connect and create new lab object, ```lab.close()``` disconnects lab.
#### LED
```lab.LED()``` Percentage of output light for __Hot__ Light.
#### Heaters
```lab.Q1()``` and ```lab.Q2()``` Percentage of power to heaters.
#### Temperatures
```lab.T1``` and ```lab.T2``` Value of current heater tempertures in Celsius.
| **TCLab Function** | **Example** | **Description** |
| ----------- | ----------- | ----------- |
| `TCLab()` | `tclab.TCLab()` | Create new lab object and connect |
| `LED` | `lab.LED(45)` | Turn on the LED to 45%. Valid range is 0-100% |
| `Q1` | `lab.Q1(63)` | Turn on heater 1 (`Q1`) to 63%. Valid range is 0-100% |
| `Q2` | `lab.Q2(28)` | Turn on heater 2 (`Q2`) to 28%. Valid range is 0-100% |
| `T1` | `print(lab.T1)` | Read temperature 1 (`T1`) in °C. valid range is -40 to 150°C (TMP36 sensor) |
| `T2` | `print(lab.T2)` | Read temperature 2 (`T2`) in °C. with +/- 1°C accuracy (TMP36 sensor) |
| `close()` | `lab.close()` | Close serial USB connection to TCLab - not needed if using `with` to open |
### Errors

Submit an error to us at support@apmonitor.com so we can fix the problem and add it to this list. There is also a list of [troubleshooting items with frequently asked questions](https://apmonitor.com/pdc/index.php/Main/ArduinoSetup). If you get the error about already having an open connection to the TCLab, try restarting the **kernel**. Go to the top of the page to the **Kernel** tab, click it, then click restart.
### How to Run a Cell
Use the symbol to run the needed cell, left of the program. If you don't see a symbol, try selecting the cell and holding `Ctrl`, then pressing `Enter`. Another option is clicking the "Run" button at the top of the page when the cell is selected.
### Install Temperature Control Lab

This code trys to import `tclab`. If it if it fails to find the package, it installs the program with `pip`. The `pip` installation is required once to let you use the Temperature Control Lab for all of the exercises. It does not need to be installed again, even if the IPython session is restarted.
```
# install tclab
try:
import tclab
except:
# Needed to communicate through usb port
!pip install --user pyserial
# The --user is put in for accounts without admin privileges
!pip install --user tclab
# restart kernel if this doesn't import
import tclab
```
### Update Temperature Control Lab
Updates package to latest version.
```
!pip install tclab --upgrade --user
```
### Connection Check

The following code connects, reads temperatures 1 and 2, sets heaters 1 and 2, turns on the LED to 45%, and then disconnects from the TCLab. If an error is shown, try unplugging your lab and/or restarting Jupyter's kernel from the Jupyter notebook menu.
```
import tclab
lab = tclab.TCLab()
print(lab.T1,lab.T2)
lab.Q1(50); lab.Q2(40)
lab.LED(45)
lab.close()
```

Another way to connect to the TCLab is the `with` statement. The advantage of the `with` statement is that the connection automatically closes if there is a fatal error (bug) in the code and the program never reaches the `lab.close()` statement. This prevents a kernel restart to reset the USB connection to the TCLab Arduino.
```
import tclab
import time
with tclab.TCLab() as lab:
print(lab.T1,lab.T2)
lab.Q1(50); lab.Q2(40)
lab.LED(45)
```
| github_jupyter |
# Face Generation
In this project, you'll use generative adversarial networks to generate new images of faces.
### Get the Data
You'll be using two datasets in this project:
- MNIST
- CelebA
Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST before CelebA. Running the GANs on MNIST will allow you to see how well your model trains sooner.
If you're using [FloydHub](https://www.floydhub.com/), set `data_dir` to "/input" and use the [FloydHub data ID](http://docs.floydhub.com/home/using_datasets/) "R5KrjnANiKVhLWAkpXhNBe".
```
data_dir = './data'
# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
data_dir = '/input'
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
```
## Explore the Data
### MNIST
As you're aware, the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset contains images of handwritten digits. You can view the first number of examples by changing `show_n_images`.
```
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
%matplotlib inline
import os
from glob import glob
from matplotlib import pyplot
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')
pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')
```
### CelebA
The [CelebFaces Attributes Dataset (CelebA)](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing `show_n_images`.
```
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')
pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))
```
## Preprocess the Data
Since the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.
The MNIST images are black and white images with a single [color channel](https://en.wikipedia.org/wiki/Channel_(digital_image%29) while the CelebA images have [3 color channels (RGB color channel)](https://en.wikipedia.org/wiki/Channel_(digital_image%29#RGB_Images).
## Build the Neural Network
You'll build the components necessary to build a GANs by implementing the following functions below:
- `model_inputs`
- `discriminator`
- `generator`
- `model_loss`
- `model_opt`
- `train`
### Check the Version of TensorFlow and Access to GPU
This will check to make sure you have the correct version of TensorFlow and access to a GPU
```
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))
# Check for a GPU
if not tf.test.gpu_device_name():
warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
```
### Input
Implement the `model_inputs` function to create TF Placeholders for the Neural Network. It should create the following placeholders:
- Real input images placeholder with rank 4 using `image_width`, `image_height`, and `image_channels`.
- Z input placeholder with rank 2 using `z_dim`.
- Learning rate placeholder with rank 0.
Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)
```
import problem_unittests as tests
def model_inputs(image_width, image_height, image_channels, z_dim):
"""
Create the model inputs
:param image_width: The input image width
:param image_height: The input image height
:param image_channels: The number of image channels
:param z_dim: The dimension of Z
:return: Tuple of (tensor of real input images, tensor of z data, learning rate)
"""
# TODO: Implement Function
input_real = tf.placeholder(tf.float32, (None, image_width, image_height, image_channels), name="input_real")
input_z = tf.placeholder(tf.float32, (None, z_dim), name="input_z")
l_rate = tf.placeholder(tf.float32, name='l_rate')
return input_real, input_z, l_rate
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)
```
### Discriminator
Implement `discriminator` to create a discriminator neural network that discriminates on `images`. This function should be able to reuse the variabes in the neural network. Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of "discriminator" to allow the variables to be reused. The function should return a tuple of (tensor output of the generator, tensor logits of the generator).
```
def discriminator(images, reuse=False):
"""
Create the discriminator network
:param image: Tensor of input image(s)
:param reuse: Boolean if the weights should be reused
:return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)
"""
# TODO: Implement Function
alpha = 0.2
with tf.variable_scope('discriminator', reuse=reuse):
# Input layer is 28x28x3
x1 = tf.layers.conv2d(images, 64, 5, strides=2, padding='same')
relu1 = tf.maximum(alpha * x1, x1)
# 14x14x64
x2 = tf.layers.conv2d(relu1, 128, 5, strides=1, padding='same')
bn2= tf.layers.batch_normalization(x2, training=True)
relu2 = tf.maximum(alpha * bn2, bn2)
# 14x14x128
x3 = tf.layers.conv2d(relu2, 128, 5, strides=2, padding='same')
bn3= tf.layers.batch_normalization(x3, training=True)
relu3 = tf.maximum(alpha * bn3, bn3)
# 7x7x256
# Flatten it
flat = tf.reshape(relu2, (-1, 7*7*256))
logits = tf.layers.dense(flat, 1)
output = tf.sigmoid(logits)
return output, logits
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_discriminator(discriminator, tf)
```
### Generator
Implement `generator` to generate an image using `z`. This function should be able to reuse the variabes in the neural network. Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x `out_channel_dim` images.
```
def generator(z, out_channel_dim, is_train=True):
"""
Create the generator network
:param z: Input z
:param out_channel_dim: The number of channels in the output image
:param is_train: Boolean if generator is being used for training
:return: The tensor output of the generator
"""
# TODO: Implement Function
alpha = 0.2
with tf.variable_scope('generator', reuse=not is_train):
# First fully connected layer
x1 = tf.layers.dense(z, 7*7*256)
# Reshape it to start the convolutional stack
x1 = tf.reshape(x1, (-1, 7, 7, 256))
x1 = tf.layers.batch_normalization(x1, training=is_train)
x1 = tf.maximum(alpha * x1, x1)
# 7x7x256 now
x2 = tf.layers.conv2d_transpose(x1, 128, 5, strides=2, padding='same')
x2 = tf.layers.batch_normalization(x2, training=is_train)
x2 = tf.maximum(alpha * x2, x2)
# 14x14x128 now
x3 = tf.layers.conv2d_transpose(x2, 64, 5, strides=2, padding='same')
x3 = tf.layers.batch_normalization(x3, training=is_train)
x3 = tf.maximum(alpha * x3, x3)
# 28x28x64 now
# Output layer
logits = tf.layers.conv2d_transpose(x3, out_channel_dim, 5, strides=1, padding='same')
# 28 x 28 x out_channel_dim
output = tf.tanh(logits)
return output
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_generator(generator, tf)
```
### Loss
Implement `model_loss` to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented:
- `discriminator(images, reuse=False)`
- `generator(z, out_channel_dim, is_train=True)`
```
def model_loss(input_real, input_z, out_channel_dim):
"""
Get the loss for the discriminator and generator
:param input_real: Images from the real dataset
:param input_z: Z input
:param out_channel_dim: The number of channels in the output image
:return: A tuple of (discriminator loss, generator loss)
"""
# TODO: Implement Function
smooth = 0.1
g_model = generator(input_z, out_channel_dim, is_train=True)
d_model_real, d_logits_real = discriminator(input_real)
d_model_fake, d_logits_fake = discriminator(g_model, reuse=True)
d_loss_real = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real,
labels=tf.ones_like(d_model_real) * (1 - smooth)))
d_loss_fake = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_model_fake)))
g_loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_model_fake)))
d_loss = d_loss_real + d_loss_fake
return d_loss, g_loss
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_loss(model_loss)
```
### Optimization
Implement `model_opt` to create the optimization operations for the GANs. Use [`tf.trainable_variables`](https://www.tensorflow.org/api_docs/python/tf/trainable_variables) to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The function should return a tuple of (discriminator training operation, generator training operation).
```
def model_opt(d_loss, g_loss, learning_rate, beta1):
"""
Get optimization operations
:param d_loss: Discriminator loss Tensor
:param g_loss: Generator loss Tensor
:param learning_rate: Learning Rate Placeholder
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:return: A tuple of (discriminator training operation, generator training operation)
"""
# TODO: Implement Function
t_vars = tf.trainable_variables()
d_vars = [var for var in t_vars if var.name.startswith('discriminator')]
g_vars = [var for var in t_vars if var.name.startswith('generator')]
# Optimize
d_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(d_loss, var_list=d_vars)
g_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(g_loss, var_list=g_vars)
return d_train_opt, g_train_opt
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_opt(model_opt, tf)
```
## Neural Network Training
### Show Output
Use this function to show the current output of the generator during training. It will help you determine how well the GANs is training.
```
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):
"""
Show example output for the generator
:param sess: TensorFlow session
:param n_images: Number of Images to display
:param input_z: Input Z Tensor
:param out_channel_dim: The number of channels in the output image
:param image_mode: The mode to use for images ("RGB" or "L")
"""
cmap = None if image_mode == 'RGB' else 'gray'
z_dim = input_z.get_shape().as_list()[-1]
example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])
samples = sess.run(
generator(input_z, out_channel_dim, False),
feed_dict={input_z: example_z})
images_grid = helper.images_square_grid(samples, image_mode)
pyplot.imshow(images_grid, cmap=cmap)
pyplot.show()
```
### Train
Implement `train` to build and train the GANs. Use the following functions you implemented:
- `model_inputs(image_width, image_height, image_channels, z_dim)`
- `model_loss(input_real, input_z, out_channel_dim)`
- `model_opt(d_loss, g_loss, learning_rate, beta1)`
Use the `show_generator_output` to show `generator` output while you train. Running `show_generator_output` for every batch will drastically increase training time and increase the size of the notebook. It's recommended to print the `generator` output every 100 batches.
```
def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode):
"""
Train the GAN
:param epoch_count: Number of epochs
:param batch_size: Batch Size
:param z_dim: Z dimension
:param learning_rate: Learning Rate
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:param get_batches: Function to get batches
:param data_shape: Shape of the data
:param data_image_mode: The image mode to use for images ("RGB" or "L")
"""
# TODO: Build Model
class GAN:
def __init__(self, data_shape, z_size, learning_rate, alpha=0.2, beta1=0.5):
#tf.reset_default_graph()
_, image_width, image_height, image_channels = data_shape
self.input_real, self.input_z, self.learning_rate = model_inputs(image_width, image_height,
image_channels,
z_size)
self.d_loss, self.g_loss = model_loss(self.input_real, self.input_z, image_channels)
self.d_opt, self.g_opt = model_opt(self.d_loss, self.g_loss, learning_rate, 0.5)
net = GAN(data_shape, z_dim, learning_rate, alpha=0.2, beta1=beta1)
saver = tf.train.Saver()
#sample_z = np.random.uniform(-1, 1, size=(50, z_dim))
samples, losses = [], []
batches = 0
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for e in range(epoch_count):
for batch_images in get_batches(batch_size):
batches += 1
#dataset range from -0.5 to 0.5
#batch_images = batch_images.reshape((batch_size, 784 * data_shape[3]))
batch_images = batch_images * 2
# Sample random noise for G
batch_z = np.random.uniform(-1, 1, size=(batch_size, z_dim))
# Run optimizers
_ = sess.run(net.d_opt, feed_dict={net.input_real: batch_images, net.input_z: batch_z})
_ = sess.run(net.g_opt, feed_dict={net.input_z: batch_z})
if batches % 10 == 0:
# At the end of each epoch, get the losses and print them out
train_loss_d = net.d_loss.eval({net.input_z: batch_z, net.input_real: batch_images})
train_loss_g = net.g_loss.eval({net.input_z: batch_z})
print("Epoch {}/{}...".format(e+1, epoch_count),
"Discriminator Loss: {:.4f}...".format(train_loss_d),
"Generator Loss: {:.4f}".format(train_loss_g))
# Save losses to view after training
losses.append((train_loss_d, train_loss_g))
if batches % 100 == 0:
_ = show_generator_output(sess, 16, net.input_z, data_shape[3], data_image_mode)
saver.save(sess, './checkpoints/generator.ckpt')
with open('samples.pkl', 'wb') as f:
pkl.dump(samples, f)
return losses, samples
```
### MNIST
Test your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.
```
batch_size = 128
z_dim = 100
learning_rate = 0.0001
beta1 = 0.5
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 2
mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))
with tf.Graph().as_default():
train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,
mnist_dataset.shape, mnist_dataset.image_mode)
```
### CelebA
Run your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces.
```
batch_size = 128
z_dim = 100
learning_rate = 0.0001
beta1 = 0.5
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 1
celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))
with tf.Graph().as_default():
train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,
celeba_dataset.shape, celeba_dataset.image_mode)
```
### Submitting This Project
When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_face_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.
| github_jupyter |
**Important**: This notebook is different from the other as it directly calls **ImageJ Kappa plugin** using the [`scyjava` ImageJ brige](https://github.com/scijava/scyjava).
Since Kappa uses ImageJ1 features, you might not be able to run this notebook on an headless machine (need to be tested).
```
from pathlib import Path
import pandas as pd
import numpy as np
from tqdm.auto import tqdm
import sys; sys.path.append("../../")
import pykappa
# Init ImageJ with Fiji plugins
# It can take a while if Java artifacts are not yet cached.
import imagej
java_deps = []
java_deps.append('org.scijava:Kappa:1.7.1')
ij = imagej.init("+".join(java_deps), headless=False)
import jnius
# Load Java classes
KappaFrame = jnius.autoclass('sc.fiji.kappa.gui.KappaFrame')
CurvesExporter = jnius.autoclass('sc.fiji.kappa.gui.CurvesExporter')
# Load ImageJ services
dsio = ij.context.getService(jnius.autoclass('io.scif.services.DatasetIOService'))
dsio = jnius.cast('io.scif.services.DatasetIOService', dsio)
# Set data path
data_dir = Path("/home/hadim/.data/Postdoc/Kappa/spiral_curve_SDM/")
# Pixel size used when fixed
fixed_pixel_size = 0.16
# Used to select pixels around the initialization curves
base_radius_um = 1.6
enable_control_points_adjustment = True
# "Point Distance Minimization" or "Squared Distance Minimization"
if '_SDM' in data_dir.name:
fitting_algorithm = "Squared Distance Minimization"
else:
fitting_algorithm = "Point Distance Minimization"
fitting_algorithm
experiment_names = ['variable_snr', 'variable_initial_position', 'variable_pixel_size', 'variable_psf_size']
experiment_names = ['variable_psf_size']
for experiment_name in tqdm(experiment_names, total=len(experiment_names)):
experiment_path = data_dir / experiment_name
fnames = sorted(list(experiment_path.glob("*.tif")))
n = len(fnames)
for fname in tqdm(fnames, total=n, leave=False):
tqdm.write(str(fname))
kappa_path = fname.with_suffix(".kapp")
assert kappa_path.exists(), f'{kappa_path} does not exist.'
curvatures_path = fname.with_suffix(".csv")
if not curvatures_path.is_file():
frame = KappaFrame(ij.context)
frame.getKappaMenubar().openImageFile(str(fname))
frame.resetCurves()
frame.getKappaMenubar().loadCurveFile(str(kappa_path))
frame.getCurves().setAllSelected()
# Compute threshold according to the image
dataset = dsio.open(str(fname))
mean = ij.op().stats().mean(dataset).getRealDouble()
std = ij.op().stats().stdDev(dataset).getRealDouble()
threshold = int(mean + std * 2)
# Used fixed pixel size or the one in the filename
if fname.stem.startswith('pixel_size'):
pixel_size = float(fname.stem.split("_")[-2])
if experiment_name == 'variable_psf_size':
pixel_size = 0.01
else:
pixel_size = fixed_pixel_size
base_radius = int(np.round(base_radius_um / pixel_size))
# Set curve fitting parameters
frame.setEnableCtrlPtAdjustment(enable_control_points_adjustment)
frame.setFittingAlgorithm(fitting_algorithm)
frame.getInfoPanel().thresholdRadiusSpinner.setValue(ij.py.to_java(base_radius))
frame.getInfoPanel().thresholdSlider.setValue(threshold)
frame.getInfoPanel().updateConversionField(str(pixel_size))
# Fit the curves
frame.fitCurves()
# Save fitted curves
frame.getKappaMenubar().saveCurveFile(str(fname.with_suffix(".FITTED.kapp")))
# Export results
exporter = CurvesExporter(frame)
exporter.exportToFile(str(curvatures_path), False)
# Remove duplicate rows during CSV export.
# See https://github.com/brouhardlab/Kappa/issues/12
df = pd.read_csv(curvatures_path)
df = df.drop_duplicates()
df.to_csv(curvatures_path)
0.13**2
```
| github_jupyter |
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content-dl/blob/main/tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Tutorial 1: PyTorch
**Week 1, Day 1: Basics and PyTorch**
**By Neuromatch Academy**
__Content creators:__ Shubh Pachchigar, Vladimir Haltakov, Matthew Sargent, Konrad Kording
__Content reviewers:__ Deepak Raya, Siwei Bai, Kelson Shilling-Scrivo
__Content editors:__ Anoop Kulkarni, Spiros Chavlis
__Production editors:__ Arush Tagade, Spiros Chavlis
**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**
<p align='center'><img src='https://github.com/NeuromatchAcademy/widgets/blob/master/sponsors.png?raw=True'/></p>
---
# Tutorial Objectives
Then have a few specific objectives for this tutorial:
* Learn about PyTorch and tensors
* Tensor Manipulations
* Data Loading
* GPUs and Cuda Tensors
* Train NaiveNet
* Get to know your pod
* Start thinking about the course as a whole
```
# @title Tutorial slides
# @markdown These are the slides for the videos in this tutorial today
from IPython.display import IFrame
IFrame(src=f"https://mfr.ca-1.osf.io/render?url=https://osf.io/wcjrv/?direct%26mode=render%26action=download%26mode=render", width=854, height=480)
```
---
# Setup
Throughout your Neuromatch tutorials, most (probably all!) notebooks contain setup cells. These cells will import the required Python packages (e.g., PyTorch, NumPy); set global or environment variables, and load in helper functions for things like plotting. In some tutorials, you will notice that we install some dependencies even if they are preinstalled on google colab or kaggle. This happens because we have added automation to our repository through [GitHub Actions](https://docs.github.com/en/actions/learn-github-actions/introduction-to-github-actions).
Be sure to run all of the cells in the setup section. Feel free to expand them and have a look at what you are loading in, but you should be able to fulfill the learning objectives of every tutorial without having to look at these cells.
If you start building your own projects built on this code base we highly recommend looking at them in more detail.
```
# @title Install dependencies
!pip install pandas --quiet
!pip install git+https://github.com/NeuromatchAcademy/evaltools --quiet
from evaltools.airtable import AirtableForm
# Imports
import time
import torch
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from torch import nn
from torchvision import datasets
from torchvision.transforms import ToTensor
from torch.utils.data import DataLoader
# @title Figure Settings
import ipywidgets as widgets
%config InlineBackend.figure_format = 'retina'
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/content-creation/main/nma.mplstyle")
# @title Helper Functions
atform = AirtableForm('appn7VdPRseSoMXEG','W1D1_T1','https://portal.neuromatchacademy.org/api/redirect/to/97e94a29-0b3a-4e16-9a8d-f6838a5bd83d')
def checkExercise1(A, B, C, D):
"""
Helper function for checking exercise.
Args:
A: torch.Tensor
B: torch.Tensor
C: torch.Tensor
D: torch.Tensor
Returns:
Nothing.
"""
errors = []
# TODO better errors and error handling
if not torch.equal(A.to(int),torch.ones(20, 21).to(int)):
errors.append(f"Got: {A} \n Expected: {torch.ones(20, 21)} (shape: {torch.ones(20, 21).shape})")
if not np.array_equal( B.numpy(),np.vander([1, 2, 3], 4)):
errors.append("B is not a tensor containing the elements of Z ")
if C.shape != (20, 21):
errors.append("C is not the correct shape ")
if not torch.equal(D, torch.arange(4, 41, step=2)):
errors.append("D does not contain the correct elements")
if errors == []:
print("All correct!")
else:
[print(e) for e in errors]
def timeFun(f, dim, iterations, device='cpu'):
iterations = iterations
t_total = 0
for _ in range(iterations):
start = time.time()
f(dim, device)
end = time.time()
t_total += end - start
if device == 'cpu':
print(f"time taken for {iterations} iterations of {f.__name__}({dim}, {device}): {t_total:.5f}")
else:
print(f"time taken for {iterations} iterations of {f.__name__}({dim}, {device}): {t_total:.5f}")
```
**Important note: Google Colab users**
*Scratch Code Cells*
If you want to quickly try out something or take a look at the data you can use scratch code cells. They allow you to run Python code, but will not mess up the structure of your notebook.
To open a new scratch cell go to *Insert* → *Scratch code cell*.
# Section 1: Welcome to Neuromatch Deep learning course
*Time estimate: ~25mins*
```
# @title Video 1: Welcome and History
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1Av411n7oL", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"ca21SNqt78I", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing
atform.add_event('Video 1: Welcome and History')
display(out)
```
*This will be an intensive 3 week adventure. We will all learn Deep Learning. In a group. Groups need standards. Read our
[Code of Conduct](https://docs.google.com/document/d/1eHKIkaNbAlbx_92tLQelXnicKXEcvFzlyzzeWjEtifM/edit?usp=sharing).
```
# @title Video 2: Why DL is cool
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1gf4y1j7UZ", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"l-K6495BN-4", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 2: Why DL is cool')
display(out)
```
**Describe what you hope to get out of this course in about 100 words.**
---
# Section 2: The Basics of PyTorch
*Time estimate: ~2 hours 05 mins*
PyTorch is a Python-based scientific computing package targeted at two sets of
audiences:
- A replacement for NumPy to use the power of GPUs
- A deep learning platform that provides significant flexibility
and speed
At its core, PyTorch provides a few key features:
- A multidimensional [Tensor](https://pytorch.org/docs/stable/tensors.html) object, similar to [NumPy Array](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html) but with GPU acceleration.
- An optimized **autograd** engine for automatically computing derivatives.
- A clean, modular API for building and deploying **deep learning models**.
You can find more information about PyTorch in the appendix.
## Section 2.1: Creating Tensors
```
# @title Video 3: Making Tensors
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1Rw411d7Uy", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"jGKd_4tPGrw", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 3: Making Tensors')
display(out)
```
There are various ways of creating tensors, and when doing any real deep learning project we will usually have to do so.
**Construct tensors directly:**
---
```
# we can construct a tensor directly from some common python iterables,
# such as list and tuple nested iterables can also be handled as long as the
# dimensions make sense
# tensor from a list
a = torch.tensor([0, 1, 2])
#tensor from a tuple of tuples
b = ((1.0, 1.1), (1.2, 1.3))
b = torch.tensor(b)
# tensor from a numpy array
c = np.ones([2, 3])
c = torch.tensor(c)
print(f"Tensor a: {a}")
print(f"Tensor b: {b}")
print(f"Tensor c: {c}")
```
**Some common tensor constructors:**
---
```
# the numerical arguments we pass to these constructors
# determine the shape of the output tensor
x = torch.ones(5, 3)
y = torch.zeros(2)
z = torch.empty(1, 1, 5)
print(f"Tensor x: {x}")
print(f"Tensor y: {y}")
print(f"Tensor z: {z}")
```
Notice that ```.empty()``` does not return zeros, but seemingly random small numbers. Unlike ```.zeros()```, which initialises the elements of the tensor with zeros, ```.empty()``` just allocates the memory. It is hence a bit faster if you are looking to just create a tensor.
**Creating random tensors and tensors like other tensors:**
---
```
# there are also constructors for random numbers
# uniform distribution
a = torch.rand(1, 3)
# normal distribution
b = torch.randn(3, 4)
# there are also constructors that allow us to construct
# a tensor according to the above constructors, but with
# dimensions equal to another tensor
c = torch.zeros_like(a)
d = torch.rand_like(c)
print(f"Tensor a: {a}")
print(f"Tensor b: {b}")
print(f"Tensor c: {c}")
print(f"Tensor d: {d}")
```
*Reproducibility*:
- PyTorch random number generator: You can use `torch.manual_seed()` to seed the RNG for all devices (both CPU and CUDA)
```python
import torch
torch.manual_seed(0)
```
- For custom operators, you might need to set python seed as well:
```python
import random
random.seed(0)
```
- Random number generators in other libraries
```python
import numpy as np
np.random.seed(0)
```
Here, we define for you a function called `set_seed` that does the job for you!
```
def set_seed(seed=None, seed_torch=True):
"""
Function that controls randomness. NumPy and random modules must be imported.
Args:
seed : Integer
A non-negative integer that defines the random state. Default is `None`.
seed_torch : Boolean
If `True` sets the random seed for pytorch tensors, so pytorch module
must be imported. Default is `True`.
Returns:
Nothing.
"""
if seed is None:
seed = np.random.choice(2 ** 32)
random.seed(seed)
np.random.seed(seed)
if seed_torch:
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
print(f'Random seed {seed} has been set.')
```
Now, let's use the `set_seed` function in the previous example. Execute the cell multiple times to verify that the numbers printed are always the same.
```
def simplefun(seed=True, my_seed=None):
if seed:
set_seed(seed=my_seed)
# uniform distribution
a = torch.rand(1, 3)
# normal distribution
b = torch.randn(3, 4)
print("Tensor a: ", a)
print("Tensor b: ", b)
simplefun(seed=True, my_seed=0) # Turn `seed` to `False` or change `my_seed`
```
**Numpy-like number ranges:**
---
The ```.arange()``` and ```.linspace()``` behave how you would expect them to if you are familar with numpy.
```
a = torch.arange(0, 10, step=1)
b = np.arange(0, 10, step=1)
c = torch.linspace(0, 5, steps=11)
d = np.linspace(0, 5, num=11)
print(f"Tensor a: {a}\n")
print(f"Numpy array b: {b}\n")
print(f"Tensor c: {c}\n")
print(f"Numpy array d: {d}\n")
```
### Coding Exercise 2.1: Creating Tensors
Below you will find some incomplete code. Fill in the missing code to construct the specified tensors.
We want the tensors:
$A:$ 20 by 21 tensor consisting of ones
$B:$ a tensor with elements equal to the elements of numpy array $Z$
$C:$ a tensor with the same number of elements as $A$ but with values $
\sim U(0,1)$
$D:$ a 1D tensor containing the even numbers between 4 and 40 inclusive.
```
def tensor_creation(Z):
"""A function that creates various tensors.
Args:
Z (numpy.ndarray): An array of shape
Returns:
A : 20 by 21 tensor consisting of ones
B : a tensor with elements equal to the elements of numpy array Z
C : a tensor with the same number of elements as A but with values ∼U(0,1)
D : a 1D tensor containing the even numbers between 4 and 40 inclusive.
"""
#################################################
## TODO for students: fill in the missing code
## from the first expression
raise NotImplementedError("Student exercise: say what they should have done")
#################################################
A = ...
B = ...
C = ...
D = ...
return A, B, C, D
# add timing to airtable
atform.add_event('Coding Exercise 2.1: Creating Tensors')
# numpy array to copy later
Z = np.vander([1, 2, 3], 4)
# Uncomment below to check your function!
# A, B, C, D = tensor_creation(Z)
# checkExercise1(A, B, C, D)
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_ad4f6c0f.py)
```
All correct!
```
## Section 2.2: Operations in PyTorch
**Tensor-Tensor operations**
We can perform operations on tensors using methods under ```torch.```
```
# @title Video 4: Tensor Operators
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1G44y127As", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"R1R8VoYXBVA", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 4: Tensor Operators')
display(out)
```
**Tensor-Tensor operations**
We can perform operations on tensors using methods under ```torch.```
```
a = torch.ones(5, 3)
b = torch.rand(5, 3)
c = torch.empty(5, 3)
d = torch.empty(5, 3)
# this only works if c and d already exist
torch.add(a, b, out=c)
#Pointwise Multiplication of a and b
torch.multiply(a, b, out=d)
print(c)
print(d)
```
However, in PyTorch most common Python operators are overridden.
The common standard arithmetic operators (+, -, *, /, and **) have all been lifted to elementwise operations
```
x = torch.tensor([1, 2, 4, 8])
y = torch.tensor([1, 2, 3, 4])
x + y, x - y, x * y, x / y, x**y # The ** operator is exponentiation
```
**Tensor Methods**
Tensors also have a number of common arithmetic operations built in. A full list of **all** methods can be found in the appendix (there are a lot!)
All of these operations should have similar syntax to their numpy equivalents.(Feel free to skip if you already know this!)
```
x = torch.rand(3, 3)
print(x)
print("\n")
# sum() - note the axis is the axis you move across when summing
print(f"Sum of every element of x: {x.sum()}")
print(f"Sum of the columns of x: {x.sum(axis=0)}")
print(f"Sum of the rows of x: {x.sum(axis=1)}")
print("\n")
print(f"Mean value of all elements of x {x.mean()}")
print(f"Mean values of the columns of x {x.mean(axis=0)}")
print(f"Mean values of the rows of x {x.mean(axis=1)}")
```
**Matrix Operations**
The ```@``` symbol is overridden to represent matrix multiplication. You can also use ```torch.matmul()``` to multiply tensors. For dot multiplication, you can use ```torch.dot()```, or manipulate the axes of your tensors and do matrix multiplication (we will cover that in the next section).
Transposes of 2D tensors are obtained using ```torch.t()``` or ```Tensor.T```. Note the lack of brackets for ```Tensor.T``` - it is an attribute, not a method.
### Coding Exercise 2.2 : Simple tensor operations
Below are two expressions involving operations on matrices.
$$ \textbf{A} =
\begin{bmatrix}2 &4 \\5 & 7
\end{bmatrix}
\begin{bmatrix} 1 &1 \\2 & 3
\end{bmatrix}
+
\begin{bmatrix}10 & 10 \\ 12 & 1
\end{bmatrix}
$$
and
$$ b =
\begin{bmatrix} 3 \\ 5 \\ 7
\end{bmatrix} \cdot
\begin{bmatrix} 2 \\ 4 \\ 8
\end{bmatrix}
$$
The code block below that computes these expressions using PyTorch is incomplete - fill in the missing lines.
```
def simple_operations(a1: torch.Tensor, a2: torch.Tensor, a3: torch.Tensor):
################################################
## TODO for students: complete the first computation using the argument matricies
raise NotImplementedError("Student exercise: fill in the missing code to complete the operation")
################################################
# multiplication of tensor a1 with tensor a2 and then add it with tensor a3
answer = ...
return answer
# add timing to airtable
atform.add_event('Coding Exercise 2.2 : Simple tensor operations-simple_operations')
# Computing expression 1:
# init our tensors
a1 = torch.tensor([[2, 4], [5, 7]])
a2 = torch.tensor([[1, 1], [2, 3]])
a3 = torch.tensor([[10, 10], [12, 1]])
## uncomment to test your function
# A = simple_operations(a1, a2, a3)
# print(A)
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_5562ea1d.py)
```
tensor([[20, 24],
[31, 27]])
```
```
def dot_product(b1: torch.Tensor, b2: torch.Tensor):
###############################################
## TODO for students: complete the first computation using the argument matricies
raise NotImplementedError("Student exercise: fill in the missing code to complete the operation")
###############################################
# Use torch.dot() to compute the dot product of two tensors
product = ...
return product
# add timing to airtable
atform.add_event('Coding Exercise 2.2 : Simple tensor operations-dot_product')
# Computing expression 2:
b1 = torch.tensor([3, 5, 7])
b2 = torch.tensor([2, 4, 8])
## Uncomment to test your function
# b = dot_product(b1, b2)
# print(b)
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_00491ea4.py)
```
tensor(82)
```
## Section 2.3 Manipulating Tensors in Pytorch
```
# @title Video 5: Tensor Indexing
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1BM4y1K7pD", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"0d0KSJ3lJbg", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 5: Tensor Indexing')
display(out)
```
**Indexing**
Just as in numpy, elements in a tensor can be accessed by index. As in any numpy array, the first element has index 0 and ranges are specified to include the first but before the last element. We can access elements according to their relative position to the end of the list by using negative indices. Indexing is also referred to as slicing.
For example, [-1] selects the last element; [1:3] selects the second and the third elements, and [:-2] will select all elements excluding the last and second-to-last elements.
```
x = torch.arange(0, 10)
print(x)
print(x[-1])
print(x[1:3])
print(x[:-2])
```
When we have multidimensional tensors, indexing rules work the same way as numpy.
```
# make a 5D tensor
x = torch.rand(1, 2, 3, 4, 5)
print(f" shape of x[0]:{x[0].shape}")
print(f" shape of x[0][0]:{x[0][0].shape}")
print(f" shape of x[0][0][0]:{x[0][0][0].shape}")
```
**Flatten and reshape**
There are various methods for reshaping tensors. It is common to have to express 2D data in 1D format. Similarly, it is also common to have to reshape a 1D tensor into a 2D tensor. We can achieve this with the ```.flatten()``` and ```.reshape()``` methods.
```
z = torch.arange(12).reshape(6, 2)
print(f"Original z: \n {z}")
# 2D -> 1D
z = z.flatten()
print(f"Flattened z: \n {z}")
# and back to 2D
z = z.reshape(3, 4)
print(f"Reshaped (3x4) z: \n {z}")
```
You will also see the ```.view()``` methods used a lot to reshape tensors. There is a subtle difference between ```.view()``` and ```.reshape()```, though for now we will just use ```.reshape()```. The documentation can be found in the appendix.
**Squeezing tensors**
When processing batches of data, you will quite often be left with singleton dimensions. e.g. [1,10] or [256, 1, 3]. This dimension can quite easily mess up your matrix operations if you don't plan on it being there...
In order to compress tensors along their singleton dimensions we can use the ```.squeeze()``` method. We can use the ```.unsqueeze()``` method to do the opposite.
```
x = torch.randn(1, 10)
# printing the zeroth element of the tensor will not give us the first number!
print(x.shape)
print(f"x[0]: {x[0]}")
```
Because of that pesky singleton dimension, x[0] gave us the first row instead!
```
# lets get rid of that singleton dimension and see what happens now
x = x.squeeze(0)
print(x.shape)
print(f"x[0]: {x[0]}")
# adding singleton dimensions works a similar way, and is often used when tensors
# being added need same number of dimensions
y = torch.randn(5, 5)
print(f"shape of y: {y.shape}")
# lets insert a singleton dimension
y = y.unsqueeze(1)
print(f"shape of y: {y.shape}")
```
**Permutation**
Sometimes our dimensions will be in the wrong order! For example, we may be dealing with RGB images with dim [3x48x64], but our pipeline expects the colour dimension to be the last dimension i.e. [48x64x3]. To get around this we can use ```.permute()```
```
# `x` has dimensions [color,image_height,image_width]
x = torch.rand(3, 48, 64)
# we want to permute our tensor to be [ image_height , image_width , color ]
x = x.permute(1, 2, 0)
# permute(1,2,0) means:
# the 0th dim of my new tensor = the 1st dim of my old tensor
# the 1st dim of my new tensor = the 2nd
# the 2nd dim of my new tensor = the 0th
print(x.shape)
```
You may also see ```.transpose()``` used. This works in a similar way as permute, but can only swap two dimensions at once.
**Concatenation**
In this example, we concatenate two matrices along rows (axis 0, the first element of the shape) vs. columns (axis 1, the second element of the shape). We can see that the first output tensor’s axis-0 length ( 6 ) is the sum of the two input tensors’ axis-0 lengths ( 3+3 ); while the second output tensor’s axis-1 length ( 8 ) is the sum of the two input tensors’ axis-1 lengths ( 4+4 ).
```
# Create two tensors of the same shape
x = torch.arange(12, dtype=torch.float32).reshape((3, 4))
y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
#concatenate them along rows
cat_rows = torch.cat((x, y), dim=0)
# concatenate along columns
cat_cols = torch.cat((x, y), dim=1)
# printing outputs
print('Concatenated by rows: shape{} \n {}'.format(list(cat_rows.shape), cat_rows))
print('\n Concatenated by colums: shape{} \n {}'.format(list(cat_cols.shape), cat_cols))
```
**Conversion to Other Python Objects**
Converting to a NumPy tensor, or vice versa, is easy. The converted result does not share memory. This minor inconvenience is actually quite important: when you perform operations on the CPU or on GPUs, you do not want to halt computation, waiting to see whether the NumPy package of Python might want to be doing something else with the same chunk of memory.
When converting to a numpy array, the information being tracked by the tensor will be lost i.e. the computational graph. This will be covered in detail when you are introduced to autograd tomorrow!
```
x = torch.randn(5)
print(f"x: {x} | x type: {x.type()}")
y = x.numpy()
print(f"y: {y} | y type: {type(y)}")
z = torch.tensor(y)
print(f"z: {z} | z type: {z.type()}")
```
To convert a size-1 tensor to a Python scalar, we can invoke the item function or Python’s built-in functions.
```
a = torch.tensor([3.5])
a, a.item(), float(a), int(a)
```
### Coding Exercise 2.3: Manipulating Tensors
Using a combination of the methods discussed above, complete the functions below.
**Function A**
This function takes in two 2D tensors $A$ and $B$ and returns the column sum of A multiplied by the sum of all the elmements of $B$ i.e. a scalar, e.g.,:
$ A = \begin{bmatrix}
1 & 1 \\
1 & 1
\end{bmatrix} \,$
and
$ B = \begin{bmatrix}
1 & 2 & 3\\
1 & 2 & 3
\end{bmatrix} \,$
so
$ \, Out = \begin{bmatrix} 2 & 2 \\
\end{bmatrix} \cdot 12 = \begin{bmatrix}
24 & 24\\
\end{bmatrix}$
**Function B**
This function takes in a square matrix $C$ and returns a 2D tensor consisting of a flattened $C$ with the index of each element appended to this tensor in the row dimension, e.g.,:
$ C = \begin{bmatrix}
2 & 3 \\
-1 & 10
\end{bmatrix} \,$
so
$ \, Out = \begin{bmatrix}
0 & 2 \\
1 & 3 \\
2 & -1 \\
3 & 10
\end{bmatrix}$
**Hint:** pay close attention to singleton dimensions
**Function C**
This function takes in two 2D tensors $D$ and $E$. If the dimensions allow it, this function returns the elementwise sum of $D$-shaped $E$, and $D$; else this function returns a 1D tensor that is the concatenation of the two tensors, e.g.,:
$ D = \begin{bmatrix}
1 & -1 \\
-1 & 3
\end{bmatrix} \,$
and
$ E = \begin{bmatrix}
2 & 3 & 0 & 2 \\
\end{bmatrix} \, $
so
$ \, Out = \begin{bmatrix}
3 & 2 \\
-1 & 5
\end{bmatrix}$
$ D = \begin{bmatrix}
1 & -1 \\
-1 & 3
\end{bmatrix}$
and
$ \, E = \begin{bmatrix}
2 & 3 & 0 \\
\end{bmatrix} \,$
so
$ \, Out = \begin{bmatrix}
1 & -1 & -1 & 3 & 2 & 3 & 0
\end{bmatrix}$
**Hint:** `torch.numel()` is an easy way of finding the number of elements in a tensor
```
def functionA(my_tensor1, my_tensor2):
"""
This function takes in two 2D tensors `my_tensor1` and `my_tensor2`
and returns the column sum of
`my_tensor1` multiplied by the sum of all the elmements of `my_tensor2`,
i.e., a scalar.
Args:
my_tensor1: torch.Tensor
my_tensor2: torch.Tensor
Retuns:
output: torch.Tensor
The multiplication of the column sum of `my_tensor1` by the sum of
`my_tensor2`.
"""
################################################
## TODO for students: complete functionA
raise NotImplementedError("Student exercise: complete function A")
################################################
# TODO multiplication the sum of the tensors
output = ...
return output
def functionB(my_tensor):
"""
This function takes in a square matrix `my_tensor` and returns a 2D tensor
consisting of a flattened `my_tensor` with the index of each element
appended to this tensor in the row dimension.
Args:
my_tensor: torch.Tensor
Retuns:
output: torch.Tensor
Concatenated tensor.
"""
################################################
## TODO for students: complete functionB
raise NotImplementedError("Student exercise: complete function B")
################################################
# TODO flatten the tensor `my_tensor`
my_tensor = ...
# TODO create the idx tensor to be concatenated to `my_tensor`
idx_tensor = ...
# TODO concatenate the two tensors
output = ...
return output
def functionC(my_tensor1, my_tensor2):
"""
This function takes in two 2D tensors `my_tensor1` and `my_tensor2`.
If the dimensions allow it, it returns the
elementwise sum of `my_tensor1`-shaped `my_tensor2`, and `my_tensor2`;
else this function returns a 1D tensor that is the concatenation of the
two tensors.
Args:
my_tensor1: torch.Tensor
my_tensor2: torch.Tensor
Retuns:
output: torch.Tensor
Concatenated tensor.
"""
################################################
## TODO for students: complete functionB
raise NotImplementedError("Student exercise: complete function C")
################################################
# TODO check we can reshape `my_tensor2` into the shape of `my_tensor1`
if ...:
# TODO reshape `my_tensor2` into the shape of `my_tensor1`
my_tensor2 = ...
# TODO sum the two tensors
output = ...
else:
# TODO flatten both tensors
my_tensor1 = ...
my_tensor2 = ...
# TODO concatenate the two tensors in the correct dimension
output = ...
return output
# add timing to airtable
atform.add_event('Coding Exercise 2.3: Manipulating Tensors')
## Implement the functions above and then uncomment the following lines to test your code
# print(functionA(torch.tensor([[1, 1], [1, 1]]), torch.tensor([[1, 2, 3], [1, 2, 3]])))
# print(functionB(torch.tensor([[2, 3], [-1, 10]])))
# print(functionC(torch.tensor([[1, -1], [-1, 3]]), torch.tensor([[2, 3, 0, 2]])))
# print(functionC(torch.tensor([[1, -1], [-1, 3]]), torch.tensor([[2, 3, 0]])))
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_ea1718cb.py)
```
tensor([24, 24])
tensor([[ 0, 2],
[ 1, 3],
[ 2, -1],
[ 3, 10]])
tensor([[ 3, 2],
[-1, 5]])
tensor([ 1, -1, -1, 3, 2, 3, 0])
```
## Section 2.4: GPUs
```
# @title Video 6: GPU vs CPU
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1nM4y1K7qx", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"9Mc9GFUtILY", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 6: GPU vs CPU')
display(out)
```
By default, when we create a tensor it will *not* live on the GPU!
```
x = torch.randn(10)
print(x.device)
```
When using Colab notebooks by default will not have access to a GPU. In order to start using GPUs we need to request one. We can do this by going to the runtime tab at the top of the page.
By following Runtime -> Change runtime type and selecting "GPU" from the Hardware Accelerator dropdown list, we can start playing with sending tensors to GPUs.
Once you have done this your runtime will restart and you will need to rerun the first setup cell to reimport PyTorch. Then proceed to the next cell.
(For more information on the GPU usage policy you can view in the appendix)
**Now we have a GPU**
The cell below should return True.
```
print(torch.cuda.is_available())
```
CUDA is an API developed by Nvidia for interfacing with GPUs. PyTorch provides us with a layer of abstraction, and allows us to launch CUDA kernels using pure Python. *NOTE I am assuming that GPU stuff might be covered in more detail on another day but there could be a bit more detail here.*
In short, we get the power of parallising our tensor computations on GPUs, whilst only writing (relatively) simple Python!
Here, we define the function `set_device`, which returns the device use in the notebook, i.e., `cpu` or `cuda`. Unless otherwise specified, we use this function on top of every tutorial, and we store the device variable such as
```python
DEVICE = set_device()
```
Let's define the function using the PyTorch package `torch.cuda`, which is lazily initialized, so we can always import it, and use `is_available()` to determine if our system supports CUDA.
```
def set_device():
device = "cuda" if torch.cuda.is_available() else "cpu"
if device != "cuda":
print("GPU is not enabled in this notebook. \n"
"If you want to enable it, in the menu under `Runtime` -> \n"
"`Hardware accelerator.` and select `GPU` from the dropdown menu")
else:
print("GPU is enabled in this notebook. \n"
"If you want to disable it, in the menu under `Runtime` -> \n"
"`Hardware accelerator.` and select `None` from the dropdown menu")
return device
```
Let's make some CUDA tensors!
```
# common device agnostic way of writing code that can run on cpu OR gpu
# that we provide for you in each of the tutorials
DEVICE = set_device()
# we can specify a device when we first create our tensor
x = torch.randn(2, 2, device=DEVICE)
print(x.dtype)
print(x.device)
# we can also use the .to() method to change the device a tensor lives on
y = torch.randn(2, 2)
print(f"y before calling to() | device: {y.device} | dtype: {y.type()}")
y = y.to(DEVICE)
print(f"y after calling to() | device: {y.device} | dtype: {y.type()}")
```
**Operations between cpu tensors and cuda tensors**
Note that the type of the tensor changed after calling ```.to()```. What happens if we try and perform operations on tensors on devices?
```
x = torch.tensor([0, 1, 2], device=DEVICE)
y = torch.tensor([3, 4, 5], device="cpu")
# Uncomment the following line and run this cell
# z = x + y
```
We cannot combine cuda tensors and cpu tensors in this fashion. If we want to compute an operation that combines tensors on different devices, we need to move them first! We can use the `.to()` method as before, or the `.cpu()` and `.cuda()` methods. Note that using the `.cuda()` will throw an error if CUDA is not enabled in your machine.
Genrally in this course all Deep learning is done on the GPU and any computation is done on the CPU, so sometimes we have to pass things back and forth so you'll see us call.
```
x = torch.tensor([0, 1, 2], device=DEVICE)
y = torch.tensor([3, 4, 5], device="cpu")
z = torch.tensor([6, 7, 8], device=DEVICE)
# moving to cpu
x = x.to("cpu") # alternatively, you can use x = x.cpu()
print(x + y)
# moving to gpu
y = y.to(DEVICE) # alternatively, you can use y = y.cuda()
print(y + z)
```
### Coding Exercise 2.4: Just how much faster are GPUs?
Below is a simple function `simpleFun`. Complete this function, such that it performs the operations:
- elementwise multiplication
- matrix multiplication
The operations should be able to perfomed on either the CPU or GPU specified by the parameter `device`. We will use the helper function `timeFun(f, dim, iterations, device)`.
```
dim = 10000
iterations = 1
def simpleFun(dim, device):
"""
Args:
dim: integer
device: "cpu" or "cuda"
Returns:
Nothing.
"""
###############################################
## TODO for students: recreate the function, but
## ensure all computations happens on the `device`
raise NotImplementedError("Student exercise: fill in the missing code to create the tensors")
###############################################
# 2D tensor filled with uniform random numbers in [0,1), dim x dim
x = ...
# 2D tensor filled with uniform random numbers in [0,1), dim x dim
y = ...
# 2D tensor filled with the scalar value 2, dim x dim
z = ...
# elementwise multiplication of x and y
a = ...
# matrix multiplication of x and y
b = ...
del x
del y
del z
del a
del b
## TODO: Implement the function above and uncomment the following lines to test your code
# timeFun(f=simpleFun, dim=dim, iterations=iterations)
# timeFun(f=simpleFun, dim=dim, iterations=iterations, device=DEVICE)
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_232a94a4.py)
Sample output (depends on your hardware)
```
time taken for 1 iterations of simpleFun(10000, cpu): 23.74070
time taken for 1 iterations of simpleFun(10000, cuda): 0.87535
```
**Discuss!**
Try and reduce the dimensions of the tensors and increase the iterations. You can get to a point where the cpu only function is faster than the GPU function. Why might this be?
## Section 2.5: Datasets and Dataloaders
```
# @title Video 7: Getting Data
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1744y127SQ", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"LSkjPM1gFu0", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 7: Getting Data')
display(out)
```
When training neural network models you will be working with large amounts of data. Fortunately, PyTorch offers some great tools that help you organize and manipulate your data samples.
```
# Import dataset and dataloaders related packages
from torchvision import datasets
from torchvision.transforms import ToTensor
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, Grayscale
```
**Datasets**
The `torchvision` package gives you easy access to many of the publicly available datasets. Let's load the [CIFAR10](https://www.cs.toronto.edu/~kriz/cifar.html) dataset, which contains color images of 10 different classes, like vehicles and animals.
Creating an object of type `datasets.CIFAR10` will automatically download and load all images from the dataset. The resulting data structure can be treated as a list containing data samples and their corresponding labels.
```
# Download and load the images from the CIFAR10 dataset
cifar10_data = datasets.CIFAR10(
root="data", # path where the images will be stored
download=True, # all images should be downloaded
transform=ToTensor() # transform the images to tensors
)
# Print the number of samples in the loaded dataset
print(f"Number of samples: {len(cifar10_data)}")
print(f"Class names: {cifar10_data.classes}")
```
We have 50000 samples loaded. Now let's take a look at one of them in detail. Each sample consists of an image and its corresponding label.
```
# Choose a random sample
random.seed(2021)
image, label = cifar10_data[random.randint(0, len(cifar10_data))]
print(f"Label: {cifar10_data.classes[label]}")
print(f"Image size: {image.shape}")
```
Color images are modeled as 3 dimensional tensors. The first dimension corresponds to the channels (C) of the image (in this case we have RGB images). The second dimensions is the height (H) of the image and the third is the width (W). We can denote this image format as C × H × W.
### Coding Exercise 2.5: Display an image from the dataset
Let's try to display the image using `matplotlib`. The code below will not work, because `imshow` expects to have the image in a different format - $H \times W \times C$.
You need to reorder the dimensions of the tensor using the `permute` method of the tensor. PyTorch `torch.permute(*dims)` rearranges the original tensor according to the desired ordering and returns a new multidimensional rotated tensor. The size of the returned tensor remains the same as that of the original.
**Code hint:**
```python
# create a tensor of size 2 x 4
input_var = torch.randn(2, 4)
# print its size and the tensor
print(input_var.size())
print(input_var)
# dimensions permuted
input_var = input_var.permute(1, 0)
# print its size and the permuted tensor
print(input_var.size())
print(input_var)
```
```
# TODO: Uncomment the following line to see the error that arises from the current image format
# plt.imshow(image)
# TODO: Comment the above line and fix this code by reordering the tensor dimensions
# plt.imshow(image.permute(...))
# plt.show()
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_b04bd357.py)
*Example output:*
<img alt='Solution hint' align='left' width=835.0 height=827.0 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W1D1_BasicsAndPytorch/static/W1D1_Tutorial1_Solution_b04bd357_0.png>
```
#@title Video 8: Train and Test
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1rV411H7s5", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"JokSIuPs-ys", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 8: Train and Test')
display(out)
```
**Training and Test Datasets**
When loading a dataset, you can specify if you want to load the training or the test samples using the `train` argument. We can load the training and test datasets separately. For simplicity, today we will not use both datasets separately, but this topic will be adressed in the next days.
```
# Load the training samples
training_data = datasets.CIFAR10(
root="data",
train=True,
download=True,
transform=ToTensor()
)
# Load the test samples
test_data = datasets.CIFAR10(
root="data",
train=False,
download=True,
transform=ToTensor()
)
# @title Video 9: Data Augmentation - Transformations
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV19B4y1N77t", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"sjegA9OBUPw", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 9: Data Augmentation - Transformations')
display(out)
```
**Dataloader**
Another important concept is the `Dataloader`. It is a wrapper around the `Dataset` that splits it into minibatches (important for training the neural network) and makes the data iterable. The `shuffle` argument is used to shuffle the order of the samples across the minibatches.
```
# Create dataloaders with
train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)
test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)
```
*Reproducibility:* DataLoader will reseed workers following Randomness in multi-process data loading algorithm. Use `worker_init_fn()` and a `generator` to preserve reproducibility:
```python
def seed_worker(worker_id):
worker_seed = torch.initial_seed() % 2**32
numpy.random.seed(worker_seed)
random.seed(worker_seed)
g_seed = torch.Generator()
g_seed.manual_seed(my_seed)
DataLoader(
train_dataset,
batch_size=batch_size,
num_workers=num_workers,
worker_init_fn=seed_worker,
generator=g_seed
)
```
**Note:** For the `seed_worker` to have an effect, `num_workers` should be 2 or more.
We can now query the next batch from the data loader and inspect it. For this we need to convert the dataloader object to a Python iterator using the function `iter` and then we can query the next batch using the function `next`.
We can now see that we have a 4D tensor. This is because we have a 64 images in the batch ($B$) and each image has 3 dimensions: channels ($C$), height ($H$) and width ($W$). So, the size of the 4D tensor is $B \times C \times H \times W$.
```
# Load the next batch
batch_images, batch_labels = next(iter(train_dataloader))
print('Batch size:', batch_images.shape)
# Display the first image from the batch
plt.imshow(batch_images[0].permute(1, 2, 0))
plt.show()
```
**Transformations**
Another useful feature when loading a dataset is applying transformations on the data - color conversions, normalization, cropping, rotation etc. There are many predefined transformations in the `torchvision.transforms` package and you can also combine them using the `Compose` transform. Checkout the [pytorch documentation](https://pytorch.org/vision/stable/transforms.html) for details.
### Coding Exercise 2.6: Load the CIFAR10 dataset as grayscale images
The goal of this excercise is to load the images from the CIFAR10 dataset as grayscale images. Note that we rerun the `set_seed` function to ensure reproducibility.
```
def my_data_load():
###############################################
## TODO for students: load the CIFAR10 data,
## but as grayscale images and not as RGB colored.
raise NotImplementedError("Student exercise: fill in the missing code to load the data")
###############################################
## TODO Load the CIFAR10 data using a transform that converts the images to grayscale tensors
data = datasets.CIFAR10(...,
transform=...)
# Display a random grayscale image
image, label = data[random.randint(0, len(data))]
plt.imshow(image.squeeze(), cmap="gray")
plt.show()
return data
set_seed(seed=2021)
## After implementing the above code, uncomment the following lines to test your code
# data = my_data_load()
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_6052d728.py)
*Example output:*
<img alt='Solution hint' align='left' width=835.0 height=827.0 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W1D1_BasicsAndPytorch/static/W1D1_Tutorial1_Solution_6052d728_1.png>
---
# Section 3: Neural Networks
*Time estimate: ~1 hour 30 mins (excluding video)*
Now it's time for you to create your first neural network using PyTorch. This section will walk you through the process of:
- Creating a simple neural network model
- Training the network
- Visualizing the results of the network
- Tweeking the network
```
# @title Video 10: CSV Files
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1xy4y1T7kv", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"JrC_UAJWYKU", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 10: CSV Files')
display(out)
```
## Section 3.1: Data Loading
First we need some sample data to train our network on. You can use the function below to generate an example dataset consisting of 2D points along two interleaving half circles. The data will be stored in a file called `sample_data.csv`. You can inspect the file directly in Colab by going to Files on the left side and opening the CSV file.
```
# @title Generate sample data
# @markdown we used `scikit-learn` module
from sklearn.datasets import make_moons
# Create a dataset of 256 points with a little noise
X, y = make_moons(256, noise=0.1)
# Store the data as a Pandas data frame and save it to a CSV file
df = pd.DataFrame(dict(x0=X[:,0], x1=X[:,1], y=y))
df.to_csv('sample_data.csv')
```
Now we can load the data from the CSV file using the Pandas library. Pandas provides many functions for reading files in various formats. When loading data from a CSV file, we can reference the columns directly by their names.
```
# Load the data from the CSV file in a Pandas DataFrame
data = pd.read_csv("sample_data.csv")
# Create a 2D numpy array from the x0 and x1 columns
X_orig = data[["x0", "x1"]].to_numpy()
# Create a 1D numpy array from the y column
y_orig = data["y"].to_numpy()
# Print the sizes of the generated 2D points X and the corresponding labels Y
print(f"Size X:{X_orig.shape}")
print(f"Size y:{y_orig.shape}")
# Visualize the dataset. The color of the points is determined by the labels `y_orig`.
plt.scatter(X_orig[:, 0], X_orig[:, 1], s=40, c=y_orig)
plt.show()
```
**Prepare Data for PyTorch**
Now let's prepare the data in a format suitable for PyTorch - convert everything into tensors.
```
# Initialize the device variable
DEVICE = set_device()
# Convert the 2D points to a float32 tensor
X = torch.tensor(X_orig, dtype=torch.float32)
# Upload the tensor to the device
X = X.to(DEVICE)
print(f"Size X:{X.shape}")
# Convert the labels to a long interger tensor
y = torch.from_numpy(y_orig).type(torch.LongTensor)
# Upload the tensor to the device
y = y.to(DEVICE)
print(f"Size y:{y.shape}")
```
## Section 3.2: Create a Simple Neural Network
```
# @title Video 11: Generating the Neural Network
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1fK4y1M74a", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"PwSzRohUvck", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 11: Generating the Neural Network')
display(out)
```
For this example we want to have a simple neural network consisting of 3 layers:
- 1 input layer of size 2 (our points have 2 coordinates)
- 1 hidden layer of size 16 (you can play with different numbers here)
- 1 output layer of size 2 (we want the have the scores for the two classes)
During the course you will deal with differend kinds of neural networks. On Day 2 we will focus on linear networks, but you will work with some more complicated architectures in the next days. The example here is meant to demonstrate the process of creating and training a neural network end-to-end.
**Programing the Network**
PyTorch provides a base class for all neural network modules called [`nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html). You need to inherit from `nn.Module` and implement some important methods:
`__init__`
In the `__init__` method you need to define the structure of your network. Here you will specify what layers will the network consist of, what activation functions will be used etc.
`forward`
All neural network modules need to implement the `forward` method. It specifies the computations the network needs to do when data is passed through it.
`predict`
This is not an obligatory method of a neural network module, but it is a good practice if you want to quickly get the most likely label from the network. It calls the `forward` method and chooses the label with the highest score.
`train`
This is also not an obligatory method, but it is a good practice to have. The method will be used to train the network parameters and will be implemented later in the notebook.
> Note that you can use the `__call__` method of a module directly and it will invoke the `forward` method: `net()` does the same as `net.forward()`.
```
# Inherit from nn.Module - the base class for neural network modules provided by Pytorch
class NaiveNet(nn.Module):
# Define the structure of your network
def __init__(self):
super(NaiveNet, self).__init__()
# The network is defined as a sequence of operations
self.layers = nn.Sequential(
nn.Linear(2, 16), # Transformation from the input to the hidden layer
nn.ReLU(), # Activation function (ReLU) is a non-linearity which is widely used because it reduces computation. The function returns 0 if it receives any
# negative input, but for any positive value x, it returns that value back.
nn.Linear(16, 2), # Transformation from the hidden to the output layer
)
# Specify the computations performed on the data
def forward(self, x):
# Pass the data through the layers
return self.layers(x)
# Choose the most likely label predicted by the network
def predict(self, x):
# Pass the data through the networks
output = self.forward(x)
# Choose the label with the highest score
return torch.argmax(output, 1)
# Train the neural network (will be implemented later)
def train(self, X, y):
pass
```
**Check that your network works**
Create an instance of your model and visualize it
```
# Create new NaiveNet and transfer it to the device
model = NaiveNet().to(DEVICE)
# Print the structure of the network
print(model)
```
### Coding Exercise 3.2: Classify some samples
Now let's pass some of the points of our dataset through the network and see if it works. You should not expect the network to actually classify the points correctly, because it has not been trained yet.
The goal here is just to get some experience with the data structures that are passed to the forward and predict methods and their results.
```
## Get the samples
# X_samples = ...
# print("Sample input:\n", X_samples)
## Do a forward pass of the network
# output = ...
# print("\nNetwork output:\n", output)
## Predict the label of each point
# y_predicted = ...
# print("\nPredicted labels:\n", y_predicted)
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_af8ae0ff.py)
```
Sample input:
tensor([[ 0.9066, 0.5052],
[-0.2024, 1.1226],
[ 1.0685, 0.2809],
[ 0.6720, 0.5097],
[ 0.8548, 0.5122]], device='cuda:0')
Network output:
tensor([[ 0.1543, -0.8018],
[ 2.2077, -2.9859],
[-0.5745, -0.0195],
[ 0.1924, -0.8367],
[ 0.1818, -0.8301]], device='cuda:0', grad_fn=<AddmmBackward>)
Predicted labels:
tensor([0, 0, 1, 0, 0], device='cuda:0')
```
## Section 3.3: Train Your Neural Network
```
# @title Video 12: Train the Network
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1v54y1n7CS", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"4MIqnE4XPaA", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 12: Train the Network')
display(out)
```
Now it is time to train your network on your dataset. Don't worry if you don't fully understand everything yet - we will cover training in much more details in the next days. For now, the goal is just to see your network in action!
You will usually implement the `train` method directly when implementing your class `NaiveNet`. Here, we will implement it as a function outside of the class in order to have it in a ceparate cell.
```
# @title Helper function to plot the decision boundary
# Code adapted from this notebook: https://jonchar.net/notebooks/Artificial-Neural-Network-with-Keras/
from pathlib import Path
def plot_decision_boundary(model, X, y, device):
# Transfer the data to the CPU
X = X.cpu().numpy()
y = y.cpu().numpy()
# Check if the frames folder exists and create it if needed
frames_path = Path("frames")
if not frames_path.exists():
frames_path.mkdir()
# Set min and max values and give it some padding
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
h = 0.01
# Generate a grid of points with distance h between them
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# Predict the function value for the whole gid
grid_points = np.c_[xx.ravel(), yy.ravel()]
grid_points = torch.from_numpy(grid_points).type(torch.FloatTensor)
Z = model.predict(grid_points.to(device)).cpu().numpy()
Z = Z.reshape(xx.shape)
# Plot the contour and training examples
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.binary)
# Implement the train function given a training dataset X and correcsponding labels y
def train(model, X, y):
# The Cross Entropy Loss is suitable for classification problems
loss_function = nn.CrossEntropyLoss()
# Create an optimizer (Stochastic Gradient Descent) that will be used to train the network
learning_rate = 1e-2
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# Number of epochs
epochs = 15000
# List of losses for visualization
losses = []
for i in range(epochs):
# Pass the data through the network and compute the loss
# We'll use the whole dataset during the training instead of using batches
# in to order to keep the code simple for now.
y_logits = model.forward(X)
loss = loss_function(y_logits, y)
# Clear the previous gradients and compute the new ones
optimizer.zero_grad()
loss.backward()
# Adapt the weights of the network
optimizer.step()
# Store the loss
losses.append(loss.item())
# Print the results at every 1000th epoch
if i % 1000 == 0:
print(f"Epoch {i} loss is {loss.item()}")
plot_decision_boundary(model, X, y, DEVICE)
plt.savefig('frames/{:05d}.png'.format(i))
return losses
# Create a new network instance a train it
model = NaiveNet().to(DEVICE)
losses = train(model, X, y)
```
**Plot the loss during training**
Plot the loss during the training to see how it reduces and converges.
```
plt.plot(np.linspace(1, len(losses), len(losses)), losses)
plt.xlabel("Epoch")
plt.ylabel("Loss")
# @title Visualize the training process
# @markdown ### Execute this cell!
!pip install imageio --quiet
!pip install pathlib --quiet
import imageio
from IPython.core.interactiveshell import InteractiveShell
from IPython.display import Image, display
from pathlib import Path
InteractiveShell.ast_node_interactivity = "all"
# Make a list with all images
images = []
for i in range(10):
filename = "frames/0"+str(i)+"000.png"
images.append(imageio.imread(filename))
# Save the gif
imageio.mimsave('frames/movie.gif', images)
gifPath = Path("frames/movie.gif")
with open(gifPath,'rb') as f:
display(Image(data=f.read(), format='png'))
# @title Video 13: Play with it
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1Cq4y1W7BH", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"_GGkapdOdSY", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 13: Play with it')
display(out)
```
### Exercise 3.3: Tweak your Network
You can now play around with the network a little bit to get a feeling of what different parameters are doing. Here are some ideas what you could try:
- Increase or decrease the number of epochs for training
- Increase or decrease the size of the hidden layer
- Add one additional hidden layer
Can you get the network to better fit the data?
```
# @title Video 14: XOR Widget
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1mB4y1N7QS", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"oTr1nE2rCWg", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
# add timing to airtable
atform.add_event('Video 14: XOR Widget')
display(out)
```
Exclusive OR (XOR) logical operation gives a true (`1`) output when the number of true inputs is odd. That is, a true output result if one, and only one, of the inputs to the gate is true. If both inputs are false (`0`) or both are true or false output results. Mathematically speaking, XOR represents the inequality function, i.e., the output is true if the inputs are not alike; otherwise, the output is false.
In case of two inputs ($X$ and $Y$) the following truth table is applied:
\begin{array}{ccc}
X & Y & \text{XOR} \\
\hline
0 & 0 & 0 \\
0 & 1 & 1 \\
1 & 0 & 1 \\
1 & 1 & 0 \\
\end{array}
Here, with `0`, we denote `False`, and with `1` we denote `True` in boolean terms.
### Interactive Demo 3.3: Solving XOR
Here we use an open source and famous visualization widget developed by Tensorflow team available [here](https://github.com/tensorflow/playground).
* Play with the widget and observe that you can not solve the continuous XOR dataset.
* Now add one hidden layer with three units, play with the widget, and set weights by hand to solve this dataset perfectly.
For the second part, you should set the weights by clicking on the connections and either type the value or use the up and down keys to change it by one increment. You could also do the same for the biases by clicking on the tiny square to each neuron's bottom left.
Even though there are infinitely many solutions, a neat solution when $f(x)$ is ReLU is:
\begin{equation}
y = f(x_1)+f(x_2)-f(x_1+x_2)
\end{equation}
Try to set the weights and biases to implement this function after you played enough :)
```
# @markdown ###Play with the parameters to solve XOR
from IPython.display import HTML
HTML('<iframe width="1020" height="660" src="https://playground.arashash.com/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=&seed=0.91390&showTestData=false&discretize=false&percTrainData=90&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false" allowfullscreen></iframe>')
# @markdown Do you think we can solve the discrete XOR (only 4 possibilities) with only 2 hidden units?
w1_min_xor = 'Select' #@param ['Select', 'Yes', 'No']
if w1_min_xor == 'No':
print("Correct!")
else:
print("How about giving it another try?")
```
---
# Section 4: Ethics And Course Info
```
# @title Video 15: Ethics
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1Hw41197oB", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"Kt6JLi3rUFU", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
display(out)
# @title Video 16: Be a group
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1j44y1272h", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"Sfp6--d_H1A", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
display(out)
# @title Video 17: Syllabus
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1iB4y1N7uQ", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"cDvAqG_hAvQ", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
display(out)
```
Meet our lecturers:
Week 1: the building blocks
* [Konrad Kording](https://kordinglab.com)
* [Andrew Saxe](https://www.saxelab.org/)
* [Surya Ganguli](https://ganguli-gang.stanford.edu/)
* [Ioannis Mitliagkas](http://mitliagkas.github.io/)
* [Lyle Ungar](https://www.cis.upenn.edu/~ungar/)
Week 2: making things work
* [Alona Fyshe](https://webdocs.cs.ualberta.ca/~alona/)
* [Alexander Ecker](https://eckerlab.org/)
* [James Evans](https://sociology.uchicago.edu/directory/james-evans)
* [He He](https://hhexiy.github.io/)
* [Vikash Gilja](https://tnel.ucsd.edu/bio) and [Akash Srivastava](https://akashgit.github.io/)
Week 3: more magic
* [Tim Lillicrap](https://contrastiveconvergence.net/~timothylillicrap/index.php) and [Blake Richards](https://www.mcgill.ca/neuro/blake-richards-phd)
* [Jane Wang](http://www.janexwang.com/) and [Feryal Behbahani](https://feryal.github.io/)
* [Tim Lillicrap](https://contrastiveconvergence.net/~timothylillicrap/index.php) and [Blake Richards](https://www.mcgill.ca/neuro/blake-richards-phd)
* [Josh Vogelstein](https://jovo.me/) and [Vincenzo Lamonaco](https://www.vincenzolomonaco.com/)
Now, go to the [visualization of ICLR papers](https://iclr.cc/virtual/2021/paper_vis.html). Read a few abstracts. Look at the various clusters. Where do you see yourself in this map?
---
# Submit to Airtable
```
# @title Video 18: Submission info
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id=f"BV1e44y127ti", width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
display(video)
out1 = widgets.Output()
with out1:
from IPython.display import YouTubeVideo
video = YouTubeVideo(id=f"JwTn7ej2dq8", width=854, height=480, fs=1, rel=0)
print("Video available at https://youtube.com/watch?v=" + video.id)
display(video)
out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')
display(out)
```
This is Darryl, the Deep Learning Dapper Lion, and he's here to teach you about content submission to airtable.
<br>
<img src="https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/static/DapperLion.png" alt="Darryl">
<br><br>
At the end of each tutorial there will be an <b>Airtable Submission Cell</b>. Run the cell to generate the airtable submission button and click on it to submit your information to airtable.
<br><br>
if it is the last tutorial of the day your button will look like this and take you to the end of day survey:
<br>
<img src="https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/static/SurveyButton.png?raw=1" alt="Survey Button">
otherwise it look like this:
<br>
<img src="https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/static/AirtableSubmissionButton.png?raw=1" alt="Submission Button">
<br><br>
It is critical that you push the submit button for every tutorial you run. <b> even if you don't finish the tutorial, still submit!</b>
Submitting is the only way we can verify that you attempted each tutorial, which is critical for us to be able to track your progress.
### TL;DR: Basic tutorial workflow
1. work through the tutorial, answering Think! questions and code exercises
2. at end each tutorial, (even if tutorial incomplete) run the airtable submission code cell
3. Push the submission button
4. if the last tutorial of the day, Submission button will also take you to the end of the day survey on a new page. complete that and submit it.
### Submission FAQs:
1. What if I want to change my answers to previous discussion questions?
> you are free to change and resubmit any of the answers and Think! questions as many times as you like. However, <b> please only run the airtable submission code and click on the link once you are ready to submit</b>.
2. Okay, but what if I submitted my airtable anyway and reallly want to resubmit?
> After making changes, you can re-run the airtable submission cell code cell. This will result in a second submission from you for the data. This will make Darryl sad as it will be more work for him to clean up the data later.
3. HELP! I accidentally ran the code to generate the airtable submission button before I was ready to submit! what do I do?
> If you run the code to generate the link, anything that happens afterwards will not be captured. Complete the tutorial and make sure to re-run the airtable submission again when you are finished before pressing the submission button.
4. What if I want to work on this on my own later, should I wait to submit until I'm finished?
> Please submit wherever you are at the end of the day. It's graet that you want to keep working on this, but it's important to see the places where we tried things that didn't quite work out, so we can fix them for next year.
Finally, we try to keep the airtable code as hidden as possible, but if you ever see any calls to `atform` such as `atform.add_event()` in the coding exercises, just know that is for saving airtable information only.<b> It will not affect the code that is being run around it in any way</b> , so please do not modify, comment out, or worry about any of those lines of code.
<br><br><br>
Now, lets try submitting today's course to Airtable by running the next cell and clicking the button when it appears.
```
# @title Airtable Submission Link
from IPython import display as IPyDisplay
IPyDisplay.HTML(
f"""
<div>
<a href= "{atform.url()}" target="_blank">
<img src="https://github.com/NeuromatchAcademy/course-content-dl/blob/main/tutorials/static/SurveyButton.png?raw=1"
alt="button link to survey" style="width:410px"></a>
</div>""" )
```
---
# Bonus - 60 years of Machine Learning Research in one Plot
by [Hendrik Strobelt](http://hendrik.strobelt.com) (MIT-IBM Watson AI Lab) with support from Benjamin Hoover.
In this notebook we visualize a subset* of 3,300 articles retreived from the AllenAI [S2ORC dataset](https://github.com/allenai/s2orc). We represent each paper by a position that is output of a dimensionality reduction method applied to a vector representation of each paper. The vector representation is output of a neural network.
*The selection is very biased on the keywords and methodology we used to filter. Please see the details section to learn about what we did.
```
# @title Import `altair` and load the data
!pip install altair vega_datasets --quiet
import requests
import altair as alt # altair is defining data visualizations
# Source data files
# Position data file maps ID to x,y positions
# original link: http://gltr.io/temp/ml_regexv1_cs_ma_citation+_99perc.pos_umap_cosine_100_d0.1.json
POS_FILE = 'https://osf.io/qyrfn/download'
# original link: http://gltr.io/temp/ml_regexv1_cs_ma_citation+_99perc_clean.csv
# Metadata file maps ID to title, abstract, author,....
META_FILE = 'https://osf.io/vfdu6/download'
# data loading and wrangling
def load_data():
positions = pd.read_json(POS_FILE)
positions[['x', 'y']] = positions['pos'].to_list()
meta = pd.read_csv(META_FILE)
return positions.merge(meta, left_on='id', right_on='paper_id')
# load data
data = load_data()
# @title Define Visualization using ALtair
YEAR_PERIOD = "quinquennial" # @param
selection = alt.selection_multi(fields=[YEAR_PERIOD], bind='legend')
data[YEAR_PERIOD] = (data["year"] / 5.0).apply(np.floor) * 5
chart = alt.Chart(data[["x", "y", "authors", "title", YEAR_PERIOD, "citation_count"]], width=800,
height=800).mark_circle(radius=2, opacity=0.2).encode(
alt.Color(YEAR_PERIOD+':O',
scale=alt.Scale(scheme='viridis', reverse=False, clamp=True, domain=list(range(1955,2020,5))),
# legend=alt.Legend(title='Total Records')
),
alt.Size('citation_count',
scale=alt.Scale(type="pow", exponent=1, range=[15, 300])
),
alt.X('x:Q',
scale=alt.Scale(zero=False), axis=alt.Axis(labels=False)
),
alt.Y('y:Q',
scale=alt.Scale(zero=False), axis=alt.Axis(labels=False)
),
tooltip=['title', 'authors'],
# size='citation_count',
# color="decade:O",
opacity=alt.condition(selection, alt.value(.8), alt.value(0.2)),
).add_selection(
selection
).interactive()
```
Lets look at the Visualization. Each dot represents one paper. Close dots mean that the respective papers are closer related than distant ones. The color indicates the 5-year period of when the paper was published. The dot size indicates the citation count (within S2ORC corpus) as of July 2020.
The view is **interactive** and allows for three main interactions. Try them and play around.
1. hover over a dot to see a tooltip (title, author)
2. select a year in the legend (right) to filter dots
2. zoom in/out with scroll -- double click resets view
```
chart
```
## Questions
By playing around, can you find some answers to the follwing questions?
1. Can you find topical clusters? What cluster might occur because of a filtering error?
2. Can you see a temporal trend in the data and clusters?
2. Can you determine when deep learning methods started booming ?
3. Can you find the key papers that where written before the DL "winter" that define milestones for a cluster? (tipp: look for large dots of different color)
## Methods
Here is what we did:
1. Filtering of all papers who fullfilled the criterria:
- are categorized as `Computer Science` or `Mathematics`
- one of the following keywords appearing in title or abstract: `"machine learning|artificial intelligence|neural network|(machine|computer) vision|perceptron|network architecture| RNN | CNN | LSTM | BLEU | MNIST | CIFAR |reinforcement learning|gradient descent| Imagenet "`
2. per year, remove all papers that are below the 99 percentile of citation count in that year
3. embed each paper by using abstract+title in SPECTER model
4. project based on embedding using UMAP
5. visualize using Altair
### Find Authors
```
# @title Edit the `AUTHOR_FILTER` variable to full text search for authors.
AUTHOR_FILTER = "Rush " # @param space at the end means "word border"
### Don't ignore case when searching...
FLAGS = 0
### uncomment do ignore case
# FLAGS = re.IGNORECASE
## --- FILTER CODE.. make it your own ---
import re
data['issel'] = data['authors'].str.contains(AUTHOR_FILTER, na=False, flags=FLAGS, )
if data['issel'].mean()<0.0000000001:
print('No match found')
## --- FROM HERE ON VIS CODE ---
alt.Chart(data[["x", "y", "authors", "title", YEAR_PERIOD, "citation_count", "issel"]], width=800,
height=800) \
.mark_circle(stroke="black", strokeOpacity=1).encode(
alt.Color(YEAR_PERIOD+':O',
scale=alt.Scale(scheme='viridis', reverse=False),
# legend=alt.Legend(title='Total Records')
),
alt.Size('citation_count',
scale=alt.Scale(type="pow", exponent=1, range=[15, 300])
),
alt.StrokeWidth('issel:Q', scale=alt.Scale(type="linear", domain=[0,1], range=[0, 2]), legend=None),
alt.Opacity('issel:Q', scale=alt.Scale(type="linear", domain=[0,1], range=[.2, 1]), legend=None),
alt.X('x:Q',
scale=alt.Scale(zero=False), axis=alt.Axis(labels=False)
),
alt.Y('y:Q',
scale=alt.Scale(zero=False), axis=alt.Axis(labels=False)
),
tooltip=['title', 'authors'],
).interactive()
```
---
# Appendix
## Official PyTorch resources:
### Tutorials
https://pytorch.org/tutorials/
### Documentation
https://pytorch.org/docs/stable/tensors.html (tensor methods)
https://pytorch.org/docs/stable/tensors.html#torch.Tensor.view (The view method in particular)
https://pytorch.org/vision/stable/datasets.html (pre-loaded image datasets)
## Google Colab Resources:
https://research.google.com/colaboratory/faq.html (FAQ including guidance on GPU usage)
## Books for reference:
https://www.deeplearningbook.org/ (Deep Learning by Ian Goodfellow, Yoshua Bengio and Aaron Courville)
| github_jupyter |
```
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib import animation
from IPython.display import HTML
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
%matplotlib inline
# Set up colors:
color_map = ListedColormap(['#1b9e77', '#d95f02', '#7570b3'])
# Make raw data using blobs
X, y = make_blobs(
n_samples=200,
n_features=2,
centers=3,
cluster_std=0.5,
shuffle=True,
random_state=0
)
# Plot the raw data:
plt.scatter(X[:,0], X[:, 1], c=y, cmap=color_map)
# Define some initial centers, these are designed to be "bad":
initial = np.array(
[
[-3.0, 0.0],
[-2.0, 0.0],
[-1.0, 0.0],
]
)
y_c = [0, 1, 2]
# Plot the initial situation:
fig0, ax0 = plt.subplots(constrained_layout=True)
ax0.scatter(X[:,0], X[:, 1], c=y, cmap=color_map)
ax0.scatter(initial[:,0], initial[:, 1],
c=y_c, cmap=color_map, marker='X', edgecolors='black', s=150)
ax0.text(-3, 5, 'Iteration: 0', fontsize='xx-large')
xlim = ax0.get_xlim()
ylim = ax0.get_ylim()
results = [(np.full_like(y, 0), initial)]
# Run clustering for different number of maximum iterations:
max_clusters = 15
for iterations in range(1, 15):
km = KMeans(n_clusters=3, init=initial, n_init=1, max_iter=iterations,
random_state=0)
y_km = km.fit_predict(X)
results.append((y_km, km.cluster_centers_))
figi, axi = plt.subplots(constrained_layout=True)
axi.scatter(X[:, 0], X[:, 1], c=y_km, cmap=color_map)
axi.set_xlim(xlim)
axi.set_ylim(ylim)
axi.text(-3, 5, 'Iteration: {}'.format(iterations), fontsize='xx-large')
axi.scatter(km.cluster_centers_[:, 0],
km.cluster_centers_[:, 1],
c=y_c, cmap=color_map,
marker='X', edgecolors='black', s=150)
%%capture
# Create an animation:
fig2, ax2 = plt.subplots(constrained_layout=True)
ax2.set_xlim(xlim)
ax2.set_ylim(ylim)
yi, centers = results[0]
scat = ax2.scatter(X[:, 0], X[:, 1])
cent = ax2.scatter(centers[:, 0], centers[:, 1], c=y_c, cmap=color_map,
marker='X', edgecolors='black', s=250)
text = ax2.text(-3, 5, 'Iteration: 0', fontsize='xx-large')
def animate(i):
"""Update the animation."""
yi, centers = results[i]
cent.set_offsets(centers)
text.set_text('Iteration: {}'.format(i))
if i == 0:
colors = ['#377eb8' for _ in yi]
else:
colors = [color_map.colors[j] for j in yi]
scat.set_facecolors(colors)
return (cent, scat, text)
anim = animation.FuncAnimation(fig2, animate,
frames=max_clusters,
interval=300, blit=True, repeat=True)
HTML(anim.to_jshtml())
```
| github_jupyter |
# Programming Assignment
## Готовим LDA по рецептам
Как вы уже знаете, в тематическом моделировании делается предположение о том, что для определения тематики порядок слов в документе не важен; об этом гласит гипотеза <<мешка слов>>. Сегодня мы будем работать с несколько нестандартной для тематического моделирования коллекцией, которую можно назвать <<мешком ингредиентов>>, потому что на состоит из рецептов блюд разных кухонь. Тематические модели ищут слова, которые часто вместе встречаются в документах, и составляют из них темы. Мы попробуем применить эту идею к рецептам и найти кулинарные <<темы>>. Эта коллекция хороша тем, что не требует предобработки. Кроме того, эта задача достаточно наглядно иллюстрирует принцип работы тематических моделей.
Для выполнения заданий, помимо часто используемых в курсе библиотек, потребуются модули json и gensim. Первый входит в дистрибутив Anaconda, второй можно поставить командой
pip install gensim
или
conda install gensim
Построение модели занимает некоторое время. На ноутбуке с процессором Intel Core i7 и тактовой частотой 2400 МГц на построение одной модели уходит менее 10 минут.
### Загрузка данных
Коллекция дана в json-формате: для каждого рецепта известны его id, кухня ("cuisine") и список ингредиентов, в него входящих. Загрузить данные можно с помощью модуля json (он входит в дистрибутив Anaconda):
```
import json
with open("recipes.json") as f:
recipes = json.load(f)
print recipes[1]
```
### Составление корпуса
```
from gensim import corpora, models
import numpy as np
```
Наша коллекция небольшая и влезает в оперативную память. Gensim может работать с такими данными и не требует их сохранения на диск в специальном формате. Для этого коллекция должна быть представлена в виде списка списков, каждый внутренний список соответствует отдельному документу и состоит из его слов. Пример коллекции из двух документов:
[["hello", "world"], ["programming", "in", "python"]]
Преобразуем наши данные в такой формат, а затем создадим объекты corpus и dictionary, с которыми будет работать модель.
```
texts = [recipe["ingredients"] for recipe in recipes]
dictionary = corpora.Dictionary(texts) # составляем словарь
corpus = [dictionary.doc2bow(text) for text in texts] # составляем корпус документов
corpus[0]
print texts[0]
print corpus[0]
```
У объекта dictionary есть две полезных переменных: dictionary.id2token и dictionary.token2id; эти словари позволяют находить соответствие между ингредиентами и их индексами.
### Обучение модели
Вам может понадобиться [документация](https://radimrehurek.com/gensim/models/ldamodel.html) LDA в gensim.
__Задание 1.__ Обучите модель LDA с 40 темами, установив количество проходов по коллекции 5 и оставив остальные параметры по умолчанию. Затем вызовите метод модели show_topics, указав количество тем 40 и количество токенов 10, и сохраните результат (топы ингредиентов в темах) в отдельную переменную. Если при вызове метода show_topics указать параметр formatted=True, то топы ингредиентов будет удобно выводить на печать, если formatted=False, будет удобно работать со списком программно. Выведите топы на печать, рассмотрите темы, а затем ответьте на вопрос:
Сколько раз ингредиенты "salt", "sugar", "water", "mushrooms", "chicken", "eggs" встретились среди топов-10 всех 40 тем? При ответе __не нужно__ учитывать составные ингредиенты, например, "hot water".
Передайте 6 чисел в функцию save_answers1 и загрузите сгенерированный файл в форму.
У gensim нет возможности фиксировать случайное приближение через параметры метода, но библиотека использует numpy для инициализации матриц. Поэтому, по утверждению автора библиотеки, фиксировать случайное приближение нужно командой, которая написана в следующей ячейке. __Перед строкой кода с построением модели обязательно вставляйте указанную строку фиксации random.seed.__
```
np.random.seed(76543)
# здесь код для построения модели:
ldamodel = models.ldamodel.LdaModel(corpus, id2word=dictionary, num_topics=40, passes=5)
topics = ldamodel.show_topics(num_topics=40, num_words=10, formatted=False)
c_salt, c_sugar, c_water, c_mushrooms, c_chicken, c_eggs = 0, 0, 0, 0, 0, 0
for topic in topics:
for word2prob in topic[1]:
word = word2prob[0]
if word == 'salt':
c_salt += 1
elif word == 'sugar':
c_sugar += 1
elif word == 'water':
c_water += 1
elif word == 'mushrooms':
c_mushrooms += 1
elif word == 'chicken':
c_chicken += 1
elif word == 'eggs':
c_eggs += 1
def save_answers1(c_salt, c_sugar, c_water, c_mushrooms, c_chicken, c_eggs):
with open("cooking_LDA_pa_task1.txt", "w") as fout:
fout.write(" ".join([str(el) for el in [c_salt, c_sugar, c_water, c_mushrooms, c_chicken, c_eggs]]))
save_answers1(c_salt, c_sugar, c_water, c_mushrooms, c_chicken, c_eggs)
print c_salt, c_sugar, c_water, c_mushrooms, c_chicken, c_eggs
```
### Фильтрация словаря
В топах тем гораздо чаще встречаются первые три рассмотренных ингредиента, чем последние три. При этом наличие в рецепте курицы, яиц и грибов яснее дает понять, что мы будем готовить, чем наличие соли, сахара и воды. Таким образом, даже в рецептах есть слова, часто встречающиеся в текстах и не несущие смысловой нагрузки, и поэтому их не желательно видеть в темах. Наиболее простой прием борьбы с такими фоновыми элементами - фильтрация словаря по частоте. Обычно словарь фильтруют с двух сторон: убирают очень редкие слова (в целях экономии памяти) и очень частые слова (в целях повышения интерпретируемости тем). Мы уберем только частые слова.
```
import copy
dictionary2 = copy.deepcopy(dictionary)
```
__Задание 2.__ У объекта dictionary2 есть переменная dfs - это словарь, ключами которого являются id токена, а элементами - число раз, сколько слово встретилось во всей коллекции. Сохраните в отдельный список ингредиенты, которые встретились в коллекции больше 4000 раз. Вызовите метод словаря filter_tokens, подав в качестве первого аргумента полученный список популярных ингредиентов. Вычислите две величины: dict_size_before и dict_size_after - размер словаря до и после фильтрации.
Затем, используя новый словарь, создайте новый корпус документов, corpus2, по аналогии с тем, как это сделано в начале ноутбука. Вычислите две величины: corpus_size_before и corpus_size_after - суммарное количество ингредиентов в корпусе (иными словами, сумма длин всех документов коллекции) до и после фильтрации.
Передайте величины dict_size_before, dict_size_after, corpus_size_before, corpus_size_after в функцию save_answers2 и загрузите сгенерированный файл в форму.
```
more4000 = [w for w, count in dictionary2.dfs.iteritems() if count > 4000]
dict_size_before = len(dictionary2.items())
dictionary2.filter_tokens(bad_ids=more4000)
dict_size_after = len(dictionary2.items())
def get_corpus_size(corp):
res = 0
for doc in corp:
res += len(doc)
#for w in doc:
# res += w[1]
return res
corpus_size_before = get_corpus_size(corpus)
corpus2 = [dictionary2.doc2bow(text) for text in texts] # составляем корпус документов
corpus_size_after = get_corpus_size(corpus2)
def save_answers2(dict_size_before, dict_size_after, corpus_size_before, corpus_size_after):
with open("cooking_LDA_pa_task2.txt", "w") as fout:
fout.write(" ".join([str(el) for el in [dict_size_before, dict_size_after, corpus_size_before, corpus_size_after]]))
save_answers2(dict_size_before, dict_size_after, corpus_size_before, corpus_size_after)
```
### Сравнение когерентностей
__Задание 3.__ Постройте еще одну модель по корпусу corpus2 и словарю dictioanary2, остальные параметры оставьте такими же, как при первом построении модели. Сохраните новую модель в другую переменную (не перезаписывайте предыдущую модель). Не забудьте про фиксирование seed!
Затем воспользуйтесь методом top_topics модели, чтобы вычислить ее когерентность. Передайте в качестве аргумента соответствующий модели корпус. Метод вернет список кортежей (топ токенов, когерентность), отсортированных по убыванию последней. Вычислите среднюю по всем темам когерентность для каждой из двух моделей и передайте в функцию save_answers3.
```
np.random.seed(76543)
# здесь код для построения модели:
ldamodel2 = models.ldamodel.LdaModel(corpus2, id2word=dictionary2, num_topics=40, passes=5)
coherences = ldamodel.top_topics(corpus)
coherences2 = ldamodel2.top_topics(corpus2)
import numpy as np
list1 = np.array([])
for coh in coherences:
list1 = np.append(list1, coh[1])
list2 = np.array([])
for coh in coherences2:
list2 = np.append(list2, coh[1])
coherence = list1.mean()
coherence2 = list2.mean()
def save_answers3(coherence, coherence2):
with open("cooking_LDA_pa_task3.txt", "w") as fout:
fout.write(" ".join(["%3f"%el for el in [coherence, coherence2]]))
save_answers3(coherence, coherence2)
```
Считается, что когерентность хорошо соотносится с человеческими оценками интерпретируемости тем. Поэтому на больших текстовых коллекциях когерентность обычно повышается, если убрать фоновую лексику. Однако в нашем случае этого не произошло.
### Изучение влияния гиперпараметра alpha
В этом разделе мы будем работать со второй моделью, то есть той, которая построена по сокращенному корпусу.
Пока что мы посмотрели только на матрицу темы-слова, теперь давайте посмотрим на матрицу темы-документы. Выведите темы для нулевого (или любого другого) документа из корпуса, воспользовавшись методом get_document_topics второй модели:
Также выведите содержимое переменной .alpha второй модели:
У вас должно получиться, что документ характеризуется небольшим числом тем. Попробуем поменять гиперпараметр alpha, задающий априорное распределение Дирихле для распределений тем в документах.
__Задание 4.__ Обучите третью модель: используйте сокращенный корпус (corpus2 и dictionary2) и установите параметр __alpha=1__, passes=5. Не забудьте задать количество тем и зафиксировать seed! Выведите темы новой модели для нулевого документа; должно получиться, что распределение над множеством тем практически равномерное. Чтобы убедиться в том, что во второй модели документы описываются гораздо более разреженными распределениями, чем в третьей, посчитайте суммарное количество элементов, __превосходящих 0.01__, в матрицах темы-документы обеих моделей. Другими словами, запросите темы модели для каждого документа с параметром minimum_probability=0.01 и просуммируйте число элементов в получаемых массивах. Передайте две суммы (сначала для модели с alpha по умолчанию, затем для модели в alpha=1) в функцию save_answers4.
```
def save_answers4(count_model2, count_model3):
with open("cooking_LDA_pa_task4.txt", "w") as fout:
fout.write(" ".join([str(el) for el in [count_model2, count_model3]]))
```
Таким образом, гиперпараметр alpha влияет на разреженность распределений тем в документах. Аналогично гиперпараметр eta влияет на разреженность распределений слов в темах.
### LDA как способ понижения размерности
Иногда распределения над темами, найденные с помощью LDA, добавляют в матрицу объекты-признаки как дополнительные, семантические, признаки, и это может улучшить качество решения задачи. Для простоты давайте просто обучим классификатор рецептов на кухни на признаках, полученных из LDA, и измерим точность (accuracy).
__Задание 5.__ Используйте модель, построенную по сокращенной выборке с alpha по умолчанию (вторую модель). Составьте матрицу $\Theta = p(t|d)$ вероятностей тем в документах; вы можете использовать тот же метод get_document_topics, а также вектор правильных ответов y (в том же порядке, в котором рецепты идут в переменной recipes). Создайте объект RandomForestClassifier со 100 деревьями, с помощью функции cross_val_score вычислите среднюю accuracy по трем фолдам (перемешивать данные не нужно) и передайте в функцию save_answers5.
```
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import cross_val_score
def save_answers5(accuracy):
with open("cooking_LDA_pa_task5.txt", "w") as fout:
fout.write(str(accuracy))
```
Для такого большого количества классов это неплохая точность. Вы можете попроовать обучать RandomForest на исходной матрице частот слов, имеющей значительно большую размерность, и увидеть, что accuracy увеличивается на 10-15%. Таким образом, LDA собрал не всю, но достаточно большую часть информации из выборки, в матрице низкого ранга.
### LDA --- вероятностная модель
Матричное разложение, использующееся в LDA, интерпретируется как следующий процесс генерации документов.
Для документа $d$ длины $n_d$:
1. Из априорного распределения Дирихле с параметром alpha сгенерировать распределение над множеством тем: $\theta_d \sim Dirichlet(\alpha)$
1. Для каждого слова $w = 1, \dots, n_d$:
1. Сгенерировать тему из дискретного распределения $t \sim \theta_{d}$
1. Сгенерировать слово из дискретного распределения $w \sim \phi_{t}$.
Подробнее об этом в [Википедии](https://en.wikipedia.org/wiki/Latent_Dirichlet_allocation).
В контексте нашей задачи получается, что, используя данный генеративный процесс, можно создавать новые рецепты. Вы можете передать в функцию модель и число ингредиентов и сгенерировать рецепт :)
```
def generate_recipe(model, num_ingredients):
theta = np.random.dirichlet(model.alpha)
for i in range(num_ingredients):
t = np.random.choice(np.arange(model.num_topics), p=theta)
topic = model.show_topic(0, topn=model.num_terms)
topic_distr = [x[1] for x in topic]
terms = [x[0] for x in topic]
w = np.random.choice(terms, p=topic_distr)
print w
```
### Интерпретация построенной модели
Вы можете рассмотреть топы ингредиентов каждой темы. Большиснтво тем сами по себе похожи на рецепты; в некоторых собираются продукты одного вида, например, свежие фрукты или разные виды сыра.
Попробуем эмпирически соотнести наши темы с национальными кухнями (cuisine). Построим матрицу A размера темы x кухни, ее элементы $a_{tc}$ - суммы p(t|d) по всем документам d, которые отнесены к кухне c. Нормируем матрицу на частоты рецептов по разным кухням, чтобы избежать дисбаланса между кухнями. Следующая функция получает на вход объект модели, объект корпуса и исходные данные и возвращает нормированную матрицу A. Ее удобно визуализировать с помощью seaborn.
```
import pandas
import seaborn
from matplotlib import pyplot as plt
%matplotlib inline
def compute_topic_cuisine_matrix(model, corpus, recipes):
# составляем вектор целевых признаков
targets = list(set([recipe["cuisine"] for recipe in recipes]))
# составляем матрицу
tc_matrix = pandas.DataFrame(data=np.zeros((model.num_topics, len(targets))), columns=targets)
for recipe, bow in zip(recipes, corpus):
recipe_topic = model.get_document_topics(bow)
for t, prob in recipe_topic:
tc_matrix[recipe["cuisine"]][t] += prob
# нормируем матрицу
target_sums = pandas.DataFrame(data=np.zeros((1, len(targets))), columns=targets)
for recipe in recipes:
target_sums[recipe["cuisine"]] += 1
return pandas.DataFrame(tc_matrix.values/target_sums.values, columns=tc_matrix.columns)
def plot_matrix(tc_matrix):
plt.figure(figsize=(10, 10))
seaborn.heatmap(tc_matrix, square=True)
# Визуализируйте матрицу
```
Чем темнее квадрат в матрице, тем больше связь этой темы с данной кухней. Мы видим, что у нас есть темы, которые связаны с несколькими кухнями. Такие темы показывают набор ингредиентов, которые популярны в кухнях нескольких народов, то есть указывают на схожесть кухонь этих народов. Некоторые темы распределены по всем кухням равномерно, они показывают наборы продуктов, которые часто используются в кулинарии всех стран.
Жаль, что в датасете нет названий рецептов, иначе темы было бы проще интерпретировать...
### Заключение
В этом задании вы построили несколько моделей LDA, посмотрели, на что влияют гиперпараметры модели и как можно использовать построенную модель.
| github_jupyter |
```
#Author: Eren Ali Aslangiray, Meryem Şahin
import pandas as pd
import os
import time
import sys
path1 = "/Users/erenmac/Desktop/NEW_DATA/Text/text_emotion.csv"
path2 = "/Users/erenmac/Desktop/NEW_DATA/Text/primary-plutchik-wheel-DFE.csv"
path3 = "/Users/erenmac/Desktop/NEW_DATA/Text/ssec-aggregated/train-combined-0.66.csv"
path4 = "/Users/erenmac/Desktop/NEW_DATA/Text/twitter_emotion_SocialCom_Wang/dev.txt"
path5 = "/Users/erenmac/Desktop/NEW_DATA/Text/twitter_emotion_SocialCom_Wang/train_2_10.txt"
path6 = "/Users/erenmac/Desktop/NEW_DATA/Text/twitter_emotion_SocialCom_Wang/test.txt"
path7 = "/Users/erenmac/Desktop/NEW_DATA/Text/GroundedEmotions/collected_data/collected_news_data.txt"
path8 = "/Users/erenmac/Desktop/NEW_DATA/Text/GroundedEmotions/collected_data/collected_tweets.txt"
path9 = "/Users/erenmac/Desktop/NEW_DATA/Text/GroundedEmotions/collected_data/collected_user_history_data.txt"
path10 = "/Users/erenmac/Desktop/NEW_DATA/Text/GroundedEmotions/collected_data/collected_weather_dataset.txt"
path11 = "/Users/erenmac/Desktop/NEW_DATA/Text/ssec-aggregated/test-combined-0.66.csv"
path12 = "/Users/erenmac/Desktop/NEW_DATA/Text/twitter-emotion/train.csv"
path13 = "/Users/erenmac/Desktop/NEW_DATA/Text/emotion.data"
path14 = "/Users/erenmac/Desktop/NEW_DATA/Text/xmltext.txt"
path15 = "/Users/erenmac/Desktop/NEW_DATA/Text/SentiWords_1.1.txt"
path16 = "Users/erenmac/Desktop/NEW_DATA/Text/NRC-Emotion-Lexicon-Wordlevel-v0.92.txt"
pathjson1 = "/Users/erenmac/Desktop/NEW_DATA/Text/cybertroll.json"
#mytask = [2,4,7,8,9,11,13,14,json]
#df1 = pd.read_csv(path1)
#df2 = pd.read_csv(path2)
#df3 = pd.read_csv(path3, error_bad_lines=False, header = None )
#df4 = pd.read_csv(path4, sep="\t", header = None) #twitter
df5 = pd.read_csv(path5, sep="\t", header = None)
df6 = pd.read_csv(path6, sep="\t", header = None)
#df7 = pd.read_csv(path7, sep="|", header = None)
#df8 = pd.read_csv(path8, sep="|", header = None) #twitter
#df9 = pd.read_csv(path9, sep="|", header = None) #twitter
#df10 = pd.read_csv(path10, sep="|", header = None)
#df11 = pd.read_csv(path11, error_bad_lines=False, header = None )
#df12 = pd.read_csv(path12,encoding = 'ISO-8859-1')
#df13 = pd.read_csv (path13)
#dfjson1 = pd.read_json(pathjson1, lines = True)
dfx = df5.append(df6, ignore_index=True)
dfx.to_json("/Users/erenmac/Desktop/NEW_DATA/tweets.json")
template_dict = {"anger":[],"disgust":[],"sad":[],"happy":[],"suprise":[],"fear":[],"neutral":[]}
```
# DF2
```
df2 = df2.drop(columns = ["emotion_gold","emotion:confidence","_unit_id", "_golden","_unit_state","_trusted_judgments","_last_judgment_at","id","idiom_id"])
unique_emoniotns = df2.emotion.unique()
unique_emoniotns
reverse_dict = {"Anger":"anger", "Aggression":"anger","Disgust":"disgust","Contempt":"disgust","Sadness":"sad","Disapproval":"sad","Remorse":"sad","Optimism":"happy","Love":"happy","Joy":"happy","Trust":"happy","Surprise":"surprise","Fear":"fear","Awe":"fear","Neutral":"neutral","Ambiguous":"neutral"}
dropemo = ["Anticipation","Submission"]
df2 = df2[df2.emotion != "Anticipation"]
df2 = df2[df2.emotion != "Submission"]
df2["emotion"] = df2["emotion"].map(reverse_dict)
df2 = df2.reset_index(drop=True)
for i in range (2270):
k = df2["sentence"][i]
if "." in k:
k = k.replace(".","")
if "," in k:
k = k.replace(",","")
if "?" in k:
k = k.replace("?","")
if "!" in k:
k = k.replace("!","")
df2["sentence"][i] = k
df2final = df2
df2final.to_csv("/Users/erenmac/Desktop/NEW_DATA/Cleaned_Data/DF2.csv")
```
# DF4
```
import tweepy
auth = tweepy.OAuthHandler("wso6hl1mmqx5YlLuuiJ7apQci", "QQ1mGejEs70qBmpzODBGhMc2FLzVo30hctpaZjSVlBtlmsTiSZ")
auth.set_access_token("1055878812-fI40KKPy7zNOK8N18WROQ02AgnH820WFeOhTIDS", "q5WJXcqCWFRoU7KxR797fz4Ku3C6a876xdECJchupsnfY")
try:
redirect_url = auth.get_authorization_url()
except tweepy.TweepError:
print('Error! Failed to get request token.')
api = tweepy.API(auth)
tweets = []
code8errorlist = []
def tweetminer(id):
tweet = api.get_status(id)
return tweet.text
#loaddf.to_json("/Users/erenmac/Desktop/NEW_DATA/semi_cleaned_data/loaddf.json")
loaddf = pd.read_json("/Users/erenmac/Desktop/NEW_DATA/semi_cleaned_data/loaddf.json")
for i in range (len(loaddf)):
if i%100 == 0:
print(i)
if loaddf[2][i] == "aslangiray":
try:
x = (tweetminer(loaddf[0][i]))
loaddf[2][i] = x
except tweepy.TweepError as e:
e1 = "'code': 88" in str(e)
e2 = "'code': 144" in str(e)
e3 = "'code': 179" in str(e)
e4 = "'code': 34" in str(e)
e5 = "'code': 63" in str(e)
if e1 == True:
print ("Have code 88 error, waiting 5 min.")
time.sleep((60*5)+5)
elif e2 == True:
loaddf[2][i] = "delet dis pls"
elif e3 == True:
loaddf[2][i] = "delet dis pls"
elif e4 == True:
loaddf[2][i] = "delet dis pls"
elif e5 == True:
loaddf[2][i] = "delet dis pls"
else:
errorlist.append(i)
errorlist.append(e)
len(errorlist)
loaddf = loaddf.drop(columns = [0])
loaddf = loaddf[loaddf[2] != "delet dis pls"]
loaddf = loaddf.reset_index(drop = True)
loaddf.to_json("/Users/erenmac/Desktop/NEW_DATA/Cleaned_Data/DF4.json")
```
# DF7
```
None
```
# DF8
```
df8[3] = "aslangiray"
df8
tweets8 = []
errorlist8 = []
code88errorlist = []
for i in range (len(df8)):
if i%100 == 0:
print(i)
if df8[3][i] == "aslangiray":
try:
x = (tweetminer(df8[0][i]))
df8[3][i] = x
except tweepy.TweepError as e:
e1 = "'code': 88" in str(e)
e2 = "'code': 144" in str(e)
e3 = "'code': 179" in str(e)
e4 = "'code': 34" in str(e)
e5 = "'code': 63" in str(e)
if e1 == True:
print ("Have code 88 error, waiting 5 min.")
time.sleep((60*5)+5)
elif e2 == True:
df8[3][i] = "delet dis pls"
elif e3 == True:
df8[3][i] = "delet dis pls"
elif e4 == True:
df8[3][i] = "delet dis pls"
elif e5 == True:
df8[3][i] = "delet dis pls"
else:
errorlist.append(i)
errorlist.append(e)
df8 = df8.drop(columns = [0,1])
df8 = df8[df8[3] != "delet dis pls"]
df8 = df8.reset_index(drop = True)
df8.to_csv("/Users/erenmac/Desktop/NEW_DATA/Cleaned_Data/DF8.csv")
```
# DF9
```
None
```
# DF11
```
for i in range (1431):
k = df11[0][i]
if "---" in k:
k = k.replace("---","")
if "\t" in k:
k = k.replace("\t", " ")
if "." in k:
k = k.replace(".","")
if "," in k:
k = k.replace(",","")
if "?" in k:
k = k.replace("?","")
if "!" in k:
k = k.replace("!","")
if "#" in k:
k = k.replace("#"," ")
df11[0][i] = k
import re
def remove_mentions(input_text):
return re.sub(r'@\w+', '', input_text)
for i in range (1431):
k = df11[0][i]
k = remove_mentions(k)
k = k.replace("SemST","")
df11[0][i] = k
emotions_list = ["Anger","Anticipation","Disgust","Joy","Fear","Sadness","Trust","Surprise"]
rowlist = []
for i in range (len(df11)):
k = df11[0][i]
k = k.split()
rowlist.append(k)
dellist = []
for i in range (len(rowlist)):
if len(rowlist[i]) < 5:
dellist.append(i)
dellist.remove(911)
i = 0
for item in dellist:
rowlist.pop(item-i)
i = i +1
dfdict = {}
for i in range (len(rowlist)):
for k in range (3):
if k == 0:
if rowlist[i][k] in emotions_list:
dfdict[i] = [rowlist[i][k]]
else:
dfdict[i] = []
else:
if rowlist[i][k] in emotions_list:
dfdict[i] += [rowlist[i][k]]
for q in range (len(dfdict[i])):
rowlist[i].pop(0)
df11s = pd.DataFrame.from_dict(dfdict, orient='index')
df11s[3] = "sad"
for i in range (len(rowlist)):
k = ' '.join(rowlist[i])
df11s[3][i] = k
df11s = df11s.dropna(subset=[0])
df11final = df11s.reset_index(drop = True)
unique_emoniotns = df11final[1].unique()
unique_emoniotns
reverse_dict = {"Trust":"happy", "Joy":"happy","Anticipation":"neutral","Anger":"anger","fear":"Fear","Sadness":"sad","Disgust":"disgust","Surprise":"surprise"}
df11final[0] = df11final[0].map(reverse_dict)
df11final[1] = df11final[1].map(reverse_dict)
df11final[2] = df11final[2].map(reverse_dict)
df11final.to_csv("/Users/erenmac/Desktop/NEW_DATA/Cleaned_Data/DF11.csv")
```
# DF13
```
df13 = df13.drop(columns = ["Unnamed: 0"])
unique_emoniotns = df13.emotions.unique()
unique_emoniotns
reverse_dict = {"sadness":"sad", "joy":"happy","love":"happy","anger":"anger","fear":"fear","surprise":"surprise"}
df13["emotions"] = df13["emotions"].map(reverse_dict)
df13final = df13
df13final.to_csv("/Users/erenmac/Desktop/NEW_DATA/Cleaned_Data/DF13.csv")
```
# DFJSON1
```
dfjson1 = dfjson1.drop(columns = ["extras","metadata"])
labellist = []
for i in range (len(dfjson1)):
if dfjson1["annotation"][i]["label"] == ['1']:
labellist.append("negative")
else:
labellist.append("del")
for i in range (len(labellist)):
k = labellist[i]
dfjson1["annotation"][i] = k
dfjson1 = dfjson1[dfjson1.annotation != "del"]
dfjson1final = dfjson1
dfjson1final.to_csv("/Users/erenmac/Desktop/NEW_DATA/Cleaned_Data/DF17.csv")
```
# Finalize DB
```
meryem1 = pd.read_json("/Users/erenmac/Downloads/df12f.json")
meryem2 = pd.read_json("/Users/erenmac/Downloads/result2.json")
meryem1
erenfin = pd.read_json("/Users/erenmac/Desktop/NEW_DATA/Cleaned_Data/final_multilabel.json")
erenfin2[0] = erenfin2.annotation
erenfin2[1] = erenfin2.content
erenfin2 = erenfin2.drop(columns= ["annotation","content"])
erenfin2 = pd.read_csv("/Users/erenmac/Desktop/NEW_DATA/Cleaned_Data/df17.csv")
erenfin2 = erenfin2.drop(columns = ["Unnamed: 0"])
frames = [erenfin2,meryem1]
result = pd.concat(frames)
result = result.reset_index(drop = True)
result.to_json("/Users/erenmac/Desktop/NEW_DATA/Finalized_Data/pos_neg_emotion_data.json")
result
test1 = pd.read_json("/Users/erenmac/Desktop/NEW_DATA/Finalized_Data/pos_neg_emotion_data.json")
test2 = pd.read_json("/Users/erenmac/Desktop/NEW_DATA/Finalized_Data/multilabel_emotion_data.json")
test1
```
| github_jupyter |
```
import os, re
import pandas as pd
import numpy as np
import requests
from bs4 import BeautifulSoup
import time
import json
URL_LIST_BASE = "https://www.dogbreedslist.info/all-dog-breeds/list_1_{}.html" # {} in [1, 19]
def get_dog_list_page(n):
r = requests.get(URL_LIST_BASE.format(n))
soup = BeautifulSoup(r.content, 'html.parser')
divs = soup.find_all('div', {'class': 'left'})
dog_urls = [div.find_all('a')[0]["href"] for div in divs]
return [(re.findall("/all-dog-breeds/(.*)?\.html", url)[0], url) for url in dog_urls]
def load_dog_list_page():
return json.load(open("./dog_url_list.json", "rb"))
# URL_LIST_ALL_DOGS = []
# for i in range(1, 20):
# URL_LIST_ALL_DOGS.extend(get_dog_list_page(i))
# time.sleep(2)
# json.dump(URL_LIST_ALL_DOGS, open("./dog_url_list.json", "w+"))
URL_LIST_ALL_DOGS_loaded = load_dog_list_page()
def get_dog_info(n):
"""Gets breed-specific info. Unfortunately, numbered by index."""
dog = URL_LIST_ALL_DOGS_loaded[n]
r = requests.get(dog[1])
soup = BeautifulSoup(r.content, 'html.parser')
info_table = soup.find_all('table', {'class': 'table-01'})
characteristics_table = soup.find_all('table', {'class': 'table-02'})
dog_classes = [[i for i in tr.contents if i != '\n'] for tr in characteristics_table[0].find_all("tr")][1:]
characteristics = {dog_class[0].string: dog_class[1].p.contents[0][0] for dog_class in dog_classes}
info = dict([[i.string for i in info_table[0].find_all("tr")[2:][i].contents if i != '\n'] for i in [0, 4]])
dog_info = [info["Name"], {**characteristics, **{'Size': info["Size"]}}]
return dog_info
# ALL_DOG_INFO = {}
# for i in range(len(URL_LIST_ALL_DOGS_loaded)):
# try:
# time.sleep(1)
# gdi = get_dog_info(i)
# ALL_DOG_INFO[gdi[0]] = gdi[1]
# except Exception as e:
# print(i, e)
## SPECIAL CASES DUE TO BAD HTML.
# dog = URL_LIST_ALL_DOGS_loaded[332]
# r = requests.get(dog[1])
# soup = BeautifulSoup(r.content, 'html.parser')
# info_table = soup.find_all('table', {'class': 'table-01'})
# characteristics_table = soup.find_all('table', {'class': 'table-02'})
# dog_classes = [[i for i in tr.contents if i != '\n'] for tr in characteristics_table[0].find_all("tr")][1:]
# characteristics = {dog_class[0].string: dog_class[1].p.contents[0][0] for dog_class in dog_classes}
# # info = dict([[i.string for i in info_table[0].find_all("tr")[2:][i].contents if i != '\n'] for i in [0, 4]])
# dog_info = {**characteristics, **{"Size": "Medium"}}
# ALL_DOG_INFO["American Husky"] = dog_info
# dog = URL_LIST_ALL_DOGS_loaded[369]
# r = requests.get(dog[1])
# soup = BeautifulSoup(r.content, 'html.parser')
# info_table = soup.find_all('table', {'class': 'table-01'})
# characteristics_table = soup.find_all('table', {'class': 'table-02'})
# dog_classes = [[i for i in tr.contents if i != '\n'] for tr in characteristics_table[0].find_all("tr")][1:]
# characteristics = {dog_class[0].string: dog_class[1].p.contents[0][0] for dog_class in dog_classes}
# # info = dict([[i.string for i in info_table[0].find_all("tr")[2:][i].contents if i != '\n'] for i in [0, 4]])
# dog_info = {**characteristics, **{"Size": "Medium"}}
# ALL_DOG_INFO["Mountain Cur"] = dog_info
json.dump(ALL_DOG_INFO, open("./dog_metadata.json", "w+"))
```
| github_jupyter |
## Dependencies
```
import json, glob
from tweet_utility_scripts import *
from tweet_utility_preprocess_roberta_scripts_aux import *
from transformers import TFRobertaModel, RobertaConfig
from tokenizers import ByteLevelBPETokenizer
from tensorflow.keras import layers
from tensorflow.keras.models import Model
```
# Load data
```
test = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/test.csv')
print('Test samples: %s' % len(test))
display(test.head())
```
# Model parameters
```
input_base_path = '/kaggle/input/239-robertabase/'
with open(input_base_path + 'config.json') as json_file:
config = json.load(json_file)
config
# vocab_path = input_base_path + 'vocab.json'
# merges_path = input_base_path + 'merges.txt'
base_path = '/kaggle/input/qa-transformers/roberta/'
vocab_path = base_path + 'roberta-base-vocab.json'
merges_path = base_path + 'roberta-base-merges.txt'
config['base_model_path'] = base_path + 'roberta-base-tf_model.h5'
config['config_path'] = base_path + 'roberta-base-config.json'
model_path_list = glob.glob(input_base_path + '*.h5')
model_path_list.sort()
print('Models to predict:')
print(*model_path_list, sep = '\n')
```
# Tokenizer
```
tokenizer = ByteLevelBPETokenizer(vocab_file=vocab_path, merges_file=merges_path,
lowercase=True, add_prefix_space=True)
```
# Pre process
```
test['text'].fillna('', inplace=True)
test['text'] = test['text'].apply(lambda x: x.lower())
test['text'] = test['text'].apply(lambda x: x.strip())
x_test, x_test_aux, x_test_aux_2 = get_data_test(test, tokenizer, config['MAX_LEN'], preprocess_fn=preprocess_roberta_test)
```
# Model
```
module_config = RobertaConfig.from_pretrained(config['config_path'], output_hidden_states=False)
def model_fn(MAX_LEN):
input_ids = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='input_ids')
attention_mask = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='attention_mask')
base_model = TFRobertaModel.from_pretrained(config['base_model_path'], config=module_config, name="base_model")
last_hidden_state, _ = base_model({'input_ids': input_ids, 'attention_mask': attention_mask})
logits = layers.Dense(2, name="qa_outputs", use_bias=False)(last_hidden_state)
start_logits, end_logits = tf.split(logits, 2, axis=-1)
start_logits = tf.squeeze(start_logits, axis=-1)
end_logits = tf.squeeze(end_logits, axis=-1)
model = Model(inputs=[input_ids, attention_mask], outputs=[start_logits, end_logits])
return model
```
# Make predictions
```
NUM_TEST_IMAGES = len(test)
test_start_preds = np.zeros((NUM_TEST_IMAGES, config['MAX_LEN']))
test_end_preds = np.zeros((NUM_TEST_IMAGES, config['MAX_LEN']))
for model_path in model_path_list:
print(model_path)
model = model_fn(config['MAX_LEN'])
model.load_weights(model_path)
test_preds = model.predict(get_test_dataset(x_test, config['BATCH_SIZE']))
test_start_preds += test_preds[0]
test_end_preds += test_preds[1]
```
# Post process
```
test['start'] = test_start_preds.argmax(axis=-1)
test['end'] = test_end_preds.argmax(axis=-1)
test['selected_text'] = test.apply(lambda x: decode(x['start'], x['end'], x['text'], config['question_size'], tokenizer), axis=1)
# Post-process
test["selected_text"] = test.apply(lambda x: ' '.join([word for word in x['selected_text'].split() if word in x['text'].split()]), axis=1)
test['selected_text'] = test.apply(lambda x: x['text'] if (x['selected_text'] == '') else x['selected_text'], axis=1)
test['selected_text'].fillna(test['text'], inplace=True)
```
# Visualize predictions
```
test['text_len'] = test['text'].apply(lambda x : len(x))
test['label_len'] = test['selected_text'].apply(lambda x : len(x))
test['text_wordCnt'] = test['text'].apply(lambda x : len(x.split(' ')))
test['label_wordCnt'] = test['selected_text'].apply(lambda x : len(x.split(' ')))
test['text_tokenCnt'] = test['text'].apply(lambda x : len(tokenizer.encode(x).ids))
test['label_tokenCnt'] = test['selected_text'].apply(lambda x : len(tokenizer.encode(x).ids))
test['jaccard'] = test.apply(lambda x: jaccard(x['text'], x['selected_text']), axis=1)
display(test.head(10))
display(test.describe())
```
# Test set predictions
```
submission = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/sample_submission.csv')
submission['selected_text'] = test['selected_text']
submission.to_csv('submission.csv', index=False)
submission.head(10)
```
| github_jupyter |
# Binary trees
```
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from dtreeviz.trees import *
from lolviz import *
import numpy as np
import pandas as pd
%config InlineBackend.figure_format = 'retina'
```
## Setup
Make sure to install stuff:
```
pip install -U dtreeviz
pip install -U lolviz
brew install graphviz
```
## Binary tree class definition
A binary tree has a payload (a value) and references to left and right children. One or both of the children references can be `None`. A reference to a node is the same thing as a reference to a tree as the tree is a self similar data structure. We don't distinguish between the two kinds of references. A reference to the root node is a reference to the entire tree.
Here is a basic tree node class in Python. The constructor requires at least a value to store in the node.
```
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return str(self.value)
def __str__(self):
return str(self.value)
```
## Manual tree construction
Here's how to create and visualize a single node:
```
root = TreeNode(1)
treeviz(root)
```
**Given `left` and `right` nodes, create node `root` with those nodes as children.**
```
left = TreeNode(2)
right = TreeNode(3)
root = ...
treeviz(root)
```
<details>
<summary>Solution</summary>
<pre>
left = TreeNode(2)
right = TreeNode(3)
root = TreeNode(1,left,right)
treeviz(root)
</pre>
</details>
**Write code to create the following tree structure**
<img src="3-level-tree.png" width="30%">
```
left = ...
right = ...
root = ...
treeviz(root)
```
<details>
<summary>Solution</summary>
<pre>
left = TreeNode(2,TreeNode(4))
right = TreeNode(3,TreeNode(5),TreeNode(6))
root = TreeNode(1,left,right)
treeviz(root)
</pre>
</details>
## Walking trees manually
To walk a tree, we simply follow the left and right children references, avoiding any `None` references.
**Q.** Given tree `r` shown here, what Python expressions refer to the nodes with 443 and 17 in them?
```
left = TreeNode(443,TreeNode(-34))
right = TreeNode(17,TreeNode(99))
r = TreeNode(10,left,right)
treeviz(r)
```
<details>
<summary>Solution</summary>
<pre>
r.left, r.right
</pre>
</details>
**Q.** Given the same tree `r`, what Python expressions refer to the nodes with -34 and 99 in them?
<details>
<summary>Solution</summary>
<pre>
r.left.left, r.right.left
</pre>
</details>
## Walking all nodes
Now let's create a function to walk all nodes in a tree. Remember that our template for creating any recursive function looks like this:
```
def f(input):
1. check termination condition
2. process the active input region / current node, etc…
3. invoke f on subregion(s)
4. combine and return results
```
```
def walk(p:TreeNode):
if p is None: return # step 1
print(p.value) # step 2
walk(p.left) # step 3
walk(p.right) # step 3 (there is no step 4 for this problem)
```
Let's create the simple 3-level tree we had before:
```
left = TreeNode(2,TreeNode(4))
right = TreeNode(3,TreeNode(5),TreeNode(6))
root = TreeNode(1,left,right)
treeviz(root)
```
**Q.** What is the output of running `walk(root)`?
<details>
<summary>Solution</summary>
We walk the tree depth first, from left to right<p>
<pre>
1
2
4
3
5
6
</pre>
</details>
## Searching through nodes
Here's how to search for an element as you walk, terminating as soon as the node with `x` is found:
```
def search(p:TreeNode, x:object):
print("enter ",p)
if p is None: return None
print(p)
if x==p.value:
return p
q = search(p.left, x)
if q is not None:
return q
q = search(p.right, x)
return q
```
**Q.** What is the output of running `search(root, 5)`?
<details>
<summary>Solution</summary>
We walk the tree depth first as before, but now we stop when we reach the node with 5:<p>
<pre>
1
2
4
3
5
</pre>
</details>
To see the recursion entering and exiting (or discovering and finishing) nodes, here is a variation that prints out its progress through the tree:
```
def search(p:TreeNode, x:object):
if p is None: return None
print("enter ",p)
if x==p.value:
print("exit ",p)
return p
q = search(p.left, x)
if q is not None:
print("exit ",p)
return q
q = search(p.right, x)
print("exit ",p)
return q
search(root, 5)
```
## Creating (random) decision tree "stumps"
A regression tree stump is a tree with a decision node at the root and two predictor leaves. These are used by gradient boosting machines as the "weak learners."
```
class TreeNode: # acts as decision node and leaf. it's a leaf if split is None
def __init__(self, split=None, prediction=None, left=None, right=None):
self.split = split
self.prediction = prediction
self.left = left
self.right = right
def __repr__(self):
return str(self.value)
def __str__(self):
return str(self.value)
df = pd.DataFrame()
df["sqfeet"] = [750, 800, 850, 900,950]
df["rent"] = [1160, 1200, 1280, 1450,1300]
df
```
The following code shows where sklearn would do a split with a normal decision tree.
```
X, y = df.sqfeet.values.reshape(-1,1), df.rent.values
t = DecisionTreeRegressor(max_depth=1)
t.fit(X,y)
fig, ax = plt.subplots(1, 1, figsize=(3,1.5))
t = rtreeviz_univar(t,
X, y,
feature_names='sqfeet',
target_name='rent',
fontsize=9,
colors={'scatter_edge': 'black'},
ax=ax)
```
Instead of picking the optimal split point, we can choose a random value in between the minimum and maximum x value, like extremely random forests do:
```
def stumpfit(x, y):
if len(x)==1 or len(np.unique(x))==1: # if one x value, make leaf
return TreeNode(prediction=y[0])
split = np.round(np.random.uniform(min(x),max(x)))
t = TreeNode(split)
t.left = TreeNode(prediction=np.mean(y[x<split]))
t.right = TreeNode(prediction=np.mean(y[x>=split]))
return t
```
**Run the following code multiple times to see how it creates different y lists in the nodes, according to the split value.**
```
root = stumpfit(X.reshape(-1),y)
treeviz(root)
```
## Creating random decision trees (single variable)
And now to demonstrate the magic of recursion. If we replace
```
t.left = TreeNode(prediction=np.mean(y[x<split]))
```
with
```
t.left = treefit(x[x<split], y[x<split])
```
(and same for `t.right`) then all of the sudden we get a full decision tree, rather than just a stump!
```
def treefit(x, y):
if len(x)==1 or len(np.unique(x))==1: # if one x value, make leaf
return TreeNode(prediction=y[0])
split = np.round(np.random.uniform(min(x),max(x)))
t = TreeNode(split)
t.left = treefit(x[x<split], y[x<split])
t.right = treefit(x[x>=split], y[x>=split])
return t
root = treefit(X.reshape(-1),y)
treeviz(root)
```
You can run that multiple times to see different tree layouts according to randomness.
**Q.** How would you modify `treefit()` so that it creates a typical decision tree rather than a randomized decision tree?
<details>
<summary>Solution</summary>
Instead of choosing a random split, we would pick the split value in $x$ that got the best average child $y$ purity/similarity. In other words, exhaustively test each $x$ value as candidate split point by computing the MSE for left and right $y$ subregions. The split point that gets the best weighted average for left and right MSE, is the optimal split point.
</details>
| github_jupyter |
```
# reload packages
%load_ext autoreload
%autoreload 2
```
### Choose GPU (this may not be needed on your computer)
```
%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=''
```
### load packages
```
from tfumap.umap import tfUMAP
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tqdm.autonotebook import tqdm
import umap
import pandas as pd
```
### Load dataset
```
from sklearn.datasets import make_moons
X_train, Y_train = make_moons(1000, random_state=0, noise=0.1)
X_train_flat = X_train
X_test, Y_test = make_moons(1000, random_state=1, noise=0.1)
X_test_flat = X_test
X_valid, Y_valid = make_moons(1000, random_state=2, noise=0.1)
plt.scatter(X_test[:,0], X_test[:,1], c=Y_test)
```
### Create model and train
```
embedder = tfUMAP(direct_embedding=True, verbose=True, negative_sample_rate=5, training_epochs=100)
z = embedder.fit_transform(X_train_flat)
```
### Plot model output
```
fig, ax = plt.subplots( figsize=(8, 8))
sc = ax.scatter(
z[:, 0],
z[:, 1],
c=Y_train.astype(int)[:len(z)],
cmap="tab10",
s=0.1,
alpha=0.5,
rasterized=True,
)
ax.axis('equal')
ax.set_title("UMAP in Tensorflow embedding", fontsize=20)
plt.colorbar(sc, ax=ax);
```
### View loss
```
from tfumap.umap import retrieve_tensors
import seaborn as sns
loss_df = retrieve_tensors(embedder.tensorboard_logdir)
loss_df[:3]
ax = sns.lineplot(x="step", y="val", hue="group", data=loss_df[loss_df.variable=='umap_loss'])
ax.set_xscale('log')
```
### Save output
```
from tfumap.paths import ensure_dir, MODEL_DIR
output_dir = MODEL_DIR/'projections'/ 'moons' / 'direct'
ensure_dir(output_dir)
embedder.save(output_dir)
loss_df.to_pickle(output_dir / 'loss_df.pickle')
np.save(output_dir / 'z.npy', z)
```
### Compare to direct embedding with base UMAP
```
from umap import UMAP
z_umap = UMAP(verbose=True).fit_transform(X_train_flat)
### realign using procrustes
from scipy.spatial import procrustes
z_align, z_umap_align, disparity = procrustes(z, z_umap)
print(disparity)
fig, axs = plt.subplots(ncols=2, figsize=(20, 8))
ax = axs[0]
sc = ax.scatter(
z_align[:, 0],
z_align[:, 1],
c=Y_train.astype(int)[:len(z)],
cmap="tab10",
s=0.1,
alpha=0.5,
rasterized=True,
)
ax.axis('equal')
ax.set_title("UMAP in Tensorflow", fontsize=20)
#plt.colorbar(sc, ax=ax);
ax = axs[1]
sc = ax.scatter(
z_umap_align[:, 0],
z_umap_align[:, 1],
c=Y_train.astype(int)[:len(z)],
cmap="tab10",
s=0.1,
alpha=0.5,
rasterized=True,
)
ax.axis('equal')
ax.set_title("UMAP with UMAP-learn", fontsize=20)
#plt.colorbar(sc, ax=ax);
```
| github_jupyter |
```
import sys
sys.executable
```
[Optional]: If you're using a Mac/Linux, you can check your environment with these commands:
```
!which pip3
!which python3
!ls -lah /usr/local/bin/python3
```
```
!pip3 install -U pip
!pip3 install torch==1.3.0
!pip3 install seaborn
import torch
torch.cuda.is_available()
# IPython candies...
from IPython.display import Image
from IPython.core.display import HTML
from IPython.display import clear_output
%%html
<style> table {float:left} </style>
```
Perceptron
=====
**Perceptron** algorithm is a:
> "*system that depends on **probabilistic** rather than deterministic principles for its operation, gains its reliability from the **properties of statistical measurements obtain from a large population of elements***"
> \- Frank Rosenblatt (1957)
Then the news:
> "*[Perceptron is an] **embryo of an electronic computer** that [the Navy] expects will be **able to walk, talk, see, write, reproduce itself and be conscious of its existence.***"
> \- The New York Times (1958)
News quote cite from Olazaran (1996)
Perceptron in Bullets
----
- Perceptron learns to classify any linearly separable set of inputs.
- Some nice graphics for perceptron with Go https://appliedgo.net/perceptron/
If you've got some spare time:
- There's a whole book just on perceptron: https://mitpress.mit.edu/books/perceptrons
- For watercooler gossips on perceptron in the early days, read [Olazaran (1996)](https://pdfs.semanticscholar.org/f3b6/e5ef511b471ff508959f660c94036b434277.pdf?_ga=2.57343906.929185581.1517539221-1505787125.1517539221)
Perceptron in Math
----
Given a set of inputs $x$, the perceptron
- learns $w$ vector to map the inputs to a real-value output between $[0,1]$
- through the summation of the dot product of the $w·x$ with a transformation function
Perceptron in Picture
----
```
##Image(url="perceptron.png", width=500)
Image(url="https://ibin.co/4TyMU8AdpV4J.png", width=500)
```
(**Note:** Usually, we use $x_1$ as the bias and fix the input to 1)
Perceptron as a Workflow Diagram
----
If you're familiar with [mermaid flowchart](https://mermaidjs.github.io)
```
.. mermaid::
graph LR
subgraph Input
x_1
x_i
x_n
end
subgraph Perceptron
n1((s)) --> n2(("f(s)"))
end
x_1 --> |w_1| n1
x_i --> |w_i| n1
x_n --> |w_n| n1
n2 --> y["[0,1]"]
```
```
##Image(url="perceptron-mermaid.svg", width=500)
Image(url="https://svgshare.com/i/AbJ.svg", width=500)
```
Optimization Process
====
To learn the weights, $w$, we use an **optimizer** to find the best-fit (optimal) values for $w$ such that the inputs correct maps to the outputs.
Typically, process performs the following 4 steps iteratively.
### **Initialization**
- **Step 1**: Initialize weights vector
### **Forward Propagation**
- **Step 2a**: Multiply the weights vector with the inputs, sum the products, i.e. `s`
- **Step 2b**: Put the sum through the sigmoid, i.e. `f()`
### **Back Propagation**
- **Step 3a**: Compute the errors, i.e. difference between expected output and predictions
- **Step 3b**: Multiply the error with the **derivatives** to get the delta
- **Step 3c**: Multiply the delta vector with the inputs, sum the product
### **Optimizer takes a step**
- **Step 4**: Multiply the learning rate with the output of Step 3c.
```
import math
import numpy as np
np.random.seed(0)
def sigmoid(x): # Returns values that sums to one.
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(sx):
# See https://math.stackexchange.com/a/1225116
# Hint: let sx = sigmoid(x)
return sx * (1 - sx)
sigmoid(np.array([2.5, 0.32, -1.42])) # [out]: array([0.92414182, 0.57932425, 0.19466158])
sigmoid_derivative(np.array([2.5, 0.32, -1.42])) # [out]: array([0.07010372, 0.24370766, 0.15676845])
def cost(predicted, truth):
return np.abs(truth - predicted)
gold = np.array([0.5, 1.2, 9.8])
pred = np.array([0.6, 1.0, 10.0])
cost(pred, gold)
gold = np.array([0.5, 1.2, 9.8])
pred = np.array([9.3, 4.0, 99.0])
cost(pred, gold)
```
Representing OR Boolean
---
Lets consider the problem of the OR boolean and apply the perceptron with simple gradient descent.
| x2 | x3 | y |
|:--:|:--:|:--:|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
```
X = or_input = np.array([[0,0], [0,1], [1,0], [1,1]])
Y = or_output = np.array([[0,1,1,1]]).T
or_input
or_output
# Define the shape of the weight vector.
num_data, input_dim = or_input.shape
# Define the shape of the output vector.
output_dim = len(or_output.T)
print('Inputs\n======')
print('no. of rows =', num_data)
print('no. of cols =', input_dim)
print('\n')
print('Outputs\n=======')
print('no. of cols =', output_dim)
# Initialize weights between the input layers and the perceptron
W = np.random.random((input_dim, output_dim))
W
```
Step 2a: Multiply the weights vector with the inputs, sum the products
====
To get the output of step 2a,
- Itrate through each row of the data, `X`
- For each column in each row, find the product of the value and the respective weights
- For each row, compute the sum of the products
```
# If we write it imperatively:
summation = []
for row in X:
sum_wx = 0
for feature, weight in zip(row, W):
sum_wx += feature * weight
summation.append(sum_wx)
print(np.array(summation))
# If we vectorize the process and use numpy.
np.dot(X, W)
```
Train the Single-Layer Model
====
```
num_epochs = 10000 # No. of times to iterate.
learning_rate = 0.03 # How large a step to take per iteration.
# Lets standardize and call our inputs X and outputs Y
X = or_input
Y = or_output
for _ in range(num_epochs):
layer0 = X
# Step 2a: Multiply the weights vector with the inputs, sum the products, i.e. s
# Step 2b: Put the sum through the sigmoid, i.e. f()
# Inside the perceptron, Step 2.
layer1 = sigmoid(np.dot(X, W))
# Back propagation.
# Step 3a: Compute the errors, i.e. difference between expected output and predictions
# How much did we miss?
layer1_error = cost(layer1, Y)
# Step 3b: Multiply the error with the derivatives to get the delta
# multiply how much we missed by the slope of the sigmoid at the values in layer1
layer1_delta = layer1_error * sigmoid_derivative(layer1)
# Step 3c: Multiply the delta vector with the inputs, sum the product (use np.dot)
# Step 4: Multiply the learning rate with the output of Step 3c.
W += learning_rate * np.dot(layer0.T, layer1_delta)
layer1
# Expected output.
Y
# On the training data
[[int(prediction > 0.5)] for prediction in layer1]
```
Lets try the XOR Boolean
---
Lets consider the problem of the OR boolean and apply the perceptron with simple gradient descent.
| x2 | x3 | y |
|:--:|:--:|:--:|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
```
X = xor_input = np.array([[0,0], [0,1], [1,0], [1,1]])
Y = xor_output = np.array([[0,1,1,0]]).T
xor_input
xor_output
num_epochs = 10000 # No. of times to iterate.
learning_rate = 0.003 # How large a step to take per iteration.
# Lets drop the last row of data and use that as unseen test.
X = xor_input
Y = xor_output
# Define the shape of the weight vector.
num_data, input_dim = X.shape
# Define the shape of the output vector.
output_dim = len(Y.T)
# Initialize weights between the input layers and the perceptron
W = np.random.random((input_dim, output_dim))
for _ in range(num_epochs):
layer0 = X
# Forward propagation.
# Inside the perceptron, Step 2.
layer1 = sigmoid(np.dot(X, W))
# How much did we miss?
layer1_error = cost(layer1, Y)
# Back propagation.
# multiply how much we missed by the slope of the sigmoid at the values in layer1
layer1_delta = sigmoid_derivative(layer1) * layer1_error
# update weights
W += learning_rate * np.dot(layer0.T, layer1_delta)
# Expected output.
Y
# On the training data
[int(prediction > 0.5) for prediction in layer1] # All correct.
```
You can't represent XOR with simple perceptron !!!
====
No matter how you change the hyperparameters or data, the XOR function can't be represented by a single perceptron layer.
There's no way you can get all four data points to get the correct outputs for the XOR boolean operation.
Solving XOR (Add more layers)
====
```
from itertools import chain
import numpy as np
np.random.seed(0)
def sigmoid(x): # Returns values that sums to one.
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(sx):
# See https://math.stackexchange.com/a/1225116
return sx * (1 - sx)
# Cost functions.
def cost(predicted, truth):
return truth - predicted
xor_input = np.array([[0,0], [0,1], [1,0], [1,1]])
xor_output = np.array([[0,1,1,0]]).T
# Define the shape of the weight vector.
num_data, input_dim = X.shape
# Lets set the dimensions for the intermediate layer.
hidden_dim = 5
# Initialize weights between the input layers and the hidden layer.
W1 = np.random.random((input_dim, hidden_dim))
# Define the shape of the output vector.
output_dim = len(Y.T)
# Initialize weights between the hidden layers and the output layer.
W2 = np.random.random((hidden_dim, output_dim))
# Initialize weigh
num_epochs = 10000
learning_rate = 0.03
for epoch_n in range(num_epochs):
layer0 = X
# Forward propagation.
# Inside the perceptron, Step 2.
layer1 = sigmoid(np.dot(layer0, W1))
layer2 = sigmoid(np.dot(layer1, W2))
# Back propagation (Y -> layer2)
# How much did we miss in the predictions?
layer2_error = cost(layer2, Y)
# In what direction is the target value?
# Were we really close? If so, don't change too much.
layer2_delta = layer2_error * sigmoid_derivative(layer2)
# Back propagation (layer2 -> layer1)
# How much did each layer1 value contribute to the layer2 error (according to the weights)?
layer1_error = np.dot(layer2_delta, W2.T)
layer1_delta = layer1_error * sigmoid_derivative(layer1)
# update weights
W2 += learning_rate * np.dot(layer1.T, layer2_delta)
W1 += learning_rate * np.dot(layer0.T, layer1_delta)
##print(epoch_n, list((layer2)))
# Training input.
X
# Expected output.
Y
layer2 # Our output layer
# On the training data
[int(prediction > 0.5) for prediction in layer2]
```
Now try adding another layer
====
Use the same process:
1. Initialize
2. Forward Propagate
3. Back Propagate
4. Update (aka step)
```
from itertools import chain
import numpy as np
np.random.seed(0)
def sigmoid(x): # Returns values that sums to one.
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(sx):
# See https://math.stackexchange.com/a/1225116
return sx * (1 - sx)
# Cost functions.
def cost(predicted, truth):
return truth - predicted
xor_input = np.array([[0,0], [0,1], [1,0], [1,1]])
xor_output = np.array([[0,1,1,0]]).T
X
Y
# Define the shape of the weight vector.
num_data, input_dim = X.shape
# Lets set the dimensions for the intermediate layer.
layer0to1_hidden_dim = 5
layer1to2_hidden_dim = 5
# Initialize weights between the input layers 0 -> layer 1
W1 = np.random.random((input_dim, layer0to1_hidden_dim))
# Initialize weights between the layer 1 -> layer 2
W2 = np.random.random((layer0to1_hidden_dim, layer1to2_hidden_dim))
# Define the shape of the output vector.
output_dim = len(Y.T)
# Initialize weights between the layer 2 -> layer 3
W3 = np.random.random((layer1to2_hidden_dim, output_dim))
# Initialize weigh
num_epochs = 10000
learning_rate = 1.0
for epoch_n in range(num_epochs):
layer0 = X
# Forward propagation.
# Inside the perceptron, Step 2.
layer1 = sigmoid(np.dot(layer0, W1))
layer2 = sigmoid(np.dot(layer1, W2))
layer3 = sigmoid(np.dot(layer2, W3))
# Back propagation (Y -> layer2)
# How much did we miss in the predictions?
layer3_error = cost(layer3, Y)
# In what direction is the target value?
# Were we really close? If so, don't change too much.
layer3_delta = layer3_error * sigmoid_derivative(layer3)
# Back propagation (layer2 -> layer1)
# How much did each layer1 value contribute to the layer3 error (according to the weights)?
layer2_error = np.dot(layer3_delta, W3.T)
layer2_delta = layer3_error * sigmoid_derivative(layer2)
# Back propagation (layer2 -> layer1)
# How much did each layer1 value contribute to the layer2 error (according to the weights)?
layer1_error = np.dot(layer2_delta, W2.T)
layer1_delta = layer1_error * sigmoid_derivative(layer1)
# update weights
W3 += learning_rate * np.dot(layer2.T, layer3_delta)
W2 += learning_rate * np.dot(layer1.T, layer2_delta)
W1 += learning_rate * np.dot(layer0.T, layer1_delta)
Y
layer3
# On the training data
[int(prediction > 0.5) for prediction in layer3]
```
# Now, lets do it with PyTorch
First lets try a single perceptron and see that we can't train a model that can represent XOR.
```
from tqdm import tqdm
import torch
from torch import nn
from torch.autograd import Variable
from torch import FloatTensor
from torch import optim
use_cuda = torch.cuda.is_available()
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set_style("darkgrid")
sns.set(rc={'figure.figsize':(15, 10)})
X # Original XOR X input in numpy array data structure.
Y # Original XOR Y output in numpy array data structure.
device = 'gpu' if torch.cuda.is_available() else 'cpu'
# Converting the X to PyTorch-able data structure.
X_pt = torch.tensor(X).float()
X_pt = X_pt.to(device)
# Converting the Y to PyTorch-able data structure.
Y_pt = torch.tensor(Y, requires_grad=False).float()
Y_pt = Y_pt.to(device)
print(X_pt)
print(Y_pt)
# Use tensor.shape to get the shape of the matrix/tensor.
num_data, input_dim = X_pt.shape
print('Inputs Dim:', input_dim)
num_data, output_dim = Y_pt.shape
print('Output Dim:', output_dim)
# Use Sequential to define a simple feed-forward network.
model = nn.Sequential(
nn.Linear(input_dim, output_dim), # Use nn.Linear to get our simple perceptron
nn.Sigmoid() # Use nn.Sigmoid to get our sigmoid non-linearity
)
model
# Remember we define as: cost = truth - predicted
# If we take the absolute of cost, i.e.: cost = |truth - predicted|
# we get the L1 loss function.
criterion = nn.L1Loss()
learning_rate = 0.03
# The simple weights/parameters update processes we did before
# is call the gradient descent. SGD is the sochastic variant of
# gradient descent.
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
```
(**Note**: Personally, I strongely encourage you to go through the [University of Washington course of machine learning regression](https://www.coursera.org/learn/ml-regression) to better understand the fundamentals of (i) ***gradient***, (ii) ***loss*** and (iii) ***optimizer***. But given that you know how to code it, the process of more complex variants of gradient/loss computation and optimizer's step is easy to grasp)
# Training a PyTorch model
To train a model using PyTorch, we simply iterate through the no. of epochs and imperatively state the computations we want to perform.
## Remember the steps?
1. Initialize
2. Forward Propagation
3. Backward Propagation
4. Update Optimizer
```
num_epochs = 1000
# Step 1: Initialization.
# Note: When using PyTorch a lot of the manual weights
# initialization is done automatically when we define
# the model (aka architecture)
model = nn.Sequential(
nn.Linear(input_dim, output_dim),
nn.Sigmoid())
criterion = nn.MSELoss()
learning_rate = 1.0
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
num_epochs = 10000
losses = []
for i in tqdm(range(num_epochs)):
# Reset the gradient after every epoch.
optimizer.zero_grad()
# Step 2: Foward Propagation
predictions = model(X_pt)
# Step 3: Back Propagation
# Calculate the cost between the predictions and the truth.
loss_this_epoch = criterion(predictions, Y_pt)
# Note: The neat thing about PyTorch is it does the
# auto-gradient computation, no more manually defining
# derivative of functions and manually propagating
# the errors layer by layer.
loss_this_epoch.backward()
# Step 4: Optimizer take a step.
# Note: Previously, we have to manually update the
# weights of each layer individually according to the
# learning rate and the layer delta.
# PyTorch does that automatically =)
optimizer.step()
# Log the loss value as we proceed through the epochs.
losses.append(loss_this_epoch.data.item())
# Visualize the losses
plt.plot(losses)
plt.show()
for _x, _y in zip(X_pt, Y_pt):
prediction = model(_x)
print('Input:\t', list(map(int, _x)))
print('Pred:\t', int(prediction))
print('Ouput:\t', int(_y))
print('######')
```
Now, try again with 2 layers using PyTorch
====
```
%%time
hidden_dim = 5
num_data, input_dim = X_pt.shape
num_data, output_dim = Y_pt.shape
model = nn.Sequential(nn.Linear(input_dim, hidden_dim),
nn.Sigmoid(),
nn.Linear(hidden_dim, output_dim),
nn.Sigmoid())
criterion = nn.MSELoss()
learning_rate = 0.3
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
num_epochs = 5000
losses = []
for _ in tqdm(range(num_epochs)):
optimizer.zero_grad()
predictions = model(X_pt)
loss_this_epoch = criterion(predictions, Y_pt)
loss_this_epoch.backward()
optimizer.step()
losses.append(loss_this_epoch.data.item())
##print([float(_pred) for _pred in predictions], list(map(int, Y_pt)), loss_this_epoch.data[0])
# Visualize the losses
plt.plot(losses)
plt.show()
for _x, _y in zip(X_pt, Y_pt):
prediction = model(_x)
print('Input:\t', list(map(int, _x)))
print('Pred:\t', int(prediction > 0.5))
print('Ouput:\t', int(_y))
print('######')
```
MNIST: The "Hello World" of Neural Nets
====
Like any deep learning class, we ***must*** do the MNIST.
The MNIST dataset is
- is made up of handwritten digits
- 60,000 examples training set
- 10,000 examples test set
```
# We're going to install tensorflow here because their dataset access is simpler =)
!pip3 install torchvision
from torchvision import datasets, transforms
mnist_train = datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]))
mnist_test = datasets.MNIST('../data', train=False, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]))
# Visualization Candies
import matplotlib.pyplot as plt
def show_image(mnist_x_vector, mnist_y_vector):
pixels = mnist_x_vector.reshape((28, 28))
label = np.where(mnist_y_vector == 1)[0]
plt.title('Label is {}'.format(label))
plt.imshow(pixels, cmap='gray')
plt.show()
# Fifth image and label.
show_image(mnist_train.data[5], mnist_train.targets[5])
```
# Lets apply what we learn about multi-layered perceptron with PyTorch and apply it to the MNIST data.
```
X_mnist = mnist_train.data.float()
Y_mnist = mnist_train.targets.float()
X_mnist_test = mnist_test.data.float()
Y_mnist_test = mnist_test.targets.float()
Y_mnist.shape
# Use FloatTensor.shape to get the shape of the matrix/tensor.
num_data, *input_dim = X_mnist.shape
print('No. of images:', num_data)
print('Inputs Dim:', input_dim)
num_data, *output_dim = Y_mnist.shape
num_test_data, *output_dim = Y_mnist_test.shape
print('Output Dim:', output_dim)
# Flatten the dimensions of the images.
X_mnist = mnist_train.data.float().view(num_data, -1)
Y_mnist = mnist_train.targets.float().unsqueeze(1)
X_mnist_test = mnist_test.data.float().view(num_test_data, -1)
Y_mnist_test = mnist_test.targets.float().unsqueeze(1)
# Use FloatTensor.shape to get the shape of the matrix/tensor.
num_data, *input_dim = X_mnist.shape
print('No. of images:', num_data)
print('Inputs Dim:', input_dim)
num_data, *output_dim = Y_mnist.shape
num_test_data, *output_dim = Y_mnist_test.shape
print('Output Dim:', output_dim)
hidden_dim = 500
model = nn.Sequential(nn.Linear(784, 1),
nn.Sigmoid())
criterion = nn.MSELoss()
learning_rate = 1.0
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
num_epochs = 10
losses = []
plt.ion()
for _e in tqdm(range(num_epochs)):
optimizer.zero_grad()
predictions = model(X_mnist)
loss_this_epoch = criterion(predictions, Y_mnist)
loss_this_epoch.backward()
optimizer.step()
##print([float(_pred) for _pred in predictions], list(map(int, Y_pt)), loss_this_epoch.data[0])
losses.append(loss_this_epoch.data.item())
clear_output(wait=True)
plt.plot(losses)
plt.pause(0.05)
predictions = model(X_mnist_test)
predictions
pred = np.array([np.argmax(_p) for _p in predictions.data.numpy()])
pred
truth = np.array([np.argmax(_p) for _p in Y_mnist_test.data.numpy()])
truth
(pred == truth).sum() / len(pred)
```
| github_jupyter |
# DBSCAN without Libraries
```
import time
import warnings
import queue
import numpy as np
import pandas as pd
from sklearn import cluster, datasets, mixture
from sklearn.neighbors import kneighbors_graph
from sklearn import datasets
# from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
from scipy.stats import norm
from matplotlib import pyplot
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from random import sample
from itertools import cycle, islice
np.random.seed(0)
# ============
# Generate datasets. We choose the size big enough to see the scalability
# of the algorithms, but not too big to avoid too long running times
# ============
n_samples = 1500
n_components = 2 # the number of clusters
X1, y1 = datasets.make_circles(n_samples=n_samples, factor=0.5, noise=0.05)
X2, y2 = datasets.make_moons(n_samples=n_samples, noise=0.05)
X3, y3 = datasets.make_blobs(n_samples=n_samples, random_state=8)
X4, y4 = np.random.rand(n_samples, 2), None
# Anisotropicly distributed data
random_state = 170
# scatter plot, data points annotated by different colors
df = pd.DataFrame(dict(feature_1=X1[:,0], feature_2=X1[:,1], label=y1))
cluster_name = set(y1)
colors = dict(zip(cluster_name, cm.rainbow(np.linspace(0, 1, len(cluster_name)))))
fig, ax = pyplot.subplots()
grouped = df.groupby('label')
for key, group in grouped:
# group.plot(ax=ax, kind='scatter', x='feature_1', y='feature_2', color=colors[key].reshape(1,-1))
group.plot(ax=ax, kind='scatter', x='feature_1', y='feature_2')
# pyplot.title('Original 2D Data from {} Clusters'.format(n_components))
pyplot.show()
# Based on Implementation of
# https://github.com/kiat/Machine-Learning-Algorithms-from-Scratch/blob/master/DBSCAN.py
class CustomDBSCAN():
def __init__(self):
self.core = -1
self.border = -2
# Find all neighbour points at epsilon distance
def neighbour_points(self, data, pointId, epsilon):
points = []
for i in range(len(data)):
# Euclidian distance
if np.linalg.norm([a_i - b_i for a_i, b_i in zip(data[i], data[pointId])]) <= epsilon:
points.append(i)
return points
# Fit the data into the DBSCAN model
def fit(self, data, Eps, MinPt):
# initialize all points as outliers
point_label = [0] * len(data)
point_count = []
# initilize list for core/border points
core = []
border = []
# Find the neighbours of each individual point
for i in range(len(data)):
point_count.append(self.neighbour_points(data, i, Eps))
# Find all the core points, border points and outliers
for i in range(len(point_count)):
if (len(point_count[i]) >= MinPt):
point_label[i] = self.core
core.append(i)
else:
border.append(i)
for i in border:
for j in point_count[i]:
if j in core:
point_label[i] = self.border
break
# Assign points to a cluster
cluster = 1
# Here we use a queue to find all the neighbourhood points of a core point and
# find the indirectly reachable points
# We are essentially performing Breadth First search of all points
# which are within Epsilon distance for each other
for i in range(len(point_label)):
q = queue.Queue()
if (point_label[i] == self.core):
point_label[i] = cluster
for x in point_count[i]:
if(point_label[x] == self.core):
q.put(x)
point_label[x] = cluster
elif(point_label[x] == self.border):
point_label[x] = cluster
while not q.empty():
neighbors = point_count[q.get()]
for y in neighbors:
if (point_label[y] == self.core):
point_label[y] = cluster
q.put(y)
if (point_label[y] == self.border):
point_label[y] = cluster
cluster += 1 # Move on to the next cluster
return point_label, cluster
# Visualize the clusters
def visualize(self, data, cluster, numberOfClusters):
N = len(data)
colors = np.array(list(islice(cycle(['#FE4A49', '#2AB7CA']), 3)))
for i in range(numberOfClusters):
if (i == 0):
# Plot all outliers point as black
color = '#000000'
else:
color = colors[i % len(colors)]
x, y = [], []
for j in range(N):
if cluster[j] == i:
x.append(data[j, 0])
y.append(data[j, 1])
plt.scatter(x, y, c=color, alpha=1, marker='.')
plt.show()
dataset = df.astype(float).values.tolist()
# normalize dataset
X = StandardScaler().fit_transform(dataset)
custom_DBSCAN = CustomDBSCAN()
point_labels, clusters = custom_DBSCAN.fit(X, 0.25, 4)
# print(point_labels, clusters)
custom_DBSCAN.visualize(X, point_labels, clusters)
# Let us change the data and see the results
df = pd.DataFrame(dict(feature_1=X2[:,0], feature_2=X2[:,1], label=y2))
dataset = df.astype(float).values.tolist()
# normalize dataset
X = StandardScaler().fit_transform(dataset)
custom_DBSCAN = CustomDBSCAN()
point_labels, clusters = custom_DBSCAN.fit(X, 0.25, 4)
# print(point_labels, clusters)
custom_DBSCAN.visualize(X, point_labels, clusters)
# Let us change the data and see the results
df = pd.DataFrame(dict(feature_1=X3[:,0], feature_2=X3[:,1], label=y3))
dataset = df.astype(float).values.tolist()
# normalize dataset
X = StandardScaler().fit_transform(dataset)
custom_DBSCAN = CustomDBSCAN()
point_labels, clusters = custom_DBSCAN.fit(X, 0.25, 4)
# print(point_labels, clusters)
custom_DBSCAN.visualize(X, point_labels, clusters)
# Let us change the data and see the results
df = pd.DataFrame(dict(feature_1=X4[:,0], feature_2=X4[:,1], label=y4))
dataset = df.astype(float).values.tolist()
# normalize dataset
X = StandardScaler().fit_transform(dataset)
custom_DBSCAN = CustomDBSCAN()
point_labels, clusters = custom_DBSCAN.fit(X, 0.25, 4)
# print(point_labels, clusters)
custom_DBSCAN.visualize(X, point_labels, clusters)
```
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@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.
#@title MIT License
#
# Copyright (c) 2017 François Chollet # IGNORE_COPYRIGHT: cleared by OSS licensing
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
```
# Transfer Learning Using Pretrained ConvNets
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/community/en/tensorflow_for_poets_reboot.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/examples/community/en/tensorflow_for_poets_reboot.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
```
from __future__ import absolute_import, division, print_function
import tensorflow.compat.v2 as tf #nightly-gpu
tf.enable_v2_behavior()
import os
import numpy as np
import matplotlib.pyplot as plt
from functools import partial
tf.__version__
```
## Data preprocessing
### Data download
```
_URL = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
zip_file = tf.keras.utils.get_file(origin=_URL,
fname="flower_photos.tgz",
extract=True)
base_dir = os.path.join(os.path.dirname(zip_file), 'flower_photos')
IMAGE_SIZE = 224
BATCH_SIZE = 64
datagen = tf.keras.preprocessing.image.ImageDataGenerator(
rescale=1./255,
validation_split=0.2)
train_generator = datagen.flow_from_directory(
base_dir,
target_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size=BATCH_SIZE,
subset='training')
val_generator = datagen.flow_from_directory(
base_dir,
target_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size=BATCH_SIZE,
subset='validation')
for image_batch, label_batch in train_generator:
break
image_batch.shape, label_batch.shape
train_generator.class_indices
```
## Create the base model from the pre-trained convnets
```
IMG_SHAPE = (IMAGE_SIZE, IMAGE_SIZE, 3)
# Create the base model from the pre-trained model MobileNet V2
base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,
include_top=False,
weights='imagenet')
```
## Feature extraction
You will freeze the convolutional base created from the previous step and use that as a feature extractor, add a classifier on top of it and train the top-level classifier.
```
base_model.trainable = False
```
### Add a classification head
```
model = tf.keras.Sequential([
base_model,
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(5, activation='softmax')
])
```
### Compile the model
You must compile the model before training it. Since there are two classes, use a binary cross-entropy loss.
```
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss='categorical_crossentropy',
metrics=['accuracy'])
model.summary()
```
The 2.5M parameters in MobileNet are frozen, but there are 1.2K _trainable_ parameters in the Dense layer. These are divided between two `tf.Variable` objects, the weights and biases.
```
len(model.trainable_variables)
train_generator.labels
```
### Train the model
<!-- TODO(markdaoust): delete steps_per_epoch in TensorFlow r1.14/r2.0 -->
```
epochs = 10
history = model.fit(train_generator,
epochs=epochs,
validation_data=val_generator)
```
### Learning curves
Let's take a look at the learning curves of the training and validation accuracy/loss when using the MobileNet V2 base model as a fixed feature extractor.
```
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.ylabel('Accuracy')
plt.ylim([min(plt.ylim()),1])
plt.title('Training and Validation Accuracy')
plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.ylabel('Cross Entropy')
plt.ylim([0,1.0])
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()
```
Note: If you are wondering why the validation metrics are clearly better than the training metrics, the main factor is because layers like `tf.keras.layers.BatchNormalization` and `tf.keras.layers.Dropout` affect accuracy during training. They are turned off when calculating validation loss.
To a lesser extent, it is also because training metrics report the average for an epoch, while validation metrics are evaluated after the epoch, so validation metrics see a model that has trained slightly longer.
## Fine tuning
In our feature extraction experiment, you were only training a few layers on top of an MobileNet V2 base model. The weights of the pre-trained network were **not** updated during training.
One way to increase performance even further is to train (or "fine-tune") the weights of the top layers of the pre-trained model alongside the training of the classifier you added. The training process will force the weights to be tuned from generic features maps to features associated specifically to our dataset.
Note: This should only be attempted after you have trained the top-level classifier with the pre-trained model set to non-trainable. If you add a randomly initialized classifier on top of a pre-trained model and attempt to train all layers jointly, the magnitude of the gradient updates will be too large (due to the random weights from the classifier) and your pre-trained model will forget what it has learned.
Also, you should try to fine-tune a small number of top layers rather than the whole MobileNet model. In most convolutional networks, the higher up a layer is, the more specialized it is. The first few layers learn very simple and generic features which generalize to almost all types of images. As you go higher up, the features are increasingly more specific to the dataset on which the model was trained. The goal of fine-tuning is to adapt these specialized features to work with the new dataset, rather than overwrite the generic learning.
### Un-freeze the top layers of the model
All you need to do is unfreeze the `base_model` and set the bottom layers be un-trainable. Then, you should recompile the model (necessary for these changes to take effect), and resume training.
```
base_model.trainable = True
# Let's take a look to see how many layers are in the base model
print("Number of layers in the base model: ", len(base_model.layers))
# Fine tune from this layer onwards
fine_tune_at = 100
# Freeze all the layers before the `fine_tune_at` layer
for layer in base_model.layers[:fine_tune_at]:
layer.trainable = False
```
### Compile the model
Compile the model using a much lower training rate.
```
model.compile(loss='categorical_crossentropy',
optimizer = tf.keras.optimizers.Adam(1e-5),
metrics=['accuracy'])
model.summary()
len(model.trainable_variables)
```
### Continue Train the model
If you trained to convergence earlier, this will get you a few percent more accuracy.
```
history_fine = model.fit(train_generator,
epochs=5,
validation_data=val_generator)
```
Let's take a look at the learning curves of the training and validation accuracy/loss, when fine tuning the last few layers of the MobileNet V2 base model and training the classifier on top of it. The validation loss is much higher than the training loss, so you may get some overfitting.
You may also get some overfitting as the new training set is relatively small and similar to the original MobileNet V2 datasets.
## Convert to TFLite
```
saved_model_dir = 'save/fine_tuning'
tf.saved_model.save(model, saved_model_dir)
model = tf.saved_model.load(saved_model_dir)
concrete_func = model.signatures[
tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]
concrete_func.inputs[0].set_shape([1, 224, 224, 3])
converter = tf.lite.TFLiteConverter.from_concrete_function(concrete_func)
tflite_model = converter.convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
```
Download the converted model
```
from google.colab import files
files.download('model.tflite')
acc += history_fine.history['accuracy']
val_acc += history_fine.history['val_accuracy']
loss += history_fine.history['loss']
val_loss += history_fine.history['val_loss']
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.ylim([0.8, 1])
plt.plot([initial_epochs-1,initial_epochs-1],
plt.ylim(), label='Start Fine Tuning')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.ylim([0, 1.0])
plt.plot([initial_epochs-1,initial_epochs-1],
plt.ylim(), label='Start Fine Tuning')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()
```
## Summary:
* **Using a pre-trained model for feature extraction**: When working with a small dataset, it is common to take advantage of features learned by a model trained on a larger dataset in the same domain. This is done by instantiating the pre-trained model and adding a fully-connected classifier on top. The pre-trained model is "frozen" and only the weights of the classifier get updated during training.
In this case, the convolutional base extracted all the features associated with each image and you just trained a classifier that determines the image class given that set of extracted features.
* **Fine-tuning a pre-trained model**: To further improve performance, one might want to repurpose the top-level layers of the pre-trained models to the new dataset via fine-tuning.
In this case, you tuned your weights such that your model learned high-level features specific to the dataset. This technique is usually recommended when the training dataset is large and very similar to the orginial dataset that the pre-trained model was trained on.
| github_jupyter |
# BiDirectional LSTM classifier in keras
#### Load dependencies
```
import keras
from keras.datasets import imdb
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Embedding, SpatialDropout1D, Dense, Flatten, Dropout, LSTM
from keras.layers.wrappers import Bidirectional
from keras.callbacks import ModelCheckpoint # new!
import os # new!
from sklearn.metrics import roc_auc_score, roc_curve # new!
import matplotlib.pyplot as plt # new!
%matplotlib inline
# output directory name:
output_dir = 'model_output/bilstm'
# training:
epochs = 6
batch_size = 128
# vector-space embedding:
n_dim = 64
n_unique_words = 10000
max_review_length = 200
pad_type = trunc_type = 'pre'
drop_embed = 0.2
# neural network architecture:
n_lstm = 256
droput_lstm = 0.2
```
#### Load data
For a given data set:
* the Keras text utilities [here](https://keras.io/preprocessing/text/) quickly preprocess natural language and convert it into an index
* the `keras.preprocessing.text.Tokenizer` class may do everything you need in one line:
* tokenize into words or characters
* `num_words`: maximum unique tokens
* filter out punctuation
* lower case
* convert words to an integer index
```
(x_train, y_train), (x_valid, y_valid) = imdb.load_data(num_words=n_unique_words)
```
#### Preprocess data
```
x_train = pad_sequences(x_train, maxlen=max_review_length, padding=pad_type, truncating=trunc_type, value=0)
x_valid = pad_sequences(x_valid, maxlen=max_review_length, padding=pad_type, truncating=trunc_type, value=0)
x_train[:6]
for i in range(6):
print len(x_train[i])
```
#### Design neural network architecture
```
model = Sequential()
model.add(Embedding(n_unique_words, n_dim, input_length=max_review_length))
model.add(SpatialDropout1D(drop_embed))
# model.add(Conv1D(n_conv, k_conv, activation='relu'))
# model.add(Conv1D(n_conv, k_conv, activation='relu'))
# model.add(GlobalMaxPooling1D())
# model.add(Dense(n_dense, activation='relu'))
# model.add(Dropout(dropout))
model.add(Bidirectional(LSTM(n_lstm, dropout=droput_lstm)))
model.add(Dense(1, activation='sigmoid'))
model.summary()
n_dim, n_unique_words, n_dim * n_unique_words
max_review_length, n_dim, n_dim * max_review_length
```
#### Configure Model
```
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
modelcheckpoint = ModelCheckpoint(filepath=output_dir+"/weights.{epoch:02d}.hdf5")
if not os.path.exists(output_dir):
os.makedirs(output_dir)
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs,
verbose=1, validation_data=(x_valid, y_valid), callbacks=[modelcheckpoint])
```
#### Evaluate
```
model.load_weights(output_dir+"/weights.01.hdf5") # zero-indexed
y_hat = model.predict_proba(x_valid)
len(y_hat)
y_hat[0]
plt.hist(y_hat)
_ = plt.axvline(x=0.5, color='orange')
pct_auc = roc_auc_score(y_valid, y_hat)*100.0
"{:0.2f}".format(pct_auc)
```
| github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from skimage.filters import gaussian
import scipy
import cv2
from scipy import ndimage
import Image_preperation as prep
import FitFunction as fit
import FileManager as fm
import Image_preperation as prep
def calc_mean(points):
size = len(points)
p1 = points[-1]
p2 = points[0]
mean_sum = scipy.spatial.distance.euclidean(p1,p2)
for i in range(size-1):
p1 = points[i]
p2 = points[i+1]
mean_sum += scipy.spatial.distance.euclidean(p1,p2)
return mean_sum / size
def calc_internal2(p1,p2,mean_points):
return np.sum( (p2 - p1)**2 ) / mean_points
def calc_internal(p1,p2,mean_points):
return scipy.spatial.distance.euclidean(p1,p2) / mean_points
def calc_external_img2(img):
median = prep.median_filter(img)
edges = prep.edge_detection_low(median)
return -edges
def calc_external_img(img):
img = np.array(img, dtype=np.int16)
kx = np.array([[-1,0,1],[-2,0,2],[-1,0,1]])
Gx = cv2.filter2D(img,-1,kx)
ky = np.array([[-1,-2,-1],[0,0,0],[1,2,1]])
Gy = cv2.filter2D(img,-1,ky)
G = np.sqrt(Gx**2 + Gy**2)
return G
def calc_external(p, external_img):
p = p.astype(int)
max_value = np.abs(np.min(external_img))
return external_img[p[1],p[0]] / max_value
def calc_energy(p1, p2, external_img, mean_points,alpha):
internal = calc_internal(p1,p2, mean_points)
external = calc_external(p1, external_img)
return internal + alpha * external
def get_point_state(point, rad, number, pixel_width):
positive = number // 2
if(positive == 1):
state = (number + 1) / 2
else:
state = -(number / 2)
return fit.get_point_at_distance(point, state, rad)
def unpack(number, back_pointers, angles, points, pixel_width):
size = len(points)
new_points = np.empty((size,2))
new_points[-1] = get_point_state(points[-1],angles[-1], number, pixel_width)
pointer = back_pointers[-1,number]
for i in range(size-2, -1, -1):
new_points[i] = get_point_state(points[i],angles[i], pointer, pixel_width)
pointer = back_pointers[i,pointer]
return new_points
#https://courses.engr.illinois.edu/cs447/fa2017/Slides/Lecture07.pdf
#viterbi algo
def active_contour(points, edge_img, pixel_width, alpha):
size = len(points)
num_states = (2*pixel_width +1)
trellis = np.zeros((size, num_states), dtype=np.float16)
back_pointers = np.zeros((size, num_states), dtype=int)
#external_img = calc_external_img(img)
if(np.dtype('bool') == edge_img.dtype):
external_img = -np.array(edge_img,dtype=np.int8)
else:
external_img = -edge_img
mean_points = calc_mean(points)
#init
trellis[0,:] = np.zeros((num_states))
back_pointers[0,:] = np.zeros((num_states))
angles = get_angles_of(points)
#recursion
for i in range(1, size):
for t in range(num_states):
trellis[i,t] = np.inf
for d in range(num_states):
p1 = get_point_state(points[i-1], angles[i-1], d, pixel_width)
p2 = get_point_state(points[i],angles[i], t, pixel_width)
energy_trans = calc_energy(p1, p2, external_img,mean_points, alpha)
tmp = trellis[i-1,d] + energy_trans
if(tmp < trellis[i,t]):
trellis[i,t] = tmp
back_pointers[i,t] = d
#find best
t_best, vit_min = 0, np.inf
for t in range(num_states):
if(trellis[size-1, t] < vit_min):
t_best = t
vit_min = trellis[size-1, t]
new_points = unpack(t_best, back_pointers,angles, points, pixel_width)
return new_points
def active_contour_loop(points, img, max_loop, pixel_width, alpha):
old_points = points
for i in range(max_loop):
new_points = active_contour(old_points, img, pixel_width, alpha)
if np.array_equal(new_points, old_points):
print(i)
break
#old_points = new_points
head, tail = np.split(new_points, [6])
old_points = np.append(tail, head).reshape(new_points.shape)
return new_points
def resolution_scale(img, points, scale):
new_points = resolution_scale_points(points, scale)
new_img = resolution_downscale_img(img, scale)
return new_img, new_points
def resolution_scale_points(points, scale):
return np.around(points*scale)
def resolution_downscale_img(img, scale):
x, y = img.shape
xn = int(x*scale)
yn = int(y*scale)
return cv2.resize(img, (yn ,xn))
def get_angles_of(points):
size = len(points)
angles = np.zeros(size)
for i in range(size):
if(i==size-1):
p1, p2, p3 = points[i-1], points[i], points[0]
else:
p1, p2, p3 = points[i-1], points[i], points[i+1]
angles[i] = fit.get_normal_angle(p1, p2, p3)
return angles
def show_results():
piece = fm.load_img_piece()
edge_img = prep.canny(piece)
tooth = fm.load_tooth_of_piece(2)
fm.show_with_points(edge_img, tooth)
new_tooth = active_contour(tooth, edge_img, 25, 1)
fm.show_with_points(edge_img, new_tooth)
def show_influence_ext_int():
new_piece, new_tooth = piece, tooth
mean = calc_mean(new_tooth)
ext = calc_external_img(new_piece)
fm.show_with_points(ext, new_tooth[0:2])
print(calc_external(new_tooth[0],ext))
print(calc_internal(new_tooth[0], new_tooth[1], mean))
print(calc_energy(new_tooth[0],new_tooth[1],ext,mean,10))
if __name__ == "__main__":
piece = fm.load_img_piece()
tooth = fm.load_tooth_of_piece()
ext = prep.calc_external_img_active_contour(piece)
fm.show_with_points(ext, tooth)
ext2, stooth = fm.resolution_scale(ext, tooth, 1/6)
fm.show_with_points(ext2, stooth)
```
| github_jupyter |
```
__name__ = "k1lib.callbacks"
#export
from .callbacks import Callback, Callbacks, Cbs
import k1lib, os, torch
__all__ = ["Autosave", "DontTrainValid", "InspectLoss", "ModifyLoss", "Cpu", "Cuda",
"DType", "InspectBatch", "ModifyBatch", "InspectOutput", "ModifyOutput",
"Beep"]
#export
@k1lib.patch(Cbs)
class Autosave(Callback):
"""Autosaves 3 versions of the network to disk"""
def __init__(self): super().__init__(); self.order = 23
def endRun(self):
os.system("mv autosave-1.pth autosave-0.pth")
os.system("mv autosave-2.pth autosave-1.pth")
self.l.save("autosave-2.pth")
#export
@k1lib.patch(Cbs)
class DontTrainValid(Callback):
"""If is not training, then don't run m.backward() and opt.step().
The core training loop in k1lib.Learner don't specifically do this,
cause there may be some weird cases where you want to also train valid."""
def _common(self):
if not self.l.model.training: return True
def startBackward(self): return self._common()
def startStep(self): return self._common()
#export
@k1lib.patch(Cbs)
class InspectLoss(Callback):
"""Expected `f` to take in 1 float."""
def __init__(self, f): super().__init__(); self.f = f; self.order = 15
def endLoss(self): self.f(self.loss.detach())
#export
@k1lib.patch(Cbs)
class ModifyLoss(Callback):
"""Expected `f` to take in 1 float and return 1 float."""
def __init__(self, f): super().__init__(); self.f = f; self.order = 13
def endLoss(self): self.l.loss = self.f(self.loss)
#export
@k1lib.patch(Cbs)
class Cuda(Callback):
"""Moves batch and model to the default GPU"""
def startRun(self): self.l.model.cuda()
def startBatch(self):
self.l.xb = self.l.xb.cuda()
self.l.yb = self.l.yb.cuda()
#export
@k1lib.patch(Cbs)
class Cpu(Callback):
"""Moves batch and model to CPU"""
def startRun(self): self.l.model.cpu()
def startBatch(self):
self.l.xb = self.l.xb.cpu()
self.l.yb = self.l.yb.cpu()
#export
@k1lib.patch(Cbs)
class DType(Callback):
"""Moves batch and model to a specified data type"""
def __init__(self, dtype): super().__init__(); self.dtype = dtype
def startRun(self): self.l.model = self.l.model.to(self.dtype)
def startBatch(self):
self.l.xb = self.l.xb.to(self.dtype)
self.l.yb = self.l.yb.to(self.dtype)
#export
@k1lib.patch(Cbs)
class InspectBatch(Callback):
"""Expected `f` to take in 2 tensors."""
def __init__(self, f:callable): super().__init__(); self.f = f; self.order = 15
def startBatch(self): self.f(self.l.xb, self.l.yb)
#export
@k1lib.patch(Cbs)
class ModifyBatch(Callback):
"""Modifies xb and yb on the fly. Expected `f`
to take in 2 tensors and return 2 tensors."""
def __init__(self, f): super().__init__(); self.f = f; self.order = 13
def startBatch(self): self.l.xb, self.l.yb = self.f(self.l.xb, self.l.yb)
#export
@k1lib.patch(Cbs)
class InspectOutput(Callback):
"""Expected `f` to take in 1 tensor."""
def __init__(self, f): super().__init__(); self.f = f; self.order = 15
def endPass(self): self.f(self.y)
#export
@k1lib.patch(Cbs)
class ModifyOutput(Callback):
"""Modifies output on the fly. Expected `f` to take
in 1 tensor and return 1 tensor"""
def __init__(self, f): super().__init__(); self.f = f; self.order = 13
def endPass(self): self.l.y = self.f(self.y)
#export
@k1lib.patch(Cbs)
class Beep(Callback):
"""Plays a beep sound when the run is over"""
def endRun(self): k1lib.beep()
!../../export.py callbacks/shorts
```
| github_jupyter |
```
from aide_design.play import*
from aide_design import floc_model as floc
from aide_design import cdc_functions as cdc
from aide_design.unit_process_design.prefab import lfom_prefab_functional as lfom
from pytexit import py2tex
import math
```
# 1 L/s Plants in Parallel
# CHANCEUX
## Priya Aggarwal, Sung Min Kim, Felix Yang
AguaClara has been designing and building water treatment plants since 2005 in Honduras, 2013 in India, and 2017 in Nicaragua. It has been providing gravity powered water treatment systems to thousands of people in rural communities. However, there were populations that could not be targeted due to the technology only being scaled up from 6 L/s. For towns and rural areas with populations with smaller needs, AguaClara technologies were out of their reach.
Recently a one liter per second (1 LPS) plant was developed based on traditional AguaClara technology, to bring sustainable water treatment to towns with populations of 300 people per plant.
The first 1 LPS plant fabricated was sent to Cuatro Comunidades in Honduras, where a built in place plant already exists, and is currently operating without the filter attachment, also known as Enclosed Stacked Rapid Sand Filter (EStaRS). EStaRS is the last step in the 1 LPS plant processes before chlorination and completes the 4 step water treatment process: flocculation, sedimentation, filtration, and chlorination.
Having water treatment plants for smaller flow rates would increase AguaClara’s reach and allow it to help more people. Despite being in its initial stages, the demand for this technology is increasing. Three 1 LPS plants were recently ordered for a town that did not have water treatment. However, the implementation of 1 LPS plants is a problem that has not yet been solved.
This project has stemmed from the possibility of implementing AguaClara technologies to be helpful in Puerto Rico’s post hurricane rebuild effort. The goal of this project is to assess whether the portable 1 L/s plant could be a viable option to help rural communities have safe drinking water. The project models multiple 1 L/s plants working in parallel to provide for the community and plans for the future when communities would need to add capacity. For this project, the team has set 6 L/s as the design constraint. We need experience building and deploying 1 LPS plants to determine the economics and ease of operation to compare to those of built in place plants. For example, if we need 12 L/s, it could still be reasonable to use the 1 LPS plants in parallel or select a 16 L/s built in place plant if more than 12 L/s is needed. Because the dividing line between the modular prefabricated 1 LPS plants and the build in place plants is unknown, the team chose 6 L/s because it is the smallest built in place plant capacity.
Our model is based on the following:
* Standardization modular designs for each plant (1 plant has one EStaRs and Flocculator)
* One entrance tank and chemical dosing controller
* Entrance Tank accomodates to 6 L/s flow
* Coagulant/ Chlorine dosing according to flow by operator
* Parallel Layout for convenience
* Extendable shelter walls to add capacity using chain-link fencing
* Manifolds connecting up to 3 plants (accounting for 3 L/s) from the sedimentation tank to the ESTaRS and after filtration for chlorination (using Ts and fernco caps)
* Manifolds to prevent flow to other filters being cut off if filters need to be backwashed and lacks enough flow
* Equal flow to the filters and chlorination from the manifolds
Calculations follow below.
### Chemical Dosing Flow Rates
Below the functions for calculating the flow rate of the coagulant and chlorine based on the target plant flow rate are shown. The Q_Plant and concentrations of PACL and Cl can be set by the engineer and is set to 3 L/s in this sample calculation.
Chlorine would be ideally done at the end of the filtration where flow recombines so that the operator would only have to administer chlorine at one point. However our drafts did not account for that and instead lack piping that unites the top and bottom 1 L/s plants. Only the 6 L/s draft reflects this optimal design for chlorination.
```
#using Q_plant as the target variable, sample values of what a plant conditions might be are included below
Temperature = u.Quantity(20,u.degC)
Desired_PACl_Concentration=3*u.mg/u.L
Desired_Cl_Concentration=3*u.mg/u.L
C_stock_PACl=70*u.gram/u.L
C_stock_Cl=51.4*u.gram/u.L
NuPaCl = cdc.viscosity_kinematic_pacl(C_stock_PACl,Temperature)
RatioError = 0.1
KMinor = 2
Q_Plant= 3*u.L/u.s
def CDC(Q_Plant, DesiredCl_Concentration,C_stock_PACl):
Q_CDC=(Q_Plant*Desired_PACl_Concentration/C_stock_PACl).to(u.mL/u.s)
return (Q_CDC)
def Chlorine_Dosing(Q_Plant,Desired_Cl_Concentration,C_stock_Cl):
Q_Chlorine=(Q_Plant*Desired_Cl_Concentration/C_stock_Cl).to(u.mL/u.s)
return (Q_Chlorine)
print('The flow rate of coagulant is ',CDC(Q_Plant, Desired_PACl_Concentration, C_stock_PACl).to(u.L/u.hour))
print('The flow rate of chlorine is ',Chlorine_Dosing(Q_Plant, Desired_Cl_Concentration, C_stock_Cl).to(u.L/u.hour))
```
### SPACE CONSTRAINTS
In the code below the team is calculating the floor plan area. The X distance and Y distance are the length and width of the floor plan respectively. The dimensions of the sedimentation tank, flocculator, and entrance tank are accounted for in this calculation.
```
#Claculting the Y distance For the Sed Tank
#properties of sedimentation tank
Sed_Tank_Diameter=0.965*u.m
Length_Top_Half=1.546*u.m #See image for clearer understanding
Y_Sed_Top_Half=Length_Top_Half*math.cos(60*u.degrees)
print(Y_Sed_Top_Half)
Y_Sed_Total=Sed_Tank_Diameter+Y_Sed_Top_Half
print(Y_Sed_Total)
```
SED TANK: Based on the calculation above, the space the Sedimentation tank would take on the floor plant is found to be 1.738 m.

This is a picture of the sedimentation tank with dimensions showing the distance jutting out from the sedimentation tank. This distance of 0.773 m is added to the sedimentation tank diameter totalling 1.738 meters.
ESTaRS: The dimensions of the ESTaRS are set and did not need to be calculated. A single manifold can collect water from the sed tanks and send it to the EStaRS. There will be valves on the manifold system installed before the entrance to the ESTaRS to allow for backwashing. These valves can be shut to allow for enough flow to provide backwashing capacity. There will be a manifold connecting flow after filtration to equate the flow for chlorination.
FLOCCULATOR: We want symmetrical piping systems coming out of the flocculator. There is a flocculator for each plant so that available head going into the parallel sedimentation tanks will be the same. We will have an asymmetrical exit lauder system coming out of the sedimentation tanks going into the ESTaRS (diagram).
ENTRANCE TANK: The entrance tank is set to be at the front of the plant. The focus of this project is to calculate the dimensions and design the plant. The entrance tank dimensions should be left to be designed in the future. An estimated dimension was set in the drawing included in this project. There will be a grit chamber included after the entrance tank. The traditional design for rapid mix that is used in AguaClara plants will be included in the entrance tank.
CONTACT CHAMBER: A contact chamber is included after the entrance tank to ensure that the coagulant is mixed with all of the water before it separates into the multiple treatment trains. Like the entrance tank, contact chamber dimensions should be left to be designed in the future. An estimated dimension was set in the drawing included in this project.
WOODEN PLATFORM: The wooden platform is 4m long, 0.8m wide, and is 1.4 meters high allowing for the operator to be able to access the top of the sedimentation tank, flocculator, and ESTaRS. It would be placed in between every sedimentation tank. In the case of only a single sedimentation tank it would go on the right of the tank because the plant expands to the right.
```
#Spacing due to Entrance Tank and contact chamber #estimated values
Space_ET=0.5*u.m
CC_Diameter=0.4*u.m
Space_Between_ET_CC=0.1*u.m
Space_CC_ET=1*u.m
#Spacing due to Manifold between contact chamber and flocculators
Space_CC_Floc=1.116*u.m
#Spacing due to Flocculator
Space_Flocc_Sed=.1*u.m
Space_Flocculator=0.972*u.m
#Spacing due to the Manifold
Space_Manifold=0.40*u.m
#Spacing due to ESTaRS
Space_ESTaRS=0.607*u.m
#Spacing for ESTaRS Manifold to the wall
Space_ESTaRS_Wall=0.962*u.m
```
The Y distance below 3 L/s is set to be as a sum of the total Y distance of the flocculator, sedimentation tank, and ESTaRS. An additional 2 meters of Y distance is added for operator access around the plant. The lengths between the sedimentation tank, flocculator and ESTarS were kept minimal but additional Y distance can be taken off between the sedimentation tank and ESTaRS. This is because the ESTaRS can hide under the sloping half of the sedimentation tank but this orientation would not account for the manifold drawn in the picture.
The total Y distance is calculated below.
```
Y_Length_Top=(Space_CC_ET+Space_CC_Floc+Space_Flocc_Sed
+Space_Flocculator+Y_Sed_Total+Space_Manifold+Space_ESTaRS+
Space_ESTaRS_Wall)
Y_Length_Bottom=Y_Length_Top-0.488*u.m
```
Below are functions that can be used to design a plant based on the desired flow rate
```
def X(Q):
if Q>3*u.L/u.s:
X_Distance_Bottom=X(Q-3*u.L/u.s)
X_Distance_Top=6.9*u.m
return(X_Distance_Top,X_Distance_Bottom)
else:
Q_Plant=Q.to(u.L/u.s)
Extra_Space=2*u.m
X_Distance=(Q_Plant.magnitude-1)*1*u.m+(Q_Plant.magnitude)*.965*u.m+Extra_Space
return(X_Distance.to(u.m))
def Y(Q):
if Q>3*u.L/u.s:
return(Y_Length_Top+Y_Length_Bottom)
else:
return(Y_Length_Top)
print(X(Q_Plant_2).to(u.m))
def Area_Plant(Q):
if Q>3*u.L/u.s:
X_Distance_Bottom=X(Q-3*u.L/u.s)
Area_Bottom=X_Distance_Bottom*Y_Length_Bottom*((Q/u.L*u.s-3))
Area_Top=X(3*u.L/u.s)*Y_Length_Top
Area_Total=Area_Top+Area_Bottom
return(Area_Total)
else:
H_Distance=X(Q_Plant)
Y_Distance=Y_Length_Top
Area_Total=H_Distance*Y_Distance
return(Area.to(u.m**2))
```

This is a layout of a sample plant for three 1 L/s tanks running in parallel. Check bottom of document for additional drafts.
A platform will be in between sedimentation tanks as a way for the operators to have access to the sedimentation tanks. The platform height will be 1.4m to allow the plant operators 0.5m to view the sedimentation tanks just as in the built in place plants. The operator access requirements influence the optimal plant layout because the operators movements and safety have to be considered. The manifold will be built underneath the platform for space efficiency. The image below shows the wooden platform with 4m of length but could be truncated or extended to depending on the situation. The last image shows the platform in between the sedimentation tanks in the 3 L/s sample plant.

Wooden platforms would fill up the space in between sedimentation tanks to allow for operator access to the top of sedimentation tanks, ESTaRS and flocculators.

### Adding Capacity
When adding capacity up to plant flow rates of 3 L/s, vertical distance will be constant so adding capacity will only change the horizontal distance of the plant. We define a set of flocculator, sedimentation tank, and EStARS as a 1 L/s plant.
After the capacity of the plant reaches 3 L/s, additional 1 L/s plants will be added to the bottom half of the building, using a mirrored layout as the top half of the building. The only difference between the spacing is that the additions no longer need another entrance tank so the width of the bottom half of the plant is shorter than the width of the top half. This was done instead of simply increasing the length of the plant each time capacity was added because the length of the pipe between the contact chamber and the farthest flocculator would become increasingly large. This addition of major losses would cause different flow rates between the farther 1LPS plant and the closest one.
The following function will only account for adding 1 L/s plants one at at a time
```
def Additional_Area(Q_Plant,Q_Extra):
if (Q_Plant+Q_Extra>3*u.L/u.s):
X_Distance_Extra=X(Q_Extra)
Y_Distance_Extra=Y_Length_Bottom
Area=(X_Distance_Extra*Y_Distance_Extra).to(u.m**2)
return(Area)
else:
Q=Q_Extra.to(u.L/u.s)
Horizontal=(Q_Extra.magnitude)*.965*u.m+(Q_Extra.magnitude)*1*u.m
Vertical=5.512*u.m
Extra_Area=Vertical*Horizontal
print('Extra length that has to be added is '+ut.sig(Horizontal,4))
return(ut.sig(Extra_Area,2))
```
### ESTaRS
The total surface area required for the ESTaRS filter is simply a product of the area one ESTaRS requires and the flow rate coming into the plant. The surface area required for an ESTaRS was measured in the DeFrees lab. It is approximately a square meter.
```
ESTaRS_SA=1*u.m**2/u.L
def Area_ESTaRS(Q):
Q_Plant=Q.to(u.L/u.s)
Surface_Area_ESTaRS=(ESTaRS_SA.magnitude)*Q_Plant.magnitude
return(Surface_Area_ESTaRS*u.m**2)
print('Surface area required for the ESTaR(s) is',Area_ESTaRS(Q_Plant))
```
### Flocculators
The total surface area required for the ESTaRS filter is simply a product of the area one ESTaRS requires and the flow rate coming into the plant. The surface area required for an ESTaRS was measured in the DeFrees lab. It is approximately a square meter.
```
Flocc_SA=0.972*u.m*0.536*u.m*u.L/u.s
def Area_Flocc(Q):
Q_Plant=Q.to(u.L/u.s)
Surface_Area_Flocc=(Flocc_SA.magnitude)*Q_Plant.magnitude
return(Surface_Area_Flocc*u.m**2)
print('Surface area required for the flocculator(s) is',Area_Flocc(Q_Plant))
```
### Manifold Headloss Calculations
The amount of headloss has to be minimal so that the amount of head availible coming out of the exit launder is enough to drive water fast enough to fluidize the sand bed in ESTaRS. This fluidization is required for backwashing the filter. Since the calculation for 4 inch pipe has a headloss for less than 1mm we conclude that the manifold is economically feasible. Any futher increase in the diameter of the manifold would become increasingly expensive.
```
SDR = 26
SF=1.33
Q_Manifold = 1 * u.L/u.s #max flowrate for a manifold
Q_UpperBound=SF*Q_Manifold
L_pipe = 5*u.m #Length sed tank to it’s ESTaRS
K_minor_bend=0.3
K_minor_branch=1
K_minor_contractions=1
K_minor_total= 2*(K_minor_bend+K_minor_branch+K_minor_contractions) # (two bends, two dividing branch, and two contractions)
# The maximum viscosity will occur at the lowest temperature.
T_crit = u.Quantity(10,u.degC)
nu = pc.viscosity_kinematic(T_crit)
e = 0.1 * u.mm
Manifold_1LPS_ID=4*u.inch
Headloss_Max=10*u.mm
Manifold_Diam=pc.diam_pipe(Q_Manifold,Headloss_Max,L_pipe,nu,e,K_minor_total).to(u.inch)
print(Manifold_Diam.to(u.inch))
print('The minimum pipe inner diameter is '+ ut.sig(Manifold_Diam,2)+'.')
Manifold_ND = pipe.ND_SDR_available(Manifold_Diam,SDR)
print('The nominal diameter of the manifold is '+ut.sig(Manifold_ND,2)+' ('+ut.sig(Manifold_ND.to(u.inch),2)+').')
HLCheck = pc.headloss(Q_UpperBound,Manifold_1LPS_ID,L_pipe,nu,e,K_minor_total)
print('The head loss is',HLCheck.to(u.mm))
```
# Drafts of 1 L/s Plant to 6 L/s Plant

A sample 1 L/s plant. The red t's indicate where the piping system can be expanded to include more 1 L/s systems. Additionally the t would be covered by a fernco cap so that the pipe can be removed when the plant is adding capacity. See cell below for pictures of manifolds with caps.

The sample 2 L/s plant. The red t's indicate where the piping system can be expanded to include more 1 L/s plants. Additionally the t exit that isn't connected to any piping would be covered by a fernco cap so that the pipe can be removed when the plant is adding capacity.

The sample 3 L/s plant. There are now no more t's that can be extended because the manifold was designed for up to 3 1 L/s plants. Further capacities are added on the bottom half of the plant like in the next 3 pictures.

The sample 4 L/s plant. Like in the 1 L/s plant the red t's indicate the start of the 2nd manifold system.

The sample 5 L/s plant. The length (x-direction) is extended by the diameter of a sedimentation tank and one meter like in the top half of the plant. However the width of the bottom half is slightly lower because it can use the already built entrance tank used for the first 3 L/s systems.

The sample 6 L/s plant. The building is now at full capacity with an area of 91.74 m^2. The flow reunites to allow for chlorination to be administered at one point.
# Manifold Drafts

The manifold with 1 L/s. The elbow at the top is connected to the exit launder of the sedimentation tank. The flow goes from the exit launder into the reducer which is not yet connected in the draft to the ESTaRS. The removeable fernco cap that allows for further expansions of the manifold pipe system can be seen in the picture.

The manifold with 2 L/s. Again a fernco cap is used to allow for future expansions up to 3 L/s.

The manifold with 3 L/s. Here there are no fernco caps because the manifold is designed for up to connections with three 1 L/s plants.
| github_jupyter |
```
from pysead import Truss_2D
import numpy as np
from random import random
import matplotlib.pyplot as plt
# initialize node dictionary
nodes = {}
# compute distances
distances_1 = np.arange(0,5*240,240)
distances_2 = np.arange(0,9*120,120)
# from node 1 to node 5
for i, distance in enumerate(distances_1):
nodes.update({i+1: [distance, 360+144*10]})
# from node 6 to node 14
for i, distance in enumerate(distances_2):
nodes.update({i+6: [distance, 360+144*9]})
# from node 15 to node 19
for i, distance in enumerate(distances_1):
nodes.update({i+15: [distance, 360+144*8]})
# from node 20 to node 28
for i, distance in enumerate(distances_2):
nodes.update({i+20: [distance, 360+144*7]})
# from node 29 to node 33
for i, distance in enumerate(distances_1):
nodes.update({i+29: [distance, 360+144*6]})
# from node 34 to node 42
for i, distance in enumerate(distances_2):
nodes.update({i+34: [distance, 360+144*5]})
# from node 43 to node 47
for i, distance in enumerate(distances_1):
nodes.update({i+43: [distance, 360+144*4]})
# from node 48 to node 56
for i, distance in enumerate(distances_2):
nodes.update({i+48: [distance, 360+144*3]})
# from node 57 to node 61
for i, distance in enumerate(distances_1):
nodes.update({i+57: [distance, 360+144*2]})
# from node 62 to node 70
for i, distance in enumerate(distances_2):
nodes.update({i+62: [distance, 360+144*1]})
# from node 71 to node 75
for i, distance in enumerate(distances_1):
nodes.update({i+71: [distance, 360]})
nodes.update({76:[240,0], 77:[120*6,0]})
elements = {1:[1,2], 2:[2,3], 3:[3,4], 4:[4,5],
5:[6,1], 6:[7,1], 7:[7,2], 8:[8,2], 9:[9,2], 10:[9,3], 11:[10,3], 12:[11,3], 13:[11,4], 14:[12,4], 15:[13,4], 16:[13,5], 17:[14,5],
18:[6,7], 19:[7,8], 20:[8,9], 21:[9,10], 22:[10,11], 23:[11,12], 24:[12,13], 25:[13,14],
26:[15,6], 27:[15,7], 28:[16,7], 29:[16,8], 30:[16,9], 31:[17,9], 32:[17,10], 33:[17,11], 34:[18,11], 35:[18,12], 36:[18,13], 37:[19,13], 38:[19,14],
39:[15,16], 40:[16,17], 41:[17,18], 42:[18,19],
43:[20,15], 44:[21,15], 45:[21,16], 46:[22,16], 47:[23,16], 48:[23,17], 49:[24,17], 50:[25,17], 51:[25,18], 52:[26,18], 53:[27,18], 54:[27,19], 55:[28,19],
56:[20,21], 57:[21,22], 58:[22,23], 59:[23,24], 60:[24,25], 61:[25,26], 62:[26,27], 63:[27,28],
64:[29,20], 65:[29,21], 66:[30,21], 67:[30,22], 68:[30,23], 69:[31,23], 70:[31,24], 71:[31,25], 72:[32,25], 73:[32,26], 74:[32,27], 75:[33,27], 76:[33,28],
77:[29,30], 78:[30,31], 79:[31,32], 80:[32,33],
81:[34,29], 82:[35,29], 83:[35,30], 84:[36,30], 85:[37,30], 86:[37,31], 87:[38,31], 88:[39,31], 89:[39,32], 90:[40,32], 91:[41,32], 92:[41,33], 93:[42,33],
94:[34,35], 95:[35,36], 96:[36,37], 97:[37,38], 98:[38,39], 99:[39,40], 100:[40,41], 101:[41,42],
102:[43,34], 103:[43,35], 104:[44,35], 105:[44,36], 106:[44,37], 107:[45,37], 108:[45,38], 109:[45,39], 110:[46,39], 111:[46,40], 112:[46,41], 113:[47,41], 114:[47,42],
115:[43,44], 116:[44,45], 117:[45,46], 118:[46,47], 119:[48,43], 120:[49,43], 121:[49,44], 122:[50,44], 123:[51,44], 124:[51,45], 125:[52,45], 126:[53,45], 127:[53,46], 128:[54,46], 129:[55,46], 130:[55,47], 131:[56,47],
132:[48,49], 133:[49,50], 134:[50,51], 135:[51,52], 136:[52,53], 137:[53,54], 138:[54,55], 139:[55,56], 140:[57,48], 141:[57,49], 142:[58,49], 143:[58,50], 144:[58,51], 145:[59,51], 146:[59,52], 147:[59,53], 148:[60,53], 149:[60,54], 150:[60,55], 151:[61,55], 152:[61,56],
153:[57,58], 154:[58,59], 155:[59,60], 156:[60,61],
157:[62,57], 158:[63,57], 159:[63,58], 160:[64,58], 161:[65,58], 162:[65,59], 163:[66,59], 164:[67,59], 165:[67,60], 166:[68,60], 167:[69,60], 168:[69,61], 169:[70,61],
170:[62,63], 171:[63,64], 172:[64,65], 173:[65,66], 174:[66,67], 175:[67,68], 176:[68,69], 177:[69,70],
178:[71,62], 179:[71,63], 180:[72,63], 181:[72,64], 182:[72,65], 183:[73,65], 184:[73,66], 185:[73,67], 186:[74,67], 187:[74,68], 188:[74,69], 189:[75,69], 190:[75,70],
191:[71,72], 192:[72,73], 193:[73,74], 194:[74,75],
195:[76,71], 196:[76,72], 197:[76,73], 198:[77,73], 199:[77,74], 200:[77,75]}
supports = {76:[1,1], 77:[1,1]}
elasticity = {key: 30_000 for key in elements}
forces = {key: [0,-10] for key in [1, 2, 3, 4, 5, 6, 8, 10, 12, 14, 15, 16, 17, 18, 19, 20, 22, 24, 26, 28, 29, 30, 31, 32, 33, 34, 36, 38, 40, 42, 43, 44, 45, 46, 47, 48, 50, 52, 54, 56, 57, 58, 59, 60, 61, 62, 64, 66, 68, 70, 71,72, 73, 74,75]}
forces.update({key: [1,-10] for key in [1,6,15,20,29,34,43,48,57,62,71]})
def Truss_solver(cross_sectional_areas):
cross_area = {key: cross_sectional_areas[key - 1] for key in elements}
Two_Hundred_Truss_Case_1 = Truss_2D(nodes = nodes,
elements= elements,
supports= supports,
forces = forces,
elasticity= elasticity,
cross_area= cross_area)
Two_Hundred_Truss_Case_1.Solve()
return (Two_Hundred_Truss_Case_1.member_lengths_, Two_Hundred_Truss_Case_1.member_stresses_, Two_Hundred_Truss_Case_1.displacements_)
```
## Step 2: Define Objective Function
```
def Objective_Function(areas):
member_lengths, member_stresses, node_displacements = Truss_solver(areas)
total_area = np.array(areas)
total_member_lengths = []
for length in member_lengths:
total_member_lengths.append(member_lengths[length])
total_member_lengths = np.array(total_member_lengths)
weight = total_area.dot(np.array(total_member_lengths))
weight = weight.sum() * 0.283 # lb/in^3
return (weight, member_stresses, node_displacements)
```
## Step 3: Define Constraints
```
def stress_constraint(stress_new):
if stress_new > 30 or stress_new < -30:
stress_counter = 1
else:
stress_counter = 0
return stress_counter
def displacement_constraint(node_displacement_new):
x = node_displacement_new[0]
y = node_displacement_new[1]
if x > 0.5 or x < -0.5:
displacement_counter = 1
elif y > 0.5 or y < -0.5:
displacement_counter = 1
else:
displacement_counter = 0
return displacement_counter
```
Step 4: Define Algorithm
Step 4.1: Initialize Parameters
```
D = [0.100, 0.347, 0.440, 0.539, 0.954, 1.081, 1.174, 1.333, 1.488,
1.764, 2.142, 2.697, 2.800, 3.131, 3.565, 3.813, 4.805, 5.952, 6.572,
7.192, 8.525, 9.300, 10.850, 13.330, 14.290, 17.170, 19.180, 23.680,
28.080, 33.700]
def closest(list_of_areas, area_values_list):
for i, area_value in enumerate(area_values_list):
idx = (np.abs(list_of_areas - area_value)).argmin()
area_values_list[i] = list_of_areas[idx]
return area_values_list
cross_area_groupings = {1:[1,4], 2:[2,3], 3:[5,17], 4:[6,16], 5:[7,15], 6:[8,14], 7:[9,13], 8:[10,12], 9:[11], 10:[132,139,170,177,18,25,56,63],
11:[19,20,23,24], 12:[21,22], 13:[26,38], 14:[27,37], 15:[28,36], 16:[29,35], 17:[30,34], 18:[31,33], 19:[32], 20:[39,42],
21:[40,41], 22:[43,55], 23:[44,54], 24:[45,53], 25:[46,52], 26:[47,51], 27:[48,50], 28:[49], 29:[57,58,61,62], 30:[59,60],
31:[64,76], 32:[65,75], 33:[66,74], 34:[67,73], 35:[68,72], 36:[69,71], 37:[70], 38:[77,80], 39:[78,79], 40:[81,93],
41:[82,92], 42:[83,91], 43:[84,90], 44:[85,89], 45:[86,88], 46:[87], 47:[95,96,99,100], 48:[97,98], 49:[102,114], 50:[103,113],
51:[104,112], 52:[105,111], 53:[106,110], 54:[107, 109], 55:[108], 56:[115,118], 57:[116,117], 58:[119,131], 59:[120,130], 60:[121,129],
61:[122,128], 62:[123,127], 63:[124,126], 64:[125], 65:[133,134,137,138], 66:[135,136], 67:[140,152], 68:[141,151], 69:[142,150], 70:[143,149],
71:[144,148], 72:[145,147], 73:[146], 74:[153,156], 75:[154,155], 76:[157,169], 77:[158,168], 78:[159,167], 79:[160,166], 80:[161,165],
81:[162,164], 82:[163], 83:[171,172,175,176], 84:[173,174], 85:[178,190], 86:[179,189], 87:[180,188], 88:[181,187], 89:[182,186], 90:[183,185],
91:[184], 92:[191,194], 93:[192,193], 94:[195,200], 95:[196,199], 96:[197,198], 97:[94,101]}
area_old = [35 for i in range(len(elements))]
# intermediate variables
k = 0.05 # move variable's constant
M = 1000 # number of loops to be performed
T0 = 10000 # initial temperature
N = 20 # initial number of neighbors per search space loop
alpha = 0.85 # cooling parameter
temp = [] # storing of values for the temperature per loop M
min_weight = [] # storing best value of the objective function per loop M
area_list = [] # storing x values per loop for plotting purposes
def Random_Number_Check(objective_old, objective_new, Init_temp):
return 1/((np.exp(objective_old - objective_new)) / Init_temp)
%%time
for m in range(M):
for n in range(N):
# generate random area from choices
# create random area array from area choices
area_random_array = np.random.choice(D,len(cross_area_groupings))
# create dictionary from random array
cross_area_dict = {key+1: area_random_array[key] for key in range(len(area_random_array))}
# create dictionary from cross area dictionary that follows the groupings dictionary
cross_area = {}
for group in cross_area_groupings:
value = cross_area_dict[group]
for element in cross_area_groupings[group]:
dict_append = {element: value}
cross_area.update(dict_append)
# Sort the cross area groupings dictionary in asending order
cross_area = {k: v for k, v in sorted(cross_area.items(), key=lambda item: item[0])}
# flatten the cross area groupings dictionary to a list
area_new = []
for area in cross_area:
area_new.append(cross_area[area])
area_new = np.array(area_new)
for i,area in enumerate(area_old):
random_area = random()
if random_area >= 0.5:
area_new[i] = k*random_area
else:
area_new[i] = -k*random_area
for i, area in enumerate(area_old):
area_new[i] = area_old[i] + area_new[i]
closest(D,area_new)
weight_computed, stresses_new, node_displacement_new = Objective_Function(area_new)
weight_old, _, _ = Objective_Function(area_old)
check = Random_Number_Check(weight_computed, weight_old, T0)
random_number = random()
# Contraint 1: stresses should be within 25ksi and -25ksi
stress_counter = []
for j in stresses_new:
stress_counter.append(stress_constraint(stresses_new[j]))
stress_counter = sum(stress_counter)
# Constraint 2: Node Displacement should be limited to -2in and 2in
displacement_counter = 0
for k in node_displacement_new:
displacement_counter = displacement_counter + displacement_constraint(node_displacement_new[k])
if stress_counter >= 1 or displacement_counter >= 1:
area_old = area_old
else:
if weight_computed <= weight_old:
area_old = area_new
elif random_number <= check:
area_old = area_new
else:
area_old = area_old
temp.append(T0)
min_weight.append(weight_old)
area_list.append(area_old)
T0 = alpha * T0
plt.figure(figsize=[12,6])
plt.grid(True)
plt.xlabel('Iterations')
plt.ylabel('Weight')
plt.title('Iterations VS Weight')
plt.plot(min_weight)
area_list[-1]
cross_area = {key: area_list[-1][key-1] for key in elements}
Two_Hundred_Truss_Case_1 = Truss_2D(nodes = nodes,
elements= elements,
supports= supports,
forces = forces,
elasticity= elasticity,
cross_area= cross_area)
Two_Hundred_Truss_Case_1.Solve()
Two_Hundred_Truss_Case_1.Draw_Truss_Displacements(figure_size=[15,25])
Two_Hundred_Truss_Case_1.displacements_
weight, _, _ = Objective_Function(area_list[-1])
weight
```
| github_jupyter |
```
import os
import sys
import keras
import numpy as np
import tensorflow as tf
from keras import datasets
import matplotlib
import matplotlib.pyplot as plt
sys.path.append(os.getcwd() + "/../")
from bfcnn import BFCNN, collage, get_conv2d_weights
# setup environment
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
tf.compat.v1.disable_eager_execution()
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
# get dataset
(x_train, y_train), (x_test, y_test) = datasets.mnist.load_data()
x_train = x_train.astype(np.float32)
x_train = np.expand_dims(x_train, axis=3)
x_test = x_test.astype(np.float32)
x_test = np.expand_dims(x_test, axis=3)
EPOCHS = 10
FILTERS = 32
NO_LAYERS = 5
MIN_STD = 1.0
MAX_STD = 100.0
LR_DECAY = 0.9
LR_INITIAL = 0.1
BATCH_SIZE = 64
CLIP_NORMAL = 1.0
INPUT_SHAPE = (28, 28, 1)
PRINT_EVERY_N_BATCHES = 2000
# build model
model = \
BFCNN(
input_dims=INPUT_SHAPE,
no_layers=NO_LAYERS,
filters=FILTERS,
kernel_regularizer=keras.regularizers.l2(0.001))
# train dataset
trained_model, history = \
BFCNN.train(
model=model,
input_dims=INPUT_SHAPE,
dataset=x_train,
epochs=EPOCHS,
batch_size=BATCH_SIZE,
min_noise_std=MIN_STD,
max_noise_std=MAX_STD,
lr_initial=LR_INITIAL,
lr_decay=LR_DECAY,
print_every_n_batches=PRINT_EVERY_N_BATCHES)
matplotlib.use("nbAgg")
# summarize history for loss
plt.figure(figsize=(15,5))
plt.plot(history.history["loss"],
marker="o",
color="red",
linewidth=3,
markersize=6)
plt.grid(True)
plt.title("model loss")
plt.ylabel("loss")
plt.xlabel("epoch")
plt.legend(["train"], loc="upper right")
plt.show()
from math import log10
# calculate mse for different std
sample_test = x_test[0:1024,:,:,:]
sample_test_mse = []
sample_train = x_train[0:1024,:,:,:]
sample_train_mse = []
sample_std = []
for std_int in range(0, int(MAX_STD), 5):
std = float(std_int)
#
noisy_sample_test = sample_test + np.random.normal(0.0, std, sample_test.shape)
noisy_sample_test = np.clip(noisy_sample_test, 0.0, 255.0)
results_test = trained_model.model.predict(noisy_sample_test)
mse_test = np.mean(np.power(sample_test - results_test, 2.0))
sample_test_mse.append(mse_test)
#
noisy_sample_train = sample_train + np.random.normal(0.0, std, sample_train.shape)
noisy_sample_train = np.clip(noisy_sample_train, 0.0, 255.0)
results_train = trained_model.model.predict(noisy_sample_train)
mse_train = np.mean(np.power(sample_train - results_train, 2.0))
sample_train_mse.append(mse_train)
#
sample_std.append(std)
matplotlib.use("nbAgg")
# summarize history for loss
plt.figure(figsize=(16,8))
plt.plot(sample_std,
[20 * log10(255) -10 * log10(m) for m in sample_test_mse],
color="red",
linewidth=2)
plt.plot(sample_std,
[20 * log10(255) -10 * log10(m) for m in sample_train_mse],
color="green",
linewidth=2)
plt.grid(True)
plt.title("Peak Signal-to-Noise Ratio")
plt.ylabel("PSNR")
plt.xlabel("Additive normal noise standard deviation")
plt.legend(["test", "train"], loc="lower right")
plt.show()
# draw test samples, predictions and diff
matplotlib.use("nbAgg")
sample = x_test[0:64,:,:,:]
noisy_sample = sample + np.random.normal(0.0, MAX_STD, sample.shape)
noisy_sample = np.clip(noisy_sample, 0.0, 255.0)
results = trained_model.model.predict(noisy_sample)
plt.figure(figsize=(14,14))
plt.subplot(2, 2, 1)
plt.imshow(collage(sample), cmap="gray_r")
plt.subplot(2, 2, 2)
plt.imshow(collage(noisy_sample), cmap="gray_r")
plt.subplot(2, 2, 3)
plt.imshow(collage(results), cmap="gray_r")
plt.subplot(2, 2, 4)
plt.imshow(collage(np.abs(sample - results)), cmap="gray_r")
plt.show()
trained_model.save("./model.h5")
m = trained_model.model
weights = get_conv2d_weights(m)
matplotlib.use("nbAgg")
plt.figure(figsize=(14,5))
plt.grid(True)
plt.hist(x=weights, bins=500, range=(-0.4,+0.4), histtype="bar", log=True)
plt.show()
```
| github_jupyter |
# Task 4: Classification
_All credit for the code examples of this notebook goes to the book "Hands-On Machine Learning with Scikit-Learn & TensorFlow" by A. Geron. Modifications were made and text was added by K. Zoch in preparation for the hands-on sessions._
# Setup
First, import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures:
```
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)
# Function to save a figure. This also decides that all output files
# should stored in the subdirectorz 'classification'.
PROJECT_ROOT_DIR = "."
EXERCISE = "classification"
def save_fig(fig_id, tight_layout=True):
path = os.path.join(PROJECT_ROOT_DIR, "output", EXERCISE, fig_id + ".png")
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(path, format='png', dpi=300)
```
# Preparing the dataset
Define a function to sort the dataset into the 'targets' train and test data. This is needed because we want to use the same 60,000 data points for training, and the sam e10,000 data points for testing on every machine (and the dataset provided through Scikit-Learn is already prepared in this way).
```
def sort_by_target(mnist):
reorder_train = np.array(sorted([(target, i) for i, target in enumerate(mnist.target[:60000])]))[:, 1]
reorder_test = np.array(sorted([(target, i) for i, target in enumerate(mnist.target[60000:])]))[:, 1]
mnist.data[:60000] = mnist.data[reorder_train]
mnist.target[:60000] = mnist.target[reorder_train]
mnist.data[60000:] = mnist.data[reorder_test + 60000]
mnist.target[60000:] = mnist.target[reorder_test + 60000]
```
Now fetch the dataset using the SciKit-Learn function (this might take a moment ...).
```
# We need this try/except for different Scikit-Learn versions.
try:
from sklearn.datasets import fetch_openml
mnist = fetch_openml('mnist_784', version=1, cache=True)
mnist.target = mnist.target.astype(np.int8) # fetch_openml() returns targets as strings
sort_by_target(mnist) # fetch_openml() returns an unsorted dataset
except ImportError:
from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original')
mnist["data"], mnist["target"]
```
Let's have a look at what the 'data' key contains: it is a numpy array with one row per instance and one column per feature.
```
mnist["data"]
```
And the same for the 'target' key which is an array of labels.
```
mnist["target"]
```
Now, let's first define the more useful `x` and `y` aliases for the data and target keys, and let's have a look at the type of data using the `shape` function: we see 70,000 entries in the data array, with 784 features each. The 784 correspond to 28x28 pixels of an image with brightness values between 0 and 255.
```
X, y = mnist["data"], mnist["target"]
X.shape # get some information about its shape
28*28 # just a little cross-check we're doing the correct arithmetics here ...
X[36000][160:200] # Plot brightness values [160:200] of the random image X[36000].
```
Now let's have a look at one of the images. We just pick a random image and use the `numpy.reshape()` function to reshape it into an array of 28x28 pixels. Then we can plot it with `matplotlib.pyplot.imshow()`:
```
some_digit = X[36000]
some_digit_image = some_digit.reshape(28, 28)
plt.imshow(some_digit_image, cmap = mpl.cm.binary,
interpolation="nearest")
plt.axis("off")
save_fig("some_digit_plot")
plt.show()
```
Let's quickly define a function to plot one of the digits, we will need it later down the line. It might also be useful to have a function to plot multiple digits in a batch (we will also use this function later). The following two cells will not produce any output.
```
def plot_digit(data):
image = data.reshape(28, 28)
plt.imshow(image, cmap = mpl.cm.binary,
interpolation="nearest")
plt.axis("off")
def plot_digits(instances, images_per_row=10, **options):
size = 28
images_per_row = min(len(instances), images_per_row)
images = [instance.reshape(size,size) for instance in instances]
n_rows = (len(instances) - 1) // images_per_row + 1
row_images = []
n_empty = n_rows * images_per_row - len(instances)
images.append(np.zeros((size, size * n_empty)))
for row in range(n_rows):
rimages = images[row * images_per_row : (row + 1) * images_per_row]
row_images.append(np.concatenate(rimages, axis=1))
image = np.concatenate(row_images, axis=0)
plt.imshow(image, cmap = mpl.cm.binary, **options)
plt.axis("off")
```
Great, now we can plot multiple digits at once. Let's ignore the details of the `np.r_[]` function and the indexing used within it for now and focus on what it does: it takes ten examples of each digit from the data array, which we can then plot with our `plot_digits()` function.
```
plt.figure(figsize=(9,9))
example_images = np.r_[X[:12000:600], X[13000:30600:600], X[30600:60000:590]]
plot_digits(example_images, images_per_row=10)
save_fig("more_digits_plot")
plt.show()
```
Ok, at this point we have a fairly good idea how our data array looks like: we have an array of 70,000 images with 28x28 pixels each. The entries in the array are sorted according to ascending digits, i.e. it starts with images of zeros and ends with images of nines at entry 59,999. Entries `x[60000:]` onwards are meant to be used for testing and again contain images of all digits in ascending order.
Before starting with binary classification, let's quickly confirm that the labels stored in `y` actually make sense. We previously looked at entry `X[36000]` and it looked like a five. Does `y[36000]` say the same?
```
y[36000]
```
Good! As a very last step, let's split train and test and store them separately. Because we also don't want our training to be biased, we should shuffle the entries randomly (i.e. not sort them in ascending order anymore). We can do this with the `np.random.permutation(60000)` function which returns a random permutation of the numbers between zero and 60,000.
```
X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]
import numpy as np
shuffle_index = np.random.permutation(60000)
X_train, y_train = X_train[shuffle_index], y_train[shuffle_index]
```
# Binary classifier
Before going towards a classifier, which can distinguish _all_ digits, let's start with something simple. Since our random digit `X[36000]` was a five, why not design a classifier that can distinguish fives from other digits? Let's first rewrite our labels from integers to booleans:
```
y_train_5 = (y_train == 5) # an array of booleans which is 'True' whenever y_train is == 5
y_test_5 = (y_test == 5)
y_train_5 # let's look at the array
```
A good model for the classification is the Stochastic Gradient Descent that was introduced in the lecture. Conveniently, Skiki-Learn already has such a classifier implemented, so let's import it and give it our training data `X_train` with the true labels `y_train_5`.
```
from sklearn.linear_model import SGDClassifier
# SDG relies on randomness, but by fixing the `random_state` we can get reproducible results.
# The other values are just to avoid a warning issued by Skikit-Learn ...
sgd_clf = SGDClassifier(random_state=42, max_iter=5, tol=-np.infty)
sgd_clf.fit(X_train, y_train_5)
```
If the training of the classifier was successful, it should be able to predict the label of our example instance `X[36000]` correctly.
```
sgd_clf.predict([some_digit])
```
That's good, but it doesn't really give us an idea about the overall performance of the classifier. One good measure for this introduced in the lecture is the cross-validation score. In k-fold cross-validation, the training data is split into k equal subsets. Then the classifier is trained on k-1 sets and evaluated on set k. It's called cross-validation, because this is done for all k possible (and non-redundant) permutations. In case of a 3-fold, this means we train on subsets 1 and 2 and validated on 3, train on 1 and 3 and validate on 2, and train on 2 and 3 and validate on 1. The _score_ represents the prediction accuracy on the validation fold.
```
from sklearn.model_selection import cross_val_score
cross_val_score(sgd_clf, X_train, y_train_5, cv=3, scoring="accuracy")
```
While these numbers seem amazingly good, keep in mind, that only 10% of our training data are images of fives, so even a classifier which always predicts 'not five' would reach an accuracy of about 90% ...
In the following box, maybe you can try to implement the cross validation yourself! The `StratifiedKFold` creates k non-biased subsets of the training data. The input to the `StratifiedKFold.split(X, y)` are the training data `X` (in our case called `X_train`) and the labels (in our case for the five-classifier `y_train_5`). The `sklearn.base.clone` function will help to make a copy of the classifier object.
```
from sklearn.model_selection import StratifiedKFold
from sklearn.base import clone
skfolds = StratifiedKFold(n_splits=3, random_state=42)
for train_indices, test_indices in skfolds.split(X_train, y_train_5):
clone_clf = clone(sgd_clf) # make a clone of the classifier
# [...] some code is missing here
X_train_folds = X_train[train_indices]
y_train_folds = y_train_5[train_indices]
clone_clf.fit(X_train_folds, y_train_folds)
X_test_fold = X_train[test_indices]
y_test_fold = y_train_5[test_indices]
y_pred = clone_clf.predict(X_test_fold)
n_correct = sum(y_pred == y_test_fold)
print("Fraction of correct predictions: %s" % (n_correct / len(y_pred)))
```
Let's move on to another performance measure: the confusion matrix. The confusion matrix is a 2x2 matrix and includes the number of true positives, false positives (type-I error), true negatives and false negatives (type-II error). First, let's use another of Scitkit-Learn's functions: `cross_val_predict` takes our classifier, our training data and our true labels, and automatically performs a k-fold cross-validation. It returns an array of the predicted labels.
```
from sklearn.model_selection import cross_val_predict
# Take our SGD classifer and perform a 3-fold cross-validation.
y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3)
# Print some of the predicted labels.
print(y_train_pred)
```
Using cross-validation always gives us a 'clean', i.e. unbiased estimate of our prediction power, because the performance of the classifier is evaluated on data it hadn't seen during training. Now we have our predicted labels in `y_train_pred` and can compare them to the true labels `y_train_5`. So let's create a confusion matrix.
```
from sklearn.metrics import confusion_matrix
confusion_matrix(y_train_5, y_train_pred)
```
How do we read this? The rows correspond to the _true_ classes, the columns to the _predicted_ classes. So the 53,272 means that about fifty-three thousand numbers that are 'not five' were predicted as such, while 1307 were predicted to be fives. 4344 true fives were predicted to be fives, but 1077 were not. Sometimes it makes sense to normalise the confusion matrix by rows, so that the values in the cells give an idea how large the _fraction_ of correctly and incorrectly predicted instances is. So let's try this:
```
matrix = confusion_matrix(y_train_5, y_train_pred)
row_sums = matrix.sum(axis=1)
matrix / row_sums[:, np.newaxis]
```
There are other metrics to evaluate the performance of classifiers as we saw in the lecture. One example is the _precision_ which is the rate of true positives among all positives. The precision is a measure how many of our predicted positives are _actually_ positives, i.e. it can be calculated as TP / (TP + FP) (TP = true positives, FP = false positives).
```
from sklearn.metrics import precision_score, recall_score
print(precision_score(y_train_5, y_train_pred))
# Can you reproduce this value by hand? All info should be in the confusion matrix.
tp = matrix[1][1]
fp = matrix[0][1]
precision_by_hand = tp / (tp + fp)
print("By hand: %s" % precision_by_hand)
```
Or in words: 77% of our predicted fives are _actually_ fives, while 23% of the predicted fives are other numbers.
Another metric, which is often used in conjunction with the _precision_, is the _recall_. The recall is a measure of how many of the true positives as predicted as such, i.e. "how many true positives do we identify". It is easy to reach perfect precision if you just make your classifier reject all negatives, but it's impossible to keep a high recall score in that case. Let's look at our classifier's recall:
```
print(recall_score(y_train_5, y_train_pred))
# Again, it should be straight-forward to make this calculation by hand. Can you try?
tp = matrix[1][1]
fn = matrix[1][0]
recall_by_hand = tp / (tp + fn)
print("By hand: %s" % recall_by_hand)
```
In words: only 80% of the fives are correctly predicted to be fives. Doesn't look as great as the 95% prediction rate, does it? A nice combination for precision and recall is their harmonic mean, usually known (and in the lecture introduced as) the _F_1 score_. The harmonic mean (as opposed to the arithmetic mean) is very sensitive low values, so only a good balance between precision and recall will lead to a high F_1 score. Very conveniently, Scikit-Learn comes with an implementation of the score already, but can you also calculate it by hand?
```
from sklearn.metrics import f1_score
print(f1_score(y_train_5, y_train_pred))
# Once more, it is fairly easy to calculate this by hand. Give it a try!
f1_score_by_hand = 2 / (1/precision_by_hand + 1/recall_by_hand)
print("By hand: %s" % f1_score_by_hand)
```
Of course, a balanced precision and recall is not _always_ desirable. Whether you want both to be equally high, depends on the use case. Sometimes, you'd definitely want to classify as many true positives as such, with the tradeoff to have low precision (example: in a test for a virus you want every true positive to know that they might be infected, but you might get a few false positives). In other cases, you might want a high precision with the tradeoff that you don't detect all positives as such (example: it's ok to remove some harmless videos in a video filter, but you don't want harmful content to pass your filter).
## Decision function
When we use the `predict()` function, our classifier gives a boolean prediction. But how is that prediction done? The classifier calculates a score, called 'decision_function' in Scikit-Learn, and any instance above a certain threshold is classified as 'true', any instance below as 'false'. By retrieving the decision function directly, we can look at different tradeoffs between precision and recall.
```
y_scores = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3,
method="decision_function")
print(y_scores) # Print scores to get an idea ...
```
This again gives us a numpy array with 60,000 entries, all of which contain a floating point value with the predicted score. Now, as we've seen before, Scikit-Learn provides many functions out-of-the-box to evaluate classifiers. The following `precision_recall_curve` metric gives us tuples of precision, recall and threshold values based on our training data. It takes the true labels, in our case `y_train_5` and the `y_scores` to calculate these. We can then use thes values to plot curves for precision and recall for different threshold values.
```
from sklearn.metrics import precision_recall_curve
precisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores)
print(precisions)
def plot_precision_recall_vs_threshold(precisions, recalls, thresholds):
plt.plot(thresholds, precisions[:-1], "b--", label="Precision", linewidth=2)
plt.plot(thresholds, recalls[:-1], "g-", label="Recall", linewidth=2)
plt.xlabel("Threshold", fontsize=16)
plt.legend(loc="upper left", fontsize=16)
plt.ylim([0, 1])
plt.figure(figsize=(8, 4))
plot_precision_recall_vs_threshold(precisions, recalls, thresholds)
plt.xlim([-700000, 700000])
save_fig("precision_recall_vs_threshold_plot")
plt.show()
```
Looks good! Bonus question: why is the precision curve bumpier than the recall?
Let's assume we want to optimise our classfier for a precision value of 93%. Can you find a good threshold? The below threshold is just a test value and definitely too low.
```
threshold = -20000
y_train_pred_93 = (y_scores > threshold)
print("precision: %s" % precision_score(y_train_5, y_train_pred_93))
print("recall: %s" % recall_score(y_train_5, y_train_pred_93))
```
Sometimes, plotting precision vs. recall can also be helpful.
```
def plot_precision_vs_recall(precisions, recalls):
plt.plot(recalls, precisions, "b-", linewidth=2)
plt.xlabel("Recall", fontsize=16)
plt.ylabel("Precision", fontsize=16)
plt.axis([0, 1, 0, 1])
plt.figure(figsize=(8, 6))
plot_precision_vs_recall(precisions, recalls)
save_fig("precision_vs_recall_plot")
plt.show()
```
# ROC curves
Because it's an extremely common performance measure, we should also have a look at the ROC curve (_receiver operating characteristic_). ROC curves plot true positives vs. false positives, or usually the true positive _rate_ vs. the false positive _rate_. While the first is exactly what we called _recall_ so far, the latter is one minus the _true negative rate_, also called specificity. Let's import the ROC curve from Scikit-Learn, this will give us tuples of FPR, TPR and threshold values again.
```
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y_train_5, y_scores)
```
Now we can plot them:
```
def plot_roc_curve(fpr, tpr, label=None):
plt.plot(fpr, tpr, linewidth=2, label=label)
plt.plot([0, 1], [0, 1], 'k--')
plt.axis([0, 1, 0, 1])
plt.xlabel('False Positive Rate', fontsize=16)
plt.ylabel('True Positive Rate', fontsize=16)
plt.figure(figsize=(8, 6))
plot_roc_curve(fpr, tpr)
save_fig("roc_curve_plot")
plt.show()
```
It is always desirable to have the curve as close to the top left corner as above. As a measure for this, one usually calculates the _area under curve_. What is the AUC value for a random classifier?
```
from sklearn.metrics import roc_auc_score
roc_auc_score(y_train_5, y_scores)
```
# Multiclass classification
So far we have completely ignored the fact that our training data not only includes fives and 'other digits', but in fact ten different input labels (one for each digit). Multiclass classification will allow us to distinguish each of them individually and predict the _most likely class_ for each instance. Scikit-Learn is clever enough to realise, that our label array `y_train` contains ten different classes, so – without explicitly telling us – it runs ten binary classifiers when we call the `fit()` function on the SGD classifier. Each of these binary classifiers trains one class vs. all others ("one-versus-all"). Let's try it out:
```
sgd_clf.fit(X_train, y_train)
```
How does it classify our previous example of something that looked like a five?
```
sgd_clf.predict([some_digit])
```
Great! But what exactly happens under the hood? It actually calculates ten different scores for the ten different binary classifiers and picks the class with the highest score. We can see this by calling the `decision_function()` as we did earlier:
```
some_digit_scores = sgd_clf.decision_function([some_digit])
print(some_digit_scores) # Print us the array content
print("Largest entry: %s" % np.argmax(some_digit_scores)) # Get the index of the largest entry
```
Scikit-Learn even comes with a class to run the one-versus-one approach as well. We can just give it our SGD classifier instance and then call the `fit()` function on it:
```
from sklearn.multiclass import OneVsOneClassifier
ovo_clf = OneVsOneClassifier(sgd_clf)
ovo_clf.fit(X_train, y_train)
# What does it predict for our random five?
ovo_clf.predict([some_digit])
```
And how many classifiers does this one-versus-one approach need? Can you come up with the formula?
```
print("Number of estimators: %s" % len(ovo_clf.estimators_))
```
Back to the one-versus-all approach – how good are we? For that, we can calculate the cross-validation score once more to get values for the accuracy. Bear in mind that now we are running a _ten-class_ classification!
```
cross_val_score(sgd_clf, X_train, y_train, cv=3, scoring="accuracy")
```
This is not bad at all, although you could probably spend hours optimising the hyperparameters of this model. How good does the onve-versus-one approach perform? Try it out!
Let's look at some other performance measures for the one-versus-all classifier. A good point to start is the confusing matrix.
```
y_train_pred = cross_val_predict(sgd_clf, X_train, y_train, cv=3)
conf_mx = confusion_matrix(y_train_pred, y_train)
conf_mx
```
Ok, maybe it's better to display this in a plot:
```
def plot_confusion_matrix(matrix):
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
plt.xlabel('Predicted class', fontsize=16)
plt.ylabel('True class', fontsize=16)
cax = ax.matshow(matrix)
fig.colorbar(cax)
plot_confusion_matrix(conf_mx)
save_fig("confusion_matrix_plot", tight_layout=False)
plt.show()
```
It's still very hard to see what's going on. So maybe we should (1) normalise the matrix by rows again, (2) "remove" all diagonal entries, because those are not interesting for us for the error analysis.
```
row_sums = conf_mx.sum(axis=1, keepdims=True)
norm_conf_mx = conf_mx / row_sums
np.fill_diagonal(norm_conf_mx, 0)
plot_confusion_matrix(norm_conf_mx)
save_fig("confusion_matrix_errors_plot", tight_layout=False)
plt.show()
```
It seems we're predicting many of the eights wrong. In particular, many of them are predicted to be a five! On the other hand, not many fives are misclassified as eights. Interesting, right? Let's pick out some eights and fives, each of which are either correctly predicted, or predicted as the other class. Maybe looking at the pictures with our "human learning" algorithm will see the problem.
```
cl_a, cl_b = 8, 5 # Define class a and class b for the plot
# Training data from class a, which is predicted as a.
X_aa = X_train[(y_train == cl_a) & (y_train_pred == cl_a)]
# Training data from class a, which is predicted as b.
X_ab = X_train[(y_train == cl_a) & (y_train_pred == cl_b)]
# Training data from class b, which is predicted as a.
X_ba = X_train[(y_train == cl_b) & (y_train_pred == cl_a)]
# Training data from class b, which is predicted as b.
X_bb = X_train[(y_train == cl_b) & (y_train_pred == cl_b)]
plt.figure(figsize=(8,8))
plt.subplot(221); plot_digits(X_aa[:25], images_per_row=5)
plt.subplot(222); plot_digits(X_ab[:25], images_per_row=5)
plt.subplot(223); plot_digits(X_ba[:25], images_per_row=5)
plt.subplot(224); plot_digits(X_bb[:25], images_per_row=5)
save_fig("error_analysis_digits_plot")
plt.show()
```
| github_jupyter |
# "Build Your First Neural Network with PyTorch"
* article <https://curiousily.com/posts/build-your-first-neural-network-with-pytorch/>
* dataset <https://www.kaggle.com/jsphyg/weather-dataset-rattle-package>
requires `torch 1.4.0`
```
import os
from os.path import dirname
import numpy as np
import pandas as pd
from tqdm import tqdm
import seaborn as sns
from pylab import rcParams
import matplotlib.pyplot as plt
from matplotlib import rc
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report
import torch
from torch import nn, optim
import torch.nn.functional as F
%matplotlib inline
sns.set(style='whitegrid', palette='muted', font_scale=1.2)
HAPPY_COLORS_PALETTE = ["#01BEFE", "#FFDD00", "#FF7D00", "#FF006D", "#93D30C", "#8F00FF"]
sns.set_palette(sns.color_palette(HAPPY_COLORS_PALETTE))
rcParams["figure.figsize"] = 12, 8
RANDOM_SEED = 42
np.random.seed(RANDOM_SEED)
torch.manual_seed(RANDOM_SEED)
df = pd.read_csv(dirname(os.getcwd()) + "/dat/weatherAUS.csv")
df.describe()
df.shape
# data pre-processing
cols = [ "Rainfall", "Humidity3pm", "Pressure9am", "RainToday", "RainTomorrow" ]
df = df[cols]
df.head()
df["RainToday"].replace({"No": 0, "Yes": 1}, inplace = True)
df["RainTomorrow"].replace({"No": 0, "Yes": 1}, inplace = True)
df.head()
# drop missing values
df = df.dropna(how="any")
df.head()
sns.countplot(df.RainTomorrow);
df.RainTomorrow.value_counts() / df.shape[0]
X = df[["Rainfall", "Humidity3pm", "RainToday", "Pressure9am"]]
y = df[["RainTomorrow"]]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=RANDOM_SEED)
X_train = torch.from_numpy(X_train.to_numpy()).float()
X_test = torch.from_numpy(X_test.to_numpy()).float()
y_train = torch.squeeze(torch.from_numpy(y_train.to_numpy()).float())
y_test = torch.squeeze(torch.from_numpy(y_test.to_numpy()).float())
print(X_train.shape, y_train.shape)
print(X_test.shape, y_test.shape)
class Net (nn.Module):
def __init__ (self, n_features):
super(Net, self).__init__()
self.fc1 = nn.Linear(n_features, 5)
self.fc2 = nn.Linear(5, 3)
self.fc3 = nn.Linear(3, 1)
def forward (self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return torch.sigmoid(self.fc3(x))
net = Net(X_train.shape[1])
# training
criterion = nn.BCELoss()
optimizer = optim.Adam(net.parameters(), lr=0.001)
# weather forecast
def calculate_accuracy (y_true, y_pred):
predicted = y_pred.ge(.5).view(-1)
return (y_true == predicted).sum().float() / len(y_true)
def round_tensor (t, decimal_places=3):
return round(t.item(), decimal_places)
MAX_EPOCH = 5000
for epoch in range(MAX_EPOCH):
y_pred = net(X_train)
y_pred = torch.squeeze(y_pred)
train_loss = criterion(y_pred, y_train)
if epoch % 100 == 0:
train_acc = calculate_accuracy(y_train, y_pred)
y_test_pred = net(X_test)
y_test_pred = torch.squeeze(y_test_pred)
test_loss = criterion(y_test_pred, y_test)
test_acc = calculate_accuracy(y_test, y_test_pred)
print(
f'''epoch {epoch}
Train set - loss: {round_tensor(train_loss)}, accuracy: {round_tensor(train_acc)}
Test set - loss: {round_tensor(test_loss)}, accuracy: {round_tensor(test_acc)}
''')
optimizer.zero_grad()
train_loss.backward()
optimizer.step()
# save the model
MODEL_PATH = "model.pth"
torch.save(net, MODEL_PATH)
# restore model
net = torch.load(MODEL_PATH)
# evaluation
classes = ["No rain", "Raining"]
y_pred = net(X_test)
y_pred = y_pred.ge(.5).view(-1).cpu()
y_test = y_test.cpu()
print(classification_report(y_test, y_pred, target_names=classes))
cm = confusion_matrix(y_test, y_pred)
df_cm = pd.DataFrame(cm, index=classes, columns=classes)
hmap = sns.heatmap(df_cm, annot=True, fmt="d")
hmap.yaxis.set_ticklabels(hmap.yaxis.get_ticklabels(), rotation=0, ha='right')
hmap.xaxis.set_ticklabels(hmap.xaxis.get_ticklabels(), rotation=30, ha='right')
plt.ylabel('True label')
plt.xlabel('Predicted label');
def will_it_rain (rainfall, humidity, rain_today, pressure):
t = torch.as_tensor([rainfall, humidity, rain_today, pressure]).float().cpu()
output = net(t)
print("net(t)", output.item())
return output.ge(0.5).item()
will_it_rain(rainfall=10, humidity=10, rain_today=True, pressure=2)
will_it_rain(rainfall=0, humidity=1, rain_today=False, pressure=100)
```
| github_jupyter |
# Scraping transfermarkt by html
```
from selenium.webdriver import (Chrome, Firefox)
import time
import requests
from bs4 import BeautifulSoup
from html_scraper import db
players = db['players']
player_urls = db['player_urls']
browser = Firefox()
url = 'https://www.transfermarkt.co.uk/primera-division/startseite/wettbewerb/AR1N'
browser.get(url)
elems = browser.find_elements_by_class_name("vereinprofil_tooltip")
url_links = []
for link in elems:
url = link.get_attribute('href')
if url not in url_links and 'startseite' in url:
url_links.append(url)
len(url_links)
club1 = url_links[0]
browser.get(club1)
```
### Go from club_url to detailed page club_url
```
detailed_url = []
for url in url_links:
change_url = url.replace('startseite', 'kader')
url_final = change_url + '/plus/1'
detailed_url.append(url_final)
detailed_url
```
### old code... skip down to scraping to DBMongo step
```
from html_scraper import scrape_player_info
scrape_player_info(detailed_url, delay=15)
db
club1 = detailed_url[0]
browser.get(club1)
sel = 'td.hauptlink a'
link_elements = browser.find_elements_by_css_selector(sel)
print(link_elements[0].text)
sel = 'td.zentriert'
link_elements = browser.find_elements_by_css_selector(sel)
print(link_elements[0].text)
for link in link_elements:
print(link.text)
sel = 'td.rechts.hauptlink'
link_elements = browser.find_elements_by_css_selector(sel)
test = '£4.05m '
chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'k', 'm', '.']
''.join(char for char in test if char in chars)
player_dict_odd = {}
for row in browser.find_elements_by_css_selector("tr.odd"):
player = row.find_element_by_css_selector('td.hauptlink a').text
squad_num = row.find_elements_by_css_selector('td.zentriert')[0].text
birthday = row.find_elements_by_css_selector('td.zentriert')[1].text
transfer_value = row.find_element_by_css_selector('td.rechts.hauptlink').text
player_dict_odd[player] = {'squad_num': squad_num, 'birthday': birthday, 'transfer_value': transfer_value}
player_dict_odd
# player_dict_even = {}
# for row in browser.find_elements_by_css_selector("tr.even"):
# player = row.find_element_by_css_selector('td.hauptlink a').text
# squad_num = row.find_elements_by_css_selector('td.zentriert')[0].text
# birthday = row.find_elements_by_css_selector('td.zentriert')[1].text
# # nationality = row.find_element_by_css_selector('td.zentriert.img')
# transfer_value = row.find_element_by_css_selector('td.rechts.hauptlink').text
# player_dict_even[player] = {'squad_num': squad_num, 'birthday': birthday, 'transfer_value': transfer_value}
# player_dict_even
player_dict = {**player_dict_even, **player_dict_odd}
len(player_dict)
# test = db['test']
# test.insert_one(player_dict)
```
# Scraping to DB Mongo
```
db_urls = detailed_url.copy()
db_urls
from html_scraper import get_all_player_data_from_url, team_scrape
teams = [get_all_player_data_from_url(url) for url in db_urls]
from html_scraper import add_player_to_db
import pandas as pd
for url in db_urls:
player_data = get_all_player_data_from_url(url)
print(url)
for player in player_data:
add_player_to_db(player)
```
# check db
```
db.players
players = db.players.find()
players.count()
master_list = []
for player in players:
master_list.append(player)
master_list
pd.DataFrame(master_list)
```
| github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
```
#@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.
#@title MIT License
#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
```
# Phân loại cơ bản: Dự đoán ảnh quần áo giày dép
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/keras/classification"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />Xem trên TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/vi/tutorials/keras/classification.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Chạy trên Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/vi/tutorials/keras/classification.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />Xem mã nguồn trên GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/vi/tutorials/keras/classification.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Tải notebook</a>
</td>
</table>
**Lưu ý:** Cộng đồng TensorFlow tại Việt Nam đã và đang dịch những tài liệu này từ nguyên bản tiếng Anh.
Những bản dịch này được hoàn thiện dựa trên sự nỗ lực đóng góp từ cộng đồng lập trình viên sử dụng TensorFlow,
và điều này có thể không đảm bảo được tính cập nhật của bản dịch đối với [Tài liệu chính thức bằng tiếng Anh](https://www.tensorflow.org/?hl=en) này.
Nếu bạn có bất kỳ đề xuất nào nhằm cải thiện bản dịch này, vui lòng tạo Pull request đến
kho chứa trên GitHub của [tensorflow/docs-l10n](https://github.com/tensorflow/docs-l10n).
Để đăng ký dịch hoặc cải thiện nội dung bản dịch, các bạn hãy liên hệ và đặt vấn đề tại
[docs-vi@tensorflow.org](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-vi).
Trong hướng dẫn này, chúng ta sẽ huấn luyện một mô hình mạng neuron để phân loại các hình ảnh về quần áo và giày dép.
Đừng ngại nếu bạn không hiểu hết mọi chi tiết, vì chương trình trong hướng dẫn này là một chương trình TensorFlow hoàn chỉnh, và các chi tiết sẽ dần được giải thích ở những phần sau.
Hướng dẫn này dùng [tf.keras](https://www.tensorflow.org/guide/keras), một API cấp cao để xây dựng và huấn luyện các mô hình trong TensorFlow.
```
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
```
## Import tập dữ liệu về quần áo và giày dép từ Fashion MNIST
Chúng ta sẽ dùng tập dữ liệu về quần áo và giày dép từ [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist), chứa khoảng 70,000 ảnh đen trắng phân thành 10 loại. Mỗi một ảnh là một loại quần áo hoặc giày dép với độ phân giải thấp (28 by 28 pixel), như hình minh hoạ bên dưới:
<table>
<tr><td>
<img src="https://tensorflow.org/images/fashion-mnist-sprite.png"
alt="Fashion MNIST sprite" width="600">
</td></tr>
<tr><td align="center">
<b>Figure 1.</b> <a href="https://github.com/zalandoresearch/fashion-mnist">Fashion-MNIST samples</a> (by Zalando, MIT License).<br/>
</td></tr>
</table>
Fashion MNIST là tập dữ liệu được dùng để thay thế cho tập dữ liệu [MNIST](http://yann.lecun.com/exdb/mnist/) kinh điển thường dùng cho các chương trình "Hello, World" của machine learning trong lĩnh vực thị giác máy tính. Tập dữ liệu kinh điển vừa đề cập gồm ảnh của các con số (ví dụ 0, 1, 2) được viết tay. Các ảnh này có cùng định dạng tệp và độ phân giải với các ảnh về quần áo và giầy dép chúng ta sắp dùng.
Hướng dẫn này sử dụng tập dữ liệu Fashion MNIST, vì đây là một bài toán tương đối phức tạp hơn so với bài toán nhận diện chữ số viết tay. Cả 2 tập dữ liệu (Fashion MNIST và MNIST kinh điển) đều tương đối nhỏ và thường dùng để đảm bảo một giải thuật chạy đúng, phù hợp cho việc kiểm thử và debug.
Với tập dữ liệu này, 60.000 ảnh sẽ được dùng để huấn luyện và 10.000 ảnh sẽ đường dùng để đánh giá khả năng phân loại nhận diện ảnh của mạng neuron. Chúng ta có dùng tập dữ liệu Fashion MNIST trực tiếp từ TensorFlow như sau:
```
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
```
Tập dữ liệu sau khi được tải sẽ trả về 4 mảng NumPy:
* 2 mảng `train_images` và `train_labels` là *tập huấn luyện*. Mô hình sẽ học từ dữ liệu của 2 mảng này.
* 2 mảng `test_images` vả `test_labels` là *tập kiểm thử*. Sau khi mô hình được huấn luyện xong, chúng ta sẽ chạy thử mô hình với dữ liệu đầu vào từ `test_images` để lấy kết quả, và so sánh kết quả đó với dữ liệu đối ứng từ `test_labels` để đánh giá chất lượng của mạng neuron.
Mỗi ảnh là một mảng NumPy 2 chiều, 28x28, với mỗi pixel có giá trị từ 0 đến 255. *Nhãn* là một mảng của các số nguyên từ 0 đến 9, tương ứng với mỗi *lớp* quần áo giày dép:
<table>
<tr>
<th>Nhãn</th>
<th>Lớp</th>
</tr>
<tr>
<td>0</td>
<td>Áo thun</td>
</tr>
<tr>
<td>1</td>
<td>Quần dài</td>
</tr>
<tr>
<td>2</td>
<td>Áo liền quần</td>
</tr>
<tr>
<td>3</td>
<td>Đầm</td>
</tr>
<tr>
<td>4</td>
<td>Áo khoác</td>
</tr>
<tr>
<td>5</td>
<td>Sandal</td>
</tr>
<tr>
<td>6</td>
<td>Áo sơ mi</td>
</tr>
<tr>
<td>7</td>
<td>Giày</td>
</tr>
<tr>
<td>8</td>
<td>Túi xách</td>
</tr>
<tr>
<td>9</td>
<td>Ủng</td>
</tr>
</table>
Mỗi ảnh sẽ được gán với một nhãn duy nhất. Vì tên của mỗi lớp không có trong tập dữ liệu, nên chúng ta có thể định nghĩa ở đây để dùng về sau:
```
class_names = ['Áo thun', 'Quần dài', 'Áo liền quần', 'Đầm', 'Áo khoác',
'Sandal', 'Áo sơ mi', 'Giày', 'Túi xách', 'Ủng']
```
## Khám phá dữ liệu
Chúng ta có thể khám phá dữ liệu một chút trước khi huấn luyện mô hình. Câu lệnh sau sẽ cho ta thấy có 60.000 ảnh trong tập huấn luyện, với mỗi ảnh được biểu diễn theo dạng 28x28 pixel:
```
train_images.shape
```
Tương tự, tập huấn luyện cũng có 60.000 nhãn đối ứng:
```
len(train_labels)
```
Mỗi nhãn là một số nguyên từ 0 đến 9:
```
train_labels
```
Có 10.000 ảnh trong tập kiểm thử, mỗi ảnh cũng được biểu diễn ở dãng 28 x 28 pixel:
```
test_images.shape
```
Và tập kiểm thử cũng chứa 10,000 nhãn:
```
len(test_labels)
```
## Tiền xử lý dữ liệu
Dữ liệu cần được tiền xử lý trước khi được dùng để huấn luyện mạng neuron. Phân tích ảnh đầu tiên trong tập dữ liệu, chúng ta sẽ thấy các pixel có giá trị từ 0 đến 255:
```
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
```
Chúng ta cần tiền xử lý để mỗi một điểm ảnh có giá trị từ 0 đến 1 (có thể hiểu là 0% đến 100%). Để làm điều này, chúng ta chỉ cần lấy giá trị của pixel chia cho 255. Cần lưu ý rằng việc tiền xử lý này phải được áp dụng đồng thời cho cả *tập huấn luyện* và *tập kiểm thử*:
```
train_images = train_images / 255.0
test_images = test_images / 255.0
```
Để chắc chắn việc tiền xử lý diễn ra chính xác, chúng ta có thể in ra 25 ảnh đầu trong *tập huấn luyện* cùng với tên lớp dưới mỗi ảnh.
```
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
```
## Xây dựng mô hình
Để xây dựng mạng neuron, chúng tay cần cấu hình các layer của mô hình, và sau đó biên dịch mô hình.
### Thiết lập các layers
Thành phần cơ bản của một mạng neuron là các *layer*. Các layer trích xuất các điểm đặc biệt từ dữ liệu mà chúng đón nhận. Khi thực hiện tốt, những điểm đặc biệt này mang nhiều ý nghĩa và phục vụ cho toán của chúng ta.
Đa số các mô hình deep learning đều chứa các layer đơn gian được xâu chuỗi lại với nhau. Đa số các layer, ví dụ `tf.keras.layers.Dense`, đều có các trọng số sẽ được học trong quá trình huấn luyện.
```
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
```
Trong mạng neuron trên, lớp đầu tiên, `tf.keras.layers.Flatten`, chuyển đổi định dạng của hình ảnh từ mảng hai chiều (28x28) thành mảng một chiều (28x28 = 784). Tưởng tương công việc của layer này là cắt từng dòng của anh, và ghép nối lại thành một dòng duy nhất nhưng dài gấp 28 lần. Lớp này không có trọng số để học, nó chỉ định dạng lại dữ liệu.
Sau layer làm phẳng ảnh (từ 2 chiều thành 1 chiều), phần mạng neuron còn lại gồm một chuỗi hai layer `tf.keras.layers.Dense`. Đây là các layer neuron được kết nối hoàn toàn (mỗi một neuron của layer này kết nối đến tất cả các neuron của lớp trước và sau nó). Layer `Dense` đầu tiên có 128 nút (hoặc neuron). Layer thứ hai (và cuối cùng) là lớp *softmax* có 10 nút, với mỗi nút tương đương với điểm xác suất, và tổng các giá trị của 10 nút này là 1 (tương đương 100%). Mỗi nút chứa một giá trị cho biết xác suất hình ảnh hiện tại thuộc về một trong 10 lớp.
### Biên dịch mô hình
Trước khi mô hình có thể được huấn luyện, chúng ta cần thêm vài chỉnh sửa. Các chỉnh sửa này được thêm vào trong bước *biên dịch* của mô hình:
* *Hàm thiệt hại* — dùng để đo lường mức độ chính xác của mô hình trong quá trình huấn luyện. Chúng ta cần giảm thiểu giá trị của hạm này "điều khiển" mô hình đi đúng hướng (thiệt hại càng ít, chính xác càng cao).
* *Trình tối ưu hoá* — Đây là cách mô hình được cập nhật dựa trên dữ liệu huấn luyện được cung cấp và hàm thiệt hại.
* *Số liệu* — dùng để theo dõi các bước huấn luyện và kiểm thử. Ví dụ sau dùng *accuracy*, tỉ lệ ảnh được phân loại chính xác.
```
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
```
## Huấn luyện mô hình
Huấn luyện mô hình mạng neuron cần các bước sau:
1. Cung cấp dữ liệu huấn luyện cho mô hình. Trong ví dụ này, dữ liệu huấn luyện năm trong 2 mảng `train_images` và `train_labels`
2. Mô hình sẽ học cách liên kết ảnh với nhãn.
3. Chúng ta sẽ yêu cầu mô hình đưa ra dự đoán từ dữ liệu của tập kiểm thử, trong ví dụ này là mảng `test_images`, sau đó lấy kết quả dự đoán đối chiếu với nhãn trong mảng `test_labels`.
Để bắt đầu huấn luyện, gọi hàm `model.fit`. Hàm này được đặt tên `fit` vì nó sẽ "fit" ("khớp") mô hình với dữ liệu huấn luyện:
```
model.fit(train_images, train_labels, epochs=10)
```
Trong quá trình huấn luyện, các số liệu như thiệt hại và hay độ chính xác được hiển thị. Với dữ liệu huấn luyện này, mô hình đạt đến độ accuracy vào khoảng 0.88 (88%).
## Đánh giá mô hình
Tiếp theo, chúng đánh giá các chất lượng của mô hình bằng tập kiểm thử:
```
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
```
Đến thời điểm này, chúng ta thấy rằng độ accuracy của mô hình, khi đánh giá bằng tập kiểm thử, hơi thấp hơn so với số liệu trong quá trình huấn luyện. Khoảng cách giữa hai độ accuracy khi huấn luyện và khi kiểm thử thể hiện sự *overfitting*. Overfitting xảy ra khi một mô hình ML hoạt động kém hơn khi được cung cấp các đầu vào mới, mà mô hình chưa từng thấy trước đây trong quá trình đào tạo.
## Đưa ra dự đoán
Với một mô hình đã được đào tạo, chúng ta có thể dùng nó để đưa ra dự đoán với một số ảnh.
```
predictions = model.predict(test_images)
```
Ở đây, mô hình sẽ dự đoán nhãn cho từng hình ảnh trong bộ thử nghiệm. Hãy xem dự đoán đầu tiên:
```
predictions[0]
```
Trong ví dụ này, dự đoán là một mảng 10 số thực, mỗi số tương ứng với "độ tự tin" của mô hình rằng ảnh đó thuộc về nhãn đó. Chúng ta có thể thấy nhãn nào có độ tư tin cao nhất:
```
np.argmax(predictions[0])
```
Vậy là mô hình tự tin nhất rằng ảnh này là một loại ủng, hoặc `class_names[9]`. Đối chiếu với nhãn trong tập kiểm thử, ta thấy dự đoán này là đúng:
```
test_labels[0]
```
Ta thử vẽ biểu đồ để xem các dự đoán trên cả 10 lớp của mô hình.
```
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array, true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
```
Chúng ta có thể nhìn vào ảnh 0th, các dự đoán, và mảng dự đoán.
Nhãn dự đoán đúng màu xanh và nhãn sai màu đỏ. Con số là số phần trăm của các nhãn được dự đoán.
```
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
```
Thử vẽ biểu đồ với vài ảnh và dự đoán đi kèm. Chú ý thấy rằng mô hình đôi khi dự đoán sai dù điểm tự tin rất cao.
```
# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()
```
Cuối cùng, dùng mô hình để đưa ra dự đoán về một ảnh duy nhất.
```
# Grab an image from the test dataset.
img = test_images[1]
print(img.shape)
```
Các mô hình `tf.keras` được tối ưu hóa để đưa ra dự đoán về một *lô* hoặc bộ sưu tập các ví dụ cùng một lúc. Theo đó, mặc dù bạn đang sử dụng một ảnh duy nhất, bạn cần thêm nó vào list:
```
# Add the image to a batch where it's the only member.
img = (np.expand_dims(img,0))
print(img.shape)
```
Dự đoán nhãn cho ảnh này:
```
predictions_single = model.predict(img)
print(predictions_single)
plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
```
`model.predict` trả về một list của lists — mỗi list cho mỗi ảnh trong lô dữ liệu. Lấy dự đoán cho hình ảnh trong lô:
```
np.argmax(predictions_single[0])
```
Mô hình dự đoán ảnh này có nhãn là đúng như mong muốn.
| github_jupyter |
```
%matplotlib inline
import pandas as pd
import xgboost as xgb
import numpy as np
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import graphviz
from sklearn.preprocessing import LabelEncoder
data = pd.read_csv("data/telco-churn.csv")
data.head()
data.shape
data.drop('customerID', axis = 1, inplace = True)
data.iloc[0]
data['gender'] = LabelEncoder().fit_transform(data['gender'])
data['Partner'] = LabelEncoder().fit_transform(data['Partner'])
data['Dependents'] = LabelEncoder().fit_transform(data['Dependents'])
data['PhoneService'] = LabelEncoder().fit_transform(data['PhoneService'])
data['MultipleLines'] = LabelEncoder().fit_transform(data['MultipleLines'])
data['InternetService'] = LabelEncoder().fit_transform(data['InternetService'])
data['OnlineSecurity'] = LabelEncoder().fit_transform(data['OnlineSecurity'])
data['OnlineBackup'] = LabelEncoder().fit_transform(data['OnlineBackup'])
data['DeviceProtection'] = LabelEncoder().fit_transform(data['DeviceProtection'])
data['TechSupport'] = LabelEncoder().fit_transform(data['TechSupport'])
data['StreamingTV'] = LabelEncoder().fit_transform(data['StreamingTV'])
data['StreamingMovies'] = LabelEncoder().fit_transform(data['StreamingMovies'])
data['Contract'] = LabelEncoder().fit_transform(data['Contract'])
data['PaperlessBilling'] = LabelEncoder().fit_transform(data['PaperlessBilling'])
data['PaymentMethod'] = LabelEncoder().fit_transform(data['PaymentMethod'])
data['Churn'] = LabelEncoder().fit_transform(data['Churn'])
data.dtypes
data.TotalCharges = pd.to_numeric(data.TotalCharges, errors='coerce')
X = data.copy()
X.drop("Churn", inplace = True, axis = 1)
Y = data.Churn
X_train, X_test = X[:int(X.shape[0]*0.8)].values, X[int(X.shape[0]*0.8):].values
Y_train, Y_test = Y[:int(Y.shape[0]*0.8)].values, Y[int(Y.shape[0]*0.8):].values
train = xgb.DMatrix(X_train, label=Y_train)
test = xgb.DMatrix(X_test, label=Y_test)
test_error = {}
for i in range(20):
param = {'max_depth':i, 'eta':0.1, 'silent':1, 'objective':'binary:hinge'}
num_round = 50
model_metrics = xgb.cv(param, train, num_round, nfold = 10)
test_error[i] = model_metrics.iloc[-1]['test-error-mean']
plt.scatter(test_error.keys(),test_error.values())
plt.xlabel('Max Depth')
plt.ylabel('Test Error')
plt.show()
param = {'max_depth':4, 'eta':0.1, 'silent':1, 'objective':'binary:hinge'}
num_round = 300
model_metrics = xgb.cv(param, train, num_round, nfold = 10)
plt.scatter(range(300),model_metrics['test-error-mean'], s = 0.7, label = 'Test Error')
plt.scatter(range(300),model_metrics['train-error-mean'], s = 0.7, label = 'Train Error')
plt.legend()
plt.show()
param = {'max_depth':4, 'eta':0.1, 'silent':1, 'objective':'binary:hinge'}
num_round = 100
model = xgb.train(param, train, num_round)
preds = model.predict(test)
accuracy = accuracy_score(Y[int(Y.shape[0]*0.8):].values, preds)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
model.save_model('churn-model.model')
```
| github_jupyter |
# ロジスティック写像
$$
f(x, a) = a x (1 - x)
$$
```
import numpy as np
import pathfollowing as pf
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set('poster', 'whitegrid', 'dark', rc={"lines.linewidth": 2, 'grid.linestyle': '-'})
def func(x, a):
return np.array([a[0] * x[0] * (1.0 - x[0])])
def dfdx(x,a):
return np.array([[a[0]*(1.0 - 2*x[0])]])
def dfda(x,a):
return np.array([x[0]*(1.0 - x[0])])
```
## 不動点の追跡
- $(x, a) = (2/3, 3)$で周期倍分岐が起こる
```
x=np.array([0.5])
a=np.array([2.0])
bd,bp,lp,pd=pf.pathfollow(x, a, func, dfdx, dfda,nmax=45, h=0.05, epsr=1.0e-10, epsb=1.0e-10, amin=0.0,amax=4.0,problem='map', quiet=True)
```
周期倍分岐点
```
bd[pd[0]]
```
## 周期点の追跡
周期2の周期点の枝に切り替える
```
v2 = pf.calcSwitchingVectorPD(bd[pd[0]], func, dfdx, dfda, period=2)
x2=bd[pd[0]]['x']
a2=bd[pd[0]]['a']
bd2,bp2,lp2, pd2=pf.pathfollow(x2, a2, func, dfdx, dfda, w=v2, nmax=65, h=0.025, epsr=1.0e-10, epsb=1.0e-10, amin=0.0,amax=4.0,problem='map', quiet=True,period=2)
```
周期点の周期倍分岐
```
bd2[pd2[0]]
```
周期4の周期点の枝に切り替える
```
v4 = pf.calcSwitchingVectorPD(bd2[pd2[0]], func, dfdx, dfda, period=4)
x4=bd2[pd2[0]]['x']
a4=bd2[pd2[0]]['a']
bd4,bp4,lp4, pd4=pf.pathfollow(x4, a4, func, dfdx, dfda, w=v4, nmax=65, h=0.0125, epsr=1.0e-10, amin=0.0,amax=4.0,epsb=1.0e-12, problem='map', quiet=True,period=4)
```
周期8の周期点の枝に切り替える
```
v8 = pf.calcSwitchingVectorPD(bd4[pd4[0]], func, dfdx, dfda, period=8)
x8=bd4[pd4[0]]['x']
a8=bd4[pd4[0]]['a']
bd8,bp8,lp8, pd8=pf.pathfollow(x8, a8, func, dfdx, dfda, w=v8, nmax=130, h=0.00625, epsr=1.0e-10, amin=0.0,amax=4.0,epsb=1.0e-12, problem='map', quiet=True,period=8)
```
これまでにもとめた周期倍分岐点のパラメータ値$a$
```
print(bd[pd[0]]['a'], bd2[pd2[0]]['a'], bd4[pd4[0]]['a'], bd8[pd8[0]]['a'])
print(pd8)
bd_r = np.array([bd[m]['a'][0] for m in range(len(bd))])
bd_x = np.array([bd[m]['x'][0] for m in range(len(bd))])
bd_r2 = np.array([bd2[m]['a'][0] for m in range(len(bd2))])
bd_x2 = np.array([bd2[m]['x'][0] for m in range(len(bd2))])
bd_r4 = np.array([bd4[m]['a'][0] for m in range(len(bd4))])
bd_x4 = np.array([bd4[m]['x'][0] for m in range(len(bd4))])
bd_r8 = np.array([bd8[m]['a'][0] for m in range(len(bd8))])
bd_x8 = np.array([bd8[m]['x'][0] for m in range(len(bd8))])
def f(x,a):
return a*x*(1-x)
bd_x22 = np.array([f(bd_x2[m], bd_r2[m]) for m in range(len(bd2))])
bd_x42 = np.array([f(bd_x4[m], bd_r4[m]) for m in range(len(bd4))])
bd_x43 = np.array([f(bd_x42[m], bd_r4[m]) for m in range(len(bd4))])
bd_x44 = np.array([f(bd_x43[m], bd_r4[m]) for m in range(len(bd4))])
bd_x82 = np.array([f(bd_x8[m], bd_r8[m]) for m in range(len(bd8))])
bd_x83 = np.array([f(bd_x82[m], bd_r8[m]) for m in range(len(bd8))])
bd_x84 = np.array([f(bd_x83[m], bd_r8[m]) for m in range(len(bd8))])
bd_x85 = np.array([f(bd_x84[m], bd_r8[m]) for m in range(len(bd8))])
bd_x86 = np.array([f(bd_x85[m], bd_r8[m]) for m in range(len(bd8))])
bd_x87 = np.array([f(bd_x86[m], bd_r8[m]) for m in range(len(bd8))])
bd_x88 = np.array([f(bd_x87[m], bd_r8[m]) for m in range(len(bd8))])
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot(111)
ax.set_xlim(2,4)
ax.set_ylim(0.2, 1)
ax.set_xlabel("$a$")
ax.set_ylabel("$x$")
ax.plot(bd_r ,bd_x, '-k')
ax.plot(bd_r2, bd_x2, '-k')
ax.plot(bd_r2, bd_x22, '-k')
ax.plot(bd_r4, bd_x4, '-k')
ax.plot(bd_r4, bd_x42, '-k')
ax.plot(bd_r4, bd_x43, '-k')
ax.plot(bd_r4, bd_x44, '-k')
ax.plot(bd_r8, bd_x8, '-k')
ax.plot(bd_r8, bd_x82, '-k')
ax.plot(bd_r8, bd_x83, '-k')
ax.plot(bd_r8, bd_x84, '-k')
ax.plot(bd_r8, bd_x85, '-k')
ax.plot(bd_r8, bd_x86, '-k')
ax.plot(bd_r8, bd_x87, '-k')
ax.plot(bd_r8, bd_x88, '-k')
# plt.savefig("bd_logistic.pdf", bbox_inches='tight')
```
| github_jupyter |
## Part 2: Introduction to Feed Forward Networks
### 1. What is a neural network?
#### 1.1 Neurons
A neuron is software that is roughly modeled after the neuons in your brain. In software, we model it with an _affine function_ and an _activation function_.
One type of neuron is the perceptron, which outputs a binary output 0 or 1 given an input [7]:
<img src="perceptron.jpg" width="600" height="480" />
You can add an activation function to the end isntead of simply thresholding values to clip values from 0 to 1. One common activiation function is the logistic function.
<img src="sigmoid_neuron.jpg" width="600" height="480" />
The most common activation function used nowadays is the rectified linear unit, which is simply max(0, z) where z = w * x + b, or the neurons output.
#### 1.2 Hidden layers and multi-layer perceptrons
A multi-layer perceptron (MLP) is quite simply layers on these perceptrons that are wired together. The layers between the input layer and the output layer are known as the hidden layers. The below is a four layer network with two hidden layers [7]:
<img src="hidden_layers.jpg" width="600" height="480" />
### 2. Tensorflow
Tensorflow (https://www.tensorflow.org/install/) is an extremely popular deep learning library built by Google and will be the main library used for of the rest of these notebooks (in the last lesson, we briefly used numpy, a numerical computation library that's useful but does not have deep learning functionality). NOTE: Other popular deep learning libraries include Pytorch and Caffe2. Keras is another popular one, but its API has since been absorbed into Tensorflow. Tensorflow is chosen here because:
* it has the most active community on Github
* it's well supported by Google in terms of core features
* it has Tensorflow serving, which allows you to serve your models online (something we'll see in a future notebook)
* it has Tensorboard for visualization (which we will use in this lesson)
Let's train our first model to get a sense of how powerful Tensorflow can be!
```
# Some initial setup. Borrowed from:
# https://github.com/ageron/handson-ml/blob/master/09_up_and_running_with_tensorflow.ipynb
# Common imports
import numpy as np
import os
import tensorflow as tf
# To plot pretty figures
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
# Where to save the figures
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "tensorflow"
def save_fig(fig_id):
path = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID, fig_id + ".png")
print("Saving figure", fig_id)
plt.tight_layout()
plt.savefig(path, format='png', dpi=300)
def stabilize_output():
tf.reset_default_graph()
# needed to avoid the following error: https://github.com/RasaHQ/rasa_core/issues/80
tf.keras.backend.clear_session()
tf.set_random_seed(seed=42)
np.random.seed(seed=42)
print "Done"
```
Below we will train our first model using the example from the Tensorflow tutorial: https://www.tensorflow.org/tutorials/
This will show you the basics of training a model!
```
# The example below is also in https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/get_started/_index.ipynb
# to ensure relatively stable output across sessions
stabilize_output()
mnist = tf.keras.datasets.mnist
# load data (requires Internet connection)
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# build a model
model = tf.keras.models.Sequential([
# flattens the input
tf.keras.layers.Flatten(),
# 1 "hidden" layer with 512 units - more on this in the next notebook
tf.keras.layers.Dense(512, activation=tf.nn.relu),
# example of regularization - dropout is a way of dropping hidden units at a certain factor
# this essentially results in a model averaging across a large set of possible configurations of the hidden layer above
# and results in model that should generalize better
tf.keras.layers.Dropout(0.2),
# 10 because there's possible didigts - 0 to 9
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# train a model (using 5 epochs -> notice the accuracy improving with each epoch)
model.fit(x_train, y_train, epochs=5)
print model.metrics_names # see https://keras.io/models/model/ for the full API
# evaluate model accuracy
model.evaluate(x_test, y_test)
```
You should see something similar to [0.06788356024027743, 0.9806]. The first number is the final loss and the second number is the accuracy.
Congratulations, it means you've trained a classifier that classifies digit images in the MNIST Dataset with __98% accuracy__! We'll break down how the model is optimizing to achieve this accuracy below.
### 3. More Training of Neural Networks in Tensorflow
#### 3.1: Data Preparation
We load the CIFAR-10 dataset using the tf.keras API.
```
# Borrowed from http://cs231n.github.io/assignments2018/assignment2/
def load_cifar10(num_training=49000, num_validation=1000, num_test=10000):
"""
Fetch the CIFAR-10 dataset from the web and perform preprocessing to prepare
it for the two-layer neural net classifier. These are the same steps as
we used for the SVM, but condensed to a single function.
"""
# Load the raw CIFAR-10 dataset and use appropriate data types and shapes
# NOTE: Download will take a few minutes but once downloaded, it should be cached.
cifar10 = tf.keras.datasets.cifar10.load_data()
(X_train, y_train), (X_test, y_test) = cifar10
X_train = np.asarray(X_train, dtype=np.float32)
y_train = np.asarray(y_train, dtype=np.int32).flatten()
X_test = np.asarray(X_test, dtype=np.float32)
y_test = np.asarray(y_test, dtype=np.int32).flatten()
# 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]
# Normalize the data: subtract the mean pixel and divide by std
mean_pixel = X_train.mean(axis=(0, 1, 2), keepdims=True)
std_pixel = X_train.std(axis=(0, 1, 2), keepdims=True)
X_train = (X_train - mean_pixel) / std_pixel
X_val = (X_val - mean_pixel) / std_pixel
X_test = (X_test - mean_pixel) / std_pixel
return X_train, y_train, X_val, y_val, X_test, y_test
# Invoke the above function to get our data.
# N - index of the number of datapoints (minibatch size)
# H - index of the the height of the feature map
# W - index of the width of the feature map
NHW = (0, 1, 2)
X_train, y_train, X_val, y_val, X_test, y_test = load_cifar10()
print('Train data shape: ', X_train.shape)
print('Train labels shape: ', y_train.shape, y_train.dtype)
print('Validation data shape: ', X_val.shape)
print('Validation labels shape: ', y_val.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
```
#### 3.2 Preparation: Dataset object
Borrowed from CS231N [2], we will define a `Dataset` class for iteration to store data and labels.
```
class Dataset(object):
def __init__(self, X, y, batch_size, shuffle=False):
"""
Construct a Dataset object to iterate over data X and labels y
Inputs:
- X: Numpy array of data, of any shape
- y: Numpy array of labels, of any shape but with y.shape[0] == X.shape[0]
- batch_size: Integer giving number of elements per minibatch
- shuffle: (optional) Boolean, whether to shuffle the data on each epoch
"""
assert X.shape[0] == y.shape[0], 'Got different numbers of data and labels'
self.X, self.y = X, y
self.batch_size, self.shuffle = batch_size, shuffle
def __iter__(self):
N, B = self.X.shape[0], self.batch_size
idxs = np.arange(N)
if self.shuffle:
np.random.shuffle(idxs)
return iter((self.X[i:i+B], self.y[i:i+B]) for i in range(0, N, B))
train_dset = Dataset(X_train, y_train, batch_size=64, shuffle=True)
val_dset = Dataset(X_val, y_val, batch_size=64, shuffle=False)
test_dset = Dataset(X_test, y_test, batch_size=64)
print "Done"
# We can iterate through a dataset like this:
for t, (x, y) in enumerate(train_dset):
print(t, x.shape, y.shape)
if t > 5: break
# You can also optionally set GPU to true if you are working on AWS/Google Cloud (more on that later). For now,
# we to false
# Set up some global variables
USE_GPU = False
if USE_GPU:
device = '/device:GPU:0'
else:
device = '/cpu:0'
# Constant to control how often we print when training models
print_every = 100
print('Using device: ', device)
# Borrowed fromcs231n.github.io/assignments2018/assignment2/
# We define a flatten utility function to help us flatten our image data - the 32x32x3
# (or 32 x 32 image size with three channels for RGB) flattens into 3072
def flatten(x):
"""
Input:
- TensorFlow Tensor of shape (N, D1, ..., DM)
Output:
- TensorFlow Tensor of shape (N, D1 * ... * DM)
"""
N = tf.shape(x)[0]
return tf.reshape(x, (N, -1))
def two_layer_fc(x, params):
"""
A fully-connected neural network; the architecture is:
fully-connected layer -> ReLU -> fully connected layer.
Note that we only need to define the forward pass here; TensorFlow will take
care of computing the gradients for us.
The input to the network will be a minibatch of data, of shape
(N, d1, ..., dM) where d1 * ... * dM = D. The hidden layer will have H units,
and the output layer will produce scores for C classes.
Inputs:
- x: A TensorFlow Tensor of shape (N, d1, ..., dM) giving a minibatch of
input data.
- params: A list [w1, w2] of TensorFlow Tensors giving weights for the
network, where w1 has shape (D, H) and w2 has shape (H, C).
Returns:
- scores: A TensorFlow Tensor of shape (N, C) giving classification scores
for the input data x.
"""
w1, w2 = params # Unpack the parameters
x = flatten(x) # Flatten the input; now x has shape (N, D)
h = tf.nn.relu(tf.matmul(x, w1)) # Hidden layer: h has shape (N, H)
scores = tf.matmul(h, w2) # Compute scores of shape (N, C)
return scores
def two_layer_fc_test():
# TensorFlow's default computational graph is essentially a hidden global
# variable. To avoid adding to this default graph when you rerun this cell,
# we clear the default graph before constructing the graph we care about.
tf.reset_default_graph()
hidden_layer_size = 42
# Scoping our computational graph setup code under a tf.device context
# manager lets us tell TensorFlow where we want these Tensors to be
# placed.
with tf.device(device):
# Set up a placehoder for the input of the network, and constant
# zero Tensors for the network weights. Here we declare w1 and w2
# using tf.zeros instead of tf.placeholder as we've seen before - this
# means that the values of w1 and w2 will be stored in the computational
# graph itself and will persist across multiple runs of the graph; in
# particular this means that we don't have to pass values for w1 and w2
# using a feed_dict when we eventually run the graph.
x = tf.placeholder(tf.float32)
w1 = tf.zeros((32 * 32 * 3, hidden_layer_size))
w2 = tf.zeros((hidden_layer_size, 10))
# Call our two_layer_fc function to set up the computational
# graph for the forward pass of the network.
scores = two_layer_fc(x, [w1, w2])
# Use numpy to create some concrete data that we will pass to the
# computational graph for the x placeholder.
x_np = np.zeros((64, 32, 32, 3))
with tf.Session() as sess:
# The calls to tf.zeros above do not actually instantiate the values
# for w1 and w2; the following line tells TensorFlow to instantiate
# the values of all Tensors (like w1 and w2) that live in the graph.
sess.run(tf.global_variables_initializer())
# Here we actually run the graph, using the feed_dict to pass the
# value to bind to the placeholder for x; we ask TensorFlow to compute
# the value of the scores Tensor, which it returns as a numpy array.
scores_np = sess.run(scores, feed_dict={x: x_np})
print scores_np
print(scores_np.shape)
two_layer_fc_test()
# should print a bunch of zeros
# should print {64, 10}
print "Done"
```
#### 3.3 Training
We will now train using the gradient descent algorithm explained in the previous notebook. The check_accuracy function below lets us check the accuracy of our neural network.
As explained in CS231N:
"The `training_step` function has three basic steps:
1. Compute the loss
2. Compute the gradient of the loss with respect to all network weights
3. Make a weight update step using (stochastic) gradient descent.
Note that the step of updating the weights is itself an operation in the computational graph - the calls to `tf.assign_sub` in `training_step` return TensorFlow operations that mutate the weights when they are executed. There is an important bit of subtlety here - when we call `sess.run`, TensorFlow does not execute all operations in the computational graph; it only executes the minimal subset of the graph necessary to compute the outputs that we ask TensorFlow to produce. As a result, naively computing the loss would not cause the weight update operations to execute, since the operations needed to compute the loss do not depend on the output of the weight update. To fix this problem, we insert a **control dependency** into the graph, adding a duplicate `loss` node to the graph that does depend on the outputs of the weight update operations; this is the object that we actually return from the `training_step` function. As a result, asking TensorFlow to evaluate the value of the `loss` returned from `training_step` will also implicitly update the weights of the network using that minibatch of data.
We need to use a few new TensorFlow functions to do all of this:
- For computing the cross-entropy loss we'll use `tf.nn.sparse_softmax_cross_entropy_with_logits`: https://www.tensorflow.org/api_docs/python/tf/nn/sparse_softmax_cross_entropy_with_logits
- For averaging the loss across a minibatch of data we'll use `tf.reduce_mean`:
https://www.tensorflow.org/api_docs/python/tf/reduce_mean
- For computing gradients of the loss with respect to the weights we'll use `tf.gradients`: https://www.tensorflow.org/api_docs/python/tf/gradients
- We'll mutate the weight values stored in a TensorFlow Tensor using `tf.assign_sub`: https://www.tensorflow.org/api_docs/python/tf/assign_sub
- We'll add a control dependency to the graph using `tf.control_dependencies`: https://www.tensorflow.org/api_docs/python/tf/control_dependencies"
```
# Borrowed from cs231n.github.io/assignments2018/assignment2/
def training_step(scores, y, params, learning_rate):
"""
Set up the part of the computational graph which makes a training step.
Inputs:
- scores: TensorFlow Tensor of shape (N, C) giving classification scores for
the model.
- y: TensorFlow Tensor of shape (N,) giving ground-truth labels for scores;
y[i] == c means that c is the correct class for scores[i].
- params: List of TensorFlow Tensors giving the weights of the model
- learning_rate: Python scalar giving the learning rate to use for gradient
descent step.
Returns:
- loss: A TensorFlow Tensor of shape () (scalar) giving the loss for this
batch of data; evaluating the loss also performs a gradient descent step
on params (see above).
"""
# First compute the loss; the first line gives losses for each example in
# the minibatch, and the second averages the losses acros the batch
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores)
loss = tf.reduce_mean(losses)
# Compute the gradient of the loss with respect to each parameter of the the
# network. This is a very magical function call: TensorFlow internally
# traverses the computational graph starting at loss backward to each element
# of params, and uses backpropagation to figure out how to compute gradients;
# it then adds new operations to the computational graph which compute the
# requested gradients, and returns a list of TensorFlow Tensors that will
# contain the requested gradients when evaluated.
grad_params = tf.gradients(loss, params)
# Make a gradient descent step on all of the model parameters.
new_weights = []
for w, grad_w in zip(params, grad_params):
new_w = tf.assign_sub(w, learning_rate * grad_w)
new_weights.append(new_w)
# Insert a control dependency so that evaluting the loss causes a weight
# update to happen; see the discussion above.
with tf.control_dependencies(new_weights):
return tf.identity(loss)
# Train using stochastic gradient descent without momentum
def train(model_fn, init_fn, learning_rate):
"""
Train a model on CIFAR-10.
Inputs:
- model_fn: A Python function that performs the forward pass of the model
using TensorFlow; it should have the following signature:
scores = model_fn(x, params) where x is a TensorFlow Tensor giving a
minibatch of image data, params is a list of TensorFlow Tensors holding
the model weights, and scores is a TensorFlow Tensor of shape (N, C)
giving scores for all elements of x.
- init_fn: A Python function that initializes the parameters of the model.
It should have the signature params = init_fn() where params is a list
of TensorFlow Tensors holding the (randomly initialized) weights of the
model.
- learning_rate: Python float giving the learning rate to use for SGD.
"""
# First clear the default graph
tf.reset_default_graph()
is_training = tf.placeholder(tf.bool, name='is_training')
# Set up the computational graph for performing forward and backward passes,
# and weight updates.
with tf.device(device):
# Set up placeholders for the data and labels
x = tf.placeholder(tf.float32, [None, 32, 32, 3])
y = tf.placeholder(tf.int32, [None])
params = init_fn() # Initialize the model parameters
scores = model_fn(x, params) # Forward pass of the model
loss = training_step(scores, y, params, learning_rate)
# Now we actually run the graph many times using the training data
with tf.Session() as sess:
# Initialize variables that will live in the graph
sess.run(tf.global_variables_initializer())
for t, (x_np, y_np) in enumerate(train_dset):
# Run the graph on a batch of training data; recall that asking
# TensorFlow to evaluate loss will cause an SGD step to happen.
feed_dict = {x: x_np, y: y_np}
loss_np = sess.run(loss, feed_dict=feed_dict)
# Periodically print the loss and check accuracy on the val set
if t % print_every == 0:
print('Iteration %d, loss = %.4f' % (t, loss_np))
check_accuracy(sess, val_dset, x, scores, is_training)
# Helper method for evaluating our model accuracy (note it also runs the computational graph but doesn't update loss)
def check_accuracy(sess, dset, x, scores, is_training=None):
"""
Check accuracy on a classification model.
Inputs:
- sess: A TensorFlow Session that will be used to run the graph
- dset: A Dataset object on which to check accuracy
- x: A TensorFlow placeholder Tensor where input images should be fed
- scores: A TensorFlow Tensor representing the scores output from the
model; this is the Tensor we will ask TensorFlow to evaluate.
Returns: Nothing, but prints the accuracy of the model
"""
num_correct, num_samples = 0, 0
for x_batch, y_batch in dset:
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
num_samples += x_batch.shape[0]
num_correct += (y_pred == y_batch).sum()
acc = float(num_correct) / num_samples
print('Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))
print "Done"
# Borrowed from cs231n.github.io/assignments2018/assignment2/
# We initialize the weight matrices for our models using a method known as Kaiming's normalization method [8]
def kaiming_normal(shape):
if len(shape) == 2:
fan_in, fan_out = shape[0], shape[1]
elif len(shape) == 4:
fan_in, fan_out = np.prod(shape[:3]), shape[3]
return tf.random_normal(shape) * np.sqrt(2.0 / fan_in)
def two_layer_fc_init():
"""
Initialize the weights of a two-layer network (one hidden layer), for use with the
two_layer_network function defined above.
Inputs: None
Returns: A list of:
- w1: TensorFlow Variable giving the weights for the first layer
- w2: TensorFlow Variable giving the weights for the second layer
"""
# Numer of neurons in hidden layer
hidden_layer_size = 4000
# Now we initialize the weights of our two layer network using tf.Variable
# "A TensorFlow Variable is a Tensor whose value is stored in the graph and persists across runs of the
# computational graph; however unlike constants defined with `tf.zeros` or `tf.random_normal`,
# the values of a Variable can be mutated as the graph runs; these mutations will persist across graph runs.
# Learnable parameters of the network are usually stored in Variables."
w1 = tf.Variable(kaiming_normal((3 * 32 * 32, hidden_layer_size)))
w2 = tf.Variable(kaiming_normal((hidden_layer_size, 10)))
return [w1, w2]
print "Done"
# Now we actually train our model with one *epoch* ! We use a learning rate of 0.01
learning_rate = 1e-2
train(two_layer_fc, two_layer_fc_init, learning_rate)
# You should see an accuracy of >40% with just one epoch (an epoch in this case consists of 700 iterations
# of gradient descent but can be tuned)
```
#### 3.3 Keras
Note in the first cell, we used the tf.keras Sequential API to make a neural network but here we use "barebones" Tensorflow. One of the good (and possibly bad) things about Tensorflow is that there are several ways to create a neural network and train it. Here are some possible ways:
* Barebones tensorflow
* tf.keras Model API
* tf.keras Sequential API
Here is a table of comparison borrowed from [2]:
| API | Flexibility | Convenience |
|---------------|-------------|-------------|
| Barebone | High | Low |
| `tf.keras.Model` | High | Medium |
| `tf.keras.Sequential` | Low | High |
Note that with the tf.keras Model API, you have the options of using the **object-oriented API**, where each layer of the neural network is represented as a Python object (like `tf.layers.Dense`) or the **functional API**, where each layer is a Python function (like `tf.layers.dense`). We will only use the Sequential API and skip the Model API in the cells below because we will simply trade off lots of flexiblity for convenience.
```
# Now we will train the same model using the Sequential API.
# First we set up our training and model initializiation functions
def train_keras(model_init_fn, optimizer_init_fn, num_epochs=1):
"""
Simple training loop for use with models defined using tf.keras. It trains
a model for one epoch on the CIFAR-10 training set and periodically checks
accuracy on the CIFAR-10 validation set.
Inputs:
- model_init_fn: A function that takes no parameters; when called it
constructs the model we want to train: model = model_init_fn()
- optimizer_init_fn: A function which takes no parameters; when called it
constructs the Optimizer object we will use to optimize the model:
optimizer = optimizer_init_fn()
- num_epochs: The number of epochs to train for
Returns: Nothing, but prints progress during trainingn
"""
tf.reset_default_graph()
with tf.device(device):
# Construct the computational graph we will use to train the model. We
# use the model_init_fn to construct the model, declare placeholders for
# the data and labels
x = tf.placeholder(tf.float32, [None, 32, 32, 3])
y = tf.placeholder(tf.int32, [None])
# We need a place holder to explicitly specify if the model is in the training
# phase or not. This is because a number of layers behaves differently in
# training and in testing, e.g., dropout and batch normalization.
# We pass this variable to the computation graph through feed_dict as shown below.
is_training = tf.placeholder(tf.bool, name='is_training')
# Use the model function to build the forward pass.
scores = model_init_fn(x, is_training)
# Compute the loss like we did in Part II
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores)
loss = tf.reduce_mean(loss)
# Use the optimizer_fn to construct an Optimizer, then use the optimizer
# to set up the training step. Asking TensorFlow to evaluate the
# train_op returned by optimizer.minimize(loss) will cause us to make a
# single update step using the current minibatch of data.
# Note that we use tf.control_dependencies to force the model to run
# the tf.GraphKeys.UPDATE_OPS at each training step. tf.GraphKeys.UPDATE_OPS
# holds the operators that update the states of the network.
# For example, the tf.layers.batch_normalization function adds the running mean
# and variance update operators to tf.GraphKeys.UPDATE_OPS.
optimizer = optimizer_init_fn()
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss)
# Now we can run the computational graph many times to train the model.
# When we call sess.run we ask it to evaluate train_op, which causes the
# model to update.
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
t = 0
for epoch in range(num_epochs):
print('Starting epoch %d' % epoch)
for x_np, y_np in train_dset:
feed_dict = {x: x_np, y: y_np, is_training:1}
loss_np, _ = sess.run([loss, train_op], feed_dict=feed_dict)
if t % print_every == 0:
print('Iteration %d, loss = %.4f' % (t, loss_np))
check_accuracy(sess, val_dset, x, scores, is_training=is_training)
print()
t += 1
def model_init_fn(inputs, is_training):
input_shape = (32, 32, 3)
hidden_layer_size, num_classes = 4000, 10
initializer = tf.variance_scaling_initializer(scale=2.0)
layers = [
tf.layers.Flatten(input_shape=input_shape),
tf.layers.Dense(hidden_layer_size, activation=tf.nn.relu,
kernel_initializer=initializer),
tf.layers.Dense(num_classes, kernel_initializer=initializer),
]
model = tf.keras.Sequential(layers)
return model(inputs)
def optimizer_init_fn():
return tf.train.GradientDescentOptimizer(learning_rate)
print "Done"
# Now the actual training
learning_rate = 1e-2
train_keras(model_init_fn, optimizer_init_fn)
# Again, you should see accuracy > 40% after one epoch (700 iterations) of gradient descent
```
### 4. Backpropagation
You'll often hear the term "backpropagation" or "backprop," which is a way of updating a neural network. Google has a great demo that walks you through the backpropagation algorithm in detail. I encourage you to check it out!
https://google-developers.appspot.com/machine-learning/crash-course/backprop-scroll/
See also this seminar by Geoffrey Hinton, a premier deep learning researcher, on whether the brain can do back-propagation. It's an interesting lecture with relatively : https://www.youtube.com/watch?v=VIRCybGgHts
### 5. References
<pre>
[1] Fast.ai (http://course.fast.ai/)
[2] CS231N (http://cs231n.github.io/)
[3] CS224D (http://cs224d.stanford.edu/syllabus.html)
[4] Hands on Machine Learning (https://github.com/ageron/handson-ml)
[5] Deep learning with Python Notebooks (https://github.com/fchollet/deep-learning-with-python-notebooks)
[6] Deep learning by Goodfellow et. al (http://www.deeplearningbook.org/)
[7] Neural networks online book (http://neuralnetworksanddeeplearning.com/)
[8] He et al, *Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
*, ICCV 2015, https://arxiv.org/abs/1502.01852
</pre>
| github_jupyter |
```
import tensorflow as tf
print(tf.__version__)
import tensorflow_datasets as tfds
print(tfds.__version__)
```
# Get dataset
```
SPLIT_WEIGHTS = (8, 1, 1)
splits = tfds.Split.TRAIN.subsplit(weighted=SPLIT_WEIGHTS)
(raw_train, raw_validation, raw_test), metadata = tfds.load('cats_vs_dogs',
split=list(splits),
with_info=True,
as_supervised=True)
print(metadata.features)
import matplotlib.pyplot as plt
%matplotlib inline
get_label_name = metadata.features['label'].int2str
for image, label in raw_train.take(2):
plt.figure()
plt.imshow(image)
plt.title(get_label_name(label))
```
# Prepare input pipelines
```
IMG_SIZE = 160
BATCH_SIZE = 32
SHUFFLE_BUFFER_SIZE = 1000
def normalize_img(image, label):
image = tf.cast(image, tf.float32)
image = (image / 127.5) - 1.0
image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))
return image, label
ds_train = raw_train.map(normalize_img)
ds_validation = raw_validation.map(normalize_img)
ds_test = raw_test.map(normalize_img)
ds_train = ds_train.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)
ds_validation = ds_validation.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)
ds_test = ds_test.batch(BATCH_SIZE)
```
# Get pretrained model
```
base_model = tf.keras.applications.MobileNetV2(input_shape=(IMG_SIZE, IMG_SIZE, 3),
include_top=False,
weights='imagenet')
base_model.trainable = False
model = tf.keras.Sequential([
base_model,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(1)
])
model.summary()
```
# (Optional): Use Tensorflow Hub
```
import tensorflow_hub as hub
print(hub.__version__)
feature_extractor_url = "https://tfhub.dev/google/imagenet/mobilenet_v2_035_160/classification/4"
base_model = hub.KerasLayer(feature_extractor_url, input_shape=(IMG_SIZE, IMG_SIZE, 3), trainable=False)
model = tf.keras.Sequential([
base_model,
tf.keras.layers.Dense(1)
])
model.summary()
```
# Compile model
```
base_learning_rate = 1e-4
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
```
# Evaluate random model
```
loss0, accuracy0 = model.evaluate(ds_validation)
```
# Train model
```
initial_epochs = 3
history = model.fit(ds_train,
epochs=initial_epochs,
validation_data=ds_validation)
```
# Fine-tune
```
base_model.trainable = True
base_learning_rate = 1e-5
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
model.summary()
fine_tune_epochs = 3
total_epochs = initial_epochs + fine_tune_epochs
history_fine = model.fit(ds_train,
epochs=total_epochs,
initial_epoch=history.epoch[-1],
validation_data=ds_validation)
```
| github_jupyter |
# Optimización
Author: Jesús Cid-Sueiro
Jerónimo Arenas-García
Versión: 0.1 (2019/09/13)
0.2 (2019/10/02): Solutions added
## Exercise: compute the minimum of a real-valued function
The goal of this exercise is to implement and test optimization algorithms for the minimization of a given function. Gradient descent and Newton's method will be explored.
Our goal it so find the minimizer of the real-valued function
$$
f(w) = - w exp(-w)
$$
but the whole code will be easily modified to try with other alternative functions.
You will need to import some libraries (at least, `numpy` and `matplotlib`). Insert below all the imports needed along the whole notebook. Remind that numpy is usually abbreviated as np and `matplotlib.pyplot` is usually abbreviated as `plt`.
```
# <SOL>
# </SOL>
```
### Part 1: The function and its derivatives.
**Question 1.1**: Implement the following three methods:
* Method **`f`**: given $w$, it returns the value of function $f(w)$.
* Method **`df`**: given $w$, it returns the derivative of $f$ at $w$
* Medhod **`d2f`**: given $w$, it returns the second derivative of $f$ at $w$
```
# Funcion f
# <SOL>
# </SOL>
# First derivative
# <SOL>
# </SOL>
# Second derivative
# <SOL>
# </SOL>
```
### Part 2: Gradient descent.
**Question 2.1**: Implement a method **`gd`** that, given `w` and a learning rate parameter `rho` applies a single iteration of the gradien descent algorithm
```
# <SOL>
# </SOL>
```
**Question 2.2**: Apply the gradient descent to optimize the given function. To do so, start with an initial value $w=0$ and iterate $20$ times. Save two lists:
* A list of succesive values of $w_n$
* A list of succesive values of the function $f(w_n)$.
```
# <SOL>
# </SOL>
```
**Question 2.3**: Plot, in a single figure:
* The given function, for values ranging from 0 to 20.
* The sequence of points $(w_n, f(w_n))$.
```
# <SOL>
# </SOL>
```
You can check the effect of modifying the value of the learning rate.
### Part 2: Newton's method.
**Question 3.1**: Implement a method **`newton`** that, given `w` and a learning rate parameter `rho` applies a single iteration of the Newton's method
```
# <SOL>
# </SOL>
```
**Question 3**: Apply the Newton's method to optimize the given function. To do so, start with an initial value $w=0$ and iterate $20$ times. Save two lists:
* A list of succesive values of $w_n$
* A list of succesive values of the function $f(w_n)$.
```
# <SOL>
# </SOL>
```
**Question 4**: Plot, in a single figure:
* The given function, for values ranging from 0 to 20.
* The sequence of points $(w_n, f(w_n))$.
```
# <SOL>
# </SOL>
```
You can check the effect of modifying the value of the learning rate.
### Part 3: Optimize other cost functions
Now you are ready to explore these optimization algorithms with other more sophisticated functions. Try with them.
| github_jupyter |
# Example 3. CNN + DDA
Here, we train the same CNN as in previous notebook but applying the Direct Domain Adaptation method (DDA) to reduce the gap between MNIST and MNIST-M datasets.
-------
This code is modified from [https://github.com/fungtion/DANN_py3](https://github.com/fungtion/DANN_py3).
```
import os
import sys
import tqdm
import random
import numpy as np
from numpy.fft import rfft2, irfft2, fftshift, ifftshift
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.nn as nn
import torch.utils.data
from torchvision import datasets
from torchvision import transforms
from components.data_loader import GetLoader
from components.model import CNNModel
from components.test import test
import components.shared as sd
# os.environ["CUDA_VISIBLE_DEVICES"] = "2"
```
### Init paths
```
# Paths to datasets
source_dataset_name = 'MNIST'
target_dataset_name = 'mnist_m'
source_image_root = os.path.join('dataset', source_dataset_name)
target_image_root = os.path.join('dataset', target_dataset_name)
os.makedirs('./dataset', exist_ok=True)
# Where to save outputs
model_root = './out_ex3_cnn_da'
os.makedirs(model_root, exist_ok=True)
```
### Init training
```
cuda = True
cudnn.benchmark = True
# Hyperparameters
lr = 1e-3
batch_size = 128
image_size = 28
n_epoch = 100
# manual_seed = random.randint(1, 10000)
manual_seed = 222
random.seed(manual_seed)
torch.manual_seed(manual_seed)
print(f'Random seed: {manual_seed}')
```
### Data
```
# Transformations / augmentations
img_transform_source = transforms.Compose([
transforms.Resize(image_size),
transforms.ToTensor(),
transforms.Normalize(mean=(0.1307,), std=(0.3081,)),
transforms.Lambda(lambda x: x.repeat(3, 1, 1)),
])
img_transform_target = transforms.Compose([
transforms.Resize(image_size),
transforms.ToTensor(),
transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))
])
# Load MNIST dataset
dataset_source = datasets.MNIST(
root='dataset',
train=True,
transform=img_transform_source,
download=True
)
# Load MNIST-M dataset
train_list = os.path.join(target_image_root, 'mnist_m_train_labels.txt')
dataset_target = GetLoader(
data_root=os.path.join(target_image_root, 'mnist_m_train'),
data_list=train_list,
transform=img_transform_target
)
```
# Direct Domain Adaptation (DDA)
## Average auto-correlation
For entire dataset
```
def get_global_acorr_for_loader(loader):
""" The average auto-correlation of all images in the dataset """
global_acorr = np.zeros((3, 28, 15), dtype=np.complex128)
prog_bar = tqdm.tqdm(loader)
for data, _ in prog_bar:
data_f = np.fft.rfft2(data, s=data.shape[-2:], axes=(-2, -1))
# Auto-correlation is multiplication with the conjucate of self
# in frequency domain
global_acorr += data_f * np.conjugate(data_f)
global_acorr /= len(loader)
print(global_acorr.shape)
return np.fft.fftshift(global_acorr)
def route_to(fname):
""" Shortcut for routing to the save folder """
return os.path.join(model_root, fname)
# Compute global acorr if not in the folder, load otherwise
if not 'gacorr_dst_tr.npy' in os.listdir(model_root):
print('Save global acorr')
gacorr_dst_tr = get_global_acorr_for_loader(dataset_target)
gacorr_src_tr = get_global_acorr_for_loader(dataset_source)
np.save(route_to('gacorr_dst_tr.npy'), gacorr_dst_tr)
np.save(route_to('gacorr_src_tr.npy'), gacorr_src_tr)
else:
print('Load global acorr')
gacorr_dst_tr = np.load(route_to('gacorr_dst_tr.npy'))
gacorr_src_tr = np.load(route_to('gacorr_src_tr.npy'))
```
## Average cross-correlation
Pick a random pixel(-s) from each image in the dataset and average
```
# Window size
crop_size = 1
print(f'Use the crop size for xcorr = {crop_size}')
def crop_ref(x, n=1, edge=5):
"""Crop a window from the image
Args:
x(np.ndarray): image [c, h, w]
n(int): window size
edge(int): margin to avoid from edges of the image
"""
if n % 2 == 0: n+=1;
k = int((n - 1) / 2)
nz, nx = x.shape[-2:]
dim1 = np.random.randint(0+k+edge, nz-k-edge)
dim2 = np.random.randint(0+k, nx-k)
out = x[..., dim1-k:dim1+k+1, dim2-k:dim2+k+1]
return out
# crop_ref(np.ones((2, 100, 100)), n=5).shape
def get_global_xcorr_for_loader(loader, crop_size=1):
# Init the placeholder for average
rand_pixel = np.zeros((3, crop_size, crop_size))
# Loop over all images in the dataset
prog_bar = tqdm.tqdm(loader)
for data, _ in prog_bar:
rand_pixel += np.mean(crop_ref(data, crop_size).numpy(), axis=0)
rand_pixel /= len(loader)
# Place the mean pixel into center of an empty image
c, h ,w = data.shape
mid_h, mid_w = int(h // 2), int(w // 2)
embed = np.zeros_like(data)
embed[..., mid_h:mid_h+1, mid_w:mid_w+1] = rand_pixel
global_xcorr = np.fft.rfft2(embed, s=data.shape[-2:], axes=(-2, -1))
return np.fft.fftshift(global_xcorr)
# Compute global xcorr if not in the folder, load otherwise
if not 'gxcorr_dst_tr.npy' in os.listdir(model_root):
# if True:
print('Save global xcorr')
gxcorr_dst_tr = get_global_xcorr_for_loader(dataset_target, crop_size)
gxcorr_src_tr = get_global_xcorr_for_loader(dataset_source, crop_size)
np.save(route_to('gxcorr_dst_tr.npy'), gxcorr_dst_tr)
np.save(route_to('gxcorr_src_tr.npy'), gxcorr_src_tr)
else:
print('Load global xcorr')
gxcorr_dst_tr = np.load(route_to('gxcorr_dst_tr.npy'))
gxcorr_src_tr = np.load(route_to('gxcorr_src_tr.npy'))
```
## Train Loader
```
def flip_channels(x):
"""Reverse polarity of random channels"""
flip_matrix = np.random.choice([-1, 1], 3)[..., np.newaxis, np.newaxis]
return (x * flip_matrix).astype(np.float32)
def shuffle_channels(x):
"""Change order of channels"""
return np.random.permutation(x)
def normalize_channels(x):
"""Map data to [-1,1] range. The scaling after conv(xcorr, acorr) is not
suitable for image processing so this function fixes it"""
cmin = np.min(x, axis=(-2,-1))[..., np.newaxis, np.newaxis]
x -= cmin
cmax = np.max(np.abs(x), axis=(-2,-1))[..., np.newaxis, np.newaxis]
x /= cmax
x *= 2
x -= 1
return x.astype(np.float32)
class DDALoaderTrain(torch.utils.data.Dataset):
def __init__(self, loader1, avg_acorr2, p=0.5, crop_size=1):
super().__init__()
self.loader1 = loader1
self.avg_acorr2 = avg_acorr2
self.p = p
self.crop_size = crop_size
def __len__(self):
return len(self.loader1)
def __getitem__(self, item):
# Get main data (data, label)
data, label = self.loader1.__getitem__(item)
data_fft = fftshift(rfft2(data, s=data.shape[-2:], axes=(-2, -1)))
# Get random pixel from another data from the same dataset
random_index = np.random.randint(0, len(self.loader1))
another_data, _ = self.loader1.__getitem__(random_index)
rand_pixel = crop_ref(another_data, self.crop_size)
# Convert to Fourier domain
c, h ,w = another_data.shape
mid_h, mid_w = int(h // 2), int(w // 2)
embed = np.zeros_like(another_data)
embed[:, mid_h:mid_h+1, mid_w:mid_w+1] = rand_pixel
pixel_fft = np.fft.rfft2(embed, s=another_data.shape[-2:], axes=(-2, -1))
pixel_fft = np.fft.fftshift(pixel_fft)
# Cross-correlate the data sample with the random pixel from the same dataset
xcorr = data_fft * np.conjugate(pixel_fft)
# Convolve the ruslt with the auto-correlation of another dataset
conv = xcorr * self.avg_acorr2
# Reverse Fourier domain and map channels to [-1, 1] range
data_da = fftshift(irfft2(ifftshift(conv), axes=(-2, -1)))
data_da = normalize_channels(data_da)
# Apply data augmentations
if np.random.rand() < self.p:
data_da = flip_channels(data_da)
if np.random.rand() < self.p:
data_da = shuffle_channels(data_da)
# Return a pair of data / label
return data_da.astype(np.float32), label
dataset_source = DDALoaderTrain(dataset_source, gacorr_dst_tr)
dataset_target = DDALoaderTrain(dataset_target, gacorr_src_tr)
dummy_data, dummy_label = dataset_source.__getitem__(0)
print('Image shape: {}\t Label: {}'.format(dummy_data.shape, dummy_label))
```
# Test Loader
```
class DDALoaderTest(torch.utils.data.Dataset):
def __init__(self, loader1, avg_acorr2, avg_xcorr1):
super().__init__()
self.loader1 = loader1
self.avg_acorr2 = avg_acorr2
self.avg_xcorr1 = avg_xcorr1
def __len__(self):
return len(self.loader1)
def __getitem__(self, item):
data, label = self.loader1.__getitem__(item)
data_fft = fftshift(rfft2(data, s=data.shape[-2:], axes=(-2, -1)))
xcorr = data_fft * np.conjugate(self.avg_xcorr1)
conv = xcorr * self.avg_acorr2
data_da = fftshift(irfft2(ifftshift(conv), axes=(-2, -1)))
data_da = normalize_channels(data_da)
return data_da.astype(np.float32), label
```
Re-define the test function so it accounts for the average cross-correlation and auto-correlation from source and target datasets
```
def test(dataset_name, model_root, crop_size=1):
image_root = os.path.join('dataset', dataset_name)
if dataset_name == 'mnist_m':
test_list = os.path.join(image_root, 'mnist_m_test_labels.txt')
dataset = GetLoader(
data_root=os.path.join(image_root, 'mnist_m_test'),
data_list=test_list,
transform=img_transform_target
)
if not 'gxcorr_dst_te.npy' in os.listdir(model_root):
print('Save global acorr and xcorr')
# acorr
gacorr_src_te = get_global_acorr_for_loader(dataset)
np.save(route_to('gacorr_src_te.npy'), gacorr_src_te)
# xcorr
gxcorr_dst_te = get_global_xcorr_for_loader(dataset, crop_size)
np.save(route_to('gxcorr_dst_te.npy'), gxcorr_dst_te)
else:
gacorr_src_te = np.load(route_to('gacorr_src_te.npy'))
gxcorr_dst_te = np.load(route_to('gxcorr_dst_te.npy'))
# Init loader for MNIST-M
dataset = DDALoaderTest(dataset, gacorr_src_te, gxcorr_dst_te)
else:
dataset = datasets.MNIST(
root='dataset',
train=False,
transform=img_transform_source,
)
if not 'gxcorr_src_te.npy' in os.listdir(model_root):
print('Save global acorr and xcorr')
# acorr
gacorr_dst_te = get_global_acorr_for_loader(dataset)
np.save(route_to('gacorr_dst_te.npy'), gacorr_dst_te)
# xcorr
gxcorr_src_te = get_global_xcorr_for_loader(dataset, crop_size)
np.save(route_to('gxcorr_src_te.npy'), gxcorr_src_te)
else:
gacorr_dst_te = np.load(route_to('gacorr_dst_te.npy'))
gxcorr_src_te = np.load(route_to('gxcorr_src_te.npy'))
# Init loader for MNIST
dataset = DDALoaderTest(dataset, gacorr_dst_te, gxcorr_src_te)
dataloader = torch.utils.data.DataLoader(
dataset=dataset,
batch_size=batch_size,
shuffle=False,
num_workers=8
)
""" test """
my_net = torch.load(os.path.join(model_root, 'mnist_mnistm_model_epoch_current.pth'))
my_net = my_net.eval()
if cuda:
my_net = my_net.cuda()
len_dataloader = len(dataloader)
data_target_iter = iter(dataloader)
i = 0
n_total = 0
n_correct = 0
while i < len_dataloader:
# test model using target data
data_target = data_target_iter.next()
t_img, t_label = data_target
_batch_size = len(t_label)
if cuda:
t_img = t_img.cuda()
t_label = t_label.cuda()
class_output, _ = my_net(input_data=t_img, alpha=0)
pred = class_output.data.max(1, keepdim=True)[1]
n_correct += pred.eq(t_label.data.view_as(pred)).cpu().sum()
n_total += _batch_size
i += 1
accu = n_correct.data.numpy() * 1.0 / n_total
return accu
```
# Training
```
dataloader_source = torch.utils.data.DataLoader(
dataset=dataset_source,
batch_size=batch_size,
shuffle=True,
num_workers=8)
dataloader_target = torch.utils.data.DataLoader(
dataset=dataset_target,
batch_size=batch_size,
shuffle=True,
num_workers=8)
class CNNModel(nn.Module):
def __init__(self):
super(CNNModel, self).__init__()
self.feature = nn.Sequential()
self.feature.add_module('f_conv1', nn.Conv2d(3, 64, kernel_size=5))
self.feature.add_module('f_bn1', nn.BatchNorm2d(64))
self.feature.add_module('f_pool1', nn.MaxPool2d(2))
self.feature.add_module('f_relu1', nn.ReLU(True))
self.feature.add_module('f_conv2', nn.Conv2d(64, 50, kernel_size=5))
self.feature.add_module('f_bn2', nn.BatchNorm2d(50))
self.feature.add_module('f_drop1', nn.Dropout2d())
self.feature.add_module('f_pool2', nn.MaxPool2d(2))
self.feature.add_module('f_relu2', nn.ReLU(True))
self.class_classifier = nn.Sequential()
self.class_classifier.add_module('c_fc1', nn.Linear(50 * 4 * 4, 100))
self.class_classifier.add_module('c_bn1', nn.BatchNorm1d(100))
self.class_classifier.add_module('c_relu1', nn.ReLU(True))
self.class_classifier.add_module('c_drop1', nn.Dropout())
self.class_classifier.add_module('c_fc2', nn.Linear(100, 100))
self.class_classifier.add_module('c_bn2', nn.BatchNorm1d(100))
self.class_classifier.add_module('c_relu2', nn.ReLU(True))
self.class_classifier.add_module('c_fc3', nn.Linear(100, 10))
self.class_classifier.add_module('c_softmax', nn.LogSoftmax(dim=1))
def forward(self, input_data, alpha):
input_data = input_data.expand(input_data.data.shape[0], 3, 28, 28)
feature = self.feature(input_data)
feature = feature.view(-1, 50 * 4 * 4)
class_output = self.class_classifier(feature)
return class_output, 0
# load model
my_net = CNNModel()
# setup optimizer
optimizer = optim.Adam(my_net.parameters(), lr=lr)
loss_class = torch.nn.NLLLoss()
if cuda:
my_net = my_net.cuda()
loss_class = loss_class.cuda()
for p in my_net.parameters():
p.requires_grad = True
# Record losses for each epoch (used in compare.ipynb)
losses = {'test': {'acc_bw': [], 'acc_color': []}}
name_losses = 'losses.pkl'
if not name_losses in os.listdir(model_root):
# if True:
# training
best_accu_t = 0.0
for epoch in range(n_epoch):
len_dataloader = min(len(dataloader_source), len(dataloader_target))
data_source_iter = iter(dataloader_source)
data_target_iter = iter(dataloader_target)
for i in range(len_dataloader):
p = float(i + epoch * len_dataloader) / n_epoch / len_dataloader
alpha = 2. / (1. + np.exp(-10 * p)) - 1
# training model using source data
data_source = data_source_iter.next()
s_img, s_label = data_source
my_net.zero_grad()
batch_size = len(s_label)
if cuda:
s_img = s_img.cuda()
s_label = s_label.cuda()
class_output, _ = my_net(input_data=s_img, alpha=alpha)
err_s_label = loss_class(class_output, s_label)
err = err_s_label
err.backward()
optimizer.step()
sys.stdout.write('\r epoch: %d, [iter: %d / all %d], err_s_label: %f' \
% (epoch, i + 1, len_dataloader, err_s_label.data.cpu().numpy()))
sys.stdout.flush()
torch.save(my_net, '{0}/mnist_mnistm_model_epoch_current.pth'.format(model_root))
print('\n')
accu_s = test(source_dataset_name, model_root)
print('Accuracy of the %s dataset: %f' % ('mnist', accu_s))
accu_t = test(target_dataset_name, model_root)
print('Accuracy of the %s dataset: %f\n' % ('mnist_m', accu_t))
losses['test']['acc_bw'].append(accu_s)
losses['test']['acc_color'].append(accu_t)
if accu_t > best_accu_t:
best_accu_s = accu_s
best_accu_t = accu_t
torch.save(my_net, '{0}/mnist_mnistm_model_epoch_best.pth'.format(model_root))
print('============ Summary ============= \n')
print('Accuracy of the %s dataset: %f' % ('mnist', best_accu_s))
print('Accuracy of the %s dataset: %f' % ('mnist_m', best_accu_t))
print('Corresponding model was save in ' + model_root + '/mnist_mnistm_model_epoch_best.pth')
sd.save_dict(os.path.join(model_root, 'losses.pkl'), losses)
else:
path_losses = os.path.join(model_root, name_losses)
print(f'Losses from previous run found!')
losses = sd.load_dict(path_losses)
sd.plot_curves(losses)
print('============ Summary ============= \n')
print('Accuracy of the %s dataset: %f' % ('mnist', max(losses['test']['acc_bw'])))
print('Accuracy of the %s dataset: %f' % ('mnist_m', max(losses['test']['acc_color'])))
print('Corresponding model was saved into ' + model_root + '/mnist_mnistm_model_epoch_best.pth')
```
| github_jupyter |
## Swow On and Free Scenes
```
from plot_helpers import *
plt.style.use('fivethirtyeight')
casi_data = PixelClassifier(CASI_DATA, CLOUD_MASK, VEGETATION_MASK)
hillshade = RasterFile(HILLSHADE, band_number=1).band_values()
snow_on_diff_data = RasterFile(SNOW_ON_DIFF, band_number=1)
band_values_snow_on_diff = snow_on_diff_data.band_values()
band_values_snow_on_diff_mask = band_values_snow_on_diff.mask.copy()
snow_free_diff_data = RasterFile(SNOW_FREE_DIFF, band_number=1)
band_values_snow_free_diff = snow_free_diff_data.band_values()
band_values_snow_free_diff_mask = band_values_snow_free_diff.mask.copy()
```
## Snow Pixels comparison
```
band_values_snow_free_diff.mask = casi_data.snow_surfaces(band_values_snow_free_diff_mask)
band_values_snow_on_diff.mask = casi_data.snow_surfaces(band_values_snow_on_diff_mask)
ax = box_plot_compare(
[
band_values_snow_free_diff,
band_values_snow_on_diff,
],
[
'SfM Bare Ground\n- Lidar Bare Ground',
'SfM Snow\n- Lidar Snow',
],
)
ax.set_ylabel('$\Delta$ Elevation (m)')
ax.set_ylim([-1, 1]);
color_map = LinearSegmentedColormap.from_list(
'snow_pixels',
['royalblue', 'none'],
N=2
)
plt.figure(figsize=(6,6), dpi=150)
plt.imshow(hillshade, cmap='gray', clim=(1, 255), alpha=0.5)
plt.imshow(
band_values_snow_on_diff.mask,
cmap=color_map,
)
set_axes_style(plt.gca())
plt.xticks([])
plt.yticks([]);
```
## Stable Ground
```
lidar_data = RasterFile(LIDAR_SNOW_DEPTH, band_number=1)
band_values_lidar = lidar_data.band_values()
sfm_data = RasterFile(SFM_SNOW_DEPTH, band_number=1)
band_values_sfm = sfm_data.band_values()
band_values_lidar.mask = casi_data.stable_surfaces(band_values_lidar.mask)
band_values_sfm.mask = casi_data.stable_surfaces(band_values_sfm.mask)
band_values_snow_on_diff.mask = casi_data.stable_surfaces(band_values_snow_on_diff_mask)
band_values_snow_free_diff.mask = casi_data.stable_surfaces(band_values_snow_free_diff_mask)
data_sources = [
band_values_lidar,
band_values_sfm,
band_values_snow_on_diff,
band_values_snow_free_diff,
]
labels=[
'Lidar Snow\n Depth',
'SfM Snow\n Depth',
'Snow On\n Scenes',
'Bare Ground\n Scenes',
]
ax = box_plot_compare(data_sources, labels)
ax.set_ylim([-1.2, 1.2]);
color_map = LinearSegmentedColormap.from_list(
'snow_pixels',
['sienna', 'none'],
N=2
)
plt.figure(figsize=(6,6), dpi=150)
plt.imshow(hillshade, cmap='gray', clim=(1, 255), alpha=0.5)
plt.imshow(
band_values_snow_on_diff.mask,
cmap=color_map,
)
set_axes_style(plt.gca())
plt.xticks([])
plt.yticks([]);
```
| github_jupyter |
## Dependencies
```
!pip install --quiet efficientnet
import warnings, time
from kaggle_datasets import KaggleDatasets
from sklearn.model_selection import KFold
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from tensorflow.keras import optimizers, Sequential, losses, metrics, Model
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import efficientnet.tfkeras as efn
from cassava_scripts import *
from scripts_step_lr_schedulers import *
import tensorflow_addons as tfa
seed = 0
seed_everything(seed)
warnings.filterwarnings('ignore')
```
### Hardware configuration
```
# TPU or GPU detection
# Detect hardware, return appropriate distribution strategy
strategy, tpu = set_up_strategy()
AUTO = tf.data.experimental.AUTOTUNE
REPLICAS = strategy.num_replicas_in_sync
print(f'REPLICAS: {REPLICAS}')
# Mixed precision
from tensorflow.keras.mixed_precision import experimental as mixed_precision
policy = mixed_precision.Policy('mixed_bfloat16')
mixed_precision.set_policy(policy)
# XLA
tf.config.optimizer.set_jit(True)
```
# Model parameters
```
BATCH_SIZE = 64 * REPLICAS #32 * REPLICAS
LEARNING_RATE = 3e-5 * REPLICAS # 1e-5 * REPLICAS
EPOCHS_CL = 5
EPOCHS = 15
HEIGHT = 512
WIDTH = 512
HEIGHT_DT = 512
WIDTH_DT = 512
CHANNELS = 3
N_CLASSES = 5
N_FOLDS = 5
FOLDS_USED = 1
ES_PATIENCE = 5
```
# Load data
```
database_base_path = '/kaggle/input/cassava-leaf-disease-classification/'
train = pd.read_csv(f'{database_base_path}train.csv')
print(f'Train samples: {len(train)}')
GCS_PATH = KaggleDatasets().get_gcs_path(f'cassava-leaf-disease-tfrecords-center-{HEIGHT_DT}x{WIDTH_DT}') # Center croped and resized (50 TFRecord)
GCS_PATH_EXT = KaggleDatasets().get_gcs_path(f'cassava-leaf-disease-tfrecords-external-{HEIGHT_DT}x{WIDTH_DT}') # Center croped and resized (50 TFRecord) (External)
GCS_PATH_CLASSES = KaggleDatasets().get_gcs_path(f'cassava-leaf-disease-tfrecords-classes-{HEIGHT_DT}x{WIDTH_DT}') # Center croped and resized (50 TFRecord) by classes
GCS_PATH_EXT_CLASSES = KaggleDatasets().get_gcs_path(f'cassava-leaf-disease-tfrecords-classes-ext-{HEIGHT_DT}x{WIDTH_DT}') # Center croped and resized (50 TFRecord) (External) by classes
FILENAMES_COMP = tf.io.gfile.glob(GCS_PATH + '/*.tfrec')
# FILENAMES_2019 = tf.io.gfile.glob(GCS_PATH_EXT + '/*.tfrec')
# FILENAMES_COMP_CBB = tf.io.gfile.glob(GCS_PATH_CLASSES + '/CBB*.tfrec')
# FILENAMES_COMP_CBSD = tf.io.gfile.glob(GCS_PATH_CLASSES + '/CBSD*.tfrec')
# FILENAMES_COMP_CGM = tf.io.gfile.glob(GCS_PATH_CLASSES + '/CGM*.tfrec')
# FILENAMES_COMP_CMD = tf.io.gfile.glob(GCS_PATH_CLASSES + '/CMD*.tfrec')
# FILENAMES_COMP_Healthy = tf.io.gfile.glob(GCS_PATH_CLASSES + '/Healthy*.tfrec')
# FILENAMES_2019_CBB = tf.io.gfile.glob(GCS_PATH_EXT_CLASSES + '/CBB*.tfrec')
# FILENAMES_2019_CBSD = tf.io.gfile.glob(GCS_PATH_EXT_CLASSES + '/CBSD*.tfrec')
# FILENAMES_2019_CGM = tf.io.gfile.glob(GCS_PATH_EXT_CLASSES + '/CGM*.tfrec')
# FILENAMES_2019_CMD = tf.io.gfile.glob(GCS_PATH_EXT_CLASSES + '/CMD*.tfrec')
# FILENAMES_2019_Healthy = tf.io.gfile.glob(GCS_PATH_EXT_CLASSES + '/Healthy*.tfrec')
TRAINING_FILENAMES = FILENAMES_COMP
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
print(f'GCS: train images: {NUM_TRAINING_IMAGES}')
display(train.head())
```
# Augmentation
```
def data_augment(image, label):
# p_rotation = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_pixel_1 = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_pixel_2 = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_pixel_3 = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
# p_shear = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_crop = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_cutout = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
# # Shear
# if p_shear > .2:
# if p_shear > .6:
# image = transform_shear(image, HEIGHT, shear=20.)
# else:
# image = transform_shear(image, HEIGHT, shear=-20.)
# # Rotation
# if p_rotation > .2:
# if p_rotation > .6:
# image = transform_rotation(image, HEIGHT, rotation=45.)
# else:
# image = transform_rotation(image, HEIGHT, rotation=-45.)
# Flips
image = tf.image.random_flip_left_right(image)
image = tf.image.random_flip_up_down(image)
if p_spatial > .75:
image = tf.image.transpose(image)
# Rotates
if p_rotate > .75:
image = tf.image.rot90(image, k=3) # rotate 270º
elif p_rotate > .5:
image = tf.image.rot90(image, k=2) # rotate 180º
elif p_rotate > .25:
image = tf.image.rot90(image, k=1) # rotate 90º
# Pixel-level transforms
if p_pixel_1 >= .4:
image = tf.image.random_saturation(image, lower=.7, upper=1.3)
if p_pixel_2 >= .4:
image = tf.image.random_contrast(image, lower=.8, upper=1.2)
if p_pixel_3 >= .4:
image = tf.image.random_brightness(image, max_delta=.1)
# Crops
if p_crop > .6:
if p_crop > .9:
image = tf.image.central_crop(image, central_fraction=.5)
elif p_crop > .8:
image = tf.image.central_crop(image, central_fraction=.6)
elif p_crop > .7:
image = tf.image.central_crop(image, central_fraction=.7)
else:
image = tf.image.central_crop(image, central_fraction=.8)
elif p_crop > .3:
crop_size = tf.random.uniform([], int(HEIGHT*.6), HEIGHT, dtype=tf.int32)
image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])
image = tf.image.resize(image, size=[HEIGHT, WIDTH])
if p_cutout > .5:
image = data_augment_cutout(image)
return image, label
```
## Auxiliary functions
```
# CutOut
def data_augment_cutout(image, min_mask_size=(int(HEIGHT * .1), int(HEIGHT * .1)),
max_mask_size=(int(HEIGHT * .125), int(HEIGHT * .125))):
p_cutout = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
if p_cutout > .85: # 10~15 cut outs
n_cutout = tf.random.uniform([], 10, 15, dtype=tf.int32)
image = random_cutout(image, HEIGHT, WIDTH,
min_mask_size=min_mask_size, max_mask_size=max_mask_size, k=n_cutout)
elif p_cutout > .6: # 5~10 cut outs
n_cutout = tf.random.uniform([], 5, 10, dtype=tf.int32)
image = random_cutout(image, HEIGHT, WIDTH,
min_mask_size=min_mask_size, max_mask_size=max_mask_size, k=n_cutout)
elif p_cutout > .25: # 2~5 cut outs
n_cutout = tf.random.uniform([], 2, 5, dtype=tf.int32)
image = random_cutout(image, HEIGHT, WIDTH,
min_mask_size=min_mask_size, max_mask_size=max_mask_size, k=n_cutout)
else: # 1 cut out
image = random_cutout(image, HEIGHT, WIDTH,
min_mask_size=min_mask_size, max_mask_size=max_mask_size, k=1)
return image
# Datasets utility functions
def random_crop(image, label):
"""
Resize and reshape images to the expected size.
"""
image = tf.image.random_crop(image, size=[HEIGHT, WIDTH, CHANNELS])
return image, label
def prepare_image(image, label):
"""
Resize and reshape images to the expected size.
"""
image = tf.image.resize(image, [HEIGHT, WIDTH])
image = tf.reshape(image, [HEIGHT, WIDTH, CHANNELS])
return image, label
def center_crop_(image, label, height_rs, width_rs, height=HEIGHT_DT, width=WIDTH_DT, channels=3):
image = tf.reshape(image, [height, width, channels]) # Original shape
h, w = image.shape[0], image.shape[1]
if h > w:
image = tf.image.crop_to_bounding_box(image, (h - w) // 2, 0, w, w)
else:
image = tf.image.crop_to_bounding_box(image, 0, (w - h) // 2, h, h)
image = tf.image.resize(image, [height_rs, width_rs]) # Expected shape
return image, label
def read_tfrecord_(example, labeled=True, n_classes=5):
"""
1. Parse data based on the 'TFREC_FORMAT' map.
2. Decode image.
3. If 'labeled' returns (image, label) if not (image, name).
"""
if labeled:
TFREC_FORMAT = {
'image': tf.io.FixedLenFeature([], tf.string),
'target': tf.io.FixedLenFeature([], tf.int64),
}
else:
TFREC_FORMAT = {
'image': tf.io.FixedLenFeature([], tf.string),
'image_name': tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, TFREC_FORMAT)
image = decode_image(example['image'])
if labeled:
label_or_name = tf.cast(example['target'], tf.int32)
# One-Hot Encoding needed to use "categorical_crossentropy" loss
# label_or_name = tf.one_hot(tf.cast(label_or_name, tf.int32), n_classes)
else:
label_or_name = example['image_name']
return image, label_or_name
def get_dataset(filenames, labeled=True, ordered=False, repeated=False,
cached=False, augment=False):
"""
Return a Tensorflow dataset ready for training or inference.
"""
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.Dataset.list_files(filenames)
dataset = dataset.interleave(tf.data.TFRecordDataset, num_parallel_calls=AUTO)
else:
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
dataset = dataset.with_options(ignore_order)
dataset = dataset.map(lambda x: read_tfrecord_(x, labeled=labeled), num_parallel_calls=AUTO)
if augment:
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
dataset = dataset.map(scale_image, num_parallel_calls=AUTO)
dataset = dataset.map(prepare_image, num_parallel_calls=AUTO)
if labeled:
dataset = dataset.map(conf_output, num_parallel_calls=AUTO)
if not ordered:
dataset = dataset.shuffle(2048)
if repeated:
dataset = dataset.repeat()
dataset = dataset.batch(BATCH_SIZE)
if cached:
dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
return dataset
def conf_output(image, label):
"""
Configure the output of the dataset.
"""
aux_label = [0.]
aux_2_label = [0.]
# if tf.math.argmax(label, axis=-1) == 4: # Healthy
if label == 4: # Healthy
aux_label = [1.]
# if tf.math.argmax(label, axis=-1) == 3: # CMD
if label == 3: # CMD
aux_2_label = [1.]
return (image, (label, aux_label, aux_2_label))
```
# Training data samples (with augmentation)
```
# train_dataset = get_dataset(FILENAMES_COMP, ordered=True, augment=True)
# train_iter = iter(train_dataset.unbatch().batch(20))
# display_batch_of_images(next(train_iter))
# display_batch_of_images(next(train_iter))
```
# Model
```
def encoder_fn(input_shape):
inputs = L.Input(shape=input_shape, name='input_image')
base_model = efn.EfficientNetB5(input_tensor=inputs,
include_top=False,
weights='noisy-student',
pooling=None)
outputs = L.GlobalAveragePooling2D()(base_model.output)
model = Model(inputs=inputs, outputs=outputs)
return model
def add_projection_head(input_shape, encoder):
inputs = L.Input(shape=input_shape, name='input_image')
features = encoder(inputs)
outputs = L.Dense(128, activation='relu', name='projection_head', dtype='float32')(features)
model = Model(inputs=inputs, outputs=outputs)
return model
def classifier_fn(input_shape, N_CLASSES, encoder, trainable=True):
for layer in encoder.layers:
layer.trainable = trainable
inputs = L.Input(shape=input_shape, name='input_image')
features = encoder(inputs)
features = L.Dropout(.5)(features)
features = L.Dense(1000, activation='relu')(features)
features = L.Dropout(.5)(features)
output = L.Dense(N_CLASSES, activation='softmax', name='output', dtype='float32')(features)
output_healthy = L.Dense(1, activation='sigmoid', name='output_healthy', dtype='float32')(features)
output_cmd = L.Dense(1, activation='sigmoid', name='output_cmd', dtype='float32')(features)
model = Model(inputs=inputs, outputs=[output, output_healthy, output_cmd])
return model
temperature = 0.1
class SupervisedContrastiveLoss(losses.Loss):
def __init__(self, temperature=0.1, name=None):
super(SupervisedContrastiveLoss, self).__init__(name=name)
self.temperature = temperature
def __call__(self, labels, feature_vectors, sample_weight=None):
# Normalize feature vectors
feature_vectors_normalized = tf.math.l2_normalize(feature_vectors, axis=1)
# Compute logits
logits = tf.divide(
tf.matmul(
feature_vectors_normalized, tf.transpose(feature_vectors_normalized)
),
temperature,
)
return tfa.losses.npairs_loss(tf.squeeze(labels), logits)
```
### Learning rate schedule
```
lr_start = 1e-8
lr_min = 1e-6
lr_max = LEARNING_RATE
num_cycles = 1
warmup_epochs = 3
hold_max_epochs = 0
total_epochs = EPOCHS
step_size = (NUM_TRAINING_IMAGES//BATCH_SIZE)
hold_max_steps = hold_max_epochs * step_size
total_steps = total_epochs * step_size
warmup_steps = warmup_epochs * step_size
def lrfn(total_steps, warmup_steps=0, lr_start=1e-4, lr_max=1e-3, lr_min=1e-4, num_cycles=1.):
@tf.function
def cosine_with_hard_restarts_schedule_with_warmup_(step):
""" Create a schedule with a learning rate that decreases following the
values of the cosine function with several hard restarts, after a warmup
period during which it increases linearly between 0 and 1.
"""
if step < warmup_steps:
lr = (lr_max - lr_start) / warmup_steps * step + lr_start
else:
progress = (step - warmup_steps) / (total_steps - warmup_steps)
lr = lr_max * (0.5 * (1.0 + tf.math.cos(np.pi * ((num_cycles * progress) % 1.0))))
if lr_min is not None:
lr = tf.math.maximum(lr_min, float(lr))
return lr
return cosine_with_hard_restarts_schedule_with_warmup_
lrfn_fn = lrfn(total_steps, warmup_steps, lr_start, lr_max, lr_min, num_cycles)
rng = [i for i in range(total_steps)]
y = [lrfn_fn(tf.cast(x, tf.float32)) for x in rng]
sns.set(style='whitegrid')
fig, ax = plt.subplots(figsize=(20, 6))
plt.plot(rng, y)
print(f'{total_steps} total steps and {step_size} steps per epoch')
print(f'Learning rate schedule: {y[0]:.3g} to {max(y):.3g} to {y[-1]:.3g}')
```
# Training
```
skf = KFold(n_splits=N_FOLDS, shuffle=True, random_state=seed)
oof_pred = []; oof_labels = []; oof_names = []; oof_folds = []; history_list = []; oof_embed = []
for fold,(idxT, idxV) in enumerate(skf.split(np.arange(15))):
if fold >= FOLDS_USED:
break
if tpu: tf.tpu.experimental.initialize_tpu_system(tpu)
K.clear_session()
print(f'\nFOLD: {fold+1}')
print(f'TRAIN: {idxT} VALID: {idxV}')
# Create train and validation sets
TRAIN_FILENAMES = tf.io.gfile.glob([GCS_PATH + '/Id_train%.2i*.tfrec' % x for x in idxT])
# FILENAMES_COMP_CBB = tf.io.gfile.glob([GCS_PATH_CLASSES + '/CBB%.2i*.tfrec' % x for x in idxT])
# FILENAMES_COMP_CBSD = tf.io.gfile.glob([GCS_PATH_CLASSES + '/CBSD%.2i*.tfrec' % x for x in idxT])
# FILENAMES_COMP_CGM = tf.io.gfile.glob([GCS_PATH_CLASSES + '/CGM%.2i*.tfrec' % x for x in idxT])
# FILENAMES_COMP_Healthy = tf.io.gfile.glob([GCS_PATH_CLASSES + '/Healthy%.2i*.tfrec' % x for x in idxT])
np.random.shuffle(TRAIN_FILENAMES)
VALID_FILENAMES = tf.io.gfile.glob([GCS_PATH + '/Id_train%.2i*.tfrec' % x for x in idxV])
ct_train = count_data_items(TRAIN_FILENAMES)
ct_valid = count_data_items(VALID_FILENAMES)
step_size = (ct_train // BATCH_SIZE)
warmup_steps = (warmup_epochs * step_size)
total_steps = (total_epochs * step_size)
total_steps_cl = (EPOCHS_CL * step_size)
warmup_steps_cl = 1
### Pre-train the encoder
print('Pre-training the encoder using "Supervised Contrastive" Loss')
with strategy.scope():
encoder = encoder_fn((None, None, CHANNELS))
encoder_proj = add_projection_head((None, None, CHANNELS), encoder)
encoder_proj.summary()
lrfn_fn = lrfn(total_steps, warmup_steps, lr_start, lr_max, lr_min, num_cycles)
# optimizer = optimizers.SGD(learning_rate=lambda: lrfn_fn(tf.cast(optimizer.iterations, tf.float32)),
# momentum=0.95, nesterov=True)
optimizer = optimizers.Adam(learning_rate=lambda: lrfn_fn(tf.cast(optimizer.iterations, tf.float32)))
encoder_proj.compile(optimizer=optimizer,
loss=SupervisedContrastiveLoss(temperature))
es = EarlyStopping(patience=ES_PATIENCE, restore_best_weights=True,
monitor='val_loss', mode='max', verbose=1)
history_enc = encoder_proj.fit(x=get_dataset(TRAIN_FILENAMES, repeated=True, augment=True),
validation_data=get_dataset(VALID_FILENAMES, ordered=True),
steps_per_epoch=step_size,
# callbacks=[es],
batch_size=BATCH_SIZE,
epochs=EPOCHS,
verbose=2).history
### Train the classifier with the frozen encoder
print('Training the classifier with the frozen encoder')
with strategy.scope():
model = classifier_fn((None, None, CHANNELS), N_CLASSES, encoder, trainable=False)
model.summary()
lrfn_fn = lrfn(total_steps_cl, warmup_steps_cl, lr_start, lr_max, lr_min, num_cycles)
# optimizer = optimizers.SGD(learning_rate=lambda: lrfn_fn(tf.cast(optimizer.iterations, tf.float32)),
# momentum=0.95, nesterov=True)
optimizer = optimizers.Adam(learning_rate=lambda: lrfn_fn(tf.cast(optimizer.iterations, tf.float32)))
model.compile(optimizer=optimizer,
loss={'output': losses.SparseCategoricalCrossentropy(),
'output_healthy': losses.BinaryCrossentropy(),
'output_cmd': losses.BinaryCrossentropy()},
loss_weights={'output': 1.,
'output_healthy': .1,
'output_cmd': .1},
metrics={'output': metrics.SparseCategoricalAccuracy(),
'output_healthy': metrics.BinaryAccuracy(),
'output_cmd': metrics.BinaryAccuracy()})
model_path = f'model_{fold}.h5'
chkpt = ModelCheckpoint(model_path, mode='max',
monitor='val_output_sparse_categorical_accuracy',
save_best_only=True, save_weights_only=True)
history = model.fit(x=get_dataset(TRAIN_FILENAMES, repeated=True, augment=True),
validation_data=get_dataset(VALID_FILENAMES, ordered=True),
steps_per_epoch=step_size,
callbacks=[chkpt],
epochs=EPOCHS_CL,
verbose=2).history
### RESULTS
print(f"#### FOLD {fold+1} OOF Accuracy = {np.max(history['val_output_sparse_categorical_accuracy']):.3f}")
history_list.append(history)
# Load best model weights
model.load_weights(model_path)
# OOF predictions
ds_valid = get_dataset(VALID_FILENAMES, ordered=True)
oof_folds.append(np.full((ct_valid), fold, dtype='int8'))
oof_labels.append([target[0].numpy() for img, target in iter(ds_valid.unbatch())])
x_oof = ds_valid.map(lambda image, target: image)
oof_pred.append(np.argmax(model.predict(x_oof)[0], axis=-1))
# OOF names
ds_valid_names = get_dataset(VALID_FILENAMES, labeled=False, ordered=True)
oof_names.append(np.array([img_name.numpy().decode('utf-8') for img, img_name in iter(ds_valid_names.unbatch())]))
oof_embed.append(encoder.predict(x_oof)) # OOF embeddings
```
## Model loss graph
```
for fold, history in enumerate(history_list):
print(f'\nFOLD: {fold+1}')
plot_metrics(history, acc_name='output_sparse_categorical_accuracy')
```
# Model evaluation
```
y_true = np.concatenate(oof_labels)
y_pred = np.concatenate(oof_pred)
folds = np.concatenate(oof_folds)
names = np.concatenate(oof_names)
acc = accuracy_score(y_true, y_pred)
print(f'Overall OOF Accuracy = {acc:.3f}')
df_oof = pd.DataFrame({'image_id':names, 'fold':fold,
'target':y_true, 'pred':y_pred})
df_oof.to_csv('oof.csv', index=False)
display(df_oof.head())
print(classification_report(y_true, y_pred, target_names=CLASSES))
```
# Confusion matrix
```
fig, ax = plt.subplots(1, 1, figsize=(20, 12))
cfn_matrix = confusion_matrix(y_true, y_pred, labels=range(len(CLASSES)))
cfn_matrix = (cfn_matrix.T / cfn_matrix.sum(axis=1)).T
df_cm = pd.DataFrame(cfn_matrix, index=CLASSES, columns=CLASSES)
ax = sns.heatmap(df_cm, cmap='Blues', annot=True, fmt='.2f', linewidths=.5).set_title('Train', fontsize=30)
plt.show()
```
# Visualize embeddings outputs
```
y_true = np.concatenate(oof_labels)
y_pred = np.concatenate(oof_pred)
y_embeddings = np.concatenate(oof_embed)
visualize_embeddings(y_embeddings, y_true)
```
# Visualize predictions
```
# train_dataset = get_dataset(TRAINING_FILENAMES, ordered=True)
# x_samp, y_samp = dataset_to_numpy_util(train_dataset, 18)
# y_samp = np.argmax(y_samp, axis=-1)
# x_samp_1, y_samp_1 = x_samp[:9,:,:,:], y_samp[:9]
# samp_preds_1 = model.predict(x_samp_1, batch_size=9)
# display_9_images_with_predictions(x_samp_1, samp_preds_1, y_samp_1)
# x_samp_2, y_samp_2 = x_samp[9:,:,:,:], y_samp[9:]
# samp_preds_2 = model.predict(x_samp_2, batch_size=9)
# display_9_images_with_predictions(x_samp_2, samp_preds_2, y_samp_2)
```
| github_jupyter |
```
# Ricordati di eseguire questa cella con Shift+Invio
import sys
sys.path.append('../')
import jupman
```
# Stringhe 4 - iterazione e funzioni
## [Scarica zip esercizi](../_static/generated/strings.zip)
[Naviga file online](https://github.com/DavidLeoni/softpython-it/tree/master/strings)
### Che fare
- scompatta lo zip in una cartella, dovresti ottenere qualcosa del genere:
```
strings
strings1.ipynb
strings1-sol.ipynb
strings2.ipynb
strings2-sol.ipynb
strings3.ipynb
strings3-sol.ipynb
jupman.py
```
<div class="alert alert-warning">
**ATTENZIONE**: Per essere visualizzato correttamente, il file del notebook DEVE essere nella cartella szippata.
</div>
- apri il Jupyter Notebook da quella cartella. Due cose dovrebbero aprirsi, prima una console e poi un browser. Il browser dovrebbe mostrare una lista di file: naviga la lista e apri il notebook `strings1.ipynb`
- Prosegui leggendo il file degli esercizi, ogni tanto al suo interno troverai delle scritte **ESERCIZIO**, che ti chiederanno di scrivere dei comandi Python nelle celle successive. Gli esercizi sono graduati per difficoltà, da una stellina ✪ a quattro ✪✪✪✪
Scorciatoie da tastiera:
* Per eseguire il codice Python dentro una cella di Jupyter, premi `Control+Invio`
* Per eseguire il codice Python dentro una cella di Jupyter E selezionare la cella seguente, premi `Shift+Invio`
* Per eseguire il codice Python dentro una cella di Jupyter E creare una nuova cella subito dopo, premi `Alt+Invio`
* Se per caso il Notebook sembra inchiodato, prova a selezionare `Kernel -> Restart`
## Esercizi con le funzioni
<div class="alert alert-warning">
**ATTENZIONE: Gli esercizi seguenti richiedono di conoscere:**
<ul>
<li>Tutti gli esercizi sulle stringhe precedenti</li>
<li>[Controllo di flusso](https://it.softpython.org/#control-flow)</li>
<li>[Funzioni](https://it.softpython.org/functions/functions-sol.html)</li>
</ul>
<br/>
**Se sei alle prime armi con la programmazione, ti conviene saltarli e ripassare in seguito**
</div>
### lung
✪ a. Scrivi una funzione `lung1(stringa)` in cui data una stringa, RITORNI quanto è lunga la stringa. Usa `len` Per esempio, con la stringa `"ciao"`, la vostra funzione dovrebbe ritornare `4` mentre con `"hi"` dovrebbe ritornare `2`
```python
>>> x = lung1("ciao")
>>> x
4
```
✪ b. Scrivi una funzione `lung2` che come prima calcola la lunghezza della stringa, ma SENZA usare `len` (usa un ciclo `for`)
```python
>>> y = lung2("mondo")
>>> y
5
```
```
# scrivi qui
# versione con len, più veloce perchè python assieme ad una stringa mantiene sempre in memoria
# il numero della lunghezza immediatamente disponibile
def lung1(stringa):
return len(stringa)
# versione con contatore, più lenta
def lung2(parola):
contatore = 0
for lettera in parola:
contatore = contatore + 1
return contatore
```
### contin
✪ Scrivi la funzione `contin(parola, stringa)`, che RITORNA `True` se `parola` contiene la `stringa` indicata, altrimenti RITORNA `False`
- Usa l'operatore `in`
```python
>>> x = contin('carpenteria', 'ent')
>>> x
True
>>> y = contin('carpenteria', 'zent')
>>> y
False
```
```
# scrivi qui
def contin(parola, stringa):
return stringa in parola
```
### invertilet
✪ Scrivi la funzione `invertilet(primo, secondo)` che prende in input due stringhe di lunghezza maggiore di 3, e RESTITUISCE una nuova stringa in cui le parole sono concatenate e separate da uno spazio, le ultime lettere delle due parole sono invertite. Questo significa che passando in input 'ciao' e 'world', la funzione dovrebbe restituire 'ciad worlo'
Se le stringhe non sono di lunghezza adeguata, il programma STAMPA _errore!_
SUGGERIMENTO: usa _le slice_
```python
>>> x = invertilet('hi','mondo')
'errore!'
>>> x
None
>>> x = invertilet('cirippo', 'bla')
'errore!'
>>> x
None
```
```
# scrivi qui
def invertilet(primo,secondo):
if len(primo) <= 3 or len(secondo) <=3:
print("errore!")
else:
return primo[:-1] + secondo[-1] + " " + secondo[:-1] + primo[-1]
```
### nspazio
✪ Scrivi la funzione `nspazio` che data una stringa in input, RITORNA una nuova stringa in
cui l’n-esimo carattere è uno spazio. Per esempio, data la stringa 'largamente' e il carattere all'indice 5, il programma deve RITORNARE `'larga ente'`. Nota: se il numero
dovesse essere troppo grande (i.e., la parola ha 6 caratteri e chiedo di rimuovere
il numero 9), il programma STAMPA _errore!_
```python
>>> x = nspazio('largamente', 5)
>>> x
'larga ente'
>>> x = nspazio('ciao', 9)
errore!
>>> x
None
>>> x = nspazio('ciao', 4)
errore!
>>> x
None
```
```
# scrivi qui
def nspazio(parola, indice):
if indice >= len(parola):
print("errore!")
return parola[:indice]+' '+parola[indice+1:]
#nspazio("largamente", 5)
```
### inifin
✪ Scrivi un programma in Python prende una stringa, e se la stringa ha una lunghezza maggiore di 4, il programma STAMPA le prime e le ultime due lettere. Altrimenti, nel caso in cui la lunghezza della stringa sia minore di 4, STAMPA `voglio almeno 4 caratteri`. Per esempio, passando alla funzione `"ciaomondo"`, la funzione dovrebbe stampare `"cido"`. Passando `"ciao"` dovrebbe stampare `ciao` e passando `"hi"` dovrebbe stampare `voglio almeno 4 caratteri`
```python
>>> inifin('ciaomondo')
cido
>>> inifin('hi')
Voglio almeno 4 caratteri
```
```
# scrivi qui
def inifin(stringa):
if len(stringa) >= 4:
print(stringa[:2] + stringa[-2:])
else:
print("Voglio almeno 4 caratteri")
```
### scambia
Scrivere una funzione che data una stringa, inverte il primo e l’ultimo carattere, e STAMPA il risultato.
Quindi, data la stringa “mondo”, il programma stamperà “oondm”
```python
>>> scambia('mondo')
oondm
```
```
# scrivi qui
def scambia(stringa):
print(stringa[-1] + stringa[1:-1] + stringa[0])
```
## Esercizi con eccezioni e test
<div class="alert alert-warning">
**ATTENZIONE: Gli esercizi seguenti richiedono di conoscere:**
<ul>
<li>[Controllo di flusso](https://it.softpython.org/#control-flow)</li>
<li>[Funzioni](https://it.softpython.org/functions/functions-sol.html)</li>
<li>**e anche**: [Eccezioni e test con assert](https://it.softpython.org/errors-and-testing/errors-and-testing-sol.html)
</ul>
<br/>
<strong>Se sei alle prime armi con la programmazione, ti conviene saltarli e ripassare in seguito</strong>
</div>
### halet
✪ RITORNA `True` se parola contiene lettera, `False` altrimenti
- usare ciclo `while`
```
def halet(parola, lettera):
#jupman-raise
indice = 0 # inizializziamo indice
while indice < len(parola):
if parola[indice] == lettera:
return True # abbiamo trovato il carattere, possiamo interrompere la ricerca
indice += 1 # è come scrivere indice = indice + 1
# se arriviamo DOPO il while, c'è una sola ragione:
# non abbiamo trovato nulla, quindi dobbiamo ritornare False
return False
#/jupman-raise
# INIZIO TEST - NON TOCCARE !
# se hai scritto tutto il codice giusto, ed esegui la cella, python non dovrebbe lanciare AssertionError
assert halet("ciao", 'a')
assert not halet("ciao", 'A')
assert halet("ciao", 'c')
assert not halet("", 'a')
assert not halet("ciao", 'z')
# FINE TEST
```
### conta
✪ RITORNA il numero di occorrenze di lettera in parola
NOTA: NON VOGLIO UNA STAMPA, VOGLIO CHE *RITORNI* IL VALORE!
- Usare ciclo for in
```
def conta(parola, lettera):
#jupman-raise
occorrenze = 0
for carattere in parola:
# print("carattere corrente = ", carattere) # le print di debug sono ammesse
if carattere == lettera:
# print("trovata occorrenza !") # le print di debug sono ammesse
occorrenze += 1
return occorrenze # L'IMPORTANTE E' _RITORANRE_ IL VALORE COME DA TESTO DELL'ESERCIZIO !!!!!
#/jupman-raise
# INIZIO TEST - NON TOCCARE !
# se hai scritto tutto il codice giusto, ed esegui la cella, python non dovrebbe lanciare AssertionError
assert conta("ciao", "z") == 0
assert conta("ciao", "c") == 1
assert conta("babbo", "b") == 3
assert conta("", "b") == 0
assert conta("ciao", "C") == 0
# FINE TEST
```
### contiene_minuscola
✪ Esercizio ripreso dall' Esercizio 4 del libro Pensare in Python Capitolo Stringhe
leggere in fondo qua: https://davidleoni.github.io/ThinkPythonItalian/html/thinkpython2009.html
- RITORNA True se la parola contiene almeno una lettera minuscola
- RITORNA False altrimenti
- Usare ciclo `while`
```
def contiene_minuscola(s):
#jupman-raise
i = 0
while i < len(s):
if s[i] == s[i].lower():
return True
i += 1
return False
#/jupman-raise
# INIZIO TEST - NON TOCCARE !
# se hai scritto tutto il codice giusto, ed esegui la cella, python non dovrebbe lanciare AssertionError
assert contiene_minuscola("David")
assert contiene_minuscola("daviD")
assert not contiene_minuscola("DAVID")
assert not contiene_minuscola("")
assert contiene_minuscola("a")
assert not contiene_minuscola("A")
```
### dialetto
✪✪ Esiste un dialetto in cui tutte le “a” devono per forza essere precedute da una “g”. Nel caso una parola dovesse contenere “a” _non_ preceduta da una “g”, possiamo dire con certezza che questa parola non fa parte di quel dialetto. Scrivere una funzione che data una parola, RITORNI `True` se la parola rispetta le regole del dialetto, `False` altrimenti.
```python
>>> dialetto("ammot")
False
>>> print(dialetto("paganog")
False
>>> print(dialetto("pgaganog")
True
>>> print(dialetto("ciao")
False
>>> dialetto("cigao")
True
>>> dialetto("zogava")
False
>>> dialetto("zogavga")
True
```
```
def dialetto(parola):
#jupman-raise
n = 0
for i in range(0,len(parola)):
if parola[i] == "a":
if i == 0 or parola[i - 1] != "g":
return False
return True
#/jupman-raise
# INIZIO TEST - NON TOCCARE !
# se hai scritto tutto il codice giusto, ed esegui la cella, python non dovrebbe lanciare AssertionError
assert dialetto("a") == False
assert dialetto("ab") == False
assert dialetto("ag") == False
assert dialetto("ag") == False
assert dialetto("ga") == True
assert dialetto("gga") == True
assert dialetto("gag") == True
assert dialetto("gaa") == False
assert dialetto("gaga") == True
assert dialetto("gabga") == True
assert dialetto("gabgac") == True
assert dialetto("gabbgac") == True
assert dialetto("gabbgagag") == True
# FINE TEST
```
### contavoc
✪✪ Data una stringa, scrivere una funzione che conti il numero di vocali.
Se il numero di vocali è pari RITORNA il numero di vocali, altrimenti solleva l'eccezione `ValueError`
```python
>>> conta_vocali("asso")
2
>>> conta_vocali("ciao")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-058310342431> in <module>()
16 contavoc("arco")
---> 19 contavoc("ciao")
ValueError: Vocali dispari !
```
```
def contavoc(parola):
#jupman-raise
n_vocali = 0
vocali = ["a","e","i","o","u"]
for lettera in parola:
if lettera.lower() in vocali:
n_vocali = n_vocali + 1
if n_vocali % 2 == 0:
return n_vocali
else:
raise ValueError("Vocali dispari !")
#/jupman-raise
# INIZIO TEST - NON TOCCARE !
# se hai scritto tutto il codice giusto, ed esegui la cella, python non dovrebbe lanciare AssertionError
assert contavoc("arco") == 2
assert contavoc("scaturire") == 4
try:
contavoc("ciao") # con questa stringa ci attendiamo che sollevi l'eccezione ValueError
raise Exception("Non dovrei arrivare fin qui !")
except ValueError: # se solleva l'eccezione ValueError,si sta comportando come previsto e non facciamo niente
pass
try:
contavoc("aiuola") # con questa stringa ci attendiamo che sollevi l'eccezione ValueError
raise Exception("Non dovrei arrivare fin qui !")
except ValueError: # se solleva l'eccezione ValueError,si sta comportando come previsto e non facciamo niente
pass
```
### palindroma
✪✪✪ Una parola è palindroma quando è esattamente la stessa se letta al contrario
Scrivi una funzione che RITORNA `True` se una parola è palindroma, `False` altrimenti
* assumi che la stringa vuota sia palindroma
Esempio:
```python
>>> x = palindroma('radar')
>>> x
True
>>> x = palindroma('scatola')
>>> x
False
```
```
def palindroma(parola):
#jupman-raise
for i in range(len(parola) // 2):
if parola[i] != parola[len(parola)- i - 1]:
return False
return True # nota che è FUORI dal for: superati tutti i controlli,
# possiamo concludere che la parola è palindroma
#/jupman-raise
# INIZIO TEST - NON TOCCARE !
# se hai scritto tutto il codice giusto, ed esegui la cella, python non dovrebbe lanciare AssertionError
assert palindroma('') == True # assumiamo che la stringa vuota sia palindroma
assert palindroma('a') == True
assert palindroma('aa') == True
assert palindroma('ab') == False
assert palindroma('aba') == True
assert palindroma('bab') == True
assert palindroma('bba') == False
assert palindroma('abb') == False
assert palindroma('abba') == True
assert palindroma('baab') == True
assert palindroma('abbb') == False
assert palindroma('bbba') == False
assert palindroma('radar') == True
assert palindroma('scatola') == False
# FINE TEST
```
## Prosegui
Continua con le [challenges](https://it.softpython.org/strings/strings5-chal.html)
| github_jupyter |
## Indexing in NumPy
### np.where vs masking
* np.where returns just the indices where the equivalent mask is true
* this is useful if you need the actual indices (maybe for counts)
* otherwise the shorthand notation (masking) is perhaps easier
* np.where returns a tuple
### Why do I care?
You may need to work directly in NumPy due to the size of your data. NumPy has a number of tricks that can speed up your code. Even if you already knew the **trick** shown here you may like to see some code that can help you compare the speeds of different methods... This is important aspect of performance tuning or more specifically code optimization.
```
import numpy as np
%matplotlib inline
x = np.arange(5)
print(np.where(x < 3))
print(x < 3)
```
### Chaining logic statements
```
x = np.arange(10)
y1 = np.intersect1d(np.where(x > 3),np.where(x<7))
y2 = np.where((x > 3) & (x < 7))
y3 = np.where(np.logical_and(x > 3, x < 7))
y4 = x[(x > 3) & (x < 7)]
print(y1,y2,y3,y4)
```
### Random helpful things in NumPy
```
a = np.array(['a','b','c','c'])
#a = np.sort(np.unique(a))
b = np.array(['c','d','e','c','f'])
mask1a = np.in1d(a,b)
mask1b = [np.where(b==i)[0].tolist() for i in a]
mask2a = np.in1d(b,a)
mask2b = [np.where(a==i)[0].tolist() for i in b]
print("1")
print(mask1a)
print(mask1b)
print("2")
print(mask2a)
print(mask2b)
```
### How does one array compare to another?
This example is also the real reason to read this notebook.
```python
a = np.array(['a','b','c'])
b = np.array(['c','d','e','c','f'])
```
* Where do we find elements of a in b?
* Where do we find elements of b in a?
* If you can use np.in1d
[np.in1d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html) is fast. But alway make sure you understand **when** it can be used before using it.
* if we have a query(a) and a search(b) list it can be helpful if you sort and make unique the query list
* it also helps to only look for things you can find
You might be suprised how often this comes up.
* matrix of hospital visits give me only data on subjects from $a$
* matrix of test scores use only subjects where name is in list $a$
```
## Get rid of nans
x = np.array([[1., 2., np.nan, 3., np.nan, np.nan]])
x[~np.isnan(x)]
## carry around indices
labels = np.array(['x' + str(i)for i in range(10)])
x = np.random.randint(1,14,10)
sortedInds = np.argsort(x)
print("sorted labels: %s"%labels[sortedInds])
## make x have exactly 5 evenly spaced points in the range 11 to 23
np.linspace(11,23,5)
## numpy has very efficient set operations
print(np.intersect1d(np.array([1,2,3]),np.arange(10)))
import matplotlib.pyplot as plt
import time
sizes = [100,1000,5000,10000]
times1,times2,times3 = [],[],[]
for n1 in sizes:
n2 = n1 * 100
a = np.random.randint(0,200,n1)
b = np.random.randint(0,100,n2)
b_list = b.tolist()
## attempt 1
time_start = time.time()
a = np.sort(np.unique(a))
a = a[np.in1d(a,b)]
times1.append(time.time()-time_start)
## attempt 2
time_start = time.time()
inds2 = [np.where(b==i)[0] for i in a]
inds2 = [item for sublist in inds2 for item in sublist]
inds2 = np.sort(np.array(inds2))
times2.append(time.time()-time_start)
## attempt 3
time_start = time.time()
inds3 = np.array([i for i,x in enumerate(b_list) if x in a])
inds3.sort()
times3.append(time.time()-time_start)
times1,times2,times3 = [np.array(t) for t in [times1,times2,times3]]
fig = plt.figure(figsize=(6,4),dpi=400)
ax = fig.add_subplot(111)
index = np.arange(len(sizes))
bar_width = 0.25
opacity = 0.4
rects1 = plt.bar(index, times1, bar_width,
alpha=opacity,
color='b',
label='np.in1d')
rects1 = plt.bar(index + bar_width, times2, bar_width,
alpha=opacity,
color='k',
label='np.where')
rects2 = plt.bar(index + (bar_width * 2.0), times3, bar_width,
alpha=opacity,
color='c',
label='list-only')
plt.xlabel('len(query_vector) by method')
plt.ylabel('Compute time (s)')
plt.title('Comparing two vectors')
plt.xticks(index + bar_width + (bar_width/2.0), [str(s) for s in sizes] )
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
```
| github_jupyter |
## Bayesian Optimisation Verification
```
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.colors import LogNorm
from scipy.interpolate import interp1d
from scipy import interpolate
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteKernel
from scipy import stats
from scipy.stats import norm
from sklearn.metrics.pairwise import euclidean_distances
from scipy.spatial.distance import cdist
from scipy.optimize import fsolve
import math
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
```
## Trial on TiOx/SiOx
Tempeature vs. S10_HF
```
#import normal data sheet at 85 C (time:0~5000s)
address = 'data/degradation.xlsx'
x_normal = []
y_normal = []
df = pd.read_excel(address,sheet_name = 'normal data',usecols = [0],names = None,nrows = 5000)
df_85 = df.values.tolist()
df = pd.read_excel(address,sheet_name = 'normal data',usecols = [3],names = None,nrows = 5000)
df_85L = df.values.tolist()
#import smooth data sheet at 85 C (time:0~5000s)
address = 'data/degradation.xlsx'
df = pd.read_excel(address,sheet_name = 'smooth data',usecols = [0],names = None,nrows = 5000)
df_85s = df.values.tolist()
df = pd.read_excel(address,sheet_name = 'smooth data',usecols = [3],names = None,nrows = 5000)
df_85Ls = df.values.tolist()
#import normal data sheet at 120 C (time:0~5000s)
address = 'data/degradation.xlsx'
x_normal = []
y_normal = []
df = pd.read_excel(address,sheet_name = 'normal data',usecols = [0],names = None,nrows = 5000)
df_120 = df.values.tolist()
df = pd.read_excel(address,sheet_name = 'normal data',usecols = [3],names = None,nrows = 5000)
df_120L = df.values.tolist()
#import smooth data sheet at 120 C (time:0~5000s)
address = 'data/degradation.xlsx'
df = pd.read_excel(address,sheet_name = 'smooth data',usecols = [0],names = None,nrows = 5000)
df_120s = df.values.tolist()
df = pd.read_excel(address,sheet_name = 'smooth data',usecols = [3],names = None,nrows = 5000)
df_120Ls = df.values.tolist()
# randomly select 7 points from normal data
x_normal = np.array(df_120).T
y_normal = np.array(df_li_L).T
x_normal = x_normal.reshape((5000))
y_normal = y_normal.reshape((5000))
def plot (X,X_,y_mean,y,y_cov,gp,kernel):
#plot function
plt.figure()
plt.plot(X_, y_mean, 'k', lw=3, zorder=9)
plt.fill_between(X_, y_mean - np.sqrt(np.diag(y_cov)),y_mean + np.sqrt(np.diag(y_cov)),alpha=0.5, color='k')
plt.scatter(X[:, 0], y, c='r', s=50, zorder=10, edgecolors=(0, 0, 0))
plt.tick_params(axis='y', colors = 'white')
plt.tick_params(axis='x', colors = 'white')
plt.ylabel('Lifetime',color = 'white')
plt.xlabel('Time',color = 'white')
plt.tight_layout()
# Preparing training set
# For log scaled plot
x_loop = np.array([1,10,32,100,316,1000,3162])
X = x_normal[x_loop].reshape(x_loop.size)
y = y_normal[x_loop]
X = X.reshape(x_loop.size,1)
X = np.log10(X)
MAX_x_value = np.log10(5000)
X_ = np.linspace(0,MAX_x_value, 5000)
# Kernel setting
length_scale_bounds_MAX = 0.5
length_scale_bounds_MIN = 1e-4
for length_scale_bounds_MAX in (0.3,0.5,0.7):
kernel = 1.0 * RBF(length_scale=20,length_scale_bounds=(length_scale_bounds_MIN, length_scale_bounds_MAX)) + WhiteKernel(noise_level=0.00000001)
gp = GaussianProcessRegressor(kernel=kernel,alpha=0.0).fit(X, y)
y_mean, y_cov = gp.predict(X_[:, np.newaxis], return_cov=True)
plot (X,X_,y_mean,y,y_cov,gp,kernel)
# Find the minimum value in the bound
# 5000 * 5000
# Find minimum value in the last row as the minimum value for the bound
def ucb(X , gp, dim, delta):
"""
Calculates the GP-UCB acquisition function values
Inputs: gp: The Gaussian process, also contains all data
x:The point at which to evaluate the acquisition function
Output: acq_value: The value of the aquisition function at point x
"""
mean, var = gp.predict(X[:, np.newaxis], return_cov=True)
#var.flags['WRITEABLE']=True
#var[var<1e-10]=0
mean = np.atleast_2d(mean).T
var = np.atleast_2d(var).T
beta = 2*np.log(np.power(5000,2.1)*np.square(math.pi)/(3*delta))
return mean - np.sqrt(beta)* np.sqrt(np.diag(var))
acp_value = ucb(X_, gp, 0.1, 5)
X_min = np.argmin(acp_value[-1])
print(acp_value[-1,X_min])
print(np.argmin(acp_value[-1]))
print(min(acp_value[-1]))
# Preparing training set
x_loop = np.array([1,10,32,100,316,1000,3162])
X = x_normal[x_loop].reshape(x_loop.size)
y = y_normal[x_loop]
X = X.reshape(x_loop.size,1)
X = np.log10(X)
MAX_x_value = np.log10(5000)
X_ = np.linspace(0,MAX_x_value, 5000)
# Kernel setting
length_scale_bounds_MAX = 0.4
length_scale_bounds_MIN = 1e-4
kernel = 1.0 * RBF(length_scale=20,length_scale_bounds=(length_scale_bounds_MIN, length_scale_bounds_MAX)) + WhiteKernel(noise_level=0.0001)
gp = GaussianProcessRegressor(kernel=kernel,alpha=0.0).fit(X, y)
y_mean, y_cov = gp.predict(X_[:, np.newaxis], return_cov=True)
acp_value = ucb(X_, gp, 0.1, 5)
ucb_y_min = acp_value[-1]
print (min(ucb_y_min))
X_min = np.argmin(acp_value[-1])
print(acp_value[-1,X_min])
print(np.argmin(acp_value[-1]))
print(min(acp_value[-1]))
plt.figure()
plt.plot(X_, y_mean, 'k', lw=3, zorder=9)
plt.plot(X_, ucb_y_min, 'x', lw=3, zorder=9)
# plt.fill_between(X_, y_mean, ucb_y_min,alpha=0.5, color='k')
plt.scatter(X[:, 0], y, c='r', s=50, zorder=10, edgecolors=(0, 0, 0))
plt.tick_params(axis='y', colors = 'white')
plt.tick_params(axis='x', colors = 'white')
plt.ylabel('Lifetime',color = 'white')
plt.xlabel('Time',color = 'white')
plt.tight_layout()
acp_value = ucb(X_, gp, 0.1, 5)
X_min = np.argmin(acp_value[-1])
print(acp_value[-1,X_min])
print(np.argmin(acp_value[-1]))
print(min(acp_value[-1]))
# Iterate i times with mins value point of each ucb bound
# Initiate with 7 data points, apply log transformation to them
x_loop = np.array([1,10,32,100,316,1000,3162])
X = x_normal[x_loop].reshape(x_loop.size)
Y = y_normal[x_loop]
X = X.reshape(x_loop.size,1)
X = np.log10(X)
MAX_x_value = np.log10(5000)
X_ = np.linspace(0,MAX_x_value, 5000)
# Kernel setting
length_scale_bounds_MAX = 0.5
length_scale_bounds_MIN = 1e-4
kernel = 1.0 * RBF(length_scale=20,length_scale_bounds=(length_scale_bounds_MIN, length_scale_bounds_MAX)) + WhiteKernel(noise_level=0.0001)
gp = GaussianProcessRegressor(kernel=kernel,alpha=0.0).fit(X, Y)
y_mean, y_cov = gp.predict(X_[:, np.newaxis], return_cov=True)
acp_value = ucb(X_, gp, 0.1, 5)
ucb_y_min = acp_value[-1]
plt.figure()
plt.plot(X_, y_mean, 'k', lw=3, zorder=9)
plt.fill_between(X_, y_mean, ucb_y_min,alpha=0.5, color='k')
plt.scatter(X[:, 0], Y, c='r', s=50, zorder=10, edgecolors=(0, 0, 0))
plt.tick_params(axis='y', colors = 'white')
plt.tick_params(axis='x', colors = 'white')
plt.ylabel('Lifetime',color = 'white')
plt.xlabel('Time',color = 'white')
plt.tight_layout()
# Change i to set extra data points
i=0
while i < 5 :
acp_value = ucb(X_, gp, 0.1, 5)
ucb_y_min = acp_value[-1]
index = np.argmin(acp_value[-1])
print(acp_value[-1,X_min])
print(min(acp_value[-1]))
# Protection to stop equal x value
while index in x_loop:
index = index - 50
x_loop = np.append(x_loop, index)
x_loop = np.sort(x_loop)
print (x_loop)
X = x_normal[x_loop].reshape(x_loop.size)
Y = y_normal[x_loop]
X = X.reshape(x_loop.size,1)
X = np.log10(X)
gp = GaussianProcessRegressor(kernel=kernel,alpha=0.0).fit(X, Y)
plt.plot(X_, y_mean, 'k', lw=3, zorder=9)
plt.fill_between(X_, y_mean, ucb_y_min,alpha=0.5, color='k')
plt.scatter(X[:, 0], Y, c='r', s=50, zorder=10, edgecolors=(0, 0, 0))
plt.tick_params(axis='y', colors = 'white')
plt.tick_params(axis='x', colors = 'white')
plt.ylabel('Lifetime',color = 'white')
plt.xlabel('Time',color = 'white')
plt.title('cycle %d'%(i), color = 'white')
plt.tight_layout()
plt.show()
i+=1
print('X:', X, '\nY:', Y)
s = interpolate.InterpolatedUnivariateSpline(x_loop,Y)
x_uni = np.arange(0,5000,1)
y_uni = s(x_uni)
# Plot figure
plt.plot(df_120s,df_120Ls,'-',color = 'gray')
plt.plot(x_uni,y_uni,'-',color = 'red')
plt.plot(x_loop, Y,'x',color = 'black')
plt.tick_params(axis='y', colors = 'white')
plt.tick_params(axis='x', colors = 'white')
plt.ylabel('Lifetime',color = 'white')
plt.xlabel('Time',color = 'white')
plt.title('cycle %d'%(i+1), color = 'white')
plt.show()
```
| github_jupyter |
# MODIS
MODIS Terra: https://lpdaac.usgs.gov/products/mod11c1v006/
MODIS Acqua: https://lpdaac.usgs.gov/products/myd11c1v061/
Docs: https://lpdaac.usgs.gov/documents/118/MOD11_User_Guide_V6.pdf
```
! wget https://e4ftl01.cr.usgs.gov/MOLA/MYD11C1.061/2018.04.19/MYD11C1.A2018109.061.2021330052306.hdf -O /network/group/aopp/predict/TIP016_PAXTON_RPSPEEDY/ML4L/MODIS.hdf
import xarray as xr
import rioxarray as rxr
modis_xarray= rxr.open_rasterio('/network/group/aopp/predict/TIP016_PAXTON_RPSPEEDY/ML4L/MODIS.hdf',masked=True)
modis_xarray['Day_view_time']
modis_df = modis_xarray.to_dataframe().reset_index()
lite = modis_df[['y','x', 'LST_Day_CMG','Day_view_time', 'LST_Night_CMG', 'Night_view_time']]
L = lite.dropna().copy()
L['T_Day'] = L['LST_Day_CMG']*0.02
L['T_Night'] = L['LST_Night_CMG']*0.02
L['Time_Day'] = L['Day_view_time']*0.2
L['Time_Night'] = L['Night_view_time']*0.2
L['Time_Day_UTC'] = L['Time_Day'] - L['x']/15
window = L.query('-70 < y < 70')
w = window.copy()
import pandas as pd
#Create time delta to change local to UTC
#time_delta = pd.to_timedelta(window.x/15,unit='H')
#Convert local satellite time to UTC and round to nearest hour
# time = (pd.to_datetime([file_date + " " + local_times[satellite]]*time_delta.shape[0]) - time_delta).round('H')
w['ideal_UTC'] = (pd.to_datetime("2022-01-01 13:30") - pd.to_timedelta(w.x/15))#.dt.time
w['actual_utc'] = (pd.to_datetime("2022-01-01 00:00") + pd.to_timedelta(w.Time_Day_UTC,unit='hours'))#.dt.time
#w['dfdf'] = w.ideal_UTC.dt.time
#w['actual_utc'] = (pd.to_datetime("00:00") + pd.to_timedelta(w.Time_Day_UTC,unit='hours')).dt.time #.dt.components['hours']
w['difference'] = pd.to_timedelta(w.ideal_UTC - w.actual_utc,unit='s').dt.total_seconds() / 60
w
import matplotlib.pyplot as plt
import matplotlib.colors as mc
import matplotlib.colorbar as cb
#Get all data as vectors
x = w.x.values
y = w.y.values
z1 = w.difference.values
cmap = plt.cm.coolwarm
#Scatter plot it
# init the figure
fig,[ax,cax] = plt.subplots(1,2, gridspec_kw={"width_ratios":[50,1]},figsize=(30, 20))
vmin = -1500
vmax= +1500
norm = mc.Normalize(vmin=vmin, vmax=vmax)
cb1 = cb.ColorbarBase(cax, cmap=cmap,norm=norm,orientation='vertical')
sc = ax.scatter(x, y,s=1,c=cmap(norm(z1)),linewidths=1, alpha=1)
#ax.set_title(z)
plt.show()
modis_xarray.LST_Day_CMG.data.dropna()
t = modis_xarray.Day_view_time.data
tt = t.flatten()
sum(tt)
import numpy as np
tnn = t[~np.isnan(t)]*0.2
len(tnn)
min(tnn)
max(tnn)
np.unique(tnn)
[[[-19.0715515614,-1.4393790966],
[53.2624328136,-1.4393790966],
[53.2624328136,36.0044133726],
[-19.0715515614,36.0044133726],
[-19.0715515614,-1.4393790966]]]
-19 56
-1.4 36
```
| github_jupyter |
# ODE solver
In this notebook, we show some examples of solving an ODE model. For the purposes of this example, we use the Scipy solver, but the syntax remains the same for other solvers
```
%pip install pybamm -q # install PyBaMM if it is not installed
import pybamm
import tests
import numpy as np
import os
import matplotlib.pyplot as plt
from pprint import pprint
os.chdir(pybamm.__path__[0]+'/..')
# Create solver
ode_solver = pybamm.ScipySolver()
```
## Integrating ODEs
In PyBaMM, a model is solved by calling a solver with `solve`. This sets up the model to be solved, and then calls the method `_integrate`, which is specific to each solver. We begin by setting up and discretising a model
```
# Create model
model = pybamm.BaseModel()
u = pybamm.Variable("u")
v = pybamm.Variable("v")
model.rhs = {u: -v, v: u}
model.initial_conditions = {u: 2, v: 1}
model.variables = {"u": u, "v": v}
# Discretise using default discretisation
disc = pybamm.Discretisation()
disc.process_model(model);
```
Now the model can be solved by calling `solver.solve` with a specific time vector at which to evaluate the solution
```
# Solve ########################
t_eval = np.linspace(0, 5, 30)
solution = ode_solver.solve(model, t_eval)
################################
# Extract u and v
t_sol = solution.t
u = solution["u"]
v = solution["v"]
# Plot
t_fine = np.linspace(0,t_eval[-1],1000)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13,4))
ax1.plot(t_fine, 2 * np.cos(t_fine) - np.sin(t_fine), t_sol, u(t_sol), "o")
ax1.set_xlabel("t")
ax1.legend(["2*cos(t) - sin(t)", "u"], loc="best")
ax2.plot(t_fine, 2 * np.sin(t_fine) + np.cos(t_fine), t_sol, v(t_sol), "o")
ax2.set_xlabel("t")
ax2.legend(["2*sin(t) + cos(t)", "v"], loc="best")
plt.tight_layout()
plt.show()
```
Note that, where possible, the solver makes use of the mass matrix and jacobian for the model. However, the discretisation or solver will have created the mass matrix and jacobian algorithmically, using the expression tree, so we do not need to calculate and input these manually.
The solution terminates at the final simulation time:
```
solution.termination
```
### Events
It is possible to specify events at which a solution should terminate. This is done by adding events to the `model.events` dictionary. In the following example, we solve the same model as before but add a termination event when `v=-2`.
```
# Create model
model = pybamm.BaseModel()
u = pybamm.Variable("u")
v = pybamm.Variable("v")
model.rhs = {u: -v, v: u}
model.initial_conditions = {u: 2, v: 1}
model.events.append(pybamm.Event('v=-2', v + 2)) # New termination event
model.variables = {"u": u, "v": v}
# Discretise using default discretisation
disc = pybamm.Discretisation()
disc.process_model(model)
# Solve ########################
t_eval = np.linspace(0, 5, 30)
solution = ode_solver.solve(model, t_eval)
################################
# Extract u and v
t_sol = solution.t
u = solution["u"]
v = solution["v"]
# Plot
t_fine = np.linspace(0,t_eval[-1],1000)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13,4))
ax1.plot(t_fine, 2 * np.cos(t_fine) - np.sin(t_fine), t_sol, u(t_sol), "o")
ax1.set_xlabel("t")
ax1.legend(["2*cos(t) - sin(t)", "u"], loc="best")
ax2.plot(t_fine, 2 * np.sin(t_fine) + np.cos(t_fine), t_sol, v(t_sol), "o", t_fine, -2 * np.ones_like(t_fine), "k")
ax2.set_xlabel("t")
ax2.legend(["2*sin(t) + cos(t)", "v", "v = -2"], loc="best")
plt.tight_layout()
plt.show()
```
Now the solution terminates because the event has been reached
```
solution.termination
print("event time: ", solution.t_event, "\nevent state", solution.y_event.flatten())
```
## References
The relevant papers for this notebook are:
```
pybamm.print_citations()
```
| github_jupyter |
## 初始化
```
import sys,os
root_path = os.path.abspath('../../../../')
sys.path.append(root_path)
root_path
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import src.features.factors.consolidate_factor as cf
import src.visualization.plotting as pt
```
## 整理数据
```
fp = root_path + "/xxx.parquet" # 需要用到的其它类型的数据
mf = pd.read_parquet(fp)
md_fp = root_path + "/data/example/IF/md.parquet" # 需要用到的行情数据
md = pd.read_parquet(md_fp)
df = pd.concat([mf, md], axis=1).dropna(axis=0) # 将数据源进行整合
df['return'] = df['close'].diff() # 基准收益
```
## 生成因子
## 设置因子的类型、名称、参数值
```
factor_type = 'tmom'
factor_signature = 'xxx'
param_signatures = [560, 720, 960, 1200, 1800]
raw_factor_name = f"factor_{factor_type}_{factor_signature}"
raw_factor_name
def factor_tmom_xxx(df: pd.DataFrame, w) -> pd.Series:
"""
最好在这里规范描述因子逻辑,以便后期整理
"""
df['factor'] = df['return'].rolling(w).mean() / df['return'].rolling(w).max() # 生成因子
return df['factor']
```
## 开启一个循环,用以检验因子在不同参数下的表现
```
# set signal shift
sig_shift = 1
compare_df, compare_df_2 = pd.DataFrame(), pd.DataFrame()
for i in param_signatures:
factor = factor_tmom_xxx(df, i)
signal = np.sign(factor)
ret_cumsum_df = pd.DataFrame((df['return'] * signal.shift(sig_shift)).cumsum(), columns=[i])
ret_df = pd.DataFrame((df['return'] * signal.shift(sig_shift)), columns=[i])
compare_df = pd.concat([compare_df, ret_cumsum_df], axis=1)
compare_df_2 = pd.concat([compare_df_2, ret_df], axis=1)
compare_df['benchmark'] = base_return.cumsum()
compare_df['close'] = df['close']
compare_df_2['benchmark'] = base_return
compare_df.plot(figsize=(16,9), secondary_y='close')
compare_df.drop(columns=['close'], inplace=True)
vol_on_return = pd.DataFrame((compare_df - compare_df.mean()).std(), columns=['volitility'])
final_return = pd.DataFrame(compare_df.iloc[-1])
final_return.columns = ['return']
sample_df = pd.concat([vol_on_return, final_return], axis=1)
sample_df.plot(kind='bar', secondary_y='volitility', figsize=(16,9))
compare_df.describe()
compare_df_2.describe()
```
## 选取你认为表现比较好的因子,将因子函数固化
```
param_signature = 1200
factor_name = f"factor_{factor_type}_{factor_signature}_{param_signature}"
factor_name
```
#### 现在,你的因子函数应该有固定的参数,而非传入参数。
```
def factor_tmom_xxx_1200(df: pd.DataFrame):
"""
衡量北向资金净买入量在1200期内的投票结果
"""
df['factor'] = df['return'].rolling(w).mean() / df['return'].rolling(w).max() # 生成因子
return df['factor']
factor = factor_tmom_xxx_1200(df)
```
## 再次对固化的因子进行回测检验
```
# set signal shift
sig_shift = 1
```
## 确认因子转换为信号的逻辑
```
signal = np.sign(factor)
```
## 确认回测结果
```
(df['return'] * signal.shift(sig_shift)).cumsum().describe()
(df['return'] * signal.shift(sig_shift)).cumsum().plot(figsize=(16,9))
data = pd.DataFrame([factor.shift(sig_shift), base_return]).T
data.columns = ['factor', 'return']
fig = plt.figure(figsize=(16,9))
sns.scatterplot(data=data, x='factor', y='return')
data = pd.DataFrame([signal.shift(sig_shift), base_return]).T
data.columns = ['signal', 'return']
fig = plt.figure(figsize=(16,9))
sns.scatterplot(data=data, x='signal', y='return')
```
-----------------
# <font color=red>CAUTION! </font>
#### <font color=red>YOU ARE ABOUT TO CONSOLIDATE A FACTOR FUNCTION AND ITS DATA. </font>
#### <font color=red>ENTER FOLLOWING STEPS WITH CAUTION!</font>
-------------------------
## consolidate factor
```
cf.record_source(factor_tmom_xxx_1200)
```
## set instrument name:
```
instrument = 'IF'
```
## save factor to parquet
```
factor_df = pd.DataFrame(factor)
factor_df.columns=['factor']
factor_df
factor_fp = root_path + f"/factor/{instrument}/"
# os.mkdir(factor_fp)
cf.save_factor(factor_df, factor_fp, factor_name)
```
## save signal to parquet
```
signal_df = pd.DataFrame(signal)
signal_df.columns=['signal']
signal_df
signal_fp = root_path + f"/signal/{instrument}"
# os.mkdir(signal_fp)
cf.save_signal(signal_df, signal_fp, factor_name)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/muhdlaziem/DR/blob/master/Testing_3_all.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
from google.colab import drive
drive.mount('/gdrive')
%cd /gdrive/'My Drive'/
%tensorflow_version 1.x
# import libraries
import json
import math
from tqdm import tqdm, tqdm_notebook
import gc
import warnings
import os
import cv2
from PIL import Image
import pandas as pd
import scipy
import matplotlib.pyplot as plt
from keras import backend as K
from keras import layers
from keras.applications.densenet import DenseNet121
from keras.callbacks import Callback, ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from sklearn.metrics import cohen_kappa_score, accuracy_score
import numpy as np
warnings.filterwarnings("ignore")
%matplotlib inline
# Image size
im_size = 320
import pandas as pd
# %cd diabetic-retinopathy-resized/
DR = pd.read_csv('/gdrive/My Drive/diabetic-retinopathy-resized/MadamAmeliaSample/label_for_out_MYRRC_data2_256x256.csv')
DR.head()
def preprocess_image(image_path, desired_size=224):
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#img = crop_image_from_gray(img)
img = cv2.resize(img, (desired_size,desired_size))
img = cv2.addWeighted(img,4,cv2.GaussianBlur(img, (0,0), desired_size/40) ,-4 ,128)
return img
# testing set
%cd /gdrive/My Drive/diabetic-retinopathy-resized/MadamAmeliaSample/image
N = DR.shape[0]
x_test = np.empty((N, im_size, im_size, 3), dtype=np.uint8)
for i, image_id in enumerate(tqdm_notebook(DR['file'])):
x_test[i, :, :, :] = preprocess_image(
f'{image_id}',
desired_size = im_size
)
y_test = pd.get_dummies(DR['class']).values
print(y_test.shape)
print(x_test.shape)
y_test_multi = np.empty(y_test.shape, dtype=y_test.dtype)
y_test_multi[:, 2] = y_test[:, 2]
for i in range(1, -1, -1):
y_test_multi[:, i] = np.logical_or(y_test[:, i], y_test_multi[:, i+1])
print("Y_test multi: {}".format(y_test_multi.shape))
# from keras.models import load_model
import tensorflow as tf
model = tf.keras.models.load_model('/gdrive/My Drive/diabetic-retinopathy-resized/resized_train_cropped/denseNet_3_all.h5')
model.summary()
y_val_pred = model.predict(x_test)
def compute_score_inv(threshold):
y1 = y_val_pred > threshold
y1 = y1.astype(int).sum(axis=1) - 1
y2 = y_test_multi.sum(axis=1) - 1
score = cohen_kappa_score(y1, y2, weights='quadratic')
return 1 - score
simplex = scipy.optimize.minimize(
compute_score_inv, 0.5, method='nelder-mead'
)
best_threshold = simplex['x'][0]
y1 = y_val_pred > best_threshold
y1 = y1.astype(int).sum(axis=1) - 1
# y1 = np.where(y1==2,1,y1)
# y1 = np.where(y1==3,2,y1)
# y1 = np.where(y1==4,2,y1)
y2 = y_test_multi.sum(axis=1) - 1
score = cohen_kappa_score(y1, y2, weights='quadratic')
print('Threshold: {}'.format(best_threshold))
print('Validation QWK score with best_threshold: {}'.format(score))
y1 = y_val_pred > .5
y1 = y1.astype(int).sum(axis=1) - 1
# y1 = np.where(y1==2,1,y1)
# y1 = np.where(y1==3,2,y1)
# y1 = np.where(y1==4,2,y1)
score = cohen_kappa_score(y1, y2, weights='quadratic')
print('Validation QWK score with .5 threshold: {}'.format(score))
from sklearn.metrics import classification_report, confusion_matrix
y_best = y_val_pred > best_threshold
y_best = y_best.astype(int).sum(axis=1) - 1
# y_best = np.where(y_best==2,1,y_best)
# y_best = np.where(y_best==3,2,y_best)
# y_best = np.where(y_best==4,2,y_best)
print('Confusion Matrix')
print(confusion_matrix(y_best, y2))
print('Classification Report')
target_names = ['No DR', 'Moderate', 'Severe']
print(classification_report(y_best, y2, target_names=target_names))
print(y_best)
print(y2)
DR['predicted'] = y_best
DR.to_excel("/gdrive/My Drive/diabetic-retinopathy-resized/MadamAmeliaSample/result_3_all.xlsx")
```
| github_jupyter |
[View in Colaboratory](https://colab.research.google.com/github/DillipKS/MLCC_assignments/blob/master/feature_sets.ipynb)
#### Copyright 2017 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.
```
# Feature Sets
**Learning Objective:** Create a minimal set of features that performs just as well as a more complex feature set
So far, we've thrown all of our features into the model. Models with fewer features use fewer resources and are easier to maintain. Let's see if we can build a model on a minimal set of housing features that will perform equally as well as one that uses all the features in the data set.
## Setup
As before, let's load and prepare the California housing data.
```
from __future__ import print_function
import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.logging.set_verbosity(tf.logging.ERROR)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format
california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",")
california_housing_dataframe = california_housing_dataframe.reindex(
np.random.permutation(california_housing_dataframe.index))
def preprocess_features(california_housing_dataframe):
"""Prepares input features from California housing data set.
Args:
california_housing_dataframe: A Pandas DataFrame expected to contain data
from the California housing data set.
Returns:
A DataFrame that contains the features to be used for the model, including
synthetic features.
"""
selected_features = california_housing_dataframe[
["latitude",
"longitude",
"housing_median_age",
"total_rooms",
"total_bedrooms",
"population",
"households",
"median_income"]]
processed_features = selected_features.copy()
# Create a synthetic feature.
processed_features["rooms_per_person"] = (
california_housing_dataframe["total_rooms"] /
california_housing_dataframe["population"])
return processed_features
def preprocess_targets(california_housing_dataframe):
"""Prepares target features (i.e., labels) from California housing data set.
Args:
california_housing_dataframe: A Pandas DataFrame expected to contain data
from the California housing data set.
Returns:
A DataFrame that contains the target feature.
"""
output_targets = pd.DataFrame()
# Scale the target to be in units of thousands of dollars.
output_targets["median_house_value"] = (
california_housing_dataframe["median_house_value"] / 1000.0)
return output_targets
# Choose the first 12000 (out of 17000) examples for training.
training_examples = preprocess_features(california_housing_dataframe.head(12000))
training_targets = preprocess_targets(california_housing_dataframe.head(12000))
# Choose the last 5000 (out of 17000) examples for validation.
validation_examples = preprocess_features(california_housing_dataframe.tail(5000))
validation_targets = preprocess_targets(california_housing_dataframe.tail(5000))
# Double-check that we've done the right thing.
print("Training examples summary:")
display.display(training_examples.describe())
print("Validation examples summary:")
display.display(validation_examples.describe())
print("Training targets summary:")
display.display(training_targets.describe())
print("Validation targets summary:")
display.display(validation_targets.describe())
```
## Task 1: Develop a Good Feature Set
**What's the best performance you can get with just 2 or 3 features?**
A **correlation matrix** shows pairwise correlations, both for each feature compared to the target and for each feature compared to other features.
Here, correlation is defined as the [Pearson correlation coefficient](https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient). You don't have to understand the mathematical details for this exercise.
Correlation values have the following meanings:
* `-1.0`: perfect negative correlation
* `0.0`: no correlation
* `1.0`: perfect positive correlation
```
correlation_dataframe = training_examples.copy()
correlation_dataframe["target"] = training_targets["median_house_value"]
correlation_dataframe.corr()
```
Features that have strong positive or negative correlations with the target will add information to our model. We can use the correlation matrix to find such strongly correlated features.
We'd also like to have features that aren't so strongly correlated with each other, so that they add independent information.
Use this information to try removing features. You can also try developing additional synthetic features, such as ratios of two raw features.
For convenience, we've included the training code from the previous exercise.
```
def construct_feature_columns(input_features):
"""Construct the TensorFlow Feature Columns.
Args:
input_features: The names of the numerical input features to use.
Returns:
A set of feature columns
"""
return set([tf.feature_column.numeric_column(my_feature)
for my_feature in input_features])
def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):
"""Trains a linear regression model.
Args:
features: pandas DataFrame of features
targets: pandas DataFrame of targets
batch_size: Size of batches to be passed to the model
shuffle: True or False. Whether to shuffle the data.
num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely
Returns:
Tuple of (features, labels) for next data batch
"""
# Convert pandas data into a dict of np arrays.
features = {key:np.array(value) for key,value in dict(features).items()}
# Construct a dataset, and configure batching/repeating.
ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit
ds = ds.batch(batch_size).repeat(num_epochs)
# Shuffle the data, if specified.
if shuffle:
ds = ds.shuffle(10000)
# Return the next batch of data.
features, labels = ds.make_one_shot_iterator().get_next()
return features, labels
def train_model(
learning_rate,
steps,
batch_size,
training_examples,
training_targets,
validation_examples,
validation_targets):
"""Trains a linear regression model.
In addition to training, this function also prints training progress information,
as well as a plot of the training and validation loss over time.
Args:
learning_rate: A `float`, the learning rate.
steps: A non-zero `int`, the total number of training steps. A training step
consists of a forward and backward pass using a single batch.
batch_size: A non-zero `int`, the batch size.
training_examples: A `DataFrame` containing one or more columns from
`california_housing_dataframe` to use as input features for training.
training_targets: A `DataFrame` containing exactly one column from
`california_housing_dataframe` to use as target for training.
validation_examples: A `DataFrame` containing one or more columns from
`california_housing_dataframe` to use as input features for validation.
validation_targets: A `DataFrame` containing exactly one column from
`california_housing_dataframe` to use as target for validation.
Returns:
A `LinearRegressor` object trained on the training data.
"""
periods = 10
steps_per_period = steps / periods
# Create a linear regressor object.
my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)
linear_regressor = tf.estimator.LinearRegressor(
feature_columns=construct_feature_columns(training_examples),
optimizer=my_optimizer
)
# Create input functions.
training_input_fn = lambda: my_input_fn(training_examples,
training_targets["median_house_value"],
batch_size=batch_size)
predict_training_input_fn = lambda: my_input_fn(training_examples,
training_targets["median_house_value"],
num_epochs=1,
shuffle=False)
predict_validation_input_fn = lambda: my_input_fn(validation_examples,
validation_targets["median_house_value"],
num_epochs=1,
shuffle=False)
# Train the model, but do so inside a loop so that we can periodically assess
# loss metrics.
print("Training model...")
print("RMSE (on training data):")
training_rmse = []
validation_rmse = []
for period in range (0, periods):
# Train the model, starting from the prior state.
linear_regressor.train(
input_fn=training_input_fn,
steps=steps_per_period,
)
# Take a break and compute predictions.
training_predictions = linear_regressor.predict(input_fn=predict_training_input_fn)
training_predictions = np.array([item['predictions'][0] for item in training_predictions])
validation_predictions = linear_regressor.predict(input_fn=predict_validation_input_fn)
validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])
# Compute training and validation loss.
training_root_mean_squared_error = math.sqrt(
metrics.mean_squared_error(training_predictions, training_targets))
validation_root_mean_squared_error = math.sqrt(
metrics.mean_squared_error(validation_predictions, validation_targets))
# Occasionally print the current loss.
print(" period %02d : %0.2f" % (period, training_root_mean_squared_error))
# Add the loss metrics from this period to our list.
training_rmse.append(training_root_mean_squared_error)
validation_rmse.append(validation_root_mean_squared_error)
print("Model training finished.")
# Output a graph of loss metrics over periods.
plt.ylabel("RMSE")
plt.xlabel("Periods")
plt.title("Root Mean Squared Error vs. Periods")
plt.tight_layout()
plt.plot(training_rmse, label="training")
plt.plot(validation_rmse, label="validation")
plt.legend()
return linear_regressor
```
Spend 5 minutes searching for a good set of features and training parameters. Then check the solution to see what we chose. Don't forget that different features may require different learning parameters.
```
#
# Your code here: add your features of choice as a list of quoted strings.
#
minimal_features = ["median_income", "rooms_per_person"]
assert minimal_features, "You must select at least one feature!"
minimal_training_examples = training_examples[minimal_features]
minimal_validation_examples = validation_examples[minimal_features]
#
# Don't forget to adjust these parameters.
#
train_model(
learning_rate=0.03,
steps=500,
batch_size=10,
training_examples=minimal_training_examples,
training_targets=training_targets,
validation_examples=minimal_validation_examples,
validation_targets=validation_targets)
```
### Solution
Click below for a solution.
```
minimal_features = [
"median_income",
"latitude",
]
minimal_training_examples = training_examples[minimal_features]
minimal_validation_examples = validation_examples[minimal_features]
_ = train_model(
learning_rate=0.01,
steps=500,
batch_size=5,
training_examples=minimal_training_examples,
training_targets=training_targets,
validation_examples=minimal_validation_examples,
validation_targets=validation_targets)
```
## Task 2: Make Better Use of Latitude
Plotting `latitude` vs. `median_house_value` shows that there really isn't a linear relationship there.
Instead, there are a couple of peaks, which roughly correspond to Los Angeles and San Francisco.
```
plt.scatter(training_examples["latitude"], training_targets["median_house_value"])
```
**Try creating some synthetic features that do a better job with latitude.**
For example, you could have a feature that maps `latitude` to a value of `|latitude - 38|`, and call this `distance_from_san_francisco`.
Or you could break the space into 10 different buckets. `latitude_32_to_33`, `latitude_33_to_34`, etc., each showing a value of `1.0` if `latitude` is within that bucket range and a value of `0.0` otherwise.
Use the correlation matrix to help guide development, and then add them to your model if you find something that looks good.
What's the best validation performance you can get?
```
# YOUR CODE HERE: Train on a new data set that includes synthetic features based on latitude.
train_lat_bins = [0,0,0,0,0,0,0,0,0,0] #bins for a unit latitude range
for lat in training_examples["latitude"]:
if int(lat)==32: train_lat_bins[0]+=1
elif int(lat)==33: train_lat_bins[1]+=1
elif int(lat)==34: train_lat_bins[2]+=1
elif int(lat)==35: train_lat_bins[3]+=1
elif int(lat)==36: train_lat_bins[4]+=1
elif int(lat)==37: train_lat_bins[5]+=1
elif int(lat)==38: train_lat_bins[6]+=1
elif int(lat)==39: train_lat_bins[7]+=1
elif int(lat)==40: train_lat_bins[8]+=1
elif int(lat)==41: train_lat_bins[9]+=1
train_lat_bins
val_lat_bins = [0,0,0,0,0,0,0,0,0,0] #bins for a unit latitude range
for lat in validation_examples["latitude"]:
if int(lat)==32: val_lat_bins[0]+=1
elif int(lat)==33: val_lat_bins[1]+=1
elif int(lat)==34: val_lat_bins[2]+=1
elif int(lat)==35: val_lat_bins[3]+=1
elif int(lat)==36: val_lat_bins[4]+=1
elif int(lat)==37: val_lat_bins[5]+=1
elif int(lat)==38: val_lat_bins[6]+=1
elif int(lat)==39: val_lat_bins[7]+=1
elif int(lat)==40: val_lat_bins[8]+=1
elif int(lat)==41: val_lat_bins[9]+=1
val_lat_bins
```
### Solution
Click below for a solution.
Aside from `latitude`, we'll also keep `median_income`, to compare with the previous results.
We decided to bucketize the latitude. This is fairly straightforward in Pandas using `Series.apply`.
```
LATITUDE_RANGES = zip(range(32, 44), range(33, 45))
def select_and_transform_features(source_df):
selected_examples = pd.DataFrame()
selected_examples["median_income"] = source_df["median_income"]
for r in LATITUDE_RANGES:
selected_examples["latitude_%d_to_%d" % r] = source_df["latitude"].apply(
lambda l: 1.0 if l >= r[0] and l < r[1] else 0.0)
return selected_examples
selected_training_examples = select_and_transform_features(training_examples)
selected_validation_examples = select_and_transform_features(validation_examples)
selected_training_examples.head()
_ = train_model(
learning_rate=0.03,
steps=500,
batch_size=10,
training_examples=selected_training_examples,
training_targets=training_targets,
validation_examples=selected_validation_examples,
validation_targets=validation_targets)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/desaibhargav/VR/blob/main/notebooks/Semantic_Search.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
## **Dependencies**
```
!pip install -U -q sentence-transformers
!git clone https://github.com/desaibhargav/VR.git
```
## **Imports**
```
import pandas as pd
import numpy as np
import torch
import time
from typing import Generator
from sentence_transformers import SentenceTransformer, CrossEncoder, util
from VR.backend.chunker import Chunker
```
## **Dataset**
```
# load scrapped data (using youtube_client.py)
dataset = pd.read_pickle('VR/datasets/youtube_scrapped.pickle')
# split transcripts of videos to smaller blocks or chunks (using chunker.py)
chunked = Chunker(chunk_by='length', expected_threshold=100, min_tolerable_threshold=75).get_chunks(dataset)
# finally, create dataset
dataset_untagged = dataset.join(chunked).drop(columns=['subtitles', 'timestamps'])
df = dataset_untagged.copy().dropna()
print(f"Average length of block: {df.length_of_block.mean()}, Standard Deviation: {df.length_of_block.std()}")
```
## **Semantic Search**
---
The idea is to compute embeddings of the query (entered by user) and use cosine similarity to find the `top_k` most similar blocks.
Blocks are nothing but the entire video transcript (big string) split into fixed length strings (small strings, ~100 words).
---
The reason for such a design choice was threefold, handled by `chunker.py` (refer the repo):
1. First and foremost, some videoes can be very long (over ~40 minutes) which means the transcript for the same is a **massive** string, and we need to avoid hitting the processing length limits of pre-trained models.
2. Secondly, and more importantly, it is always good to maintain the inputs at a length on which the models being used were trained (to stay as close as poossible to the training set for optimum results).
3. But perhaps, most importantly, the purpose for splitting transcripts to blocks is so that the recommendations can be targeted to a snippet within a video. The vision is to recommend many snippets from various videoes highly relevant to the query, rather than entire videoes themselves in which matching snippets have been found (which may sometimes be long and the content may not always be related to the query).
---
```
# request to enable GPU
if not torch.cuda.is_available():
print("Warning: No GPU found. Please add GPU to your notebook")
# load model (to encode the dataset)
bi_encoder = SentenceTransformer('paraphrase-distilroberta-base-v1')
# number of blocks we want to retrieve with the bi-encoder
top_k = 200
# the bi-encoder will retrieve 50 blocks (top_k).
# we use a cross-encoder, to re-rank the results list to improve the quality.
cross_encoder = CrossEncoder('cross-encoder/ms-marco-electra-base')
# encode dataset
corpus_embeddings = bi_encoder.encode(df.block.to_list(), convert_to_tensor=True, show_progress_bar=True)
# send corpus embeddings to GPU
corpus_embeddings = torch.tensor(corpus_embeddings).cuda()
# this function will search the dataset for passages that answer the query
def search(query):
start_time = time.time()
# encode the query using the bi-encoder and find potentially relevant passages
question_embedding = bi_encoder.encode(query, convert_to_tensor=True)
# send query embeddings to GPU
question_embedding = question_embedding.cuda()
# perform sematic search by computing cosine similarity between corpus and query embeddings
# return top_k highest similarity matches
hits = util.semantic_search(question_embedding, corpus_embeddings, top_k=top_k)[0]
# now, score all retrieved passages with the cross_encoder
cross_inp = [[query, df.block.to_list()[hit['corpus_id']]] for hit in hits]
cross_scores = cross_encoder.predict(cross_inp)
# sort results by the cross-encoder scores
for idx in range(len(cross_scores)):
hits[idx]['cross-score'] = cross_scores[idx]
hits = sorted(hits, key=lambda x: x['cross-score'], reverse=True)
end_time = time.time()
# print output of top-5 hits (for iteractive environments only)
print(f"Input query: {query}")
print(f"Results (after {round(end_time - start_time, 2)} seconds):")
for hit in hits[0:10]:
print("\t{:.3f}\t{}".format(hit['cross-score'], df.block.to_list()[hit['corpus_id']].replace("\n", " ")))
```
## **Try some queries!**
```
query = "I feel lost in life. I feel like there is no purpose of living. How should I deal with this?"
search(query)
query = "I just recently became a parent and I am feeling very nervous. What is the best way to bring up a child?"
search(query)
query = "I had a divorce. I feel like a failure. How should I handle this heartbreak?"
search(query)
query = "How to be confident while making big decisions in life?"
search(query)
```
## **Semantic Search x Auxiliary Features**
This section is under active development.
---
This purpose of this section is to explore two primary frontiers:
1. Just semantic search yields satisfactory results, but comes at the cost of compute power. The bottleneck for compute power is the cross-encoder step. This section explores how to reduce the search area, so that semantic search (by the cross-encoder) is performed over a small number blocks, significantly cutting down on the recommendation time.
2. Other than the content itself, several other features such as video statistics (views, likes, dislikes), video titles, video descriptions, video tags present in the dataset can be leveraged to improve the recommendations.
---
```
```
| github_jupyter |
# USGS Earthquakes with the Mapboxgl-Jupyter Python Library
https://github.com/mapbox/mapboxgl-jupyter
```
# Python 3.5+ only!
import asyncio
from aiohttp import ClientSession
import json, geojson, os, time
import pandas as pd
from datetime import datetime, timedelta
from mapboxgl.viz import *
from mapboxgl.utils import *
import pysal.esda.mapclassify as mapclassify
# Get Data from the USGS API
data = []
async def fetch(url, headers, params, session):
async with session.get(url, headers=headers, params=params) as resp:
tempdata = await resp.json()
data.append(tempdata)
return tempdata
async def bound_fetch(sem, url, headers, params, session):
# Getter function with semaphore.
async with sem:
await fetch(url, headers, params, session)
async def get_quakes(param_list, headers):
# Store tasks to run
tasks = []
# create instance of Semaphore
sem = asyncio.Semaphore(1000)
# Generate URL from parameters
endpoint = '/query'
url = '{base_url}{endpoint}'.format(base_url=base_url, endpoint=endpoint)
async with ClientSession() as session:
for i in range(len(param_list)):
task = asyncio.ensure_future(bound_fetch(sem, url, headers, param_list[i], session))
tasks.append(task)
responses = await asyncio.gather(*tasks)
return responses
def create_params(starttime, endtime, minmagnitude):
return {
'format': 'geojson',
'starttime': starttime,
'endtime': endtime,
'minmagnitude': minmagnitude
}
# Default parameters
base_url = 'https://earthquake.usgs.gov/fdsnws/event/1'
HEADERS = {
'user-agent': ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/45.0.2454.101 Safari/537.36'),
}
# Make a list of data to get in a date range
api_args = []
startdate = '2012-01-01'
date = datetime.strptime(startdate, "%Y-%m-%d")
for i in range(1000):
low = datetime.strftime(date + timedelta(days=i*10), "%Y-%m-%d")
high = datetime.strftime(date + timedelta(days=(i+1)*10), "%Y-%m-%d")
api_args.append(create_params(low, high, 2))
#Run api queries for all queries generated
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(get_quakes(api_args, HEADERS))
temp = loop.run_until_complete(future)
#Collect results into a Pandas dataframe
keep_props = ['felt', 'mag', 'magType', 'place', 'time', 'tsunami', 'longitude', 'latitude']
df = pd.DataFrame(columns=keep_props, index=[0])
features = []
for fc in data:
for f in fc['features']:
feature = {}
for k in f['properties']:
if k in keep_props:
feature[k] = f['properties'][k]
feature['longitude'] = f['geometry']['coordinates'][0]
feature['latitude'] = f['geometry']['coordinates'][1]
feature['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(feature['time']/1000))
features.append(feature)
df = pd.DataFrame.from_dict(features)
print(df.shape)
df.head(1)
```
# Set your Mapbox access token.
Set a MAPBOX_ACCESS_TOKEN environment variable, or copy your token to use this notebook.
If you do not have a Mapbox access token, sign up for an account at https://www.mapbox.com/
If you already have an account, you can grab your token at https://www.mapbox.com/account/
```
token = os.getenv('MAPBOX_ACCESS_TOKEN')
# Generate a geojson file from the dataframe
df_to_geojson(df, filename='points.geojson', precision=4, lon='longitude', lat='latitude',
properties=['mag','timestamp'])
# Create the visualization
#Calculate the visualization to create
color_breaks = mapclassify.Natural_Breaks(df['mag'], k=6, initial=0).bins
color_stops = create_color_stops(color_breaks, colors='YlOrRd')
radius_breaks = mapclassify.Natural_Breaks(df['mag'], k=6, initial=0).bins
radius_stops = create_radius_stops(radius_breaks, 1, 10)
viz = GraduatedCircleViz('https://dl.dropbox.com/s/h4xjjlc9ggnr88b/earthquake-points-180223.geojson', #'points.geojson',
color_property = 'mag',
color_stops = color_stops,
radius_property = 'mag',
radius_stops = radius_stops,
opacity=0.8,
below_layer='waterway-label',
zoom=2,
center= [-95, 37],
access_token=token)
viz.show()
```
| github_jupyter |
Using min and max in another way
Just passing minrange and maxrange
r
/ \
/ \
min, r-1 r, max
```
import queue
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def minTree(root):
if root == None:
return 1000000
leftMin = minTree(root.left)
rightMin = minTree(root.right)
return min(leftMin, rightMin, root.data)
def maxTree(root):
if root == None:
return -10000000
leftMax = maxTree(root.left)
rightMax = maxTree(root.right)
return max(leftMax, rightMax, root.data)
def isBST(root):
if root == None:
return True
leftMax = maxTree(root.left)
rightMin = minTree(root.right)
if root.data > rightMin or root.data <= leftMax:
return False
isLeftBST = isBST(root.left)
isRightBST = isBST(root.right)
return isLeftBST and isRightBST
def isBST2(root):
if root == None:
return 1000000, -1000000, True
leftMin, leftMax, isLeftBST = isBST2(root.left)
rightMin, rightMax, isRightBST = isBST2(root.right)
minimum = min(leftMin, rightMin, root.data)
maximum = max(leftMax, rightMax, root.data)
isTreeBST = True
if root.data <= leftMax or root.data > rightMin:
isTreeBST = False
if not(isLeftBST) or not(isRightBST):
isTreeBST = False
return minimum, maximum, isTreeBST
def isBST3(root, min_range, max_range):
if root == None:
return True
if root.data < min_range or root.data > max_range:
return False
isLeftWithinConstraints = isBST3(root.left, min_range, root.data -1)
isRightWithinConstraints = isBST3(root.right, root.data, max_range)
return isLeftWithinConstraints and isRightWithinConstraints
def printTreeDetailed(root):
if root == None:
return
print(root.data, end = ":")
if root.left is not None:
print(root.left.data, end = ",")
if root.right is not None:
print(root.right.data, end = " ")
print()
printTreeDetailed(root.left)
printTreeDetailed(root.right)
def takeLevelWiseTreeInput():
q = queue.Queue()
print("Enter root")
rootData = int(input())
if rootData == -1:
return None
root = BinaryTreeNode(rootData)
q.put(root)
while (not(q.empty())):
current_node = q.get()
print("Enter left child of ", current_node.data)
leftChildData = int(input())
if leftChildData != -1:
leftChild = BinaryTreeNode(leftChildData)
current_node.left = leftChild
q.put(leftChild)
print("Enter right child of ", current_node.data)
rightChildData = int(input())
if rightChildData != -1:
rightChild = BinaryTreeNode(rightChildData)
current_node.right = rightChild
q.put(rightChild)
return root
root = takeLevelWiseTreeInput()
printTreeDetailed(root)
isBST3(root, -10000, 10000)
```
| github_jupyter |
```
%matplotlib inline
```
Saving and loading models for inference in PyTorch
==================================================
There are two approaches for saving and loading models for inference in
PyTorch. The first is saving and loading the ``state_dict``, and the
second is saving and loading the entire model.
Introduction
------------
Saving the model’s ``state_dict`` with the ``torch.save()`` function
will give you the most flexibility for restoring the model later. This
is the recommended method for saving models, because it is only really
necessary to save the trained model’s learned parameters.
When saving and loading an entire model, you save the entire module
using Python’s
`pickle <https://docs.python.org/3/library/pickle.html>`__ module. Using
this approach yields the most intuitive syntax and involves the least
amount of code. The disadvantage of this approach is that the serialized
data is bound to the specific classes and the exact directory structure
used when the model is saved. The reason for this is because pickle does
not save the model class itself. Rather, it saves a path to the file
containing the class, which is used during load time. Because of this,
your code can break in various ways when used in other projects or after
refactors.
In this recipe, we will explore both ways on how to save and load models
for inference.
Setup
-----
Before we begin, we need to install ``torch`` if it isn’t already
available.
::
pip install torch
Steps
-----
1. Import all necessary libraries for loading our data
2. Define and intialize the neural network
3. Initialize the optimizer
4. Save and load the model via ``state_dict``
5. Save and load the entire model
1. Import necessary libraries for loading our data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For this recipe, we will use ``torch`` and its subsidiaries ``torch.nn``
and ``torch.optim``.
```
import torch
import torch.nn as nn
import torch.optim as optim
```
2. Define and intialize the neural network
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For sake of example, we will create a neural network for training
images. To learn more see the Defining a Neural Network recipe.
```
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
print(net)
```
3. Initialize the optimizer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We will use SGD with momentum.
```
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
```
4. Save and load the model via ``state_dict``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Let’s save and load our model using just ``state_dict``.
```
# Specify a path
PATH = "state_dict_model.pt"
# Save
torch.save(net.state_dict(), PATH)
# Load
model = Net()
model.load_state_dict(torch.load(PATH))
model.eval()
```
A common PyTorch convention is to save models using either a ``.pt`` or
``.pth`` file extension.
Notice that the ``load_state_dict()`` function takes a dictionary
object, NOT a path to a saved object. This means that you must
deserialize the saved state_dict before you pass it to the
``load_state_dict()`` function. For example, you CANNOT load using
``model.load_state_dict(PATH)``.
Remember too, that you must call ``model.eval()`` to set dropout and
batch normalization layers to evaluation mode before running inference.
Failing to do this will yield inconsistent inference results.
5. Save and load entire model
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now let’s try the same thing with the entire model.
```
# Specify a path
PATH = "entire_model.pt"
# Save
torch.save(net, PATH)
# Load
model = torch.load(PATH)
model.eval()
```
Again here, remember that you must call model.eval() to set dropout and
batch normalization layers to evaluation mode before running inference.
Congratulations! You have successfully saved and load models for
inference in PyTorch.
Learn More
----------
Take a look at these other recipes to continue your learning:
- `Saving and loading a general checkpoint in PyTorch <https://pytorch.org/tutorials/recipes/recipes/saving_and_loading_a_general_checkpoint.html>`__
- `Saving and loading multiple models in one file using PyTorch <https://pytorch.org/tutorials/recipes/recipes/saving_multiple_models_in_one_file.html>`__
| github_jupyter |
# Sampling the potential energy surface
## Introduction
This interactive notebook demonstrates how to utilize the Potential Energy Surface (PES) samplers algorithm of qiskit chemistry to generate the dissociation profile of a molecule. We use the Born-Oppenhemier Potential Energy Surface (BOPES)and demonstrate how to exploit bootstrapping and extrapolation to reduce the total number of function evaluations in computing the PES using the Variational Quantum Eigensolver (VQE).
```
# import common packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from functools import partial
# qiskit
from qiskit.aqua import QuantumInstance
from qiskit import BasicAer
from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, IQPE
from qiskit.aqua.components.optimizers import SLSQP
from qiskit.circuit.library import ExcitationPreserving
from qiskit import BasicAer
from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE
from qiskit.aqua.components.optimizers import SLSQP
# chemistry components
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry.core import Hamiltonian, TransformationType, QubitMappingType
from qiskit.aqua.algorithms import VQAlgorithm, VQE, MinimumEigensolver
from qiskit.chemistry.transformations import FermionicTransformation
from qiskit.chemistry.drivers import PySCFDriver
from qiskit.chemistry.algorithms.ground_state_solvers import GroundStateEigensolver
from qiskit.chemistry.algorithms.pes_samplers.bopes_sampler import BOPESSampler
from qiskit.chemistry.drivers.molecule import Molecule
from qiskit.chemistry.algorithms.pes_samplers.extrapolator import *
import warnings
warnings.simplefilter('ignore', np.RankWarning)
```
Here, we use the H2 molecule as a model sysem for testing.
```
ft = FermionicTransformation()
driver = PySCFDriver()
solver = VQE(quantum_instance=
QuantumInstance(backend=BasicAer.get_backend('statevector_simulator')))
me_gsc = GroundStateEigensolver(ft, solver)
stretch1 = partial(Molecule.absolute_stretching, atom_pair=(1, 0))
mol = Molecule(geometry=[('H', [0., 0., 0.]),
('H', [0., 0., 0.3])],
degrees_of_freedom=[stretch1],
)
# pass molecule to PSYCF driver
driver = PySCFDriver(molecule=mol)
print(mol.geometry)
```
### Make a perturbation to the molecule along the absolute_stretching dof
```
mol.perturbations = [0.2]
print(mol.geometry)
mol.perturbations = [0.6]
print(mol.geometry)
```
# Calculate bond dissociation profile using BOPES Sampler
Here, we pass the molecular information and the VQE to a built-in type called the BOPES Sampler. The BOPES Sampler allows the computation of the potential energy surface for a specified set of degrees of freedom/points of interest.
## First we compare no bootstrapping vs bootstrapping
Bootstrapping the BOPES sampler involves utilizing the optimal variational parameters for a given degree of freedom, say r (ex. interatomic distance) as the initial point for VQE at a later degree of freedom, say r + $\epsilon$. By default, if boostrapping is set to True, all previous optimal parameters are used as initial points for the next runs.
```
stretch1 = partial(Molecule.absolute_stretching, atom_pair=(1, 0))
mol = Molecule(geometry=[('H', [0., 0., 0.]),
('H', [0., 0., 0.3])],
degrees_of_freedom=[stretch1],
)
# pass molecule to PSYCF driver
driver = PySCFDriver(molecule=mol)
# Specify degree of freedom (points of interest)
points = np.linspace(0.1, 2, 20)
results_full = {} # full dictionary of results for each condition
results = {} # dictionary of (point,energy) results for each condition
conditions = {False: 'no bootstrapping', True: 'bootstrapping'}
for value, bootstrap in conditions.items():
# define instance to sampler
bs = BOPESSampler(
gss=me_gsc
,bootstrap=value
,num_bootstrap=None
,extrapolator=None)
# execute
res = bs.sample(driver,points)
results_full[f'{bootstrap}'] = res.raw_results
results[f'points_{bootstrap}'] = res.points
results[f'energies_{bootstrap}'] = res.energies
```
# Compare to classical eigensolver
```
# define numpy solver
solver_numpy = NumPyMinimumEigensolver()
me_gsc_numpy = GroundStateEigensolver(ft, solver_numpy)
bs_classical = BOPESSampler(
gss=me_gsc_numpy
,bootstrap=False
,num_bootstrap=None
,extrapolator=None)
# execute
res_np = bs_classical.sample(driver, points)
results_full['np'] = res_np.raw_results
results['points_np'] = res_np.points
results['energies_np'] = res_np.energies
```
## Plot results
```
fig = plt.figure()
for value, bootstrap in conditions.items():
plt.plot(results[f'points_{bootstrap}'], results[f'energies_{bootstrap}'], label = f'{bootstrap}')
plt.plot(results['points_np'], results['energies_np'], label = 'numpy')
plt.legend()
plt.title('Dissociation profile')
plt.xlabel('Interatomic distance')
plt.ylabel('Energy')
```
# Compare number of evaluations
```
for condition, result_full in results_full.items():
print(condition)
print('Total evaluations for ' + condition + ':')
sum = 0
for key in result_full:
if condition is not 'np':
sum += result_full[key]['raw_result']['cost_function_evals']
else:
sum = 0
print(sum)
```
# Extrapolation
Here, an extrapolator added that will try to fit each (param,point) set to some specified function and suggest an initial parameter set for the next point (degree of freedom).
- Extrapolator is based on an external extrapolator that sets the 'window', that is, the number of previous points to use for extrapolation, while the internal extrapolator proceeds with the actual extrapolation.
- In practice, the user sets the window by specifies an integer value to num_bootstrap - which also the number of previous points to use for bootstrapping. Additionally, the external extrapolator defines the space within how to extrapolate - here PCA, clustering and the standard window approach.
In practice, if no extrapolator is defined and bootstrapping is True, then all previous points will be bootstrapped. If an extrapolator list is defined and no points are specified for bootstrapping, then the extrapolation will be done based on all previous points.
1. Window Extrapolator: An extrapolator which wraps another extrapolator, limiting the internal extrapolator's ground truth parameter set to a fixed window size
2. PCA Extrapolator: A wrapper extrapolator which reduces the points' dimensionality with PCA, performs extrapolation in the transformed pca space, and untransforms the results before returning.
3. Sieve Extrapolator: A wrapper extrapolator which performs an extrapolation, then clusters the extrapolated parameter values into two large and small clusters, and sets the small clusters' parameters to zero.
4. Polynomial Extrapolator: An extrapolator based on fitting each parameter to a polynomial function of a user-specified degree.
5. Differential Extrapolator: An extrapolator based on treating each param set as a point in space, and performing regression to predict the param set for the next point. A user-specified degree also adds derivatives to the values in the point vectors which serve as features in the training data for the linear regression.
## Here we test two different extrapolation techniques
```
# define different extrapolators
degree = 1
extrap_poly = Extrapolator.factory("poly", degree = degree)
extrap_diff = Extrapolator.factory("diff_model", degree = degree)
extrapolators = {'poly': extrap_poly, 'diff_model': extrap_diff}
for key in extrapolators:
extrap_internal = extrapolators[key]
extrap = Extrapolator.factory("window", extrapolator = extrap_internal)
# define extrapolator
# BOPES sampler
bs_extr = BOPESSampler(
gss=me_gsc
,bootstrap=True
,num_bootstrap=None
,extrapolator=extrap)
# execute
res = bs_extr.sample(driver, points)
results_full[f'{key}']= res.raw_results
results[f'points_{key}'] = res.points
results[f'energies_{key}'] = res.energies
```
## Plot results
```
fig = plt.figure()
for value, bootstrap in conditions.items():
plt.plot(results[f'points_{bootstrap}'], results[f'energies_{bootstrap}'], label = f'{bootstrap}')
plt.plot(results['points_np'], results['energies_np'], label = 'numpy')
for condition in extrapolators.keys():
print(condition)
plt.plot(results[f'points_{condition}'], results[f'energies_{condition}'], label = condition)
plt.legend()
plt.title('Dissociation profile')
plt.xlabel('Interatomic distance')
plt.ylabel('Energy')
```
# Compare number of evaluations
```
for condition, result_full in results_full.items():
print(condition)
print('Total evaluations for ' + condition + ':')
sum = 0
for key in results_full[condition].keys():
if condition is not 'np':
sum += results_full[condition][key]['raw_result']['cost_function_evals']
else:
sum = 0
print(sum)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
```
| github_jupyter |
# 實驗:實作InceptionV3網路架構
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/taipeitechmmslab/MMSLAB-TF2/blob/master/Lab8.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/taipeitechmmslab/MMSLAB-TF2/blob/master/Lab8.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
### Import必要套件
```
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
```
---
## Keras Applications
### 創建InceptionV3網路架構
- 輸入大小(預設):(299, 299, 3)
- 權重(預設):`imagenet`
- 輸出類別(預設):1000個類別
```
model = tf.keras.applications.InceptionV3(include_top=True, weights='imagenet')
```
透過`model.summary`可以察看網路模型的每一層資訊:
```
model.summary()
```
將網路模型儲存到TensorBoard上:
```
model_tb = tf.keras.callbacks.TensorBoard(log_dir='lab8-logs-inceptionv3-keras')
model_tb.set_model(model)
```
### 資料前處理和輸出解碼
使用別人提供的模型預測,需要注意兩件事情,1)訓練時的資料前處理,2)輸出結果對應到的類別。
Keras很貼心的提供每個模型相對應的資料預處理和輸出解碼的函式。
- preprocess_input:網路架構的影像前處理(注意:每一個模型在訓練時做的資料正規化並不會相同,例如:VGG、ResNet-50輸入影像為0~255的數值,而inception_v3、xception輸入影像為-1~1的數值)。
- decode_predictions:對應網路架構的輸出解碼。
Import資料預處理和輸出解碼的函式:
```
from tensorflow.keras.applications.inception_v3 import preprocess_input
from tensorflow.keras.applications.inception_v3 import decode_predictions
```
### 預測輸出結果
創建影像讀取的函式:讀取影像,並將影像大小縮放大299x299x3的尺寸。
```
def read_img(img_path, resize=(299,299)):
img_string = tf.io.read_file(img_path) # 讀取檔案
img_decode = tf.image.decode_image(img_string) # 將檔案以影像格式來解碼
img_decode = tf.image.resize(img_decode, resize) # 將影像resize到網路輸入大小
# 將影像格式增加到4維(batch, height, width, channels),模型預測要求格式
img_decode = tf.expand_dims(img_decode, axis=0)
return img_decode
```
從資料夾中讀取一張影像(elephant.jpg)作為測試:
```
img_path = 'image/elephant.jpg'
img = read_img(img_path) # 透過剛創建的函式讀取影像
plt.imshow(tf.cast(img, tf.uint8)[0]) # 透過matplotlib顯示圖片需將影像轉為Integers
```
預測結果:
```
img = preprocess_input(img) # 影像前處理
preds = model.predict(img) # 預測圖片
print("Predicted:", decode_predictions(preds, top=3)[0]) # 輸出預測最高的三個類別
```
---
## TensorFlow Hub
Install:
```
pip install tensorflow-hub
```
Search:
https://tfhub.dev/
```
import tensorflow as tf
import tensorflow_hub as hub
```
### 創建Inception V3模型
Model:
https://tfhub.dev/google/tf2-preview/inception_v3/classification/2
num_classes = 1001 classes of the classification from the original training
Image:height x width = 299 x 299 pixels, 3 RGB color values in the range 0~1
labels file: https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt
```
# Inception V3預訓練模型的URL
module_url = "https://tfhub.dev/google/tf2-preview/inception_v3/classification/4"
# 創建一個Sequential Model,網路模型裡面包含了Inception V3網路層
model = tf.keras.Sequential([
# hub.KerasLayer將載入的Inception V3模型封裝成網路層(Keras Layer)
hub.KerasLayer(module_url,
input_shape=(299, 299, 3), # 模型輸入大小
output_shape=(1001, ), # 模型輸出大小
name='Inception_v3') # 網路層名稱
])
model.summary()
```
### 資料前處理和輸出解碼
創建資料前處理函式:
```
def read_img(img_path, resize=(299,299)):
img_string = tf.io.read_file(img_path) # 讀取檔案
img_decode = tf.image.decode_image(img_string) # 將檔案以影像格式來解碼
img_decode = tf.image.resize(img_decode, resize) # 將影像resize到網路輸入大小
img_decode = img_decode / 255.0 # 對影像做正規畫,將數值縮放到0~1之間
# 將影像格式增加到4維(batch, height, width, channels),模型預測要求格式
img_decode = tf.expand_dims(img_decode, axis=0) #
return img_decode
```
創建輸出解碼器:
```
# 下載ImageNet 的標籤檔
labels_path = tf.keras.utils.get_file('ImageNetLabels.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')
# 讀取標籤檔中的數據
with open(labels_path) as file:
lines = file.read().splitlines()
print(lines) # 顯示讀取的標籤
imagenet_labels = np.array(lines) # 將標籤轉成numpy array做為網路輸出的解碼器
```
### 預測輸出結果
從資料夾中讀取一張影像(elephant.jpg)作為測試:
```
img_path = 'image/elephant.jpg'
img = read_img(img_path) # 透過剛創建的函式讀取影像
plt.imshow(img[0])
```
預測結果:
```
preds = model.predict(img) # 預測圖片
index = np.argmax(preds) # 取得預測結果最大的Index
print("Predicted:", imagenet_labels[index]) # 透過解碼器將輸出轉成標籤
```
顯示最好的三個預測:
```
# 取得預測結果最大的三個indexs
top3_indexs = np.argsort(preds)[0, ::-1][:3]
print("Predicted:", imagenet_labels[top3_indexs]) # 透過解碼器將輸出轉成標籤
```
| github_jupyter |
```
%matplotlib notebook
import pickle
import numpy as np
import matplotlib.pyplot as plt
from refnx.reflect import SLD, Slab, ReflectModel, MixedReflectModel
from refnx.dataset import ReflectDataset as RD
from refnx.analysis import Objective, CurveFitter, PDF, Parameter, process_chain, load_chain
from FreeformVFP import FreeformVFP
# Version numbers allow you to repeat the analysis on your computer and obtain identical results.
import refnx, scipy
refnx.version.version, np.version.version, scipy.version.version
```
# Load data
Three datasets are included, pNIPAM at 25 °C, 32.5 °C and 40 °C.
pNIPAM is thermoresponsive; the 25 °C is a swollen, diffuse layer, whilst the 40 °C data is a collapsed slab.
```
data = RD("pNIPAM brush in d2o at 25C.dat")
# data = RD("pNIPAM brush in d2o at 32C.dat")
# data = RD("pNIPAM brush in d2o at 40C.dat")
```
# Define materials and slab components
For simplicity some parameters that may normally have been allowed to vary have been set to predetermined optimum values.
```
si = SLD(2.07, 'si')
sio2 = SLD(2.9, 'sio2')
d2o = SLD(6.23 , 'd2o')
polymer = SLD(0.81, 'polymer')
si_l = si(0, 0)
sio2_l = sio2(20, 4.8)
d2o_l = d2o(0, 0)
```
# Create the freeform component
```
NUM_KNOTS = 4
#Polymer layer 1
polymer_0 = polymer(2, 0.5)
# Polymer-Solvent interface (spline)
polymer_vfp = FreeformVFP(adsorbed_amount=120,
vff=[0.6] * NUM_KNOTS,
dzf=[1/(NUM_KNOTS + 1)] * (NUM_KNOTS + 1),
polymer_sld=polymer,
name='freeform vfp',
left_slabs=[polymer_0])
```
# Set parameter bounds
```
sio2.real.setp(vary=True, bounds=(2.8, 3.47))
polymer_0.thick.setp(vary=True, bounds=(2, 20))
polymer_0.vfsolv.setp(vary=True, bounds=(0.1, 0.7))
polymer_vfp.adsorbed_amount.setp(vary=True, bounds=(100, 130))
# We can enforce monotonicity through the bounds we place on the fractional volume fraction changes.
enforce_mono = True
if enforce_mono:
bounds = (0.1, 1)
else:
bounds = (0.1, 1.5)
# Here we set the bounds on the knot locations
for idx in range(NUM_KNOTS):
polymer_vfp.vff[idx].setp(vary=True, bounds=bounds)
polymer_vfp.dzf[idx].setp(vary=True, bounds=(0.05, 1))
polymer_vfp.dzf[-1].setp(vary=True, bounds=(0.05, 1))
polymer_vfp.dzf[0].setp(vary=True, bounds=(0.005, 1))
```
# Create the structure, model, objective
```
structure = si_l | sio2_l | polymer_0 | polymer_vfp | d2o_l
# contracting the slab representation reduces computation time.
structure.contract = 1.5
model = ReflectModel(structure)
model.bkg.setp(vary=True, bounds=(1e-6, 1e-5))
objective = Objective(model, data)
fitter= CurveFitter(objective)
fitter.fit('differential_evolution');
fig, [ax_vfp, ax_sld, ax_refl] = plt.subplots(1, 3, figsize=(10,3), dpi=90)
z = np.linspace(-50, 1750, 2000)
ax_vfp.plot(*polymer_vfp.profile())
ax_sld.plot(*structure.sld_profile(z))
ax_refl.plot(data.x, objective.generative())
ax_refl.errorbar(data.x, data.y, yerr=data.y_err)
ax_refl.set_yscale('log')
fig.tight_layout()
```
| github_jupyter |
# Iterative reconstruction of undersampled MR data
This demonstration shows how to hande undersampled data
and how to write a simple iterative reconstruction algorithm with
the acquisition model.
This demo is a 'script', i.e. intended to be run step by step in a
Python notebook such as Jupyter. It is organised in 'cells'. Jupyter displays these
cells nicely and allows you to run each cell on its own.
First version: 27th of March 2019
Updated: 26nd of June 2021
Author: Johannes Mayer, Christoph Kolbitsch
CCP SyneRBI Synergistic Image Reconstruction Framework (SIRF).
Copyright 2015 - 2017 Rutherford Appleton Laboratory STFC.
Copyright 2015 - 2017 University College London.
Copyright 2015 - 2017, 2019, 2021 Physikalisch-Technische Bundesanstalt.
This is software developed for the Collaborative Computational
Project in Positron Emission Tomography and Magnetic Resonance imaging
(http://www.ccppetmr.ac.uk/).
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
http://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.
```
#%% make sure figures appears inline and animations works
%matplotlib notebook
# Setup the working directory for the notebook
import notebook_setup
from sirf_exercises import cd_to_working_dir
cd_to_working_dir('MR', 'd_undersampled_reconstructions')
__version__ = '0.1.0'
# import engine module
import sirf.Gadgetron as pMR
from sirf.Utilities import examples_data_path
from sirf_exercises import exercises_data_path
# import further modules
import os, numpy
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from tqdm.auto import trange
```
### Undersampled Reconstruction
#### Goals of this notebook:
- Write a fully sampled reconstruction on your own.
- Obtain knowledge of how to deal with undersampled data.
- User SIRF and Gadgetron to perform a GRAPPA reconstruction.
- Implement an iterative parallel imaging SENSE reconstruction algorithm from scratch.
```
# This is just an auxiliary function
def norm_array( arr ):
min_a = abs(arr).min()
max_a = abs(arr).max()
return (arr - min_a)/(max_a - min_a)
```
### Time to get warmed up again:
Since we deal with undersampled data in this last section, we need to compare it to a reference.
So we need to reconstruct the fully sampled dataset we encountered before.
This is an ideal opportunity to test what we learned and employ the `pMR.FullSampledReconstructor` class from before.
### Programming Task: Fully sampled reconstruction
__Please write code that does the following:__
- create a variable called `full_acq_data` of type `pMR.AcquisitionData` from the file `ptb_resolutionphantom_fully_ismrmrd.h5`
- create a variable called `prep_full_data` and assign it the preprocessed data by calling the function `pMR.preprocess_acquisition_data` on our variable `full_acq_data`
- create a variable called `recon` of type `pMR.FullySampledReconstructor()`
- call the `set_input` method of `recon` on `prep_full_data` to assign our fully sampled dataset to our reconstructor
- call the `process()` method of `recon` without arguments.
- create a variable called `fs_image` and assign it the output of the `get_output` method of `recon`
__Hint:__ if you call a function without arguments, don't forget the empty parenthesis.
#### Don't look at the solution before you tried!
```
# YOUR CODE GOES HERE
# VALIDATION CELL
fs_image_array = fs_image.as_array()
fs_image_array = norm_array(fs_image_array)
fig = plt.figure()
plt.set_cmap('gray')
ax = fig.add_subplot(1,1,1)
ax.imshow( abs(fs_image_array[0,:,:]), vmin=0, vmax=1)
ax.set_title('Fully sampled reconstruction')
ax.axis('off')
# Solution Cell. Don't look if you didn't try!
data_path = exercises_data_path('MR', 'PTB_ACRPhantom_GRAPPA')
filename_full_file = os.path.join(data_path, 'ptb_resolutionphantom_fully_ismrmrd.h5')
full_acq_data = pMR.AcquisitionData(filename_full_file)
prep_full_data = pMR.preprocess_acquisition_data(full_acq_data)
recon = pMR.FullySampledReconstructor()
recon.set_input(prep_full_data)
recon.process()
fs_image = recon.get_output()
# VALIDATION CELL
fs_image_array = fs_image.as_array()
fs_image_array = norm_array(fs_image_array)
fig = plt.figure()
plt.set_cmap('gray')
ax = fig.add_subplot(1,1,1)
ax.imshow( abs(fs_image_array[0,:,:]), vmin=0, vmax=1)
ax.set_title('Fully sampled reconstruction')
ax.axis('off')
# LOADING AND PREPROCESSING DATA FOR THIS SET
filename_grappa_file = os.path.join(data_path, 'ptb_resolutionphantom_GRAPPA4_ismrmrd.h5')
acq_data = pMR.AcquisitionData(filename_grappa_file)
preprocessed_data = pMR.preprocess_acquisition_data(acq_data)
preprocessed_data.sort()
print('Is the data we loaded undersampled? %s' % preprocessed_data.is_undersampled())
#%% RETRIEVE K-SPACE DATA
k_array = preprocessed_data.as_array()
print('Size of k-space %dx%dx%d' % k_array.shape)
#%% SELECT VIEW DATA FROM DIFFERENT COILS
print('Size of k-space %dx%dx%d' % k_array.shape)
num_channels = k_array.shape[1]
print(num_channels)
k_array = norm_array(k_array)
fig = plt.figure()
plt.set_cmap('gray')
for c in range(num_channels):
ax = fig.add_subplot(2,num_channels//2,c+1)
ax.imshow(abs(k_array[:,c,:]), vmin=0, vmax=0.05)
ax.set_title('Coil '+str(c+1))
ax.axis('off')
```
This looks pretty similar to what we had before, so we should be good.
```
# we define a quick fft with sos coil combination to do a standard reconstruction.
def our_fft( k_array ):
image_array = numpy.zeros(k_array.shape, numpy.complex128)
for c in range(num_channels):
image_array[:,c,:] = numpy.fft.fftshift( numpy.fft.ifft2( numpy.fft.ifftshift(k_array[:,c,:])))
# image_array = image_array/image_array.max()
image_array = numpy.sqrt(numpy.sum(numpy.square(numpy.abs(image_array)),1))
return image_array
# now we make a FFT of the data we looked at and compare it to our fully sampled image
image_array_sos = our_fft(k_array)
image_array_sos = norm_array(image_array_sos)
fig = plt.figure()
ax = fig.add_subplot(1,2,1)
ax.imshow(abs(image_array_sos), vmin=0, vmax=1)
ax.set_title('Undersampled')
ax.axis('off')
ax = fig.add_subplot(1,2,2)
ax.imshow(abs(fs_image_array[0,:,:]), vmin=0, vmax=1)
ax.set_title('Fully sampled')
ax.axis('off')
```
### Question:
Please answer the following question for yourself:
- Why is the undersampled reconstruction squeezed, but covers the whole FOV?
```
# NOW LET'S LOOK WHICH PARTS ARE SAMPLED AND WHICH ARE LEFT OUT
# kspace_encode_step_1 gives the phase encoding steps which were performed
which_pe = preprocessed_data.get_ISMRMRD_info('kspace_encode_step_1')
print('The following Phase Encoding (PE) points were sampled: \n')
print(which_pe)
```
#### Observation: approximately 3 out of 4 phase encoding steps are missing.
```
# Fill an array with 1 only if a datapoint was acquired
sampling_mask = numpy.zeros([256,256])
for pe in which_pe:
sampling_mask[pe,:] = 1
# PLOT THE SAMPLING MASK
fig = plt.figure()
plt.set_cmap('gray')
ax = fig.add_subplot(1,1,1)
ax.imshow( sampling_mask, vmin=0, vmax=1)
ax.set_title('Sampling pattern of a GRAPPA acquisition')
plt.xlabel('Frequency encoding')
plt.ylabel('Phase encoding')
#ax.axis('off')
```
We notice that $112 = \frac{256}{4} + 48$.
This means the around the center of k-space is densely sampled containing 48 readout lines.
The outside of k-space is undersampled by a factor of 4.
### Workaround: 'zero-fill' the k-space data
Since the artifacts seem to be related to the shape of the data, let's just unsqueeze the shape into the correct one.
Somehow we need to supply more datapoints to our FFT. But can we just add datapoints? This will corrupt the data!
Actually, a Fourier transform is just a sum weighted by a phase:
$$
f(x) = \sum_k e^{j k x} \cdot F(k)
$$
So it does not mind if we add a data point $F(k) = 0$ at a position we didn't sample!
This means we make a larger array, __add our data in the correct spots__, and the gaps we fill with zeros. The correct spots are given by our sampling mask!
```
k_shape = [sampling_mask.shape[0], num_channels, sampling_mask.shape[1]]
zf_k_array = numpy.zeros(k_shape, numpy.complex128)
for i in range(k_array.shape[0]):
zf_k_array[which_pe[i],:,:] = k_array[i,:,:]
fig = plt.figure()
plt.set_cmap('gray')
for c in range(num_channels):
ax = fig.add_subplot(2,num_channels//2,c+1)
ax.imshow(abs(zf_k_array[:,c,:]), vmin=0, vmax=0.05)
ax.set_title('Coil '+str(c+1))
ax.axis('off')
# Reconstruct the zero-filled data and take a look
zf_recon = our_fft( zf_k_array)
zf_recon = norm_array(zf_recon)
fig = plt.figure()
ax = fig.add_subplot(1,2,1)
ax.imshow(abs(zf_recon), vmin=0, vmax=1)
ax.set_title('Zero-filled Undersampled ')
ax.axis('off')
ax = fig.add_subplot(1,2,2)
ax.imshow(abs(fs_image_array[0,:,:]), vmin=0, vmax=1)
ax.set_title('Fully Sampled ')
ax.axis('off')
```
### Observation:
Bummer. Now the shape is correct, however the artifacts are still present.
- What artifacts appear in the zero-filled reconstruction?
- Why are they artifacts all fine-lined?
- How come they only appear in one direction?
To get rid of these we will need some parallel imaging techniques.
### Coil Sensitivity Map computation
Parallel imaging, this has something to do with exploiting the spatially varying coil sensitivities.
```
# WHICH COILMAPS DO WE GET FROM THIS DATASET?
csm = pMR.CoilSensitivityData()
csm.smoothness = 50
csm.calculate(preprocessed_data)
csm_array = numpy.squeeze(csm.as_array())
csm_array = csm_array.transpose([1,0,2])
fig = plt.figure()
plt.set_cmap('jet')
for c in range(csm_array.shape[1]):
ax = fig.add_subplot(2,num_channels//2,c+1)
ax.imshow(abs(csm_array[:,c,:]))
ax.set_title('Coil '+str(c+1))
ax.axis('off')
plt.set_cmap('gray')
```
### Question:
In practice we would want to use a weighted sum (WS) coil combination technique so any artifacts in the coilmap would directly translate into the combined image. But we didn't see any of the high frequency artifacts!
Please answer the following question:
- Why are there are artifacts in the reconstruction but not in the coilmaps?
We learned before, that parallel imaging is easily able to get rid of undersampling factor R=4.
But to have enough information to estimate coilmaps the center must be fully sampled.
Ergo a perfect acceleration by R=4 is not possible, one needs to spends some time to sample the center densely, to obtain coil sensitivities. Still, $\frac{112}{256} = 0.44$, we acquired 56% faster.
### GRAPPA Reconstruction
GRAPPA is a parallel imaging technique which promises to get rid of undersampling artifacts.
So let's use one of our SIRF classes and see what it can do!
```
# WE DO A GRAPPA RECONSTRUCTION USING SIRF
recon = pMR.CartesianGRAPPAReconstructor()
recon.set_input(preprocessed_data)
recon.compute_gfactors(False)
print('---\n reconstructing...')
recon.process()
# for undersampled acquisition data GRAPPA computes Gfactor images
# in addition to reconstructed ones
grappa_images = recon.get_output()
grappa_images_array = grappa_images.as_array()
grappa_images_array = norm_array(grappa_images_array)
# PLOT THE RESULTS
fig = plt.figure(figsize=(9, 4))
ax = fig.add_subplot(1,3,1)
ax.imshow(abs(zf_recon), vmin=0, vmax=1)
ax.set_title('Zero-filled Undersampled ')
ax.axis('off')
ax = fig.add_subplot(1,3,2)
ax.imshow(abs(grappa_images_array[0,:,:]), vmin=0, vmax=1)
ax.set_title('GRAPPA')
ax.axis('off')
ax = fig.add_subplot(1,3,3)
ax.imshow(abs(fs_image_array[0,:,:]), vmin=0, vmax=1)
ax.set_title('Fully Sampled')
ax.axis('off')
plt.tight_layout()
```
__Well, that was very little code to perform a difficult task!__ That is because we sent our data off to The Gadgetron and they did all the work.
### Question:
In what respect did a GRAPPA reconstruction:
* improve the resulting image?
* deterioate the resulting image?
# GREAT! Now we want to develop our own algorithm and be better than the GRAPPA reconstruction!
## Urgh, let's rather not because we are annoyed by how much code we have to write all the time! Zero filling, coil combining, inverse FFTs. Frankly: terrible!
We want to capture our entire imaging and reconstruction process in one single object and don't care about data structure. Also we don't want to have to sum over coil channels all the time and take care of zero filling, this is just too much work!
When we want to develop some reconstruction algorithm, we want to be able to go from an image $x$ __forward__ to k-space data $y$:
$$ E: x \rightarrow y,$$
implicitly performing multiplication of the image with the coil sensitivities $C_c$ for each channel $c$ and performing an FFT:
$$
E x = y_c = \mathcal{F}( C_c \cdot x).
$$
In iterative image reconstruction we often to apply the so-called __backward__ or __adjoint__ to transform the k-space data into image space. This bundles doing the zero-filling, inverse FFT, and coil combination into one operation:
$$ E^H: y \rightarrow x,$$
implicitly performing everything:
$$
E^H y = x = \sum_c C_c^*\mathcal{F}^{-1}(y)
$$
$E^H$ in this case is the hermitian conjugate of the complex valued operator $E$. It is the combination of transposing and complex conjugation of a matrix: $ E^H = (E^T)^* $. Note, that this is not generally the inverse: $ E^H \neq E^{-1}$
### Enter: AcquisitionModel
In SIRF there exists something called `AcquisitionModel`, in the literature also referenced as and Encoding operator $E$, *E* for encoding.
```
# NOW WE GENERATE THE ACQUISITION MODEL
E = pMR.AcquisitionModel(preprocessed_data, grappa_images)
# We need help again to see what this thing here can do
help(E)
# to supply coil info to the acquisition model we use the dedicated method
E.set_coil_sensitivity_maps(csm)
# Now we can hop back from k-space into image space in just one line:
aq_model_image = E.backward( preprocessed_data )
```
Well this is not much code any more. Suddenly implementing our own iterative algorithm seems feasible!
### QUESTION
BEFORE YOU RUN THE NEXT CELL AND LOOK AT THE PLOT:
In the next plot the image stored in `aq_model_image_array` will be shown, i.e. $x = E^H y$.
Based on the discussion what the AcquisitionModel E does, what do you expect the reconstruction to look like?
- Is it squeezed or is it the correct size?
- Does it contain artifacts? If so, which ones?
```
aq_model_image_array = norm_array(aq_model_image.as_array())
fig = plt.figure()
plt.set_cmap('gray')
ax = fig.add_subplot(1,1,1)
ax.imshow(abs(aq_model_image_array[0,:,:]))
ax.set_title('Result Backward Method of E ')
ax.axis('off')
```
__Well, bummer again, the artifacts are still there!__ Of course, the acquisition model is just a compact version of our above code. We need something smarter to kill them off. But it got a bit more homogeneous, due to the weighted coil combination.
# Image Reconstruction as an Inverse Problem
## Iterative Parallel Imaging Reconstruction
In order to employ parallel imagaing, we should look at image reconstruction as an inverse problem.
By "image reconstruction" we actually mean to achieve the following equality:
$$ E x = y,$$ or equivalently
$$ E^H E \, x = E^H y,$$
where $E$ is the encoding operator $x$ is the true image object and $y$ is the MR raw data we acquired.
The task of image reconstruction boils down to optimizing the following function:
$$ \mathcal{C}(x) = \frac{1}{2} \bigl{|} \bigl{|} E \, x - y \bigr{|} \bigr{|}_2^2 \\
\tilde{x} = \min_x \mathcal{C}(x)
$$
To iteratively find the minimum of this cost function, $\tilde{x}$, we need to go through steps of the kind:
1. have a first guess for our image (usually an empty image)
2. generate k-space data from this guess and compute the discrepancy to our acquired data (i.e. evaluate the cost fuction).
3. update our image guess based on the computed discrepancy s.t. the cost will be lowered.
__By iterating steps 2 and 3 many times we will end up at $\tilde{x}$.__
Is that going to be better than a GRAPPA reconstruction?
## Implementing Conjugate Gradient Descent SENSE
Conjugate Gradient (CG) optimization is such an iterative procedure which will quickly result in finding $\tilde{x}$.
We can study the corresponding [Wikipedia Article](https://en.wikipedia.org/wiki/Conjugate_gradient_method#Description_of_the_problem_addressed_by_conjugate_gradients).
This looks like our thang!
For that we need to write a bit of code:
- We already have this encoding operator `E` defined where we can go from image to k-space and back.
- Now we need to implement our first guess
- and somehow we loop through steps 2 and 3 updating our image s.t. the costs are lowered.
They want to compute x in $Ax = b$, we want to compute x in $E^H E x = E^H y$.
This means we need to translate what it says on Wikipedia:
- $x$ = reconstructed image
- $A$ = $E^HE$
- $b$ = $E^H y$
### Programming task
Please write code executing the following task:
- define a fuction named `A_operator`
- it should have one single argument `image`
- it should return $E^H( E (image))$
__Hint 1:__ We defined `E` already. Use it methods `forward` and `backward`. `forward` goes from image space to k-space and `backward` the other way round.
__Hint 2:__ Short reminder on the syntax. The function should look like:
```
def function_name( arugment_name):
variable = code_that_does_something_with ( argument_name )
return variable
```
```
# Write your code here (this is as much space as you need!)
# make sure the name of your function is A_operator
# Don't look at the solution before you tried!
# With this guy we will write our optimization
def A_operator( image ):
return E.backward( E.forward(image) )
```
#### Back to Wikipedia!
Now we have all the tools we need. Now let's write the code to optimize our cost function iteratively.
We don't care too much about maths, but we want the [algorithm](https://en.wikipedia.org/wiki/Conjugate_gradient_method#The_resulting_algorithm).
```
# our images should be the same shape as the GRAPPA output
recon_img = grappa_images
# since we have no knowledge at all of what the image is we start from zero
zero_array = recon_img.as_array()
zero_array.fill(0)
recon_img.fill(zero_array)
# now name the variables the same as in the Wikipedia article:
x = recon_img
y = preprocessed_data
```
### Programming task: Initialize Iterative Reconstruction
Please write code executing the following task:
- Initialize a variable `r` with `r` = $b - Ax$ (`r` stands for residual).
__Hint 0:__ Remember: $b=E^H y$. Don't forget we just defined the A operator!
- Print the type of `r` using Pythons built-in `type` and `print` function. What type of r do you expect? Is it an image, or is it acquisition data?
- After you wrote these two lines run your cell pressing `Ctrl+Enter`, to get the output of the print statement. This will tell you the class of `r`.
- Afterwards, initialize a variable named `rr` with `rr` = $r^\dagger r$. (`rr` stands for r times r). `rr` is the value of the cost function by the way.
__Hint 1:__ No need to access any numpy arrays! Objects of type `sirf.Gadgetron.ImageData` have the method called ` norm()` giving you the square root of the quantity we are looking for.
__Hint 2:__ Python-Power: $c=a^b$ $\equiv$ `c = a**b`.
- Initialize a variable `rr0` with the value of `rr` to store the starting norm of the residuals.
- Initialize a variable `p` with the value of `r`.
```
## WRITE YOUR CODE IN THIS CELL
## Please make sure to name the variables correctly
##### Don't look at the solution before you tried! #############################
############################################################################
# this is our first residual
r = E.backward( y ) - A_operator(x)
# print the type
print('The type of r is: ' + str( type(r) ) )
# this is our cost function at the start
rr = r.norm() ** 2
rr0 = rr
# initialize p
p = r
# now we write down the algorithm
# how many iterative steps do we want
# how low should the cost be
num_iter = 15
sufficiently_small = 1e-7
#prep a container to store the updated image after each iteration, this is just for plotting reasons!
data_shape = numpy.array( x.as_array().shape )
data_shape[0] = num_iter
array_with_iterations = numpy.zeros(data_shape, numpy.complex128)
# HERE WE RUN THE LOOP.
print('Cost for k = 0: ' + str( rr/ rr0) )
with trange(num_iter) as iters:
for k in iters:
Ap = A_operator( p )
alpha = rr / Ap.dot(p)
x = x + alpha * p
r = r - alpha * Ap
beta = r.norm()**2 / rr
rr = r.norm()**2
p = r + beta * p
relative_residual = numpy.sqrt(rr/rr0)
array_with_iterations[k,:,:] = x.as_array()
iters.write('Cost for k = ' +str(k+1) + ': ' + str(relative_residual) )
iters.set_postfix(cost=relative_residual)
if( relative_residual < sufficiently_small ):
iters.write('We achieved our desired accuracy. Stopping iterative reconstruction')
break
if k is num_iter-1:
print('Reached maximum number of iterations. Stopping reconstruction.')
# See how the reconstructed image evolves
fig = plt.figure()
ims = []
for i in range(k):
im = plt.imshow(abs( array_with_iterations[i,:,:]), animated=True)
ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=500, blit=True, repeat_delay=0)
plt.show()
## now check out the final result as a still image
recon_arr = norm_array( x.as_array())
plt.set_cmap('gray')
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.imshow(abs(recon_arr[0,:,:]))
ax.set_title('SENSE RECONSTRUCTION')
ax.axis('off')
# Let's Plot
recon_arr = x.as_array()
fig = plt.figure(figsize=(9, 9))
ax = fig.add_subplot(2,2,1)
ax.imshow(abs(aq_model_image_array[0,:,:]))
ax.set_title('UNDERSAMPLED RECONSTRUCTION')
ax.axis('off')
ax = fig.add_subplot(2,2,2)
ax.imshow(abs(grappa_images_array[0,:,:]))
ax.set_title('GRAPPA RECONSTRUCTION')
ax.axis('off')
ax = fig.add_subplot(2,2,3)
ax.imshow(abs(recon_arr[0,:,:]))
ax.set_title('SENSE RECONSTRUCTION')
ax.axis('off')
ax = fig.add_subplot(2,2,4)
ax.imshow(abs(fs_image_array[0,:,:]))
ax.set_title('FULLY SAMPLED RECONSTRUCTION')
ax.axis('off')
plt.tight_layout()
```
### Question: Evaluation SENSE Reconstruction
[So what is better, GRAPPA or SENSE?](https://www.youtube.com/watch?v=XVCtkzIXYzQ)
Please answer the following questions:
- Where is the noise coming from?
- Why has not every high-frequency artifact vanished?
And if you had typed the above code into your computer in 2001 and written a [paper](https://scholar.google.de/scholar?hl=de&as_sdt=0%2C5&q=Advances+in+sensitivity+encoding+with+arbitrary+k%E2%80%90space+trajectories&btnG=) on it, then 18 years later you had a good 1000 citations (plus 6k from the [previous one](https://scholar.google.de/scholar?hl=de&as_sdt=0%2C5&q=SENSE%3A+sensitivity+encoding+for+fast+MRI&btnG=)).
### Undersampled Reconstruction
#### Recap:
In this notebook you
- wrote your own fully sampled recon using SIRF.
- saw the undersampling structure of GRAPPA files
- discovered high-frequency undersampling artifacts.
- implemented our own version of SENSE and beat (?) GRAPPA.
### Fin
This was the last exercise. We hoped you learned some new things about MRI and had a pleasant experience with SIRF and Python.
See you later!
| github_jupyter |
# k-Nearest Neighbor (kNN) 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](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.*
The kNN classifier consists of two stages:
- During training, the classifier takes the training data and simply remembers it
- During testing, kNN classifies every test image by comparing to all training images and transfering the labels of the k most similar training examples
- The value of k is cross-validated
In this exercise you will implement these steps and understand the basic Image Classification pipeline, cross-validation, and gain proficiency in writing efficient, vectorized code.
```
# Run some setup code for this notebook.
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%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'
# Some more magic so that the notebook will reload external python modules;
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
# 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)
# As a sanity check, we print out the size of the training and test data.
print 'Training data shape: ', X_train.shape
print 'Training labels shape: ', y_train.shape
print 'Test data shape: ', X_test.shape
print 'Test labels shape: ', y_test.shape
# Visualize some examples from the dataset.
# We show a few examples of training images from each class.
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
num_classes = len(classes)
samples_per_class = 7
for y, cls in enumerate(classes):
idxs = np.flatnonzero(y_train == y)
# select $samples_per_class different samples from a class
idxs = np.random.choice(idxs, samples_per_class, replace=False)
for i, idx in enumerate(idxs):
plt_idx = i * num_classes + y + 1
plt.subplot(samples_per_class, num_classes, plt_idx)
plt.imshow(X_train[idx].astype('uint8'))
plt.axis('off')
if i == 0:
plt.title(cls)
plt.show()
# Subsample the data for more efficient code execution in this exercise
num_training = 5000
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]
num_test = 500
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
# Reshape the image data into rows
X_train = np.reshape(X_train, (X_train.shape[0], -1))
X_test = np.reshape(X_test, (X_test.shape[0], -1))
print X_train.shape, X_test.shape
from cs231n.classifiers import KNearestNeighbor
# Create a kNN classifier instance.
# Remember that training a kNN classifier is a noop:
# the Classifier simply remembers the data and does no further processing
classifier = KNearestNeighbor()
classifier.train(X_train, y_train)
```
We would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps:
1. First we must compute the distances between all test examples and all train examples.
2. Given these distances, for each test example we find the k nearest examples and have them vote for the label
Lets begin with computing the distance matrix between all training and test examples. For example, if there are **Ntr** training examples and **Nte** test examples, this stage should result in a **Nte x Ntr** matrix where each element (i,j) is the distance between the i-th test and j-th train example.
First, open `cs231n/classifiers/k_nearest_neighbor.py` and implement the function `compute_distances_two_loops` that uses a (very inefficient) double loop over all pairs of (test, train) examples and computes the distance matrix one element at a time.
```
# Open cs231n/classifiers/k_nearest_neighbor.py and implement
# compute_distances_two_loops.
# Test your implementation:
dists = classifier.compute_distances_two_loops(X_test)
print dists.shape
# We can visualize the distance matrix: each row is a single test example and
# its distances to training examples
plt.imshow(dists, interpolation='none')
```
**Inline Question #1:** Notice the structured patterns in the distance matrix.
- What is the cause behind the distinctly visible rows?
- What causes the columns?
**Your Answer**:
* Each test image will have variant L2 distance to the training images
* Each training image have distinct L2 distance to the test images
```
# Now implement the function predict_labels and run the code below:
# We use k = 1 (which is Nearest Neighbor).
y_test_pred = classifier.predict_labels(dists, k=1)
# Compute and print the fraction of correctly predicted examples
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print 'Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy)
# Now lets speed up distance matrix computation by using partial vectorization
# with one loop. Implement the function compute_distances_one_loop and run the
# code below:
dists_one = classifier.compute_distances_one_loop(X_test)
# To ensure that our vectorized implementation is correct, we make sure that it
# agrees with the naive implementation. There are many ways to decide whether
# two matrices are similar; one of the simplest is the Frobenius norm. In case
# you haven't seen it before, the Frobenius norm of two matrices is the square
# root of the squared sum of differences of all elements; in other words, reshape
# the matrices into vectors and compute the Euclidean distance between them.
difference = np.linalg.norm(dists - dists_one, ord='fro')
print 'Difference was: %f' % (difference, )
if difference < 0.001:
print 'Good! The distance matrices are the same'
else:
print 'Uh-oh! The distance matrices are different'
# Now implement the fully vectorized version inside compute_distances_no_loops
# and run the code
dists_two = classifier.compute_distances_no_loops(X_test)
# check that the distance matrix agrees with the one we computed before:
difference = np.linalg.norm(dists - dists_two, ord='fro')
print 'Difference was: %f' % (difference, )
if difference < 0.001:
print 'Good! The distance matrices are the same'
else:
print 'Uh-oh! The distance matrices are different'
# Let's compare how fast the implementations are
def time_function(f, *args):
"""
Call a function f with args and return the time (in seconds) that it took to execute.
"""
import time
tic = time.time()
f(*args)
toc = time.time()
return toc - tic
two_loop_time = time_function(classifier.compute_distances_two_loops, X_test)
print 'Two loop version took %f seconds' % two_loop_time
one_loop_time = time_function(classifier.compute_distances_one_loop, X_test)
print 'One loop version took %f seconds' % one_loop_time
no_loop_time = time_function(classifier.compute_distances_no_loops, X_test)
print 'No loop version took %f seconds' % no_loop_time
# you should see significantly faster performance with the fully vectorized implementation
```
### Cross-validation
We have implemented the k-Nearest Neighbor classifier but we set the value k = 5 arbitrarily. We will now determine the best value of this hyperparameter with cross-validation.
```
num_folds = 5
k_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100]
X_train_folds = []
y_train_folds = []
################################################################################
# TODO: #
# Split up the training data into folds. After splitting, X_train_folds and #
# y_train_folds should each be lists of length num_folds, where #
# y_train_folds[i] is the label vector for the points in X_train_folds[i]. #
# Hint: Look up the numpy array_split function. #
################################################################################
idxes = range(num_training)
idx_folds = np.array_split(idxes, num_folds)
for idx in idx_folds:
# mask = np.ones(num_training, dtype=bool)
# mask[idx] = False
# X_train_folds.append( (X_train[mask], X_train[~mask]) )
# y_train_folds.append( (y_train[mask], y_train[~mask]) )
X_train_folds.append( X_train[idx] )
y_train_folds.append( y_train[idx] )
# A dictionary holding the accuracies for different values of k that we find
# when running cross-validation. After running cross-validation,
# k_to_accuracies[k] should be a list of length num_folds giving the different
# accuracy values that we found when using that value of k.
k_to_accuracies = {}
################################################################################
# TODO: #
# Perform k-fold cross validation to find the best value of k. For each #
# possible value of k, run the k-nearest-neighbor algorithm num_folds times, #
# where in each case you use all but one of the folds as training data and the #
# last fold as a validation set. Store the accuracies for all fold and all #
# values of k in the k_to_accuracies dictionary. #
################################################################################
import sys
classifier = KNearestNeighbor()
Verbose = False
for k in k_choices:
if Verbose: print "processing k=%f" % k
else: sys.stdout.write('.')
k_to_accuracies[k] = list()
for num in xrange(num_folds):
if Verbose: print "processing fold#%i/%i" % (num, num_folds)
X_cv_train = np.vstack( [ X_train_folds[x] for x in xrange(num_folds) if x != num ])
y_cv_train = np.hstack( [ y_train_folds[x].T for x in xrange(num_folds) if x != num ])
X_cv_test = X_train_folds[num]
y_cv_test = y_train_folds[num]
# train k-nearest neighbor classifier
classifier.train(X_cv_train, y_cv_train)
# calculate trained matrix
dists = classifier.compute_distances_no_loops(X_cv_test)
y_cv_test_pred = classifier.predict_labels(dists, k=k)
# Compute and print the fraction of correctly predicted examples
num_correct = np.sum(y_cv_test_pred == y_cv_test)
k_to_accuracies[k].append( float(num_correct) / y_cv_test.shape[0] )
################################################################################
# END OF YOUR CODE #
################################################################################
# Print out the computed accuracies
for k in sorted(k_to_accuracies):
for accuracy in k_to_accuracies[k]:
print 'k = %d, accuracy = %f' % (k, accuracy)
# plot the raw observations
for k in k_choices:
accuracies = k_to_accuracies[k]
plt.scatter([k] * len(accuracies), accuracies)
# plot the trend line with error bars that correspond to standard deviation
accuracies_mean = np.array([np.mean(v) for k,v in sorted(k_to_accuracies.items())])
accuracies_std = np.array([np.std(v) for k,v in sorted(k_to_accuracies.items())])
plt.errorbar(k_choices, accuracies_mean, yerr=accuracies_std)
plt.title('Cross-validation on k')
plt.xlabel('k')
plt.ylabel('Cross-validation accuracy')
plt.show()
# Based on the cross-validation results above, choose the best value for k,
# retrain the classifier using all the training data, and test it on the test
# data.
best_k = 6
classifier = KNearestNeighbor()
classifier.train(X_train, y_train)
y_test_pred = classifier.predict(X_test, k=best_k)
# Compute and display the accuracy
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print 'Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy)
```
| github_jupyter |
### Forced Alignment with Wav2Vec2
In this notebook we are going to follow [this pytorch tutorial](https://pytorch.org/tutorials/intermediate/forced_alignment_with_torchaudio_tutorial.html) to align script to speech with torchaudio using the CTC segmentation algorithm described in [ CTC-Segmentation of Large Corpora for German End-to-end Speech Recognition](https://arxiv.org/abs/2007.09127)
The process of alignment looks like the following.
1. Estimate the frame-wise label probability from audio waveform
Generate the trellis matrix which represents the probability of labels aligned at time step.
2. Find the most likely path from the trellis matrix.
3. In this example, we use torchaudio’s Wav2Vec2 model for acoustic feature extraction.
### Installation of `tourchaudio`
```
!pip install torchaudio
```
### Imports
```
import os, requests, torch, torchaudio, IPython
from dataclasses import dataclass
import matplotlib.pyplot as plt
SPEECH_URL = 'https://download.pytorch.org/torchaudio/test-assets/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.flac'
SPEECH_FILE = 'speech.flac'
if not os.path.exists(SPEECH_FILE):
with open(SPEECH_FILE, 'wb') as file:
with requests.get(SPEECH_URL) as resp:
resp.raise_for_status()
file.write(resp.content)
```
### Generate frame-wise label probability
The first step is to generate the label class porbability of each aduio frame. We can use a ``Wav2Vec2`` model that is trained for ASR.
``torchaudio`` provides easy access to pretrained models with associated labels.
**Note:** In the subsequent sections, we will compute the probability in log-domain to avoid numerical instability. For this purpose, we normalize the emission with ``log_softmax``.
```
bundle = torchaudio.pipelines.WAV2VEC2_ASR_BASE_960H
model = bundle.get_model()
labels = bundle.get_labels()
with torch.inference_mode():
waveform, _ = torchaudio.load(SPEECH_FILE)
emissions, _ = model(waveform)
emissions = torch.log_softmax(emissions, dim=-1)
emission = emissions[0].cpu().detach()
```
### Visualization
```
print(labels)
plt.imshow(emission.T)
plt.colorbar()
plt.title("Frame-wise class probability")
plt.xlabel("Time")
plt.ylabel("Labels")
plt.show()
```
### Generate alignment probability (trellis)
From the emission matrix, next we generate the trellis which represents
the probability of transcript labels occur at each time frame.
Trellis is 2D matrix with time axis and label axis. The label axis
represents the transcript that we are aligning. In the following, we use
$t$ to denote the index in time axis and $j$ to denote the
index in label axis. $c_j$ represents the label at label index
$j$.
To generate, the probability of time step $t+1$, we look at the
trellis from time step $t$ and emission at time step $t+1$.
There are two path to reach to time step $t+1$ with label
$c_{j+1}$. The first one is the case where the label was
$c_{j+1}$ at $t$ and there was no label change from
$t$ to $t+1$. The other case is where the label was
$c_j$ at $t$ and it transitioned to the next label
$c_{j+1}$ at $t+1$.
The follwoing diagram illustrates this transition.

Since we are looking for the most likely transitions, we take the more
likely path for the value of $k_{(t+1, j+1)}$, that is
$ k_{(t+1, j+1)} = max( k_{(t, j)} p(t+1, c_{j+1}), k_{(t, j+1)} p(t+1,
repeat) ) $
where $k$ represents is trellis matrix, and $p(t, c_j)$
represents the probability of label $c_j$ at time step $t$.
$repeat$ represents the blank token from CTC formulation. (For the
detail of CTC algorithm, please refer to the `Sequence Modeling with CTC
[distill.pub] <https://distill.pub/2017/ctc/>`__)
```
transcript = 'I|HAD|THAT|CURIOSITY|BESIDE|ME|AT|THIS|MOMENT'
dictionary = {c: i for i, c in enumerate(labels)}
tokens = [dictionary[c] for c in transcript]
print(list(zip(transcript, tokens)))
def get_trellis(emission, tokens, blank_id=0):
num_frame = emission.size(0)
num_tokens = len(tokens)
# Trellis has extra diemsions for both time axis and tokens.
# The extra dim for tokens represents <SoS> (start-of-sentence)
# The extra dim for time axis is for simplification of the code.
trellis = torch.full((num_frame+1, num_tokens+1), -float('inf'))
trellis[:, 0] = 0
for t in range(num_frame):
trellis[t+1, 1:] = torch.maximum(
# Score for staying at the same token
trellis[t, 1:] + emission[t, blank_id],
# Score for changing to the next token
trellis[t, :-1] + emission[t, tokens],
)
return trellis
trellis = get_trellis(emission, tokens)
trellis
```
### Visualization.
```
plt.imshow(trellis[1:, 1:].T, origin='lower')
plt.annotate("- Inf", (trellis.size(1) / 5, trellis.size(1) / 1.5))
plt.colorbar()
plt.show()
```
>In the above visualization, we can see that there is a trace of high probability crossing the matrix diagonally.
### Find the most likely path (backtracking)
Once the trellis is generated, we will traverse it following the
elements with high probability.
We will start from the last label index with the time step of highest
probability, then, we traverse back in time, picking stay
($c_j \rightarrow c_j$) or transition
($c_j \rightarrow c_{j+1}$), based on the post-transition
probability $k_{t, j} p(t+1, c_{j+1})$ or
$k_{t, j+1} p(t+1, repeat)$.
Transition is done once the label reaches the beginning.
The trellis matrix is used for path-finding, but for the final
probability of each segment, we take the frame-wise probability from
emission matrix.
```
@dataclass
class Point:
token_index: int
time_index: int
score: float
def backtrack(trellis, emission, tokens, blank_id=0):
# Note:
# j and t are indices for trellis, which has extra dimensions
# for time and tokens at the beginning.
# When refering to time frame index `T` in trellis,
# the corresponding index in emission is `T-1`.
# Similarly, when refering to token index `J` in trellis,
# the corresponding index in transcript is `J-1`.
j = trellis.size(1) - 1
t_start = torch.argmax(trellis[:, j]).item()
path = []
for t in range(t_start, 0, -1):
# 1. Figure out if the current position was stay or change
# Note (again):
# `emission[J-1]` is the emission at time frame `J` of trellis dimension.
# Score for token staying the same from time frame J-1 to T.
stayed = trellis[t-1, j] + emission[t-1, blank_id]
# Score for token changing from C-1 at T-1 to J at T.
changed = trellis[t-1, j-1] + emission[t-1, tokens[j-1]]
# 2. Store the path with frame-wise probability.
prob = emission[t-1, tokens[j-1] if changed > stayed else 0].exp().item()
# Return token index and time index in non-trellis coordinate.
path.append(Point(j-1, t-1, prob))
# 3. Update the token
if changed > stayed:
j -= 1
if j == 0:
break
else:
raise ValueError('Failed to align')
return path[::-1]
path = backtrack(trellis, emission, tokens)
print(path)
```
### Visualization
```
def plot_trellis_with_path(trellis, path):
# To plot trellis with path, we take advantage of 'nan' value
trellis_with_path = trellis.clone()
for i, p in enumerate(path):
trellis_with_path[p.time_index, p.token_index] = float('nan')
plt.imshow(trellis_with_path[1:, 1:].T, origin='lower')
plot_trellis_with_path(trellis, path)
plt.title("The path found by backtracking")
plt.show()
```
Looking good. Now this path contains repetations for the same labels, so let’s merge them to make it close to the original transcript.
When merging the multiple path points, we simply take the average probability for the merged segments.
```
# Merge the labels
@dataclass
class Segment:
label: str
start: int
end: int
score: float
def __repr__(self):
return f"{self.label}\t({self.score:4.2f}): [{self.start:5d}, {self.end:5d})"
@property
def length(self):
return self.end - self.start
def merge_repeats(path):
i1, i2 = 0, 0
segments = []
while i1 < len(path):
while i2 < len(path) and path[i1].token_index == path[i2].token_index:
i2 += 1
score = sum(path[k].score for k in range(i1, i2)) / (i2 - i1)
segments.append(Segment(transcript[path[i1].token_index], path[i1].time_index, path[i2-1].time_index + 1, score))
i1 = i2
return segments
segments = merge_repeats(path)
for seg in segments:
print(seg)
```
### Visualization
```
def plot_trellis_with_segments(trellis, segments, transcript):
# To plot trellis with path, we take advantage of 'nan' value
trellis_with_path = trellis.clone()
for i, seg in enumerate(segments):
if seg.label != '|':
trellis_with_path[seg.start+1:seg.end+1, i+1] = float('nan')
plt.figure()
plt.title("Path, label and probability for each label")
ax1 = plt.axes()
ax1.imshow(trellis_with_path.T, origin='lower')
ax1.set_xticks([])
for i, seg in enumerate(segments):
if seg.label != '|':
ax1.annotate(seg.label, (seg.start + .7, i + 0.3))
ax1.annotate(f'{seg.score:.2f}', (seg.start - .3, i + 4.3))
plt.figure()
plt.title("Probability for each label at each time index")
ax2 = plt.axes()
xs, hs = [], []
for p in path:
label = transcript[p.token_index]
if label != '|':
xs.append(p.time_index + 1)
hs.append(p.score)
for seg in segments:
if seg.label != '|':
ax2.axvspan(seg.start+.4, seg.end+.4, color='gray', alpha=0.2)
ax2.annotate(seg.label, (seg.start + .8, -0.07))
ax2.bar(xs, hs, width=0.5)
ax2.axhline(0, color='black')
ax2.set_position(ax1.get_position())
ax2.set_xlim(ax1.get_xlim())
ax2.set_ylim(-0.1, 1.1)
plot_trellis_with_segments(trellis, segments, transcript)
plt.show()
```
Looks good. Now let’s merge the words. The Wav2Vec2 model uses ``'|'`` as the word boundary, so we merge the segments before each occurance of ``'|'``.
```
# Merge words
def merge_words(segments, separator='|'):
words = []
i1, i2 = 0, 0
while i1 < len(segments):
if i2 >= len(segments) or segments[i2].label == separator:
if i1 != i2:
segs = segments[i1:i2]
word = ''.join([seg.label for seg in segs])
score = sum(seg.score * seg.length for seg in segs) / sum(seg.length for seg in segs)
words.append(Segment(word, segments[i1].start, segments[i2-1].end, score))
i1 = i2 + 1
i2 = i1
else:
i2 += 1
return words
word_segments = merge_words(segments)
for word in word_segments:
print(word)
```
### Visualization
```
trellis_with_path = trellis.clone()
for i, seg in enumerate(segments):
if seg.label != '|':
trellis_with_path[seg.start+1:seg.end+1, i+1] = float('nan')
plt.imshow(trellis_with_path[1:, 1:].T, origin='lower')
ax1 = plt.gca()
ax1.set_yticks([])
ax1.set_xticks([])
for word in word_segments:
plt.axvline(word.start - 0.5)
plt.axvline(word.end - 0.5)
for i, seg in enumerate(segments):
if seg.label != '|':
plt.annotate(seg.label, (seg.start, i + 0.3))
plt.annotate(f'{seg.score:.2f}', (seg.start , i + 4), fontsize=8)
plt.show()
# The original waveform
ratio = waveform.size(1) / (trellis.size(0) - 1)
plt.plot(waveform[0])
for word in word_segments:
x0 = ratio * word.start
x1 = ratio * word.end
plt.axvspan(x0, x1, alpha=0.1, color='red')
plt.annotate(f'{word.score:.2f}', (x0, 0.8))
for seg in segments:
if seg.label != '|':
plt.annotate(seg.label, (seg.start * ratio, 0.9))
ax2 = plt.gca()
xticks = ax2.get_xticks()
plt.xticks(xticks, xticks / bundle.sample_rate)
plt.xlabel('time [second]')
ax2.set_position(ax1.get_position())
ax2.set_yticks([])
ax2.set_ylim(-1.0, 1.0)
ax2.set_xlim(0, waveform.size(-1))
plt.show()
# Generate the audio for each segment
print(transcript)
IPython.display.display(IPython.display.Audio(SPEECH_FILE))
for i, word in enumerate(word_segments):
x0 = int(ratio * word.start)
x1 = int(ratio * word.end)
filename = f"{i}_{word.label}.wav"
torchaudio.save(filename, waveform[:, x0:x1], bundle.sample_rate)
print(f"{word.label}: {x0 / bundle.sample_rate:.3f} - {x1 / bundle.sample_rate:.3f}")
IPython.display.display(IPython.display.Audio(filename))
```
| github_jupyter |
```
import pandas as pd
import random
```
### Read the data
```
movies_df = pd.read_csv('mymovies.csv')
ratings_df = pd.read_csv('myratings.csv')
```
### Select the data
The recommender system should avoid bias, for example, the recommender system should not recommend movie with just 1 rating which is also a 5-star rating. But should recommend movies with more ratings.
Therefore, we only take into account movies with at least 200 ratings and users who have at least rated 50 movies.
```
user_threshold = 50
movie_threshold = 200
filtered_users = ratings_df['user'].value_counts()>=user_threshold
filtered_users = filtered_users[filtered_users].index.tolist()
filtered_movies = ratings_df['item'].value_counts()>=movie_threshold
filtered_movies = filtered_movies[filtered_movies].index.tolist()
filtered_df = ratings_df[(ratings_df['user'].isin(filtered_users)) & (ratings_df['item'].isin(filtered_movies))]
display(filtered_df)
```
### Select a group of n random users
Here we let n = 5, we select 5 random users from the filtered dataset
```
#Select a random group of user
user_ids = filtered_df['user'].unique()
group_users_ids = random.sample(list(user_ids), 5)
group_users_ids
```
### Select rated and unrated movies for the given group
We now can get the rated movies all users in the groups, and from that, we can also get the unrated movies for the whole group of 5
```
selected_group_rating = ratings_df.loc[ratings_df['user'].isin(group_users_ids)]
group_rated_movies_ids = selected_group_rating['item'].unique()
group_unrated_movies_ids = set(movies_df['item']) - set(group_rated_movies_ids)
group_rated_movies_df = movies_df.loc[movies_df['item'].isin(group_rated_movies_ids)]
group_unrated_movies_df = movies_df.loc[movies_df['item'].isin(group_unrated_movies_ids)]
group_rated_movies_df
group_unrated_movies_df
```
### Calculate expected ratings for unrated movies
For each users, we need to calculate the expected ratings for the user's unrated movies. To calculate unrated ratings, we first need to train
an algorithm, here, the SVD algorithm from Surprise is used
```
from surprise import Reader, Dataset, SVD
from surprise.model_selection.validation import cross_validate
```
We perform 5-fold cross validation on the whole ratings dataset to see how well SVD will perform
```
reader = Reader()
data = Dataset.load_from_df(ratings_df[['user', 'item', 'rating']], reader)
svd = SVD()
cross_validate(svd, data, measures=['RMSE', 'MAE'], cv=5, verbose=True)
```
Next, We train the SVD model on the dataset
```
trainset = data.build_full_trainset()
svd = svd.fit(trainset)
def predict(user):
unrated_movies = list(group_unrated_movies_df['item'].unique())
pred = pd.DataFrame()
i = 0
for item in unrated_movies:
pred = pred.append({'user':user,'item': item, 'predicted_rating':svd.predict(user, item)[3]}, ignore_index=True)
return pred
users_rating = []
for user in group_users_ids:
prediction = predict(user)
prediction = prediction.sort_values('predicted_rating')
prediction = prediction.merge(movies_df, on= 'item')
users_rating.append(prediction[['user','item','title','predicted_rating']])
```
The algorithm will iterate through 5 users, for each user, it will calculate the predicted rating for each unrated movie. Then the algorithm combines the predicted ratings of 5 users into one big dataset, to perform aggregation calculation
```
final = pd.concat([df for df in users_rating], ignore_index = True)
final
```
### Additive Strategy
```
additive = final.copy()
additive= additive.groupby(['item','title']).sum()
additive = additive.sort_values(by="predicted_rating", ascending=False).reset_index()
additive
```
### Most Pleasure Strategy
```
most_pleasure = final.copy()
most_pleasure = final.copy()
most_pleasure= most_pleasure.groupby(['item','title']).max()
most_pleasure = most_pleasure.sort_values(by="predicted_rating", ascending=False).reset_index()
most_pleasure
```
### Least Misery Strategy
```
least_misery = final.copy()
least_misery = final.copy()
least_misery= least_misery.groupby(['item','title']).min()
least_misery = least_misery.sort_values(by="predicted_rating", ascending=False).reset_index()
least_misery
def fairness():
titles = []
for uid in group_users_ids:
data = final.loc[final['user'] == uid]
data = data.sort_values(by = 'predicted_rating', ascending = False).reset_index().iloc[0]['title']
titles.append([uid,data])
return titles
tt = fairness()
print(tt)
def gen_rec_and_explain():
most_pleasure = final.copy()
most_pleasure= most_pleasure.groupby(['item','title']).max()
most_pleasure = most_pleasure.sort_values(by="predicted_rating", ascending=False).reset_index()
most_pleasure_movie = most_pleasure.iloc[0:5]['title']
least_misery = final.copy()
least_misery= least_misery.groupby(['item','title']).min()
least_misery = least_misery.sort_values(by="predicted_rating", ascending=False).reset_index()
least_misery_movie = least_misery.iloc[0:5]['title']
additive = final.copy()
additive= additive.groupby(['item','title']).sum()
additive = additive.sort_values(by="predicted_rating", ascending=False).reset_index()
additive_movie = additive.iloc[0:5]['title']
fairnesss = fairness()
print("#FAIR")
for uid, title in fairnesss:
print("The movie {} is the most favorite movie of user {}".format(title, uid))
print("#ADD: ")
print("The movies: {} was recommended to you because they have highest additive rating within your group".format(list(additive_movie)))
print("#LEAST: ")
print("The movies: {} was recommended to you because they are everyones' preferences ".format(list(least_misery_movie)))
print("#MOST: ")
print("The movies: {} was recommended to you because they are the most loved".format(list(most_pleasure_movie)))
gen_rec_and_explain()
import itertools
from lenskit.algorithms import Recommender
from lenskit.algorithms.user_knn import UserUser
user_user = UserUser(15, min_nbrs=3) # Minimum (3) and maximum (15) number of neighbors to consider
recsys = Recommender.adapt(user_user)
recsys.fit(ratings_df)
group_unseen_df = pd.DataFrame(list(itertools.product(group_users_ids, group_unrated_movies_ids)), columns=['user', 'item'])
group_unseen_df['predicted_rating'] = recsys.predict(group_unseen_df)
group_unseen_df = group_unseen_df.loc[group_unseen_df['predicted_rating'].notnull()]
display(group_unseen_df)
group_unseen_df
group_unseen_df.groupby('item').sum()
additive_df = group_unseen_df.groupby('item').sum()
additive_df = additive_df.join(movies_df['title'], on='item')
additive_df = additive_df.sort_values(by="predicted_rating", ascending=False).reset_index()[['item', 'title', 'predicted_rating']]
display(additive_df.head(10))
additive_df = group_unseen_df.groupby('item').sum()
additive_df
movies_df.loc[movies_df['item'] == 177593]
```
| github_jupyter |
# Call stacks and recursion
In this notebook, we'll take a look at *call stacks*, which will provide an opportunity to apply some of the concepts we've learned about both stacks and recursion.
### What is a *call stack*?
When we use functions in our code, the computer makes use of a data structure called a **call stack**. As the name suggests, a *call stack* is a type of stack—meaning that it is a *Last-In, First-Out* (LIFO) data structure.
So it's a type of stack—but a stack of *what*, exactly?
Essentially, a *call stack* is a stack of *frames* that are used for the *functions* that we are calling. When we call a function, say `print_integers(5)`, a *frame* is created in memory. All the variables local to the function are created in this memory frame. And as soon as this frame is created, it's pushed onto the call stack.
The frame that lies at the top of the call stack is executed first. And as soon as the function finishes executing, this frame is discarded from the *call stack*.
### An example
Let's consider the following function, which simply takes two integers and returns their sum
```
def add(num_one, num_two):
output = num_one + num_two
return output
result = add(5, 7)
print(result)
```
Before understanding what happens when a function is executed, it is important to remind ourselves that whenever an expression such as `product = 5 * 7` is evaluated, the right hand side of the `=` sign is evaluted first. When the right-hand side is completely evaluated, the result is stored in the variable name mentioned in the left-hand side.
When Python executes line 1 in the previous cell (`result = add(5, 7)`), the following things happen in memory:
* A frame is created for the `add` function. This frame is then pushed onto the *call stack*. We do not have to worry about this because Python takes care of this for us.
* Next, the parameters `num_one` and `num_two` get the values `5` and `7`, respectively
If we run this code in Python tutor website [http://pythontutor.com/](http://pythontutor.com/) , we can get a nice visualization of what's happening "behind the scenes" in memory:
<img src='./stack-frame-resources/01.png'>
* Python then moves on to the first line of the function. The first line of the function is
output = num_one + num_two
Here an expression is being evaluated and the result is stored in a new variable. The expression here is sum of two numbers the result of which is stored in the variable `output`. We know that whenever an expression is evaluated, the right-hand side of the `= sign` is evaluated first. So, the numbers `5 and 7` will be added first.
* Once the right-hand side is completely evaluated, then the assignment operation happens i.e. now the result of `5 + 7` will be stored in the variable `output`.
<img src='./stack-frame-resources/02.png'>
* In the next line, we are returning this value.
return output
Python acknowledged this return statement.
<img src='./stack-frame-resources/03.png'>
* Now the last line of the function has been executed. Therefore, this function can now be discarded from the stack frame. Also, the right-hand side of the expression `result = add(5, 7)` has finished evaluation. Now, the result of this evaluation will be stored in the variable `result`.
<img src='./stack-frame-resources/04.png'>
Now the next question is how does this behave like a stack?
The answer is pretty simple. We know that a stack is a Last-In First-Out (LIFO) structure, meaning the latest element inserted in the stack is the first to be removed.
You can play more with such "behind-the-scenes" of code execution on the Python tutor website: http://pythontutor.com/
### Another example
Here's another example. Let's say we have a function `add()` which adds two integers and then prints a custom message for us using the `custom_print()` function.
```
def add(num_one, num_two):
output = num_one + num_two
custom_print(output, num_one, num_two)
return output
def custom_print(output, num_one, num_two):
print("The sum of {} and {} is: {}".format(num_one, num_two, output))
result = add(5, 7)
```
What happens "behind-the-scenes" when `add()` is called, as in `result = add(5, 7)`?
Feel free to play with this on the Python tutor website. Here are a few points which might help aid the understanding.
* We know that when add function is called using `result = add(5, 7)`, a frame is created in the memory for the `add()` function. This frame is then pushed onto the call stack.
* Next, the two numbers are added and their result is stored in the variable `output`.
* On the next line we have a new function call - `custom_print(output, num_one, num_two)`. It's obvious that a new frame should be created for this function call as well. You must have realized that this new frame is now pushed into the call stack.
* We also know that the function which is at the top of the call stack is the one which Python executes. So, our `custom_print(output, num_one, num_two)` will now be executed.
* Python executes this function and as soon as it is finished with execution, the frame for `custom_print(output, num_one, num_two)` is discarded. If you recall, this is the LIFO behavior that we have discussed while studying stacks.
* Now, again the frame for `add()` function is at the top. Python resumes operation just after the line where it had left and returns the `output`.
### Call Stack and Recursion
#### Problem Statement
Consider the following problem:
Given a positive integer `n`, write a function, `print_integers`, that uses recursion to print all numbers from `n` to `1`.
For example, if `n` is `4`, the function shuld print `4 3 2 1`.
If we use iteration, the solution to the problem is simple. We can simply start at `4` and use a loop to print all numbers till `1`. However, instead of using an interative approach, our goal is to solve this problem using recursion.
```
def print_integers(n):
# TODO: Complete the function so that it uses recursion to print all integers from n to 1
if n <= 0:
return
print(n)
print_integers(n - 1)
```
<span class="graffiti-highlight graffiti-id_0usbivt-id_8peifb7"><i></i><button>Show Solution</button></span>
```
print_integers(5)
```
Now let's consider what happens in the call stack when `print_integers(5)` is called.
* As expected, a frame will be created for the `print_integers()` function and pushed onto the call stack.
* Next, the parameter `n` gets the value `5`.
* Following this, the function starts executing. The base condition is checked. For `n = 5`, the base case is `False`, so we move forward and print the value of `n`.
* In the next line, `print_integers()` is called again. This time it is called with the argument `n - 1`. The value of `n` in the current frame is `5`. So this new function call takes place with value `4`. Again, a new frame is created. **Note that for every new call a new frame will be created.** This frame is pushed onto the top of the stack.
* Python now starts executing this frame. Again the base case is checked. It's `False` for `n = 4`. Following this, the `n` is printed and then `print_integers()` is called with argument `n - 1 = 3`.
* The process keeps on like this until we hit the base case. When `n <= 0`, we return from the frame without calling the function `print_integers()` again. Because we have returned from the function call, the frame is discarded from the call stack and the next frame resumes execution right after the line where we left off.
| github_jupyter |
# GLM: Logistic Regression
* This is a reproduction with a few slight alterations of [Bayesian Log Reg](http://jbencook.github.io/portfolio/bayesian_logistic_regression.html) by J. Benjamin Cook
* Author: Peadar Coyle and J. Benjamin Cook
* How likely am I to make more than $50,000 US Dollars?
* Exploration of model selection techniques too - I use WAIC to select the best model.
* The convenience functions are all taken from Jon Sedars work.
* This example also has some explorations of the features so serves as a good example of Exploratory Data Analysis and how that can guide the model creation/ model selection process.
```
%matplotlib inline
import pandas as pd
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
import seaborn
import warnings
warnings.filterwarnings('ignore')
from collections import OrderedDict
from time import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import fmin_powell
from scipy import integrate
import theano as thno
import theano.tensor as T
def run_models(df, upper_order=5):
'''
Convenience function:
Fit a range of pymc3 models of increasing polynomial complexity.
Suggest limit to max order 5 since calculation time is exponential.
'''
models, traces = OrderedDict(), OrderedDict()
for k in range(1,upper_order+1):
nm = 'k{}'.format(k)
fml = create_poly_modelspec(k)
with pm.Model() as models[nm]:
print('\nRunning: {}'.format(nm))
pm.glm.GLM.from_formula(fml, df, family=pm.glm.families.Normal())
traces[nm] = pm.sample(2000, chains=1, init=None, tune=1000)
return models, traces
def plot_traces(traces, retain=1000):
'''
Convenience function:
Plot traces with overlaid means and values
'''
ax = pm.traceplot(traces[-retain:], figsize=(12,len(traces.varnames)*1.5),
lines={k: v['mean'] for k, v in pm.summary(traces[-retain:]).iterrows()})
for i, mn in enumerate(pm.summary(traces[-retain:])['mean']):
ax[i,0].annotate('{:.2f}'.format(mn), xy=(mn,0), xycoords='data'
,xytext=(5,10), textcoords='offset points', rotation=90
,va='bottom', fontsize='large', color='#AA0022')
def create_poly_modelspec(k=1):
'''
Convenience function:
Create a polynomial modelspec string for patsy
'''
return ('income ~ educ + hours + age ' + ' '.join(['+ np.power(age,{})'.format(j)
for j in range(2,k+1)])).strip()
```
The [Adult Data Set](http://archive.ics.uci.edu/ml/datasets/Adult) is commonly used to benchmark machine learning algorithms. The goal is to use demographic features, or variables, to predict whether an individual makes more than \\$50,000 per year. The data set is almost 20 years old, and therefore, not perfect for determining the probability that I will make more than \$50K, but it is a nice, simple dataset that can be used to showcase a few benefits of using Bayesian logistic regression over its frequentist counterpart.
The motivation for myself to reproduce this piece of work was to learn how to use Odd Ratio in Bayesian Regression.
```
data = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data", header=None, names=['age', 'workclass', 'fnlwgt',
'education-categorical', 'educ',
'marital-status', 'occupation',
'relationship', 'race', 'sex',
'captial-gain', 'capital-loss',
'hours', 'native-country',
'income'])
data.head(10)
```
## Scrubbing and cleaning
We need to remove any null entries in Income.
And we also want to restrict this study to the United States.
```
data = data[~pd.isnull(data['income'])]
data[data['native-country']==" United-States"]
income = 1 * (data['income'] == " >50K")
age2 = np.square(data['age'])
data = data[['age', 'educ', 'hours']]
data['age2'] = age2
data['income'] = income
income.value_counts()
```
## Exploring the data
Let us get a feel for the parameters.
* We see that age is a tailed distribution. Certainly not Gaussian!
* We don't see much of a correlation between many of the features, with the exception of Age and Age2.
* Hours worked has some interesting behaviour. How would one describe this distribution?
```
g = seaborn.pairplot(data)
# Compute the correlation matrix
corr = data.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = seaborn.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
seaborn.heatmap(corr, mask=mask, cmap=cmap, vmax=.3,
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
```
We see here not many strong correlations. The highest is 0.30 according to this plot. We see a weak-correlation between hours and income
(which is logical), we see a slighty stronger correlation between education and income (which is the kind of question we are answering).
## The model
We will use a simple model, which assumes that the probability of making more than $50K
is a function of age, years of education and hours worked per week. We will use PyMC3
do inference.
In Bayesian statistics, we treat everything as a random variable and we want to know the posterior probability distribution of the parameters
(in this case the regression coefficients)
The posterior is equal to the likelihood $$p(\theta | D) = \frac{p(D|\theta)p(\theta)}{p(D)}$$
Because the denominator is a notoriously difficult integral, $p(D) = \int p(D | \theta) p(\theta) d \theta $ we would prefer to skip computing it. Fortunately, if we draw examples from the parameter space, with probability proportional to the height of the posterior at any given point, we end up with an empirical distribution that converges to the posterior as the number of samples approaches infinity.
What this means in practice is that we only need to worry about the numerator.
Getting back to logistic regression, we need to specify a prior and a likelihood in order to draw samples from the posterior. We could use sociological knowledge about the effects of age and education on income, but instead, let's use the default prior specification for GLM coefficients that PyMC3 gives us, which is $p(θ)=N(0,10^{12}I)$. This is a very vague prior that will let the data speak for themselves.
The likelihood is the product of n Bernoulli trials, $\prod^{n}_{i=1} p_{i}^{y} (1 - p_{i})^{1-y_{i}}$,
where $p_i = \frac{1}{1 + e^{-z_i}}$,
$z_{i} = \beta_{0} + \beta_{1}(age)_{i} + \beta_2(age)^{2}_{i} + \beta_{3}(educ)_{i} + \beta_{4}(hours)_{i}$ and $y_{i} = 1$ if income is greater than 50K and $y_{i} = 0$ otherwise.
With the math out of the way we can get back to the data. Here I use PyMC3 to draw samples from the posterior. The sampling algorithm used is NUTS, which is a form of Hamiltonian Monte Carlo, in which parameteres are tuned automatically. Notice, that we get to borrow the syntax of specifying GLM's from R, very convenient! I use a convenience function from above to plot the trace infromation from the first 1000 parameters.
```
with pm.Model() as logistic_model:
pm.glm.GLM.from_formula('income ~ age + age2 + educ + hours', data, family=pm.glm.families.Binomial())
trace_logistic_model = pm.sample(2000, chains=1, init=None, tune=1000)
plot_traces(trace_logistic_model, retain=1000)
```
## Some results
One of the major benefits that makes Bayesian data analysis worth the extra computational effort in many circumstances is that we can be explicit about our uncertainty. Maximum likelihood returns a number, but how certain can we be that we found the right number? Instead, Bayesian inference returns a distribution over parameter values.
I'll use seaborn to look at the distribution of some of these factors.
```
plt.figure(figsize=(9,7))
trace = trace_logistic_model[1000:]
seaborn.jointplot(trace['age'], trace['educ'], kind="hex", color="#4CB391")
plt.xlabel("beta_age")
plt.ylabel("beta_educ")
plt.show()
```
So how do age and education affect the probability of making more than $$50K?$ To answer this question, we can show how the probability of making more than $50K changes with age for a few different education levels. Here, we assume that the number of hours worked per week is fixed at 50. PyMC3 gives us a convenient way to plot the posterior predictive distribution. We need to give the function a linear model and a set of points to evaluate. We will pass in three different linear models: one with educ == 12 (finished high school), one with educ == 16 (finished undergrad) and one with educ == 19 (three years of grad school).
```
# Linear model with hours == 50 and educ == 12
lm = lambda x, samples: 1 / (1 + np.exp(-(samples['Intercept'] +
samples['age']*x +
samples['age2']*np.square(x) +
samples['educ']*12 +
samples['hours']*50)))
# Linear model with hours == 50 and educ == 16
lm2 = lambda x, samples: 1 / (1 + np.exp(-(samples['Intercept'] +
samples['age']*x +
samples['age2']*np.square(x) +
samples['educ']*16 +
samples['hours']*50)))
# Linear model with hours == 50 and educ == 19
lm3 = lambda x, samples: 1 / (1 + np.exp(-(samples['Intercept'] +
samples['age']*x +
samples['age2']*np.square(x) +
samples['educ']*19 +
samples['hours']*50)))
```
Each curve shows how the probability of earning more than $ 50K$ changes with age. The red curve represents 19 years of education, the green curve represents 16 years of education and the blue curve represents 12 years of education. For all three education levels, the probability of making more than $50K increases with age until approximately age 60, when the probability begins to drop off. Notice that each curve is a little blurry. This is because we are actually plotting 100 different curves for each level of education. Each curve is a draw from our posterior distribution. Because the curves are somewhat translucent, we can interpret dark, narrow portions of a curve as places where we have low uncertainty and light, spread out portions of the curve as places where we have somewhat higher uncertainty about our coefficient values.
```
# Plot the posterior predictive distributions of P(income > $50K) vs. age
pm.plot_posterior_predictive_glm(trace, eval=np.linspace(25, 75, 1000), lm=lm, samples=100, color="blue", alpha=.15)
pm.plot_posterior_predictive_glm(trace, eval=np.linspace(25, 75, 1000), lm=lm2, samples=100, color="green", alpha=.15)
pm.plot_posterior_predictive_glm(trace, eval=np.linspace(25, 75, 1000), lm=lm3, samples=100, color="red", alpha=.15)
import matplotlib.lines as mlines
blue_line = mlines.Line2D(['lm'], [], color='b', label='High School Education')
green_line = mlines.Line2D(['lm2'], [], color='g', label='Bachelors')
red_line = mlines.Line2D(['lm3'], [], color='r', label='Grad School')
plt.legend(handles=[blue_line, green_line, red_line], loc='lower right')
plt.ylabel("P(Income > $50K)")
plt.xlabel("Age")
plt.show()
b = trace['educ']
plt.hist(np.exp(b), bins=20, normed=True)
plt.xlabel("Odds Ratio")
plt.show()
```
Finally, we can find a credible interval (remember kids - credible intervals are Bayesian and confidence intervals are frequentist) for this quantity. This may be the best part about Bayesian statistics: we get to interpret credibility intervals the way we've always wanted to interpret them. We are 95% confident that the odds ratio lies within our interval!
```
lb, ub = np.percentile(b, 2.5), np.percentile(b, 97.5)
print("P(%.3f < O.R. < %.3f) = 0.95" % (np.exp(lb),np.exp(ub)))
```
## Model selection
One question that was immediately asked was what effect does age have on the model, and why should it be $age^2$ versus age? We'll run the model with a few changes to see what effect higher order terms have on this model in terms of WAIC.
```
models_lin, traces_lin = run_models(data, 4)
dfwaic = pd.DataFrame(index=['k1','k2','k3','k4'], columns=['lin'])
dfwaic.index.name = 'model'
for nm in dfwaic.index:
dfwaic.loc[nm, 'lin'] = pm.waic(traces_lin[nm],models_lin[nm])[0]
dfwaic = pd.melt(dfwaic.reset_index(), id_vars=['model'], var_name='poly', value_name='waic')
g = seaborn.factorplot(x='model', y='waic', col='poly', hue='poly', data=dfwaic, kind='bar', size=6)
```
WAIC confirms our decision to use age^2.
| github_jupyter |
```
import numpy
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Activation
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.utils import to_categorical
from keras import backend as K
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
import numpy as np
import pandas as pd
from sklearn import preprocessing
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import linear_model
from statistics import mean, stdev
from sklearn.preprocessing import scale
from keras.utils import to_categorical
from sklearn import metrics
SOXL = pd.read_csv('soxl_new.csv') #ETF growth cycle
TQQQ = pd.read_csv('tqqq_new.csv') #3X Index
MU = pd.read_csv('mu_new.csv') #high Beta
AMD = pd.read_csv('amd_new.csv') # high beta
NFLX = pd.read_csv('nflx_new.csv') #High growth
AMZN = pd.read_csv('amzn_new.csv') #High growth
V = pd.read_csv('visa_new.csv') #low volalitity
NVDA = pd.read_csv('nvda_new.csv') #high growth
NFLX['tar_3best_class'].unique()
features = ['Day_previous_roi','ma10','rsi10','ma20','rsi20','ma_chg20',
'ma60','rsi60','ma200','rsi200','obv','macd_diff','ma_chg10',
'macd_diff_hist','aroon_diff','slope60','r_sqr_60','ma_chg60',
'slope10','r_sqr_10','slope5','r_sqr_5','stDev20','ma_chg200',
'rsi_chg10','rsi_chg20','rsi_chg60','rsi_chg200',
'percent_down','sine','leadsine','tsf10','tsf20','tsf60','tsf200',
'up_dwn_prev','shawman','hammer','semi_pk_pr']
top_feats = ['ma200',
'macd_diff_hist',
'tsf200',
'r_sqr_60',
'slope60']#,
# 'macd_diff',
# 'tsf60',
# 'slope10',
# 'r_sqr_10',
# 'percent_down',
# 'rsi60',
# 'obv']
#Set stock or dataframe
df_cln = NFLX
target_name = 'tar_3best_class'
#.75 make a 25/75 split
stop = round(.80*len(df_cln))
#set features
features = df_cln[features].values
top_features = df_cln[top_feats].values
targets = df_cln[target_name].values
arr = []
end = targets.shape[0]
for i in range(end):
#print(targets[i])
if targets[i] == 'bel_1.02':
arr.append([1,0,0,0])
elif targets[i] == 'abv_1.02':
arr.append([0,1,0,0])
elif targets[i] == 'abv_1.04':
arr.append([0,0,1,0])
elif targets[i] == 'abv_1.07':
arr.append([0,0,0,1])
target_int = arr
feature_train = features[:stop]
feature_test = features[stop:]
top_feat_train = top_features[:stop]
top_feat_test = top_features[stop:]
target_test_int = target_int[stop:]
target_train_int = target_int[:stop]
#set my targets
# feature_train = np.array(feature_train)
# target_train = np.array(target_train)
# feature_test = np.array(feature_test)
# target_test = np.array(target_test)
feature_train.reshape(feature_train.shape[0],
feature_train.shape[1],
1).astype( 'float32' )
feature_test.reshape(feature_test.shape[0],
feature_test.shape[1],
1).astype( 'float32' )
#print(feature_train.shape,target_train.shape)
# from keras.utils.np_utils import to_categorical
# categorical_labels = to_categorical(target_int, num_classes=4)
# categorical_labels
#target_train_int
# # Standardize the train and test features
# scaled_train_features = scale(feature_train)
# scaled_test_features = scale(feature_test)
# # Create the model
# def baseline_model():
# model_1 = Sequential()
# model_1.add(Dense(200, input_dim=scaled_train_features.shape[1], activation='relu'))
# #model_1.add(Dropout(0.25))
# model_1.add(Dense(200, activation='relu'))
# #model_1.add(Dropout(0.25))
# model_1.add(Dense(100, activation='relu'))
# model_1.add(Dense(10, activation='relu'))
# model_1.add(Dense(4, activation='softmax'))
# model_1.compile(loss= 'categorical_crossentropy' ,
# optimizer= 'adam' ,
# metrics=[ 'accuracy' ])
# return model_1
# # Fit the model
# history = KerasClassifier(build_fn=baseline_model, epochs=40, batch_size=200, verbose=True)
# kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)
# results = cross_val_score(history,scaled_train_features , target_train, cv=kfold)
# print(results.mean())
# %matplotlib inline
# plt.plot(history.history['acc'],'b')
# plt.plot(history.history['val_acc'],'r')
# plt.show()
# model = baseline_model()
# model.fit(feature_train,target_train, epochs=40, verbose=2)
# target_test.unique()
# Standardize the train and test features
min_max_scaler = preprocessing.MinMaxScaler()
X_train = min_max_scaler.fit_transform(feature_train)
X_test = min_max_scaler.fit_transform(feature_test)
min_max_scaler = preprocessing.MinMaxScaler()
top_X_train = min_max_scaler.fit_transform(top_feat_train)
top_X_test = min_max_scaler.fit_transform(top_feat_test)
from keras.layers import Input, Dense, Dropout, BatchNormalization
from keras.models import Model, load_model
import keras.backend as K
from keras.callbacks import ModelCheckpoint
# Standardize the train and test features
K.clear_session()
target_test = np.array(target_test_int)
target_train = np.array(target_train_int)
# scaled_train_features = scale(feature_train)
# scaled_test_features = scale(feature_test)
# Create the model
K.clear_session()
inputs = Input(shape=(top_X_train.shape[1], ))
x1 = Dense(128)(inputs)
x1 = BatchNormalization()(x1)
x1 = Activation('relu')(x1)
x1 = Dropout(0.5)(x1)
# x2 = Dense(16, activation='relu')(x1)
# x2 = BatchNormalization()(x2)
# x2 = Activation('relu')(x2)
# x3 = Dense(16, activation='relu')(x2)
# x3 = BatchNormalization()(x3)
# x3 = Activation('relu')(x3)
# x4 = Dense(8, activation='relu')(x3)
# x4 = BatchNormalization()(x4)
# x4 = Activation('relu')(x4)
# x5 = Dense(16, activation='relu')(x4)
# x5 = BatchNormalization()(x5)
# x5 = Activation('relu')(x5)
# x6 = Dense(32, activation='relu')(x5)
# x6 = BatchNormalization()(x6)
# x6 = Activation('relu')(x6)
# x7 = Dense(64, activation='relu')(x6)
# x7 = BatchNormalization()(x7)
# x7 = Activation('relu')(x7)
x = Dense(4, activation='softmax')(x1)
checkpoint = ModelCheckpoint('3_layer_dense.h5',
monitor='val_loss',
save_best_only=True)
cb = [checkpoint]
# this compiles our model so it is ready to fit
model = Model(inputs, x)
model.compile(loss= 'categorical_crossentropy' ,
optimizer= 'adam' ,
metrics=[ 'accuracy' ])
model.summary()
2**7
#target_test = categorical_labels[stop:]
#target_train = categorical_labels[:stop]
# we actually fit the model here
history = model.fit(top_X_train,
target_train,
epochs=100,
validation_split=0.15,
callbacks=cb,
batch_size=200)
plt.plot(history.history['loss'], label = 'training loss')
plt.plot(history.history['val_loss'], label = 'validation loss')
plt.legend()
plt.show()
history = model.fit(top_X_train,
target_train,
epochs=100,
validation_split=0.15,
callbacks=cb,
batch_size=200)
target_pred = model.predict(top_X_test)
print("Accuracy:",metrics.accuracy_score(target_test_int, target_pred),'\n'
'Cohans Kappa:', metrics.cohen_kappa_score(target_test_int, target_pred),'\n'
'Train ACC:', metrics.accuracy_score(target_train_int, target_pred), '\n'
"Confusion Matrix:",'\n',
metrics.confusion_matrix(target_test, target_pred))
target_pred
target_train_int
targets = df_cln[target_name].values
targ_test = targets[stop:]
targ_train = targets[:stop]
targ_train[0:10]
history.predict_classes(feature_test)
top_X_train,
target_train,
epochs=100,
validation_split=0.15,
callbacks=cb,
batch_size=200
```
| github_jupyter |
```
import os
import sys
module_path = os.path.abspath('..')
sys.path.append(module_path)
from lc.measurements import CurveMeasurements
from lc.curve import LearningCurveEstimator
from omegaconf import OmegaConf
```
Load error measurements using `CurveMeasurements`. See `notebooks/measurements.ipynb` for more about reading error measurements.
```
curvems = CurveMeasurements()
curvems.load_from_json('../data/no_pretr_ft.json')
print(curvems)
```
Load default config. Modify `config.yaml` directly or update parameters once loaded.
```
cfg = OmegaConf.load('../lc/config.yaml')
print('-'*20)
print('Default config')
print('-'*20)
print(OmegaConf.to_yaml(cfg))
cfg.gamma_search = False
print('-'*20)
print('Modified config')
print('-'*20)
print(OmegaConf.to_yaml(cfg))
curve_estimator = LearningCurveEstimator(cfg)
curve, objective = curve_estimator.estimate(curvems)
print('Quality of the fit:',objective)
curve.print_summary(cfg.N)
```
Searching for gamma leads to better fit. To enable gamma search set `gamma_search` to `True` (default). When gamma search is disabled, `curve_estimator.estimate()` uses `cfg.gamma` to estimate the curve.
```
cfg.gamma_search = True
curve, objective = curve_estimator.estimate(curvems)
print('Quality of the fit:',objective)
curve.print_summary(cfg.N)
```
Use `curve_estimator.plot()` to visualizes the learning curve and the error measurements.
```
curve_estimator.plot(curve,curvems,label='No Pretr; Ft')
```
You may also want to visualize the variance estimates. We recommend using the smoothed variance estimate but you can switch to using sample variance for curve estimation by setting `cfg.variance_type='sample'`. See `notebooks/variance.ipynb` for details on smooth variance estimation.
```
curve_estimator.err_mean_var_estimator.visualize(curvems)
```
Plot multiple curves for easy comparison.
```
plot_metadata = [
['../data/no_pretr_linear.json','No Pretr; Lin','r','--'],
['../data/no_pretr_ft.json','No Pretr; Ft','g','-'],
['../data/pretr_linear.json','Pretr; Lin','b','--'],
['../data/pretr_ft.json','Pretr; Ft','m','-']
]
for (json_path,label,color,linestyle) in plot_metadata:
curvems.load_from_json(json_path)
curve, _ = curve_estimator.estimate(curvems)
curve_estimator.plot(curve,curvems,label,color,linestyle)
```
## What if you don't have all recommended error measurements?
Technically, it is possible to use just 2 training set sizes to estimate the learning curve but the results may be susceptible to high variance. For instance, here we estimate the learning curve using only measurements on training set sizes of 400 and 200. Note that below, we plot all error measurements and not just the ones used to estimate the curve.
```
import copy
for (json_path,label,color,linestyle) in plot_metadata:
curvems.load_from_json(json_path)
curvems_filtered = copy.deepcopy(curvems)
curvems_filtered.curvems = [errms for errms in curvems if errms.num_train_samples in [400,200]]
curve, _ = curve_estimator.estimate(curvems_filtered)
curve_estimator.plot(curve,curvems,label,color,linestyle)
```
However, results improve considerably when using 3 training set sizes. Below, we estimate learning curve using measurements on training sets of sizes 400, 200, and 100.
```
for (json_path,label,color,linestyle) in plot_metadata:
curvems.load_from_json(json_path)
curvems_filtered = copy.deepcopy(curvems)
curvems_filtered.curvems = [errms for errms in curvems if errms.num_train_samples in [400,200,100]]
curve, _ = curve_estimator.estimate(curvems_filtered)
curve_estimator.plot(curve,curvems,label,color,linestyle)
```
It may be possible to use much smaller training set sizes to compute learning curves as shown below. Note that the errors predicted by the curve at 200 and 400 training set sizes, which were not used to estimate the curve, are reasonably accurate.
```
for (json_path,label,color,linestyle) in plot_metadata:
curvems.load_from_json(json_path)
curvems_filtered = copy.deepcopy(curvems)
curvems_filtered.curvems = [errms for errms in curvems if errms.num_train_samples in [100,50,25]]
curve, _ = curve_estimator.estimate(curvems_filtered)
curve_estimator.plot(curve,curvems,label,color,linestyle)
```
## Quick and Lazy Approach
It is possible to compute a decent learning curve with only 3 error measurments - 1 for each of full, half, and quarter dataset sizes. In this case, simply set `cfg.v_1` to a reasonable value and proceed as before. This is our recommended approach if you are in a rush. See `notebooks/basic_lazy_usage.ipynb` for more details on this quick and lazy approach.
```
cfg.v_1 = 10
for (json_path,label,color,linestyle) in plot_metadata:
curvems.load_from_json(json_path)
curvems_filtered = copy.deepcopy(curvems)
curvems_filtered.curvems = [errms for errms in curvems if errms.num_train_samples in [400,200,100]]
for errms in curvems_filtered:
# Through away all but 1 error measurment per train set size
errms.test_errors = [errms.test_errors[0]]
errms.num_ms = 1
curve, _ = curve_estimator.estimate(curvems_filtered)
curve_estimator.plot(curve,curvems,label,color,linestyle)
```
| github_jupyter |
# Exercises
## Playing with the interpreter
Try to execute some simple statements and expressions (one at a time) e.g
```
print("Hello!")
1j**2
1 / 2
1 // 2
5 + 5
10 / 2 + 5
my_tuple = (1, 2, 3)
my_tuple[0] = 1
2.3**4.5
```
Do you understand what is going on in all cases?
Most Python functions and objects can provide documentation via **help** function. Look the documentation of e.g open function with ```help(open)```
Play with tabulator completion, by typing just ```pr``` and pressing then tabulator key. Pressing Shift-tab (after finalising completion) one sees also short documentation about the function or object. This works also on variable names, try e.g.
```
my_extremely_long_variable_name = 5
my <TAB>
```
## Basic syntax
Try to assign the value 6 to the following variable names
````
first-name
family_name
3PO
____variable
inb4tool8
print
in
```
Which of them are valid to assign to?
Extra: why do you think the ones that cause an error are not valid? What's the reason?
You probably noticed that even though ``print`` is a method in the namespace it was still valid to create a variable called ``print``. If you now try to actually print something, you will get an error. For built-in functions (such as print) one can recover with the following code
```
print = __builtin__.print
print("hello")
```
Are the following pieces valid Python code?
** Case 1 **
```
numbers = [4, 5, 6, 9, 11]
sum = 0
for n in numbers:
sum += n
print("Sum is now"), sum
```
** Case 2 **
```
x = 11
test(x)
def test(a):
if a < 0:
print("negative number")
```
## Tuples and lists
1. Create a tuple called ``mytuple``, with the following strings: "sausage", "eggs" and "bacon"
2. check it's type using ``type()``
3. Create than a list called ``mylist`` with the same contents. You use can the normal list definition syntax (``[]``) or coerce it from the tuple with the ``list()`` function.
Attempt to append the string "spam"
to ``mylist`` and ``mytuple`` using ``append``.
List objects have a sort()
function, use that for sorting the list alphabetically (e.g.
mylist.sort() ). What is now the first item of the list?
Next, remove the first item from the list, investigate the contents and remove then last item from the list.
### Slicing
Using ``range()`` create a list that has the numbers from 50 to 0 with a step of -2. Note that in Python 3 ``range()`` returns an *iterator* (we'll discuss iterators more later on), ``list(range(args))`` returns an actual list.
Using slicing syntax, select
* the last 4 items from the list
* the items from index 10 to index 13
* the first 5 items from the list
Read up on the [stride syntax](https://en.wikipedia.org/wiki/Array_slicing#1991:_Python) . Then using it select
* every third value in the list
* the values with an odd-numbered index in the list
### Multidimensional lists
Create a two dimensional list of (x,y) value pairs, i.e.
arbitrary long list whose elements are two element lists.
Are you able to use slicing for extracting only the y values? (Answer is no, but try it in any case)
## Dictionaries
Create a dictionary whose keys are the fruits “pineapple”, “strawberry”, and “banana”. As values use numbers
representing e.g. prices.
Add “orange” to the dictionary and then remove “banana” from the dictionary. Investigate the contents of dictionary and pay attention to the order of key-value pairs.
# Bonus exercises
Create a new “fruits” dictionary where the values are also
dictionaries containing key-value pairs for color and weight,
e.g.
```
fruits['apple'] = {'color':'green', 'weight': 120}
```
Change the color of *apple* from green to red
It is often useful idiom to create empty lists or dictionaries
and add contents little by little.
Create first an empty dictionary for a mid-term grades of
students. Then, add a key-value pairs where the keys are
student names and the values are empty lists.
Finally, add values to the lists and investigate the contents of the
dictionary.
| github_jupyter |
**_Privacy and Confidentiality Exercises_**
This notebook shows you how to prepare your results for export and what you have to keep in mind in general when you want to export output. You will learn how to prepare files for export so they meet our export requirements.
```
# Load packages
%pylab inline
from __future__ import print_function
import os
import pandas as pd
import numpy as np
import psycopg2
import matplotlib.pyplot as plt
%matplotlib inline
matplotlib.style.use('ggplot')
```
# General Remarks on Disclosure Review
This notebook provides you with information on how to prepare research output for disclosure control. It outlines how to prepare different kind of outputs before submitting an export request and gives you an overview of the information needed for disclosure review.
## Files you can export
In general you can export any kind of file format. However, most research results that researchers typically export are tables, graphs, regression output and aggregated data. Thus, we ask you to export one of these types which implies that every result you would like to export needs to be saved in either .csv, .txt or graph format.
## Jupyter notebooks are only exported to retrieve code
Unfortunately, you can't export results in a jupyter notebook. Doing disclosure reviews on output in jupyter notebooks is too burdensome for us. Jupyter notebooks will only be exported when the output is deleted for the purpose of exporting code. This does not mean that you won't need your jupyter notebooks during the export process.
## Documentation of code is important
During the export process we ask you to provide the code for every output you are asking to export. It is important for ADRF staff to have the code to better understand what you exactly did. Understanding how research results are created is important to understand your research output. Thus, it is important to document every single step of your analysis in your jupyter notebook.
## General rules to keep in mind
A more detailed description of the rules for exporting results can be found on the class website. This is just a quick overview. We recommend that you to go to the class website and read the entire guidelines before you prepare your files for export.
- The disclosure review is based on the underlying observations of your study. Every statistic you want to export should be based on at least 10 individual data points
- Document your code so the reviewer can follow your data work. Assessing re-identification risks highly depends on the context. Thus it is important that you provide context info with your anlysis for the reviewer
- Save the requested output with the corresponding code in you input and output folder. Make sure the code is executable. The code should exactly produce the output you requested
- In case you are exporting powerpoint slides that show project results you have to provide the code which produces the output in the slide
- Please export results only when there are final and you need them for your presentation or final projcet report
# Disclosure Review Walkthrough
We will IL DES data and MO DES to construct our statistics we are interested in, and prepare it in a way so we can submit the output for disclosure review.
```
# get working directory
mypath = (os.getcwd())
print(mypath)
# connect to database
db_name = "appliedda"
hostname = "10.10.2.10"
conn = psycopg2.connect(database=db_name, host = hostname)
```
## pull data
In this example we will use the workers who had a job in both MO and IL at some point over the course of our datasets (2005-2016)
```
# Get data
query = """
SELECT *, il_wage + mo_wage AS earnings
FROM ada_18_uchi.il_mo_overlap_by_qtr
WHERE year = 2011
AND quarter IN (2,3)"""
# Save query in dataframe
df = pd.read_sql( query, con = conn )
# Check dataframe
df.head()
# another way to check dataframe
df.info()
# basic stats of
df.describe()
# let's add an earnings categorization for "low", "mid" and "high" using a simple function
def earn_calc(earn):
if earn < 16500:
return('low')
elif earn < 45000:
return('mid')
else:
return('high')
earn_calc(24000)
df['earn_cat'] = df['earnings'].apply(lambda x: earn_calc(x))
```
We now have loaded the data that we need to generate some basic statistics about our populations we want to compare
```
# Let's look at some first desccriptives by group
grouped = df.groupby('earn_cat')
grouped.describe()
grouped.describe().T
```
Statistics in this table will be released if the statistic is based on at least 10 entities (in this example individuals). We can see that the total number of individuals we observe in each group completely satisfies this (see cell count). However, we also report percentiles, and we report the minimum and maximum value. Especially the minimum and maximum value are most likely representing one individual person.
Thus, during disclosure review these values will be supressed.
```
# Now let's export the statistics. Ideally we want to have a csv file
# We can safe the statistics in a dataframe
export1 = grouped.describe()
# and then print to csv
export1.to_csv('descriptives_by_group.csv')
```
### Reminder: Export of Statistics
You can save any dataframe as a csv file and export this csv file. The only thing you have to keep in mind is that besides the statistic X you are interested in you have to include a variable count of X so we can see on how many observations the statistic is based on. This also applies if you aggregate data. For example if you agregate by benefit type, we need to know how many observations are in each benefit program (because after the aggregation each benefit type will be only one data point).
### Problematic Output
Some subgroups (eg for some of the Illinois datasets dealing with race and gender) will result in cell sizes representing less than 10 people.
Tables with cells representing less than 10 individuals won't be released. In this case, disclosure review would mean to delete all cells with counts of less than 10. In addition, secondary suppression has to take place. The disclosure reviewer has to delete as many cells as needed to make it impossible to recalculate the suppressed values.
### How to do it better
Instead of asking for export of a tables like this, you should prepare your tables in advance that all cell sizes are at least represented by a minimum of 10 observations.
### Reminder: Export of Tables
For tables of any kind you need to provide the underlying counts of the statistics presented in the table. Make sure you provide all counts. If you calculate ratios, for example employment rates you need to provide the count of individuals who are employed and the count of the ones who are not. If you are interested in percentages we still need the underlying counts for disclosure review. Please label the table in a way that we can easily understand what you are plotting.
```
df[['il_flag', 'mo_flag']].describe(percentiles = [.5, .9, .99, .999])
# for this example let's cap the job counts to 5
df['il_flag'] = df['il_flag'].apply(lambda x: x if x < 5 else 5)
df['mo_flag'] = df['mo_flag'].apply(lambda x: x if x < 5 else 5)
# Let's say we are interested in plotting parts of the crosstabulation as a graph, for example benefit type and race
# First we need to calulate the counts
graph = df.groupby(['earn_cat', 'il_flag'])['ssn'].count()
# Note: we need to add the unstack command here because our dataframe has nested indices.
# We need to flatten out the data before plotting the graph
print(graph)
print(graph.unstack())
# Now we can generate the graph
mygraph = graph.unstack().plot(kind='bar')
```
In this graph it is not clearly visible how many observations are in each bar. Thus we either have to provide a corresponding table (as we generated earlier), or we can use the table=True option to add a table of counts to the graph. In addition, we wnat to make sure that all our axes and legend are labeled properly.
```
# Graphical representation including underlying values: the option table=True displays the underlying counts
mygraph = graph.unstack().plot(kind='bar', table=True, figsize=(7,5), fontsize=7)
# Adjust legend and axes
mygraph.legend(["Unknown","1", "2", "3", "4", '5'], loc = 1, ncol= 3, fontsize=9)
mygraph.set_ylabel("Number of Observations", fontsize=9)
# Add table with counts
# We don't need an x axis if we display table
mygraph.axes.get_xaxis().set_visible(False)
# Grab table info
table = mygraph.tables[0]
# Format table and figure
table.set_fontsize(9)
```
> in this example there is a problematic value, we will instead cap to 4 maximum jobs to ensure all cells are more than 10
```
# for this example let's cap the job counts to 5
df['il_flag'] = df['il_flag'].apply(lambda x: x if x < 4 else 4)
df['mo_flag'] = df['mo_flag'].apply(lambda x: x if x < 4 else 4)
# create our new "graph" dataframe to plot with
graph = df.groupby(['earn_cat', 'il_flag'])['ssn'].count()
# confirm we solved the issue
mygraph = graph.unstack().plot(kind='bar', table=True, figsize=(7,5), fontsize=7)
# Adjust legend and axes
mygraph.legend(["Unknown","1", "2", "3", "4", '5'], loc = 1, ncol= 3, fontsize=9)
mygraph.set_ylabel("Number of Observations", fontsize=9)
# Add table with counts
# We don't need an x axis if we display table
mygraph.axes.get_xaxis().set_visible(False)
# Grab table info
table = mygraph.tables[0]
# Format table and figure
table.set_fontsize(9)
# We want to export the graph without the table though
# Because we already generated the crosstab earlier which shows the counts
mygraph = graph.unstack().plot(kind='bar', figsize=(7,5), fontsize=7, rot=0)
# Adjust legend and axes
mygraph.legend(["Unknown","1", "2", "3", "4", '5'], loc = 1, ncol= 3, fontsize=9)
mygraph.set_ylabel("Number of Observations", fontsize=9)
mygraph.set_xlabel("Income category", fontsize=9)
mygraph.annotate('Source: IL & MO DES', xy=(0.7,-0.2), xycoords="axes fraction");
# Now we can export the graph as pdf
# Save plot to file
export2 = mygraph.get_figure()
export2.set_size_inches(15,10, forward=True)
export2.savefig('barchart_jobs_income_category.pdf', bbox_inches='tight', dpi=300)
```
### Reminder: Export of Graphs
It is important that every point which is plotted in a graph is based on at least 10 observations. Thus scatterplots for example cannot be released. In case you are interested in a histogram you have to change the bin size to make sure that every bin contains at least 10 people. In addition to the graph you have to provide the ADRF with the underlying table in a .csv or .txt file. This file should have the same name as the graph so ADRF can directly see which files go together. Alternatively you can include the counts in the graph as shown in the example above.
| github_jupyter |
# Logistic Regression with Hyperparameter Optimization (scikit-learn)
<a href="https://colab.research.google.com/github/VertaAI/modeldb/blob/master/client/workflows/examples-without-verta/notebooks/sklearn-census.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
## Imports
```
import warnings
from sklearn.exceptions import ConvergenceWarning
warnings.filterwarnings("ignore", category=ConvergenceWarning)
import itertools
import time
import numpy as np
import pandas as pd
from sklearn import model_selection
from sklearn import linear_model
from sklearn import metrics
```
---
## Prepare Data
```
try:
import wget
except ImportError:
!pip install wget # you may need pip3
import wget
train_data_url = "http://s3.amazonaws.com/verta-starter/census-train.csv"
train_data_filename = wget.download(train_data_url)
test_data_url = "http://s3.amazonaws.com/verta-starter/census-test.csv"
test_data_filename = wget.download(test_data_url)
df_train = pd.read_csv("census-train.csv")
X_train = df_train.iloc[:,:-1].values
y_train = df_train.iloc[:, -1]
df_train.head()
```
## Prepare Hyperparameters
```
hyperparam_candidates = {
'C': [1e-4, 1e-1, 1, 10, 1e3],
'solver': ['liblinear', 'lbfgs'],
'max_iter': [15, 28],
}
# total models 20
# create hyperparam combinations
hyperparam_sets = [dict(zip(hyperparam_candidates.keys(), values))
for values
in itertools.product(*hyperparam_candidates.values())]
```
## Run Validation
```
# create validation split
(X_val_train, X_val_test,
y_val_train, y_val_test) = model_selection.train_test_split(X_train, y_train,
test_size=0.2,
shuffle=True)
def run_experiment(hyperparams):
# create and train model
model = linear_model.LogisticRegression(**hyperparams)
model.fit(X_train, y_train)
# calculate and log validation accuracy
val_acc = model.score(X_val_test, y_val_test)
print(hyperparams, end=' ')
print("Validation accuracy: {:.4f}".format(val_acc))
# NOTE: run_experiment() could also be defined in a module, and executed in parallel
for hyperparams in hyperparam_sets:
run_experiment(hyperparams)
```
## Pick the best hyperparameters and train the full data
```
best_hyperparams = {}
model = linear_model.LogisticRegression(multi_class='auto', **best_hyperparams)
model.fit(X_train, y_train)
```
## Calculate Accuracy on Full Training Set
```
train_acc = model.score(X_train, y_train)
print("Training accuracy: {:.4f}".format(train_acc))
```
---
| github_jupyter |
# Other widget libraries
We would have loved to show you everything the Jupyter Widgets ecosystem has to offer today, but we are blessed to have such an active community of widget creators and unfortunately can't fit all widgets in a single session, no matter how long.
This notebook lists some of the widget libraries we wanted to demo but did not have enough time to include in the session. Enjoy!
# ipyleaflet: Interactive maps
## A Jupyter - LeafletJS bridge
## https://github.com/jupyter-widgets/ipyleaflet
ipyleaflet is a jupyter interactive widget library which provides interactive maps to the Jupyter notebook.
- MIT Licensed
**Installation:**
```bash
conda install -c conda-forge ipyleaflet
```
```
from ipywidgets import Text, HTML, HBox
from ipyleaflet import GeoJSON, WidgetControl, Map
import json
m = Map(center = (43,-100), zoom = 4)
geo_json_data = json.load(open('us-states-density-colored.json'))
geojson = GeoJSON(data=geo_json_data, hover_style={'color': 'black', 'dashArray': '5, 5', 'weight': 2})
m.add_layer(geojson)
html = HTML('''
<h4>US population density</h4>
Hover over a state
''')
html.layout.margin = '0px 20px 20px 20px'
control = WidgetControl(widget=html, position='topright')
m.add_control(control)
def update_html(properties, **kwargs):
html.value = '''
<h4>US population density</h4>
<h2><b>{}</b></h2>
{} people / mi^2
'''.format(properties['name'], properties['density'])
geojson.on_hover(update_html)
m
```
# pythreejs: 3D rendering in the browser
## A Jupyter - threejs bridge
## https://github.com/jupyter-widgets/pythreejs
Pythreejs is a jupyter interactive widget bringing fast WebGL 3d visualization to the Jupyter notebook.
- Originally authored by Jason Grout, currently maintained by Vidar Tonaas Fauske
- BSD Licensed
Pythreejs is *not* a 3d plotting library, it only exposes the threejs scene objects to the Jupyter kernel.
**Installation:**
```bash
conda install -c conda-forge pythreejs
```
```
from pythreejs import *
import numpy as np
from IPython.display import display
from ipywidgets import HTML, Text, Output, VBox
from traitlets import link, dlink
# Generate surface data:
view_width = 600
view_height = 400
nx, ny = (20, 20)
xmax=1
x = np.linspace(-xmax, xmax, nx)
y = np.linspace(-xmax, xmax, ny)
xx, yy = np.meshgrid(x, y)
z = xx ** 2 - yy ** 2
#z[6,1] = float('nan')
# Generate scene objects from data:
surf_g = SurfaceGeometry(z=list(z[::-1].flat),
width=2 * xmax,
height=2 * xmax,
width_segments=nx - 1,
height_segments=ny - 1)
surf = Mesh(geometry=surf_g,
material=MeshLambertMaterial(map=height_texture(z[::-1], 'YlGnBu_r')))
surfgrid = SurfaceGrid(geometry=surf_g, material=LineBasicMaterial(color='black'),
position=[0, 0, 1e-2]) # Avoid overlap by lifting grid slightly
# Set up picking bojects:
hover_point = Mesh(geometry=SphereGeometry(radius=0.05),
material=MeshLambertMaterial(color='green'))
click_picker = Picker(controlling=surf, event='dblclick')
hover_picker = Picker(controlling=surf, event='mousemove')
# Set up scene:
key_light = DirectionalLight(color='white', position=[3, 5, 1], intensity=0.4)
c = PerspectiveCamera(position=[0, 3, 3], up=[0, 0, 1], aspect=view_width / view_height,
children=[key_light])
scene = Scene(children=[surf, c, surfgrid, hover_point, AmbientLight(intensity=0.8)])
renderer = Renderer(camera=c, scene=scene,
width=view_width, height=view_height,
controls=[OrbitControls(controlling=c), click_picker, hover_picker])
# Set up picking responses:
# Add a new marker when double-clicking:
out = Output()
def f(change):
value = change['new']
with out:
print('Clicked on %s' % (value,))
point = Mesh(geometry=SphereGeometry(radius=0.05),
material=MeshLambertMaterial(color='hotpink'),
position=value)
scene.add(point)
click_picker.observe(f, names=['point'])
# Have marker follow picker point:
link((hover_point, 'position'), (hover_picker, 'point'))
# Show picker point coordinates as a label:
h = HTML()
def g(change):
h.value = 'Green point at (%.3f, %.3f, %.3f)' % tuple(change['new'])
h.value += ' Double-click to add marker'
g({'new': hover_point.position})
hover_picker.observe(g, names=['point'])
display(VBox([h, renderer, out]))
```
# bqplot: complex interactive visualizations
## https://github.com/bloomberg/bqplot
## A Jupyter - d3.js bridge
bqplot is a jupyter interactive widget library bringing d3.js visualization to the Jupyter notebook.
- Apache Licensed
bqplot implements the abstractions of Wilkinson’s “The Grammar of Graphics” as interactive Jupyter widgets.
bqplot provides both
- high-level plotting procedures with relevant defaults for common chart types,
- lower-level descriptions of data visualizations meant for complex interactive visualization dashboards and applications involving mouse interactions and user-provided Python callbacks.
**Installation:**
```bash
conda install -c conda-forge bqplot
```
```
import numpy as np
import bqplot as bq
xs = bq.LinearScale()
ys = bq.LinearScale()
x = np.arange(100)
y = np.cumsum(np.random.randn(2, 100), axis=1) #two random walks
line = bq.Lines(x=x, y=y, scales={'x': xs, 'y': ys}, colors=['red', 'green'])
xax = bq.Axis(scale=xs, label='x', grid_lines='solid')
yax = bq.Axis(scale=ys, orientation='vertical', tick_format='0.2f', label='y', grid_lines='solid')
fig = bq.Figure(marks=[line], axes=[xax, yax], animation_duration=1000)
display(fig)
# update data of the line mark
line.y = np.cumsum(np.random.randn(2, 100), axis=1)
```
# ipympl: The Matplotlib Jupyter Widget Backend
## https://github.com/matplotlib/ipympl
Enabling interaction with matplotlib charts in the Jupyter notebook and JupyterLab
- BSD-3-Clause
**Installation:**
```bash
conda install -c conda-forge ipympl
```
Enabling the `widget` backend. This requires ipympl. ipympl can be install via pip or conda.
```
%matplotlib widget
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import VBox, FloatSlider
```
When using the `widget` backend from ipympl, fig.canvas is a proper Jupyter interactive widget, which can be embedded in Layout classes like HBox and Vbox.
One can bound figure attributes to other widget values.
```
plt.ioff()
plt.clf()
slider = FloatSlider(
value=1.0,
min=0.02,
max=2.0
)
fig1 = plt.figure(1)
x1 = np.linspace(0, 20, 500)
lines = plt.plot(x1, np.sin(slider.value * x1))
def update_lines(change):
lines[0].set_data(x1, np.sin(change.new * x1))
fig1.canvas.draw()
fig1.canvas.flush_events()
slider.observe(update_lines, names='value')
VBox([slider, fig1.canvas])
```
# ipytree: Interactive tree view based on ipywidgets
## https://github.com/QuantStack/ipytree/
ipytree is a jupyter interactive widget library which provides a tree widget to the Jupyter notebook.
- MIT Licensed
**Installation:**
```bash
conda install -c conda-forge ipytree
```
## Create a tree
```
from ipywidgets import Text, link
from ipytree import Tree, Node
tree = Tree()
tree.add_node(Node('node1'))
node2 = Node('node2')
tree.add_node(node2)
tree
node3 = Node('node3', disabled=True)
node4 = Node('node4')
node5 = Node('node5', [Node('1'), Node('2')])
node2.add_node(node3)
node2.add_node(node4)
node2.add_node(node5)
```
| github_jupyter |
```
from IPython import display
from torch.utils.data import DataLoader
from torchvision import transforms, datasets
from utils import Logger
import tensorflow as tf
import numpy as np
DATA_FOLDER = './tf_data/VGAN/MNIST'
IMAGE_PIXELS = 28*28
NOISE_SIZE = 100
BATCH_SIZE = 100
def noise(n_rows, n_cols):
return np.random.normal(size=(n_rows, n_cols))
def xavier_init(size):
in_dim = size[0] if len(size) == 1 else size[1]
stddev = 1. / np.sqrt(float(in_dim))
return tf.random_uniform(shape=size, minval=-stddev, maxval=stddev)
def images_to_vectors(images):
return images.reshape(images.shape[0], 784)
def vectors_to_images(vectors):
return vectors.reshape(vectors.shape[0], 28, 28, 1)
```
## Load Data
```
def mnist_data():
compose = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((.5, .5, .5), (.5, .5, .5))
])
out_dir = '{}/dataset'.format(DATA_FOLDER)
return datasets.MNIST(root=out_dir, train=True, transform=compose, download=True)
# Load data
data = mnist_data()
# Create loader with data, so that we can iterate over it
data_loader = DataLoader(data, batch_size=BATCH_SIZE, shuffle=True)
# Num batches
num_batches = len(data_loader)
```
## Initialize Graph
```
## Discriminator
# Input
X = tf.placeholder(tf.float32, shape=(None, IMAGE_PIXELS))
# Layer 1 Variables
D_W1 = tf.Variable(xavier_init([784, 1024]))
D_B1 = tf.Variable(xavier_init([1024]))
# Layer 2 Variables
D_W2 = tf.Variable(xavier_init([1024, 512]))
D_B2 = tf.Variable(xavier_init([512]))
# Layer 3 Variables
D_W3 = tf.Variable(xavier_init([512, 256]))
D_B3 = tf.Variable(xavier_init([256]))
# Out Layer Variables
D_W4 = tf.Variable(xavier_init([256, 1]))
D_B4 = tf.Variable(xavier_init([1]))
# Store Variables in list
D_var_list = [D_W1, D_B1, D_W2, D_B2, D_W3, D_B3, D_W4, D_B4]
## Generator
# Input
Z = tf.placeholder(tf.float32, shape=(None, NOISE_SIZE))
# Layer 1 Variables
G_W1 = tf.Variable(xavier_init([100, 256]))
G_B1 = tf.Variable(xavier_init([256]))
# Layer 2 Variables
G_W2 = tf.Variable(xavier_init([256, 512]))
G_B2 = tf.Variable(xavier_init([512]))
# Layer 3 Variables
G_W3 = tf.Variable(xavier_init([512, 1024]))
G_B3 = tf.Variable(xavier_init([1024]))
# Out Layer Variables
G_W4 = tf.Variable(xavier_init([1024, 784]))
G_B4 = tf.Variable(xavier_init([784]))
# Store Variables in list
G_var_list = [G_W1, G_B1, G_W2, G_B2, G_W3, G_B3, G_W4, G_B4]
def discriminator(x):
l1 = tf.nn.dropout(tf.nn.leaky_relu(tf.matmul(x, D_W1) + D_B1, .2), .3)
l2 = tf.nn.dropout(tf.nn.leaky_relu(tf.matmul(l1, D_W2) + D_B2, .2), .3)
l3 = tf.nn.dropout(tf.nn.leaky_relu(tf.matmul(l2, D_W3) + D_B3, .2), .3)
out = tf.matmul(l3, D_W4) + D_B4
return out
def generator(z):
l1 = tf.nn.leaky_relu(tf.matmul(z, G_W1) + G_B1, .2)
l2 = tf.nn.leaky_relu(tf.matmul(l1, G_W2) + G_B2, .2)
l3 = tf.nn.leaky_relu(tf.matmul(l2, G_W3) + G_B3, .2)
out = tf.nn.tanh(tf.matmul(l3, G_W4) + G_B4)
return out
G_sample = generator(Z)
D_real = discriminator(X)
D_fake = discriminator(G_sample)
# Losses
D_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_real, labels=tf.ones_like(D_real)))
D_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake, labels=tf.zeros_like(D_fake)))
D_loss = D_loss_real + D_loss_fake
G_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake, labels=tf.ones_like(D_fake)))
# Optimizers
D_opt = tf.train.AdamOptimizer(2e-4).minimize(D_loss, var_list=D_var_list)
G_opt = tf.train.AdamOptimizer(2e-4).minimize(G_loss, var_list=G_var_list)
```
## Train
#### Testing
```
num_test_samples = 16
test_noise = noise(num_test_samples, NOISE_SIZE)
```
#### Inits
```
num_epochs = 200
# Start interactive session
session = tf.InteractiveSession()
# Init Variables
tf.global_variables_initializer().run()
# Init Logger
logger = Logger(model_name='DCGAN1', data_name='CIFAR10')
```
#### Train
```
# Iterate through epochs
for epoch in range(num_epochs):
for n_batch, (batch,_) in enumerate(data_loader):
# 1. Train Discriminator
X_batch = images_to_vectors(batch.permute(0, 2, 3, 1).numpy())
feed_dict = {X: X_batch, Z: noise(BATCH_SIZE, NOISE_SIZE)}
_, d_error, d_pred_real, d_pred_fake = session.run(
[D_opt, D_loss, D_real, D_fake], feed_dict=feed_dict
)
# 2. Train Generator
feed_dict = {Z: noise(BATCH_SIZE, NOISE_SIZE)}
_, g_error = session.run(
[G_opt, G_loss], feed_dict=feed_dict
)
if n_batch % 100 == 0:
display.clear_output(True)
# Generate images from test noise
test_images = session.run(
G_sample, feed_dict={Z: test_noise}
)
test_images = vectors_to_images(test_images)
# Log Images
logger.log_images(test_images, num_test_samples, epoch, n_batch, num_batches, format='NHWC');
# Log Status
logger.display_status(
epoch, num_epochs, n_batch, num_batches,
d_error, g_error, d_pred_real, d_pred_fake
)
```
| github_jupyter |
# Mining the Social Web, 2nd Edition
## Appendix B: OAuth Primer
This IPython Notebook provides an interactive way to follow along with and explore the numbered examples from [_Mining the Social Web (3rd Edition)_](http://bit.ly/Mining-the-Social-Web-3E). The intent behind this notebook is to reinforce the concepts from the sample code in a fun, convenient, and effective way. This notebook assumes that you are reading along with the book and have the context of the discussion as you work through these exercises.
In the somewhat unlikely event that you've somehow stumbled across this notebook outside of its context on GitHub, [you can find the full source code repository here](http://bit.ly/Mining-the-Social-Web-3E).
## Copyright and Licensing
You are free to use or adapt this notebook for any purpose you'd like. However, please respect the [Simplified BSD License](https://github.com/mikhailklassen/Mining-the-Social-Web-3rd-Edition/blob/master/LICENSE) that governs its use.
## Notes
While the chapters in the book opt to simplify the discussion by avoiding a discussion of OAuth and instead opting to use application credentials provided by social web properties for API access, this notebook demonstrates how to implement some OAuth flows for several of the more prominent social web properties. While IPython Notebook is used for consistency and ease of learning, and in some cases, this actually adds a little bit of extra complexity in some cases given the nature of embedding a web server and handling asynchronous callbacks. (Still, the overall code should be straightforward to adapt as needed.)
# Twitter OAuth 1.0a Flow with IPython Notebook
Twitter implements OAuth 1.0A as its standard authentication mechanism, and in order to use it to make requests to Twitter's API, you'll need to go to https://dev.twitter.com/apps and create a sample application. There are three items you'll need to note for an OAuth 1.0A workflow, a consumer key and consumer secret that identify the application as well as the oauth_callback URL that tells Twitter where redirect back to after the user has authorized the application. Note that you will need an ordinary Twitter account in order to login, create an app, and get these credentials. Keep in mind that for development purposes or for accessing your own account's data, you can simply use the oauth token and oauth token secret that are provided in your appliation settings to authenticate as opposed to going through the steps here. The process of obtaining an the oauth token and oauth token secret is fairly straight forward (especially with the help of a good library), but an implementation in IPython Notebook is a bit tricker due to the nature of embedding a web server, capturing information within web server contexts, and handling the various redirects along the way.
You must ensure that your browser is not blocking popups in order for this script to work.
<img src="files/resources/ch01-twitter/images/Twitter-AppCredentials-oauth_callback.png" width="600px">
## Example 1. Twitter OAuth 1.0a Flow
```
import json
from flask import Flask, request
from threading import Timer
from IPython.display import IFrame
from IPython.display import display
from IPython.display import Javascript as JS
import twitter
from twitter.oauth_dance import parse_oauth_tokens
from twitter.oauth import read_token_file, write_token_file
OAUTH_FILE = "/tmp/twitter_oauth"
# XXX: Go to http://twitter.com/apps/new to create an app and get values
# for these credentials that you'll need to provide in place of these
# empty string values that are defined as placeholders.
# See https://dev.twitter.com/docs/auth/oauth for more information
# on Twitter's OAuth implementation and ensure that *oauth_callback*
# is defined in your application settings as shown below if you are
# using Flask in this IPython Notebook
# Define a few variables that will bleed into the lexical scope of a couple of
# functions below
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
oauth_callback = 'http://127.0.0.1:5000/oauth_helper'
# Setup a callback handler for when Twitter redirects back to us after the user authorizes the app
webserver = Flask("TwitterOAuth")
@webserver.route("/oauth_helper")
def oauth_helper():
oauth_verifier = request.args.get('oauth_verifier')
# Pick back up credentials from ipynb_oauth_dance
oauth_token, oauth_token_secret = read_token_file(OAUTH_FILE)
_twitter = twitter.Twitter(
auth=twitter.OAuth(
oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET),
format='', api_version=None)
oauth_token, oauth_token_secret = parse_oauth_tokens(
_twitter.oauth.access_token(oauth_verifier=oauth_verifier))
# This web server only needs to service one request, so shut it down
shutdown_after_request = request.environ.get('werkzeug.server.shutdown')
shutdown_after_request()
# Write out the final credentials that can be picked up after the blocking
# call to webserver.run() below.
write_token_file(OAUTH_FILE, oauth_token, oauth_token_secret)
return "%s %s written to %s" % (oauth_token, oauth_token_secret, OAUTH_FILE)
# To handle Twitter's OAuth 1.0a implementation, we'll just need to implement a custom
# "oauth dance" and will closely follower the pattern defined in twitter.oauth_dance.
def ipynb_oauth_dance():
_twitter = twitter.Twitter(
auth=twitter.OAuth('', '', CONSUMER_KEY, CONSUMER_SECRET),
format='', api_version=None)
oauth_token, oauth_token_secret = parse_oauth_tokens(
_twitter.oauth.request_token(oauth_callback=oauth_callback))
# Need to write these interim values out to a file to pick up on the callback from Twitter
# that is handled by the web server in /oauth_helper
write_token_file(OAUTH_FILE, oauth_token, oauth_token_secret)
oauth_url = ('http://api.twitter.com/oauth/authorize?oauth_token=' + oauth_token)
# Tap the browser's native capabilities to access the web server through a new window to get
# user authorization
display(JS("window.open('%s')" % oauth_url))
# After the webserver.run() blocking call, start the oauth dance that will ultimately
# cause Twitter to redirect a request back to it. Once that request is serviced, the web
# server will shutdown, and program flow will resume with the OAUTH_FILE containing the
# necessary credentials
Timer(1, lambda: ipynb_oauth_dance()).start()
webserver.run(host='0.0.0.0')
# The values that are read from this file are written out at
# the end of /oauth_helper
oauth_token, oauth_token_secret = read_token_file(OAUTH_FILE)
# These 4 credentials are what is needed to authorize the application
auth = twitter.oauth.OAuth(oauth_token, oauth_token_secret,
CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
print(twitter_api)
```
# Facebook OAuth 2.0 Flow with IPython Notebook
Facebook implements OAuth 2.0 as its standard authentication mechanism, and this example demonstrates how get an access token for making API requests once you've created an app and gotten a "client id" value that can be used to initiate an OAuth flow. Note that you will need an ordinary Facebook account in order to login, create an app, and get these credentials. You can create an app through the "Developer" section of your account settings as shown below or by navigating directly to https://developers.facebook.com/apps/. During development or debugging cycles, or to just access data in your own account, you may sometimes find it convenient to also reference the access token that's available to you through the Graph API Explorer tool at https://developers.facebook.com/tools/explorer as opposed to using the flow described here. The process of obtaining an access token is fairly straight forward, but an implementation in IPython Notebook is a bit tricker due to the nature of embedding a web server, capturing information within web server contexts, and handling the various redirects along the way.
You must ensure that your browser is not blocking popups in order for this script to work.
<br />
<br />
<img src="files/resources/ch02-facebook/images/fb_create_app.png" width="400px"><br />
Create apps at https://developers.facebook.com/apps/<br />
<br />
<img src="files/resources/ch02-facebook/images/fb_edit_app.png" width="400px"><br />
Clicking on the app in your list to see the app dashboard and access app settings.
## Example 2. Facebook OAuth 2.0 Flow
```
import urllib
from flask import Flask, request
from threading import Timer
from IPython.display import display
from IPython.display import Javascript as JS
# XXX: Get this value from your Facebook application's settings for the OAuth flow
# at https://developers.facebook.com/apps
APP_ID = ''
# This value is where Facebook will redirect. We'll configure an embedded
# web server to be serving requests here
REDIRECT_URI = 'http://localhost:5000/oauth_helper'
# You could customize which extended permissions are being requested for your app
# by adding additional items to the list below. See
# https://developers.facebook.com/docs/reference/login/extended-permissions/
EXTENDED_PERMS = ['user_likes']
# A temporary file to store a code from the web server
OAUTH_FILE = 'resources/ch02-facebook/access_token.txt'
# Configure an emedded web server that accepts one request, parses
# the fragment identifier out of the browser window redirects to another
# handler with the parsed out value in the query string where it can be captured
# and stored to disk. (A webserver cannot capture information in the fragment
# identifier or that work would simply be done in here.)
webserver = Flask("FacebookOAuth")
@webserver.route("/oauth_helper")
def oauth_helper():
return '''<script type="text/javascript">
var at = window.location.hash.substring("access_token=".length+1).split("&")[0];
setTimeout(function() { window.location = "/access_token_capture?access_token=" + at }, 1000 /*ms*/);
</script>'''
# Parses out a query string parameter and stores it to disk. This is required because
# the address space that Flask uses is not shared with IPython Notebook, so there is really
# no other way to share the information than to store it to a file and access it afterward
@webserver.route("/access_token_capture")
def access_token_capture():
access_token = request.args.get('access_token')
f = open(OAUTH_FILE, 'w') # Store the code as a file
f.write(access_token)
f.close()
# It is safe (and convenient) to shut down the web server after this request
shutdown_after_request = request.environ.get('werkzeug.server.shutdown')
shutdown_after_request()
return access_token
# Send an OAuth request to Facebook, handle the redirect, and display the access
# token that's included in the redirect for the user to copy and paste
args = dict(client_id=APP_ID, redirect_uri=REDIRECT_URI,
scope=','.join(EXTENDED_PERMS), type='user_agent', display='popup'
)
oauth_url = 'https://facebook.com/dialog/oauth?' + urllib.parse.urlencode(args)
Timer(1, lambda: display(JS("window.open('%s')" % oauth_url))).start()
webserver.run(host='0.0.0.0')
access_token = open(OAUTH_FILE).read()
print(access_token)
```
# LinkedIn OAuth 2.0 Flow with IPython Notebook
LinkedIn implements OAuth 2.0 as one of its standard authentication mechanism, and "Example 3" demonstrates how to use it to get an access token for making API requests once you've created an app and gotten the "API Key" and "Secret Key" values that are part of the OAuth flow. Note that you will need an ordinary LinkedIn account in order to login, create an app, and get these credentials. You can create an app through the "Developer" section of your account settings as shown below or by navigating directly to https://www.linkedin.com/secure/developer.
You must ensure that your browser is not blocking popups in order for this script to work.
<img src="files/resources/ch04-linkedin/images/LinkedIn-app.png" width="600px">
## Example 3. Using LinkedIn OAuth credentials to receive an access token an authorize an application
Note: You must ensure that your browser is not blocking popups in order for this script to work. LinkedIn's OAuth flow appears to expressly involve opening a new window, and it does not appear that an inline frame can be used as is the case with some other social web properties. You may also find it very convenient to ensure that you are logged into LinkedIn at http://www.linkedin.com/ with this browser before executing this script, because the OAuth flow will prompt you every time you run it if you are not already logged in. If for some reason you cause IPython Notebook to hang, just select "Kernel => Interrupt" from its menu.
```
import os
from threading import Timer
from flask import Flask, request
from linkedin import linkedin # pip install python3-linkedin
from IPython.display import display
from IPython.display import Javascript as JS
# XXX: Get these values from your application's settings for the OAuth flow
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
# This value is where LinkedIn will redirect. We'll configure an embedded
# web server to be serving requests here. Make sure to add this to your
# app settings
REDIRECT_URL = 'http://localhost:5000/oauth_helper'
# A temporary file to store a code from the web server
OAUTH_FILE = 'resources/ch04-linkedin/linkedin.authorization_code'
# These should match those in your app settings
permissions = {'BASIC_PROFILE': 'r_basicprofile',
'EMAIL_ADDRESS': 'r_emailaddress',
'SHARE': 'w_share',
'COMPANY_ADMIN': 'rw_company_admin'}
# Configure an emedded web server that accepts one request, stores a file
# that will need to be accessed outside of the request context, and
# immediately shuts itself down
webserver = Flask("OAuthHelper")
@webserver.route("/oauth_helper")
def oauth_helper():
code = request.args.get('code')
f = open(OAUTH_FILE, 'w') # Store the code as a file
f.write(code)
f.close()
shutdown_after_request = request.environ.get('werkzeug.server.shutdown')
shutdown_after_request()
return """<p>Handled redirect and extracted code <strong>%s</strong>
for authorization</p>""" % (code,)
# Send an OAuth request to LinkedIn, handle the redirect, and display the access
# token that's included in the redirect for the user to copy and paste
auth = linkedin.LinkedInAuthentication(CONSUMER_KEY, CONSUMER_SECRET, REDIRECT_URL,
permissions.values())
# Display popup after a brief delay to ensure that the web server is running and
# can handle the redirect back from LinkedIn
Timer(1, lambda: display(JS("window.open('%s')" % auth.authorization_url))).start()
# Run the server to accept the redirect back from LinkedIn and capture the access
# token. This command blocks, but the web server is configured to shut itself down
# after it serves a request, so after the redirect occurs, program flow will continue
webserver.run(host='0.0.0.0')
# As soon as the request finishes, the web server shuts down and these remaining commands
# are executed, which exchange an authorization code for an access token. This process
# seems to need full automation because the authorization code expires very quickly.
auth.authorization_code = open(OAUTH_FILE).read()
auth.get_access_token()
# Prevent stale tokens from sticking around, which could complicate debugging
os.remove(OAUTH_FILE)
# How you can use the application to access the LinkedIn API...
app = linkedin.LinkedInApplication(auth)
print(app.get_profile())
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.