text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
```
# look at tools/set_up_magics.ipynb
yandex_metrica_allowed = True ; get_ipython().run_cell('# one_liner_str\n\nget_ipython().run_cell_magic(\'javascript\', \'\', \'// setup cpp code highlighting\\nIPython.CodeCell.options_default.highlight_modes["text/x-c++src"] = {\\\'reg\\\':[/^%%cpp/]} ;\')\n\n# creating magics\nfrom IPython.core.magic import register_cell_magic, register_line_magic\nfrom IPython.display import display, Markdown, HTML\nimport argparse\nfrom subprocess import Popen, PIPE\nimport random\nimport sys\nimport os\nimport re\nimport signal\nimport shutil\nimport shlex\nimport glob\n\n@register_cell_magic\ndef save_file(args_str, cell, line_comment_start="#"):\n parser = argparse.ArgumentParser()\n parser.add_argument("fname")\n parser.add_argument("--ejudge-style", action="store_true")\n args = parser.parse_args(args_str.split())\n \n cell = cell if cell[-1] == \'\\n\' or args.no_eof_newline else cell + "\\n"\n cmds = []\n with open(args.fname, "w") as f:\n f.write(line_comment_start + " %%cpp " + args_str + "\\n")\n for line in cell.split("\\n"):\n line_to_write = (line if not args.ejudge_style else line.rstrip()) + "\\n"\n if line.startswith("%"):\n run_prefix = "%run "\n if line.startswith(run_prefix):\n cmds.append(line[len(run_prefix):].strip())\n f.write(line_comment_start + " " + line_to_write)\n continue\n run_prefix = "%# "\n if line.startswith(run_prefix):\n f.write(line_comment_start + " " + line_to_write)\n continue\n raise Exception("Unknown %%save_file subcommand: \'%s\'" % line)\n else:\n f.write(line_to_write)\n f.write("" if not args.ejudge_style else line_comment_start + r" line without \\n")\n for cmd in cmds:\n display(Markdown("Run: `%s`" % cmd))\n get_ipython().system(cmd)\n\n@register_cell_magic\ndef cpp(fname, cell):\n save_file(fname, cell, "//")\n\n@register_cell_magic\ndef asm(fname, cell):\n save_file(fname, cell, "//")\n \n@register_cell_magic\ndef makefile(fname, cell):\n assert not fname\n save_file("makefile", cell.replace(" " * 4, "\\t"))\n \n@register_line_magic\ndef p(line):\n try:\n expr, comment = line.split(" #")\n display(Markdown("`{} = {}` # {}".format(expr.strip(), eval(expr), comment.strip())))\n except:\n display(Markdown("{} = {}".format(line, eval(line))))\n \ndef show_file(file, clear_at_begin=True, return_html_string=False):\n if clear_at_begin:\n get_ipython().system("truncate --size 0 " + file)\n obj = file.replace(\'.\', \'_\').replace(\'/\', \'_\') + "_obj"\n html_string = \'\'\'\n <!--MD_BEGIN_FILTER-->\n <script type=text/javascript>\n var entrance___OBJ__ = 0;\n var errors___OBJ__ = 0;\n function refresh__OBJ__()\n {\n entrance___OBJ__ -= 1;\n var elem = document.getElementById("__OBJ__");\n if (elem) {\n var xmlhttp=new XMLHttpRequest();\n xmlhttp.onreadystatechange=function()\n {\n var elem = document.getElementById("__OBJ__");\n console.log(!!elem, xmlhttp.readyState, xmlhttp.status, entrance___OBJ__);\n if (elem && xmlhttp.readyState==4) {\n if (xmlhttp.status==200)\n {\n errors___OBJ__ = 0;\n if (!entrance___OBJ__) {\n elem.innerText = xmlhttp.responseText;\n entrance___OBJ__ += 1;\n console.log("req");\n window.setTimeout("refresh__OBJ__()", 300); \n }\n return xmlhttp.responseText;\n } else {\n errors___OBJ__ += 1;\n if (errors___OBJ__ < 10 && !entrance___OBJ__) {\n entrance___OBJ__ += 1;\n console.log("req");\n window.setTimeout("refresh__OBJ__()", 300); \n }\n }\n }\n }\n xmlhttp.open("GET", "__FILE__", true);\n xmlhttp.setRequestHeader("Cache-Control", "no-cache");\n xmlhttp.send(); \n }\n }\n \n if (!entrance___OBJ__) {\n entrance___OBJ__ += 1;\n refresh__OBJ__(); \n }\n </script>\n \n <font color="white"> <tt>\n <p id="__OBJ__" style="font-size: 16px; border:3px #333333 solid; background: #333333; border-radius: 10px; padding: 10px; "></p>\n </tt> </font>\n <!--MD_END_FILTER-->\n <!--MD_FROM_FILE __FILE__ -->\n \'\'\'.replace("__OBJ__", obj).replace("__FILE__", file)\n if return_html_string:\n return html_string\n display(HTML(html_string))\n \nBASH_POPEN_TMP_DIR = "./bash_popen_tmp"\n \ndef bash_popen_terminate_all():\n for p in globals().get("bash_popen_list", []):\n print("Terminate pid=" + str(p.pid), file=sys.stderr)\n p.terminate()\n globals()["bash_popen_list"] = []\n if os.path.exists(BASH_POPEN_TMP_DIR):\n shutil.rmtree(BASH_POPEN_TMP_DIR)\n\nbash_popen_terminate_all() \n\ndef bash_popen(cmd):\n if not os.path.exists(BASH_POPEN_TMP_DIR):\n os.mkdir(BASH_POPEN_TMP_DIR)\n h = os.path.join(BASH_POPEN_TMP_DIR, str(random.randint(0, 1e18)))\n stdout_file = h + ".out.html"\n stderr_file = h + ".err.html"\n run_log_file = h + ".fin.html"\n \n stdout = open(stdout_file, "wb")\n stdout = open(stderr_file, "wb")\n \n html = """\n <table width="100%">\n <colgroup>\n <col span="1" style="width: 70px;">\n <col span="1">\n </colgroup> \n <tbody>\n <tr> <td><b>STDOUT</b></td> <td> {stdout} </td> </tr>\n <tr> <td><b>STDERR</b></td> <td> {stderr} </td> </tr>\n <tr> <td><b>RUN LOG</b></td> <td> {run_log} </td> </tr>\n </tbody>\n </table>\n """.format(\n stdout=show_file(stdout_file, return_html_string=True),\n stderr=show_file(stderr_file, return_html_string=True),\n run_log=show_file(run_log_file, return_html_string=True),\n )\n \n cmd = """\n bash -c {cmd} &\n pid=$!\n echo "Process started! pid=${{pid}}" > {run_log_file}\n wait ${{pid}}\n echo "Process finished! exit_code=$?" >> {run_log_file}\n """.format(cmd=shlex.quote(cmd), run_log_file=run_log_file)\n # print(cmd)\n display(HTML(html))\n \n p = Popen(["bash", "-c", cmd], stdin=PIPE, stdout=stdout, stderr=stdout)\n \n bash_popen_list.append(p)\n return p\n\n\n@register_line_magic\ndef bash_async(line):\n bash_popen(line)\n \n \ndef show_log_file(file, return_html_string=False):\n obj = file.replace(\'.\', \'_\').replace(\'/\', \'_\') + "_obj"\n html_string = \'\'\'\n <!--MD_BEGIN_FILTER-->\n <script type=text/javascript>\n var entrance___OBJ__ = 0;\n var errors___OBJ__ = 0;\n function halt__OBJ__(elem, color)\n {\n elem.setAttribute("style", "font-size: 14px; background: " + color + "; padding: 10px; border: 3px; border-radius: 5px; color: white; "); \n }\n function refresh__OBJ__()\n {\n entrance___OBJ__ -= 1;\n if (entrance___OBJ__ < 0) {\n entrance___OBJ__ = 0;\n }\n var elem = document.getElementById("__OBJ__");\n if (elem) {\n var xmlhttp=new XMLHttpRequest();\n xmlhttp.onreadystatechange=function()\n {\n var elem = document.getElementById("__OBJ__");\n console.log(!!elem, xmlhttp.readyState, xmlhttp.status, entrance___OBJ__);\n if (elem && xmlhttp.readyState==4) {\n if (xmlhttp.status==200)\n {\n errors___OBJ__ = 0;\n if (!entrance___OBJ__) {\n if (elem.innerHTML != xmlhttp.responseText) {\n elem.innerHTML = xmlhttp.responseText;\n }\n if (elem.innerHTML.includes("Process finished.")) {\n halt__OBJ__(elem, "#333333");\n } else {\n entrance___OBJ__ += 1;\n console.log("req");\n window.setTimeout("refresh__OBJ__()", 300); \n }\n }\n return xmlhttp.responseText;\n } else {\n errors___OBJ__ += 1;\n if (!entrance___OBJ__) {\n if (errors___OBJ__ < 6) {\n entrance___OBJ__ += 1;\n console.log("req");\n window.setTimeout("refresh__OBJ__()", 300); \n } else {\n halt__OBJ__(elem, "#994444");\n }\n }\n }\n }\n }\n xmlhttp.open("GET", "__FILE__", true);\n xmlhttp.setRequestHeader("Cache-Control", "no-cache");\n xmlhttp.send(); \n }\n }\n \n if (!entrance___OBJ__) {\n entrance___OBJ__ += 1;\n refresh__OBJ__(); \n }\n </script>\n\n <p id="__OBJ__" style="font-size: 14px; background: #000000; padding: 10px; border: 3px; border-radius: 5px; color: white; ">\n </p>\n \n </font>\n <!--MD_END_FILTER-->\n <!--MD_FROM_FILE __FILE__.md -->\n \'\'\'.replace("__OBJ__", obj).replace("__FILE__", file)\n if return_html_string:\n return html_string\n display(HTML(html_string))\n\n \nclass TInteractiveLauncher:\n tmp_path = "./interactive_launcher_tmp"\n def __init__(self, cmd):\n try:\n os.mkdir(TInteractiveLauncher.tmp_path)\n except:\n pass\n name = str(random.randint(0, 1e18))\n self.inq_path = os.path.join(TInteractiveLauncher.tmp_path, name + ".inq")\n self.log_path = os.path.join(TInteractiveLauncher.tmp_path, name + ".log")\n \n os.mkfifo(self.inq_path)\n open(self.log_path, \'w\').close()\n open(self.log_path + ".md", \'w\').close()\n\n self.pid = os.fork()\n if self.pid == -1:\n print("Error")\n if self.pid == 0:\n exe_cands = glob.glob("../tools/launcher.py") + glob.glob("../../tools/launcher.py")\n assert(len(exe_cands) == 1)\n assert(os.execvp("python3", ["python3", exe_cands[0], "-l", self.log_path, "-i", self.inq_path, "-c", cmd]) == 0)\n self.inq_f = open(self.inq_path, "w")\n interactive_launcher_opened_set.add(self.pid)\n show_log_file(self.log_path)\n\n def write(self, s):\n s = s.encode()\n assert len(s) == os.write(self.inq_f.fileno(), s)\n \n def get_pid(self):\n n = 100\n for i in range(n):\n try:\n return int(re.findall(r"PID = (\\d+)", open(self.log_path).readline())[0])\n except:\n if i + 1 == n:\n raise\n time.sleep(0.1)\n \n def input_queue_path(self):\n return self.inq_path\n \n def close(self):\n self.inq_f.close()\n os.waitpid(self.pid, 0)\n os.remove(self.inq_path)\n # os.remove(self.log_path)\n self.inq_path = None\n self.log_path = None \n interactive_launcher_opened_set.remove(self.pid)\n self.pid = None\n \n @staticmethod\n def terminate_all():\n if "interactive_launcher_opened_set" not in globals():\n globals()["interactive_launcher_opened_set"] = set()\n global interactive_launcher_opened_set\n for pid in interactive_launcher_opened_set:\n print("Terminate pid=" + str(pid), file=sys.stderr)\n os.kill(pid, signal.SIGKILL)\n os.waitpid(pid, 0)\n interactive_launcher_opened_set = set()\n if os.path.exists(TInteractiveLauncher.tmp_path):\n shutil.rmtree(TInteractiveLauncher.tmp_path)\n \nTInteractiveLauncher.terminate_all()\n \nyandex_metrica_allowed = bool(globals().get("yandex_metrica_allowed", False))\nif yandex_metrica_allowed:\n display(HTML(\'\'\'<!-- YANDEX_METRICA_BEGIN -->\n <script type="text/javascript" >\n (function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};\n m[i].l=1*new Date();k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})\n (window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");\n\n ym(59260609, "init", {\n clickmap:true,\n trackLinks:true,\n accurateTrackBounce:true\n });\n </script>\n <noscript><div><img src="https://mc.yandex.ru/watch/59260609" style="position:absolute; left:-9999px;" alt="" /></div></noscript>\n <!-- YANDEX_METRICA_END -->\'\'\'))\n\ndef make_oneliner():\n html_text = \'("В этот ноутбук встроен код Яндекс Метрики для сбора статистики использований. Если вы не хотите, чтобы по вам собиралась статистика, исправьте: yandex_metrica_allowed = False" if yandex_metrica_allowed else "")\'\n html_text += \' + "<""!-- MAGICS_SETUP_PRINTING_END -->"\'\n return \'\'.join([\n \'# look at tools/set_up_magics.ipynb\\n\',\n \'yandex_metrica_allowed = True ; get_ipython().run_cell(%s);\' % repr(one_liner_str),\n \'display(HTML(%s))\' % html_text,\n \' #\'\'MAGICS_SETUP_END\'\n ])\n \n\n');display(HTML(("В этот ноутбук встроен код Яндекс Метрики для сбора статистики использований. Если вы не хотите, чтобы по вам собиралась статистика, исправьте: yandex_metrica_allowed = False" if yandex_metrica_allowed else "") + "<""!-- MAGICS_SETUP_PRINTING_END -->")) #MAGICS_SETUP_END
```
# Inter Process Communications (IPC)
<br>
<div style="text-align: right"> Спасибо <a href="https://github.com/SyrnikRebirth">Сове Глебу</a> и <a href="https://github.com/Disadvantaged">Голяр Димитрису</a> за участие в написании текста </div>
<br>
Сегодня в программе:
* <a href="#mmap" style="color:#856024">`mmap` для IPC</a>
<br> Используем примитивы межпоточной синхронизации для межпроцессной. Через разделяемую память создаем правильные мьютексы.
<br> [Ссылка про правильные мьютексы](https://linux.die.net/man/3/pthread_mutexattr_init)
* <a href="#shm" style="color:#856024">Объекты разделяемой памяти POSIX</a>
<br>Это почти то же самое, что и обычные файлы, но у них ортогональное пространство имен и они не сохраняются на диск.
<br>Вызовы `shm_open` (открывает/создает объект разделяемой памяти, аналогично `open`) и `shm_unlink` (удаляет ссылку на объект, аналогично `unlink`)
<br>[Документашка](https://www.opennet.ru/man.shtml?topic=shm_open&category=3&russian=0). [Отличия от `open`](https://stackoverflow.com/questions/24875257/why-use-shm-open)
<br><br>
* Семафоры
<br><a href="#sem_anon" style="color:#856024">Неименованные</a>
<br><a href="#sem_named" style="color:#856024">Именованные</a>
* <a href="#sem_signal" style="color:#856024">Сочетаемость семафоров и сигналов</a>
<a href="#hw" style="color:#856024">Комментарии к ДЗ</a>
[Ридинг Яковлева](https://github.com/victor-yacovlev/mipt-diht-caos/tree/master/practice/posix_ipc)
# <a name="mmap"></a> `mmap`
Разделяемая память - это когда два региона виртуальной памяти (один в одном процессе, другой в другом)
ссылаются на одну и ту же физическую память. То есть могут обмениваться информацией через нее.
Межпроцессное взаимодействие через разделяемую память нужно,
когда у нас есть две различные программы (могут быть написаны на разных языках)
и когда нам не подходит взаимодействие через сокеты (такое взаимодействие не очень эффективно).
```
%%cpp mmap.c
%run gcc -Wall -fsanitize=thread mmap.c -lpthread -o mmap.exe
%run ./mmap.exe
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pthread.h>
#include <stdatomic.h>
const char* log_prefix(const char* file, int line) {
struct timeval tp; gettimeofday(&tp, NULL); struct tm ltime; localtime_r(&tp.tv_sec, <ime);
static __thread char prefix[100];
size_t time_len = strftime(prefix, sizeof(prefix), "%H:%M:%S", <ime);
sprintf(prefix + time_len, ".%03ld %s:%3d [pid=%d]", tp.tv_usec / 1000, file, line, getpid());
return prefix;
}
#define log_printf_impl(fmt, ...) { dprintf(2, "%s: " fmt "%s", log_prefix(__FILE__, __LINE__), __VA_ARGS__); }
#define log_printf(...) log_printf_impl(__VA_ARGS__, "")
// process-aware assert
#define pa_assert(stmt) if (stmt) {} else { log_printf("'" #stmt "' failed\n"); exit(EXIT_FAILURE); }
typedef enum {
VALID_STATE = 0,
INVALID_STATE = 1
} state_t;
typedef struct {
pthread_mutex_t mutex;
state_t current_state; // protected by mutex
} shared_state_t;
shared_state_t* state; // interprocess state
// process_safe_func и process_func - функции-примеры с прошлого семинара (с точностью до замены thread/process)
void process_safe_func() {
// all function is critical section, protected by mutex
pthread_mutex_lock(&state->mutex); // try comment lock&unlock out and look at result
pa_assert(state->current_state == VALID_STATE);
state->current_state = INVALID_STATE; // do some work with state.
sched_yield();
state->current_state = VALID_STATE;
pthread_mutex_unlock(&state->mutex);
}
void process_func(int process_num)
{
log_printf(" Process %d started\n", process_num);
for (int j = 0; j < 10000; ++j) {
process_safe_func();
}
log_printf(" Process %d finished\n", process_num);
}
shared_state_t* create_state() {
// Создаем кусок разделяемой памяти. Он будет общим для данного процесса и его дочерних
shared_state_t* state = mmap(
/* desired addr, addr = */ NULL,
/* length = */ sizeof(shared_state_t), // Размер разделяемого фрагмента памяти
/* access attributes, prot = */ PROT_READ | PROT_WRITE,
/* flags = */ MAP_SHARED | MAP_ANONYMOUS,
/* fd = */ -1,
/* offset in file, offset = */ 0
);
pa_assert(state != MAP_FAILED);
// create and initialize interprocess mutex
pthread_mutexattr_t mutex_attrs;
pa_assert(pthread_mutexattr_init(&mutex_attrs) == 0);
// Важно! Без этого атрибута один из процессов навсегда зависнет в lock мьютекса
// Вероятно этот атрибут влияет на отсутствие флага FUTEX_PRIVATE_FLAG в операциях с futex
// Если он стоит, то ядро может делать некоторые оптимизации в предположении, что futex используется одним процессом
pa_assert(pthread_mutexattr_setpshared(&mutex_attrs, PTHREAD_PROCESS_SHARED) == 0);
pa_assert(pthread_mutex_init(&state->mutex, &mutex_attrs) == 0);
pa_assert(pthread_mutexattr_destroy(&mutex_attrs) == 0);
state->current_state = VALID_STATE; // Инициализирем защищаемое состояние
return state;
}
void delete_state(shared_state_t* state) {
pa_assert(pthread_mutex_destroy(&state->mutex) == 0);
pa_assert(munmap(state, sizeof(shared_state_t)) == 0);
}
int main()
{
log_printf("Main process started\n");
state = create_state(); // Создаем разделяемое состояние
const int process_count = 2;
pid_t processes[process_count];
// Создаем дочерние процессы
for (int i = 0; i < process_count; ++i) {
log_printf("Creating process %d\n", i);
// дочерние процессы унаследуют разделяемое состояние (оно не скопируется, а будет общим)
pa_assert((processes[i] = fork()) >= 0);
if (processes[i] == 0) {
process_func(i); // Имитируем работу из разных процессов
exit(0);
}
}
for (int i = 0; i < process_count; ++i) {
int status;
pa_assert(waitpid(processes[i], &status, 0) != -1)
pa_assert(WIFEXITED(status) && WEXITSTATUS(status) == 0);
log_printf("Process %d 'joined'\n", i);
}
delete_state(state);
log_printf("Main process finished\n");
return 0;
}
```
# Ну и spinlock давайте. А почему бы и нет?
Отличие только в замене инициализации и в взятии/снятии локов.
```
%%cpp mmap.c
%run gcc -Wall -fsanitize=thread mmap.c -lpthread -o mmap.exe
%run ./mmap.exe
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pthread.h>
#include <stdatomic.h>
const char* log_prefix(const char* file, int line) {
struct timeval tp; gettimeofday(&tp, NULL); struct tm ltime; localtime_r(&tp.tv_sec, <ime);
static __thread char prefix[100];
size_t time_len = strftime(prefix, sizeof(prefix), "%H:%M:%S", <ime);
sprintf(prefix + time_len, ".%03ld %s:%3d [pid=%d]", tp.tv_usec / 1000, file, line, getpid());
return prefix;
}
#define log_printf_impl(fmt, ...) { dprintf(2, "%s: " fmt "%s", log_prefix(__FILE__, __LINE__), __VA_ARGS__); }
#define log_printf(...) log_printf_impl(__VA_ARGS__, "")
// process-aware assert
#define pa_assert(stmt) if (stmt) {} else { log_printf("'" #stmt "' failed\n"); exit(EXIT_FAILURE); }
typedef enum {
VALID_STATE = 0,
INVALID_STATE = 1
} state_t;
typedef struct {
_Atomic int lock;
state_t current_state; // protected by mutex
} shared_state_t;
shared_state_t* state; // interprocess state
void sl_lock(_Atomic int* lock) {
int expected = 0;
while (!atomic_compare_exchange_weak(lock, &expected, 1)) {
expected = 0;
}
}
void sl_unlock(_Atomic int* lock) {
atomic_fetch_sub(lock, 1);
}
void process_safe_func() {
// all function is critical section, protected by spinlock
sl_lock(&state->lock);
pa_assert(state->current_state == VALID_STATE);
state->current_state = INVALID_STATE; // do some work with state.
sched_yield();
state->current_state = VALID_STATE;
sl_unlock(&state->lock);
}
void process_func(int process_num)
{
log_printf(" Process %d started\n", process_num);
for (int j = 0; j < 10000; ++j) {
process_safe_func();
}
log_printf(" Process %d finished\n", process_num);
}
shared_state_t* create_state() {
shared_state_t* state = mmap(
/* desired addr, addr = */ NULL,
/* length = */ sizeof(shared_state_t),
/* access attributes, prot = */ PROT_READ | PROT_WRITE,
/* flags = */ MAP_SHARED | MAP_ANONYMOUS,
/* fd = */ -1,
/* offset in file, offset = */ 0
);
pa_assert(state != MAP_FAILED);
state->lock = 0;
state->current_state = VALID_STATE;
return state;
}
void delete_state(shared_state_t* state) {
pa_assert(munmap(state, sizeof(shared_state_t)) == 0);
}
int main()
{
log_printf("Main process started\n");
state = create_state();
const int process_count = 2;
pid_t processes[process_count];
for (int i = 0; i < process_count; ++i) {
log_printf("Creating process %d\n", i);
pa_assert((processes[i] = fork()) >= 0);
if (processes[i] == 0) {
process_func(i);
exit(0);
}
}
for (int i = 0; i < process_count; ++i) {
int status;
pa_assert(waitpid(processes[i], &status, 0) != -1)
pa_assert(WIFEXITED(status) && WEXITSTATUS(status) == 0);
log_printf("Process %d 'joined'\n", i);
}
delete_state(state);
log_printf("Main process finished\n");
return 0;
}
```
# <a name="shm"></a> `shm_open`
Сделаем то же самое, что и в предыдущем примере, но на этот раз не из родственных процессов. Воспользуемся именноваными объектами разделяемой памяти.
```
%%cpp shm.c
%# Обратите внимание: -lrt. Здесь нужна новая разделяемая библиотека
%run gcc -Wall -fsanitize=thread shm.c -lrt -lpthread -o s.exe
%run ./s.exe create_shm /my_shm
%run ./s.exe work 1 /my_shm & PID=$! ; ./s.exe work 2 /my_shm ; wait $PID
%run ./s.exe remove_shm /my_shm
#define _GNU_SOURCE
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pthread.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
const char* log_prefix(const char* file, int line) {
struct timeval tp; gettimeofday(&tp, NULL); struct tm ltime; localtime_r(&tp.tv_sec, <ime);
static __thread char prefix[100];
size_t time_len = strftime(prefix, sizeof(prefix), "%H:%M:%S", <ime);
sprintf(prefix + time_len, ".%03ld %s:%3d [pid=%d]", tp.tv_usec / 1000, file, line, getpid());
return prefix;
}
#define log_printf_impl(fmt, ...) { dprintf(2, "%s: " fmt "%s", log_prefix(__FILE__, __LINE__), __VA_ARGS__); }
#define log_printf(...) log_printf_impl(__VA_ARGS__, "")
// process-aware assert
#define pa_assert(stmt) if (stmt) {} else { log_printf("'" #stmt "' failed\n"); exit(EXIT_FAILURE); }
typedef enum {
VALID_STATE = 0,
INVALID_STATE = 1
} state_t;
typedef struct {
pthread_mutex_t mutex;
state_t current_state; // protected by mutex
} shared_state_t;
void process_safe_func(shared_state_t* state) {
// all function is critical section, protected by mutex
pthread_mutex_lock(&state->mutex); // try comment lock&unlock out and look at result
pa_assert(state->current_state == VALID_STATE);
state->current_state = INVALID_STATE; // do some work with state.
sched_yield();
state->current_state = VALID_STATE;
pthread_mutex_unlock(&state->mutex);
}
shared_state_t* load_state(const char* shm_name, bool do_create) {
// открываем / создаем объект разделяемой памяти
// по сути это просто open, только для виртуального файла (без сохранения данных на диск + ортогональное пространство имен)
int fd = shm_open(shm_name, O_RDWR | (do_create ? O_CREAT : 0), 0644);
pa_assert(fd >= 0);
pa_assert(ftruncate(fd, sizeof(shared_state_t)) == 0);
shared_state_t* state = mmap(
/* desired addr, addr = */ NULL,
/* length = */ sizeof(shared_state_t),
/* access attributes, prot = */ PROT_READ | PROT_WRITE,
/* flags = */ MAP_SHARED,
/* fd = */ fd,
/* offset in file, offset = */ 0
);
pa_assert(state != MAP_FAILED);
if (!do_create) {
return state;
}
// create interprocess mutex
pthread_mutexattr_t mutex_attrs;
pa_assert(pthread_mutexattr_init(&mutex_attrs) == 0);
// Важно!
pa_assert(pthread_mutexattr_setpshared(&mutex_attrs, PTHREAD_PROCESS_SHARED) == 0);
pa_assert(pthread_mutex_init(&state->mutex, &mutex_attrs) == 0);
pa_assert(pthread_mutexattr_destroy(&mutex_attrs) == 0);
state->current_state = VALID_STATE;
return state;
}
void unload_state(shared_state_t* state) {
pa_assert(munmap(state, sizeof(shared_state_t)) == 0);
}
int main(int argc, char** argv)
{
pa_assert(argc >= 2);
if (strcmp("create_shm", argv[1]) == 0) {
log_printf(" Creating state: %s\n", argv[2]);
unload_state(load_state(argv[2], /*do_create=*/ 1));
log_printf(" State created\n");
} else if (strcmp("remove_shm", argv[1]) == 0) {
log_printf(" Removing state: %s\n", argv[2]);
// Файлы shm существуют пока не будет вызвана unlink.
pa_assert(shm_unlink(argv[2]) == 0)
log_printf(" State removed\n");
} else if (strcmp("work", argv[1]) == 0) {
pa_assert(argc >= 3);
int worker = strtol(argv[2], 0, 10);
log_printf(" Worker %d started\n", worker);
shared_state_t* state = load_state(argv[3], /*do_create=*/ 0);
for (int j = 0; j < 10000; ++j) {
process_safe_func(state);
}
unload_state(state);
log_printf(" Worker %d finished\n", worker);
} else {
pa_assert(0 && "unknown command")
}
return 0;
}
```
Проблема: как решить, кто из независимых процессов будет создавать участок?
Способ разрешить конфликт создания участка разделяемой памяти:
* Все процессы создают файлы с флагом O_EXCL | O_CREAT
* Из-за О_EXCL выкинет ошибку для всех процессов кроме одного
* Этот один процесс создаст файл, выделит память, создаст спинлок на инициализацию и начнёт инициализировать
* Другие, которые получили ошибку попытаются открыть файл ещё раз, без этих флагов уже.
* Далее они будут ждать (регулярно проверять) пока не изменится размер файла, потом откроют его, и дальше будут ждать инициализации на спинлоке.
# <a name="sem_anon"></a> Анонимные семафоры
Игровое сравнение: семафор это ящик с шариками.
<pre>
| |
| |
| |
|_*_|</pre>
^
|
Это семафор со значением 1 (ящик с одним шариком)
У семафора такая семантика:
* Операция post() кладет шарик в ящик. Работает мгновенно.
* Операция wait() извлекает шарик из ящика. Если шариков нет, то блокируется пока не появится шарик и затем его извлекает.
* Еще есть try_wait(), timed_wait() - они соответствуют названиям.
Шарики можно так же рассматривать как свободные ресурсы.
Семафор с одним шариком можно использовать как мьютекс. В данном случае шарик - это ресурс на право входить в критическую секцию. Соответственно lock - это wait. А unlock это post.
### Пример использования с многими шариками: Построение очереди.
Создаём 2 семафора, semFree и semElementsInside.
При добавлении берём ресурс (~шарик) из semFree, под lock добавляем элемент, кладём ресурс в semElementsInside
При удалении берём ресурс из semElementsInside, под локом удаляем элемент, кладём ресурс в semFree<br>
```
%%cpp sem_anon.c
%run gcc -Wall -fsanitize=thread -lrt sem_anon.c -o sem_anon.exe
%run ./sem_anon.exe
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pthread.h>
#include <semaphore.h>
const char* log_prefix(const char* file, int line) {
struct timeval tp; gettimeofday(&tp, NULL); struct tm ltime; localtime_r(&tp.tv_sec, <ime);
static __thread char prefix[100];
size_t time_len = strftime(prefix, sizeof(prefix), "%H:%M:%S", <ime);
sprintf(prefix + time_len, ".%03ld %s:%3d [pid=%d]", tp.tv_usec / 1000, file, line, getpid());
return prefix;
}
#define log_printf_impl(fmt, ...) { dprintf(2, "%s: " fmt "%s", log_prefix(__FILE__, __LINE__), __VA_ARGS__); }
#define log_printf(...) log_printf_impl(__VA_ARGS__, "")
// process-aware assert
#define pa_assert(stmt) if (stmt) {} else { log_printf("'" #stmt "' failed\n"); exit(EXIT_FAILURE); }
typedef enum {
VALID_STATE = 0,
INVALID_STATE = 1
} state_t;
typedef struct {
sem_t semaphore;
state_t current_state; // protected by semaphore
} shared_state_t;
shared_state_t* state; // interprocess state
void process_safe_func() {
// all function is critical section, protected by mutex
sem_wait(&state->semaphore); // ~ lock
pa_assert(state->current_state == VALID_STATE);
state->current_state = INVALID_STATE; // do some work with state.
sched_yield();
state->current_state = VALID_STATE;
sem_post(&state->semaphore); // ~ unlock
}
void process_func(int process_num)
{
log_printf(" Process %d started\n", process_num);
for (int j = 0; j < 10000; ++j) {
process_safe_func();
}
log_printf(" Process %d finished\n", process_num);
}
shared_state_t* create_state() {
shared_state_t* state = mmap(
/* desired addr, addr = */ NULL,
/* length = */ sizeof(shared_state_t),
/* access attributes, prot = */ PROT_READ | PROT_WRITE,
/* flags = */ MAP_SHARED | MAP_ANONYMOUS,
/* fd = */ -1,
/* offset in file, offset = */ 0
);
pa_assert(state != MAP_FAILED);
// create interprocess semaphore
pa_assert(sem_init(
&state->semaphore,
1, // interprocess? (0 if will be used in one process)
1 // initial value
) == 0);
state->current_state = VALID_STATE;
return state;
}
void delete_state(shared_state_t* state) {
pa_assert(sem_destroy(&state->semaphore) == 0);
pa_assert(munmap(state, sizeof(shared_state_t)) == 0);
}
int main()
{
log_printf("Main process started\n");
state = create_state();
const int process_count = 2;
pid_t processes[process_count];
for (int i = 0; i < process_count; ++i) {
log_printf("Creating process %d\n", i);
pa_assert((processes[i] = fork()) >= 0);
if (processes[i] == 0) {
process_func(i);
exit(0);
}
}
for (int i = 0; i < process_count; ++i) {
int status;
pa_assert(waitpid(processes[i], &status, 0) != -1)
pa_assert(WIFEXITED(status) && WEXITSTATUS(status) == 0);
log_printf("Process %d 'joined'\n", i);
}
delete_state(state);
log_printf("Main process finished\n");
return 0;
}
```
# <a name="sem_named"></a> Именнованные семафоры
В примере про именованные объекты разделяемой памяти мы явно запускали процесс для инициализации состояния до процессов-воркеров, чтобы избежать гонки инициализации состояния.
В этом примере предлагается способ избежать гонки используя именованный семафор.
В примере используется одно и то же имя для объекта разделяемой памяти и семафора. Это безопасно, так как имя семафора автоматически расширяется префиксом или суффиксом `sem`. То есть в результате имена разные.
```
%%cpp sem_named.c
%# Обратите внимание: -lrt. Здесь нужна новая разделяемая библиотека
%run gcc -Wall -fsanitize=thread sem_named.c -lrt -lpthread -o s.exe
%run ./s.exe work 1 /s42 & PID=$! ; ./s.exe work 2 /s42 ; wait $PID
%run ./s.exe cleanup /s42 # необязательная команда. Будет работать и без нее
#define _GNU_SOURCE
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pthread.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <semaphore.h>
const char* log_prefix(const char* file, int line) {
struct timeval tp; gettimeofday(&tp, NULL); struct tm ltime; localtime_r(&tp.tv_sec, <ime);
static __thread char prefix[100];
size_t time_len = strftime(prefix, sizeof(prefix), "%H:%M:%S", <ime);
sprintf(prefix + time_len, ".%03ld %s:%3d [pid=%d]", tp.tv_usec / 1000, file, line, getpid());
return prefix;
}
#define log_printf_impl(fmt, ...) { dprintf(2, "%s: " fmt "%s", log_prefix(__FILE__, __LINE__), __VA_ARGS__); }
#define log_printf(...) log_printf_impl(__VA_ARGS__, "")
// process-aware assert
#define pa_warn_if_not(stmt) if (stmt) {} else { log_printf("WARNING: '" #stmt "' failed\n"); }
#define pa_assert(stmt) if (stmt) {} else { log_printf("'" #stmt "' failed\n"); exit(EXIT_FAILURE); }
typedef enum {
VALID_STATE = 0,
INVALID_STATE = 1
} state_t;
typedef struct {
pthread_mutex_t mutex;
state_t current_state; // protected by mutex
} shared_state_t;
void process_safe_func(shared_state_t* state) {
// all function is critical section, protected by mutex
pthread_mutex_lock(&state->mutex); // try comment lock&unlock out and look at result
pa_assert(state->current_state == VALID_STATE);
state->current_state = INVALID_STATE; // do some work with state.
sched_yield();
state->current_state = VALID_STATE;
pthread_mutex_unlock(&state->mutex);
}
shared_state_t* load_state(const char* shm_name, bool do_create) {
// открываем / создаем объект разделяемой памяти
int fd = shm_open(shm_name, O_RDWR | (do_create ? O_CREAT : 0), 0644);
if (do_create) {
pa_assert(ftruncate(fd, sizeof(shared_state_t)) == 0);
}
shared_state_t* state = mmap(
/* desired addr, addr = */ NULL,
/* length = */ sizeof(shared_state_t),
/* access attributes, prot = */ PROT_READ | PROT_WRITE,
/* flags = */ MAP_SHARED,
/* fd = */ fd,
/* offset in file, offset = */ 0
);
pa_assert(state != MAP_FAILED);
if (do_create) {
// create interprocess mutex
pthread_mutexattr_t mutex_attrs;
pa_assert(pthread_mutexattr_init(&mutex_attrs) == 0);
// Важно!
pa_assert(pthread_mutexattr_setpshared(&mutex_attrs, PTHREAD_PROCESS_SHARED) == 0);
pa_assert(pthread_mutex_init(&state->mutex, &mutex_attrs) == 0);
pa_assert(pthread_mutexattr_destroy(&mutex_attrs) == 0);
state->current_state = VALID_STATE;
}
return state;
}
void unload_state(shared_state_t* state) {
pa_assert(munmap(state, sizeof(shared_state_t)) == 0);
}
shared_state_t* process_safe_init_and_load(const char* name) {
// succeeded only for first process. This process will initalize state
sem_t* init_semaphore = sem_open(
name, O_CREAT | O_EXCL, 0644, 0); // Создаем семафор с изначальным значением 0. Если семафор уже есть, то команда пофейлится
if (init_semaphore != SEM_FAILED) { // Если смогли сделать семафор, то мы - главный процесс, ответственный за инициализацию
// initializing branch for initializing process
shared_state_t* state = load_state(name, /*do_create=*/ 1);
sem_post(init_semaphore); // Кладем в "ящик" весточку, что стейт проинициализирован
sem_close(init_semaphore);
return state;
} else { // Если мы не главные процесс, то подождем инициализацию
// branch for processes waiting initialisation
init_semaphore = sem_open(name, 0);
pa_assert(init_semaphore != SEM_FAILED);
sem_wait(init_semaphore); // ждем весточку, что стейт готов
sem_post(init_semaphore); // возвращаем весточку на место, чтобы другим процессам тоже досталось
sem_close(init_semaphore);
return load_state(name, /*do_create=*/ 0);
}
}
int main(int argc, char** argv)
{
pa_assert(argc >= 2);
if (strcmp("cleanup", argv[1]) == 0) {
log_printf(" Cleanup sem and shm: %s\n", argv[2]);
pa_warn_if_not(shm_unlink(argv[2]) == 0);
pa_warn_if_not(sem_unlink(argv[2]) == 0);
log_printf(" State created\n");
} else if (strcmp("work", argv[1]) == 0) {
pa_assert(argc >= 3);
int worker = strtol(argv[2], 0, 10);
log_printf(" Worker %d started\n", worker);
shared_state_t* state = process_safe_init_and_load(argv[3]);
for (int j = 0; j < 10000; ++j) {
process_safe_func(state);
}
unload_state(state);
log_printf(" Worker %d finished\n", worker);
} else {
pa_assert(0 && "unknown command")
}
return 0;
}
```
### Важное замечание про именованные и неименованные семафоры
Для открытия/закрытия именованных семафоров используются `sem_open` и `sem_close`.
А для неименованных `sem_init` и `sem_destroy`.
Смешивать эти операции определенно не стоит, если конечно, вы где-нибудь не найдете документацию, подтверждающую обратное. Делать `sem_open`, а затем `sem_destroy`, это как создавать объект конструктором одного класса, а уничтожать деструктором другого (для родственных классов, без виртуального деструктора).
# <a name="sem_signal"></a> Сочетаемость семафоров и сигналов
Нет этой сочетаемости.
```
process 1
> send signal to process 2
> sem_post
process 2
> sem_wait
> check variable that is set in signal handler
```
Не гарантируется, что сигнал будет доставлен и обработан до того, как отработает sem_wait.
```
%%cpp sem_and_signal.c
%run gcc -Wall -fsanitize=thread -lrt sem_and_signal.c -o sem_and_signal.exe
%run ./sem_and_signal.exe
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pthread.h>
#include <semaphore.h>
const char* log_prefix(const char* file, int line) {
struct timeval tp; gettimeofday(&tp, NULL); struct tm ltime; localtime_r(&tp.tv_sec, <ime);
static __thread char prefix[100];
size_t time_len = strftime(prefix, sizeof(prefix), "%H:%M:%S", <ime);
sprintf(prefix + time_len, ".%03ld %s:%3d [pid=%d]", tp.tv_usec / 1000, file, line, getpid());
return prefix;
}
#define log_printf_impl(fmt, ...) { dprintf(2, "%s: " fmt "%s", log_prefix(__FILE__, __LINE__), __VA_ARGS__); }
#define log_printf(...) log_printf_impl(__VA_ARGS__, "")
// process-aware assert
#define pa_assert(stmt) if (stmt) {} else { log_printf("'" #stmt "' failed\n"); exit(EXIT_FAILURE); }
volatile sig_atomic_t signal_count = 0;
static void handler(int signum) {
signal_count += 1;
}
typedef struct {
sem_t semaphore_1;
sem_t semaphore_2;
} shared_state_t;
shared_state_t* state;
shared_state_t* create_state() {
shared_state_t* state = mmap(
/* desired addr, addr = */ NULL,
/* length = */ sizeof(shared_state_t),
/* access attributes, prot = */ PROT_READ | PROT_WRITE,
/* flags = */ MAP_SHARED | MAP_ANONYMOUS,
/* fd = */ -1,
/* offset in file, offset = */ 0
);
pa_assert(state != MAP_FAILED);
pa_assert(sem_init(&state->semaphore_1, 1, 0) == 0);
pa_assert(sem_init(&state->semaphore_2, 1, 0) == 0);
return state;
}
void delete_state(shared_state_t* state) {
pa_assert(sem_destroy(&state->semaphore_1) == 0);
pa_assert(sem_destroy(&state->semaphore_2) == 0);
pa_assert(munmap(state, sizeof(shared_state_t)) == 0);
}
int main()
{
log_printf("Main process started\n");
state = create_state();
pid_t process = fork();
if (process == 0) {
sigaction(SIGUSR1, &(struct sigaction){.sa_handler = handler, .sa_flags = SA_RESTART}, NULL);
sleep(1); // imitate synchronous start
for (int i = 0; ; ++i) {
sem_wait(&state->semaphore_1);
int cnt = signal_count;
if (cnt != i + 1) {
fprintf(stderr, "Signals and semaphors are not ordered... i = %d, signals_count = %d\n", i, cnt);
exit(-1);
}
if (i % 100000 == 0) {
fprintf(stderr, "i = %d\n", i);
}
sem_post(&state->semaphore_2);
}
} else {
sleep(1); // imitate synchronous start
int status;
int ret;
while ((ret = waitpid(process, &status, WNOHANG)) == 0) {
kill(process, SIGUSR1);
sem_post(&state->semaphore_1);
while (sem_timedwait(&state->semaphore_2, &(struct timespec){.tv_nsec = 500000000}) == -1
&& (ret = waitpid(process, &status, WNOHANG)) == 0) {
}
}
pa_assert(ret != -1)
pa_assert(WIFEXITED(status) && WEXITSTATUS(status) == 0);
}
delete_state(state);
log_printf("Main process finished\n");
return 0;
}
```
Ломается, долго, но ломается. Так, что нельзя рассчитывать, что сигнал отрпавленный раньше, будет обработан до того, как дойдет событие через sem_post/sem_wait отправленное позже.
Что неудивительно, так как семафоры работают напрямую через разделяемую память, а в обработке сигналов принимает участие еще и планировщик задач.
Если система многоядерная и два процесса выполняются одновременно, то между отправкой сигнала и получением события через семафор может не случиться переключений процессов планировщиком - тогда сигнал будет доставлен позже.
А на одноядерной системе представленная схема скорее всего будет работать. Так как между sem_post в одном процессе и завершением sem_wait в другом должно случиться переключение на второй процесс. В ходе которого вызовутся обработчики.
# <a name="hw"></a> Комментарии к ДЗ
*
| github_jupyter |
<a href="https://colab.research.google.com/github/babasxn/Titanic_Survival_Predictions/blob/main/Titanic_Survival_Predictions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
#Train Data Cleaning
```
!unzip /content/titanic.zip
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
testData=pd.read_csv("/content/test.csv")
trainData=pd.read_csv("/content/train.csv")
trainData.head()
trainData.drop('Name',axis=1, inplace=True)
trainData.drop('Embarked',axis=1, inplace=True)
trainData.drop('Ticket',axis=1, inplace=True)
trainData.drop('Cabin',axis=1, inplace=True)
#trainData.drop('PassengerId',axis=1, inplace=True)
trainData.head()
trainData.info()
trainData['Age']=trainData['Age'].fillna(value=trainData['Age'].mean())
trainData.info()
from sklearn.preprocessing import LabelEncoder
le=LabelEncoder()
trainData['Sex']=le.fit_transform(trainData['Sex'])
#1- Male, 0-Female
trainData.head()
x = trainData.drop('Survived',axis = 1) # features
y = trainData['Survived'] # target
x
y
from sklearn.preprocessing import StandardScaler
ss = StandardScaler() # Min Max scalar
for col in x.columns:
x[col] = ss.fit_transform(x[col].values.reshape((-1,1)))
x
import seaborn as sns
plt.figure(figsize=(12,8))
sns.heatmap(x.corr(),annot=True)
plt.show()
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y, test_size=0.2, random_state=12)
```
#Test Data Cleaning
```
testData.head()
testData.drop('Name',axis=1, inplace=True)
testData.drop('Embarked',axis=1, inplace=True)
testData.drop('Ticket',axis=1, inplace=True)
testData.drop('Cabin',axis=1, inplace=True)
testData.info()
from sklearn.preprocessing import LabelEncoder
le=LabelEncoder()
testData['Sex']=le.fit_transform(testData['Sex'])
#1- Male, 0-Female
testData['Age']=testData['Age'].fillna(value=trainData['Age'].mean())
testData.info()
from sklearn.linear_model import LinearRegression
# Model object
lr = LinearRegression(normalize=True)
pclass = trainData['Pclass'].values.reshape((-1,1))
fare = trainData['Fare'].values.reshape((-1,1))
lr.fit(pclass, fare) # fit the model
testData[testData['Fare'].isnull() == True]['Pclass']
lr.predict([[3]])
testData.fillna(9.63, inplace = True)
testData.info()
forTest=pd.DataFrame({"PassengerID": testData['PassengerId']})
forTest
#testData.drop('PassengerId',axis=1, inplace=True)
```
#Modelling
```
from sklearn.base import clone
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV # This is for hyperparamter tuning
from sklearn.metrics import accuracy_score # to mesasure the accuracy of the model
from sklearn.neighbors import KNeighborsClassifier # To use the knn algorithm
# KNN--> K- Nearest negihbors
knn = KNeighborsClassifier()
# Set parameters
n_neighbors = list(np.arange(3, 200, 2)) #---> last element
weights = ['uniform', 'distance']
algorithm = ['auto', 'ball_tree', 'kd_tree', 'brute']
p = [1,2] #--> Distance: Euclidean and Manhattan
# dictonary for parameters
params = {'n_neighbors' : n_neighbors,
'weights' : weights,
'algorithm' : algorithm,
'p' : p
}
# RSCV
GSCV_Knn = GridSearchCV(knn, params, scoring='accuracy', n_jobs=-1, cv = 5, verbose=1) # n_iter = 20
# FIt the model
GSCV_Knn.fit(x, y)
GSCV_Knn.best_estimator_
KNN_best_model = clone(GSCV_Knn.best_estimator_)
KNN_best_model # best KNN modell
GSCV_Knn.score(x, y)*100
```
#Predictions
```
predictions = GSCV_Knn.predict(testData)
predictions
df=pd.DataFrame({"PassengerId": forTest['PassengerID'], "Survived":predictions})
display(df)
df.to_csv('Titanic_prediction2',index=False)
```
| github_jupyter |
# 随机矩阵引论:理论与实践
[**Introduction to Random Matrices: Theory and Practice**](https://arxiv.org/pdf/1712.07903.pdf) by Giacomo Livan, Marcel Novaes, Pierpaolo Vivo (2017)
该书给出了 **Matlab** 代码实现,下面是我的 **Python 2.7** 代码实现
## Chapter 0 辅助函数
+ 双阶乘函数
```
def double_factorial(n):
x = 1
if n % 2 == 0:
for k in range(int(n / 2)):
x = x * (2 * (k + 1))
else:
for k in range(int((n + 1) / 2)):
x = x * (2 * (k + 1) - 1)
return x
print double_factorial(5), double_factorial(6)
%notebook inline
```
## Chapter 1 Getting Started
+ This program plots a numerical histogram of the **eigenvalue density of Gaussian random matrix ensembles (Orthogonal, Unitary and Symplectic)**. You will be asked to select the ensemble by providing the value of the Dyson beta index (1 for GOE, 2 for GUE, 4 for GSE), to provide the matrix size N, and to choose the number of matrices to be diagonalized.
```
import numpy as np
from numpy import histogram, mat, diff
from numpy.linalg import eigvalsh
import matplotlib.pyplot as plt
# Choose value of beta (1 for GOE, 2 for GUE, 4 for GSE):
beta = input()
while beta != 1 and beta != 2 and beta != 4:
print 'Error: beta has to be equal to 1, 2, or 4'
beta = input()
# Choose matrix size:
N = 8
# Choose number of matrices to be diagonalized:
Nmatr = 50000
x = []
if beta == 1:
# Gaussian Orthogonal Ensemble
for nm in range(Nmatr):
M = np.random.randn(N, N)
M = (M + M.T) / 2
x = np.append(x, eigvalsh(M))
elif beta == 2:
# Gaussian Unitary Ensemble
for nm in range(Nmatr):
M = np.random.randn(N, N) + 1j * np.random.randn(N, N)
M = mat(M)
M = (M + M.H) / 2
x = np.append(x, eigvalsh(M))
else:
# Gaussian Symplectic Ensemble
for nm in range(Nmatr):
A = np.random.randn(N, N) + 1j * np.random.randn(N, N)
B = np.random.randn(N, N) + 1j * np.random.randn(N, N)
M1 = np.hstack((A, B))
M2 = np.hstack((-np.conjugate(B), np.conjugate(A)))
M = np.vstack((M1, M2))
M = mat(M)
M = (M + M.H) / 2
x = np.append(x, np.unique(eigvalsh(M))) # The unique function gets rid of the double eigenvalues
plt.figure(figsize=(5, 5))
# Normalized eigenvalue histogram
n, bins = histogram(x, bins=50, normed=1)
bins_new = []
for i in range(len(bins) - 1):
bins_new.append((bins[i] + bins[i + 1]) / 2)
plt.plot(bins_new, n, 'o-')
plt.title('Eigenvalue Density', fontsize=18)
plt.xlabel(r'$x$', fontsize=18)
plt.ylabel(r'$\rho(x)$', fontsize=18)
plt.show()
```
## Chapter 2 Value the eigenvalue
+ This program plots a numerical histogram of the **eigenvalue spacing distribution for 2x2 GOE random matrices**, and compares it with the **Wigner surmise**. You will be asked to choose the number of matrices to be diagonalized.
> Why is it defined a ’surmise’? After all, it is the result of an exact calculation! The story goes as follows: at a conference on Neutron Physics by Time-of-Flight, held at the Oak Ridge National Laboratory in 1956, people asked a question about the possible shape of the distribution of the spacings of energy levels in a heavy nucleus. E. P. Wigner, who was in the audience, walked up to the blackboard and guessed (= surmised) the answer given above.
```
# Choose number of matrices to be diagonalized:
Nmatr = input()
x = []
for nm in range(Nmatr):
#M = np.random.randn(2, 2) / np.sqrt(2)
m1 = np.random.randn()
m2 = np.random.randn()
m3 = np.random.randn() / np.sqrt(2)
M = np.array([[m1, m3], [m3, m2]])
x = np.append(x, abs(diff(eigvalsh(M))))
plt.figure(figsize=(5, 5))
# Normalized spacing histogram
n, bins = histogram(x, bins=50, normed=1)
bins_new = []
for i in range(len(bins) - 1):
bins_new.append((bins[i] + bins[i + 1]) / 2)
plt.plot(bins_new, n, 'or')
x_new = np.linspace(0, np.max(x), 100)
# Definition of the Wigner surmise function
p = lambda s: s * np.exp(- s ** 2 / 4) / 2
plt.plot(x_new, p(x_new))
plt.title('Wigner surmise', fontsize=18)
plt.xlabel(r'$s$', fontsize=18)
plt.ylabel(r'$p(s)$', fontsize=18)
plt.show()
```
## Chapter 3 Classified Material & Chapter 4 The fluid semicircle
+ This program generates the **equilibrium density of the Coulomb gas of particles (eigenvalues)** discussed in Chapters 3 and 4, and compares it to the **semicircle distribution**. Starting from an initial random particle configuration, a simple Monte Carlo scheme is applied: at each time step the program tries to change the position of a randomly selected particle by a Gaussian increment epsilon. The move is accepted with probability min(1, exp(-beta*DeltaH)), where DeltaH is the energy difference caused by the move. You will be asked to specify the number N of particles in the gas (which is equivalent to the matrix size in the corresponding ensemble), and the value of the Dyson Index beta, which in this context plays the role of the system's inverse temperature. You will also be asked to select the number of Monte Carlo sweeps, where one sweep corresponds to N attempted moves. A good rule of thumb is to accept roughly 35-50% of the proposed Monte Carlo moves, and the standard deviation of the increments must be tuned accordingly. The program's default value is set at 10/sqrt(N).
```
import numpy as np
from numpy import histogram
import matplotlib.pyplot as plt
from __future__ import division
N = 500 # Number of particles (matrix size)
Nsweeps = 1000 # Number of sweeps. A sweep consists of N attempted Monte Carlo moves
beta = input() # Inverse temperature / Dyson index
while beta != 1 and beta != 2 and beta != 4:
print 'Error: beta has to be equal to 1, 2, or 4'
beta = input()
sigma = 10 / np.sqrt(N) # Standard deviation of the Gaussian distribution for Monte Carlo moves
# Initial uniform distribution of particles between -sqrt(2*N) and sqrt(2*N)
x = -np.sqrt(2 * N) + 2 * np.sqrt(2 * N) * np.random.rand(N)
for ns in range(Nsweeps):
count = 0
for n in range(N):
k = np.random.randint(N) # Random selection of a particle
epsilon = sigma * np.random.randn() # Size of the proposed position shift of particle k
# The particles' positions (except for particle k) are stored in
# an auxiliary vector aux, which is used to compute the change in
# energy (Hamiltonian) upon moving particle k from its current
# position x(k) to x(k)+epsilon
aux = np.hstack((x[0:k], x[k+1:]))
# Change in energy
DeltaH = epsilon ** 2 + epsilon * x[k] + np.sum(np.log(abs(x[k] - aux) / abs(x[k] + epsilon - aux)))
# The position change of particle k is accepted with probability min(1,exp(-beta*DeltaH))
if min(1, np.exp(-beta * DeltaH)) > np.random.rand():
x[k] = x[k] + epsilon
count = count + 1
# Printing to screen the number of completed sweeps, and the fraction of accepted moves in the latest sweep
if ns % 100 == 0:
print 'Sweep number: % d\nAccepted moves: %4.3f' % (ns, count / N)
# Plot of normalized particle density and Wigner's semicircle
plt.figure(figsize=(5, 5))
#n, bins, patches = plt.hist(x, bins=30, normed=1, facecolor='None', edgecolor='black',alpha=1, histtype='bar')
n, bins = histogram(x, bins=30, normed=1)
bins_new = []
for i in range(len(bins) - 1):
bins_new.append((bins[i] + bins[i + 1]) / 2)
plt.scatter(bins_new, n)
# Definition of the semicircle distribution function
rho = lambda x: np.sqrt(2 * N - x ** 2) / (np.pi * N)
# Plot of the semicircle distribution (between -sqrt(2*N) and sqrt(2*N))
x_sc = np.linspace(-np.sqrt(2 * N), np.sqrt(2 * N), N)
plt.plot(x_sc, rho(x_sc), 'r')
plt.title('Particle Density', fontsize=18)
plt.xlabel('x', fontsize=18)
plt.ylabel(r'$\rho(x)$', fontsize=18)
plt.xticks([-np.sqrt(2 * N), 0, np.sqrt(2*N)], [r'$-\sqrt{2N}$','0',r'$\sqrt{2N}$'])
plt.show()
```
## Chapter 5 Saddle-point-of-view
+ This program computes the results of Eqs. (5.21) and (5.22) and prints their values to screen
+ The fact that the soft edges are symmetrically located around the origin is a consequence of the symmetry of the confining potential under the exchange $x \rightarrow -x$.
+ **Question:** If I drop the symmetry requirements on the entries of the ensemble ($H_{ij}\ne H_{ji}$), what is the resulting analogue of the semicircle law for complex eigenvalues?
> This is called the **Girko-Ginibre (or circular) law**. In essence, for any sequence of random N × N matrices whose entries are i.i.d. random variables, all with mean zero and variance equal to 1/N, the limiting spectral density is the **uniform distribution over the unit disc in the complex plane**.
```
import numpy as np
from numpy import histogram, mat, diff
from numpy.linalg import eigvalsh
from scipy.integrate import quad
import matplotlib.pyplot as plt
from __future__ import division
# Endpoints of semicircle density
a = -np.sqrt(2)
b = -a
# Definition of the semicircle distribution function
sc = lambda x: np.sqrt(2 - x ** 2) / np.pi
# Integrand functions of the two integrals in Eq. (5.21)
integrand1 = lambda x: sc(x) * x ** 2
integrand2 = lambda x: sc(x) * np.log(x - a)
# Computing Eq. (5.21)
f_int = quad(integrand1, a, b)[0] / 4 + a ** 2 / 4 - quad(integrand2, a, b)[0] / 2
# Computing Eq. (5.22)
f = (-9 * a ** 4 + 4 * a ** 3 * b + 2 * a ** 2 * (5 * b ** 2 + 48) + 4 * a * b * (b ** 2 + 16)
- 256 * np.log(b - a) -9 * b ** 4 + 96 * b ** 2 + 512 * np.log(2)) / 512
print 'Result of Eq. 5.21: %5.4f' % f_int
print 'Result of Eq. 5.22: %5.4f' % f
```
+ This short code performs a numerical check of the **Tricomi equation** (5.14), where n*(x) is the semicircle density. The density is computed over a number Npts of points in the interval (-sqrt(2),sqrt(2)). The value in each point s is computed as a principal value integral, i.e. by splitting the integration domain (a,b) into two parts (a,s-eps) and (s+eps,b). You will be asked to enter the value of a parameter eps, which determines the accuracy with which the integral is computed, and the number of points where the integral is computed.
```
# Reads the number of points where the Tricomi equation integral is computed
Npts = input()
# Reads the value which determines the accuracy of the principal value
# integral (values in the range 1e-1 - 1e-10 are recommended)
eps = 1e-5
# Endpoints of semicircle density
a = -np.sqrt(2)
b = -a
# Setting the interval over which the Tricomi equation integral is computed
s = np.linspace(a, b, Npts)
v = np.zeros(Npts)
# Integrand function of the Tricomi equation integral
sc = lambda x: np.sqrt(2 - x ** 2) / np.pi
for i in range(Npts):
# Here the above integrand function is specialized to the particular
# point s(i) where the integral is going to be computed
integrand = lambda x: sc(x) / (s[i] - x)
# Principal value integral
v[i] = quad(integrand, a, s[i] - eps)[0] + quad(integrand, s[i] + eps, b)[0]
# Plotting the results of the principal value integrals and comparing them with the bisector line
plt.figure(figsize=(5, 5))
plt.plot(s, s, 'b')
plt.plot(s, v, 'or')
plt.title('Numerical check of Tricomi equation', fontsize=18)
plt.xlabel(r'$x$', fontsize=18)
plt.ylabel(r'$\mathrm{PV \ integral}$', fontsize=18)
plt.show()
```
+ This program plots a numerical histogram of the **rescaled densities for all three Gaussian Ensembles**, and compares them with the semicircle distribution. You will be asked to choose both the size and the number of matrices to be diagonalized (for each of the three ensembles).
```
# Choose matrix size:
# N = 10
N = 100
# N = 1000
# Choose number of matrices to be diagonalized:
Nmatr = 100
# Definition of the semicircle distribution function
rho = lambda x: np.sqrt(2 - x ** 2) / np.pi
x1 = []; x2 = []; x4 = []
for nm in range(Nmatr):
# GOE
M = np.random.randn(N, N) / np.sqrt(N)
M = (M + M.T) / 2
x1 = np.append(x1, eigvalsh(M))
# GUE
M = (np.random.randn(N, N) + 1j * np.random.randn(N, N)) / np.sqrt(2 * N)
M = mat(M)
M = (M + M.H) / 2
x2 = np.append(x2, eigvalsh(M))
# GSE
A = (np.random.randn(N, N) + 1j * np.random.randn(N, N)) / np.sqrt(4 * N)
B = (np.random.randn(N, N) + 1j * np.random.randn(N, N)) / np.sqrt(4 * N)
M1 = np.hstack((A, B))
M2 = np.hstack((-np.conjugate(B), np.conjugate(A)))
M = np.vstack((M1, M2))
M = mat(M)
M = (M + M.H) / 2
x4 = np.append(x4, np.unique(eigvalsh(M)))
plt.figure(figsize=(10, 10))
# Plot of the semicircle distribution
x = np.linspace(-np.sqrt(2), np.sqrt(2), 100)
semicircle, = plt.plot(x, rho(x), 'b')
# Normalized eigenvalue histogram
n1, bins1 = histogram(x1, bins=50, normed=1)
n2, bins2 = histogram(x2, bins=50, normed=1)
n4, bins4 = histogram(x4, bins=50, normed=1)
bins_new1 = []
for i in range(len(bins1) - 1):
bins_new1.append((bins1[i] + bins1[i + 1]) / 2)
bins_new2 = []
for i in range(len(bins2) - 1):
bins_new2.append((bins2[i] + bins2[i + 1]) / 2)
bins_new4 = []
for i in range(len(bins4) - 1):
bins_new4.append((bins4[i] + bins4[i + 1]) / 2)
GOE, = plt.plot(bins_new1, n1, 'or-')
GUE, = plt.plot(bins_new2, n2, 'ok-')
GSE, = plt.plot(bins_new4, n4, 'om-')
plt.title('Rescaled Eigenvalue Densities', fontsize=18)
plt.xlabel(r'$x$', fontsize=18)
plt.ylabel(r'$\rho(x)$', fontsize=18)
plt.xlim((-2, 2))
#plt.xticks([-np.sqrt(2), 0, np.sqrt(2)], [r'$-\sqrt{2}$','0',r'$\sqrt{2}$'])
plt.legend(handles=[semicircle, GOE, GUE, GSE], labels=['SemiCircle', 'GOE', 'GUE', 'GSE'], loc='upper right')
plt.show()
```
## Chapter 8 Resolve(nt) the semicircle
+ This program provides a quick numerical verification that the two **resolvent** branches in eq. (8.20) match eq. (8.5) for different signs. Namely, you will be asked to choose the real and imaginary parts of a complex number z (with real part such that -sqrt(2) < Real(z) < sqrt(2)). For small values of the imaginary parts you will be able to verify that G_plus matches the resolvent for -sqrt(2) < Real(z) < 0, whereas G_minus matches it for 0 < Real(z) < sqrt(2).
```
import numpy as np
from scipy.integrate import quad
re = input()
while abs(re) >= np.sqrt(2):
print 'ERROR: Real(z) must be smaller than sqrt(2) in absolute value'
re = input()
im = input()
z = re - 1j * im
# The value of the resolvent is computed in z
G = quad(lambda x: np.sqrt(2 - x ** 2) / (np.pi * (z - x)), -np.sqrt(2), np.sqrt(2))[0]
G_plus = lambda x: x + np.sqrt(x ** 2 - 2)
G_minus = lambda x: x - np.sqrt(x ** 2 - 2)
print 'Value of resolvent in z: %6.4f%+6.4fi' % (G.real, G.imag)
print 'Value of G plus in z: %6.4f%+6.4fi' % (G_plus(z).real, G_plus(z).imag)
print 'Value of G minus in z: %6.4f%+6.4fi' % (G_minus(z).real, G_minus(z).imag)
```
## Chapter 10 Finite N
+ What does in the bulk mean? The point is that Hermite polynomials (and other classical orthogonal polynomials) have two different asymptotics, according to the way their argument and parameter scale with N. This in turns corresponds to different regimes, namely different locations x where the spectrum is looked at, and different zooming resolutions.
## Chapter 11 Meet Andréief
+ This program performs an indirect numerical check of the **Andréief identity** by verifying that the equations reported in Chapter 11 (see, e.g., eq. (11.9)) correctly provide the **probability of a GUE matrix having a certain number of positive eigenvalues**. You will be asked to provide the matrix size N and the number n of positive eigenvalues. First, you will be shown the analytical prediction computed by the program for the aforementioned probability. Based on that, you will be able to choose the number of matrices to diagonalize numerically in order to obtain a numerical estimate for the same probability.
### 数值实验
```
import numpy as np
from numpy import *
from numpy.linalg import eigvalsh
import matplotlib.pyplot as plt
from __future__ import division
N = 5 # size of a GUE matrix
n = 2 # number of eigenvalues of a GUE matrix is positive
Nmatr = 1000 # samples of GUE matrices
count = 0
for nm in range(Nmatr):
M = np.random.randn(N, N) + 1j * np.random.randn(N, N)
M = mat(M)
M = (M + M.H) / 2
eigvals_pos = filter(lambda e: e > 0, eigvalsh(M))
if len(eigvals_pos) == n:
count = count + 1
p = count / Nmatr
print 'Numerically estimated probability of GUE matrix of size %d having %d positive eigenvalues: %.2f%%' % (N, n, p * 100.0)
```
### 符号计算
+ 这里,使用sympy库进行高维矩阵的符号计算非常慢,利用**符号计算(symbolic computation)**方法应该可以大幅改进算法效率
```
from sympy import Matrix, Symbol, zeros, diff, det, factorial, simplify, exp, sin
N = 5 # size of a GUE matrix
n = 2 # number of eigenvalues of a GUE matrix is positive
z = Symbol('z', integer=True)
A = Matrix(N, N, lambda j, k: ((-1) ** (j + k) + z) * 2 ** (((j + k) - 3) / 2) * factorial(((j + k) - 1) / 2))
B = Matrix(N, N, lambda j, k: ((-1) ** (j + k) + 1) * 2 ** (((j + k) - 3) / 2) * factorial(((j + k) - 1) / 2))
phi = A.det() / B.det()
phi_der = diff(phi, z, n) / factorial(n)
p = phi_der.subs(z, 0)
print 'Theoretical probability of GUE matrix of size %d having %d positive eigenvalues: %.2f%%' % (N, n, p.evalf() * 100.0)
```
+ This code performs a symbolic check of the **Toda recurrence** of equations (11.11) and (11.12). You will be asked to type in a function a0(x) that will be used to fill the entries of the tau matrices through derivation, i.e. a1(x) = a0'(x), a2(x) = a1'(x) = a0''(x), and so on.
```
x = Symbol('x', integer=True)
# Reads the function a0 to be used in the example. In order for the code
# to produce a result quickly we recommend using a smooth and simple
# function, e.g. a0(x) = cos(x), a0(x) = exp(-x)
a0 = exp(x)
# Choose value of n:
n = input()
# Allocating space for matrices that will be used to derive the functions
# tau_n and tau_{n+1}
tau_n = Matrix(n, n, lambda j, k: diff(a0, x, j + k))
tau_n_plus_1 = Matrix(n + 1, n + 1, lambda j, k: diff(a0, x, j + k))
# Computing values of tau functions as determinants of tau matrices
tau_n_minus_1 = det(tau_n[0:-1, 0:-1])
tau_n = simplify(det(tau_n))
tau_n_plus_1 = simplify(det(tau_n_plus_1))
# Computing difference between the two sides of equation (11.12)
res = simplify(diff(tau_n, x, 2) * tau_n - (diff(tau_n, x, 1)) ** 2 - tau_n_minus_1 * tau_n_plus_1)
print 'The difference between the two sides of equation (11.12) is: %3.2f' % res.evalf()
```
## Chapter 12 Finite N is not finished
+ This program plots a histogram of the **eigenvalue density obtained from the numerical diagonalization of random matrices from the Gaussian ensembles**, and compares it with the theoretical densities (eq. (12.22) for the GOE, (10.21) for the GUE, (12.38) for the GSE). You will be asked to select the ensemble by providing the value of the Dyson beta index (1 for GOE, 2 for GUE, 4 for GSE), to provide the matrix size N, and to choose the number of matrices to be diagonalized.
```
import numpy as np
from numpy import histogram, mat, diff, trapz, sign
from numpy.linalg import eigvalsh
from scipy.integrate import quad
from scipy.special import hermite, factorial
import matplotlib.pyplot as plt
from __future__ import division
# Choose value of beta (1 for GOE, 2 for GUE, 4 for GSE):
beta = input()
# Choose matrix size:
N = input()
# N = 8
if beta == 1:
while N % 2 != 0:
print 'Error: N has to be even for beta = 1'
N = input()
# Choose number of matrices to be diagonalized:
Nmatr = 50000
E = []
# The following IF condition selects the desired ensemble: a number Nmatr
# of matrices are diagonalized, and the eigenvalues are collected in the
# vector E
if beta == 1:
# Gaussian Orthogonal Ensemble
for nm in range(Nmatr):
M = np.random.randn(N, N)
M = (M + M.T) / 2
E = np.append(E, eigvalsh(M))
x = np.linspace(np.min(E), np.max(E), 1000)
# Computing the GOE density for finite even N (eq. 11.21)
rho = np.zeros(len(x))
a_N = 1
for k in range(int(N / 2)):
R_2k = np.array(map(hermite(2 * k), x)) * np.sqrt(2) / (np.pi ** (1 / 4) * 2 ** k * double_factorial(2 * k))
if k == 0:
R_2k1 = (-np.array(map(hermite(2 * k + 1), x))) * np.sqrt(2) / (np.pi ** (1 / 4) * 2 ** (k + 2) * double_factorial(2 * k - 1))
else:
R_2k1 = (4 * k * np.array(map(hermite(2 * k - 1), x)) - np.array(map(hermite(2 * k + 1), x))) * np.sqrt(2) / (np.pi ** (1 / 4) * 2 ** (k + 2) * double_factorial(2 * k - 1))
Phi_2k = np.zeros(len(x)); Phi_2k1 = np.zeros(len(x))
for i in range(len(x)):
Phi_2k[i] = trapz(np.multiply(np.multiply(R_2k, np.exp(-np.power(x, 2) / 2)), sign(x[i] - x)), x)
Phi_2k1[i] = trapz(np.multiply(np.multiply(R_2k1, np.exp(-np.power(x, 2) / 2)), sign(x[i]-x)), x)
rho = np.add(rho, np.multiply(np.exp(-np.power(x, 2) / 2), (np.multiply(R_2k, Phi_2k1) - np.multiply(R_2k1, Phi_2k))))
a_N = a_N * factorial(2 * k)
a_N = (-1) ** (N / 2) * 2 ** (N * (N - 2) / 4) / (np.pi ** (N / 4) * a_N)
Z = factorial(N) * a_N * 2 ** (N/2)
rho = factorial(N - 1) * 2 ** (N / 2 - 1) * a_N * rho
rho = rho / Z
elif beta == 2:
# Gaussian Unitary Ensemble
for nm in range(Nmatr):
M = np.random.randn(N, N) + 1j * np.random.randn(N, N)
M = mat(M)
M = (M + M.H) / 2
E = np.append(E, eigvalsh(M))
x = np.linspace(np.min(E), np.max(E), 1000)
# Computing the GUE density for finite N (eq. 10.20)
rho = np.zeros(len(x))
for j in range(N):
rho = np.add(rho, np.multiply(np.power(map(hermite(j), x / np.sqrt(2)), 2), np.exp(-np.power(x, 2) / 2)) / (2 ** j * factorial(j)))
rho = rho / (N * np.sqrt(2 * np.pi))
else:
# Gaussian Symplectic Ensemble
for nm in range(Nmatr):
A = np.random.randn(N, N) + 1j * np.random.randn(N, N)
B = np.random.randn(N, N) + 1j * np.random.randn(N, N)
M1 = np.hstack((A, B))
M2 = np.hstack((-np.conjugate(B), np.conjugate(A)))
M = np.vstack((M1, M2))
M = mat(M)
M = (M + M.H) / 2
E = np.append(E, np.unique(eigvalsh(M))) # The unique function gets rid of the double eigenvalues
x = np.linspace(np.min(E), np.max(E), 1000)
# Computing the GSE density for finite N (eq. 11.36)
rho = np.zeros(len(x))
for k in range(int(N)):
if k == 0:
Q_2k = np.ones(len(x)) * np.sqrt(2) / (np.pi ** (1/4))
Q_2k_tilde = np.ones(len(x))
Q_2k_der = np.zeros(len(x))
Q_2k_tilde_der = np.zeros(len(x))
else:
Q_2k_tilde = np.add(4 * k * Q_2k_tilde_old, np.array(map(hermite(2 * k), x / np.sqrt(2))))
Q_2k = Q_2k_tilde * np.sqrt(2) / (np.pi ** (1/4) * 2 ** k * double_factorial(2 * k))
Q_2k_tilde_der = 4 * k * np.add(Q_2k_tilde_der_old, np.array(map(hermite(2 * k - 1), x / np.sqrt(2))) / np.sqrt(2))
Q_2k_der = Q_2k_tilde_der * np.sqrt(2) / (np.pi ** (1/4) * 2 ** k * double_factorial(2 * k))
Q_2k1 = np.array(map(hermite(2 * k + 1), x / np.sqrt(2))) * np.sqrt(2) / (np.pi ** (1/4) * 2 ** (k + 1) * double_factorial(2 * k + 1))
Q_2k1_der = (2 * k + 1) * np.array(map(hermite(2 * k), x / np.sqrt(2))) /(np.pi ** (1/4) * 2 ** k * double_factorial(2 * k + 1))
rho = np.add(rho, np.multiply(np.exp(-x ** 2 / 2), np.multiply(Q_2k, Q_2k1_der) - np.multiply(Q_2k1, Q_2k_der)) / (2 * N))
Q_2k_tilde_old = Q_2k_tilde
Q_2k_tilde_der_old = Q_2k_tilde_der
plt.figure(figsize=(5, 5))
# Normalized eigenvalue histogram
n, bins = histogram(E, bins=50, normed=1)
bins_new = []
for i in range(len(bins) - 1):
bins_new.append((bins[i] + bins[i + 1]) / 2)
plt.plot(bins_new, n, 'or')
plt.plot(x, rho, 'b')
plt.title('Eigenvalue Density', fontsize=18)
plt.xlabel(r'$x$', fontsize=18)
plt.ylabel(r'$\rho(x)$', fontsize=18)
plt.show()
```
## Chapter 13 Classical Ensembles: Wishart-Laguerre & Chapter 14 Meet Marčenko and Pastur
+ This program plots a histogram of the **eigenvalue densities obtained via numerical diagonalization of Wishart-Laguerre random matrices** (for beta = 1,2,4) and compares them with the **Marčenko-Pastur density** for the corresponding matrix size. You will be asked to provide the sizes of the rectangular NxM matrices H used to build Wishart-Laguerre matrices of the type W = X'*X, and the number of matrices to be diagonalized.
+ Historically, one of the **earliest appearances** of a random matrix ensemble1 occurred in **1928**, when the Scottish mathematician **John Wishart** published a paper on multivariate data analysis in the journal Biometrika.
+ In Mathematics, however, the **1897** work by **Hurwitz** on the volume form of a general unitary matrix is of historical significance.
+ The Wishart ensemble is also referred to as **“Laguerre”**, since its spectral properties involve Laguerre polynomials, and also **“chiral”** in the context of applications to **Quantum Chromodynamics (QCD)**.
```
import numpy as np
from numpy import mat
from numpy.linalg import eigvalsh
import matplotlib.pyplot as plt
from __future__ import division
# Choose first matrix size:
N = input()
#N = 100
# Choose second matrix size:
M = input()
# M = 200
# M = 800
while N >= M:
print 'ERROR: N must be less than M\n'
N = input()
M = input()
# Defining the Marcenko-Pastur density function
c = N / M
xmin = (1 - 1 / np.sqrt(c)) ** 2
xmax = (1 + 1 / np.sqrt(c)) ** 2
rho = lambda x: np.sqrt((x - xmin) * (xmax - x)) / (2 * np.pi * x)
# Choose number of matrices to be diagonalized:
Nmatr = 5000
x1 = []; x2 = []; x4 = []
for nm in range(Nmatr):
# beta = 1
beta = 1
H = np.random.randn(N, M)
W = np.dot(H, H.T)
x1 = np.append(x1, eigvalsh(W) / (beta * N)) # Notice the rescaling of the eigenvalues
# beta = 2
H = np.random.randn(N, M) + 1j * np.random.randn(N, M)
H = mat(H)
W = np.dot(H, H.H)
x2 = np.append(x2, eigvalsh(W) / (beta * N)) # Notice the rescaling of the eigenvalues
# beta = 4
beta = 4
A = np.random.randn(N, N) + 1j * np.random.randn(N, N)
B = np.random.randn(N, N) + 1j * np.random.randn(N, N)
H1 = np.hstack((A, B))
H2 = np.hstack((-np.conjugate(B), np.conjugate(A)))
H = np.vstack((H1, H2))
H = mat(H)
W = np.dot(H, H.H)
x4 = np.append(x4, np.unique(eigvalsh(W)) / (beta * N)) # Notice the rescaling of the eigenvalues
plt.figure(figsize=(5, 5))
x = np.linspace(xmin, xmax, 1000)
MP, = plt.plot(x, rho(x), 'b')
# Plotting the histograms for the three numerical eigenvalue densities
n1, bins1 = histogram(x1, bins=15, normed=1)
n2, bins2 = histogram(x2, bins=15, normed=1)
n4, bins4 = histogram(x4, bins=15, normed=1)
bins_new1 = []
for i in range(len(bins1) - 1):
bins_new1.append((bins1[i] + bins1[i + 1]) / 2)
bins_new2 = []
for i in range(len(bins2) - 1):
bins_new2.append((bins2[i] + bins2[i + 1]) / 2)
bins_new4 = []
for i in range(len(bins4) - 1):
bins_new4.append((bins4[i] + bins4[i + 1]) / 2)
beta1, = plt.plot(bins_new1, n1, 'ob')
beta2, = plt.plot(bins_new2, n2, 'or')
beta4, = plt.plot(bins_new4, n4, 'om')
plt.title(r'Mar$c\check$enko-Pastur density', fontsize=18)
plt.xlabel(r'$x$', fontsize=18)
plt.ylabel(r'$\rho(x)$', fontsize=18)
plt.legend(handles=[MP, beta1, beta2, beta4], labels=['MP density', r'$\beta$ = 1', r'$\beta$ = 2', r'$\beta$ = 4'], loc='upper right')
plt.show()
```
## Chapter 15 Replicas...
+ This program provides a numerical verification that equations (15.2) and (15.6) coincide in a 2x2 case. The program generates a random 2x2 GOE matrix H and uses it to compute the numerical value of Z(x) according to the two formulas. You will be asked to choose the real and imaginary parts of the number x (imaginary part has to be positive).
```
import numpy as np
from numpy.linalg import eigvalsh
from scipy.integrate import nquad
# Choose real part of argument x:
#re = 0.2
re = input()
# Choose imaginary part of argument x:
# im = 4.4
im = input()
while im <= 0:
print 'ERROR: Imaginary part has to be positive'
im = input()
x = re - 1j * im
# Generating 2x2 GOE matrix
H = np.random.randn(2, 2) / np.sqrt(2)
H = (H + H.T) / 2
# Eigenvalues of matrix H
E = eigvalsh(H)
# Definition of integrand function for Z
f = lambda y1, y2: np.exp(- 1j * ((x - H[0, 0]) * y1 ** 2 + 2 * H[0, 1] * y1 * y2 + (x - H[1, 1]) * y2 ** 2) / 2)
# Z function
Z = nquad(f, [[-np.Inf, np.Inf], [-np.Inf, np.Inf]])[0]
# Explicit form of Z function
Z_exp = 2 * np.pi * np.exp(-(np.log(E[0] - x) + np.log(E[1] - x)) / 2 + 1j * np.pi / 2)
print 'Value of Z function computed as integral: %6.4f%+6.4fi' % (Z.real, Z.imag)
print 'Value of Z function computed explicitly via eigenvalues of H: %6.4f%+6.4fi' % (Z_exp.real, Z_exp.imag)
```
## Chapter 17 Born to be free
+ This program presents a numerical verification of the **free addition** example discussed in section 17.4, i.e. that of the addition of GOE and Wishart random matrices. You will be asked to select the size of the matrices (including the size of the rectangular matrices used to build Wishart matrices), the number of matrices to be numerically diagonalized, and the relative weight p between the two ensembles (with p=1 coinciding with the GOE and p=0 coinciding with the Wishart ensemble).
+ **Two random matrices are free if the traces of all non-commutative products of matrix polynomials, whose traces are zero, are zero.**
> 这里补充介绍Python中调用Matlab函数:
+ sympy中的solve, solveset求解复杂的代数方程异常慢, 建议选择Matlab, Mathematica或Maple等专门软件来处理这类符号计算问题.
```
#matlab
#syms G z a w
#sol = solve('w^2*G/2 + (1-w)*(1+a)/(1-(1-w)*G) + 1/G - z', 'G');
#sol = subs(sol,[a,w],[alpha,p]);
#sol = vpa(sol);
```
+ 当然也可以在Python中调用Matlab函数, 详细说明见[MathWorks教程](https://www.mathworks.com/help/matlab/matlab-engine-for-python.html)
+ 首先进入Matlab应用中相应的python目录中: cd /Applications/MATLAB_R2014b.app/extern/engines/python
+ 在root权限下安装python支持: sudo python setup.py install
```
import matlab
import matlab.engine as engine
eng = engine.start_matlab()
future = eng.sqrt(2.0, async=True)
res = future.result()
print(res)
eng.quit()
```
+ Hybrid computation of numerical and symbolical Python
```
import numpy as np
from numpy import histogram
from numpy.linalg import eigvalsh
import matplotlib.pyplot as plt
from sympy import symbols, solve
from __future__ import division
# Choose size of GOE and Wishart matrices:
#N = 100
N = input()
# Choose second dimension of rectangular matrices used to build Wishart matrices:
#T = 200
T = input()
while N >= T:
print 'ERROR: T must be larger than N\n'
N = input()
T = input()
# Parameters associated with Wishart matrices to be used in later calculations
c = N / float(T)
alpha = (1 - c) / c
# Choose relative weight of GOE matrices:
# p = 0.3
# p = 0.5
# p = 0.7
p = input()
# Choose number of matrices to be diagonalized:
Nmatr = 200
E = []
for nm in range(Nmatr):
# Generating GOE matrix
M = np.random.randn(N, N)
M = (M + M.T) / 2
# Generating Wishart matrix
H = np.random.randn(N, T)
W = np.dot(H, H.T)
# Sum of rescaled GOE and rescaled Wishart
H = p * M / np.sqrt(N) + (1 - p) * W / N
E = np.append(E, eigvalsh(H))
# In the following the analytical solution for the eigenvalue density is
# computed on a support ranging from the minimum to the maximum of the
# numerically obtained eigenvalues. The density is computed in a number
# Npts of points
Npts = 100
x = np.linspace(np.min(E), np.max(E), Npts)
# Defining symbolic variables: G denotes the resolvent, z denotes the
# complex variable the resolvent is a function of, whereas a and w are
# the symbolic variables that will be eventually replaced, respectively,
# by the numerical values of the parameter alpha = (1-c)/c and of the
# relative weight p.
G, z, a, w = symbols('G, z, a, w')
# Here the symbolic solution for the resolvent G is obtained, initially
# as a function of z, a, and w. Then, the numerical values of alpha and p
# are used to replace a and w. The sol variable is a 3-dimensional vector
# whose components represent solutions of the 3rd degree polynomial
# equation for G.
expr = w ** 2 * G / 2 + (1 - w) * (1 + a) / (1 - (1 - w) * G) + 1 / G - z
expr = expr.subs({a:alpha, w:p})
sol = solve(expr, G)
G = []
for i in range(Npts):
# Replacing the symbolic variable z with the numerical value of the
# point x(i) where the resolvent is being computed
tmp = [complex(s.subs({z: x[i]})) for s in sol]
# The following if condition selects solutions with a non-zero
# imaginary part (see Eq. 8.8)
if tmp[0].imag == 0:
G.append(abs(tmp[1].imag) / np.pi)
else:
G.append(abs(tmp[0].imag) / np.pi)
plt.figure(figsize=(5, 5))
# Normalized eigenvalue histogram
n, bins = histogram(E, bins=30, normed=1)
bins_new = []
for i in range(len(bins) - 1):
bins_new.append((bins[i] + bins[i + 1]) / 2)
plt.plot(bins_new, n, 'o')
plt.plot(x, G, 'r')
plt.title('GOE + Wishart free sum', fontsize=18)
plt.xlabel(r'$x$', fontsize=18)
plt.ylabel(r'$\rho(x)$', fontsize=18)
plt.show()
```
| github_jupyter |
# Example: CanvasXpress bar Chart No. 8
This example page demonstrates how to, using the Python package, create a chart that matches the CanvasXpress online example located at:
https://www.canvasxpress.org/examples/bar-8.html
This example is generated using the reproducible JSON obtained from the above page and the `canvasxpress.util.generator.generate_canvasxpress_code_from_json_file()` function.
Everything required for the chart to render is included in the code below. Simply run the code block.
```
from canvasxpress.canvas import CanvasXpress
from canvasxpress.js.collection import CXEvents
from canvasxpress.render.jupyter import CXNoteBook
cx = CanvasXpress(
render_to="bar8",
data={
"x": {
"Drug Sensitivity": [
"Sensitive",
"Sensitive",
"Sensitive",
"Sensitive",
"Sensitive",
"Resistant",
"Resistant",
"Resistant"
],
"IC50": [
0.08,
0.07,
0.06,
0.05,
0.04,
0.03,
0.02,
0.01
]
},
"y": {
"vars": [
"V1"
],
"smps": [
"S1",
"S2",
"S3",
"S4",
"S5",
"S6",
"S7",
"S8"
],
"data": [
[
10,
15,
20,
30,
40,
70,
80,
90
]
]
}
},
config={
"axisTitleFontStyle": "italic",
"colorBy": "Drug Sensitivity",
"colorScheme": "CanvasXpress",
"decorationScaleFontFactor": 1.3,
"decorations": {
"line": [
{
"align": "left",
"width": 2,
"value": 50,
"label": "Cutoff",
"color": "rgb(255,0,0)"
}
]
},
"graphOrientation": "vertical",
"graphType": "Bar",
"legendBox": True,
"showFunctionNamesAfterRender": False,
"smpTitle": "Cell Lines",
"smpTitleFontStyle": "bold",
"title": "Random data set",
"xAxis2Show": False
},
width=613,
height=613,
events=CXEvents(),
after_render=[],
other_init_params={
"version": 35,
"events": False,
"info": False,
"afterRenderInit": False,
"noValidate": True
}
)
display = CXNoteBook(cx)
display.render(output_file="bar_8.html")
```
| 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.
```
# Automatically upgrade code to TensorFlow 2
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/upgrade">
<img src="https://www.tensorflow.org/images/tf_logo_32px.png" />
View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/upgrade.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/docs/blob/master/site/en/guide/upgrade.ipynb">
<img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />
View source on GitHub</a>
</td>
<td>
<a target="_blank" href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/upgrade.ipynb">
<img src="https://www.tensorflow.org/images/download_logo_32px.png" />
Download notebook</a>
</td>
</table>
TensorFlow 2.0 includes many API changes, such as reordering arguments, renaming symbols, and changing default values for parameters. Manually performing all of these modifications would be tedious and prone to error. To streamline the changes, and to make your transition to TF 2.0 as seamless as possible, the TensorFlow team has created the `tf_upgrade_v2` utility to help transition legacy code to the new API.
Note: `tf_upgrade_v2` is installed automatically for TensorFlow 1.13 and later (including all TF 2.0 builds).
Typical usage is like this:
<pre class="devsite-terminal devsite-click-to-copy prettyprint lang-bsh">
tf_upgrade_v2 \
--intree my_project/ \
--outtree my_project_v2/ \
--reportfile report.txt
</pre>
It will accelerate your upgrade process by converting existing TensorFlow 1.x Python scripts to TensorFlow 2.0.
The conversion script automates as much as possible, but there are still syntactical and stylistic changes that cannot be performed by the script.
## Compatibility modules
Certain API symbols can not be upgraded simply by using a string replacement. To ensure your code is still supported in TensorFlow 2.0, the upgrade script includes a `compat.v1` module. This module replaces TF 1.x symbols like `tf.foo` with the equivalent `tf.compat.v1.foo` reference. While the compatibility module is nice, we recommend that you manually proofread replacements and migrate them to new APIs in the `tf.*` namespace instead of `tf.compat.v1` namespace as quickly as possible.
Because of TensorFlow 2.x module deprecations (for example, `tf.flags` and `tf.contrib`), some changes can not be worked around by switching to `compat.v1`. Upgrading this code may require using an additional library (for example, [`absl.flags`](https://github.com/abseil/abseil-py)) or switching to a package in [tensorflow/addons](http://www.github.com/tensorflow/addons).
## Recommended upgrade process
The rest of this guide demonstrates how to use the upgrade script. While the upgrade script is easy to use, it is strongly recomended that you use the script as part of the following process:
1. **Unit Test**: Ensure that the code you’re upgrading has a unit test suite with reasonable coverage. This is Python code, so the language won’t protect you from many classes of mistakes. Also ensure that any dependency you have has already been upgraded to be compatible with TensorFlow 2.0.
1. **Install TensorFlow 1.14**: Upgrade your TensorFlow to the latest TensorFlow 1.x version, at least 1.14. This includes the final TensorFlow 2.0 API in `tf.compat.v2`.
1. **Test With 1.14**: Ensure your unit tests pass at this point. You’ll be running them repeatedly as you upgrade so starting from green is important.
1. **Run the upgrade script**: Run `tf_upgrade_v2` on your entire source tree, tests included. This will upgrade your code to a format where it only uses symbols available in TensorFlow 2.0. Deprecated symbols will be accessed with `tf.compat.v1`. These will will eventually require manual attention, but not immediately.
1. **Run the converted tests with TensorFlow 1.14**: Your code should still run fine in TensorFlow 1.14. Run your unit tests again. Any error in your tests here means there’s a bug in the upgrade script. [Please let us know](https://github.com/tensorflow/tensorflow/issues).
1. **Check the upgrade report for warnings and errors**: The script writes a report file that explains any conversions you should double-check, or any manual action you need to take. For example: Any remaining instances of contrib will require manual action to remove. Please consult [the RFC for more instructions](https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md).
1. **Install TensorFlow 2.0**: At this point it should be safe to switch to TensorFlow 2.0
1. **Test with `v1.disable_v2_behavior`**: Re-running your tests with al `v1.disable_v2_behavior()` in the tests main function should give the same results as running under 1.14.
1. **Enable V2 Behavior**: Now that your tests work using the v2 API, you can start looking into turning on v2 behavior. Depending on how your code is written this may require some changes. See the [Migration guide](migrate.ipynb) for details.
## Using the upgrade script
### Setup
Before getting started ensure that TensorlFlow 2.0 is installed.
```
from __future__ import absolute_import, division, print_function, unicode_literals
try:
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
print(tf.__version__)
```
Clone the [tensorflow/models](https://github.com/tensorflow/models) git repository so you have some code to test on:
```
!git clone --branch r1.13.0 --depth 1 https://github.com/tensorflow/models
```
### Read the help
The script should be installed with TensorFlow. Here is the builtin help:
```
!tf_upgrade_v2 -h
```
### Example TF1 code
Here is a simple TensorFlow 1.0 script:
```
!head -n 65 models/samples/cookbook/regression/custom_regression.py | tail -n 10
```
With TensorFlow 2.0 installed it does not run:
```
!(cd models/samples/cookbook/regression && python custom_regression.py)
```
### Single file
The upgrade script can be run on a single Python file:
```
!tf_upgrade_v2 \
--infile models/samples/cookbook/regression/custom_regression.py \
--outfile /tmp/custom_regression_v2.py
```
The script will print errors if it can not find a fix for the code.
### Directory tree
Typical projects, including this simple example, will use much more than one file. Typically want to upgrade an entire package, so the script can also be run on a directory tree:
```
# upgrade the .py files and copy all the other files to the outtree
!tf_upgrade_v2 \
--intree models/samples/cookbook/regression/ \
--outtree regression_v2/ \
--reportfile tree_report.txt
```
Note the one warning about the `dataset.make_one_shot_iterator` function.
Now the script works in with TensorFlow 2.0:
Note that because the `tf.compat.v1` module, the converted script will also run in TensorFlow 1.14.
```
!(cd regression_v2 && python custom_regression.py 2>&1) | tail
```
## Detailed report
The script also reports a list of detailed changes. In this example it found one possibly unsafe transformation and included a warning at the top of the file:
```
!head -n 20 tree_report.txt
```
Note again the one warning about the `Dataset.make_one_shot_iterator function`.
In other cases the output will explain the reasoning for non-trivial changes:
```
%%writefile dropout.py
import tensorflow as tf
d = tf.nn.dropout(tf.range(10), 0.2)
z = tf.zeros_like(d, optimize=False)
!tf_upgrade_v2 \
--infile dropout.py \
--outfile dropout_v2.py \
--reportfile dropout_report.txt > /dev/null
!cat dropout_report.txt
```
Here is the modified file contents, note how the script adds argument names to deal with moved and renamed arguments:
```
!cat dropout_v2.py
```
A larger project might contain a few errors. For example convert the deeplab model:
```
!tf_upgrade_v2 \
--intree models/research/deeplab \
--outtree deeplab_v2 \
--reportfile deeplab_report.txt > /dev/null
```
It produced the output files:
```
!ls deeplab_v2
```
But there were errors. The report will help you pin-point what you need to fix before this will run. Here are the first three errors:
```
!cat deeplab_report.txt | grep -i models/research/deeplab | grep -i error | head -n 3
```
## "Safety" mode
The conversion script also has a less invasive `SAFETY` mode that simply changes the imports to use the `tensorflow.compat.v1` module:
```
!cat dropout.py
!tf_upgrade_v2 --mode SAFETY --infile dropout.py --outfile dropout_v2_safe.py > /dev/null
!cat dropout_v2_safe.py
```
As you can see this doesn't upgrade your code, but does allow TensorFlow 1 code to run in TensorFlow 2
## Caveats
- Do not update parts of your code manually before running this script. In particular, functions that have had reordered arguments like `tf.argmax` or `tf.batch_to_space` cause the script to incorrectly add keyword arguments that mismap your existing code.
- The script assumes that `tensorflow` is imported using `import tensorflow as tf`.
- This script does not reorder arguments. Instead, the script adds keyword arguments to functions that have their arguments reordered.
- Check out [tf2up.ml](http://tf2up.ml) for a convenient tool to upgrade Jupyter
notebooks and Python files in a GitHub repository.
To report upgrade script bugs or make feature requests, please file an issue on [GitHub](https://github.com/tensorflow/tensorflow/issues). And if you’re testing TensorFlow 2.0, we want to hear about it! Join the [TF 2.0 Testing community](https://groups.google.com/a/tensorflow.org/forum/#!forum/testing) and send questions and discussion to [testing@tensorflow.org](mailto:testing@tensorflow.org).
| github_jupyter |
- Comparison Sort => bubble, insertion, selection, merge, quick
- Recursive (Divide and Conquer) => MergeSort and QuickSort
- Non-Comparison Sort => radix, bucket
# Bubble Sort
<span style="color:red">
bubbleSort(array)<br>
for i in range(array.length-1)<br>
for j in range(array.length-1-i)<br>
if array[j] > array[j+1]<br>
swap(array, j, j+1)<br>
</span>
- <span style="color:orange">O(N<sup>2</sup>)</span>
```
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
for j in range(n-1-i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
arr = [4,3,2,1]
print(bubbleSort(arr))
```
# Selection Sort
<span style="color:red">
selectionSort(array)<br>
for i in range(array.length-1)<br>
index = i<br>
for j in range(i+1, array.length)<br>
if array[index] > array[j]<br>
index = j<br>
if index not i<br>
swap(array, j, j+1)<br>
</span>
- <span style="color:orange">O(N<sup>2</sup>)</span>
```
def selectionSort(arr, n):
for i in range(n-1):
index = i
for j in range(i+1, n):
if arr[index] > arr[j]:
index = j
if index != i:
arr[i], arr[index] = arr[index], arr[i]
return arr
arr = [4,3,2,1]
print(selectionSort(arr, len(arr)))
```
# Insertion Sort
<span style="color:red">
insertionSort(array)<br>
for i in range(1, array.length)<br>
j = i<br>
while j>0 and array[j-1] > array[j]<br>
swap(array, j, j+1)<br>
j = j-1
</span>
- <span style="color:orange">O(N<sup>2</sup>)</span>
```
def insertionSort(arr, n):
for i in range(1, n):
j = i
while j>0 and arr[j-1] > arr[j]:
arr[j-1], arr[j] = arr[j], arr[j-1]
j = j-1
return arr
arr = [5, 2, 10, -2, 6, 4, 1]
print(insertionSort(arr, len(arr)))
```
# Quick Sort
- <span style="color:red">
quickSort(array, low, high)<br>
if low >= high return<br>
pivot = partition(array, low, high)<br>
quickSort(array, low, pivot-1)<br>
quickSort(array, pivot+1, high) <br>
</span>
- <span style="color:yellow">
partition(array, low, high)<br>
pi = low + ((high - low) / 2) <br>
swap(pi, high)<br>
i = low<br>
for j = low to high<br>
if array[high] >= array[j]<br>
swap(i, j)<br>
i += 1<br>
swap(i, high)<br>
return i<br>
</span>
- <span style="color:orange">O(N logN)</span>
```
def quickSort(arr, low, high):
if low >= high:
return
pivot = partition(arr, low, high)
quickSort(arr, low, pivot-1)
quickSort(arr, pivot+1, high)
def partition(arr, low, high):
pivotIndex = (low+high) // 2
arr[pivotIndex], arr[high] = arr[high], arr[pivotIndex]
i = low
for j in range(low, high, 1):
if arr[j] <= arr[high]:
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[high] = arr[high], arr[i]
return i
arr = [-2, -1, 0, 1, 0, -1, -2]
n = len(arr)
quickSort(arr, 0, n-1)
print(arr)
```
# Merge Sort
- <span style="color:orange">O(N logN)</span>
```
def mergeSort(arr):
if len(arr) == 1:
return
middle = len(arr)//2
left = arr[:middle]
right = arr[middle:]
mergeSort(left)
mergeSort(right)
i,j,k = 0,0,0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
arr = [3, 5, 6, 10, 1, 4,8]
mergeSort(arr)
print(arr)
```
| github_jupyter |
```
%reload_ext autoreload
%autoreload 2
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn as sk
import sklearn.model_selection
import albumentations as A
import cv2
import itertools
import os
import time
from pathlib import Path
from tqdm.notebook import tqdm
import math
import pickle
from scipy import ndimage
# pytorch stuff
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.models as models
from torch.utils.data import Dataset, DataLoader
# need for AMP
from torch.cuda.amp import autocast
from torch.cuda.amp import GradScaler
torch.manual_seed(3)
from tqdm.notebook import tqdm
#https://github.com/mcordts/cityscapesScripts
```
## Data
1. To get the data go to https://www.cityscapes-dataset.com/ and register. Then download these files:
`gtFine_trainvaltest.zip` and `leftImg8bit_trainvaltest.zip`. Put the data in your gpu and unzip.
2. Go to directory `utils` open the file `preprocess_data.py` and replace the following paths
`cityscapes_data_path` and `cityscapes_meta_path`.
3. Run `python preprocess_data.py`
```
PATH = Path('/data2/yinterian/cityscapes/')
def read_image(path):
im = cv2.imread(str(path))
return cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
list((PATH/"leftImg8bit/train/zurich").iterdir())[:10]
path = PATH/"leftImg8bit/train/zurich/zurich_000051_000019_leftImg8bit.png"
im1 = read_image(path)
plt.imshow(im1), im1.shape
list((PATH/"meta").iterdir())[:10]
list((PATH/"meta/label_imgs").iterdir())[:10]
path = PATH/"meta/label_imgs/zurich_000051_000019.png"
label_img = read_image(path)
plt.imshow(label_img[:,:,0]), label_img.shape
(label_img[:,:,0] == label_img[:,:,2]).sum(), 1024*2048
# 20 classes
label_img.reshape(-1).min(), label_img.reshape(-1).max()
```
## Resizing images
Note that this should be done before training and not `during` training.
```
def resize_image(img, img_h=532, img_w=1064):
img = cv2.resize(img, (img_w, img_h), interpolation=cv2.INTER_NEAREST) # (shape: (512, 1024, 3))
return img
x = resize_image(im1, img_h=266, img_w=532)
y = resize_image(label_img[:,:,0], img_h=266, img_w=532)
x.shape, y.shape
def plot_two_imgs(im1, im2):
f = plt.figure(figsize=(12,8))
f.add_subplot(1,2, 1)
plt.imshow(im1)
f.add_subplot(1,2, 2)
plt.imshow(im2)
plot_two_imgs(x, y)
def resize_all_imgs(old_folder, new_folder, img_h=266, img_w=532):
files = [f for f in old_folder.rglob("*.png")]
for path in files:
im = read_image(path)
im2 = resize_image(im, img_h=img_h, img_w=img_w)
new_path = new_folder/path.name
cv2.imwrite(str(new_path), im2)
def create_img_dirs(img_h=266, img_w=532):
imgs_dir = PATH/"imgs_{1}_{2}".format(PATH,img_h, img_w)
for folder in ["train", "val", "test"]:
(imgs_dir/folder).mkdir(parents=True, exist_ok=True)
print(imgs_dir/folder)
resize_all_imgs(PATH/"leftImg8bit"/folder, imgs_dir/folder, img_h=266, img_w=532)
(imgs_dir/"labels").mkdir(parents=True, exist_ok=True)
resize_all_imgs(PATH/"meta", imgs_dir/"labels")
#create_img_dirs()
```
## albumentations for data augmentation
See other tranformations here: <br>
`https://albumentations.ai/docs/api_reference/augmentations/transforms/` <br>
`https://github.com/albumentations-team/albumentations`
```
crop = (512, 256)
transformImg = A.Compose([A.RandomCrop(width=crop[0],height=crop[1]),
A.HorizontalFlip(p=.5),
A.VerticalFlip(p=.5),
A.Rotate(limit = 10, border_mode = cv2.BORDER_REFLECT, value = 0.0, p = .75),
A.GridDistortion(border_mode=cv2.BORDER_REFLECT, value=0.0, p=0.75)])
centercrop = A.CenterCrop(width=crop[0],height=crop[1])
path = PATH/"imgs_266_532/train/zurich_000051_000019_leftImg8bit.png"
x = read_image(path)
path = PATH/"imgs_266_532/labels/zurich_000051_000019.png"
y = read_image(path)
transformed = transformImg(image=x, mask=y[:,:,0])
img = transformed['image']
mask = transformed['mask']
plot_two_imgs(img, mask)
transformed = centercrop(image=x, mask=y)
img = transformed['image']
mask = transformed['mask']
plt.imshow(img), img.shape
```
## Dataset
```
class CityScapesDataset(Dataset):
def __init__(self, data_path, folder, transform=True, crop = (512, 256)):
"""data_path = PATH/"imgs_266_532"
folder is in [val, train, test]
trasform should be True for train
"""
self.transform = transform
self.imgs_files = [f for f in (data_path/folder).glob('*.png')]
self.label_names = [(f.name).split("_leftImg8bit.png")[0] + ".png" for f in self.imgs_files]
self.labels_files = [data_path/"labels"/f for f in self.label_names]
self.train_transforms = A.Compose([
A.HorizontalFlip(p=.5),
A.VerticalFlip(p=.5),
A.Rotate(limit = 10, border_mode = cv2.BORDER_REFLECT, value = 0.0, p = .75),
A.GridDistortion(border_mode=cv2.BORDER_REFLECT, value=0.0, p=0.75),
A.RandomCrop(width=crop[0],height=crop[1])])
self.val_transforms = A.CenterCrop(width=crop[0],height=crop[1])
def __getitem__(self, index):
im_path = self.imgs_files[index]
label_path = self.labels_files[index]
im = read_image(im_path)
label = read_image(label_path)
if self.transform:
transformed = self.train_transforms(image=im, mask=label[:,:,0])
else:
transformed = self.val_transforms(image=im, mask=label[:,:,0])
x = transformed['image']/255.
y = transformed['mask']
return np.rollaxis(x, 2), y
def __len__(self):
return len(self.imgs_files)
ds_train = CityScapesDataset(PATH/"imgs_266_532/", "train")
ds_val = CityScapesDataset(PATH/"imgs_266_532/", "val", transform=False)
x, y = ds_train[0]
x.shape, y.shape
x, y = ds_val[0]
x.shape, y.shape
len(ds_train), len(ds_val)
dl_train = DataLoader(ds_train, batch_size=3, shuffle=True, num_workers=1)
dl_val = DataLoader(ds_val, batch_size=3, shuffle=False, num_workers=1)
```
## Basic UNet model
```
# basic unet with batch normalization
f_size = 7
padding = (int((f_size-1)/2),int((f_size-1)/2))
chs = [32, 64, 128, 256, 512] #, 1024]
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.relu = nn.ReLU()
self.conv1 = nn.Conv2d(in_channels, out_channels, f_size, padding=padding)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, f_size, padding=padding)
self.bn2 = nn.BatchNorm2d(out_channels)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
return x
class unet(nn.Module):
def __init__(self):
super().__init__()
# pooling
self.pool = nn.MaxPool2d(2,2)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
# ENCODER
self.conv00 = ConvBlock(3, 32)
self.conv10 = ConvBlock(32, 64)
self.conv20 = ConvBlock(64, 128)
self.conv30 = ConvBlock(128, 256)
self.conv40 = ConvBlock(256, 512)
# DECODER
self.upconv31 = nn.ConvTranspose2d(512, 256, 2, stride=2)
self.conv31 = ConvBlock(2*256, 256)
self.upconv22 = nn.ConvTranspose2d(256, 128, 2, stride=2)
self.conv22 = ConvBlock(2*128, 128)
self.upconv13 = nn.ConvTranspose2d(128, 64, 2, stride=2)
self.conv13 = ConvBlock(2*64, 64)
self.upconv04 = nn.ConvTranspose2d(64, 32, 2, stride=2)
self.conv04 = ConvBlock(2*32, 32)
# final layers
self.final04 = nn.Conv2d(32, 20, 1)
def forward(self, x):
# Encoder Path
x00 = self.conv00(x)
x10 = self.conv10(self.pool(x00))
x20 = self.conv20(self.pool(x10))
x30 = self.conv30(self.pool(x20))
x40 = self.conv40(self.pool(x30))
# Up-sampling
x31 = self.upconv31(x40)
x31 = self.conv31(torch.cat((x30,x31), dim=1))
x22 = self.upconv22(x31)
x22 = self.conv22(torch.cat((x20,x22),dim=1))
x13 = self.upconv13(x22)
x13 = self.conv13(torch.cat((x10,x13),dim=1))
x04 = self.upconv04(x13)
x04 = self.conv04(torch.cat((x00,x04),dim=1))
# Outputs
x04 = self.final04(x04)
return x04
model = unet().cuda()
x, y = next(iter(dl_train))
y_hat = model(x.float().cuda())
y_hat.shape
with open(PATH/"meta/class_weights.pkl", "rb") as file: # (needed for python3)
class_weights = np.array(pickle.load(file))
class_weights = torch.from_numpy(class_weights)
class_weights = class_weights.type(torch.FloatTensor).cuda()
class_weights, class_weights.sum()
F.cross_entropy(y_hat, y.long().cuda(), weight=class_weights)
x.shape, y.shape, y_hat.shape
```
## computing accuracy
```
y_hat.shape
y = y.float().cuda()
y.shape
pred = torch.max(y_hat, 1)[1]
pred.shape
pred[0]
correct = (pred == y).sum()
correct.shape
# why this formula?
accuracy = correct/(256*512*3)
accuracy
```
## training
```
def valid_metrics(model, dl_valid, pretrained=False):
model.eval()
batch_losses = []
total = 0
correct = 0
for x, y in dl_valid:
with torch.no_grad(): # reduces memory comsumption
total += y.size(0)
x = x.float().cuda()
y = y.long().cuda()
y_hat = model(x)
if pretrained:
y_hat = y_hat["out"]
loss = F.cross_entropy(y_hat, y, weight=class_weights)
batch_losses.append(loss.item())
pred = torch.max(y_hat, 1)[1]
correct += (pred == y).float().sum().item()
total *= y.size(1)*y.size(2)
return np.mean(batch_losses), correct/total
def train_epochs(model, optimizer, dl_train, dl_valid, epochs, pretrained=False):
batch_losses = []
pbar = tqdm(total=epochs*len(dl_train))
for epoch in range(epochs):
best_val_loss, _ = valid_metrics(model, dl_valid, pretrained)
model.train()
for x, y in dl_train:
x = x.float().cuda()
y = y.long().cuda()
y_hat = model(x)
if pretrained:
y_hat = y_hat["out"]
loss = F.cross_entropy(y_hat, y, weight=class_weights)
batch_losses.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
pbar.update()
train_loss = np.mean(batch_losses)
val_loss, val_acc = valid_metrics(model, dl_valid, pretrained)
print ("train loss: %.3f val loss: %.3f val acc: %.3f" % (train_loss, val_loss, val_acc))
# save the model weights to disk:
if val_loss < best_val_loss:
path = "{0}/models/model_{1:.0f}.pth".format(PATH, 100*val_acc)
print(path)
torch.save(model.state_dict(), path)
best_val_loss = val_loss
dl_train = DataLoader(ds_train, batch_size=16, shuffle=True, num_workers=1)
dl_val = DataLoader(ds_val, batch_size=16, shuffle=False, num_workers=1)
model = unet().cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=0.0001, weight_decay=0.0001)
train_epochs(model, optimizer, dl_train, dl_val, epochs=10)
```
## Making predictions
```
def load_model(m, p): m.load_state_dict(torch.load(p))
model = unet().cuda()
path = "/data2/yinterian/cityscapes/models/model_78.pth"
load_model(model, path)
ds_val.imgs_files[10], ds_val.labels_files[10]
img = read_image(ds_val.imgs_files[10])
mask = read_image(ds_val.labels_files[10])
plot_two_imgs(img, mask[:,:,0])
x, y = ds_val[10]
x.shape
x1 = x[None,]
x1.shape
y_hat = model(torch.FloatTensor(x1).cuda())
y_hat.shape
pred = torch.max(y_hat, 1)[1]
pred.shape
plot_two_imgs(mask[:,:,0], pred[0].cpu().numpy())
```
## Training with half precision
Here is the a tick to increase batch size and train faster.
```
from apex import amp
def valid_metrics_half(model, dl_valid):
model.eval()
batch_losses = []
total = 0
correct = 0
for x, y in dl_valid:
with torch.no_grad(): # reduces memory comsumption
total += y.size(0)
x = x.half().cuda()
y = y.long().cuda()
y_hat = model(x)
loss = F.cross_entropy(y_hat, y, weight=class_weights)
batch_losses.append(loss.item())
pred = torch.max(y_hat, 1)[1]
correct += (pred == y).float().sum().item()
total *= y.size(1)*y.size(2)
return np.mean(batch_losses), correct/total
def train_epochs_half(model, optimizer, dl_train, dl_valid, epochs):
batch_losses = []
pbar = tqdm(total=epochs*len(dl_train))
for epoch in range(epochs):
best_val_loss, _ = valid_metrics_half(model, dl_valid)
model.train()
for x, y in dl_train:
x = x.half().cuda()
y = y.long().cuda()
y_hat = model(x)
loss = F.cross_entropy(y_hat, y, weight=class_weights)
batch_losses.append(loss.item())
optimizer.zero_grad()
#loss.backward()
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
optimizer.step()
pbar.update()
train_loss = np.mean(batch_losses)
val_loss, val_acc = valid_metrics_half(model, dl_valid)
print ("train loss: %.3f val loss: %.3f val acc: %.3f" % (train_loss, val_loss, val_acc))
# save the model weights to disk:
if val_loss < best_val_loss:
path = "{0}/models/model_half_{1:.0f}.pth".format(PATH, 100*val_acc)
print(path)
torch.save(model.state_dict(), path)
best_val_loss = val_loss
dl_train = DataLoader(ds_train, batch_size=32, shuffle=True, num_workers=1)
dl_val = DataLoader(ds_val, batch_size=32, shuffle=False, num_workers=1)
model = unet().cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=0.0001, weight_decay=0.0001)
model, optimizer = amp.initialize(model, optimizer, opt_level="O2",
keep_batchnorm_fp32=True, loss_scale="dynamic")
train_epochs_half(model, optimizer, dl_train, dl_val, epochs=10)
train_epochs_half(model, optimizer, dl_train, dl_val, epochs=10)
```
## Segmentation from pretrained models
```
from torchvision.models.segmentation.deeplabv3 import DeepLabHead
from torchvision import models
def createDeepLabv3(outputchannels=1):
"""DeepLabv3 class with custom head
Args:
outputchannels (int, optional): The number of output channels
in your dataset masks. Defaults to 1.
Returns:
model: Returns the DeepLabv3 model with the ResNet101 backbone.
"""
model = models.segmentation.deeplabv3_resnet101(pretrained=True,
progress=True)
model.classifier = DeepLabHead(2048, outputchannels)
# Set the model in training mode
model.train()
return model
model = createDeepLabv3(outputchannels=20)
model = model.cuda()
dl_train = DataLoader(ds_train, batch_size=10, shuffle=True, num_workers=1)
dl_val = DataLoader(ds_val, batch_size=10, shuffle=False, num_workers=1)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
x, y = next(iter(dl_train))
x = x.float().cuda()
y_hat = model(x)
y_hat.keys()
y_hat['out'].shape
train_epochs(model, optimizer, dl_train, dl_val, epochs=10, pretrained=True)
```
| github_jupyter |
# Principle Component Explained Variance
### Matt Harrington
```
# Standard imports
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from subsets import *
from coin_helpers import load_coins, simplify
coins, returns = load_coins('pairs/', top_50)
hour_ret = simplify(returns, '1h')
day_ret = simplify(returns, '1D')
n = 365
twoyr, oneyr = [], []
for c in day_ret.columns:
nulls = day_ret[c].isnull().sum()
lengs = day_ret[c].shape[0]
if lengs - nulls > n:
oneyr.append(c)
if lengs - nulls > 2*n:
twoyr.append(c)
nyr = len(oneyr)
nall = len(returns.columns)
p = round(100 * nyr / nall, 2)
print("{0} of {1} ({2}%) have more than {3} days of data".format(nyr, nall, p, n))
print("{0} of {1} ({2}%) have more than {3} days of data".format(len(twoyr), nall, p, 2 * n))
# Grab historical subset and drop bad days
twoall = returns[twoyr].count(axis=1)
tpca = returns[twoyr].dropna(how='any').count(axis=1)
oneall = returns[oneyr].count(axis=1)
opca = returns[oneyr].dropna(how='any').count(axis=1)
# Illustrate relationship
fig = plt.figure(figsize=(10,6))
plt.plot(oneall, label='Raw One Year', lw=2.5)
plt.plot(opca, label='Filtered One Year', lw='3')
plt.plot(twoall, label='Raw Two Year', ls='--')
plt.plot(tpca, label='Filtered Two Year', ls='--', lw='3')
plt.title("Num Coins vs Time")
plt.legend()
plt.show()
from sklearn.decomposition import PCA
# the Oxford paper suggests setting T s.t. T / N >= 1
def numpy_ma(x, w):
return np.convolve(x, np.ones(w), 'valid') / w
def linear_pca_explained_var(ts, samps, T = 14, ma_window = 10):
N = max(ts.dropna(how='any').count(axis=1))
print(N)
for samp in samps:
forpca = simplify(ts, samp).dropna(how='any')
n_windows = forpca.shape[0] - T + 1
ma_window = int(n_windows / 30)
# print(n_windows, ma_window)
pca = PCA(n_components=N)
expl_vars = np.zeros(n_windows)
windows = forpca.rolling(window=T)
for i, window in enumerate(windows):
if window.shape[0] < T: continue
expl_vars[i - T] = pca.fit(window).explained_variance_ratio_[0]
ma = numpy_ma(expl_vars, ma_window)
fig = plt.figure(figsize=(12,8))
plt.plot(forpca.index[-n_windows:], expl_vars,
label='Explained {}-Period Variance'.format(T))
plt.plot(forpca.index[-ma.shape[0]:], ma,
color='black', lw=2.5, label="{}-Period MA".format(ma_window))
plt.title("{}-Interval LPCA Explained Variance for Oldest {} Coins".format(samp, len(forpca.columns)))
plt.legend()
plt.ylim([0, 1])
plt.show()
linear_pca_explained_var(returns[twoyr], ['10min', '1h', '12h', '1D'], 14)
def sample_aggregated_linear_pca_explained_var(ts, samps, T = 14, ma_window = 10):
N = max(ts.dropna(how='any').count(axis=1))
print(N)
fig = plt.figure(figsize=(12,8))
for samp in samps:
forpca = simplify(ts, samp).dropna(how='any')
n_windows = forpca.shape[0] - T + 1
ma_window = int(n_windows / 30)
# print(n_windows, ma_window)
pca = PCA(n_components=N)
expl_vars = np.zeros(n_windows)
windows = forpca.rolling(window=T)
for i, window in enumerate(windows):
if window.shape[0] < T: continue
expl_vars[i - T] = pca.fit(window).explained_variance_ratio_[0]
ma = numpy_ma(expl_vars, ma_window)
plt.plot(forpca.index[-ma.shape[0]:], ma, label="{}|{}-Period MA".format(samp, ma_window))
plt.title("LPCA Explained Variance for Oldest {} Coins".format(len(forpca.columns)))
plt.legend()
plt.ylim([0, 1])
plt.show()
sample_aggregated_linear_pca_explained_var(returns[twoyr], ['15min', '1h', '3h', '6h', '12h', '1D'], 14)
```
| github_jupyter |
# Import Libraries
```
import sys
import glob, os
import pandas as pd
import plotly.plotly as py
from scipy import linalg
from scipy import signal
import matplotlib.pyplot as plt
import numpy as np
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
```
# Prepare data
```
path = '../../machine_learning/cloud_functions/data-large.csv'
features = ['temporal_canny-euclidean', 'temporal_cross_correlation-euclidean',
'temporal_difference-euclidean', 'temporal_histogram_distance-euclidean',
'temporal_dct-euclidean', 'size', 'dimension', 'temporal_gaussian_mse-mean',
'temporal_dct-std', 'temporal_dct-manhattan', 'temporal_dct-mean', 'temporal_histogram_distance-mean',
'temporal_cross_correlation-mean', 'temporal_canny-mean', 'temporal_gaussian_mse-euclidean']
metric_processor = MetricProcessor(features,'UL', path)
df = metric_processor.read_and_process_data()
df.shape
_, (df_train, df_test, df_attacks) = metric_processor.split_test_and_train(df)
print('Shape of train: {}'.format(df_train.shape))
print('Shape of test: {}'.format(df_test.shape))
print('Shape of attacks: {}'.format(df_attacks.shape))
```
# Model
The idea behind this model is to reduce the number of features used in the inference and use a simple model. The key part is that, as shown in the curves below, the relation between the mean value of some of the metrics and the resolutions is logarithmic.
The inference is then very simple. We first get the resolution of the asset and compute the treshold that fixes a TPR of 99%. If the mean value of the series is above this threshold, the asset is marked as an attack.
```
metrics = ['temporal_dct-mean', 'temporal_histogram_distance-mean', 'temporal_gaussian_mse-mean']
resolutions = [144, 240, 360, 480, 720]
# We compute the quantile of 99%, fixing the TPR to this value.
params = {}
quantile = 0.99
for metric in metrics:
params[metric] = {}
for res in resolutions:
th = np.quantile(df_train[df_train['attack'] == str(res) + 'p'][metric].to_numpy(), quantile)
params[metric][res] = th
# We need to extrapolate the thresholds for 1080p
ticks = ['144p', '240p', '360p', '480p', '720p', '1080p']
fig, ax = plt.subplots(len(metrics),1, figsize=(10, 15))
resolutions_ = resolutions.copy()
resolutions_.extend([1080])
# Note that the axis of the plots are y-logarithmic
for i, metric in enumerate(metrics):
ths = []
for res in resolutions:
ths.append(params[metric][res])
fit = np.polyfit(resolutions, np.log10(ths),1)
fit_means = np.poly1d(fit)
y_pred = fit_means(resolutions_)
ax[i].semilogy(resolutions, ths, '--*', resolutions_, 10 ** y_pred, '--k')
ax[i].set_xticks(resolutions_)
_ = ax[i].set_xticklabels(ticks, rotation='horizontal', fontsize=18)
params[metric][1080] = 10 ** y_pred[-1]
print('The parameters of the curve are: y = {}*x + ({}) ## (Logarithmic)'.format(fit_means[1], fit_means[0]))
results_train = {}
for metric in metrics:
results_train[metric] = {}
for res in resolutions_:
results_train[metric][res] = df_train[df_train['attack'] == str(res) + 'p'][metric].to_numpy() > params[metric][res]
results_test = {}
for metric in metrics:
results_test[metric] = {}
for res in resolutions_:
results_test[metric][res] = df_test[df_test['attack'] == str(res) + 'p'][metric].to_numpy() > params[metric][res]
results_attacks = {}
for metric in metrics:
results_attacks[metric] = {}
for res in resolutions_:
results_attacks[metric][res] = df_attacks[df_attacks['attack'].str.contains(str(res) + 'p')][metric].to_numpy() > params[metric][res]
tp_train = 0
tp_test = 0
fn_test = 0
tn_attacks = 0
fp_attacks = 0
metric = 'temporal_gaussian_mse-mean'
for res in resolutions_:
tp_train += sum(results_train[metric][res] < params[metric][res])
tp_test += sum(results_test[metric][res] < params[metric][res])
fn_test += sum(results_test[metric][res] > params[metric][res])
tn_attacks += sum(results_attacks[metric][res] > params[metric][res])
fp_attacks += sum(results_attacks[metric][res] < params[metric][res])
beta = 20
precision = tp_test/(tp_test+fp_attacks)
recall = tp_test/(tp_test+fn_test)
F20 = (1 + (beta ** 2))*precision*recall/((beta ** 2)*precision + recall)
print('With the metric {} we have:'.format(metric))
print('TPR train: {}'.format(tp_train / df_train.shape[0]))
print('TPR test: {}'.format(tp_test / df_test.shape[0]))
print('TNR: {}'.format(tn_attacks / df_attacks.shape[0]))
print('F20: {}'.format(F20))
df_attacks['pred'] = df_attacks.apply(lambda row: row[metric] < params[metric][row['dimension']], axis=1)
df_attacks[df_attacks['pred'] == True].groupby(['dimension', 'attack']).count()
```
| github_jupyter |
TSG001 - Run azdata copy-logs
=============================
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):
"""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 supportabilty, 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])
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:
return output
else:
return
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:
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("tsg001-copy-logs.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.'))
print('Common functions defined successfully.')
# Hints for binary (transient fault) retry, (known) error and install guide
#
retry_hints = {'kubectl': ['A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'], 'azdata': ['Endpoint sql-server-master does not exist', 'Endpoint livy does not exist', 'Failed to get state for cluster', 'Endpoint webhdfs does not exist', 'Adaptive Server is unavailable or does not exist', 'Error: Address already in use']}
error_hints = {'kubectl': [['no such host', 'TSG010 - Get configuration contexts', '../monitor-k8s/tsg010-get-kubernetes-contexts.ipynb'], ['No connection could be made because the target machine actively refused it', 'TSG056 - Kubectl fails with No connection could be made because the target machine actively refused it', '../repair/tsg056-kubectl-no-connection-could-be-made.ipynb']], 'azdata': [['azdata login', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['The token is expired', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['Reason: Unauthorized', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['Max retries exceeded with url: /api/v1/bdc/endpoints', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['Look at the controller logs for more details', 'TSG027 - Observe cluster deployment', '../diagnose/tsg027-observe-bdc-create.ipynb'], ['provided port is already allocated', 'TSG062 - Get tail of all previous container logs for pods in BDC namespace', '../log-files/tsg062-tail-bdc-previous-container-logs.ipynb'], ['Create cluster failed since the existing namespace', 'SOP061 - Delete a big data cluster', '../install/sop061-delete-bdc.ipynb'], ['Failed to complete kube config setup', 'TSG067 - Failed to complete kube config setup', '../repair/tsg067-failed-to-complete-kube-config-setup.ipynb'], ['Error processing command: "ApiError', 'TSG110 - Azdata returns ApiError', '../repair/tsg110-azdata-returns-apierror.ipynb'], ['Error processing command: "ControllerError', 'TSG036 - Controller logs', '../log-analyzers/tsg036-get-controller-logs.ipynb'], ['ERROR: 500', 'TSG046 - Knox gateway logs', '../log-analyzers/tsg046-get-knox-logs.ipynb'], ['Data source name not found and no default driver specified', 'SOP069 - Install ODBC for SQL Server', '../install/sop069-install-odbc-driver-for-sql-server.ipynb'], ["Can't open lib 'ODBC Driver 17 for SQL Server", 'SOP069 - Install ODBC for SQL Server', '../install/sop069-install-odbc-driver-for-sql-server.ipynb'], ['Control plane upgrade failed. Failed to upgrade controller.', 'TSG108 - View the controller upgrade config map', '../diagnose/tsg108-controller-failed-to-upgrade.ipynb']]}
install_hint = {'kubectl': ['SOP036 - Install kubectl command line interface', '../install/sop036-install-kubectl.ipynb'], 'azdata': ['SOP063 - Install azdata CLI (using package manager)', '../install/sop063-packman-install-azdata.ipynb']}
```
### Get the Kubernetes namespace for the big data cluster
Get the namespace of the Big Data Cluster use the kubectl command line
interface .
**NOTE:**
If there is more than one Big Data Cluster in the target Kubernetes
cluster, then either:
- set \[0\] to the correct value for the big data cluster.
- set the environment variable AZDATA\_NAMESPACE, before starting
Azure Data Studio.
```
# Place Kubernetes namespace name for BDC into 'namespace' variable
if "AZDATA_NAMESPACE" in os.environ:
namespace = os.environ["AZDATA_NAMESPACE"]
else:
try:
namespace = run(f'kubectl get namespace --selector=MSSQL_CLUSTER -o jsonpath={{.items[0].metadata.name}}', return_output=True)
except:
from IPython.display import Markdown
print(f"ERROR: Unable to find a Kubernetes namespace with label 'MSSQL_CLUSTER'. SQL Server Big Data Cluster Kubernetes namespaces contain the label 'MSSQL_CLUSTER'.")
display(Markdown(f'HINT: Use [TSG081 - Get namespaces (Kubernetes)](../monitor-k8s/tsg081-get-kubernetes-namespaces.ipynb) to resolve this issue.'))
display(Markdown(f'HINT: Use [TSG010 - Get configuration contexts](../monitor-k8s/tsg010-get-kubernetes-contexts.ipynb) to resolve this issue.'))
display(Markdown(f'HINT: Use [SOP011 - Set kubernetes configuration context](../common/sop011-set-kubernetes-context.ipynb) to resolve this issue.'))
raise
print(f'The SQL Server Big Data Cluster Kubernetes namespace is: {namespace}')
```
### Run copy-logs
```
import os
import tempfile
import shutil
target_folder = os.path.join(tempfile.gettempdir(), "copy-logs", namespace)
if os.path.isdir(target_folder):
shutil.rmtree(target_folder)
```
### View the `--help` options
```
run(f'azdata bdc debug copy-logs --help')
```
### Run the `copy-logs`
NOTES:
1. The –timeout option does not work on Windows
2. Use –skip-compress on Windows if no utility available to uncompress
.tar.gz files.
```
run(f'azdata bdc debug copy-logs --namespace {namespace} --target-folder {target_folder} --exclude-dumps --skip-compress --verbose')
print(f'The logs are available at: {target_folder}')
print('Notebook execution complete.')
```
| github_jupyter |
## Model evaluation
For model performance assessment we want to obtain the distribution of the model accuracy over N independent runs of the training procedure.
* [Research configuration](#Research-configuration)
* [Results](#Results)
```
import os
import sys
import glob
import dill
import numpy as np
import matplotlib.pyplot as plt
sys.path.insert(0, os.path.join("..", ".."))
from batchflow import B, V, C, D, Pipeline
from batchflow.opensets import MNIST
from batchflow.models.tf import TFModel
from batchflow.research import Research, Results
from src import show_histogram
```
## Research configuration
Dataset loading
```
dataset = MNIST(bar=True)
```
Define the model config:
```
model_config = {
'inputs/images/shape': B('image_shape'),
'inputs/labels/classes': D('num_classes'),
'initial_block/inputs': 'images',
'body': dict(layout='cpna cpna cpna', filters=[64, 128, 256],
strides=2, pool_strides=1, kernel_size=3),
'head': dict(layout='Pf', units=D('num_classes')),
'loss': 'crossentropy',
'optimizer': ('Momentum', {'use_nesterov': True, 'learning_rate': 0.01, 'momentum': 0.5}),
'output': ['proba']}
```
Define training and test pipelines:
```
train_template = (Pipeline()
.init_variable('loss_history', init_on_each_run=list)
.init_model('dynamic', TFModel, 'mnist_model', config=model_config)
.to_array()
.train_model('mnist_model', fetches='loss', images=B('images'), labels=B('labels'),
save_to=V('loss_history', mode='a'))
.run_later(64, shuffle=True, n_epochs=1, drop_last=True, bar=False))
test_template = (Pipeline()
.import_model('mnist_model', C('import_from'))
.init_variable('predictions', init_on_each_run=list)
.init_variable('metrics', init_on_each_run=None)
.to_array()
.predict_model('mnist_model', fetches='proba', images=B('images'),
save_to=V('predictions'))
.gather_metrics('class', targets=B('labels'), predictions=V('predictions'),
fmt='proba', axis=-1, save_to=V('metrics', mode='u'))
.run_later(64, shuffle=False, n_epochs=1, drop_last=True, bar=False))
```
Create a research object and run 20 independent training and test procedures:
```
research = (Research()
.add_pipeline(train_template, dataset=dataset.train, name='train', execute='last', run=True)
.add_pipeline(test_template, dataset=dataset.test, name='test', import_from='train', execute='last', run=True)
.get_metrics(pipeline='test', metrics_var='metrics', metrics_name='accuracy',
returns='accuracy', execute='last')
.run(n_reps=20, n_iters=1, name='model_evaluation', bar=True, workers=1, gpu=[4]))
```
## Results
Save accuracy metric to an array
```
values = research.load_results(names='test_metrics')['accuracy'].values
```
Accuracy histogram and the average value
```
show_histogram(values)
print('The average value (median) is %.3f' % np.median(values))
```
| github_jupyter |
```
# http://scikit-learn.org/stable/auto_examples/applications/topics_extraction_with_nmf_lda.html
from __future__ import print_function
from time import time
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decomposition import NMF, LatentDirichletAllocation # v. 0.17.1
from sklearn.datasets import fetch_20newsgroups
n_samples = 2000
n_features = 1000
n_topics = 10
n_top_words = 20
def print_top_words(model, feature_names, n_top_words):
for topic_idx, topic in enumerate(model.components_):
print("Topic #%d:" % topic_idx)
print(" ".join([feature_names[i]
for i in topic.argsort()[:-n_top_words - 1:-1]]))
print()
# Load the 20 newsgroups dataset and vectorize it. We use a few heuristics
# to filter out useless terms early on: the posts are stripped of headers,
# footers and quoted replies, and common English words, words occurring in
# only one document or in at least 95% of the documents are removed.
print("Loading dataset...")
t0 = time()
dataset = fetch_20newsgroups(shuffle=True, random_state=1,
remove=('headers', 'footers', 'quotes'))
data_samples = dataset.data # list of str
print("done in %0.3fs." % (time() - t0))
# Use tf-idf features for NMF.
print("Extracting tf-idf features for NMF...")
tfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2, #max_features=n_features,
stop_words='english')
t0 = time()
tfidf = tfidf_vectorizer.fit_transform(data_samples)
print("done in %0.3fs." % (time() - t0))
dataset.keys()
type(data_samples)
data_samples[:3]
# Use tf (raw term count) features for LDA.
print("Extracting tf features for LDA...")
tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2,
max_features=n_features,
stop_words='english')
t0 = time()
tf = tf_vectorizer.fit_transform(data_samples)
print("done in %0.3fs." % (time() - t0))
# Fit the NMF model
print("Fitting the NMF model with tf-idf features,"
"n_samples=%d and n_features=%d..."
% (n_samples, n_features))
t0 = time()
nmf = NMF(n_components=n_topics,
random_state=1,
alpha=.1,
l1_ratio=.5).fit(tfidf)
exit()
print("done in %0.3fs." % (time() - t0))
print("\nTopics in NMF model:")
tfidf_feature_names = tfidf_vectorizer.get_feature_names()
print_top_words(nmf, tfidf_feature_names, n_top_words)
print("Fitting LDA models with tf features, n_samples=%d and n_features=%d..."
% (n_samples, n_features))
lda = LatentDirichletAllocation(n_topics=n_topics, max_iter=5,
learning_method='online', learning_offset=50.,
random_state=0)
t0 = time()
lda.fit(tf)
print("done in %0.3fs." % (time() - t0))
print("\nTopics in LDA model:")
tf_feature_names = tf_vectorizer.get_feature_names()
print_top_words(lda, tf_feature_names, n_top_words)
```
| github_jupyter |
# Python ile Programlama
Lambda Fonksiyonları
Dr. Murat Gezer https://github.com/mgezer/PythonDers
Soru Aşağıdaki programın hata durumunda çalışmasını sağlayacak Hata istisnasını yazınız
```
def toplama(sayi1,sayi2):
return sayi1 + sayi2
x = int(input("Sayı Giriniz:"))
y = int(input("Sayı Giriniz:"))
print(toplama(x,y))
def toplama(sayi1,sayi2):
return sayi1 + sayi2
try:
x = int(input("Sayı Giriniz:"))
y = int(input("Sayı Giriniz:"))
print(toplama(x,y))
except:
print("Hatalı Değer girdiniz!!! Lütfen Sayı Giriniz")
def toplama(sayi1,sayi2):
return sayi1 + sayi2
while True:
try:
x = int(input("1. Sayı Giriniz:"))
y = int(input("2. Sayı Giriniz:"))
except:
print("Hatalı Değer girdiniz!!! Lütfen Sayı Giriniz")
continue
else:
print(toplama(x,y))
finally:
print("Her durumda çalışırım ben")
```
## Lambda Fonksiyonu
Lambda ifadeleri fonksiyonlarımızı oluşturmak için Pythonda bulunan pratik bir yöntemdir. Genelde tek satıra inirgenmiş fonksiyonlardır. Örneğin x ve y değişkenlerini toplayan bir fonsiyon tanımlamak istersek
```
fonksiyon ismi = lambda argümanları: fonksiyon ifadesi
lambda x : x + 2
```
```
ikikat = lambda x: x * 2
print(ikikat(5))
topla = lambda x, y: x + y
print (topla (1, 2))
usalma = lambda x, y: x ** y
print(usalma(2,3))
celcius2fahrenheit = lambda C: 1.8 * C + 32
celcius2fahrenheit(100)
```
# Sayısal analizde Integral çözümlerinde bilgisayarın kullanımı
## Simpson Yöntemi
$S_N(f) = \frac{\Delta x}{3} \sum_{i=1}^{N/2} \left( f(x_{2i-2}) + 4 f(x_{2i-1}) + f(x_{2i}) \right)$
burada adım sayısı N çift sayı $[a,b] aralığımız , \Delta x = (b - a)/N$ ve $x_i = a + i \Delta x$.
https://web.itu.edu.tr/kalenderli/sayisalintegrasyon-OK2016.pdf
$\int_0^{\pi/2} \sin(x) dx = 1$ için grafiğini ve Simpson kuralına göre çözümünü bulun ve grafiğini çizdirin
$\int_{\pi/2}^{3\pi/2} \left( \sin(0.2 x) + \sin(2x) + 1 \right) dx$ integralinin $[{\pi/2} -{3\pi/2}]$ aralığında grafiğini ve integralin sayısal çözümünü bulunuz
**Soru 1:**
1’den 10’a kadar bütün sayılara kalansız bölünen en küçük sayı 2520’dir. 1’den 20’ye kadar bütün sayılara kalansız bölünen en küçük pozitif sayı kaçtır?
Python dili ile çözen program yazınız
Yol Gösterme: Sonsuz döngü içersinde her birimi sağlayan şartı kontrol ediniz. **(10 Puan)**
```
x=1
while True:
if x % 1 == 0 and x % 2 == 0 and x % 3 == 0 and x % 4 == 0 and x % 5 == 0 \
and x % 6 == 0 and x % 7 == 0 and x % 8 == 0 and x % 9 == 0 and x % 10 ==0\
and x % 11 == 0 and x % 12 == 0 and x % 13 == 0 and x % 14 == 0 and x % 15 == 0\
and x % 16 == 0 and x % 17 == 0 and x % 18 == 0 and x % 19==0 and x % 20==0:
print(x)
break
x=x+1
```
**Soru 2:**
İlk 20 Fibonacci sayısını bir liste halinde veren bir fonksiyon yazın.
Yol Gösterme:
Çıktımız şeklinde olsun
```
fib(0)
[ ]
fib(1)
[1]
fib(2)
[1, 1]
…
fib(10)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
```
**(10 puan)**
```
def fib(x):
if x == 0:
dizi = []
return dizi
elif x==1:
dizi = [1]
return dizi
else:
dizi = [1]
sayi1 = 0
sayi2 = 1
toplam = 0
for i in range (x):
toplam=sayi1+sayi2
sayi1=sayi2
sayi2=toplam
dizi.append(toplam)
return dizi
for i in range(20):
print("fib(",i,")",fib(i))
```
**Soru 3:**
Kullanıcıdan 3 basamaklı bir sayı alın ve bu sayının okunuşunu bulan bir fonksiyon yazın.
Örnek:
197 --------->Yüz Doksan Yedi
678 ---------> Alt Yüz Yetmiş Sekiz
**(10 Puan)**
**Soru 4:**
Kullanıcı tarafından girilen bir yazının içindeki sözcükleri sayan program yazınız.
Örnek:
bir yazi girin :Iyi bir Python Programcisi olmak icin cok calismak gerekir
(Iyi bir Python Programcisi olmak icin cok calismak gerekir) yazisinda (9) sozcuk var!
**(5 Puan)**
```
yazi=input("Bir yazı girin:")
print("(",yazi,") yazısında (",len(yazi.split(" ")),") söcük var")
```
**Soru 5**
Bir sayı bütün çarpanlarının (1 dahil, kendisi hariç) toplamına eşitse, o sayıya mükemmel sayı denir.
Sözgelişi, 1*2*3=1+2+3=6 olduğundan, 6 bir mükemmel sayıdır.
Verilen bir sayı “mükemmel"s ise True, değilse False veren bir fonksiyon yazın.
Bu fonksiyonu kullanarak, 10 000'den küçük bütün "mükemmel" sayıları ekrana bastıran program yazınız.
Örnek:
```
mukemmel(6)
True
mukemmel(10)
False
```
**(10 Puan)**
```
def mukemmel(x):
toplam=0
for i in range(1,x):
if(x%i == 0):
toplam =toplam + i
if(x == toplam):
return True
else:
return False
for i in range(9999):
if mukemmel(i+1):
print(i+1)
```
**Soru 6**
Kullanıcı tarafından klavyeden girilen 5 karakterlik bir ismin içerisindeki küçük harfleri büyük harfe, büyük harfleri küçük harfe çeviren bir fonksiyon tasarlayınız. Eğer isim 5 karakterden az yada çok ise uyarı yapıp tekrar kullanıcıdan istesin.
**(5 Puan)**
```
def cevir(isim):
return isim.swapcase()
ad=""
while len(ad)!=5:
ad = input("Lütfen 5 haneli ad giriniz:")
print(cevir(ad))
```
**Soru 7**
Bir n sayısı için 2n ‘i hesaplayan ve çıkan sonucu ve çıkan sonucun basamaklarını toplayan ve geri döndüren bir fonksiyon yazınız. Bu fonksiyon ile 1’den başlayarak 50’e kadar giden tüm sayıları bu fonksiyon sonuclarını ve basamak toplamlarını formatlı şekilde ekrana bastıran program yazınız.
Yol Gösterme:
Çıktınız aşağıdaki şekilde olmalı
```
2**15 = 32768 ve basamaklarının toplamı 3 + 2 + 7 + 6 + 8 = 26
```
**(5 Puan)**
```
def hesapla(n):
toplam=0
us=2**n
for i in range(len(str(us))):
toplam=int(str(us)[i])+toplam
print("2**{}={} ve basamakların toplamı ".format(n,us),end="")
print(*str(us),sep=" + ",end="")
print(" = {}".format(toplam))
for i in range(10):
hesapla(i+1)
```
**Soru 8**
Bir otoparkın ücret tarifesi aşağıdaki gibidir:
1 saate kadar: 10 TL
2-5 saat arası: her saat için ek 3 TL
6-fazlası saatten fazla:her saat için ek 4 TL
Buna göre kullanıcının girdiği otoparkta kalınan saat süresine göre ödenecek miktarı bularak ekrana yazdırınız.
**(10 Puan)**
```
saat=int(input("Otoparkta kaç saat kaldınız:"))
ucret=10
if saat>0 and saat<=1:
ucret=10
print("Ödeyeceğiniz ücret {} TL".format(ucret))
elif saat>1 and saat <=5:
saat=saat-1
ucret=ucret+(saat*3)
print("Ödeyeceğiniz ücret {} TL".format(ucret))
elif saat>5:
saat=saat-1
ucret=ucret+(saat*4)
print("Ödeyeceğiniz ücret {} TL".format(ucret))
else:
print("Otoparkta 1 saatin altında kalmışsınız")
```
**Soru 9**
Virgülle ayrılmış bir ad dizisini girdi olarak kabul eden ve kelimeleri alfabetik olarak sıraladıktan sonra virgülle ayrılmış bir dizide basan bir program yazın. Not: Sıralamada Türkçe karakterleri göz ardı ediniz
Programa aşağıdaki girişin sağlandığını varsayalım:
Virgülle ayrılmış şekilde ad girin: Ahmet , Ali , Berrin, Ayşe, Zehra
Ahmet, Ali, Ayşe, Berrin, Zehra
**10puan**
```
ad=input("Virgülle ayrılmış şekilde ad girin:")
dizi=ad.split(",")
dizi.sort()
print(dizi)
```
Soru 10:
Kullanıcının girdiği üç kenar bilgisine göre üçgenin tipini belirleyen eğer girilen kenarları uzunlukları bir üçgen oluşturmuyorsa bunu bildiren kodu yazınız. ( mutlak değer içinde iki kenarın farkı alınır eğer fark diğer kenardan büyükse girilen değerler üçgen oluşturmaz. Bu işlem tüm kenarlar için yapılır
**(10 Puan)**
```
a=int(input("1. kenar:"))
b=int(input("2. kenar:"))
c=int(input("3. kenar:"))
if(abs(b-c)<a and a<b+c and abs(c-a)<b and b<a+c and abs(a-b)<c and c<a+b):
if((a==b and a!=c) or (a==c and a!=b) or (b==c and b!=a)):
print("İkizkenar Üçgen!")
elif(a==b==c):
print("Eşkenar Üçgen!")
else:
print("Normal Üçgen")
else:
print("Üçgen Oluşturmuyor")
```
**Soru 11**
Sezar şifrelemesi, ilk kez Romalı lider Jül Sezar tarafından kullanılmış olan şifreleme tekniğidir. Ana mesajın her bir harfini belirtilen anahtar sayı kadar ileri kaydırarak şifreli mesajı oluşturmak üzeredir. Şifreyi çözmek için ise anahtar sayısı ile şifreli mesajdaki her karakterin anahtar sayısı kadar geriye giderek ana mesajı dönüştürmesi üzerinedir.
Günümüzde şifreleme için pek güvenli sayılmamaktadır. Bir filolog, bir dilde en çok geçen harfleri bulabilir. O harfler ile mesajda en sık geçen harfleri karşılaştırarak hangi harfin hangi harf ile değiştirildiğini de çözmüş olur.
yukarıdaki tabloda anahtar sayı 3 belirlenmiş ve bazı harflerin 3 adım sonraki karşılığı gösterilmiştir.
Sizin göreviniz Türkçe harflerinde (ABCÇDEFGĞHIIJKLMNOÖPRSŞTUÜVYZ) çalışacağı bir Sezar şifreleyici ve açıcı fonksiyonlar yazmanız.
**(15 Puan)**
```
def sifrele(metin,anahtar=3):
alfabe=[*"ABCÇDEFGĞHIIJKLMNOÖPRSŞTUÜVYZ"]
metin=metin.upper()
sifre=""
for harf in [*metin]:
sifre+=(alfabe[(alfabe.index(harf)+anahtar)%29])
return sifre
def sifreac(metin,anahtar=3):
alfabe=[*"ABCÇDEFGĞHIIJKLMNOÖPRSŞTUÜVYZ"]
metin=metin.upper()
sifre=""
for harf in [*metin]:
sifre+=(alfabe[(alfabe.index(harf)-anahtar)%29])
return sifre
print(sifrele("Muratz",anahtar=3))
print(sifreac("ÖYTÇVC"))
!conda install rise -y
```
| github_jupyter |
# Training Object Detection Models in SageMaker with Augmented Manifests
This notebook demonstrates the use of an "augmented manifest" to train an object detection machine learning model with AWS SageMaker.
## Setup
Here we define S3 file paths for input and output data, the training image containing the semantic segmentaion algorithm, and instantiate a SageMaker session.
```
import boto3
import re
import sagemaker
from sagemaker import get_execution_role
import time
from time import gmtime, strftime
import json
role = get_execution_role()
sess = sagemaker.Session()
s3 = boto3.resource('s3')
training_image = sagemaker.amazon.amazon_estimator.get_image_uri(boto3.Session().region_name, 'object-detection', repo_version='latest')
```
### Required Inputs
*Be sure to edit the file names and paths below for your own use!*
```
augmented_manifest_filename_train = 'augmented-manifest-train.manifest' # Replace with the filename for your training data.
augmented_manifest_filename_validation = 'augmented-manifest-validation.manifest' # Replace with the filename for your validation data.
bucket_name = "ground-truth-augmented-manifest-demo" # Replace with your bucket name.
s3_prefix = 'object-detection' # Replace with the S3 prefix where your data files reside.
s3_output_path = 's3://{}/output'.format(bucket_name) # Replace with your desired output directory.
```
The setup section concludes with a few more definitions and constants.
```
# Defines paths for use in the training job request.
s3_train_data_path = 's3://{}/{}/{}'.format(bucket_name, s3_prefix, augmented_manifest_filename_train)
s3_validation_data_path = 's3://{}/{}/{}'.format(bucket_name, s3_prefix, augmented_manifest_filename_validation)
print("Augmented manifest for training data: {}".format(s3_train_data_path))
print("Augmented manifest for validation data: {}".format(s3_validation_data_path))
```
### Understanding the Augmented Manifest format
Augmented manifests provide two key benefits. First, the format is consistent with that of a labeling job output manifest. This means that you can take your output manifests from a Ground Truth labeling job and, whether the dataset objects were entirely human-labeled, entirely machine-labeled, or anything in between, and use them as inputs to SageMaker training jobs - all without any additional translation or reformatting! Second, the dataset objects and their corresponding ground truth labels/annotations are captured *inline*. This effectively reduces the required number of channels by half, since you no longer need one channel for the dataset objects alone and another for the associated ground truth labels/annotations.
The augmented manifest format is essentially the [json-lines format](http://jsonlines.org/), also called the new-line delimited JSON format. This format consists of an arbitrary number of well-formed, fully-defined JSON objects, each on a separate line. Augmented manifests must contain a field that defines a dataset object, and a field that defines the corresponding annotation. Let's look at an example for an object detection problem.
The Ground Truth output format is discussed more fully for various types of labeling jobs in the [official documenation](https://docs.aws.amazon.com/sagemaker/latest/dg/sms-data-output.html).
{<span style="color:blue">"source-ref"</span>: "s3://bucket_name/path_to_a_dataset_object.jpeg", <span style="color:blue">"labeling-job-name"</span>: {"annotations":[{"class_id":"0",`<bounding box dimensions>`}],"image_size":[{`<image size simensions>`}]}
The first field will always be either `source` our `source-ref`. This defines an individual dataset object. The name of the second field depends on whether the labeling job was created from the SageMaker console or through the Ground Truth API. If the job was created through the console, then the name of the field will be the labeling job name. Alternatively, if the job was created through the API, then this field maps to the `LabelAttributeName` parameter in the API.
The training job request requires a parameter called `AttributeNames`. This should be a two-element list of strings, where the first string is "source-ref", and the second string is the label attribute name from the augmented manifest. This corresponds to the <span style="color:blue">blue text</span> in the example above. In this case, we would define `attribute_names = ["source-ref", "labeling-job-name"]`.
*Be sure to carefully inspect your augmented manifest so that you can define the `attribute_names` variable below.*
### Preview Input Data
Let's read the augmented manifest so we can inspect its contents to better understand the format.
```
augmented_manifest_s3_key = s3_train_data_path.split(bucket_name)[1][1:]
s3_obj = s3.Object(bucket_name, augmented_manifest_s3_key)
augmented_manifest = s3_obj.get()['Body'].read().decode('utf-8')
augmented_manifest_lines = augmented_manifest.split('\n')
num_training_samples = len(augmented_manifest_lines) # Compute number of training samples for use in training job request.
print('Preview of Augmented Manifest File Contents')
print('-------------------------------------------')
print('\n')
for i in range(2):
print('Line {}'.format(i+1))
print(augmented_manifest_lines[i])
print('\n')
```
The key feature of the augmented manifest is that it has both the data object itself (i.e., the image), and the annotation in-line in a single JSON object. Note that the `annotations` keyword contains dimensions and coordinates (e.g., width, top, height, left) for bounding boxes! The augmented manifest can contain an arbitrary number of lines, as long as each line adheres to this format.
Let's discuss this format in more detail by descibing each parameter of this JSON object format.
* The `source-ref` field defines a single dataset object, which in this case is an image over which bounding boxes should be drawn. Note that the name of this field is arbitrary.
* The `object-detection-job-name` field defines the ground truth bounding box annotations that pertain to the image identified in the `source-ref` field. As mentioned above, note that the name of this field is arbitrary. You must take care to define this field in the `AttributeNames` parameter of the training job request, as shown later on in this notebook.
* Because this example augmented manifest was generated through a Ground Truth labeling job, this example also shows an additional field called `object-detection-job-name-metadata`. This field contains various pieces of metadata from the labeling job that produced the bounding box annotation(s) for the associated image, e.g., the creation date, confidence scores for the annotations, etc. This field is ignored during the training job. However, to make it as easy as possible to translate Ground Truth labeling jobs into trained SageMaker models, it is safe to include this field in the augmented manifest you supply to the training job.
```
attribute_names = ["source-ref","XXXX"] # Replace as appropriate for your augmented manifest.
```
# Create Training Job
First, we'll construct the request for the training job.
```
try:
if attribute_names == ["source-ref","XXXX"]:
raise Exception("The 'attribute_names' variable is set to default values. Please check your augmented manifest file for the label attribute name and set the 'attribute_names' variable accordingly.")
except NameError:
raise Exception("The attribute_names variable is not defined. Please check your augmented manifest file for the label attribute name and set the 'attribute_names' variable accordingly.")
# Create unique job name
job_name_prefix = 'groundtruth-augmented-manifest-demo'
timestamp = time.strftime('-%Y-%m-%d-%H-%M-%S', time.gmtime())
job_name = job_name_prefix + timestamp
training_params = \
{
"AlgorithmSpecification": {
"TrainingImage": training_image, # NB. This is one of the named constants defined in the first cell.
"TrainingInputMode": "Pipe"
},
"RoleArn": role,
"OutputDataConfig": {
"S3OutputPath": s3_output_path
},
"ResourceConfig": {
"InstanceCount": 1,
"InstanceType": "ml.p3.2xlarge",
"VolumeSizeInGB": 50
},
"TrainingJobName": job_name,
"HyperParameters": { # NB. These hyperparameters are at the user's discretion and are beyond the scope of this demo.
"base_network": "resnet-50",
"use_pretrained_model": "1",
"num_classes": "1",
"mini_batch_size": "1",
"epochs": "5",
"learning_rate": "0.001",
"lr_scheduler_step": "3,6",
"lr_scheduler_factor": "0.1",
"optimizer": "rmsprop",
"momentum": "0.9",
"weight_decay": "0.0005",
"overlap_threshold": "0.5",
"nms_threshold": "0.45",
"image_shape": "300",
"label_width": "350",
"num_training_samples": str(num_training_samples)
},
"StoppingCondition": {
"MaxRuntimeInSeconds": 86400
},
"InputDataConfig": [
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "AugmentedManifestFile", # NB. Augmented Manifest
"S3Uri": s3_train_data_path,
"S3DataDistributionType": "FullyReplicated",
"AttributeNames": attribute_names # NB. This must correspond to the JSON field names in your augmented manifest.
}
},
"ContentType": "application/x-recordio",
"RecordWrapperType": "RecordIO",
"CompressionType": "None"
},
{
"ChannelName": "validation",
"DataSource": {
"S3DataSource": {
"S3DataType": "AugmentedManifestFile", # NB. Augmented Manifest
"S3Uri": s3_validation_data_path,
"S3DataDistributionType": "FullyReplicated",
"AttributeNames": attribute_names # NB. This must correspond to the JSON field names in your augmented manifest.
}
},
"ContentType": "application/x-recordio",
"RecordWrapperType": "RecordIO",
"CompressionType": "None"
}
]
}
print('Training job name: {}'.format(job_name))
print('\nInput Data Location: {}'.format(training_params['InputDataConfig'][0]['DataSource']['S3DataSource']))
```
Now we create the Amazon SageMaker training job.
```
client = boto3.client(service_name='sagemaker')
client.create_training_job(**training_params)
# Confirm that the training job has started
status = client.describe_training_job(TrainingJobName=job_name)['TrainingJobStatus']
print('Training job current status: {}'.format(status))
TrainingJobStatus = client.describe_training_job(TrainingJobName=job_name)['TrainingJobStatus']
SecondaryStatus = client.describe_training_job(TrainingJobName=job_name)['SecondaryStatus']
print(TrainingJobStatus, SecondaryStatus)
while TrainingJobStatus !='Completed' and TrainingJobStatus!='Failed':
time.sleep(60)
TrainingJobStatus = client.describe_training_job(TrainingJobName=job_name)['TrainingJobStatus']
SecondaryStatus = client.describe_training_job(TrainingJobName=job_name)['SecondaryStatus']
print(TrainingJobStatus, SecondaryStatus)
training_info = client.describe_training_job(TrainingJobName=job_name)
print(training_info)
```
# Conclusion
That's it! Let's review what we've learned.
* Augmented manifests are a new format that provide a seamless interface between Ground Truth labeling jobs and SageMaker training jobs.
* In augmented manifests, you specify the dataset objects and the associated annotations in-line.
* Be sure to pay close attention to the `AttributeNames` parameter in the training job request. The strings you specifuy in this field must correspond to those that are present in your augmented manifest.
| github_jupyter |
###### Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license © 2015 L.A. Barba, C.D. Cooper, G.F. Forsyth. Based on [CFD Python](https://github.com/barbagroup/CFDPython), © 2013 L.A. Barba, also under CC-BY license.
# Relax and hold steady
This is **Module 5** of the open course [**"Practical Numerical Methods with Python"**](https://openedx.seas.gwu.edu/courses/course-v1:MAE+MAE6286+2017/about), titled *"Relax and hold steady: elliptic problems"*.
If you've come this far in the [#numericalmooc](https://twitter.com/hashtag/numericalmooc) ride, it's time to stop worrying about **time** and relax.
So far, you've learned to solve problems dominated by convection—where solutions have a directional bias and can form shocks—in [Module 3](https://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/tree/master/lessons/03_wave/): *"Riding the Wave."* In [Module 4](https://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/tree/master/lessons/04_spreadout/) (*"Spreading Out"*), we explored diffusion-dominated problems—where solutions spread in all directions. But what about situations where solutions are steady?
Many problems in physics have no time dependence, yet are rich with physical meaning: the gravitational field produced by a massive object, the electrostatic potential of a charge distribution, the displacement of a stretched membrane and the steady flow of fluid through a porous medium ... all these can be modeled by **Poisson's equation**:
$$
\begin{equation}
\nabla^2 u = f
\end{equation}
$$
where the unknown $u$ and the known $f$ are functions of space, in a domain $\Omega$. To find the solution, we require boundary conditions. These could be Dirichlet boundary conditions, specifying the value of the solution on the boundary,
$$
\begin{equation}
u = b_1 \text{ on } \partial\Omega,
\end{equation}
$$
or Neumann boundary conditions, specifying the normal derivative of the solution on the boundary,
$$
\begin{equation}
\frac{\partial u}{\partial n} = b_2 \text{ on } \partial\Omega.
\end{equation}
$$
A boundary-value problem consists of finding $u$, given the above information. Numerically, we can do this using *relaxation methods*, which start with an initial guess for $u$ and then iterate towards the solution. Let's find out how!
## Laplace's equation
The particular case of $f=0$ (homogeneous case) results in Laplace's equation:
$$
\begin{equation}
\nabla^2 u = 0
\end{equation}
$$
For example, the equation for steady, two-dimensional heat conduction is:
$$
\begin{equation}
\frac{\partial ^2 T}{\partial x^2} + \frac{\partial ^2 T}{\partial y^2} = 0
\end{equation}
$$
This is similar to the model we studied in [lesson 3](https://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/04_spreadout/04_03_Heat_Equation_2D_Explicit.ipynb) of **Module 4**, but without the time derivative: i.e., for a temperature $T$ that has reached steady state. The Laplace equation models the equilibrium state of a system under the supplied boundary conditions.
The study of solutions to Laplace's equation is called *potential theory*, and the solutions themselves are often potential fields. Let's use $p$ from now on to represent our generic dependent variable, and write Laplace's equation again (in two dimensions):
$$
\begin{equation}
\frac{\partial ^2 p}{\partial x^2} + \frac{\partial ^2 p}{\partial y^2} = 0
\end{equation}
$$
Like in the diffusion equation of the previous course module, we discretize the second-order derivatives with *central differences*. You should be able to write down a second-order central-difference formula by heart now! On a two-dimensional Cartesian grid, it gives:
$$
\begin{equation}
\frac{p_{i+1, j} - 2p_{i,j} + p_{i-1,j} }{\Delta x^2} + \frac{p_{i,j+1} - 2p_{i,j} + p_{i, j-1} }{\Delta y^2} = 0
\end{equation}
$$
When $\Delta x = \Delta y$, we end up with the following equation:
$$
\begin{equation}
p_{i+1, j} + p_{i-1,j} + p_{i,j+1} + p_{i, j-1}- 4 p_{i,j} = 0
\end{equation}
$$
This tells us that the Laplacian differential operator at grid point $(i,j)$ can be evaluated discretely using the value of $p$ at that point (with a factor $-4$) and the four neighboring points to the left and right, above and below grid point $(i,j)$.
The stencil of the discrete Laplacian operator is shown in Figure 1. It is typically called the *five-point stencil*, for obvious reasons.
<img src="./figures/laplace.svg">
#### Figure 1: Laplace five-point stencil.
The discrete equation above is valid for every interior point in the domain. If we write the equations for *all* interior points, we have a linear system of algebraic equations. We *could* solve the linear system directly (e.g., with Gaussian elimination), but we can be more clever than that!
Notice that the coefficient matrix of such a linear system has mostly zeroes. For a uniform spatial grid, the matrix is *block diagonal*: it has diagonal blocks that are tridiagonal with $-4$ on the main diagonal and $1$ on two off-center diagonals, and two more diagonals with $1$. All of the other elements are zero. Iterative methods are particularly suited for a system with this structure, and save us from storing all those zeroes.
We will start with an initial guess for the solution, $p_{i,j}^{0}$, and use the discrete Laplacian to get an update, $p_{i,j}^{1}$, then continue on computing $p_{i,j}^{k}$ until we're happy. Note that $k$ is _not_ a time index here, but an index corresponding to the number of iterations we perform in the *relaxation scheme*.
At each iteration, we compute updated values $p_{i,j}^{k+1}$ in a (hopefully) clever way so that they converge to a set of values satisfying Laplace's equation. The system will reach equilibrium only as the number of iterations tends to $\infty$, but we can approximate the equilibrium state by iterating until the change between one iteration and the next is *very* small.
The most intuitive method of iterative solution is known as the [**Jacobi method**](https://en.wikipedia.org/wiki/Jacobi_method), in which the values at the grid points are replaced by the corresponding weighted averages:
$$
\begin{equation}
p^{k+1}_{i,j} = \frac{1}{4} \left(p^{k}_{i,j-1} + p^k_{i,j+1} + p^{k}_{i-1,j} + p^k_{i+1,j} \right)
\end{equation}
$$
This method does indeed converge to the solution of Laplace's equation. Thank you Professor Jacobi!
##### Challenge task
Grab a piece of paper and write out the coefficient matrix for a discretization with 7 grid points in the $x$ direction (5 interior points) and 5 points in the $y$ direction (3 interior). The system should have 15 unknowns, and the coefficient matrix three diagonal blocks. Assume prescribed Dirichlet boundary conditions on all sides (not necessarily zero).
### Boundary conditions and relaxation
Suppose we want to model steady-state heat transfer on (say) a computer chip with one side insulated (zero Neumann BC), two sides held at a fixed temperature (Dirichlet condition) and one side touching a component that has a sinusoidal distribution of temperature.
We would need to solve Laplace's equation with boundary conditions like
$$
\begin{equation}
\begin{gathered}
p=0 \text{ at } x=0\\
\frac{\partial p}{\partial x} = 0 \text{ at } x = L_x\\
p = 0 \text{ at }y = 0 \\
p = \sin \left( \frac{\frac{3}{2}\pi x}{L_x} \right) \text{ at } y = L_y
\end{gathered}
\end{equation}
$$
We'll take $L_x=1$ and $L_y=1$ for the sizes of the domain in the $x$ and $y$ directions.
One of the defining features of elliptic PDEs is that they are "driven" by the boundary conditions. In the iterative solution of Laplace's equation, boundary conditions are set and **the solution relaxes** from an initial guess to join the boundaries together smoothly, given those conditions. Our initial guess will be $p=0$ everywhere. Now, let's relax!
First, we import our usual smattering of libraries (plus a few new ones!)
```
import numpy
from matplotlib import pyplot
%matplotlib inline
# Set the font family and size to use for Matplotlib figures.
pyplot.rcParams['font.family'] = 'serif'
pyplot.rcParams['font.size'] = 16
```
To visualize 2D data, we can use [`pyplot.imshow()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow), like we've done before, but a 3D plot can sometimes show a more intuitive view the solution. Or it's just prettier!
Be sure to enjoy the many examples of 3D plots in the `mplot3d` section of the [Matplotlib Gallery](http://matplotlib.org/gallery.html#mplot3d).
We'll import the `mplot3d` module to create 3D plots and also grab the `cm` package, which provides different colormaps for visualizing plots.
```
from mpl_toolkits import mplot3d
from matplotlib import cm
```
Let's define a function for setting up our plotting environment, to avoid repeating this set-up over and over again. It will save us some typing.
```
def plot_3d(x, y, p, label='$z$', elev=30.0, azim=45.0):
"""
Creates a Matplotlib figure with a 3D surface plot
of the scalar field p.
Parameters
----------
x : numpy.ndarray
Gridline locations in the x direction as a 1D array of floats.
y : numpy.ndarray
Gridline locations in the y direction as a 1D array of floats.
p : numpy.ndarray
Scalar field to plot as a 2D array of floats.
label : string, optional
Axis label to use in the third direction;
default: 'z'.
elev : float, optional
Elevation angle in the z plane;
default: 30.0.
azim : float, optional
Azimuth angle in the x,y plane;
default: 45.0.
"""
fig = pyplot.figure(figsize=(8.0, 6.0))
ax = mplot3d.Axes3D(fig)
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_zlabel(label)
X, Y = numpy.meshgrid(x, y)
ax.plot_surface(X, Y, p, cmap=cm.viridis)
ax.set_xlim(x[0], x[-1])
ax.set_ylim(y[0], y[-1])
ax.view_init(elev=elev, azim=azim)
```
##### Note
This plotting function uses *Viridis*, a new (and _awesome_) colormap available in Matplotlib versions 1.5 and greater. If you see an error when you try to plot using `cm.viridis`, just update Matplotlib using `conda` or `pip`.
### Analytical solution
The Laplace equation with the boundary conditions listed above has an analytical solution, given by
$$
\begin{equation}
p(x,y) = \frac{\sinh \left( \frac{\frac{3}{2} \pi y}{L_y}\right)}{\sinh \left( \frac{\frac{3}{2} \pi L_y}{L_x}\right)} \sin \left( \frac{\frac{3}{2} \pi x}{L_x} \right)
\end{equation}
$$
where $L_x$ and $L_y$ are the length of the domain in the $x$ and $y$ directions, respectively.
We previously used `numpy.meshgrid` to plot our 2D solutions to the heat equation in Module 4. Here, we'll use it again as a plotting aid. Always useful, `linspace` creates 1-row arrays of equally spaced numbers: it helps for defining $x$ and $y$ axes in line plots, but now we want the analytical solution plotted for every point in our domain. To do this, we'll use in the analytical solution the 2D arrays generated by `numpy.meshgrid`.
```
def laplace_solution(x, y, Lx, Ly):
"""
Computes and returns the analytical solution of the Laplace equation
on a given two-dimensional Cartesian grid.
Parameters
----------
x : numpy.ndarray
The gridline locations in the x direction
as a 1D array of floats.
y : numpy.ndarray
The gridline locations in the y direction
as a 1D array of floats.
Lx : float
Length of the domain in the x direction.
Ly : float
Length of the domain in the y direction.
Returns
-------
p : numpy.ndarray
The analytical solution as a 2D array of floats.
"""
X, Y = numpy.meshgrid(x, y)
p = (numpy.sinh(1.5 * numpy.pi * Y / Ly) /
numpy.sinh(1.5 * numpy.pi * Ly / Lx) *
numpy.sin(1.5 * numpy.pi * X / Lx))
return p
```
Ok, let's try out the analytical solution and use it to test the `plot_3D` function we wrote above.
```
# Set parameters.
Lx = 1.0 # domain length in the x direction
Ly = 1.0 # domain length in the y direction
nx = 41 # number of points in the x direction
ny = 41 # number of points in the y direction
# Create the gridline locations.
x = numpy.linspace(0.0, Lx, num=nx)
y = numpy.linspace(0.0, Ly, num=ny)
# Compute the analytical solution.
p_exact = laplace_solution(x, y, Lx, Ly)
# Plot the analytical solution.
plot_3d(x, y, p_exact)
```
It worked! This is what the solution *should* look like when we're 'done' relaxing. (And isn't viridis a cool colormap?)
### How long do we iterate?
We noted above that there is no time dependence in the Laplace equation. So it doesn't make a lot of sense to use a `for` loop with `nt` iterations, like we've done before.
Instead, we can use a `while` loop that continues to iteratively apply the relaxation scheme until the difference between two successive iterations is small enough.
But how small is small enough? That's a good question. We'll try to work that out as we go along.
To compare two successive potential fields, a good option is to use the [L2 norm](http://en.wikipedia.org/wiki/Norm_%28mathematics%29#Euclidean_norm) of the difference. It's defined as
$$
\begin{equation}
|\textbf{x}| = \sqrt{\sum_{i=0, j=0}^k \left|p^{k+1}_{i,j} - p^k_{i,j}\right|^2}
\end{equation}
$$
But there's one flaw with this formula. We are summing the difference between successive iterations at each point on the grid. So what happens when the grid grows? (For example, if we're refining the grid, for whatever reason.) There will be more grid points to compare and so more contributions to the sum. The norm will be a larger number just because of the grid size!
That doesn't seem right. We'll fix it by normalizing the norm, dividing the above formula by the norm of the potential field at iteration $k$.
For two successive iterations, the relative L2 norm is then calculated as
$$
\begin{equation}
|\textbf{x}| = \frac{\sqrt{\sum_{i=0, j=0}^k \left|p^{k+1}_{i,j} - p^k_{i,j}\right|^2}}{\sqrt{\sum_{i=0, j=0}^k \left|p^k_{i,j}\right|^2}}
\end{equation}
$$
For this purpose, we define the `l2_norm` function:
```
def l2_norm(p, p_ref):
"""
Computes and returns the relative L2-norm of the difference
between a solution p and a reference solution p_ref.
Parameters
----------
p : numpy.ndarray
The solution as an array of floats.
p_ref : numpy.ndarray
The reference solution as an array of floats.
Returns
-------
diff : float
The relative L2-norm of the difference.
"""
l2_diff = (numpy.sqrt(numpy.sum((p - p_ref)**2)) /
numpy.sqrt(numpy.sum(p_ref**2)))
return l2_diff
```
Now, let's define a function that will apply Jacobi's method for Laplace's equation. Three of the boundaries are Dirichlet boundaries and so we can simply leave them alone. Only the Neumann boundary needs to be explicitly calculated at each iteration.
```
def laplace_2d_jacobi(p0, maxiter=20000, rtol=1e-6):
"""
Solves the 2D Laplace equation using Jacobi relaxation method.
The function assumes Dirichlet condition with value zero
at all boundaries except at the right boundary where it uses
a zero-gradient Neumann condition.
The exit criterion of the solver is based on the relative L2-norm
of the solution difference between two consecutive iterations.
Parameters
----------
p0 : numpy.ndarray
The initial solution as a 2D array of floats.
maxiter : integer, optional
Maximum number of iterations to perform;
default: 20000.
rtol : float, optional
Relative tolerance for convergence;
default: 1e-6.
Returns
-------
p : numpy.ndarray
The solution after relaxation as a 2D array of floats.
ite : integer
The number of iterations performed.
diff : float
The final relative L2-norm of the difference.
"""
p = p0.copy()
diff = rtol + 1.0 # initial difference
ite = 0 # iteration index
while diff > rtol and ite < maxiter:
pn = p.copy()
# Update the solution at interior points.
p[1:-1, 1:-1] = 0.25 * (p[1:-1, :-2] + p[1:-1, 2:] +
p[:-2, 1:-1] + p[2:, 1:-1])
# Apply Neumann condition (zero-gradient)
# at the right boundary.
p[1:-1, -1] = p[1:-1, -2]
# Compute the residual as the L2-norm of the difference.
diff = l2_norm(p, pn)
ite += 1
return p, ite, diff
```
##### Rows and columns, and index order
Recall that in the [2D explicit heat equation](http://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/04_spreadout/04_03_Heat_Equation_2D_Explicit.ipynb) we stored data with the $y$ coordinates corresponding to the rows of the array and $x$ coordinates on the columns (this is just a code design decision!). We did that so that a plot of the 2D-array values would have the natural ordering, corresponding to the physical domain ($y$ coordinate in the vertical).
We'll follow the same convention here (even though we'll be plotting in 3D, so there's no real reason), just to be consistent. Thus, $p_{i,j}$ will be stored in array format as `p[j,i]`. Don't be confused by this.
### Let's relax!
The initial values of the potential field are zero everywhere (initial guess), except at the top boundary:
$$
p = \sin \left( \frac{\frac{3}{2}\pi x}{L_x} \right) \text{ at } y=L_y
$$
To initialize the domain, `numpy.zeros` will handle everything except that one Dirichlet condition. Let's do it!
```
# Set the initial conditions.
p0 = numpy.zeros((ny, nx))
p0[-1, :] = numpy.sin(1.5 * numpy.pi * x / Lx)
```
Now let's visualize the initial conditions using the `plot_3D` function, just to check we've got it right.
```
# Plot the initial conditions.
plot_3d(x, y, p0)
```
The `p` array is equal to zero everywhere, except along the boundary $y = 1$. Hopefully you can see how the relaxed solution and this initial condition are related.
Now, run the iterative solver with a target L2-norm difference between successive iterations of $10^{-8}$.
```
# Compute the solution using Jacobi relaxation method.
p, ites, diff = laplace_2d_jacobi(p0, rtol=1e-8)
print('Jacobi relaxation: {} iterations '.format(ites) +
'to reach a relative difference of {}'.format(diff))
```
Let's make a gorgeous plot of the final field using the newly minted `plot_3d` function.
```
# Plot the numerical solution.
plot_3d(x, y, p)
```
Awesome! That looks pretty good. But we'll need more than a simple visual check, though. The "eyeball metric" is very forgiving!
## Convergence analysis
### Convergence, Take 1
We want to make sure that our Jacobi function is working properly. Since we have an analytical solution, what better way than to do a grid-convergence analysis? We will run our solver for several grid sizes and look at how fast the L2 norm of the difference between consecutive iterations decreases.
Now run Jacobi's method on the Laplace equation using four different grids, with the same exit criterion of $10^{-8}$ each time. Then, we look at the error versus the grid size in a log-log plot. What do we get?
```
# List of the grid sizes to investigate.
nx_values = [11, 21, 41, 81]
# Create an empty list to record the error on each grid.
errors = []
# Compute the solution and error for each grid size.
for nx in nx_values:
ny = nx # same number of points in all directions.
# Create the gridline locations.
x = numpy.linspace(0.0, Lx, num=nx)
y = numpy.linspace(0.0, Ly, num=ny)
# Set the initial conditions.
p0 = numpy.zeros((ny, nx))
p0[-1, :] = numpy.sin(1.5 * numpy.pi * x / Lx)
# Relax the solution.
# We do not return the number of iterations or
# the final relative L2-norm of the difference.
p, _, _ = laplace_2d_jacobi(p0, rtol=1e-8)
# Compute the analytical solution.
p_exact = laplace_solution(x, y, Lx, Ly)
# Compute and record the relative L2-norm of the error.
errors.append(l2_norm(p, p_exact))
# Plot the error versus the grid-spacing size.
pyplot.figure(figsize=(6.0, 6.0))
pyplot.xlabel(r'$\Delta x$')
pyplot.ylabel('Relative $L_2$-norm\nof the error')
pyplot.grid()
dx_values = Lx / (numpy.array(nx_values) - 1)
pyplot.loglog(dx_values, errors,
color='black', linestyle='--', linewidth=2, marker='o')
pyplot.axis('equal');
```
Hmm. That doesn't look like 2nd-order convergence, but we're using second-order finite differences. *What's going on?* The culprit is the boundary conditions. Dirichlet conditions are order-agnostic (a set value is a set value), but the scheme we used for the Neumann boundary condition is 1st-order.
Remember when we said that the boundaries drive the problem? One boundary that's 1st-order completely tanked our spatial convergence. Let's fix it!
### 2nd-order Neumann BCs
Up to this point, we have used the first-order approximation of a derivative to satisfy Neumann B.C.'s. For a boundary located at $x=0$ this reads,
$$
\begin{equation}
\frac{p^{k+1}_{1,j} - p^{k+1}_{0,j}}{\Delta x} = 0
\end{equation}
$$
which, solving for $p^{k+1}_{0,j}$ gives us
$$
\begin{equation}
p^{k+1}_{0,j} = p^{k+1}_{1,j}
\end{equation}
$$
Using that Neumann condition will limit us to 1st-order convergence. Instead, we can start with a 2nd-order approximation (the central-difference approximation):
$$
\begin{equation}
\frac{p^{k+1}_{1,j} - p^{k+1}_{-1,j}}{2 \Delta x} = 0
\end{equation}
$$
That seems problematic, since there is no grid point $p^{k}_{-1,j}$. But no matter … let's carry on. According to the 2nd-order approximation,
$$
\begin{equation}
p^{k+1}_{-1,j} = p^{k+1}_{1,j}
\end{equation}
$$
Recall the finite-difference Jacobi equation with $i=0$:
$$
\begin{equation}
p^{k+1}_{0,j} = \frac{1}{4} \left(p^{k}_{0,j-1} + p^k_{0,j+1} + p^{k}_{-1,j} + p^k_{1,j} \right)
\end{equation}
$$
Notice that the equation relies on the troublesome (nonexistent) point $p^k_{-1,j}$, but according to the equality just above, we have a value we can substitute, namely $p^k_{1,j}$. Ah! We've completed the 2nd-order Neumann condition:
$$
\begin{equation}
p^{k+1}_{0,j} = \frac{1}{4} \left(p^{k}_{0,j-1} + p^k_{0,j+1} + 2p^{k}_{1,j} \right)
\end{equation}
$$
That's a bit more complicated than the first-order version, but it's relatively straightforward to code.
##### Note
Do not confuse $p^{k+1}_{-1,j}$ with `p[-1]`:
`p[-1]` is a piece of Python code used to refer to the last element of a list or array named `p`. $p^{k+1}_{-1,j}$ is a 'ghost' point that describes a position that lies outside the actual domain.
### Convergence, Take 2
We can copy the previous Jacobi function and replace only the line implementing the Neumann boundary condition.
##### Careful!
Remember that our problem has the Neumann boundary located at $x = L$ and not $x = 0$ as we assumed in the derivation above.
```
def laplace_2d_jacobi_neumann(p0, maxiter=20000, rtol=1e-6):
"""
Solves the 2D Laplace equation using Jacobi relaxation method.
The function assumes Dirichlet condition with value zero
at all boundaries except at the right boundary where it uses
a zero-gradient second-order Neumann condition.
The exit criterion of the solver is based on the relative L2-norm
of the solution difference between two consecutive iterations.
Parameters
----------
p0 : numpy.ndarray
The initial solution as a 2D array of floats.
maxiter : integer, optional
Maximum number of iterations to perform;
default: 20000.
rtol : float, optional
Relative tolerance for convergence;
default: 1e-6.
Returns
-------
p : numpy.ndarray
The solution after relaxation as a 2D array of floats.
ite : integer
The number of iterations performed.
diff : float
The final relative L2-norm of the difference.
"""
p = p0.copy()
diff = rtol + 1.0 # intial difference
ite = 0 # iteration index
while diff > rtol and ite < maxiter:
pn = p.copy()
# Update the solution at interior points.
p[1:-1, 1:-1] = 0.25 * (p[1:-1, :-2] + p[1:-1, 2:] +
p[:-2, 1:-1] + p[2:, 1:-1])
# Apply 2nd-order Neumann condition (zero-gradient)
# at the right boundary.
p[1:-1, -1] = 0.25 * (2.0 * pn[1:-1, -2] +
pn[2:, -1] + pn[:-2, -1])
# Compute the residual as the L2-norm of the difference.
diff = l2_norm(p, pn)
ite += 1
return p, ite, diff
```
Again, this is the exact same code as before, but now we're running the Jacobi solver with a 2nd-order Neumann boundary condition. Let's do a grid-refinement analysis, and plot the error versus the grid spacing.
```
# List of the grid sizes to investigate.
nx_values = [11, 21, 41, 81]
# Create an empty list to record the error on each grid.
errors = []
# Compute the solution and error for each grid size.
for nx in nx_values:
ny = nx # same number of points in all directions.
# Create the gridline locations.
x = numpy.linspace(0.0, Lx, num=nx)
y = numpy.linspace(0.0, Ly, num=ny)
# Set the initial conditions.
p0 = numpy.zeros((ny, nx))
p0[-1, :] = numpy.sin(1.5 * numpy.pi * x / Lx)
# Relax the solution.
# We do not return the number of iterations or
# the final relative L2-norm of the difference.
p, _, _ = laplace_2d_jacobi_neumann(p0, rtol=1e-8)
# Compute the analytical solution.
p_exact = laplace_solution(x, y, Lx, Ly)
# Compute and record the relative L2-norm of the error.
errors.append(l2_norm(p, p_exact))
# Plot the error versus the grid-spacing size.
pyplot.figure(figsize=(6.0, 6.0))
pyplot.xlabel(r'$\Delta x$')
pyplot.ylabel('Relative $L_2$-norm\nof the error')
pyplot.grid()
dx_values = Lx / (numpy.array(nx_values) - 1)
pyplot.loglog(dx_values, errors,
color='black', linestyle='--', linewidth=2, marker='o')
pyplot.axis('equal');
```
Nice! That's much better. It might not be *exactly* 2nd-order, but it's awfully close. (What is ["close enough"](http://ianhawke.github.io/blog/close-enough.html) in regards to observed convergence rates is a thorny question.)
Now, notice from this plot that the error on the finest grid is around $0.0002$. Given this, perhaps we didn't need to continue iterating until a target difference between two solutions of $10^{-8}$. The spatial accuracy of the finite difference approximation is much worse than that! But we didn't know it ahead of time, did we? That's the "catch 22" of iterative solution of systems arising from discretization of PDEs.
## Final word
The Jacobi method is the simplest relaxation scheme to explain and to apply. It is also the *worst* iterative solver! In practice, it is seldom used on its own as a solver, although it is useful as a smoother with multi-grid methods. As we will see in the [third lesson](https://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/05_relax/05_03_Iterate.This.ipynb) of this module, there are much better iterative methods! But first, let's play with [Poisson's equation](https://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/05_relax/05_02_2D.Poisson.Equation.ipynb).
---
###### The cell below loads the style of the notebook
```
from IPython.core.display import HTML
css_file = '../../styles/numericalmoocstyle.css'
HTML(open(css_file, 'r').read())
```
| github_jupyter |
## Hands-On Data Preprocessing in Python
Learn how to effectively prepare data for successful data analytics
AUTHOR: Dr. Roy Jafari
### Chapter 12: Data Fusion & Data Integration
#### Excercises
```
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
```
# Excercise 1
In your own words, what is the difference between Data Fusion and Data Integration? Give examples other than the ones in this chapter.
# Excercise 2
Answer the following question about **Challenge 4: Aggregation mismatch**. Is this challenge a data fusion one, a data integration, or both? Explain.
# Excercise 3
How come **Challenge 2: Unwise data collection** is somehow both a data cleaning step and a data integration? Do you think it is essential that we categorize if an unwise data collection should be under data cleaning or data integration?
# Excercise 4
In Example 1 of this chapter, we used multi-level indexing using Date and Hour to overcome the index mismatched formatting challenge. For this exercise, repeat this example but this time use a single level indexing using python DataTime object.
# Excercise 5
Recreate **Figure 5.23** from **Chapter 5 Data Visualization**, but this time instead of using *WH Report_preprocessed.csv*, integrate the following three files yourself first: *WH Report.csv*, *populations.csv*, and *Countires.csv*. Hint: information about happiness indices come from *WH Report.csv*, information of the countries content comes from *Countires.csv*, and population information comes from *populations.csv*.
# Excercise 6
In **Chapter 6, Exercise 2**, we used *ToyotaCorolla_preprocessed.csv* to create a model that predicts the price of cars. In this exercise, we want to do the preprocessing ourselves. Use *ToyotaCorolla.csv* to perform the following steps.
a. Are there any concerns regarding Level Ⅰ data cleaning? If yes, address them if necessary.
b. Are there any concerns regarding Level Ⅱ data cleaning? If yes, address them if necessary.
c. Are there any concerns regarding Level Ⅲ data cleaning? If yes, address them if necessary.
d. Are there attributes in ToyotaCorolla.csv that can be considered redundant?
e. Apply LinearRegression from sklearn.linear_model. Did you have to remove the redundant attributes? Why/Why now?
f. Apply MLPRegressor from sklearn.neural_network. Did you have to remove the redundant attributes? Why/Why now?
# Excercise 7
We would like to use the file *Universities.csv* to cluster the universities into two meaningful clusters. However, the data source has many issues including data cleaning levels Ⅰ - Ⅲ and data redundancy. Perform the following steps.
a. Deal with data cleaning issues
b. Deal with data redundancy issues
c. Use any column necessary except State and Public (1)/ Private (2) to find the two meaningful clusters.
d. Perform centroid analysis and give a name to each cluster.
e. Find if the newly created categorical attribute cluster has a relationship with either of the two categorical attributes we intentionally did not use for clustering: State or Public (1)/ Private (2).
# Excercise 8
In this exercise, we will see an example of data fusion. The case study that we will use in this exercise was already introduced under Data Fusion Example in this chapter, please go back and read it again before continuing with this exercise.
In short, in this example, we would like to integrate Yeild.csv and Treatment.csv to see if the amount of water that can impact the amount of yield.
Perform the following steps to make this happen.
a. Use pd.read_csv() to read Yeild.csv into yield_df, and read Treatment.csv into treatment_df.
b. Draw a scatterplot of the points in treatment_df. use the dimension of color to add the amount of watter that has been dispensed from each point.
c. Draw a scatterplot of the points in yield_df. use the dimension of color to add the amount of harvest that has been collected from each point.
d. Create a scatterplot that combines the visual in b and c.
e. From the scatterplots in the preceding steps, we can deduce that the water stations are within an equidistant space from one another. Based on this realization, calculate the equidistant diameter between the water points, and call it radius. We are going to use this variable in the next steps of calculations.
f. First, use the following code to create the function calculateDistance().
```import math
def calculateDistance(x1,y1,x2,y2):
dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
return dist```
Then, use the following code and the preceding function we just created, create the function waterRecieved() so we can apply it to the function to the rows of treatment_df.
```def WaterReceived(r):
w = 0
for i, rr in treatment_df.iterrows():
distance = calculateDistance(rr.longitude,
rr.latitude,
r.longitude,
r.latitude)
if (distance< radius):
w= w + rr.water * ((radius-distance)/radius)
return w```
g. Apply **waterRecieved()** to the rows of **yeild_df**, and add the newly calucated value for each row under the column name water.
h. Study the newly updated yeild_df. You were just able to fuse these two data sources. Go back and study these steps, especially the creation of function waterRecieved(). What are the assumptions that made this data fusion possible?
Answer:
i. Draw the scatter plot of the two attributes yeild_df.harvest and yeild_df.water. Do we see an impact from yeild_df.water on yeild_df.harvest?
j. Use correlation coefficient to confirm your observation from the previous step.
| github_jupyter |
```
import cv2
import os
import matplotlib.pyplot as plt
from glob import glob
import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
np.random.seed(42)
import tensorflow as tf
tf.compat.v1.reset_default_graph()
import keras
#from keras.utils import np_utils
from keras.models import Sequential, Model, Input
from keras.layers.core import Dense, Activation, Flatten, Dropout, Reshape
from keras.layers.convolutional import Conv2D, MaxPooling2D,AveragePooling2D, ZeroPadding2D
from keras.layers import Input, Add
from keras.optimizers import SGD, Adam, RMSprop, Adagrad
from keras import regularizers
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.models import Model, load_model
from keras.preprocessing import image
from keras.initializers import glorot_uniform
IMG_CHANNELS = 3
IMG_ROWS = 128
IMG_COLS = 128
#CONSTANT
BATCH_SIZE = 16
NB_EPOCH = 15
NB_CLASSES = 2
VERBOSE = 1
VALIDATION_SPLIT = 0.15
OPTIM = Adam(lr=0.005) # Other optimizers are SGD, Adam, Adagrad
from google.colab import drive
drive.mount('/content/gdrive')
!unzip '/content/gdrive/My Drive/Colab_Dataset/Dataset2.zip'
image_name = []
image_label = []
for file in os.listdir('COVID'):
filename, fileextension = os.path.splitext(file)
if(fileextension == '.png'):
file_path = 'COVID' + '/' + file
image_name.append(file_path)
image_label.append(1)
for file in os.listdir('non-COVID'):
filename, fileextension = os.path.splitext(file)
if(fileextension == '.png'):
file_path = 'non-COVID' + '/' + file
image_name.append(file_path)
image_label.append(0)
WIDTH = 128
HEIGHT = 128
def process_image():
#Return two array. One of resized images and other of array of labels
x = [] # array of images
y = [] # array of labels
for i in range(0,len(image_name)):
#Read and resize image
full_size_image = cv2.imread(image_name[i])
x.append(cv2.resize(full_size_image,(WIDTH, HEIGHT),interpolation=cv2.INTER_CUBIC));
# Labels
y.append(image_label[i])
return x,y
x,y = process_image()
x = np.asarray(x)
y = np.asarray(y)
print('Shape of x: ',x.shape, ' Shape of y: ', y.shape)
print('Dimension of x: ', x.ndim, ' Dimension of y: ', y.ndim)
X_train, X_test, y_train, y_test = train_test_split(x,y, test_size = 0.2, random_state = 42)
print('Shape of X_train: ',X_train.shape, ' Shape of y_train: ', y_train.shape)
print('Shape of X_test: ',X_test.shape, ' Shape of y_test: ', y_test.shape)
train_datagen = ImageDataGenerator(
rescale = 1.0/255.0,
#zoom_range = 0.2,
horizontal_flip = True,
fill_mode="nearest"
)
test_datagen = ImageDataGenerator(
rescale = 1.0/255.0)
train_generator = train_datagen.flow(X_train,y_train, batch_size = BATCH_SIZE)
test_generator = test_datagen.flow(X_test,y_test, batch_size = BATCH_SIZE)
model = Sequential()
# 1st Convolutional Layer
model.add(Conv2D(filters=96, input_shape=(128,128,3), kernel_size=(11,11), strides=(4,4), padding='same', activation='relu'))
# Max Pooling
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# 2nd Convolutional Layer
model.add(Conv2D(filters=256, kernel_size=(11,11), strides=(1,1), padding='same', activation='relu'))
# Max Pooling
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# 3rd Convolutional Layer
model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu'))
# 4th Convolutional Layer
model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu'))
# 5th Convolutional Layer
model.add(Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu'))
# Max Pooling
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Passing it to a Fully Connected layer
model.add(Flatten())
# 1st Fully Connected Layer
model.add(Dense(4096, activation='relu'))
# Add Dropout to prevent overfitting
model.add(Dropout(0.4))
# 2nd Fully Connected Layer
model.add(Dense(4096, activation='relu'))
# Add Dropout
model.add(Dropout(0.4))
# 3rd Fully Connected Layer
model.add(Dense(1000, activation='relu'))
# Add Dropout
model.add(Dropout(0.4))
# Output Layer
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer=RMSprop(1e-5), loss='binary_crossentropy', metrics = ['accuracy'])
model.summary()
model_history = model.fit_generator(train_generator,epochs=100 ,validation_data=test_generator)
score = model.evaluate_generator(test_generator)
print('Test score: ', score[0])
print('Test accuracy: ', score[1])
print('Train Score: ',model.evaluate_generator(train_generator)[0])
print('Train Accuracy: ',model.evaluate_generator(train_generator)[1])
plt.plot(model_history.history['loss'], label='train')
plt.plot(model_history.history['val_loss'], label='test')
plt.xlabel('No of Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
# learning curves of model accuracy
plt.plot(model_history.history['accuracy'], label='train')
plt.plot(model_history.history['val_accuracy'], label='test')
plt.xlabel('No of Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
model.save('Saved Models/CNN2.h5')
```
| github_jupyter |
# Previously
We practiced the workflow of defining/building neural nets and training them which involved defining the loss and optimizer and doing the backpropagation. We also learned how to get the test and train losses and try it out on one image. Our results are kind of good; however, we also need to quantify the "good" in our performance. Also, that's not the end, the results can be better!
# In this notebook,
We will learn about:
- the concepts regarding one of the main subprocceses of our workflow-- the Validation Pass
- improving our neural network
- we will learn how to solve overfitting via regularization such as dropout
- we will look at the use of the validation set
- to complete the whole basic process, we'll learn about Inference
# Conceptual
We introduce some new terms here:
**1. Inference**
- this is done after the training the network
- a term borrowed from statistics which actually means making predictions
**2. Overfitting**
- the problem in which neural networks have a tendency to perform too well on the training data and aren't able to generalize to data that hasn't been seen before.
- this impairs the inference performance
**3. Validation Set**
- data used to test for overfitting while training
- these are the data not in the training set
**Overall**
These terms makes sense by:
- We do inferences; however, overfitting lurks. We avoid overfitting through regularization such as dropout while monitoring the validation performance during training.
# Coding in PyTorch
## Preliminaries
Here we do:
- Downloading and Loading of Data along with the creation of datasets
- Defining/Building Neural Networks
### 1. Dowloading and Loading the Dataset
```
import torch
from torchvision import datasets, transforms
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# Download and load the training data
trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
# Download and load the test data
testset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)
```
***Remark: the Test Set***
- As we can see, the **test set*** was created by setting `train = False` above
- The test set contains images just like the training set
- Typically you'll see 10-20% of the original dataset held out for testing and validation with the rest being used for training.
### 2. Build the Neural Network
```
from torch import nn, optim
import torch.nn.functional as F
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 128)
self.fc3 = nn.Linear(128, 64)
self.fc4 = nn.Linear(64, 10)
def forward(self, x):
# make sure input tensor is flattened
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = F.log_softmax(self.fc4(x), dim=1)
return x
```
## Adding Validation Pass
This is tied to performance metrics. Reiterating:
**validation set**
- the goal is to measure the model's performance on data that isn't part of the training set
**Performance Metrics**
- standards used to tell how the model is performing
- examples are accuracy, [precision and recall](https://en.wikipedia.org/wiki/Precision_and_recall#Definition_(classification_context)), and top-5 error rate.
***Remark:***
- Here we focus on accuracy
### 1. One batch and one forward pass
- we do only a forward pass with one batch from the test set
#### a. Set Up the Model
```
# Setting Up the model and images and label
model = Classifier()
images, labels = next(iter(testloader))
# with this we have the true values
```
#### b. Calculate Accuracy
**accuracy**
- (number of correct predictions divided by total number of values considered) * 100%
Thus to get accuracy, we want to compare the true labels containing the correct classes with the predicted classes.
The steps are as follows:
```
# 1. Get the class probabilities
ps = torch.exp(model(images))
# recall: our model returns a log-softmax output
# but this time we want the class probabilities
# so we call torch.exp to turn it back to that
# Make sure the shape is appropriate, we should get 10 class probabilities for 64 examples
print(ps.shape)
```
Since for every image, we have probabilities for each class.
We only want the class with highest probability to be the predicted label.
Rephrasing that one will be:
**predicted label**
- the class that has the highest prediction among the other classes
So we do:
```
# 2. Get the predicted label
top_p, top_class = ps.topk(1, dim=1)
print(top_class[:10,:])
```
**ps.topk method**
- returns the *k* highest values
**ps.topk(1)**
- returns the most likely class
- returns a tuple of the top-k values and the top-k indices
- that is, if the highest value is the fifth element, we'll get 4 as the index
```
# 3. Know which predictions are correctly labeled.
# that is, 0 for wrong - 1 for right
equals = top_class == labels.view(*top_class.shape)
# recall: .view is used to change the shape of the tensor
# this is because top_class is a 2D tensor (64,1) and
# labels is 1D with shape (64)
# 4. Calculate the percentage of predictions
accuracy = torch.mean(equals.type(torch.FloatTensor))
print(f'Accuracy: {accuracy.item()*100}%')
```
(copying again here)
**accuracy**
- (number of correct predictions divided by total number of values considered) * 100%
in our case, since we use 1 for correct,
number of correct predictions = sum of 1s in `equals`
total number of values considered is = length of equals
However, we converted `equals` to a float tensor since `torch.mean` do not accept byte tensors which is initally the type of our `equal`.
***Remark:***
- Such a low accuracy? That's because our network is untrained.
Now let's train our network and include our validation pass so we can measure how well the network is performing on the test set.
### 2. Entire Dataset - Training the network with Validation pass (30 epochs)
#### The Process
**Bit of Change: Turning off the Gradients**
Since we're not updating our parameters in the validation pass, we can speed up the by turning off gradients using torch.no_grad():
```python
# turn off gradients
with torch.no_grad():
# validation pass here
for images, labels in testloader:
...
```
Here's how we do training the network with Validation Pass:
```
# 1. Define all preliminary variables
model = Classifier()
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=0.003)
epochs = 30
steps = 0
train_losses, test_losses = [], []
# 2 Train the Network with Validation Pass
for e in range(epochs):
running_loss = 0
# 2a. We do out usual flow
# - optimizer
# - loss
# - backprop
for images, labels in trainloader:
optimizer.zero_grad()
log_ps = model(images)
loss = criterion(log_ps, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
# now that we've already trained through the entire dataset
# let's test the adjustments made (the weights, etc)
#2b Validation pass
# actually the same as above but
# - we're using the test dataset as the validation dataset
# - we're computing the accuracy per epoch
else:
test_loss = 0
accuracy = 0
# Turn off gradients for validation, saves memory and computations
with torch.no_grad():
for images, labels in testloader:
log_ps = model(images)
test_loss += criterion(log_ps, labels)
# this is what we did above in the One Pass
ps = torch.exp(log_ps)
top_p, top_class = ps.topk(1, dim=1)
equals = top_class == labels.view(*top_class.shape)
accuracy += torch.mean(equals.type(torch.FloatTensor))
train_losses.append(running_loss/len(trainloader))
test_losses.append(test_loss/len(testloader))
print("Epoch: {}/{}.. ".format(e+1, epochs),
"Training Loss: {:.3f}.. ".format(running_loss/len(trainloader)),
"Test Loss: {:.3f}.. ".format(test_loss/len(testloader)),
"Test Accuracy: {:.3f}".format(accuracy/len(testloader)))
```
***Remark:***
- Do not be confused here. We named the validation loss as the test loss. Later on, we'll use the three of them.
**Spoiler: Difference of validation dataset and test dataset**
*you actually know this but restating here
**Validation Dataset**
- "test dataset" (in a sense as it is used to get the accuracy) used while training
**Test Dataset**
- used after training
- most likely used in saved models (As we will learn later)
#### Visualizing
```
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
plt.plot(train_losses, label='Training loss')
plt.plot(test_losses, label='Validation loss')
plt.legend(frameon=False)
```
We're having a problem of overfitting here
## Improving Performance
### Conceptual (with little bit of code)
#### The Problem of Overfitting

**Overfitting**
- Decreasing Train loss: when the network learns the training set better and better, resulting in training losses
- Increasing Validation loss: means that the network starts having problems generalizing data outside the training set
#### Strategies for Reducing Overfitting
##### **1. Early-stopping**
- to use the model with the lowest validation loss
- you heard that right. To make sense, in practice, you'd save the model frequently as you're training then later choose the model with the lowest validation loss.
- *In this example that can be found around 8-10 training epochs
##### **2. Dropout**
- this is done outside early-stopping
- means that you can use both of them at the same time
- the randomly dropping of input units
- this forces the network to share information between weights, increasing it's ability to generalize to new data
###### Sample Code
```python
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 128)
self.fc3 = nn.Linear(128, 64)
self.fc4 = nn.Linear(64, 10)
# Dropout module with 0.2 drop probability
self.dropout = nn.Dropout(p=0.2)
def forward(self, x):
# make sure input tensor is flattened
x = x.view(x.shape[0], -1)
# Now with dropout
x = self.dropout(F.relu(self.fc1(x)))
x = self.dropout(F.relu(self.fc2(x)))
x = self.dropout(F.relu(self.fc3(x)))
# output so no dropout here
x = F.log_softmax(self.fc4(x), dim=1)
return x
```
###### Guidelines in using Dropout
There are parts where we want to turn on and off the Dropout.
**During Training**
- We want **to use** dropout to prevent overfitting
- we use `model.train()`
**During Validation, Testing and whenever we Make Predictions**
- We want to not use dropout since we want to use the entire network
- we use `model.eval()`
In general, the whole process of the validation loop with Dropout is like:
1. Turn OFF the gradient
2. Set the model to evaluation mode to not use Dropout
3. Calculate the Validation loss and metric
4. Set the model back to train mode to use Dropout
```python
# turn off gradients
with torch.no_grad():
# set model to evaluation mode
model.eval()
# validation pass here
for images, labels in testloader:
...
# set model back to train mode
model.train()
```
### Coding All Previous Processes with Dropout Solution
So far our process is: (after Loading the Data and Splitting the dataset)
1. Define/Build the Network with Dropout
2. Training
- includes loss, optimizers, and backprop + Dropout
3. Validation Pass
- includes calculation of accuracy + No Dropout
```
# 1. Define/Build the Network with Dropout
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 128)
self.fc3 = nn.Linear(128, 64)
self.fc4 = nn.Linear(64, 10)
# Dropout module with 0.2 drop probability
self.dropout = nn.Dropout(p=0.2)
def forward(self, x):
# make sure input tensor is flattened
x = x.view(x.shape[0], -1)
# Now with dropout
x = self.dropout(F.relu(self.fc1(x)))
x = self.dropout(F.relu(self.fc2(x)))
x = self.dropout(F.relu(self.fc3(x)))
# output so no dropout here
x = F.log_softmax(self.fc4(x), dim=1)
return x
# 2. Training + Dropout
model = Classifier()
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=0.003)
epochs = 30
steps = 0
train_losses, test_losses = [], []
for e in range(epochs):
running_loss = 0
for images, labels in trainloader:
optimizer.zero_grad()
log_ps = model(images)
loss = criterion(log_ps, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
else:
test_loss = 0
accuracy = 0
# 3. Validation pass + No Dropout
# Turn off gradients for validation, saves memory and computations
with torch.no_grad():
model.eval()
for images, labels in testloader:
log_ps = model(images)
test_loss += criterion(log_ps, labels)
ps = torch.exp(log_ps)
top_p, top_class = ps.topk(1, dim=1)
equals = top_class == labels.view(*top_class.shape)
accuracy += torch.mean(equals.type(torch.FloatTensor))
model.train()
train_losses.append(running_loss/len(trainloader))
test_losses.append(test_loss/len(testloader))
print("Epoch: {}/{}.. ".format(e+1, epochs),
"Training Loss: {:.3f}.. ".format(train_losses[-1]),
"Test Loss: {:.3f}.. ".format(test_losses[-1]),
"Test Accuracy: {:.3f}".format(accuracy/len(testloader)))
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
plt.plot(train_losses, label='Training loss')
plt.plot(test_losses, label='Validation loss')
plt.legend(frameon=False)
```
## Inference
*recall*
**Inference**
- this is done after the training the network
- a term borrowed from statistics which actually means making predictions
- **recall:**
- we use `model.eval()` to turn off Dropout
- we use `torch.no_grad()` to turn off autograd
```
# folks the helper package always goes in the way as with the previous notebooks
# so don't forget this one if you're running in colab
!wget https://raw.githubusercontent.com/udacity/deep-learning-v2-pytorch/3bd7dea850e936d8cb44adda8200e4e2b5d627e3/intro-to-pytorch/helper.py
# if this doesn't still get through by running, reset your runtime and
# it will work
# also don't forget to change your Hardware Accelerator above to GPU for faster processing
# Import helper module (should be in the repo)
import helper
# Test out your network!
model.eval()
dataiter = iter(testloader)
images, labels = dataiter.next()
img = images[0]
# Convert 2D image to 1D vector
img = img.view(1, 784)
# Calculate the class probabilities (softmax) for img
with torch.no_grad():
output = model.forward(img)
ps = torch.exp(output)
# Plot the image and probabilities
helper.view_classify(img.view(1, 28, 28), ps, version='Fashion')
```
# Next Up!
Here, we saw the whole basic skeleton of our workflow with additional improvements.
In the next part, as we've stated above, we'll need to save the trained models with the lowest validation loss. So we'll learn saving trained models. This can be done after training or after inference. Though, we may wanna load the model we saved for inference.
| github_jupyter |
```
import numpy as np#you usually need numpy
#---these are for plots---#
import matplotlib
matplotlib.use('nbAgg')
import matplotlib.pyplot as plt
plt.rcParams['font.size']=16
plt.rcParams['font.family']='dejavu sans'
plt.rcParams['mathtext.fontset']='stix'
plt.rcParams['mathtext.rm']='custom'
plt.rcParams['mathtext.it']='stix:italic'
plt.rcParams['mathtext.bf']='stix:bold'
#-------------------------#
#load the module
from sys import path as sysPath
from os import path as osPath
sysPath.append(osPath.join(osPath.dirname('./'), '../../src'))
from interfacePy.Axion import Axion
from interfacePy.AxionMass import AxionMass
from interfacePy.Cosmo import Hubble,rho_crit,h_hub
from interfacePy.FT import FT #easy tick formatting
theta_i, fa=0.1, 1e16
umax=500
TSTOP=1e-4
ratio_ini=1e3
N_convergence_max, convergence_lim=15, 1e-2 #this is fine, but you can experiment a bit.
#radiation dominated example
inputFile="../../UserSpace/InputExamples/MatterInput.dat"
#you can define the axion mass using a data file
axionMass = AxionMass(r'../../src/data/chi.dat',0,1e5)
#you can define the axion mass via a function
# def ma2(T,fa):
# TQCD=150*1e-3;
# ma20=3.1575e-05/fa/fa;
# if T<=TQCD:
# return ma20;
# return ma20*pow((TQCD/T),8.16)
# axionMass = AxionMass(ma2)
# options for the solver
# These variables are optional. Yoou can use the Axion class without them.
initial_step_size=1e-1; #initial step the solver takes.
minimum_step_size=1e-8; #This limits the sepsize to an upper limit.
maximum_step_size=1e-1; #This limits the sepsize to a lower limit.
absolute_tolerance=1e-11; #absolute tolerance of the RK solver
relative_tolerance=1e-11; #relative tolerance of the RK solver
beta=0.95; #controls how agreesive the adaptation is. Generally, it should be around but less than 1.
#The stepsize does not increase more than fac_max, and less than fac_min.
#This ensures a better stability. Ideally, fac_max=inf and fac_min=0, but in reality one must
#tweak them in order to avoid instabilities.
fac_max=1.2;
fac_min=0.8;
maximum_No_steps=int(1e7); #maximum steps the solver can take Quits if this number is reached even if integration is not finished.
# Axion instance
ax=Axion(theta_i, fa, umax, TSTOP, ratio_ini, N_convergence_max, convergence_lim, inputFile, axionMass,
initial_step_size,minimum_step_size, maximum_step_size, absolute_tolerance,
relative_tolerance, beta, fac_max, fac_min, maximum_No_steps)
# solve the EOM (this only gives you the relic, T_osc, theta_osc, and a_osc)
ax.solveAxion()
ax.relic, ax.T_osc, ax.theta_osc
ax.getPeaks()#this gives you the peaks of the oscillation
ax.getPoints()#this gives you all the points of integration
ax.getErrors()#this gives you local errors of integration
if True:
fig=plt.figure(figsize=(9,4))
fig.subplots_adjust(bottom=0.15, left=0.15, top = 0.95, right=0.9,wspace=0.0,hspace=0.0)
sub = fig.add_subplot(1,1,1)
#this plot shows the peaks of the oscillation
sub.plot(ax.T_peak,ax.theta_peak,linestyle=':',marker='+',color='xkcd:blue',linewidth=2)
#this plot shows all the points
sub.plot(ax.T,ax.theta,linestyle='-',linewidth=2,alpha=1,c='xkcd:black')
sub.set_xlabel(r'$T ~[{\rm GeV}]$')
sub.xaxis.set_label_coords(0.5, -0.1)
sub.set_ylabel(r'$\theta$')
sub.yaxis.set_label_coords(-0.1,0.5)
sub.axhline(ax.theta_osc,linestyle=':',color='xkcd:red',linewidth=1.5)
sub.axvline(ax.T_osc,linestyle='--',color='xkcd:gray',linewidth=1.5)
#set major ticks
_M_xticks=[ round(0.025+i*0.025,4) for i in range(0,15) ]
_M_yticks=[ round(-0.025+i*0.025,3) for i in range(0,10) ]
#set major ticks that will not have a label
_M_xticks_exception=[]
_M_yticks_exception=[]
_m_xticks=[]
_m_yticks=[]
ft=FT(_M_xticks,_M_yticks,
_M_xticks_exception,_M_yticks_exception,
_m_xticks,_m_yticks,
xmin=0.025,xmax=0.15,ymin=-0.025,ymax=0.101,xscale='linear',yscale='linear')
ft.format_ticks(plt,sub)
sub.text(x=0.055,y=0.07, s=r'$T_{\rm osc}$',rotation=90)
sub.text(x=0.07,y=0.048, s=r'$\theta_{\rm osc}$')
sub.text(x=0.03,y=0.006, s=r'$\theta_{\rm peak}$',rotation=20)
sub.text(x=0.12,y=-0.02,
s=r'$f_{a}=10^{16}~{\rm GeV}$'+'\n'+ r'$\theta_i = 10^{-1}$')
sub.text(x=0.028,y=0.09, s=r'EMD')
fig.savefig('theta_evolution-EMD.pdf',bbox_inches='tight')
fig.show()
if True:
fig=plt.figure(figsize=(9,4))
fig.subplots_adjust(bottom=0.15, left=0.15, top = 0.9, right=0.9,wspace=0.0,hspace=0.25)
sub = fig.add_subplot(1,1,1)
sub.plot(ax.T,ax.zeta,linestyle='-',linewidth=2,alpha=1,c='xkcd:black')
# sub.plot(ax.T_peak,ax.zeta_peak,linestyle=':',marker='+',color='xkcd:blue',linewidth=2)
sub.axvline(ax.T_osc,linestyle='--',color='xkcd:gray',linewidth=1.5)
#set major ticks
_M_xticks=[ round(0.025+i*0.025,4) for i in range(0,15) ]
_M_yticks=[ round(-0.15+i*0.05,3) for i in range(0,20,1) ]
#set major ticks that will not have a label
_M_xticks_exception=[]
_M_yticks_exception=[]
_m_xticks=[]
_m_yticks=[]
ft=FT(_M_xticks,_M_yticks,
_M_xticks_exception,_M_yticks_exception,
_m_xticks,_m_yticks,
xmin=0.025,xmax=0.15,ymin=-0.16,ymax=0.16,xscale='linear',yscale='linear')
ft.format_ticks(plt,sub)
sub.text(x=0.055,y=0.1, s=r'$T_{\rm osc}$',rotation=90)
sub.text(x=0.12,y=-0.15,
s=r'$f_{a}=10^{16}~{\rm GeV}$'+'\n'+ r'$\theta_i = 10^{-1}$')
# fig.savefig('zeta_evolution-EMD.pdf',bbox_inches='tight')-EMD
fig.show()
if True:
fig=plt.figure(figsize=(9,4))
fig.subplots_adjust(bottom=0.15, left=0.15, top = 0.9, right=0.9,wspace=0.0,hspace=0.25)
sub = fig.add_subplot(1,1,1)
sub.plot(ax.T,np.abs(ax.dtheta/ax.theta),linestyle='-',linewidth=2,alpha=1,c='xkcd:black',label=r'$\dfrac{\delta \theta}{\theta}$')
sub.plot(ax.T,np.abs(ax.dzeta/ax.zeta),linestyle='-',linewidth=2,alpha=1,c='xkcd:red',label=r'$\dfrac{\delta \zeta}{\zeta}$')
sub.set_xlabel(r'$T ~[{\rm GeV}]$')
sub.xaxis.set_label_coords(0.5, -0.1)
sub.set_ylabel(r'local errors')
sub.yaxis.set_label_coords(-0.1,0.5)
sub.legend(bbox_to_anchor=(0.98, 0.7),borderaxespad=0.,
borderpad=0.05,ncol=1,loc='upper right',fontsize=14,framealpha=0)
sub.axvline(ax.T_osc,linestyle='--',color='xkcd:gray',linewidth=1.5)
#set major ticks
_M_xticks=[ round(0.025+i*0.025,4) for i in range(0,15) ]
_M_yticks=[ 10.**i for i in range(-12,5,1) ]
#set major ticks that will not have a label
_M_xticks_exception=[]
_M_yticks_exception=[]
_m_xticks=[]
_m_yticks=[]
ft=FT(_M_xticks,_M_yticks,
_M_xticks_exception,_M_yticks_exception,
_m_xticks,_m_yticks,
xmin=0.025,xmax=0.15,ymin=1e-12,ymax=1e-6,xscale='linear',yscale='log')
ft.format_ticks(plt,sub)
sub.text(x=0.055,y=1e-7, s=r'$T_{\rm osc}$',rotation=90)
fig.savefig('local_errors-EMD.pdf',bbox_inches='tight')
fig.show()
if True:
fig=plt.figure(figsize=(9,4))
fig.subplots_adjust(bottom=0.15, left=0.15, top = 0.9, right=0.9,wspace=0.0,hspace=0.25)
sub = fig.add_subplot(1,1,1)
sub.hist(ax.T,bins=np.linspace(ax.T[-1],0.15,30),color='xkcd:blue',histtype='step')
sub.set_xlabel(r'$T ~[{\rm GeV}]$')
sub.xaxis.set_label_coords(0.5, -0.1)
sub.set_ylabel(r'Number of steps')
sub.yaxis.set_label_coords(-0.1,0.5)
sub.axvline(ax.T_osc,linestyle='--',color='xkcd:gray',linewidth=1.5)
#set major ticks
_M_xticks=[ round(0.025+i*0.025,4) for i in range(0,15) ]
_M_yticks=[ 10.**i for i in range(-12,5,1) ]
#set major ticks that will not have a label
_M_xticks_exception=[]
_M_yticks_exception=[]
_m_xticks=[]
_m_yticks=[]
ft=FT(_M_xticks,_M_yticks,
_M_xticks_exception,_M_yticks_exception,
_m_xticks,_m_yticks,
xmin=0.025,xmax=0.15,ymin=1e0,ymax=1e4,xscale='linear',yscale='log')
ft.format_ticks(plt,sub)
sub.text(x=0.055,y=1e3, s=r'$T_{\rm osc}$',rotation=90)
fig.savefig('histogram-EMD.pdf',bbox_inches='tight')
fig.show()
if True:
fig=plt.figure(figsize=(9,4))
fig.subplots_adjust(bottom=0.15, left=0.15, top = 0.9, right=0.9,wspace=0.0,hspace=0.25)
sub = fig.add_subplot(1,1,1)
sub.plot(ax.T,ax.rho_axion/rho_crit,linestyle='-',linewidth=2,alpha=1,c='xkcd:black')
sub.plot(ax.T_peak,ax.rho_axion_peak/rho_crit,linestyle=':',linewidth=2,alpha=1,c='xkcd:blue')
sub.set_xlabel(r'$T ~[{\rm GeV}]$')
sub.xaxis.set_label_coords(0.5, -0.1)
sub.set_ylabel(r'$\dfrac{\rho_{a}(T)}{\rho_{\rm crit}}$')
sub.yaxis.set_label_coords(-0.1,0.5)
sub.axvline(ax.T_osc,linestyle='--',color='xkcd:gray',linewidth=1.5)
#set major ticks
_M_xticks=[ round(0.025+i*0.025,4) for i in range(0,15) ]
_M_yticks=[ 10.**i for i in range(32,42,1) ]
#set major ticks that will not have a label
_M_xticks_exception=[]
_M_yticks_exception=[]
_m_xticks=[]
_m_yticks=[]
ft=FT(_M_xticks,_M_yticks,
_M_xticks_exception,_M_yticks_exception,
_m_xticks,_m_yticks,
xmin=0.025,xmax=0.15,ymin=1e36,ymax=1e40,xscale='linear',yscale='log')
ft.format_ticks(plt,sub)
sub.text(x=0.055,y=1e38, s=r'$T_{\rm osc}$',rotation=90)
sub.text(x=0.12,y=1.2e36,
s=r'$f_{a}=10^{16}~{\rm GeV}$'+'\n'+ r'$\theta_i = 10^{-1}$')
# fig.savefig('axion_energy_density-EMD.pdf',bbox_inches='tight')
fig.show()
if True:
fig=plt.figure(figsize=(9,4))
fig.subplots_adjust(bottom=0.15, left=0.15, top = 0.9, right=0.9,wspace=0.0,hspace=0.25)
sub = fig.add_subplot(1,1,1)
Delta=[1]
for i,_ in enumerate(ax.T[1:]):
sc1=relative_tolerance * max([np.abs(ax.theta[i]),np.abs(ax.theta[i-1])]) + absolute_tolerance
sc2=relative_tolerance * max([np.abs(ax.zeta[i]),np.abs(ax.zeta[i-1])]) + absolute_tolerance
Delta.append( np.sqrt(0.5*((ax.dtheta[i]/sc1)**2 + (ax.dzeta[i]/sc2)**2)) )
Delta=np.array(Delta)
sub.plot(ax.T,Delta,linestyle='-',linewidth=2,alpha=1,c='xkcd:black')
sub.set_yscale('log')
sub.set_xscale('linear')
sub.set_xlabel(r'$T ~[{\rm GeV}]$')
sub.xaxis.set_label_coords(0.5, -0.1)
sub.set_ylabel(r'$\Delta$')
sub.yaxis.set_label_coords(-0.1,0.5)
sub.axvline(ax.T_osc,linestyle='--',color='xkcd:gray',linewidth=1.5)
#set major ticks
_M_xticks=[ round(0.025+i*0.025,4) for i in range(0,15) ]
_M_yticks=[ round(0+i*0.2,2) for i in range(0,15) ]
#set major ticks that will not have a label
_M_xticks_exception=[]
_M_yticks_exception=[]
_m_xticks=[]
_m_yticks=[]
ft=FT(_M_xticks,_M_yticks,
_M_xticks_exception,_M_yticks_exception,
_m_xticks,_m_yticks,
xmin=0.025,xmax=0.15,ymin=0,ymax=1.02,xscale='linear',yscale='linear')
ft.format_ticks(plt,sub)
sub.text(x=0.055,y=1e-6, s=r'$T_{\rm osc}$',rotation=90)
# fig.savefig('Delta-EMD.pdf',bbox_inches='tight')
fig.show()
#run the destructor
del ax
```
| github_jupyter |
# TensorFlow by example
https://github.com/INM-6/Python-Module-of-the-Week
```
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
plt.xkcd()
# In case there are font warnings:
# https://github.com/ipython/xkcd-font/blob/master/xkcd/build/xkcd.otf
# Fixing the seeds to prevent things from breaking unexpectedly...
np.random.seed(42)
tf.set_random_seed(42)
```
## Part 1: A toy example
### Setup
Let's consider a toy 'neural network' consisting of two 'neurons' that map an input $x$ to an output $z$:
$$
y = f(w_1 x + b_1)
$$
$$
z = f(w_2 y + b_2)
$$
Here, $y$ is a vector (i.e. we have many 'hidden neurons'):
<img src="img/sketch.png" alt="sketch" width="200" align="middle"/>
For the nonlinearity, we use a sigmoid:
$$f(x) = 1 / (1 + e^{-x})$$
We want out network to approximate an arbitrary function $t(x)$. In principle, the above network should be able to do this with any precision according to the [universal approximation theorem](http://neuralnetworksanddeeplearning.com/chap4.html) - if we use enough hidden neurons.
For the loss, we use a simple quadratic loss:
$$L = [z - t(x)]^2$$
### Computational Graph
In TensorFlow, we have to define the *computational graph* before doing any calculations. For our setup, we have this graph (created using TensorBoard):
<img src="img/graph.png" alt="drawing" width="700" align="middle"/>
Disclaimer: With [eager execution](https://www.tensorflow.org/tutorials/eager/eager_basics) the above is not strictly true anymore.
### TensorFlow implementation
```
num_hidden = 5 # number of hidden neurons
x_linspace = np.linspace(0, 1, 100) # some input values
# A placeholder for the input (batch size unknown)
x = tf.placeholder(tf.float32, [None, 1], name='x')
# Our hidden neurons
w1 = tf.Variable(tf.random_normal([1, num_hidden], stddev=.1), name='w1')
b1 = tf.Variable(tf.random_normal([num_hidden], stddev=.1), name='b1')
y = tf.sigmoid(tf.add(tf.matmul(x, w1), b1))
# The output neuron
w2 = tf.Variable(tf.random_normal([num_hidden, 1], stddev=.1), name='w2')
b2 = tf.Variable(tf.random_normal([1], stddev=.1), name='b2')
z = tf.sigmoid(tf.add(tf.matmul(y, w2), b2))
# Execute the graph
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
z_out = sess.run(z, feed_dict={x: x_linspace[:, np.newaxis]})
```
### Let's have a look
```
def target_funct(x):
return 4*(x - 0.5)**2 # our target function
# return 0.5*np.sin(4*np.pi*x) + 0.5 # another target function
# Plot network output against target function
plt.plot(x_linspace, z_out, label='NETWORK')
plt.plot(x_linspace, target_funct(x_linspace), label='TARGET')
plt.legend()
```
### Backprop
Now we want to optimize. To do so, we need the derivatives of the loss $L = [z - t(x)]^2$ wrt. the parameters $w_1, b_1, w_2, b_2$. Let's start with the bias of our output neuron $z = f(w_2 y + b_2)$:
$$
\frac{dL}{db_2} = \frac{\partial L}{\partial z}\frac{dz}{db_2} = \frac{\partial L}{\partial z} f^\prime(w_2 y + b_2)
$$
with $\frac{\partial L}{\partial z} = 2[z - t(x)]$. From the forward pass we know $y$ and $z$ so the expression can be evaluated. Now the weights:
$$
\frac{dL}{dw_2} = \frac{\partial L}{\partial z}\frac{dz}{dw_2} = \frac{dL}{db_2} y
$$
Neat - we don't need to compute anything here because we know $\frac{dL}{db_2}$ already! Finally:
$$
\frac{dL}{db_1} = \frac{\partial L}{\partial z}\frac{\partial z}{\partial y}\frac{dy}{db_1} = \frac{dL}{db_2} w_2f^\prime(w_1 x + b_1)
$$
$$
\frac{dL}{dw_1} = \frac{\partial L}{\partial z}\frac{\partial z}{\partial y}\frac{dy}{dw_1} = \frac{dL}{db_1} x
$$
Of course with more layers we could play this game ad infinitum. The nice part here is that many operations can be parallelized.
### Optimization
That's all there is - backprop is just the chain rule and a clever strategy to compute it. A few notes:
* The name is pretty obvious: We go backwards along the computational graph here.
* We see a problem on the horizon: Any vanishing term in the products above make them vanish entirely,
* e.g. when $f^\prime(\dots) \approx 0$ for the saturated sigmoid -> ReLu's, ELU's ...
* e.g. when the weights are initialized too small or too big -> Xavier init, ...
* The main purpose (afaik) of TensorFlow is to automate the calculation of the derivatives and distribute them optimally.
The dénouement is the update of the parameters along the gradient, e.g.
$$
w_1 = w_1 - \lambda \frac{dL}{dw_1}
$$
where $\lambda$ is the learning rate. Of course, there plenty of better schemes than this vanilla gradient descent. Again, a few notes:
* The loss function is not convex, i.e. there are in most cases plenty of local optima / saddle points
* Because it is non-convex, a simple gradient descent would get stuck in a local minimum -> SGD, Adam, ...
* The learning rate is crucial: If it is too large you get lost (could even diverge), if it is too small you never arrive -> [Grad Student Descent](https://www.reddit.com/r/MachineLearning/comments/6hso7g/d_how_do_people_come_up_with_all_these_crazy_deep/)
### Training the model
```
learning_rate = 1e-2 # learning rate
epochs = int(3e3) # number of epochs
batch_size = 128 # batch size
# target and loss
target = tf.placeholder(tf.float32, [None, 1], name='target')
loss = tf.reduce_mean(tf.square(z - target))
# optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
loss_storage = np.empty(epochs)
# iterate 'epochs'
for epoch in range(epochs):
# generate samples
batch_x = np.random.rand(batch_size)
batch_target = target_funct(batch_x)
# calculate loss and execute train_op
_, loss_storage[epoch] = sess.run(
[train_op, loss], feed_dict={
x: batch_x[:, np.newaxis],
target: batch_target[:, np.newaxis]})
# generate prediction
z_out = sess.run(z, feed_dict={x: x_linspace[:, np.newaxis]})
```
### Loss
```
plt.plot(loss_storage, label='LOSS')
plt.legend(loc=0)
```
### Let's have a look
```
plt.plot(x_linspace, z_out, label='NETWORK')
plt.plot(x_linspace, target_funct(x_linspace), label='TARGET')
plt.legend(loc=0)
```
## Part 2: MNIST - what else?
```
# clear the tensorflow graph
tf.reset_default_graph()
```
### Setup
Essentially, we use the same architecture as above. Differences:
* $28 \times 28 = 784$ inputs instead of a single one
* $10$ output neurons for the ten digits
* $300$ hidden neurons
* `relu` (hidden) and `softmax` (output) nonlinearity
* We use another optimizer
* We use another loss function (cross entropy)
Basically this is a concise code-only example without all the annoying text.
Let's start by getting the data:
```
# tensorflow.examples.tutorials.mnist is deprecated
# Because it is useful we just suppress the warnings...
old_tf_verbosity = tf.logging.get_verbosity()
tf.logging.set_verbosity(tf.logging.ERROR)
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# ... and restore the warnings again
tf.logging.set_verbosity(old_tf_verbosity)
```
### Building the model
```
# input placeholder - for 28 x 28 pixels = 784
x = tf.placeholder(tf.float32, [None, 784])
# label placeholder - 10 digits
y = tf.placeholder(tf.float32, [None, 10])
# hidden layer
w1 = tf.Variable(tf.random_normal([784, 300], stddev=0.03), name='w1')
b1 = tf.Variable(tf.random_normal([300]), name='b1')
hidden_out = tf.nn.relu(tf.add(tf.matmul(x, w1), b1))
# output layer
w2 = tf.Variable(tf.random_normal([300, 10], stddev=0.03), name='w2')
b2 = tf.Variable(tf.random_normal([10]), name='b2')
y_ = tf.nn.softmax(tf.add(tf.matmul(hidden_out, w2), b2))
```
### Setting up the optimization
```
learning_rate = 0.5
# loss function
y_clipped = tf.clip_by_value(y_, 1e-10, 0.9999999) # needed for logarithm
cross_entropy = -tf.reduce_mean(tf.reduce_sum(
y * tf.log(y_clipped) + (1 - y) * tf.log(1 - y_clipped), axis=1))
# optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(cross_entropy)
# accuracy
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
```
### Running it
```
epochs = 10
batch_size = 128
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
total_batch = int(len(mnist.train.labels) / batch_size)
loss_storage = np.empty(epochs)
for epoch in range(epochs):
avg_loss = 0.
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size=batch_size)
_, batch_loss = sess.run([train_op, cross_entropy],
feed_dict={x: batch_x, y: batch_y})
avg_loss += batch_loss / total_batch
loss_storage[epoch] = avg_loss
final_acc = sess.run(accuracy, feed_dict={
x: mnist.test.images, y: mnist.test.labels})
```
### Let's have a look
```
plt.plot(loss_storage, label='LOSS')
plt.legend(loc=0)
print("Final accuracy: {:.1f}%".format(100*final_acc))
```
## References
* Strongly influenced by this [Python TensorFlow Tutorial](http://adventuresinmachinelearning.com/python-tensorflow-tutorial/)
* [A high-bias, low-variance introduction to Machine Learning for physicists](https://arxiv.org/abs/1803.08823)
* The [CS231n](http://cs231n.github.io) Stanford class
* The [Neural Networks and Deep Learning](http://www.neuralnetworksanddeeplearning.com) online book
| github_jupyter |
# Crawling Twitter in Python
by
[__Michael Granitzer__ (michael.granitzer@uni-passau.de)]( http://www.mendeley.com/profiles/michael-granitzer/)
<p>
<p>
<br>
__Licences__
<br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" align="left"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png" /></a>
# RESTful API's
RESTful API's (REST = Representational state transfer) are the most dominant API's in the web. We will briefly review the underlying technology, namely:
- HTTP as protocol
- JSON as return format
- OAuth as authentication method
## HTTP in a nutshell
<div class="alert alert-warning">
The **HyperText Transfer Protocol** is an generic, stateless, request-response (pull) application protocol for distributed and collaborative hypermedia information systems (Fielding et. al. 99)
</div>
Current Version is HTTP/1.1
### Format
**Request-Format**
- Request line (e.g. `GET /index.html HTTP/1.1`)
- Request header fields as `Key: Value1, Value2 ...` line (e.g. `Accept-Language:en`)
- empty line
- Optional message body
**Response-Format**
- Status line with status code and reason message (e.g. `HTTP/1.1 200 OK`)
- Response header fields `Key: Value1, Value2 ...` line (e.g. `Content-Type:text/html`)
- empty line
- Optional message body
*Header Examples*
|Key | Description|
|------|-|
|Accept | Content type accepted as response|
|Authorization | Credentials for authentication|
|Content-Type| The MIME Type of the Body|
|User-Agent| a string identfiying the user agent|
**Status Codes**
|Code-Group| Description|
|----------|------------|
| 1xx | Informational|
| 2xx | Success|
| 3xx | Redirection|
| 4xx | Client Error|
| 5xx | Server Error |
Details@[Iana](http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml)
### Request Methods
HTTP addresses a resource via an URL (host+file part) and can apply several [methods](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html), also known as verbs, to this resource.
** Safe Methods:** Methods do not change the resource. They only retrieve information.
- `GET` - retrieve the resource or parts of the resource
- `HEAD` - identical response to a GET resource but without body
- `OPTIONS` - returns the HTTP methods supported by the server
- `TRACE` - echos back the received request to see probable changes or additions made by intermediate servers
Only `GET` and `HEAD` are available in version HTTP/1.0
**Idempotent Methods:** multiple identical requests have the same effect on a single resource. The system is in the same state after multiple identical requests have been made.
- `PUT` - Stores a resource under the supplied URI
- `DELETE` - Deletes the specified resource
**Non-Idempotent Methods:** Sending two identical requests are allowed produce different results.
- `POST` - Post the entity encludes in the request to the resource
### MIME Types
Multipurpose Internet Mail Extension Types (MIME Types) are used describing the type of media returned.
A media type (e.g. `text/html;charset=UTF-8`) is composed of
- a top-level type (e.g. `text`)
- a sub-type (e.g. `html`)
- zero or more optional parameters (e.g. `charset=UTF-8`)
**top-level type names** are `application, audio, example, image, message, model, multipart, text, video`
**sub-types** are composed as `{|vnd.|prs.|x.}subtype-name[+suffix]`
- `{|vnd.|prs.|x.}` refers to different sub-trees, namely the standard tree, the vendor tree `vnd.`, the personal (experimental) tree `prs.`, the `x.` (private) tree.
- `[+suffix]` referes to an optional structure specification of the media type, namely `+xml, +json, +ber, +der, +fastinfoset, +wbxml, +zip, +cbor`
**Example**: `'application/vnd.mozilla.xul+xml'`
All types are listed at [IANA](http://www.iana.org/assignments/media-types/media-types.xhtml)
### HTTP Example
telnet www.uni-passau.de 80
Trying 132.231.51.59...
Connected to www.uni-passau.de.
Escape character is '^]'.
GET / HTTP/1.1
HTTP/1.1 302 Found
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: PHP/5.3.10-1ubuntu3.14
Location: http://www.uni-passau.de/404fehlerseite/
Vary: Accept-Encoding
Cache-Control: max-age=3600
Expires: Sun, 12 Oct 2014 15:37:00 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Date: Sun, 12 Oct 2014 14:37:00 GMT
X-Varnish: 1997371000
Age: 0
Via: 1.1 varnish
Connection: keep-alive
## REST Architecture in a nutshell
<div class="alert alert-warning">
**Representational state transfer (REST)** describes an architectural style of a distributed hypermedia information system like the WWW. Its basic properties are:
<br>
<ul>
<li> Scalability
<li> Performance
<li> Simplicity
<li> Reliability
<li> Modifiability
<li> Portability
</ul>
</div>
It has been developed by Roy Fielding in his PhD thesis at UC Irvine in 2000.
### Architectural constraints
- **Client-Server Model:** The client is separated from the server through a uniform interface (separation of concerns)
- **Uniformed Interface:** REST defines four interface constraints:
- Identification of resources (in the Web through URIs) in requests, decoupled from the return results (e.g. XML, JSON, HTML)
- Manipulation of resources through returned representation
- Self-descriptive messages
- Hypermedia as the engine of application state (HATEOAS). Given a fixed entry point, the server returns potential state transitions to the client. The client must not make any assumptions besides that
- **Stateless:** Client context must not be stored on the server. Every client request contains all information necessary
- **Cacheable:** Clients can cache responses, if a response is defined so.
- **Layered System:** Clients can connect to intermediate/proxy servers.
- **Code on demand (optional):** Servers may transfer executable code to the client.
### REST over HTTP
REST over HTTP consists of:
- an **URI** representing the resource
- an **Internet Media Type (MIME Type)** indicating the format of the data/resource.
- **HTTP Methods:** Put, Get, Post Delete
- **Hyperlinks** indicating server **state transitions** (HATEOAS)
- **Hyperlinks** to reference **related resources**
|Resource|Get | Put | Delete |Post|
|--------|----|-----|--------|----|
|Collection URI|List URIs in Collection| Replace entire collection|Delete collection| Create new entry|
|Element URI|Get representation of URI|Replace or Create element| delete element|Not generally used. Treat element as collection and create new entry|
## JSON in a nutshell
<div class ="alert alert-warning" align="centred"> "JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language" [1]
</div>
[1]:http://json.org/
JSON builds on two structures that can be mixed with each other:
- A collection of key/value pairs (e.g. a dictionary in Python)
- Format: `{Key1: Value, ...., KeyN: Value}`
- An ordered list of values (e.g. a list in Python)
- Format: `[Value1, ...., ValueM]`
It improves readability and is easier to parse in JavaScript than XML.
**Example:**
{ "FirstName" : "Michael",
"LastName" : "Granitzer",
"Courses" : [{"Name" : "Web Mining", "ID" :1234},
{"Name" : "Data Mining", "ID" :1235}]
}
## OAuth in a nutshell
<div class="alert alert-warning">
"An open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications." [1]
</div>
[1]: http://oauth.net/
Latest version is OAuth 2.0, which enables a third-party application to obtain limited access to an HTTTP Service.
For the user there is no need to share credentials with a consumer application (e.g. e-Learning System) that consumes user-authenticated web services (e.g. Twitter for posting tweets through the e-Learning System)
**Example:** "Login via Google"
### A Brief Overview on the Protocol
We will take a very brief look on the OAuth protocol, Version 2.0. This is by no means exhaustive, but should be sufficient for our purpose of web mining.
For details on the protocol please see the corresponding [standard](https://tools.ietf.org/html/draft-ietf-oauth-v2-31).
For a fast introduction see [this tutorial](http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified) (which has been used as basis for the description here)
#### Roles
- **Client:** The third party application attempting to get access to a user's account on the resource server
- **Resource-Server: The API ** that the Client wants to access on the behalf of the user
- **Resource Owner: The User** who is the person who is giving access to some propotion of the services the user is allowed to use on the resource server
#### Preliminaries: Application-based access
- **Registering an Application:** The OAuth process requires the **Client** to register an **application** at the **resource-server**.
- **Redirect URI:** It is an URI that will be called when a user registers at the **client** and must be registered with the **application** on the **resource-server**.
- **Client ID and Secret:** They form the credentials for your application. The client ID represents public information and is used to build the login URLs. The client secret must be kept confidential, since it represents the authorization token for an app.
#### Authorization for Web Server based Clients
For Web Server based Clients, the following OAuth dance is performed:
<img src="files/images/OAuth.svg"/>
**Example:**
1. Redirect User to Resource Server for Login
https://resource-server.com/auth?response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&scope=photos
2. resource server answers with user prompt to get access for the registered app
3. On acceptance, the user is redirected to `REDIRECT_URI` with an auth code:
https://client.com/cb?code=AUTH_CODE_HERE
4. The resource server exchanges the Auth Code for an access token:
<pre><code>
POST https://api.oauth2server.com/token
grant_type=authorization_code&
code=AUTH_CODE_HERE&
redirect_uri=REDIRECT_URI&
client_id=CLIENT_ID&
client_secret=CLIENT_SECRET
</pre></code>
Server-replies the access token which has to be used in further calls:
<pre><code>
{
"access_token":"RsT5OjbzRn430zqMLgV3Ia"
}
</pre></code>
5. Making authenticated requests via `Authorization` HTTP Header field (use HTTPS to keep the token secure!)
<pre><code>
Authorization: Bearer RsT5OjbzRn430zqMLgV3Ia
</pre></code>
**Other Request Types**
- **Password:** Allows to exchange the access token with the real user/password. Used for Clients from the same vendor like the resource server (e.g. Twitter Native App)
- **Application Access:** Change the applications registry information without any user context
#### Differences to OAuth V 1.0
- **Simplicity:** reduced requirements on signing requests/cryptographic signatures
- **User Experience:** Better user experience for native applications
- **Performance:** Separation of client ID/authorization code and access token enhances scalability for resources servers.
## HTTP Requests in Python: The `requests` Package
Although the Python Standard Library comes with the http-client library called [`urllib2`](https://docs.python.org/2/library/urllib2.html), the API is hard to use.
The `requests` module provides an easy and handy API to send http requests over the network.
This section briefly summarizes the most important calls with `requests`. For details see the [documentation](http://docs.python-requests.org/en/latest/).
### Installation
In the following you find an install procedure working within the notebook (respectively after restart). Usefull links for installing modules and managing packages can be found here:
- [Python Setup Tools](https://pypi.python.org/pypi/setuptools):
Softwaremanagers are `easy_install` or `pip`
- [Installing Python Modules](https://docs.python.org/2/install/index.html):
Standard command after downloading the source `python setup.py install`
```
def installed():
try:
import requests
return True
except ImportError as ie:
return False
print installed()
#note we execute a shell command called pip (using !), which comes with python setuptools.
#we install it to the users site with --user in order to avoid any rights issues
if not installed():
!easy_install --user requests
if not installed(): #we might not have pip installed. so install it from source locally
import tempfile
td = tempfile.tempdir
!cd $td
!git clone git://github.com/kennethreitz/requests.git
!cd requests.git
!python setup.py install --user
```
### Usage
A brief example (based on the [requests documentation](http://docs.python-requests.org/en/latest/user/quickstart/)):
```
import requests
r = requests.get('http://en.wikipedia.org/w/api.php')
print "Status of request (200=success): %d"%r.status_code
print "HTTP Headers %s"%str(r.headers['content-type'])
print "Encoding %s"% r.encoding
print "Returned text %s"%r.text.encode(r.encoding)[0:100]
```
#### The request object
The request is the main source of invoking http requst. For every request method (the verbs), a separate function exist.
```
r = requests.post("http://httpbin.org/post")
r = requests.put("http://httpbin.org/put")
r = requests.delete("http://httpbin.org/delete")
r = requests.head("http://httpbin.org/get")
r = requests.options("http://httpbin.org/get")
```
#### Passing Parameters
Parameters are passed as dictionary object.
```
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
print(r.url)
```
#### Response Content
Response automatically decode content from the server by guessing/estimating the encoding. The content can be accessed under the `'text'` field. After changing the encoding through setting `'encoding'` subsquent access to `'text'` provides the new encoding.
```
r = requests.get('https://api.github.com/events')
r.text[1:1000]
print "The encoding of the response is", r.encoding
```
#### Binary Response Content
The binary content can be accessed under the field `'content'`. `gzip` and `deflate` transfer-encodings are automatically decoded.
```
c = r.content
print type(c), ": ", c[:1000]
```
#### JSON Response Content
JSON is returned via `requests.json`
```
print type(r.json())
#pretty print the json using json.dumps
print json.dumps(r.json(), indent = 4)
```
### Custom Headers
You can set custom headers simply via `dict` objects containing the header parameter
```
import json
url = 'https://api.github.com/events'
#add some additional payload, i.e. post parameters
payload = {'some': 'data'}
#set custom headers here
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
#pretty print the json this time
print json.dumps(r.json(), sort_keys=True, indent=4)
```
### Response Headers
We can view the server's response header:
```
r.headers
```
## Exercise I: OAuth Authentication with Twitter
Details see "Exercises Folder", "Exercise I" in "Exercise Twitter with Python" ([local](exercises/Exercises%20Crawling%20Twitter%20with%20Python.ipynb)|[online](http://nbviewer.ipython.org/urls/raw.github.com/mgrani/LODA-lecture-notes-on-data-analysis/master/V.Web-Mining-Applications/exercises/Exercises%20Crawling%20Twitter%20with%20Python.ipynb))
# Twitter
<div class="alert alert-warning">
Twitter is an online social networking services where users can send and read 140-character messages called tweets. It can be compared to a mobile phone Short Message Service (SMS) for the internet.
</div>
## Conceptual Model
- A **twitter user** creates Tweets, 140 character long messages
- **Tweets** are public on default, but can be protected.
- **Private Messages** are allowed between users.
- **Retweeting** refers to the process of forwarding a tweet through another Twitter user.
- **Following** refers to the process of one twitter user following the tweets of another twitter users. It can be seen as a filtering tweets on a per user basis or subscribing to another users tweets. Mutual following is often considered as indicator for friendship, but there is no explicit way of stating friendship.
- **Tweet Metadata** refers to metadata associated with a tweet, like for example the authors location.
- **Tweet Special Characters:** Due to the limited amount of characters, certain "special" characters have been introduced by the community. Technically they are treated as characters, but add meaning for users:
- `@` followed by a username is used for mentioning or replying to the named user
- `#` followed by a word indicates a topic description
<img src="files/images/twitter-example.png"/>
## API
All Twitter functionality and data relating to the conceptual models are provided via the API. We will take a brief look at the API and its possibilities. This also clarifies the details of the conceptual Twitter model.
There are different APIs/Tools on Twitter:
- **Fabric** - a mobile app development kit to include Twitter functionality.
- **Twitter for Websites** - a set of embeddable widgets, buttons etc. to integrate Twitter in a website
- **Cards** - allow to display additional content alongside a Tweet (e.g. Photos, Videos, summary HTML pages)
- **OAuth** - endpoints for authentication on behalf of a user or on behalf of an application
- **REST API** - read and write access to Twitter data.
- **Streaming API** - deliver a stream of update to REST API queries over a long lived HTTP connection
- **Ads API** - Allows to integrate Twitter advertising management.
We will focus on the REST API and here only on *reading* Twitter data.
### REST API V1.1
- Standard Rest Calls
- Authentication either with user context or without (application-only)
- Details under https://dev.twitter.com/rest/public
**Searching Twitter**
- URL: https://api.twitter.com/1.1/search/tweets.json
- Method: Get
- Parameters:
- `q=<Query>` where `Query` is an url encoded query similar to using the standard Twitter search. Operators are:
- `word1 word2` - standard is and search
- `"word1 word2"` - phrases search with "
- `word1 OR word2` - OR search
- `word1 -word2` - not containing a word through `-`
- `#hashtag` - searches for a hash tag
- `from:User1` - tweet posted by User1
- `to:User1` - tweet send to User1
- more like positive/negative attitude, date ranges, asking questsions, type of feeds etc.
- *Result Type:* choose between recent or popular tweets
- *Geolocation:* restrict query by location
- *Language:* language of a tweet
- *Iterating in a result set:* through count, until, since, max
- Rate limit:
- 180 requests per 15 minutes for a user context
- 450 queries per 15 minutes
- Details for rate limits: https://dev.twitter.com/rest/public/rate-limits
**Get Requests which are interesting for Mining Twitter**
`GET` requests return resources of interest, while `POST` requests update/manipulate the resources. Hence, we only look into `GET` requests for now.
*Some Details*
- prefix: https://api.twitter.com/1.1/
- Documentation: https://dev.twitter.com/rest/public
*Requests*
|Request|Description|
|-------|-----------|
|statuses/user_timeline.json | returns most recent tweets posted by a user|
|statuses/home_timeline.json | returns the most recent Tweets and Retweets posted by a user and the his/her followed users|
|statuses/retweets\*|a collection of functions for accessing retweets|
|statuses/show/:id|Returns the details of a single Tweet including information on the Tweet Author|
|friends/ids| Returns the users the specified user is following|
|followers/ids| Returns the followers of a specified user|
|friendships/\*| Returns incoming and outgoing pending follow requests|
|users/search|search public user accounts on Twitter|
|users/show|returns the details of a user|
|lists/\*|a collection of list realted functions|
|geo/\*|a collection of geo related functions|
**Working with Timelines**
Due to the real-time characteristic of Twitter, working with timelines is not so easy (see https://dev.twitter.com/rest/public/timelines)
Paging does not work due to the arrival of new Tweets during processing:
<img src="files/images/twitter-paging-problem.png"\>
(Image-Source: Twitter)
**Solution using `max_id`**
Work not relative to the static ordered list of tweets (page 0, count 5), but to the tweets processed.
Procedure:
1. Call Twitter with the `count` parameter for retrieving `count` number of tweets.
2. Subsequent calls use the `max_id` parameter and set it to the lowest retrieved tweet id (Note: `max_id` is inclusive).
3. Twitter returns all Tweets with ids lower than `max_id`
<img src="files/images/twitter-paging-max_id.png"/>
(Image Source Twitter)
**Solution using `since_id`**
For timelines efficient processing of newly arrived tweets can be done using the `since_id` parameter.
`since_id` returns all tweets that arrived since the Tweet specified with `since_id`. Note that `since_id` is exclusive.
`max_id` would be too inefficent:
<img src="files/images/twitter-maxid-problem.png"/>
(Image Source Twitter)
So we combine `since_id` and `max_id`.
<img src="files/images/twitter-paging-since_id.png"\>
(Image source Twitter)
### Tweet Metadata
A nice summary of what metadata is available to a tweet has been given by Raffi Krikorian.
http://online.wsj.com/public/resources/documents/TweetMetadata.pdf
Roughly tweets include
- Tweet information like text, entities, polarity, mentioned geo locations, hash tags, creation date
- Author information like creation date, profile, location of the user
## The Python Twitter Module for accessing the API
There is a [`twitter`](https://pypi.python.org/pypi/twitter) module (Version 1.15) that warps the Twitter API and provides convenience function for accessing twitter. Be careful which version you use (API might change).
### Installing the Python Twitter Module
```
def installed_twitter():
try:
import twitter
return True
except ImportError as ie:
return False
#note we execute a shell command called pip, which comes with python setuptools.
#we install it to the users site with --user in order to avoid any rights issues
if not installed_twitter():
print "Twitter module is not installed. Continuing with pip and installing it to current user."
!pip install twitter --user
if not installed_twitter(): #we might not have pip installed. so install it from source locally
print "Pip installation failed. Trying to build from source"
import tempfile
td = tempfile.tempdir
!cd $td
!git clone git://github.com/bear/python-twitter.git
!cd python-twitter
!python setup.py install --user
if installed_twitter():
print "Twitter module is now installed. restart the kernal and use import twitter to access it."
else:
print "Buidling from source failed. Do manually"
```
### Some examples with the Twitter module
```
import twitter
help(twitter)
```
In principle, class members of the Twitter API class are getting translated to Twitter REST requests.
### Authentication First
The twitter module can do the OAuth dance using application keys/secret and user token/secret
```
import twitter
consumer_key = "IhrU9UwHys1IBnVXh2tLt5dDW"
consumer_secret ="H4kL6FHOJlZ0wiCHUhqD2u3FmRm2q8vKJRqoqCwJzEN5t9Fsfw" #the secret has been scrambled. Use your own.
token = "2843747566-333S6Hv9clIrvfb0Ne8FRpY5OuYFqLowrUJksmv"
token_secret = "DKZAFwKfc63SSf7XnyVVw8IyT0YtWQjOmh8YklfYL6OKu"
auth = twitter.oauth.OAuth(token, token_secret,
consumer_key, consumer_secret)
twitter_api = twitter.Twitter(auth = auth)
print twitter_api
```
### Getting timelines
```
# Get your "home" timeline
[t["text"] for t in twitter_api.statuses.home_timeline()]
# Get a particular friend's timeline
[t["text"] for t in twitter_api.statuses.user_timeline(screen_name="mgrani")]
# to pass in GET/POST parameters, such as `count`
[t["text"] for t in twitter_api.statuses.home_timeline(count=5)]
```
### User centric functions
```
#calling the followers which is a substitute for https://dev.twitter.com/rest/reference/get/followers/ids
twitter_api.followers.ids(screen_name="mgrani")
#examine the occuring exception to see how the call construction works.
#This is a perfect example for python magic overwriting the __call__ function of a library
twitter_api.url.path.none.exists.followers.ids(screen_name="mgrani")
```
### Accessing trends
```
# See https://dev.twitter.com/docs/api/1.1/get/trends/place and
# We define some ids based on the Yahoo Where On Earth ID
# Use http://woeid.rosselliot.co.nz/ for lookups
WORLD_WOE_ID = 1
GER_WOE_ID = 23424829
twitter_api.trends.place(_id=WORLD_WOE_ID)
twitter_api.trends.place(_id=GER_WOE_ID)
```
## Time to do Exercise II in Exercises - Crawling Twitter in Python
Go to the Exercise folder and conduct Exercise II in Exercises - Crawling Twitter in Python
# Literature
- **Matthew A. Russel, ["Mining the Social Web: Data Mining Facebook, Twitter, LinkedIn, Google+, GitHub, and More"](http://miningthesocialweb.com/), O'Reilly Media, 2013 **
- Fielding, Roy T.; Gettys, James; Mogul, Jeffrey C.; Nielsen, Henrik Frystyk; Masinter, Larry; Leach, Paul J.; Berners-Lee (June 1999). [Hypertext Transfer Protocol -- HTTP/1.1.](https://tools.ietf.org/html/rfc2616) IETF. RFC 2616.
- Fielding, Roy Thomas (2000). ["Architectural Styles and the Design of Network-based Software Architectures"](https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm). Dissertation. University of California, Irvine.
- D. Hardt, Ed. ["The OAuth 2.0 Authorization Framework, draft-ietf-oauth-v2-31"](https://tools.ietf.org/html/draft-ietf-oauth-v2-31) OAuth Working Group, Internet Draft, 2012
```
#Stuff for presentation
#loads section numbering https://github.com/ipython/ipython/wiki/Extensions-Index
%reload_ext secnum
%secnum
```
| github_jupyter |
```
import sys
sys.path.append(r'C:\Users\moallemie\EMAworkbench-master')
sys.path.append(r'C:\Users\moallemie\EM_analysis')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from ema_workbench import load_results, ema_logging
from ema_workbench.em_framework.salib_samplers import get_SALib_problem
from SALib.analyze import morris
# Set up number of scenarios, outcome of interest.
sc = 500 # Specify the number of scenarios where the convergence in the SA indices occures
t = 2100
top_factor = 5
outcome_var = 'Biomass Energy Production Indicator' # Specify the outcome of interest for SA ranking verification
```
## Loading experiments
```
ema_logging.log_to_stderr(ema_logging.INFO)
from Model_init import vensimModel
from ema_workbench import (TimeSeriesOutcome,
perform_experiments,
RealParameter,
CategoricalParameter,
ema_logging,
save_results,
load_results)
directory = 'C:/Users/moallemie/EM_analysis/Model/'
df_unc = pd.read_excel(directory+'ScenarioFramework.xlsx', sheet_name='Uncertainties')
df_unc['Min'] = df_unc['Min'] + df_unc['Reference'] * 0.75
df_unc['Max'] = df_unc['Max'] + df_unc['Reference'] * 1.25
# From the Scenario Framework (all uncertainties), filter only those top 20 sensitive uncertainties under each outcome
sa_dir='C:/Users/moallemie/EM_analysis/Data/'
mu_df = pd.read_csv(sa_dir+"MorrisIndices_{}_sc5000_t{}.csv".format(outcome_var, t))
mu_df.rename(columns={'Unnamed: 0': 'Uncertainty'}, inplace=True)
mu_df.sort_values(by=['mu_star'], ascending=False, inplace=True)
mu_df = mu_df.head(20)
mu_unc = mu_df['Uncertainty']
mu_unc_df = mu_unc.to_frame()
# Remove the rest of insensitive uncertainties from the Scenario Framework and update df_unc
keys = list(mu_unc_df.columns.values)
i1 = df_unc.set_index(keys).index
i2 = mu_unc_df.set_index(keys).index
df_unc2 = df_unc[i1.isin(i2)]
vensimModel.uncertainties = [RealParameter(row['Uncertainty'], row['Min'], row['Max']) for index, row in df_unc2.iterrows()]
df_out = pd.read_excel(directory+'ScenarioFramework.xlsx', sheet_name='Outcomes')
vensimModel.outcomes = [TimeSeriesOutcome(out) for out in df_out['Outcome']]
r_dir = 'D:/moallemie/EM_analysis/Data/'
results = load_results(r_dir+'SDG_experiments_ranking_verification_{}_sc{}.tar.gz'.format(outcome_var, sc))
experiments, outcomes = results
```
## Calculating SA (Morris) metrics
```
#Sobol indice calculation as a function of number of scenarios and time
def make_morris_df(scores, problem, outcome_var, sc, t):
scores_filtered = {k:scores[k] for k in ['mu_star','mu_star_conf','mu','sigma']}
Si_df = pd.DataFrame(scores_filtered, index=problem['names'])
sa_dir='C:/Users/moallemie/EM_analysis/Data/'
Si_df.to_csv(sa_dir+"MorrisIndices_verification_{}_sc{}_t{}.csv".format(outcome_var, sc, t))
Si_df.sort_values(by=['mu_star'], ascending=False, inplace=True)
Si_df = Si_df.head(20)
Si_df = Si_df.iloc[::-1]
indices = Si_df[['mu_star','mu']]
errors = Si_df[['mu_star_conf','sigma']]
return indices, errors
# Set the outcome variable, number of scenarios generated, and the timeslice you're interested in for SA
problem = get_SALib_problem(vensimModel.uncertainties)
X = experiments.iloc[:, :-3].values
Y = outcomes[outcome_var][:,-1]
scores = morris.analyze(problem, X, Y, print_to_console=False)
inds, errs = make_morris_df(scores, problem, outcome_var, sc, t)
```
## Plotting SA results
```
# define the ploting function
def plot_scores(inds, errs, outcome_var, sc):
sns.set_style('white')
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(3, 6))
ind = inds.iloc[:,0]
err = errs.iloc[:,0]
ind.plot.barh(xerr=err.values.T,ax=ax, color = ['#FCF6F5']*(20-top_factor)+['#C6B5ED']*top_factor,
ecolor='dimgray', capsize=2, width=.9)
ax.set_ylabel('')
ax.legend().set_visible(False)
ax.set_xlabel('mu_star index', fontsize=12)
ylabels = ax.get_yticklabels()
ylabels = [item.get_text()[:-10] for item in ylabels]
ax.set_yticklabels(ylabels, fontsize=12)
ax.set_title("Number of experiments (N): "+str(sc*21), fontsize=12)
plt.suptitle("{} in 2100".format(outcome_var), y=0.94, fontsize=12)
plt.rcParams["figure.figsize"] = [7.08,7.3]
plt.savefig('{}/Morris_verification_set_{}_sc{}.png'.format(r'C:/Users/moallemie/EM_analysis/Fig/sa_ranking', outcome_var, sc), dpi=600, bbox_inches='tight')
return fig
plot_scores(inds, errs, outcome_var, sc)
plt.close()
```
| github_jupyter |
# Big Assignment 4
### A number of organizations and governments are considering policies to supply students with access to free computers, in an effort to boost learning outcomes. Suppose that you want to learn about the effect of having a free computer on test scores. For a sample of high school students, you collect data on test scores (`test` ), parent’s income (`inc`), and whether they have a computer at home (`comp`).
### Part A:
#### Suppose that a local organization held a lottery, and offered computers at random to a number of students, indicated by freecomp. Suppose that among the population who were not offered a free computer, 60% have a computer, whereas after the lottery, 90% of people offered a computer had a computer. Compare the specifications
\begin{align}
test=\beta_0+\beta_1comp+u
\end{align}
#### or
\begin{align}
test=\beta_0+\beta_1freecomp+u
\end{align}
#### Both tell you something different about the effect of computers on test scores. Describe the limitations of each approach.
Click here to type you answer to part A.
### Part B:
#### You are concerned that household income may be correlated with test scores for a variety of reasons. Suggest an alternate specification that holds income constant, and discuss how you anticipate it changing inference using each estimated $\beta_1$ above.
Click here to type you answer to part B.
### Part C:
#### Propose a “Treatment on the treated” estimator for the free computer lottery.
Click here to type you answer to part C.
### Part D:
#### You think computers might have two different effects on test scores. On the one hand, they are a productive tool which can help learning. On the other hand, they open up recreational opportunities (like social networking) which may not be very useful for learning. As a result, you wonder what the effects of a free computer would be if you could hold recreational screentime constant. That is, you would like to estimate
\begin{align}
test=\beta_0+\beta_1freecomp+\beta_2screentime+u
\end{align}
#### However, in practice you cannot observe screentime. You have two options:
#### - either you can just use whether they have a smart phone as a proxy variable for screentime (variable `Smartphone`),
#### -or you can ask the students to report how much screentime they spend per day (`repscreentime`).
#### Describe algebraically how each approach will affect estimation of $\beta_1$ and $\beta_2$ in the equation for part D, and the analogue to MLR4 which is necessary to grant unbiased estimates. Discuss different potential forms for any measurement error, and the likely consequences of that measurement error.
Click here to type you answer to part D.
### Part E:
#### Suppose instead that the organization offered free computers to the students whose parent’s income was in the bottom 20% of the school. Write down a regression equation which will implement a regression-discontinuity estimator to learn the impact of receiving a free computer. Discuss why results from that estimator may be different from the results from the randomized lottery in part A.
Click here to type you answer to part E.
| github_jupyter |
```
from google.colab import drive
drive.mount('/content/drive')
import nltk
nltk.download('stopwords')
import numpy as np
import pandas as pd
from gensim.models.keyedvectors import KeyedVectors
import gc
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from smart_open import open
from nltk.corpus import stopwords
from sklearn.metrics import classification_report
from keras.layers import Dropout
from matplotlib import pyplot as plt
from sklearn.metrics import classification_report
dataset1 = np.array(pd.read_csv('/content/drive/My Drive/Dataset/dev_split_Depression_AVEC2017.csv',delimiter=',',encoding='utf-8'))[:, 0:2]
dataset2 = np.array(pd.read_csv('/content/drive/My Drive/Dataset/full_test_split.csv',delimiter=',',encoding='utf-8'))[:, 0:2]
dataset3 = np.array(pd.read_csv('/content/drive/My Drive/Dataset/train_split_Depression_AVEC2017.csv',delimiter=',',encoding='utf-8'))[:, 0:2]
dataset = np.concatenate((dataset1, np.concatenate((dataset2, dataset3))))
countPos = 0
def checkPosNeg(dataset, index):
for i in range(0, len(dataset)):
if(dataset[i][0] == index):
return dataset[i][1]
return 0
Data = []
Y = []
countPos = 0
index = -1
Data_test = []
Y_test = []
for i in range(0, len(dataset3)):
val = checkPosNeg(dataset, dataset3[i][0])
Y.append(val)
try:
fileName = "/content/drive/My Drive/Dataset/train_data/" + str(int(dataset3[i][0])) + "_TRANSCRIPT.csv"
Data.append(np.array(pd.read_csv(fileName,delimiter='\t',encoding='utf-8', engine='python'))[:, 2:4])
except Exception as e:
print(e)
for i in range(0, len(dataset1)):
val = checkPosNeg(dataset, dataset1[i][0])
Y.append(val)
try:
fileName = "/content/drive/My Drive/Dataset/dev_data/" + str(int(dataset1[i][0])) + "_TRANSCRIPT.csv"
Data.append(np.array(pd.read_csv(fileName,delimiter='\t',encoding='utf-8', engine='python'))[:, 2:4])
except Exception as e:
print(e)
for i in range(0, len(dataset2)):
Y_test.append(checkPosNeg(dataset, dataset2[i][0]))
try:
fileName = "/content/drive/My Drive/Dataset/test_data/" + str(int(dataset2[i][0])) + "_TRANSCRIPT.csv"
Data_test.append(np.array(pd.read_csv(fileName,delimiter='\t',encoding='utf-8', engine='python'))[:, 2:4])
except Exception as e:
print(e)
Y = np.array(Y)
Data2 = []
Data2_test = []
Y_test = np.array(Y_test)
for i in range(0, len(Data)):
script = []
for k in range(1, len(Data[i])):
if(Data[i][k][0] == "Participant"):
script.append(Data[i][k][1])
Data2.append(script)
for i in range(0, len(Data_test)):
script = []
for k in range(1, len(Data_test[i])):
if(Data_test[i][k][0] == "Participant"):
script.append(Data_test[i][k][1])
Data2_test.append(script)
Data = []
Data_test = []
gc.collect()
Data2 = np.array(Data2)
Data2_test = np.array(Data2_test)
model = KeyedVectors.load_word2vec_format('/content/drive/My Drive/Dataset/GoogleNews-vectors-negative300.bin.gz', binary=True)
stop_words = set(stopwords.words('english'))
def Thresholding(Y_pred, threshold):
Y_pred2 = []
for i in range(len(Y_pred)):
if(Y_pred[i] < threshold):
Y_pred2.append(0)
else:
Y_pred2.append(1)
return np.array(Y_pred2)
def remove_StopWords(sentence):
filtered_sentence = []
for w in sentence:
if w not in stop_words:
filtered_sentence.append(w)
return filtered_sentence
def checkAcc(Y_pred, Y_test):
correct = 0
for i in range(len(Y_pred)):
if(Y_pred[i] == Y_test[i]):
correct+=1
return float(correct)/len(Y_pred)
def upsample(X_train,Y_train):
X_train_0 = X_train[Y_train==0]
X_train_1 = X_train[Y_train==1]
Y_train_1 = Y_train[Y_train==1]
size = X_train_0.shape[0] - X_train_1.shape[0]
X = []
Y = []
X_train = list(X_train)
Y_train = list(Y_train)
while(size>0):
size -= 1
index = np.random.randint(0,X_train_1.shape[0]-1)
leave_index = np.random.randint(0,len(X_train)-1)
X_add = X_train_1[index]
X_leave = X_train[leave_index]
Y_add = Y_train_1[index]
Y_leave = Y_train[leave_index]
X_train[leave_index] = X_add
X_train.append(X_leave)
Y_train[leave_index] = Y_add
Y_train.append(Y_leave)
X_train = np.array(X_train)
Y_train = np.array(Y_train)
return X_train,Y_train
max_num_words = 20
max_num_sentence = 250
#train_data
finalMatrix = np.zeros((Data2.shape[0], max_num_sentence, max_num_words, 300))
max_length_sent = 0
sent = ""
for k in range(Data2.shape[0]):
if(max_length_sent < len(Data2[k])):
max_length_sent = len(Data2[k])
sent = Data2[k]
for i in range(min(max_num_sentence, len(Data2[k]))):
try:
sentence = Data2[k][i].split(" ")
except:
continue
sentence = remove_StopWords(sentence)
for j in range(min(max_num_words, len(sentence))):
try:
word = sentence[j]
# print("Before", word)
if(word[0] == '<'):
if(word.find('>')!=-1):
word = word[1:-1]
else:
word = word[1:]
else:
if(word.find('>')!=-1):
word = word[0:-1]
finalMatrix[k][i][j] = np.array(model[word])
except Exception as e:
continue
#Test_data
max_length_sent = 0
finalMatrix_test = np.zeros((Data2_test.shape[0], max_num_sentence, max_num_words, 300))
# print(finalMatrix_test.shape)
for k in range(Data2_test.shape[0]):
if(max_length_sent < len(Data2_test[k])):
max_length_sent = len(Data2_test[k])
sent = Data2_test[k]
for i in range(min(max_num_sentence, len(Data2_test[k]))):
try:
sentence = Data2_test[k][i].split(" ")
except:
continue
sentence = remove_StopWords(sentence)
for j in range(min(max_num_words, len(sentence))):
try:
word = sentence[j]
if(word[0] == '<'):
if(word.find('>')!=-1):
word = word[1:-1]
else:
word = word[1:]
else:
if(word.find('>')!=-1):
word = word[0:-1]
finalMatrix_test[k][i][j] = np.array(model[word])
except Exception as e:
continue
Data2 = []
Data2_test = []
model = []
stop_words = []
gc.collect()
finalMatrix, Y = upsample(finalMatrix,Y)
finalMatrix_test, Y_test = upsample(finalMatrix_test,Y_test)
classifier = Sequential()
classifier.add(Conv2D(150, (1, 5), input_shape = (finalMatrix.shape[1], finalMatrix.shape[2], finalMatrix.shape[3]), activation = 'relu', data_format="channels_last"))
classifier.add(MaxPooling2D(pool_size = (1, 3)))
classifier.add(Conv2D(75, (1, 3), activation = 'relu', data_format="channels_last"))
classifier.add(MaxPooling2D(pool_size = (1, 2)))
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
class_weight = {0: 0.5, 1: 0.6}
classifier.fit(finalMatrix, Y, epochs = 10, class_weight=class_weight)
Y_Pred = Thresholding(classifier.predict(finalMatrix_test), 0.5)
print(classification_report(Y_test, Y_Pred))
```
| github_jupyter |
```
from icf.frame import Frame
import numpy as np
from datetime import datetime
from icf.pyicf import ICFFile
import pandas as pd
from icf.frame import dispatch_serializer
import struct
import numpy as np
from importlib import import_module
import logging
import sys
class TopicFrame(Frame):
def serialize(self) -> bytes:
"""Serializes the frame to a bytestream
Returns:
bytes: serialized frame
"""
data_stream = bytearray()
index = []
classes = []
pos = 0
for k, v in self.items():
v = dispatch_serializer(v)
_module = v.__class__.__module__
_module = _module if _module not in [__name__,"icf.frame"] else ""
classes.append("{},{},{}\n".format(k, v.__class__.__name__, _module))
d = v.serialize()
pos += len(d)
index.append(pos)
data_stream.extend(d)
n_obj = len(index)
classes = "".join(classes)
header = bytearray(struct.pack(
"<2H{}I{}s".format(n_obj, len(classes)),
len(classes),
n_obj,
*index,
classes.encode(),
))
print(classes)
header.extend(data_stream)
return header
@classmethod
def deserialize_header(cls,data):
ncls, nobj=struct.unpack("<2H",data[:4])
print(ncls,nobj,ncls+4*nobj)
index = struct.unpack("<{}I{}s".format(nobj, ncls), data[4:ncls+4*nobj+4])
classes = index[nobj:][0].decode()
index = list(index[:nobj])
print(classes)
print(index)
class FileStream:
def __init__(self, path, mode=""):
self.buffer = bytearray()
self.size = len(self.buffer)
self.fp = 0
self.path = path
self.mode = mode
def read(self, size=-1):
if size == -1:
size = self.size
self.fp += size
return self.buffer[self.fp-size:self.fp]
def write(self, buffer):
self.buffer.extend(buffer)
self.size = len(self.buffer)
self.fp = self.size
return len(buffer)
def flush(self):
pass
def close(self):
pass
def tell(self):
return self.fp
def seek(self,cookie, whence=0):
if whence == 0:
self.fp = cookie
return self.fp
if whence == 1:
self.fp += cookie
return self.fp
if whence == 2:
self.fp = self.size+cookie
return self.fp
frame = TopicFrame()
frame.add("First",1)
frame.add("Second", np.array([123,2,3,54,5,3,23,4,35,42,3,43,],dtype=np.uint8))
print(frame.serialize())
print(len(frame.serialize()))
TopicFrame.deserialize_header(frame.serialize())
frame = Frame()
frame.add("First",1)
frame.add("Second", [123,2,3,54,5,3,23,4,35,42,3,43,])
print(frame.serialize())
print(len(frame.serialize()))
f = FileStream(frame.serialize())
file = ICFFile("test",custom_stream=FileStream("test"))
file.write(frame.serialize())
frame["some array"] = np.arange(10)
file.write(frame.serialize())
file.flush()
file.close()
file._file.buffer
filer= ICFFile("test.icf","trunc")
filer.write(frame.serialize())
filer.write(frame.serialize())
filer.flush()
#file._file.buffer
filer.close()
d = open("test.icf","rb").read()
print(len(d))
print(len(file._file.buffer))
print(d)
Frame.deserialize(file.read_at(1))
end = file._file.seek(0,2)
file._file.seek(end-4)
d = file._file.read(4)
i = struct.unpack("<I", d)[0]
print(d,i)
file._file.buffer.extend(file._file.buffer)
file._file.size = len(file._file.buffer)
print(file._file.buffer)
file._file.seek(0)
file2 = ICFFile("test",custom_stream=file._file)
print(file2)
Frame.deserialize(file2.read_at(3))['some array']
print(f.read(10))
print(f.read(10))
print(f.tell())
print(f.seek(0))
print(f.read(10))
print(f.seek(-8,2))
startTime = datetime.now()
writer = ICFFile("testing.icf", compressor=None) #'bz2')
for i in range(90):
frame = Frame()
frame.add("r",1)
frame.add("r2", np.random.uniform(0,1012321))
#frame["a_list_of_lists"] = [1, 3, 4, 5, [9, 4, 5], (93, 3.034)]
writer.write(frame.serialize())
writer.close()
```
| github_jupyter |
```
%matplotlib inline
```
# A demo of K-Means clustering on the handwritten digits data
In this example we compare the various initialization strategies for
K-means in terms of runtime and quality of the results.
As the ground truth is known here, we also apply different cluster
quality metrics to judge the goodness of fit of the cluster labels to the
ground truth.
Cluster quality metrics evaluated (see `clustering_evaluation` for
definitions and discussions of the metrics):
=========== ========================================================
Shorthand full name
=========== ========================================================
homo homogeneity score
compl completeness score
v-meas V measure
ARI adjusted Rand index
AMI adjusted mutual information
silhouette silhouette coefficient
=========== ========================================================
```
print(__doc__)
from time import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale
np.random.seed(42)
digits = load_digits()
data = scale(digits.data)
n_samples, n_features = data.shape
n_digits = len(np.unique(digits.target))
labels = digits.target
sample_size = 300
print("n_digits: %d, \t n_samples %d, \t n_features %d"
% (n_digits, n_samples, n_features))
print(82 * '_')
print('init\t\ttime\tinertia\thomo\tcompl\tv-meas\tARI\tAMI\tsilhouette')
def bench_k_means(estimator, name, data):
t0 = time()
estimator.fit(data)
print('%-9s\t%.2fs\t%i\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f'
% (name, (time() - t0), estimator.inertia_,
metrics.homogeneity_score(labels, estimator.labels_),
metrics.completeness_score(labels, estimator.labels_),
metrics.v_measure_score(labels, estimator.labels_),
metrics.adjusted_rand_score(labels, estimator.labels_),
metrics.adjusted_mutual_info_score(labels, estimator.labels_),
metrics.silhouette_score(data, estimator.labels_,
metric='euclidean',
sample_size=sample_size)))
bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10),
name="k-means++", data=data)
bench_k_means(KMeans(init='random', n_clusters=n_digits, n_init=10),
name="random", data=data)
# in this case the seeding of the centers is deterministic, hence we run the
# kmeans algorithm only once with n_init=1
pca = PCA(n_components=n_digits).fit(data)
bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1),
name="PCA-based",
data=data)
print(82 * '_')
# #############################################################################
# Visualize the results on PCA-reduced data
reduced_data = PCA(n_components=2).fit_transform(data)
kmeans = KMeans(init='k-means++', n_clusters=n_digits, n_init=10)
kmeans.fit(reduced_data)
# Step size of the mesh. Decrease to increase the quality of the VQ.
h = .02 # point in the mesh [x_min, x_max]x[y_min, y_max].
# Plot the decision boundary. For that, we will assign a color to each
x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# Obtain labels for each point in mesh. Use last trained model.
Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1)
plt.clf()
plt.imshow(Z, interpolation='nearest',
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
cmap=plt.cm.Paired,
aspect='auto', origin='lower')
plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)
# Plot the centroids as a white X
centroids = kmeans.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', s=169, linewidths=3,
color='w', zorder=10)
plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n'
'Centroids are marked with white cross')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/adding_C3/C3/W3/ungraded_labs/C3_W3_Lab_5_sarcasm_with_bi_LSTM.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
#@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.
```
**IMPORTANT NOTE:** This notebook is designed to run as a Colab. Click the button on top that says, `Open in Colab`, to run this notebook as a Colab. Running the notebook on your local machine might result in some of the code blocks throwing errors.
**Note:** This notebook can run using TensorFlow 2.5.0
```
#!pip install tensorflow==2.5.0
import numpy as np
import json
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
# sarcasm.json
!gdown --id 1dRzdJS7-cZS4S5CuUc32MZYSLJGkkxnp
vocab_size = 1000
embedding_dim = 16
max_length = 120
trunc_type='post'
padding_type='post'
oov_tok = "<OOV>"
training_size = 20000
with open("./sarcasm.json", 'r') as f:
datastore = json.load(f)
sentences = []
labels = []
urls = []
for item in datastore:
sentences.append(item['headline'])
labels.append(item['is_sarcastic'])
training_sentences = sentences[0:training_size]
testing_sentences = sentences[training_size:]
training_labels = labels[0:training_size]
testing_labels = labels[training_size:]
tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)
tokenizer.fit_on_texts(training_sentences)
word_index = tokenizer.word_index
training_sequences = tokenizer.texts_to_sequences(training_sentences)
training_padded = pad_sequences(training_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)
testing_sequences = tokenizer.texts_to_sequences(testing_sentences)
testing_padded = pad_sequences(testing_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
tf.keras.layers.Dense(24, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
model.summary()
num_epochs = 50
training_padded = np.array(training_padded)
training_labels = np.array(training_labels)
testing_padded = np.array(testing_padded)
testing_labels = np.array(testing_labels)
history = model.fit(training_padded, training_labels, epochs=num_epochs, validation_data=(testing_padded, testing_labels), verbose=1)
import matplotlib.pyplot as plt
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.plot(history.history['val_'+string])
plt.xlabel("Epochs")
plt.ylabel(string)
plt.legend([string, 'val_'+string])
plt.show()
plot_graphs(history, 'accuracy')
plot_graphs(history, 'loss')
model.save("test.h5")
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
import io
pd.set_option('display.max_rows',500)
pd.set_option('display.max_columns', 500)
```
# Neighbourhood Census Data
```
neighbourhood_census = pd.read_csv('raw_data/NYC_neighborhood_census_data_2020.csv')
neighbourhood_census.head()
# Getting out the columns in the data
print(neighbourhood_census.columns)
# Selecting the more useful columns
neighbourhood_census_trimmed = neighbourhood_census[[
'Neighborhood',
'Car-free commute (% of commuters)',
'Disabled population',
'Foreign-born population',
'Median household income (2018$)',
'Median rent, all (2018$)',
'Percent Asian',
'Percent Hispanic',
'Percent black',
'Percent white',
'Population',
'Poverty rate',
'Public housing (% of rental units)',
'Unemployment rate',
'Residential units within 12 mile of a subway station',
'Population density (1,000 persons per square mile)',
'Serious crime rate (per 1,000 residents)',
'Severely rent-burdened households',
'Rental vacancy rate',
'Mean travel time to work (minutes)'
]]
neighbourhood_census_trimmed.head()
```
## Distribution
```
#remove neighbour column
no_neighbour = neighbourhood_census_trimmed.drop(['Neighborhood'], axis=1)
for i in no_neighbour.columns:
plt.figure()
plt.hist(no_neighbour[i])
plt.ylabel(i)
percent_missing = no_neighbour.isnull().sum() * 100 / len(no_neighbour)
missing_value_df = pd.DataFrame({'column_name': no_neighbour.columns,
'percent_missing': percent_missing})
missing_value_df.sort_values('percent_missing', inplace=True,ascending=False)
missing_value_df
```
## Skew
```
# checking skewness
# -0.5 to 0.5 -> Fairly symmetrical
# -1 to -0.5 OR 0.5 to 1 -> Moderately Skewed
# <-1 OR >1 -> Highly skewed
no_neighbour.skew(axis = 0, skipna = True)
```
# Subway Data
```
subway_raw = pd.read_csv('raw_data/NYC_subway_traffic_2017-2021.csv')
subway_raw.head()
subway_raw['year'] = pd.DatetimeIndex(subway_raw['Datetime']).year
subway_raw['month'] = pd.DatetimeIndex(subway_raw['Datetime']).month
subway_raw.head()
```
## Check for missing value
```
percent_missing = subway_raw.isnull().sum() * 100 / len(subway_raw)
missing_value_df = pd.DataFrame({'column_name': subway_raw.columns,
'percent_missing': percent_missing})
missing_value_df.sort_values('percent_missing', inplace=True,ascending=False)
missing_value_df
```
## Distribution
```
distribution_check = subway_raw[['Line','Connecting Lines','Daytime Routes','Division','Structure','Borough','Neighborhood']]
for i in distribution_check.columns:
plt.figure()
plt.hist(distribution_check[i])
plt.ylabel(i)
#no check for north/south direction label
```
## Selecting Apr, May, June from 2020, dropping columns
```
subway_filitered = subway_raw.loc[subway_raw['year'] == 2020]
subway_filitered = subway_filitered[subway_filitered['month'].isin([3,4,5])]
subway_filitered = subway_filitered.drop(['year', 'month', 'Unique ID', 'North Direction Label',
'South Direction Label','Latitude', 'Longitude','Remote Unit','Line','Daytime Routes'], axis=1)
subway_filitered.to_csv('subway_filitered.csv')
subway_filitered.head()
# subway_filitered.shape
# combining entries and exits
subway_filitered['EntriesExits']= subway_filitered[['Entries','Exits']].sum(axis=1)
subway_filitered = subway_filitered.drop(['Entries','Exits'], axis=1)
subway_filitered.head()
```
## OHE Columns
```
#OHE for Division, Structure, Borough
def one_hot(df, cols):
for each in cols:
dummies = pd.get_dummies(df[each], prefix=each, drop_first=False)
df = pd.concat([df, dummies], axis=1)
return df
cols = ['Division','Structure','Borough']
encoded_subway = one_hot(subway_filitered,cols)
encoded_subway.to_csv('encoded_subway.csv')
encoded_subway.head()
# OHE for connecting lines and DAytime Routes
list_of_routes = ["N",'Q','R','D','W','B','F','M','A','C','E','S','J','Z','1','2','3','L','G','5','4','7','6']
#Connecting Liness
for line in list_of_routes:
name = 'ConnectingLine_' + line
encoded_subway.loc[encoded_subway['Connecting Lines'].str.contains(line), name] = 1
encoded_subway = encoded_subway.fillna(0)
encoded_subway.head()
```
## Groupby Neighbourhood, Datetime
```
#drop extra columns and OHE columns before grouping
to_group = encoded_subway
encoded_subway = encoded_subway.drop(['Connecting Lines','Division','Structure', 'Borough','Stop Name'], axis=1)
grouped = encoded_subway.groupby(['Neighborhood','Datetime']).max().reset_index()
# grouped.to_csv('grouped.csv')
grouped.head()
```
## Feature engineering on num of stations
```
# find the number of stations in each neighbourhood (after the groupby)
neighbourhood_stations = to_group.groupby(['Neighborhood']).nunique().reset_index()
neighbourhood_stations.rename(columns={'Stop Name':'num_of_stations'}, inplace=True)
neighbourhood_stations = neighbourhood_stations[['Neighborhood','num_of_stations']]
neighbourhood_stations.head()
# encoded_subway.head()
#joining the 2 df together
grouped = pd.merge(grouped, neighbourhood_stations, on="Neighborhood")
grouped = grouped.drop(['Stop Name'])
# grouped.to_csv('grouped.csv')
grouped.head()
#aggregating the entries/exit column to a binary
grouped.head()
grouped_datetime = grouped.groupby(['Datetime']).median()
grouped_datetime = grouped_datetime.iloc[:, 0]
grouped_datetime.head()
# grouped_datetime.to_csv('median.csv')
# print(grouped.head())
median_dict = grouped_datetime.to_dict()
grouped["median"] = grouped["Datetime"].map(median_dict)
grouped.loc[grouped['EntriesExits'] >= grouped['median'], 'binary_target'] = 1
grouped.loc[grouped['EntriesExits'] < grouped['median'], 'binary_target'] = 0
# grouped.to_csv('grouped.csv')
grouped.head()
```
## Merging the Subway and neighbourhood data
```
result = pd.merge(grouped, neighbourhood_census_trimmed, on="Neighborhood").reset_index()
result = result.groupby(['Neighborhood','Datetime']).max()
# result.to_csv('final.csv')
result.head()
```
## Feature engineering on area size
```
# population/area = density --> find the area (feature engineering)
result["Area (in sq miles)"] = (result['Population']/1000) / result['Population density (1,000 persons per square mile)']
result.to_csv('final_rawdata.csv')
result.head()
```
| github_jupyter |
# scikit-learn-k-means
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn;
from sklearn.linear_model import LinearRegression
from scipy import stats
import pylab as pl
seaborn.set()
```
## K-Means Clustering
```
from sklearn import neighbors, datasets
iris = datasets.load_iris()
X, y = iris.data, iris.target
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
pca.fit(X)
X_reduced = pca.transform(X)
print("Reduced dataset shape:", X_reduced.shape)
import pylab as pl
pl.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y,
cmap='RdYlBu')
print("Meaning of the 2 components:")
for component in pca.components_:
print(" + ".join("%.3f x %s" % (value, name)
for value, name in zip(component,
iris.feature_names)))
from sklearn.cluster import KMeans
k_means = KMeans(n_clusters=3, random_state=0) # Fixing the RNG in kmeans
k_means.fit(X)
y_pred = k_means.predict(X)
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y_pred,cmap='RdYlBu');
```
K Means is an algorithm for **unsupervised clustering**: that is, finding clusters in data based on the data attributes alone (not the labels).
K Means is a relatively easy-to-understand algorithm. It searches for cluster centers which are the mean of the points within them, such that every point is closest to the cluster center it is assigned to.
Let's look at how KMeans operates on the simple clusters we looked at previously. To emphasize that this is unsupervised, we'll not plot the colors of the clusters:
```
from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples=200, centers=4,
random_state=0, cluster_std=0.60)
plt.scatter(X[:, 0], X[:, 1], s=50);
```
By eye, it is relatively easy to pick out the four clusters. If you were to perform an exhaustive search for the different segmentations of the data, however, the search space would be exponential in the number of points. Fortunately, there is a well-known *Expectation Maximization (EM)* procedure which scikit-learn implements, so that KMeans can be solved relatively quickly.
```
from sklearn.cluster import KMeans
est = KMeans(4) # 4 clusters
est.fit(X)
y_kmeans = est.predict(X)
plt.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=50, cmap='rainbow');
```
The algorithm identifies the four clusters of points in a manner very similar to what we would do by eye!
## The K-Means Algorithm: Expectation Maximization
K-Means is an example of an algorithm which uses an *Expectation-Maximization* approach to arrive at the solution.
*Expectation-Maximization* is a two-step approach which works as follows:
1. Guess some cluster centers
2. Repeat until converged
A. Assign points to the nearest cluster center
B. Set the cluster centers to the mean
Let's quickly visualize this process:
```
from fig_code import plot_kmeans_interactive
plot_kmeans_interactive();
```
This algorithm will (often) converge to the optimal cluster centers.
### KMeans Caveats
* The convergence of this algorithm is not guaranteed; for that reason, by default scikit-learn uses a large number of random initializations and finds the best results.
* The number of clusters must be set beforehand. There are other clustering algorithms for which this requirement may be lifted.
| github_jupyter |
```
%cd ..
%load_ext autoreload
%autoreload 2
import tensorflow as tf
tf.get_logger().setLevel("ERROR")
import tensorflow_datasets as tfds
import tensorflow_datasets_bw as datasets
from tensorflow_datasets_bw import visualize
import dppp
```
# Using Bicubic Downscaling
```
scale_factor = 4
resize_method = tf.image.ResizeMethod.BICUBIC
builder_kwargs = {
"resize_method": resize_method,
"scale": scale_factor,
"antialias": True,
}
images = (
tfds.load(name="set14", split="test", builder_kwargs=builder_kwargs)
.map(datasets.map_on_dict(datasets.to_float32))
.map(datasets.map_on_dict(datasets.from_255_to_1_range))
)
image_dict = datasets.get_one_example(images, index=2)
image_hr = image_dict["hr"][None, ...]
image_lr = image_dict["lr"][None, ...]
```
### Reconstruct
```
# Load the denoiser
denoiser, (denoiser_min, denoiser_max) = dppp.load_denoiser("models/drugan+_0.0-0.2.h5")
# Callbacks: Print the PSNR every 5th step
callbacks = [dppp.callback_print_psnr("psnr", 5, image_hr)]
resize_fn = dppp.create_resize_fn(resize_method)
reconstructed = dppp.hqs_super_resolve(
degraded=image_lr,
sr_factor=scale_factor,
denoiser=denoiser,
max_denoiser_stddev=denoiser_max,
resize_fn=resize_fn,
callbacks=callbacks,
)
# Print PSNR and LPIPS
psnr = dppp.psnr(image_hr, reconstructed).numpy()[0]
lpips = dppp.lpips_alex(image_hr, reconstructed).numpy()[0]
print(f"Reconstructed PSNR: {psnr:0.2f}, LPIPS: {lpips:0.4f}")
# Visualize
visualize.draw_images([image_hr[0], image_lr[0], reconstructed[0]])
```
# Using a Gaussian Blur Kernel
```
scale_factor = 2
images = (
tfds.load(name="cbsd68", split="test")
.map(datasets.get_image)
.map(datasets.to_float32)
.map(datasets.from_255_to_1_range)
)
image_hr = datasets.get_one_example(images, index=31)[None, :480, :320, :]
kernel = dppp.conv2D_filter_rgb(dppp.ZHANG_GAUSSIAN_KERNELS[6])
image_blurred = dppp.blur(image_hr, kernel, 0, mode="wrap")
image_lr = image_blurred[:,::scale_factor,::scale_factor,:]
```
### Reconstruct
```
# Load the denoiser
denoiser, (denoiser_min, denoiser_max) = dppp.load_denoiser("models/drugan+_0.0-0.2.h5")
# Callbacks: Print the PSNR every 5th step
callbacks = [dppp.callback_print_psnr("psnr", 5, image_hr)]
reconstructed = dppp.hqs_super_resolve(
degraded=image_lr,
sr_factor=scale_factor,
denoiser=denoiser,
max_denoiser_stddev=denoiser_max,
kernel=kernel,
callbacks=callbacks,
)
# Print PSNR and LPIPS
psnr = dppp.psnr(image_hr, reconstructed).numpy()[0]
lpips = dppp.lpips_alex(image_hr, reconstructed).numpy()[0]
print(f"Reconstructed PSNR: {psnr:0.2f}, LPIPS: {lpips:0.4f}")
# Visualize
visualize.draw_images([image_hr[0], image_lr[0], reconstructed[0]])
```
| github_jupyter |
```
# Use the previous version of the SageMaker SDK
import sys
!{sys.executable} -m pip install sagemaker==1.72.0 -U
```
# Creating our custom LightGBM training container for SageMaker
Now that we have successfully developed the LightGBM model, we can proceed and create our custom Docker container. We'll use the [sagemaker-training-toolkit library](https://github.com/aws/sagemaker-training-toolkit) to define script mode and framework containers (our custom LightGBM container).
This part of the workshop is composed of 4 parts:
1. <a href="#custom_training_container">Create our <strong>custom Docker container that SageMaker will run for training</strong> in Script Mode and Framework mode</a>
2. <a href="#training_toolkit">Create a Python package to configure <strong>SageMaker Training toolkit</strong></a>
3. <a href="#container_training_build"><strong>Building</strong> our Docker image and <strong>pushing</strong> it to Amazon Elastic Container Registry</a>
3. <a href="#testing_training"><strong>Testing the training locally</strong> with our container using the SageMaker Python SDK</a>
### First of all, what are the types of SageMaker containers? What is a SageMaker Framework container?
Basically, SageMaker provides 3 types of containers (and APIs) that you can interact with:
#### a) Basic Training Container (click on the three dots below for mode details)
The bare minimum that is required for building a custom Docker container to run training in Amazon SageMaker (using pre-defined training logic and prepared to receive data in specific shape, e.g. target variable in the first column).
<img src="./media/basic_training_container.jpg" class="center">
When interacting with SageMaker with the basic training container, we use the Estimator API with the class ['sagemaker.estimator.Estimator(...)'](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator) passing only the configurations like container image URI, hyperparamenters, etc. **We cannot pass custom code into SageMaker as it is already specified inside the Docker container.**
#### b) Script Mode Container (click on the three dots below for mode details)
A custom container where **we can pass a user defined script that SageMaker will execute at training time** (sagemaker-training toolkit will load and execute the defined script as entry point).
This training script can be passed to the container in a Python module (shown below in Script Mode Container on the left) or can be stored in Amazon S3 and passed to the container that will download it and run it as entry point (shown below in Script Mode Conatiner 2 on the right).
<table><tr>
<td> <img src="./media/script_mode_container.jpg" style="height: 100%"> </td>
<td> <img src="./media/script_mode_container_2.jpg" style="height: 100%"> </td>
</tr></table>
We can use the Estimator API with the class ['sagemaker.estimator.Estimator(...)'](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator) and pass the configurations including `sagemaker_program` for the entry point Python module and `sagemaker_submit_directory` for URI of the tarball in S3 with the code used for training (this way SageMaker at training time knows where to download the code from and how to run it).
#### c) Framework Container (click on the three dots below for mode details)
A framework container is similar to a script-mode container, but in addition it loads a Python framework module that is used to configure the framework and then run the user-provided module. **The SageMaker Python SDK with Framework mode will create a tarball with local files and upload our code to S3. Then, in the training stage, SageMaker will load the script similarly to the Script Mode Container 2 above and run it for training.**
<img src="./media/framework_container.jpg" class="center">
We can use the Estimator API with the class ['sagemaker.estimator.Framework(...)'](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Framework) and pass the configurations including `entry_point` for the entry point Python module and `source_dir` for the local directory with code.
[More details about the containers and examples here.](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/advanced_functionality/custom-training-containers)
> **Quick Recap**: [In the previous exercise](https://github.com/marcelokscunha/amazon-sagemaker-mlops-workshop/blob/master/lab/00_Warmup_Studio/xgboost_customer_churn_studio.ipynb) we used XGBoost in both "basic training container" and "framework" modes.
<div id="custom_training_container">
<h2> 1. Creating the training container</h2>
</div>
We start by defining some variables like the current execution role, the ECR repository that we are going to use for pushing the custom Docker container and the default Amazon S3 bucket to be used by Amazon SageMaker:
```
import boto3
import sagemaker
from sagemaker import get_execution_role
ecr_repository_name = 'sagemaker-custom-lightgbm'
role = get_execution_role()
account_id = role.split(':')[4]
region = boto3.Session().region_name
sagemaker_session = sagemaker.session.Session()
bucket = sagemaker_session.default_bucket()
print(account_id)
print(region)
print(role)
print(bucket)
print(ecr_repository_name)
```
Let's take a look at the Dockerfile which defines the statements for building our custom script/framework container:
```
!pygmentize ../docker/Dockerfile
```
---
At high-level the Dockerfile specifies the following operations for building this container:
1. Start from Ubuntu 16.04
2. Define some variables to be used at build time to install Python 3
3. Some handful libraries are installed with apt-get
4. We then install Python 3 and create a symbolic link
5. We copy a .tar.gz package named **custom_framework_training-1.0.0.tar.gz** in the WORKDIR
6. We then install some Python libraries like Numpy, Pandas, Scikit-Learn, **LightGBM and our package we copied at the previous step**
7. We set e few environment variables, including PYTHONUNBUFFERED which is used to avoid buffering Python standard output (useful for logging)
8. Finally, we set the value of the environment variable `SAGEMAKER_TRAINING_MODULE` to a Python module in the training package we installed.
> **Under the hood**:
>
>- After installing the sagemaker-training-tookit, we can run it as a command line script just executing `train` in the terminal.
>
>[Take a look at the setup.py of sagemaker-training-toolkit here.](https://github.com/aws/sagemaker-training-toolkit/blob/master/setup.py)
>
>(see the last lines of setup.py → `entry_points={"console_scripts": : ["train=(...)}`)
>
>- When executing `train` the toolkit will run the specified script and look for this environment variable `SAGEMAKER_TRAINING_MODULE` above.
>
>In another words:
>
>- We define `ENV SAGEMAKER_TRAINING_MODULE custom_lightgbm_framework.training:main`. When we run `train` in bash, the SageMaker Training Toolkit execute our `main()` function defined at [custom_lightgbm_framework.training](../package/src/custom_lightgbm_framework/training.py).
>
>SageMaker will run our Docker image for training with `docker run <YOUR-IMAGE> train` ([more details here](https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo-dockerfile.html)).
<div id="training_toolkit">
<h2>2. What is our custom_framework_training-1.0.0.tar.gz package?</h2>
</div>
Looking at our Dockerfile above, we see that we didn't install sagemaker-training (the toolkit) with `pip install sagemaker-training`, nor created a custom console script for the command `train`. All of that is configured within our package.
The advantage here is that **we can re-use the package and change just the libraries installed in the Docker container**. In the end if we wanted to use another Framework (e.g. [Catboost](https://catboost.ai/)) we would just change the step 6. in the Dockerfile (e.g. `RUN pip install catboost`).
Let's see the configurations of our custom Python package:
```
!pygmentize ../package/setup.py
```
This build script looks at the packages under the local src/ path and specifies the dependency on sagemaker-training. As previously explained, the training module containing the `main()` function that will be executed is the following:
```
!pygmentize ../package/src/custom_lightgbm_framework/training.py
```
The idea here is that we will use the <strong>entry_point.run()</strong> function of the sagemaker-training-toolkit library to execute the user-provided module.
You might want to set additional framework-level configurations (e.g. parameter servers) before calling the user module.
<div id="container_training_build">
<h2>3. Build and push the container</h2>
</div>
We are now ready to build this container and push it to Amazon ECR. This task is executed using a shell script stored in the ../script/ folder. Let's take a look at this script and then execute it.
```
! pygmentize ../scripts/build_and_push.sh
```
---
This script does the following:
1. runs the **setup.py** to create the training package (a tarball in this case) and copy it under **../docker/code/**
2. builds the Docker image and tags it
3. logs in to Amazon Elastic Container Registry and creates a repository if there's none
4. push the image to our ECR repository
The build task requires a few minutes to be executed the first time, then Docker caches build outputs to be reused for the subsequent build operations.
**Let's run this script now:**
```
print('Confgurations for our bash script:')
print('account ID:', account_id)
print('region:', region)
print('ECR repository name:', ecr_repository_name)
! ../scripts/build_and_push.sh $account_id $region $ecr_repository_name
```
[Go to ECR in the AWS console](https://console.aws.amazon.com/ecr/home?region=us-east-2) and check if our new repository called `sagemaker-custom-lightgbm` was created and the image was pushed to it.

<div id="testing_training">
<h2>4. Training with Amazon SageMaker</h2>
</div>
Once we have correctly pushed our container to Amazon ECR, we are ready to start training with Amazon SageMaker. As previously explained, we have 2 options to pass this training script to SageMaker: via **Script Mode** or **Framework mode**.
*We have to:*
a) **upload the data to S3** so that SageMaker knows from where to dowload it and train (defining our S3-based training channels).
b) to train using our script:
- b.1) **if in Script mode** → upload training script to S3
- b.2) **if in Framework mode** → extend the sagemaker.estimator.Framework class(the SageMaker Python SDK will do the uploading for us)
#### a) Uploading the data to S3
Let's **upload our data** from the directory `data` (created in the first notebook) to Amazon S3 and configure SageMaker input:
```
# Save data in S3 for training with SageMaker
prefix = 'sagemaker-custom'
data_dir = 'data'
input_train = sagemaker_session.upload_data('data/train/iris_train.csv', key_prefix="{}/{}".format(prefix, data_dir) )
input_test = sagemaker_session.upload_data('data/test/iris_test.csv', key_prefix="{}/{}".format(prefix, data_dir) )
sagemaker_session.list_s3_files(sagemaker_session.default_bucket(), prefix+'/'+data_dir)
input_train, input_test
train_config = sagemaker.session.s3_input(input_train, content_type='text/csv')
test_config = sagemaker.session.s3_input(input_test, content_type='text/csv')
```
[Go to the S3 bucket to check how the data was stored.](https://s3.console.aws.amazon.com/s3/home)

### b.1) Now, for the Script mode container:
As discussed, in script mode, SageMaker will load the training script from S3.
Let's create a tarball with the training script and upload it to S3:
```
# helper function to create a tarball
import tarfile
import os
def create_tar_file(source_files, target=None):
if target:
filename = target
else:
_, filename = tempfile.mkstemp()
with tarfile.open(filename, mode="w:gz") as t:
for sf in source_files:
# Add all files from the directory into the root of the directory structure of the tar
t.add(sf, arcname=os.path.basename(sf))
return filename
# Create a tarball with our training script
create_tar_file(["source_dir/train.py"], "sourcedir.tar.gz")
# Upload the tarball to S3
sources = sagemaker_session.upload_data('sourcedir.tar.gz', bucket, prefix + '/code')
print('Uploaded tarball to:', sources)
! rm sourcedir.tar.gz
```
Let's configure SageMaker to use our Docker container:
```
container_image_uri = '{0}.dkr.ecr.{1}.amazonaws.com/{2}:latest'.format(account_id, region, ecr_repository_name)
print(container_image_uri)
```
To remember the training script we created before ([in the previous notebook](./0_local_development.ipynb)), [click here to view the script.](./source_dir/train.py)
Train in Script mode with SageMaker (use `sagemaker.estimator.Estimator`):
```
import sagemaker
import json
# JSON encode hyperparameters.
def json_encode_hyperparameters(hyperparameters):
return {str(k): json.dumps(v) for (k, v) in hyperparameters.items()}
hyperparameters = json_encode_hyperparameters({
"sagemaker_program": "train.py",
"sagemaker_submit_directory": sources,
"num_leaves": 40,
"max_depth": 10,
"learning_rate": 0.11,
"random_state": 42})
estimator = sagemaker.estimator.Estimator(container_image_uri,
role,
train_instance_count=1,
train_instance_type='local',
#train_instance_type='ml.m5.xlarge',
base_job_name=prefix,
hyperparameters=hyperparameters)
```
Observe that the *sagemaker-training-toolkit library* uses the following reserved hyperparameters to know where the our sources are stored in Amazon S3:
- `sagemaker_program`
- `sagemaker_submit_directory`
```
estimator.fit({'train': train_config, 'validation': test_config })
```
>Again, as expected the training finished with the final validation loss of 0.138846 and F1 score of 0.94 after choosing the same hyperparameters ([look the previous notebook again if you want](./0_local_development.ipynb)).
### b.2) Now, for the Framework mode container:
As you have seen, in the previous steps we had to upload our code to Amazon S3 and then inject reserved hyperparameters to execute training. However, **with the Framework class in the SageMaker Python SDK, the upload is automated for us.**
Let's extend the `sagemaker.estimator.Framework` class from the SageMaker Python SDK. We'll create a class called `MyLightGBMFramework` that inherits from the Framework class:
```
%%writefile custom_framework.py
from sagemaker.estimator import Framework
class MyLightGBMFramework(Framework):
def __init__(
self,
entry_point,
source_dir=None,
hyperparameters=None,
py_version="py3",
framework_version=None,
image_name=None,
distributions=None,
**kwargs
):
super(MyLightGBMFramework, self).__init__(
entry_point, source_dir, hyperparameters, image_name=image_name, **kwargs
)
def _configure_distribution(self, distributions):
return
def create_model(
self,
model_server_workers=None,
role=None,
vpc_config_override=None,
entry_point=None,
source_dir=None,
dependencies=None,
image_name=None,
**kwargs
):
return None
```
We can now use our `MyLightGBMFramework` class for training with SageMaker and pass the local script and directory (`entry_point` and `source_dir`):
```
import sagemaker
from custom_framework import MyLightGBMFramework
framework = MyLightGBMFramework(image_name=container_image_uri,
role=role,
entry_point='train.py',
source_dir='source_dir/',
train_instance_count=1,
train_instance_type='local', # we use local mode
#train_instance_type='ml.m5.xlarge',
base_job_name=prefix,
hyperparameters={"num_leaves": 40,
"max_depth": 10,
"learning_rate": 0.11,
"random_state": 42}
)
framework.fit({'train': train_config, 'validation': test_config })
```
>Again, as expected the training finished with the final validation loss of 0.138846 and F1 score of 0.94 after choosing the same hyperparameters ([look the previous notebook again if you want](./0_local_development.ipynb)).
> If wanted we could have used a Python script that is stored in a Git repository instead of the local file using [git_config](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Framework) (this could be helpful when we automate and create a ML pipeline).
## The end of the creating the training container!
### What's next? How can we deploy the custom model?
If we try to deploy it, we'll receive an error (obviously, since we didn't implement the logic for serving the trained model and inference.
Click on the **STOP** button (square button on the top) to stop this test:
Since there's no implementation of web server nor inference logic, if you deploy the model with the script mode (the `estimator` object above) you'll receive the error:
```
Traceback (most recent call last):
File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/sagemaker/local/image.py", line 618, in run
_stream_output(self.process)
File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/sagemaker/local/image.py", line 677, in _stream_output
raise RuntimeError("Process exited with code: %s" % exit_code)
RuntimeError: Process exited with code: 1
(...)
RuntimeError: Failed to run: ['docker-compose', '-f', '/tmp/tmpjswa7hh1/docker-compose.yaml', 'up', '--build', '--abort-on-container-exit'], Process exited with code: 1
```
```
estimator.deploy(initial_instance_count=1,
instance_type='local',
)
```
For the `framework` object above for the Framework mode, again there will be an error since we didn't implement the [Framework Model class](https://sagemaker.readthedocs.io/en/stable/api/inference/model.html#sagemaker.model.FrameworkModel) (when executing `framwork.deploy(...)` the SageMaker Python SDK first creates a Model object and then uses it to deploy ([more details in the source code](https://github.com/aws/sagemaker-python-sdk/blob/4100bfa8aba871c3b947f88891a7719139b6f394/src/sagemaker/estimator.py#L1377)):
```
AttributeError: 'NoneType' object has no attribute 'name'
```
```
framework.deploy(initial_instance_count=1,
instance_type='local')
```
## Let's implement the final logic for serving and inference!
## → [CLICK HERE TO MOVE ON](../../1_custom_inference/lab/2_inference-container.ipynb)
| github_jupyter |
```
import torch
import torch.nn as nn
import pyro
from pyro.distributions import Bernoulli
from pyro.distributions import Delta
from pyro.distributions import Normal
from pyro.distributions import Uniform
from pyro.distributions import LogNormal
from pyro.infer import SVI
from pyro.infer import Trace_ELBO
from pyro.optim import Adam
import torch.distributions.constraints as constraints
# initialize the autodiagonal with init_to_feasible instead of init_to_median
from pyro.infer.autoguide import init_to_feasible
from pyro.infer.autoguide import AutoDiagonalNormal
# Data Loader
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '../')
from box_office.data_loader import load_tensor_data
pyro.set_rng_seed(101)
x_train_tensors, y_train_tensors, actors, full_data = load_tensor_data("../data/ohe_movies.csv")
def f_z(params):
"""Samples from P(Z)"""
z_mean0 = params['z_mean0']
z_std0 = params['z_std0']
z = pyro.sample("z", Normal(loc = z_mean0, scale = z_std0))
return z
def f_x(z, params):
"""
Samples from P(X|Z)
P(X|Z) is a Bernoulli with E(X|Z) = logistic(Z * W),
where W is a parameter (matrix). In training the W is
hyperparameters of the W distribution are estimated such
that in P(X|Z), the elements of the vector of X are
conditionally independent of one another given Z.
"""
def sample_W():
"""
Sample the W matrix
W is a parameter of P(X|Z) that is sampled from a Normal
with location and scale hyperparameters w_mean0 and w_std0
"""
w_mean0 = params['w_mean0']
w_std0 = params['w_std0']
W = pyro.sample("W", Normal(loc = w_mean0, scale = w_std0))
return W
W = sample_W()
linear_exp = torch.matmul(z, W)
# sample x using the Bernoulli likelihood
x = pyro.sample("x", Bernoulli(logits = linear_exp))
return x
def f_y(x, z, params):
"""
Samples from P(Y|X, Z)
Y is sampled from a Gaussian where the mean is an
affine combination of X and Z. Bayesian linear
regression is used to estimate the parameters of
this affine transformation function. Use torch.nn.Module to create
the Bayesian linear regression component of the overall
model.
"""
predictors = torch.cat((x, z), 1)
w = pyro.sample('weight', Normal(params['weight_mean0'], params['weight_std0']))
b = pyro.sample('bias', Normal(params['bias_mean0'], params['bias_std0']))
y_hat = (w * predictors).sum(dim=1) + b
# variance of distribution centered around y
sigma = pyro.sample('sigma', Normal(params['sigma_mean0'], params['sigma_std0']))
with pyro.iarange('data', len(predictors)):
pyro.sample('y', LogNormal(y_hat, sigma))
return y_hat
def model(params):
"""The full generative causal model"""
z = f_z(params)
x = f_x(z, params)
y = f_y(x, z, params)
return {'z': z, 'x': x, 'y': y}
def step_1_guide(params):
"""
Guide function for fitting P(Z) and P(X|Z) from data
"""
# Infer z hyperparams
qz_mean = pyro.param("qz_mean", params['z_mean0'])
qz_stddv = pyro.param("qz_stddv", params['z_std0'],
constraint=constraints.positive)
z = pyro.sample("z", Normal(loc = qz_mean, scale = qz_stddv))
# Infer w params
qw_mean = pyro.param("qw_mean", params["w_mean0"])
qw_stddv = pyro.param("qw_stddv", params["w_std0"],
constraint=constraints.positive)
W = pyro.sample("W", Normal(loc = qw_mean, scale = qw_stddv))
def step_2_guide(params):
# Z and W are just sampled using param values optimized in previous step
z = pyro.sample("z", Normal(loc = params['qz_mean'], scale = params['qz_stddv']))
W = pyro.sample("W", Normal(loc = params['qw_mean'], scale = params['qw_stddv']))
# Infer regression params
# parameters of (w : weight)
w_loc = pyro.param('w_loc', params['weight_mean0'])
w_scale = pyro.param('w_scale', params['weight_std0'])
# parameters of (b : bias)
b_loc = pyro.param('b_loc', params['bias_mean0'])
b_scale = pyro.param('b_scale', params['bias_std0'])
# parameters of (sigma)
sigma_loc = pyro.param('sigma_loc', params['sigma_mean0'])
sigma_scale = pyro.param('sigma_scale', params['sigma_std0'])
# sample (w, b, sigma)
w = pyro.sample('weight', Normal(w_loc, w_scale))
b = pyro.sample('bias', Normal(b_loc, b_scale))
sigma = pyro.sample('sigma', Normal(sigma_loc, sigma_scale))
def training_step_1(x_data, params):
adam_params = {"lr": 0.0005}
optimizer = Adam(adam_params)
conditioned_on_x = pyro.condition(model, data = {"x" : x_data})
svi = SVI(conditioned_on_x, step_1_guide, optimizer, loss=Trace_ELBO())
print("\n Training Z marginal and W parameter marginal...")
n_steps = 2000
pyro.set_rng_seed(101)
# do gradient steps
pyro.get_param_store().clear()
for step in range(n_steps):
loss = svi.step(params)
if step % 100 == 0:
print("[iteration %04d] loss: %.4f" % (step + 1, loss/len(x_data)))
# grab the learned variational parameters
updated_params = {k: v for k, v in params.items()}
for name, value in pyro.get_param_store().items():
print("Updating value of hypermeter{}".format(name))
updated_params[name] = value.detach()
return updated_params
def training_step_2(x_data, y_data, params):
print("Training Bayesian regression parameters...")
pyro.set_rng_seed(101)
num_iterations = 1000
pyro.clear_param_store()
# Create a regression model
optim = Adam({"lr": 0.003})
conditioned_on_x_and_y = pyro.condition(model, data = {
"x": x_data,
"y" : y_data
})
svi = SVI(conditioned_on_x_and_y, step_2_guide, optim, loss=Trace_ELBO(), num_samples=1000)
for step in range(num_iterations):
loss = svi.step(params)
if step % 100 == 0:
print("[iteration %04d] loss: %.4f" % (step + 1, loss/len(x_data)))
updated_params = {k: v for k, v in params.items()}
for name, value in pyro.get_param_store().items():
print("Updating value of hypermeter: {}".format(name))
updated_params[name] = value.detach()
print("Training complete.")
return updated_params
def train_model():
num_datapoints, data_dim = x_train_tensors.shape
latent_dim = 30 # can be changed
# print(torch.zeros(data_dim + latent_dim).shape)
params0 = {
'z_mean0': torch.zeros([num_datapoints, latent_dim]),
'z_std0' : torch.ones([num_datapoints, latent_dim]),
'w_mean0' : torch.zeros([latent_dim, data_dim]),
'w_std0' : torch.ones([latent_dim, data_dim]),
'weight_mean0': torch.zeros(data_dim + latent_dim),
'weight_std0': torch.ones(data_dim + latent_dim),
'bias_mean0': torch.tensor(0.),
'bias_std0': torch.tensor(1.),
'sigma_mean0' : torch.tensor(1.),
'sigma_std0' : torch.tensor(0.05)
}
params1 = training_step_1(x_train_tensors, params0)
params2 = training_step_2(x_train_tensors, y_train_tensors, params1)
return params1, params2
# trained_params = train_model()
p1, p2 = train_model()
# Save all params to disk
import pickle
with open('params.pickle', 'wb') as handle:
pickle.dump(p2, handle, protocol=pickle.HIGHEST_PROTOCOL)
handle.close()
```
| github_jupyter |
# Finding routes for appliance delivery with Vehicle Routing Problem Solver
<h2>Table of Contents<span class="tocSkip"></span></h2>
<div class="toc"><ul class="toc-item"><li><span><a href="#Finding-routes-for-appliance-delivery-with-Vehicle-Routing-Problem-Solver" data-toc-modified-id="Finding-routes-for-appliance-delivery-with-Vehicle-Routing-Problem-Solver-1">Finding routes for appliance delivery with Vehicle Routing Problem Solver</a></span><ul class="toc-item"><li><ul class="toc-item"><li><span><a href="#Create-orders-layer-with-csv-file:" data-toc-modified-id="Create-orders-layer-with-csv-file:-1.0.1">Create orders layer with csv file:</a></span></li><li><span><a href="#Create-routes-layer-with-csv-file:" data-toc-modified-id="Create-routes-layer-with-csv-file:-1.0.2">Create routes layer with csv file:</a></span></li><li><span><a href="#Create-depots-layer-with-csv-file:" data-toc-modified-id="Create-depots-layer-with-csv-file:-1.0.3">Create depots layer with csv file:</a></span></li><li><span><a href="#Draw-the-depots-and-orders-in-map." data-toc-modified-id="Draw-the-depots-and-orders-in-map.-1.0.4">Draw the <code>depots</code> and <code>orders</code> in map.</a></span></li><li><span><a href="#Create-depots-layer-by-geocoding-the-location" data-toc-modified-id="Create-depots-layer-by-geocoding-the-location-1.0.5">Create depots layer by geocoding the location</a></span></li><li><span><a href="#Create-routes-layer-with-JSON-file" data-toc-modified-id="Create-routes-layer-with-JSON-file-1.0.6">Create routes layer with JSON file</a></span></li></ul></li><li><span><a href="#Solve-VRP" data-toc-modified-id="Solve-VRP-1.1">Solve VRP</a></span></li><li><span><a href="#Result" data-toc-modified-id="Result-1.2">Result</a></span></li><li><span><a href="#Conclusion" data-toc-modified-id="Conclusion-1.3">Conclusion</a></span></li></ul></li></ul></div>
The network module of the ArcGIS API for Python can be used to solve different types of network analysis operations. For example, an appliance delivery company wants to serve multiple customers in a day using several delivery drivers, a health inspection company needs to schedule inspection visits for the inspectors. The problem that is common to these examples is called vehicle routing problem (VRP). Each such problem requires to determine which orders should be serviced by which vehicle/driver and in what sequence, so the total operating cost is minimized and the routes are operational. In addition, the VRP solver can solve more specific problems because numerous options are available, such as matching vehicle capacities with order quantities, giving breaks to drivers, and pairing orders so they are serviced by the same route.
In this sample, we find a solution for an appliance delivery company to find routes for two vehicles which start from the warehouse and return to the same, at the end of the working day. We will find optimized routes given a set of orders to serve and a set of vehicles with constraints. All we need to do is pass in the `depot` locations, `route` (vehicle/driver) details, the `order` locations, and specify additional properties for `orders`. The VRP service will return `routes` with directions. Once you have the results, you can add the `routes` to a map, display the turn-by-turn directions, or integrate them further into your application. To learn more about the capabilities of the routing and directions services, please visit the [documentation](http://desktop.arcgis.com/en/arcmap/latest/extensions/network-analyst/vehicle-routing-problem.htm#).
**Note** :If you run the tutorial using ArcGIS Online, 2 [credits](http://pro.arcgis.com/en/pro-app/tool-reference/appendices/geoprocessing-tools-that-use-credits.htm#ESRI_SECTION2_5FAF16DB9F044F78AF164A22752A9A7F) will be consumed.
As a first step, let's import required libraries and establish a connection to your organization which could be an ArcGIS Online organization or an ArcGIS Enterprise. If you dont have an ArcGIS account, [get ArcGIS Trial](https://www.esri.com/en-us/arcgis/trial).
```
import arcgis
from arcgis.gis import GIS
import pandas as pd
import datetime
import getpass
from IPython.display import HTML
from arcgis import geocoding
from arcgis.features import Feature, FeatureSet
from arcgis.features import GeoAccessor, GeoSeriesAccessor
my_gis = GIS('home')
```
To solve the Vehicle Routing Problem, we need `orders` layer with stop information, `depots` layer with the warehouse location information from where the routes start and `routes` table with constraints on routes like maximum total time the driver can work etc.
To provide this information to the service, different types of inputs are supported as listed below:
- Csv file
- Address information to geocode or reverse geocode
- Json file with attribute names and values
Let us see how to get the layer from each of these input types.
### Create orders layer with csv file:
Use this parameter to specify the orders the routes should visit. An order can represent a delivery (for example, furniture delivery), a pickup (such as an airport shuttle bus picking up a passenger), or some type of service or inspection (a tree trimming job or building inspection, for instance). When specifying the orders, you can specify additional properties for orders using attributes, such as their names, service times, time windows, pickup or delivery quantities etc.
Orders csv file has an `Address` column. So, we convert orders csv to a SpatialDataFrame using the address values to geocode order locations.To perform the geocode operations, we imported the geocoding module of the ArcGIS API.
```
orders_csv = "data/orders.csv"
# Read the csv file and convert the data to feature set
orders_df = pd.read_csv(orders_csv)
orders_sdf = pd.DataFrame.spatial.from_df(orders_df, "Address")
orders_fset = orders_sdf.spatial.to_featureset()
orders_sdf.head(3)
```
### Create routes layer with csv file:
A route specifies vehicle and driver characteristics. A route can have start and end depot service times, a fixed or flexible starting time, time-based operating costs, distance-based operating costs, multiple capacities, various constraints on a driver’s workday, and so on. When specifying the routes, you can set properties for each one by using attributes. Attributes in the csv are explained below.
`Name`- The name of the route
`StartDepotName`- The name of the starting depot for the route. This field is a foreign key to the Name field in Depots.
`EndDepotName`- The name of the ending depot for the route. This field is a foreign key to the Name field in the Depots class.
`EarliestStartTime`- The earliest allowable starting time for the route.
`LatestStartTime`- The latest allowable starting time for the route.
`Capacities`- The maximum capacity of the vehicle.
`CostPerUnitTime`- The monetary cost incurred per unit of work time, for the total route duration, including travel times as well as service times and wait times at orders, depots, and breaks.
`MaxOrderCount`- The maximum allowable number of orders on the route.
`MaxTotalTime`- The maximum allowable route duration.
`AssignmentRule`- This field specifies the rule for assigning the order to a route for example, Exclude, Preserve route, Preserve rooute with relative sequence, override etc, please read [documentation](https://esri.github.io/arcgis-python-api/apidoc/html/arcgis.network.analysis.html#solve-vehicle-routing-problem) for more details.
To get a featureset from dataframe, we convert the CSV to a pandas data frame using read_csv function. Note that in our CSV, `EarliestStartTime` and `LatestStartTime` values are represented as strings denoting time in the local time zone of the computer. So we need to parse these values as date-time values which we accomplish by specifying to_datetime function as the datetime parser.
When calling `arcgis.network.analysis.solve_vehicle_routing_problem` function we need to pass the datetime values in milliseconds since epoch. The `routes_df` dataframe stores these values as datetime type. We convert from datetime to int64 datatype which stores the values in nano seconds. We then convert those to milliseconds.
```
routes_csv = "data/routes.csv"
# Read the csv file
routes_df = pd.read_csv(routes_csv, parse_dates=["EarliestStartTime", "LatestStartTime"], date_parser=pd.to_datetime)
routes_df["EarliestStartTime"] = routes_df["EarliestStartTime"].astype("int64") / 10 ** 6
routes_df["LatestStartTime"] = routes_df["LatestStartTime"].astype("int64") / 10 ** 6
routes_fset = arcgis.features.FeatureSet.from_dataframe(routes_df)
routes_df
```
### Create depots layer with csv file:
Use this parameter to specify a location that a vehicle departs from at the beginning of its workday and returns to, at the end of the workday. Vehicles are loaded (for deliveries) or unloaded (for pickups) at depots at the start of the route.
Depots CSV file has depot locations in columns called `Latitude` (representing Y values) and `Longitude` (representing X values). So, we convert depots CSV to a SpatialDataFrame using the X and Y values. We need to reverse geocode these locations as these are provided in latitude/longitude format. Depots must have `Name` values because the `StartDepotName` and `EndDepotName` attributes of the `routes` parameter reference the names you specify here.
```
depots_csv = "data/depots.csv"
# Read the csv file and convert the data to feature set
depots_df = pd.read_csv(depots_csv)
depots_sdf = pd.DataFrame.spatial.from_xy(depots_df, "Longitude", "Latitude")
depots_sdf = depots_sdf.drop(axis=1, labels=["Longitude", "Latitude"])
depots_fset = depots_sdf.spatial.to_featureset()
depots_sdf
```
### Draw the `depots` and `orders` in map.
To visualize the `orders` and `depots` layer in the map, create a map as done below. The layer can also be drawn with suitable symbol, size and color with draw service in map. The green dots represent stops location to service and the orange square represents the depot from where `routes` should start.
```
# Create a map instance to visualize inputs in map
map_view_inputs = my_gis.map('San Fransisco, United States', zoomlevel=10)
map_view_inputs
# Visualize order and depot locations with symbology
map_view_inputs.draw(orders_fset, symbol={"type": "esriSMS","style": "esriSMSCircle","color": [76,115,0,255],"size": 8})
map_view_inputs.draw(depots_fset, symbol={"type": "esriSMS","style": "esriSMSSquare","color": [255,115,0,255], "size": 10})
```
Alternatively, if the input data is provided in different formats, we could still create layers from those data. In practice, there might not always be csv files for all the inputs. It could be just a list of addresses or the inputs are feed from an automated script or server output in JSON format from REST API.
Let's see how to convert each of input type to featureset to provide as input directly to the VRP service.
### Create depots layer by geocoding the location
If we know address of depot, we would geocode the address to get the feature set to input that to the VRP solver as follows.
```
depot_geocoded_fs = geocoding.geocode("2-98 Pier 1, San Francisco, California, 94111",
as_featureset=True, max_locations=1)
depot_geocoded_fs.sdf
```
### Create routes layer with JSON file
If we have json files for inputs, without needing to parse it, we could feed that to from_json service of FeatureSet and we would get feature set to input to the [VRP service](https://developers.arcgis.com/rest/network/api-reference/vehicle-routing-problem-service.htm#ESRI_SECTION3_E65DBEE0F0BF46EB946A63A2537137C5).
```
import json
with open("data/Routes_fset.json") as f:
df1 = json.load(f)
routes_string = json.dumps(df1)
routes_fset2 = FeatureSet.from_json(routes_string)
routes_fset2
routes_string
```
## Solve VRP
Once you have all the inputs as featuresets, you can pass inputs converted from different formats. For example, depot could be a featureset geocoded from address, `orders` and `routes` could be read from csv files to convert to featureset. As result to the solve, we get routes with geometry. If we need driving directions for navigation, `populate_directions` must be set to true.
```
%%time
today = datetime.datetime.now()
from arcgis.network.analysis import solve_vehicle_routing_problem
results = solve_vehicle_routing_problem(orders= orders_fset,
depots = depots_fset,
routes = routes_fset,
save_route_data='true',
populate_directions='true',
travel_mode="Driving Time",
default_date=today)
print('Analysis succeeded? {}'.format(results.solve_succeeded))
```
## Result
Let's have a look at the output routes in the dataframe. Description about the fields returned for each route can be read in the [documentation](https://developers.arcgis.com/rest/network/api-reference/vehicle-routing-problem-service.htm#ESRI_SECTION3_E65DBEE0F0BF46EB946A63A2537137C5). Some fields shown in the output are:
`Name`- The name of the route.
`OrderCount`- The number of orders assigned to the route.
`StartTime`- The starting time of the route.
`EndTime`- The ending time of the route.
`StartTimeUTC`- The start time of the route in UTC time.
`EndTimeUTC`- The end time of the route in UTC time.
`TotalCost`- The total operating cost of the route, which is the sum of the following attribute values: FixedCost, RegularTimeCost, OvertimeCost, and DistanceCost.
`TotalDistance`- The total travel distance for the route.
`TotalTime`- The total route duration.
`TotalTravelTime`- The total travel time for the route.
The time values returned from VRP service are in milliseconds from epoch, we need to convert those to datetime format. From the output table, Route1 starts at 8 am, the total time duration for the route is 126 minutes and the total distance for the route is around 60 miles and Route1 services 4 orders.
```
# Display the output routes in a pandas dataframe.
out_routes_df = results.out_routes.sdf
out_routes_df[['Name','OrderCount','StartTime','EndTime','TotalCost','TotalDistance','TotalTime','TotalTravelTime','StartTimeUTC','EndTimeUTC']]
```
The information about stops sequence and which routes will service the stops, let's read out_stops output table. Relevant attributes from the table are:
`Name`- The name of the stop.
`RouteName`- The name of the route that makes the stop.
`Sequence`- The relative sequence in which the assigned route visits the stop.
`ArriveTime`- The time of day when the route arrives at the stop. The time-of-day value for this attribute is in the time zone in which the stop is located.
`DepartTime`- The time of day when the route departs from the stop. The time-of-day value for this attribute is in the time zone in which the stop is located.
Similar to routes table, it has time values in milliseconds from epoch, we will convert those values to date time format.
In the table, Route1 starts at 2019-01-17 08:00:00.000 from Warehouse, and arrives at the stop 6 located at '10264 San Pablo Ave, El Cerrito, CA 94530', at 2019-02-01 08:28 local time.
```
out_stops_df = results.out_stops.sdf
out_stops_df[['Name','RouteName','Sequence','ArriveTime','DepartTime']].sort_values(by=['RouteName',
'Sequence'])
```
Now, let us visualize the results on a map.
```
# Create a map instance to visualize outputs in map
map_view_outputs = my_gis.map('San Fransisco, United States', zoomlevel=10)
map_view_outputs
#Visusalize the inputsn with different symbols
map_view_outputs.draw(orders_fset, symbol={"type": "esriSMS",
"style": "esriSMSCircle",
"color": [76,115,0,255],"size": 8})
map_view_outputs.draw(depots_fset, symbol={"type": "esriSMS",
"style": "esriSMSSquare",
"color": [255,115,0,255], "size": 10})
#Visualize the first route
out_routes_flist = []
out_routes_flist.append(results.out_routes.features[0])
out_routes_fset = []
out_routes_fset = FeatureSet(out_routes_flist)
map_view_outputs.draw(out_routes_fset,
symbol={"type": "esriSLS",
"style": "esriSLSSolid",
"color": [0,100,240,255],"size":10})
#Visualize the second route
out_routes_flist = []
out_routes_flist.append(results.out_routes.features[1])
out_routes_fset = []
out_routes_fset = FeatureSet(out_routes_flist)
map_view_outputs.draw(out_routes_fset,
symbol={"type": "esriSLS",
"style": "esriSLSSolid",
"color": [255,0,0,255],"size":10})
```
Save the route data from result to local disk, which would then be used to upload to online portal to share with drivers eventually and share the routes in ArcGIS online on the portal. Individual routes are saved as route layers which could then be opened in navigator with directions(if you solve with 'populate_directions'=true')
```
route_data = results.out_route_data.download('.')
route_data
route_data_item = my_gis.content.add({"type": "File Geodatabase"}, route_data)
route_data_item
```
Create route layers from the route data. This will create route layers in the online portal which could then be shared with drivers, so they would be able to open this in navigator.
```
route_layers = arcgis.features.analysis.create_route_layers(route_data_item,
delete_route_data_item=True)
for route_layer in route_layers:
route_layer.share(org=True)
display(route_layer.homepage)
display(route_layer)
```
## Conclusion
The network module of the ArcGIS API for Python allows you to solve a Vehicle Routing Problem and other network problems with necessary business constraints. Learn more about how to solve VRP with business constraints [here](https://esri.github.io/arcgis-python-api/apidoc/html/arcgis.network.analysis.html#solve-vehicle-routing-problem).
| github_jupyter |
K-nearest neighbors classifier (KNN) is a simple and powerful classification learner.
KNN has three basic parts:
- $y\_i$: The class of an observation (what we are trying to predict in the test data).
- $X\_i$: The predictors/IVs/attributes of an observation.
- $K$: A positive number specified by the researcher. K denotes the number of observations closest to a particular observation that define its "neighborhood". For example, K=2 means that each observation's has a neighorhood comprising of the two other observations closest to it.
Imagine we have an observation where we know its independent variables $x\_{test}$ but do not know its class $y\_{test}$. The KNN learner finds the K other observations that are closest to $x\_{test}$ and uses their known classes to assign a classes to $\_{test}$.
## Preliminaries
```
import pandas as pd
from sklearn import neighbors
import numpy as np
%matplotlib inline
import seaborn
```
## Create Dataset
Here we create three variables, `test_1` and `test_2` are our independent variables, 'outcome' is our dependent variable. We will use this data to train our learner.
```
training_data = pd.DataFrame()
training_data['test_1'] = [0.3051,0.4949,0.6974,0.3769,0.2231,0.341,0.4436,0.5897,0.6308,0.5]
training_data['test_2'] = [0.5846,0.2654,0.2615,0.4538,0.4615,0.8308,0.4962,0.3269,0.5346,0.6731]
training_data['outcome'] = ['win','win','win','win','win','loss','loss','loss','loss','loss']
training_data.head()
```
## Plot the data
This is not necessary, but because we only have three variables, we can plot the training dataset. The X and Y axes are the independent variables, while the colors of the points are their classes.
```
seaborn.lmplot('test_1', 'test_2', data=training_data, fit_reg=False,hue="outcome", scatter_kws={"marker": "D","s": 100})
```
## Convert Data Into np.arrays
The `scikit-learn` library requires the data be formatted as a `numpy` array. Here are doing that reformatting.
```
X = training_data.as_matrix(columns=['test_1', 'test_2'])
y = np.array(training_data['outcome'])
```
## Train The Learner
This is our big moment. We train a KNN learner using the parameters that an observation's neighborhood is its three closest neighors. `weights = 'uniform'` can be thought of as the voting system used. For example, `uniform` means that all neighbors get an equally weighted "vote" about an observation's class while `weights = 'distance'` would tell the learner to weigh each observation's "vote" by its distance from the observation we are classifying.
```
clf = neighbors.KNeighborsClassifier(3, weights = 'uniform')
trained_model = clf.fit(X, y)
```
## View The Model's Score
How good is our trained model compared to our training data?
```
trained_model.score(X, y)
```
Our model is 80% accurate!
_Note: that in any real world example we'd want to compare the trained model to some holdout test data. But since this is a toy example I used the training data_.
## Apply The Learner To A New Data Point
Now that we have trained our model, we can predict the class any new observation, $y_{test}$. Let us do that now!
```
# Create a new observation with the value of the first independent variable, 'test_1', as .4
# and the second independent variable, test_1', as .6
x_test = np.array([[.4,.6]])
# Apply the learner to the new, unclassified observation.
trained_model.predict(x_test)
```
Huzzah! We can see that the learner has predicted that the new observation's class is `loss`.
We can even look at the probabilities the learner assigned to each class:
```
trained_model.predict_proba(x_test)
```
According to this result, the model predicted that the observation was `loss` with a ~67% probability and `win` with a ~33% probability. Because the observation had a greater probability of being `loss`, it predicted that class for the observation.
## Notes
- The choice of K has major affects on the classifer created.
- The greater the K, more linear (high bias and low variance) the decision boundary.
- There are a variety of ways to measure distance, two popular being simple euclidean distance and cosine similarity.
| github_jupyter |
```
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers, losses
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras.models import Model
# Read and downsize dataset to reduce computation
dataframe = pd.read_csv("./credit_card_dataset.csv")
dataframe = dataframe.sample(120000, random_state=1234)
dataframe.head(10)
# dataframe_features = dataframe.drop(columns="Class")
# feature_size = len(dataframe.columns)-1
# raw_data = dataframe_features.values
# normal_dataframe = dataframe[dataframe["Class"]==0]
# outliers_dataframe = dataframe[dataframe["Class"]==1]
# Select the top n features
data_norm = MinMaxScaler().fit_transform(dataframe.values)
n = 10
selector = SelectKBest(chi2, k=n)
data_new = selector.fit_transform(data_norm, dataframe["Class"])
feature_support = selector.get_support()
selected_features = dataframe.loc[:,feature_support].columns
# Prepare transformed dataset with reduced features as dataframe
reduced_df = pd.DataFrame(data = data_new, columns = selected_features)
# Prepare dataset for autoencoder
raw_data = reduced_df.values
feature_size = len(selected_features)-1
# The last column contains the labels
labels = raw_data[:, -1]
# The other columns consist of selected features
data = raw_data[:, 0:-1]
# Train test split
train_data, test_data, train_labels, test_labels = train_test_split(data, labels, test_size=0.2, random_state=7)
train_data = tf.cast(train_data, tf.float32)
test_data = tf.cast(test_data, tf.float32)
# Differentiate between normal and anomalous datasets
train_labels = train_labels.astype(bool)
test_labels = test_labels.astype(bool)
normal_train_data = train_data[~train_labels]
normal_test_data = test_data[~test_labels]
anomalous_train_data = train_data[train_labels]
anomalous_test_data = test_data[test_labels]
# Define an anomaly detector model as an autoencoder
class AnomalyDetector(Model):
def __init__(self):
super(AnomalyDetector, self).__init__()
self.encoder = tf.keras.Sequential([
layers.Dense(64, activation="relu"),
layers.Dense(32, activation="relu"),
layers.Dense(16, activation="relu"),
layers.Dense(8, activation="relu")])
self.decoder = tf.keras.Sequential([
layers.Dense(8, activation="relu"),
layers.Dense(16, activation="relu"),
layers.Dense(32, activation="relu"),
layers.Dense(64, activation="relu"),
layers.Dense(feature_size, activation="sigmoid")])
def call(self, x):
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded
autoencoder = AnomalyDetector()
autoencoder.compile(optimizer='adam', loss='MAE')
# Train the autoencoder on the normal dataset
history = autoencoder.fit(normal_train_data, normal_train_data,
epochs=20,
batch_size=32,
validation_data=(normal_test_data, normal_test_data),
shuffle=True)
plt.plot(history.history["loss"], label="Training Loss")
plt.plot(history.history["val_loss"], label="Validation Loss")
plt.legend()
# Compute reconstruction error of normal test data
reconstructions = autoencoder.predict(normal_test_data)
train_loss = tf.keras.losses.MAE(reconstructions, normal_test_data)
# Initial ansatz for threshold
threshold = np.mean(train_loss) + np.std(train_loss)
print("Threshold: ", threshold)
# Compute reconstruction error of anomalous test data
reconstructions = autoencoder.predict(anomalous_test_data)
test_loss = tf.keras.losses.MAE(reconstructions, anomalous_test_data)
plt.hist(test_loss, bins=50)
plt.xlabel("Test loss")
plt.ylabel("No of examples")
plt.show()
def predict(model, data, threshold):
reconstructions = model(data)
loss = tf.keras.losses.MAE(reconstructions, data)
return tf.math.less(loss, threshold)
def print_stats(predictions, labels):
print("Accuracy = {}".format(accuracy_score(labels, preds)))
print("Precision = {}".format(precision_score(labels, preds)))
print("Recall = {}".format(recall_score(labels, preds)))
# Evaluate performance
preds = predict(autoencoder, test_data, threshold)
print_stats(preds, test_labels)
# Evaluate performance based on a different threshold
preds = predict(autoencoder, test_data, threshold/10)
print_stats(preds, test_labels)
# Select the top two features for visualization
feature_size = len(dataframe.columns)-1
outliers_df = dataframe[dataframe["Class"]==1]
X1 = dataframe[selected_features[0]]
X2 = dataframe[selected_features[1]]
Y1 = outliers_df[selected_features[0]]
Y2 = outliers_df[selected_features[1]]
# Plot all data points according to the top two selected features
plt.figure(figsize=(15, 5), dpi=80, facecolor='w', edgecolor='k')
plt.title("Dataset reduced from " + str(feature_size) + "D to 2D")
plt.scatter(X1, X2,
color="g",
s=3,
label="Data points")
# Plot red circles around outliers in the dataset according to ground truth
plt.scatter(Y1, Y2,
s=30,
edgecolors="r",
facecolors="none",
label="Outliers")
plt.axis("tight")
plt.xlim((1.1*min(X1), 1.1*max(X1)))
plt.xlabel("Feature no. 1: " + selected_features[0])
plt.ylim((1.1*min(X2), 1.5*max(X2)))
plt.ylabel("Feature no. 2: " + selected_features[1])
legend = plt.legend(loc="upper left")
legend.legendHandles[0]._sizes = [10]
legend.legendHandles[1]._sizes = [20]
plt.show()
```
The data points that are within the dense cluster and yet marked as outliers are possibly outliers along some other dimensions. We have plotted the data points according to the top two most relevant features.
| github_jupyter |
# How to do Semantic Segmentation using Deep learning

Nowadays, semantic segmentation is one of the key problems in the field of computer vision.
Looking at the big picture, semantic segmentation is one of the high-level task that paves the way towards complete scene understanding.
The importance of scene understanding as a core computer vision problem is highlighted by the fact that an increasing number of applications nourish from inferring knowledge from imagery.
Some of those applications include self-driving vehicles, human-computer interaction, virtual reality etc.
With the popularity of deep learning in recent years, many semantic segmentation problems are being tackled using deep architectures, most often Convolutional Neural Nets, which surpass other approaches by a large margin in terms of accuracy and efficiency.
Semantic segmentation is a natural step in the progression from coarse to fine inference:
More specifically, the goal of semantic image segmentation is to label each pixel of an image with a corresponding class of what is being represented. Because we're predicting for every pixel in the image, this task is commonly referred to as dense prediction.

#### Diff networks?
It is also worthy to review some standard deep networks that have made significant contributions to the field of computer vision, as they are often used as the basis of semantic segmentation systems:
* AlexNet: Toronto’s pioneering deep CNN that won the 2012 ImageNet competition with a test accuracy of 84.6%. It consists of 5 convolutional layers, max-pooling ones, ReLUs as non-linearities, 3 fully-convolutional layers, and dropout.
* VGG-16: This Oxford’s model won the 2013 ImageNet competition with 92.7% accuracy. It uses a stack of convolution layers with small receptive fields in the first layers instead of few layers with big receptive fields.
* GoogLeNet: This Google’s network won the 2014 ImageNet competition with accuracy of 93.3%. It is composed by 22 layers and a newly introduced building block called inception module. The module consists of a Network-in-Network layer, a pooling operation, a large-sized convolution layer, and small-sized convolution layer.
* ResNet: This Microsoft’s model won the 2016 ImageNet competition with 96.4 % accuracy. It is well-known due to its depth (152 layers) and the introduction of residual blocks. The residual blocks address the problem of training a really deep architecture by introducing identity skip connections so that layers can copy their inputs to the next layer.
One important thing to note is that we're not separating instances of the same class; we only care about the category of each pixel. In other words, if you have two objects of the same category in your input image, the segmentation map does not inherently distinguish these as separate objects. There exists a different class of models, known as instance segmentation models, which do distinguish between separate objects of the same class.
Segmentation models are useful for a variety of tasks, including:
#### Autonomous vehicles
* We need to equip cars with the necessary perception to understand their environment so that self-driving cars can safely integrate into our existing roads.

__Medical image diagnostics__
* Machines can augment analysis performed by radiologists, greatly reducing the time required to run diagnositic tests.

## Representing the task
Simply, our goal is to take either a RGB color image (height×width×3) or a grayscale image (height×width×1) and output a segmentation map where each pixel contains a class label represented as an integer (height×width×1).

Note: For visual clarity, I've labeled a low-resolution prediction map. In reality, the segmentation label resolution should match the original input's resolution.
Similar to how we treat standard categorical values, we'll create our target by one-hot encoding the class labels - essentially creating an output channel for each of the possible classes.

A prediction can be collapsed into a segmentation map (as shown in the first image) by taking the argmax of each depth-wise pixel vector.
We can easily inspect a target by overlaying it onto the observation.

## Constructing an architecture
A naive approach towards constructing a neural network architecture for this task is to simply stack a number of convolutional layers (with same padding to preserve dimensions) and output a final segmentation map. This directly learns a mapping from the input image to its corresponding segmentation through the successive transformation of feature mappings; however, it's quite computationally expensive to preserve the full resolution throughout the network.

Recall that for deep convolutional networks, earlier layers tend to learn low-level concepts while later layers develop more high-level (and specialized) feature mappings. In order to maintain expressiveness, we typically need to increase the number of feature maps (channels) as we get deeper in the network.
This didn't necessarily pose a problem for the task of image classification, because for that task we only care about what the image contains (and not where it is located). Thus, we could alleviate computational burden by periodically downsampling our feature maps through pooling or strided convolutions (ie. compressing the spatial resolution) without concern. However, for image segmentation, we would like our model to produce a full-resolution semantic prediction.
One popular approach for image segmentation models is to follow an encoder/decoder structure where we downsample the spatial resolution of the input, developing lower-resolution feature mappings which are learned to be highly efficient at discriminating between classes, and the upsample the feature representations into a full-resolution segmentation map.
Encoder
• Takes an input image
and generates a
high-dimensional
feature vector
• Aggregate features
at multiple levels
Decoder
• Takes a highdimensional
feature
vector and generates
a semantic
segmentation mask
• Decode features
aggregated by
encoder at multiple
levels

# Methods for upsampling
There are a few different approaches that we can use to upsample the resolution of a feature map. Whereas pooling operations downsample the resolution by summarizing a local area with a single value (ie. average or max pooling), "unpooling" operations upsample the resolution by distributing a single value into a higher resolution.

However, transpose convolutions are by far the most popular approach as they allow for us to develop a learned upsampling.

### What is a transpose convolution?
Whereas a typical convolution operation will take the dot product of the values currently in the filter's view and produce a single value for the corresponding output position, a transpose convolution essentially does the opposite. For a transpose convolution, we take a single value from the low-resolution feature map and multiply all of the weights in our filter by this value, projecting those weighted values into the output feature map.

## Fully convolutional neural networks
The approach of using a "fully convolutional" network trained end-to-end, pixels-to-pixels for the task of image segmentation was introduced by Long et al. in late 2014. The paper's authors propose adapting existing, well-studied image classification networks (eg. AlexNet) to serve as the encoder module of the network, appending a decoder module with transpose convolutional layers to upsample the coarse feature maps into a full-resolution segmentation map.

The full network, as shown below, is trained according to a pixel-wise cross entropy loss.

However, because the encoder module reduces the resolution of the input by a factor of 32, the decoder module struggles to produce fine-grained segmentations (as shown below).

The authors address this tension by slowly upsampling (in stages) the encoded representation, adding "skip connections" from earlier layers, and summing these two feature maps.

These skip connections from earlier layers in the network (prior to a downsampling operation) should provide the necessary detail in order to reconstruct accurate shapes for segmentation boundaries. Indeed, we can recover more fine-grain detail with the addition of these skip connections.

We can use the U-Net architecture which "consists of a contracting path to capture context and a symmetric expanding path that enables precise localization." This simpler architecture has grown to be very popular and has been adapted for a variety of segmentation problems.

The standard U-Net model consists of a series of convolution operations for each "block" in the architecture. There exist a number of more advanced "blocks" that can be substituted in for stacked convolutional layers.
We can swap out the basic stacked convolution blocks in favor of residual blocks. This residual block introduces short skip connections (within the block) alongside the existing long skip connections (between the corresponding feature maps of encoder and decoder modules) found in the standard U-Net structure. They report that the short skip connections allow for faster convergence when training and allow for deeper models to be trained.
Expanding on this, Jegou et al. proposed the use of dense blocks, still following a U-Net structure, arguing that the "characteristics of DenseNets make them a very good fit for semantic segmentation as theynaturally induce skip connections and multi-scale supervision." These dense blocks are useful as they carry low level features from previous layers directly alongside higher level features from more recent layers, allowing for highly efficient feature reuse.

One very important aspect of this architecture is the fact that the upsampling path does not have a skip connection between the input and output of a dense block. The authors note that because the "upsampling path increases the feature maps spatial resolution, the linear growth in the number of features would be too memory demanding." Thus, only the output of a dense block is passed along in the decoder module.

Defining a loss function
The most commonly used loss function for the task of image segmentation is a pixel-wise cross entropy loss. This loss examines each pixel individually, comparing the class predictions (depth-wise pixel vector) to our one-hot encoded target vector.

Because the cross entropy loss evaluates the class predictions for each pixel vector individually and then averages over all pixels, we're essentially asserting equal learning to each pixel in the image. This can be a problem if your various classes have unbalanced representation in the image, as training can be dominated by the most prevalent class.
Let's try a loss weighting scheme for each pixel such that there is a higher weight at the border of segmented objects.
This penalizes bad border segmentation, and not pixels which are at the inside of a class.

Another popular loss function for image segmentation tasks is based on the Dice coefficient, which is essentially a measure of overlap between two samples. This measure ranges from 0 to 1 where a Dice coefficient of 1 denotes perfect and complete overlap. The Dice coefficient was originally developed for binary data, and can be calculated as:
Dice=
(2|A∩B|) /
(|A|+|B|)
where |A∩B| represents the common elements between sets A and B, and |A| represents the number of elements in set A (and likewise for set B).
For the case of evaluating a Dice coefficient on predicted segmentation masks, we can approximate |A∩B| as the element-wise multiplication between the prediction and target mask, and then sum the resulting matrix.

Because our target mask is binary, we effectively zero-out any pixels from our prediction which are not "activated" in the target mask. For the remaining pixels, we are essentially penalizing low-confidence predictions; a higher value for this expression, which is in the numerator, leads to a better Dice coefficient.
In order to quantify |A| and |B|, some researchers use the simple sum whereas other researchers prefer to use the squared sum for this calculation. I don't have the practical experience to know which performs better empirically over a wide range of tasks, so I'll leave you to try them both and see which works better.
| github_jupyter |
```
#### Imports ####
# Install a pip package in the current Jupyter kernel
import sys
!{sys.executable} -m pip install causality
# Install a pip package in the current Jupyter kernel
import sys
!{sys.executable} -m pip install pandas
!{sys.executable} -m pip install decorator>=4.1.2
!{sys.executable} -m pip install networkx>=2.0
!{sys.executable} -m pip install numpy>=1.13.3
!{sys.executable} -m pip install pandas>=0.20.3
!{sys.executable} -m pip install patsy>=0.4.1
!{sys.executable} -m pip install python-dateutil>=2.6.1
!{sys.executable} -m pip install pytz>=2017.2
!{sys.executable} -m pip install scipy>=0.19.1
!{sys.executable} -m pip install six>=1.11.0
!{sys.executable} -m pip install statsmodels>=0.8.0
!{sys.executable} -m pip install networkx
!{sys.executable} -m pip install matplotlib
!{sys.executable} -m pip install pycm
# causality imports
# IC Algorithm Tutorial: https://pypi.org/project/causality/
import numpy
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import time
from causality.inference.search import IC
from causality.inference.independence_tests import RobustRegressionTest
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score
from sklearn.metrics import precision_recall_curve, roc_curve, auc, average_precision_score
from sklearn.metrics import confusion_matrix
from pycm import *
print('causality packages imported successfully')
import os
directory = '/Users/yaminimathur/Desktop/COM S 673 Project/Data without noise'
df_index = []
time_df = pd.DataFrame(columns=['Time Taken'], index = index_df_IC)
for filename in os.listdir(directory):
if('Yeast' in filename or 'Ecoli' in filename):
directory = directory+filename
split_filename = (filename.split('-'))
print(split_filename)
if(split_filename[2] in ['null','nonoise']):
type = split_filename[3].split('.')
split_mix = split_filename[2]+'-'+type[0]
else:
type = split_filename[2].split('.')
split_mix = type[0]
df_index.append(split_filename[1]+'-'+split_mix)
df_columns = ['Accuracy']
print(df_index)
result_df = pd.DataFrame(columns=df_columns, index=df_index)
time_df = pd.DataFrame(columns=['Time Taken'], index = df_index)
result_df
time_df
import numpy as np
header_dct = {'G1': 'c', 'G2': 'c', 'G3': 'c', 'G4': 'c', 'G5': 'c', 'G6': 'c', 'G7': 'c', 'G8': 'c', 'G9': 'c', 'G10': 'c'}
def print_theta_accuracy(standardnw_path,dataset_path):
acc_value = []
data = pd.read_csv(dataset_path, sep='\t')
data = data.iloc[: , 1:]
benchmark_network = pd.read_csv(standardnw_path, sep='\t', header=None)
benchmark_network = benchmark_network.loc[benchmark_network[2] == 1]
benchmark_graph = nx.Graph()
for i in (1,10):
benchmark_graph.add_node('G'+str(i))
for row in range(0,benchmark_network.shape[0]):
benchmark_graph.add_edge(benchmark_network[0][row], benchmark_network[1][row])
benchmark_adjMatrix = nx.adjacency_matrix(benchmark_graph)
# Check time Elapsed for IC Algorithm to run
# Time in seconds
start = time.time()
# run the IC search
ic_algorithm = IC(RobustRegressionTest)
predicted_graph = ic_algorithm.search(data, header_dct)
end = time.time()
# print(end - start)
time_elapsed = end - start
# time_list.append(time_elapsed)
predicted_adjMatrix = nx.adjacency_matrix(predicted_graph)
y_test = benchmark_adjMatrix.todense().flatten()
y_pred = predicted_adjMatrix.todense().flatten()
y_pred = np.asarray(y_pred)
y_test = np.asarray(y_test)
y_pred = y_pred.reshape(y_pred.shape[1],)
y_test = y_test.reshape(y_test.shape[1],)
cm = ConfusionMatrix(y_test, y_pred)
# acc_list.append(cm.ACC_Macro)
return time_elapsed,cm.ACC_Macro;
directory = '/Users/yaminimathur/Desktop/COM S 673 Project/Data without noise/'
goldstandard = '/Users/yaminimathur/Desktop/COM S 673 Project/DREAM3 gold standards/'
df_columns = ['accuracy','timetaken']
df_index = os.listdir(directory)
filename_df = []
#result_df = pd.DataFrame(columns = df_columns, index = filename_df)
result_df = pd.DataFrame(columns = df_columns, index= df_index)
for filename in os.listdir(directory):
data_path = directory+filename
filename_temp = filename
split_filename = (filename_temp.split('-'))
if(split_filename[2] == 'null'):
type = split_filename[3].split('.')
else:
type = split_filename[2].split('.')
split_mix = type[0]
print(filename_temp, split_filename)
index_location = split_filename[1]+'-'+split_mix
print(split_filename[1]+'-'+split_filename[2]+'-'+split_filename[3])
filename_df = split_filename[1]+'-'+split_filename[2]+'-'+split_filename[3]
print(filename_df)
goldstandardname = ('DREAM3GoldStandard_'+split_filename[0]+'_'+split_filename[1]+'.txt')
goldstandard_path = goldstandard+goldstandardname
time_value, acc_value = print_theta_accuracy(goldstandard_path, data_path)
print(filename+':')
print(time_value, acc_value)
print()
result_df['accuracy'][filename] = acc_value
result_df['timetaken'][filename] = time_value
result_df
```
| github_jupyter |
# ContrastiveExplanation
This file contains a Notebook for example usage of the `ContrastiveExplanation` Python script, so that you can familiarize yourself with the usage flow and showcasing the package functionalities. It contains three examples, two for explaining classification problems and one for explaining a regression analysis problem.
###### Contents
1. [Classification (continuous features)](#classification-1)
2. [Classification (Pandas DataFrame, categorical features) ](#classification-2)
3. [Regression](#regression-1)
---
Before we proceed, let us set a seed for reproducibility, and import packages.
```
import numpy as np
import pandas as pd
import os.path
import urllib.request
import pprint
from sklearn import datasets, model_selection, ensemble, metrics, pipeline, preprocessing
SEED = np.random.RandomState(1994)
```
For printing out the features and their corresponding values of an instance we define a function `print_sample()`:
```
def print_sample(feature_names, sample):
print('\n'.join(f'{name}: {value}' for name, value in zip(feature_names, sample)))
```
---
## 1. Classification (continuous features) <a name="classification-1"></a>
First, for classification we use the [Iris](https://archive.ics.uci.edu/ml/datasets/iris) data set (as also used in the example of `README.md`). We first load the data set (and print its characteristics), then train an ML model on the data, and finally explain an instance predicted using the model.
#### 1.1 Data set characteristics
```
data = datasets.load_iris()
print(data['DESCR'])
```
#### 1.2 Train a (black-box) model on the Iris data
```
# Split data in a train/test set and in predictor (x) and target (y) variables
x_train, x_test, y_train, y_test = model_selection.train_test_split(data.data,
data.target,
train_size=0.80,
random_state=SEED)
# Train a RandomForestClassifier
model = ensemble.RandomForestClassifier(random_state=SEED, n_estimators=100)
model.fit(x_train, y_train)
# Print out the classifier performance (F1-score)
print('Classifier performance (F1):', metrics.f1_score(y_test, model.predict(x_test), average='weighted'))
```
#### 1.3a Perform contrastive explanation
```
# Import
import contrastive_explanation as ce
# Select a sample to explain ('questioned data point') why it predicted the fact instead of the foil
sample = x_test[1]
print_sample(data.feature_names, sample)
# Create a domain mapper (map the explanation to meaningful labels for explanation)
dm = ce.domain_mappers.DomainMapperTabular(x_train,
feature_names=data.feature_names,
contrast_names=data.target_names)
# Create the contrastive explanation object (default is a Foil Tree explanator)
exp = ce.ContrastiveExplanation(dm)
# Explain the instance (sample) for the given model
exp.explain_instance_domain(model.predict_proba, sample)
```
#### 1.3b Perform contrastive explanation on manually selected foil
Instead, we can also manually provide a foil to explain (e.g. class 'virginica'):
```
exp.explain_instance_domain(model.predict_proba, sample, foil='virginica')
```
## 2. Classification (Pandas DataFrame, categorical features) <a name="classification-2"></a>
We use the [Adult Census Income](https://archive.ics.uci.edu/ml/datasets/Adult) data set from the UCI Machine Learning repository as an additional classification example, where we showcase the usage of multi-valued categorical features and Pandas DataFrames as input.
---
#### 2.1 Data set characteristics
```
# Import
import contrastive_explanation as ce
# Read the adult data set (https://archive.ics.uci.edu/ml/datasets/Adult)
c_file = ce.utils.download_data('https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data')
c_df = pd.read_csv(c_file, header=None, skipinitialspace=True)
c_df = c_df.drop([2, 4], axis=1)
# Give descriptive names to features
c_features = ['age', 'workclass', 'education', 'marital-status',
'occupation', 'relationship', 'race', 'sex',
'capital-gain', 'capital-loss', 'hours-per-week',
'native-country']
c_categorical = ['workclass', 'education', 'marital-status', 'occupation',
'relationship', 'race', 'sex', 'native-country']
c_df.columns = c_features + ['class']
c_contrasts = c_df['class'].unique()
# Split into x and y (class feature is last feature)
cx, cy = c_df.iloc[:, :-1], c_df.iloc[:, -1]
c_df.head()
```
#### 2.2 Train a (black-box) model on the Adult data
```
# Split data in a train/test set and in predictor (x) and target (y) variables
cx_train, cx_test, cy_train, cy_test = model_selection.train_test_split(cx,
cy,
train_size=0.80,
random_state=SEED)
# Train an AdaBoostClassifier
c_model = pipeline.Pipeline([('label_encoder', ce.CustomLabelEncoder(c_categorical).fit(cx)),
('classifier', ensemble.AdaBoostClassifier(random_state=SEED, n_estimators=100))])
c_model.fit(cx_train, cy_train)
# Print out the classifier performance (F1-score)
print('Classifier performance (F1):', metrics.f1_score(cy_test, c_model.predict(cx_test), average='weighted'))
```
#### 2.3 Perform contrastive explanation
```
# Select a sample to explain ('questioned data point') why it predicted the fact instead of the foil
sample = cx_test.iloc[1]
print(sample)
# Create a domain mapper for the Pandas DataFrame (it will automatically infer feature names)
c_dm = ce.domain_mappers.DomainMapperPandas(cx_train,
contrast_names=c_contrasts)
# Create the contrastive explanation object (default is a Foil Tree explanator)
c_exp = ce.ContrastiveExplanation(c_dm)
# Explain the instance (sample) for the given model
c_exp.explain_instance_domain(c_model.predict_proba, sample)
```
---
## 3. Regression <a name="regression-1"></a>
Here, we explain an instance of the [Diabetes](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html#sklearn.datasets.load_diabetes) data set using the same steps as the classification problems. Instead of just the counterfactual explanation (difference between fact and foil), this example also includes the factual explanation (difference of fact versus all foils).
#### 3.1 Data set characteristics
```
r_data = datasets.load_diabetes()
print(r_data['DESCR'])
```
#### 3.2 Train a (black-box) model on the Diabetes data
```
# Split data in a train/test set and in predictor (x) and target (y) variables
rx_train, rx_test, ry_train, ry_test = model_selection.train_test_split(r_data.data,
r_data.target,
train_size=0.80,
random_state=SEED)
# Train a RandomForestRegressor with hyperparameter tuning (selecting the best n_estimators)
m_cv = ensemble.RandomForestRegressor(random_state=SEED)
r_model = model_selection.GridSearchCV(m_cv, cv=5, param_grid={'n_estimators': [50, 100, 500]})
r_model.fit(rx_train, ry_train)
# Print out the regressor performance
print('Regressor performance (R-squared):', metrics.r2_score(ry_test, r_model.predict(rx_test)))
```
#### 3.3 Perform contrastive explanation
```
# Import
import contrastive_explanation as ce
# Select a sample to explain
r_sample = rx_test[1]
print_sample(r_data.feature_names, r_sample)
print('\n')
# Create a domain mapper (still tabular data, but for regression we do not have named labels for the outcome)
r_dm = ce.domain_mappers.DomainMapperTabular(rx_train,
feature_names=r_data.feature_names)
# Create the CE objects, ensure that 'regression' is set to True
# again, we use the Foil Tree explanator, but now we print out intermediary outcomes and steps (verbose)
r_exp = ce.ContrastiveExplanation(r_dm,
regression=True,
explanator=ce.explanators.TreeExplanator(verbose=True),
verbose=False)
# Explain using the model, also include a 'factual' (non-contrastive 'why fact?') explanation
r_exp.explain_instance_domain(r_model.predict, r_sample, include_factual=True)
```
| github_jupyter |
# ANOVOS - Statistic Generator
Following notebook shows the list of functions related to "stats generator" module provided under ANOVOS package and how it can be invoked accordingly.
* [Global Summary](#Global-Summary)
* [Measures of Counts](#Measures-of-Counts)
* [Measures of Central Tendency](#Measures-of-Central-Tendency)
* [Measures of Cardinality](#Measures-of-Cardinality)
* [Measures of Dispersion](#Measures-of-Dispersion)
* [Measures of Percentiles](#Measures-of-Percentiles)
* [Measures of Shape](#Measures-of-Shape)
**Setting Spark Session**
```
from anovos.shared.spark import *
sc.setLogLevel("ERROR")
import warnings
warnings.filterwarnings('ignore')
```
**Input/Output Path**
```
inputPath = "../data/income_dataset/csv"
outputPath = "../output/income_dataset/data_analyzer"
from anovos.data_ingest.data_ingest import read_dataset
df = read_dataset(spark, file_path = inputPath, file_type = "csv",file_configs = {"header": "True",
"delimiter": "," ,
"inferSchema": "True"})
df = df.drop("dt_1", "dt_2")
df.toPandas().head(5)
```
# Global Summary
- API specification of function **global_summary** can be found <a href="https://docs.anovos.ai/api/data_analyzer/stats_generator.html">here</a>
```
from anovos.data_analyzer.stats_generator import global_summary
# Example 1 - with manadatory arguments (rest arguments have default values)
odf = global_summary(spark, df)
odf.toPandas()
# Example 2 - 'all' columns (excluding drop_cols)
odf = global_summary(spark, idf = df, list_of_cols='all', drop_cols=['ifa'])
odf.toPandas()
# Example 3 - selected columns
odf = global_summary(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'])
odf.toPandas()
```
# Measures of Counts
- API specification of function **measures_of_counts** can be found <a href="https://docs.anovos.ai/api/data_analyzer/stats_generator.html">here</a>
- Non zero count/% calculated only for numerical columns
```
from anovos.data_analyzer.stats_generator import measures_of_counts, nonzeroCount_computation
# Example 1 - with manadatory arguments (rest arguments have default values)
odf = measures_of_counts(spark, df)
odf.toPandas()
# Example 2 - 'all' columns (excluding drop_cols)
odf = measures_of_counts(spark, idf = df, list_of_cols='all', drop_cols=['ifa'])
odf.toPandas()
# Example 3 - selected columns
odf = measures_of_counts(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'])
odf.toPandas()
# Example 4 - only numerical columns
odf = measures_of_counts(spark, idf = df, list_of_cols= ['age','education-num','capital-gain'])
odf.toPandas()
# Example 5 - only categorical columns (user warning is shown as nonon-zero computation didn't happen due to absence of any numerical column)
odf = measures_of_counts(spark, idf = df, list_of_cols= ['sex','race','workclass'])
odf.toPandas()
```
# Measures of Central Tendency
- API specification of function **measures_of_centralTendency** can be found <a href="https://docs.anovos.ai/api/data_analyzer/stats_generator.html">here</a>
- Mode & Mode% calculated only for discrete columns (string + integer datatypes)
```
from anovos.data_analyzer.stats_generator import measures_of_centralTendency
# Example 1 - with manadatory arguments (rest arguments have default values)
odf = measures_of_centralTendency(spark, df)
odf.toPandas()
# Example 2 - 'all' columns (excluding drop_cols)
odf = measures_of_centralTendency(spark, idf = df, list_of_cols='all', drop_cols=['ifa'])
odf.toPandas()
# Example 3 - selected columns
odf = measures_of_centralTendency(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'])
odf.toPandas()
# Example 4 - only numerical columns
odf = measures_of_centralTendency(spark, idf = df, list_of_cols= ['age','education-num','capital-gain','logfnl'])
odf.toPandas()
# Example 5 - only categorical columns
odf = measures_of_centralTendency(spark, idf = df, list_of_cols= ['sex','race','workclass'])
odf.toPandas()
```
# Measures of Cardinality
- API specification of function **measures_of_cardinality** can be found <a href="https://docs.anovos.ai/api/data_analyzer/stats_generator.html">here</a>
- Calculated only for discrete columns (string + integer datatypes)
```
from anovos.data_analyzer.stats_generator import measures_of_cardinality
# Example 1 - with manadatory arguments (rest arguments have default values)
odf = measures_of_cardinality(spark, df)
odf.toPandas()
# Example 2 - 'all' columns (excluding drop_cols)
odf = measures_of_cardinality(spark, idf = df, list_of_cols='all', drop_cols=['ifa'])
odf.toPandas()
# Example 3 - selected columns
odf = measures_of_cardinality(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'])
odf.toPandas()
# Example 4 - only numerical columns
odf = measures_of_cardinality(spark, idf = df, list_of_cols= ['age','education-num','capital-gain','logfnl'])
odf.toPandas()
# Example 5 - only categorical columns
odf = measures_of_cardinality(spark, idf = df, list_of_cols= ['sex','race','workclass'])
odf.toPandas()
```
# Measures of Dispersion
- API specification of function **measures_of_dispersion** can be found <a href="https://docs.anovos.ai/api/data_analyzer/stats_generator.html">here</a>
- Supports only numerical columns
```
from anovos.data_analyzer.stats_generator import measures_of_dispersion
# Example 1 - with manadatory arguments (rest arguments have default values)
odf = measures_of_dispersion(spark, df)
odf.toPandas()
# Example 2 - 'all' columns (excluding drop_cols)
odf = measures_of_dispersion(spark, idf = df, list_of_cols='all', drop_cols=['capital-loss'])
odf.toPandas()
# Example 3 - selected numerical columns
odf = measures_of_dispersion(spark, idf = df, list_of_cols= ['age','education-num','capital-gain','logfnl'])
odf.toPandas()
```
# Measures of Percentiles
- API specification of function **measures_of_percentiles** can be found <a href="https://docs.anovos.ai/api/data_analyzer/stats_generator.html">here</a>
- Supports only numerical columns
```
from anovos.data_analyzer.stats_generator import measures_of_percentiles
# Example 1 - with manadatory arguments (rest arguments have default values)
odf = measures_of_percentiles(spark, df)
odf.toPandas()
# Example 2 - 'all' columns (excluding drop_cols)
odf = measures_of_percentiles(spark, idf = df, list_of_cols='all', drop_cols=['capital-gain'])
odf.toPandas()
# Example 3 - selected numerical columns
odf = measures_of_percentiles(spark, idf = df, list_of_cols= ['age','education-num','capital-gain','logfnl'])
odf.toPandas()
```
# Measures of Shape
- API specification of function **measures_of_shape** can be found <a href="https://docs.anovos.ai/api/data_analyzer/stats_generator.html">here</a>
- Supports only numerical columns
```
from anovos.data_analyzer.stats_generator import measures_of_shape
# Example 1 - with manadatory arguments (rest arguments have default values)
odf = measures_of_shape(spark, df)
odf.toPandas()
# Example 2 - 'all' columns (excluding drop_cols)
odf = measures_of_shape(spark, idf = df, list_of_cols='all', drop_cols=['capital-gain'])
odf.toPandas()
# Example 3 - selected numerical columns
odf = measures_of_shape(spark, idf = df, list_of_cols= ['age','education-num','capital-gain','logfnl'])
odf.toPandas()
```
| github_jupyter |
# Credit Card Kaggle- Handle Imbalanced Dataset
## Context
It is important that credit card companies are able to recognize fraudulent credit card transactions so that customers are not charged for items that they did not purchase.
## Content
The datasets contains transactions made by credit cards in September 2013 by european cardholders. This dataset presents transactions that occurred in two days, where we have 492 frauds out of 284,807 transactions. The dataset is highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.
It contains only numerical input variables which are the result of a PCA transformation. Unfortunately, due to confidentiality issues, we cannot provide the original features and more background information about the data. Features V1, V2, ... V28 are the principal components obtained with PCA, the only features which have not been transformed with PCA are 'Time' and 'Amount'. Feature 'Time' contains the seconds elapsed between each transaction and the first transaction in the dataset. The feature 'Amount' is the transaction Amount, this feature can be used for example-dependant cost-senstive learning. Feature 'Class' is the response variable and it takes value 1 in case of fraud and 0 otherwise.
## Inspiration
Identify fraudulent credit card transactions.
Given the class imbalance ratio, we recommend measuring the accuracy using the Area Under the Precision-Recall Curve (AUPRC). Confusion matrix accuracy is not meaningful for unbalanced classification.
## Acknowledgements
The dataset has been collected and analysed during a research collaboration of Worldline and the Machine Learning Group (http://mlg.ulb.ac.be) of ULB (Université Libre de Bruxelles) on big data mining and fraud detection. More details on current and past projects on related topics are available on https://www.researchgate.net/project/Fraud-detection-5 and the page of the DefeatFraud project
```
import numpy as np
import pandas as pd
import sklearn
import scipy
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import classification_report,accuracy_score
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.svm import OneClassSVM
from pylab import rcParams
rcParams['figure.figsize'] = 14, 8
RANDOM_SEED = 42
LABELS = ["Normal", "Fraud"]
data = pd.read_csv('creditcard.csv',sep=',')
data.head()
data.info()
#Create independent and Dependent Features
columns = data.columns.tolist()
# Filter the columns to remove data we do not want
columns = [c for c in columns if c not in ["Class"]]
# Store the variable we are predicting
target = "Class"
# Define a random state
state = np.random.RandomState(42)
X = data[columns]
Y = data[target]
X_outliers = state.uniform(low=0, high=1, size=(X.shape[0], X.shape[1]))
# Print the shapes of X & Y
print(X.shape)
print(Y.shape)
data.isnull().values.any()
count_classes = pd.value_counts(data['Class'], sort = True)
count_classes.plot(kind = 'bar', rot=0)
plt.title("Transaction Class Distribution")
plt.xticks(range(2), LABELS)
plt.xlabel("Class")
plt.ylabel("Frequency")
## Get the Fraud and the normal dataset
fraud = data[data['Class']==1]
normal = data[data['Class']==0]
print(fraud.shape,normal.shape)
from imblearn.under_sampling import NearMiss
# Implementing Undersampling for Handling Imbalanced
nm = NearMiss(random_state=42)
X_res,y_res=nm.fit_sample(X,Y)
X_res.shape,y_res.shape
from collections import Counter
print('Original dataset shape {}'.format(Counter(Y)))
print('Resampled dataset shape {}'.format(Counter(y_res)))
```
| 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.
```
# The Basics: Training Your First Model
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l02c01_celsius_to_fahrenheit.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/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l02c01_celsius_to_fahrenheit.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
Welcome to this Colab where you will train your first Machine Learning model!
We'll try to keep things simple here, and only introduce basic concepts. Later Colabs will cover more advanced problems.
The problem we will solve is to convert from Celsius to Fahrenheit, where the approximate formula is:
$$ f = c \times 1.8 + 32 $$
Of course, it would be simple enough to create a conventional Python function that directly performs this calculation, but that wouldn't be machine learning.
Instead, we will give TensorFlow some sample Celsius values (0, 8, 15, 22, 38) and their corresponding Fahrenheit values (32, 46, 59, 72, 100).
Then, we will train a model that figures out the above formula through the training process.
## Import dependencies
First, import TensorFlow. Here, we're calling it `tf` for ease of use. We also tell it to only display errors.
Next, import [NumPy](http://www.numpy.org/) as `np`. Numpy helps us to represent our data as highly performant lists.
```
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
import numpy as np
```
## Set up training data
As we saw before, supervised Machine Learning is all about figuring out an algorithm given a set of inputs and outputs. Since the task in this Codelab is to create a model that can give the temperature in Fahrenheit when given the degrees in Celsius, we create two lists `celsius_q` and `fahrenheit_a` that we can use to train our model.
```
celsius_q = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
fahrenheit_a = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=float)
for i,c in enumerate(celsius_q):
print("{} degrees Celsius = {} degrees Fahrenheit".format(c, fahrenheit_a[i]))
```
### Some Machine Learning terminology
- **Feature** — The input(s) to our model. In this case, a single value — the degrees in Celsius.
- **Labels** — The output our model predicts. In this case, a single value — the degrees in Fahrenheit.
- **Example** — A pair of inputs/outputs used during training. In our case a pair of values from `celsius_q` and `fahrenheit_a` at a specific index, such as `(22,72)`.
## Create the model
Next create the model. We will use simplest possible model we can, a Dense network. Since the problem is straightforward, this network will require only a single layer, with a single neuron.
### Build a layer
We'll call the layer `l0` and create it by instantiating `tf.keras.layers.Dense` with the following configuration:
* `input_shape=[1]` — This specifies that the input to this layer is a single value. That is, the shape is a one-dimensional array with one member. Since this is the first (and only) layer, that input shape is the input shape of the entire model. The single value is a floating point number, representing degrees Celsius.
* `units=1` — This specifies the number of neurons in the layer. The number of neurons defines how many internal variables the layer has to try to learn how to solve the problem (more later). Since this is the final layer, it is also the size of the model's output — a single float value representing degrees Fahrenheit. (In a multi-layered network, the size and shape of the layer would need to match the `input_shape` of the next layer.)
```
l0 = tf.keras.layers.Dense(units=1, input_shape=[1])
```
### Assemble layers into the model
Once layers are defined, they need to be assembled into a model. The Sequential model definition takes a list of layers as argument, specifying the calculation order from the input to the output.
This model has just a single layer, l0.
```
model = tf.keras.Sequential([l0])
```
**Note**
You will often see the layers defined inside the model definition, rather than beforehand:
```python
model = tf.keras.Sequential([
tf.keras.layers.Dense(units=1, input_shape=[1])
])
```
## Compile the model, with loss and optimizer functions
Before training, the model has to be compiled. When compiled for training, the model is given:
- **Loss function** — A way of measuring how far off predictions are from the desired outcome. (The measured difference is called the "loss".)
- **Optimizer function** — A way of adjusting internal values in order to reduce the loss.
```
model.compile(loss='mean_squared_error',
optimizer=tf.keras.optimizers.Adam(0.1))
```
These are used during training (`model.fit()`, below) to first calculate the loss at each point, and then improve it. In fact, the act of calculating the current loss of a model and then improving it is precisely what training is.
During training, the optimizer function is used to calculate adjustments to the model's internal variables. The goal is to adjust the internal variables until the model (which is really a math function) mirrors the actual equation for converting Celsius to Fahrenheit.
TensorFlow uses numerical analysis to perform this tuning, and all this complexity is hidden from you so we will not go into the details here. What is useful to know about these parameters are:
The loss function ([mean squared error](https://en.wikipedia.org/wiki/Mean_squared_error)) and the optimizer ([Adam](https://machinelearningmastery.com/adam-optimization-algorithm-for-deep-learning/)) used here are standard for simple models like this one, but many others are available. It is not important to know how these specific functions work at this point.
One part of the Optimizer you may need to think about when building your own models is the learning rate (`0.1` in the code above). This is the step size taken when adjusting values in the model. If the value is too small, it will take too many iterations to train the model. Too large, and accuracy goes down. Finding a good value often involves some trial and error, but the range is usually within 0.001 (default), and 0.1
## Train the model
Train the model by calling the `fit` method.
During training, the model takes in Celsius values, performs a calculation using the current internal variables (called "weights") and outputs values which are meant to be the Fahrenheit equivalent. Since the weights are initially set randomly, the output will not be close to the correct value. The difference between the actual output and the desired output is calculated using the loss function, and the optimizer function directs how the weights should be adjusted.
This cycle of calculate, compare, adjust is controlled by the `fit` method. The first argument is the inputs, the second argument is the desired outputs. The `epochs` argument specifies how many times this cycle should be run, and the `verbose` argument controls how much output the method produces.
```
history = model.fit(celsius_q, fahrenheit_a, epochs=500, verbose=False)
print("Finished training the model")
```
In later videos, we will go into more details on what actually happens here and how a Dense layer actually works internally.
## Display training statistics
The `fit` method returns a history object. We can use this object to plot how the loss of our model goes down after each training epoch. A high loss means that the Fahrenheit degrees the model predicts is far from the corresponding value in `fahrenheit_a`.
We'll use [Matplotlib](https://matplotlib.org/) to visualize this (you could use another tool). As you can see, our model improves very quickly at first, and then has a steady, slow improvement until it is very near "perfect" towards the end.
```
import matplotlib.pyplot as plt
plt.xlabel('Epoch Number')
plt.ylabel("Loss Magnitude")
plt.plot(history.history['loss'])
```
## Use the model to predict values
Now you have a model that has been trained to learn the relationship between `celsius_q` and `fahrenheit_a`. You can use the predict method to have it calculate the Fahrenheit degrees for a previously unknown Celsius degrees.
So, for example, if the Celsius value is 100, what do you think the Fahrenheit result will be? Take a guess before you run this code.
```
print(model.predict([100.0]))
```
The correct answer is $100 \times 1.8 + 32 = 212$, so our model is doing really well.
### To review
* We created a model with a Dense layer
* We trained it with 3500 examples (7 pairs, over 500 epochs).
Our model tuned the variables (weights) in the Dense layer until it was able to return the correct Fahrenheit value for any Celsius value. (Remember, 100 Celsius was not part of our training data.)
## Looking at the layer weights
Finally, let's print the internal variables of the Dense layer.
```
print("These are the layer variables: {}".format(l0.get_weights()))
```
The first variable is close to ~1.8 and the second to ~32. These values (1.8 and 32) are the actual variables in the real conversion formula.
This is really close to the values in the conversion formula. We'll explain this in an upcoming video where we show how a Dense layer works, but for a single neuron with a single input and a single output, the internal math looks the same as [the equation for a line](https://en.wikipedia.org/wiki/Linear_equation#Slope%E2%80%93intercept_form), $y = mx + b$, which has the same form as the conversion equation, $f = 1.8c + 32$.
Since the form is the same, the variables should converge on the standard values of 1.8 and 32, which is exactly what happened.
With additional neurons, additional inputs, and additional outputs, the formula becomes much more complex, but the idea is the same.
### A little experiment
Just for fun, what if we created more Dense layers with different units, which therefore also has more variables?
```
l0 = tf.keras.layers.Dense(units=4, input_shape=[1])
l1 = tf.keras.layers.Dense(units=4)
l2 = tf.keras.layers.Dense(units=1)
model = tf.keras.Sequential([l0, l1, l2])
model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1))
model.fit(celsius_q, fahrenheit_a, epochs=500, verbose=False)
print("Finished training the model")
print(model.predict([100.0]))
print("Model predicts that 100 degrees Celsius is: {} degrees Fahrenheit".format(model.predict([100.0])))
print("These are the l0 variables: {}".format(l0.get_weights()))
print("These are the l1 variables: {}".format(l1.get_weights()))
print("These are the l2 variables: {}".format(l2.get_weights()))
```
As you can see, this model is also able to predict the corresponding Fahrenheit value really well. But when you look at the variables (weights) in the `l0` and `l1` layers, they are nothing even close to ~1.8 and ~32. The added complexity hides the "simple" form of the conversion equation.
Stay tuned for the upcoming video on how Dense layers work for the explanation.
| github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# For reference, see chapter 9 of Python for Data Analysis, 2nd Edition
```
# Line graphs
```
url = 'https://github.com/nytimes/covid-19-data/raw/master/us.csv'
covid = pd.read_csv(url)
covid.tail()
covid.plot()
# covid.plot(kind='line') # .plot() defaults to this specific kind of plot
# covid.plot.line() # alternate method of specifying the kind of plot
covid.set_index(['date']).plot() # sets the index of the dataframe to the date column
```
Fix the dates on the X axis
```
# See https://stackoverflow.com/questions/25416955/plot-pandas-dates-in-matplotlib for setting X axis as dates
covid['date'] = pd.to_datetime(covid['date'], format = '%Y-%m-%d') # converts string to datetime object
covid.set_index(['date'], inplace=True)
covid.head()
covid.plot()
```
## Subplots
```
covid.plot(title = 'Covid 19 cases in the U.S.', subplots = True)
covid.plot(title = 'Covid 19 cases in the U.S.', subplots = True, figsize=(10,10))
covid.plot(title = 'Covid 19 cases in the U.S.', subplots = True, figsize=(10,10), logy = True)
```
## Scatterplot
```
# Scatter plot requires specifying both the X and Y columns as arguments
covid.plot.scatter('cases', 'deaths')
```
## Pie chart
```
url = 'https://github.com/HeardLibrary/digital-scholarship/raw/master/data/codegraf/co2_state_2016_sector.xlsx'
state_co2_sector = pd.read_excel(url)
state_co2_sector.set_index('State', inplace=True)
state_co2_sector.head()
az_sector = state_co2_sector.loc['Arizona']
az_sector
az_sector_components = az_sector['Commercial': "Transportation"]
az_sector_components
az_sector_components.plot(kind = 'pie')
no_totals = state_co2_sector.copy()
no_totals.drop('Total', inplace=True)
no_totals.tail()
decreasing = no_totals.sort_values(by='Total', ascending=False)
decreasing.head()
decreasing.drop(['Total'], axis='columns', inplace=True)
decreasing.head()
decreasing[:3]
# Transpose so that states will be subplots and sectors will be plot categories
decreasing[:3].T.plot(kind='pie', subplots=True, legend=False, figsize=(20,10))
decreasing.loc[['Texas', 'Alaska', 'Ohio', 'District of Columbia']].T.plot(kind='pie', subplots=True, legend=False, figsize=(20,10))
```
## Bar chart
```
totals_by_state = state_co2_sector.Total['Alabama': 'Wyoming']
totals_by_state.head()
totals_by_state.plot(kind = 'barh')
totals_by_state.sort_index(ascending=False).plot(kind = 'barh', figsize=(10,10))
```
# pyplot from matplotlib
```
first_cases = covid[:50]
first_cases.head()
```
## Using the plt.plot function
```
plt.plot(first_cases.cases, first_cases.deaths)
plt.scatter(first_cases.cases, first_cases.deaths)
plt.plot(first_cases.cases, first_cases.deaths, color='k', linestyle='dashed', marker='o')
# pyplot will accept calculated series in addition to series that are columns from DataFrames
thousands_cases = covid['cases']/1000
thousands_deaths = covid['deaths']/1000
plt.scatter(thousands_cases, thousands_deaths)
```
## Controlling display with figures and subplots
```
# Create a figure object
fig = plt.figure()
# Create 2 subplots with 1 row and 2 columns
axes1 = fig.add_subplot(1, 2, 1)
axes2 = fig.add_subplot(1, 2, 2)
# Create a figure object
fig = plt.figure()
# Create 2 subplots with 2 rows and 1 column
axes1 = fig.add_subplot(2, 1, 1)
axes2 = fig.add_subplot(2, 1, 2)
plt.show() # displays the graph if you aren't using Jupyter notebooks
```
In Jupyter notebooks, plots are reset after every cell, so setup code must be included in a single cell
```
# Create a figure object
fig = plt.figure(figsize=(10,10))
# Create 2 subplots with 2 rows and 1 column
axes1 = fig.add_subplot(2, 1, 1)
axes2 = fig.add_subplot(2, 1, 2)
axes1.plot(first_cases.index, first_cases.cases, color='k', linestyle='dashed', marker='o')
axes1.set_title('cases')
axes2.plot(first_cases.index, first_cases.deaths, color='r', linestyle='dashed', marker='x')
axes2.set_title('deaths')
```
## Plot in a single subplot
```
# Create a figure object
fig = plt.figure(figsize=(10,10))
# Create a single subplot
ax = fig.add_subplot(1, 1, 1)
ax.plot(first_cases.index, first_cases.cases, color='k', linestyle='dashed', marker='o')
ax.plot(first_cases.index, first_cases.deaths, color='r', linestyle='dashed', marker='x')
ax.set_title('start of the COVID 19 pandemic in the U.S.')
```
Display as a bar graph (unstacked)
```
# Create a figure object
fig = plt.figure(figsize=(10,10))
# Create a single subplot
ax = fig.add_subplot(1, 1, 1)
ax.bar(first_cases.index, first_cases.cases, color='k')
ax.bar(first_cases.index, first_cases.deaths, color='r')
ax.set_title('start of the COVID 19 pandemic in the U.S.')
```
## Creating a plot programatically
Stacked bar graph
```
# Reload state_co2_sector if necessary
url = 'https://github.com/HeardLibrary/digital-scholarship/raw/master/data/codegraf/co2_state_2016_sector.xlsx'
state_co2_sector = pd.read_excel(url)
state_co2_sector.tail()
# Extract sector data for the top few states
number_of_states = 4
top_state_sectors = state_co2_sector.set_index('State').drop('Total').sort_values(by='Total', ascending=False).drop(['Total'], axis='columns')[:number_of_states]
top_state_sectors
# Based on example at https://subscription.packtpub.com/book/big_data_and_business_intelligence/9781849513265/1/ch01lvl1sec17/plotting-stacked-bar-charts
# See also https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/bar_stacked.html
# Create a figure object
fig = plt.figure(figsize=(15,10))
# Create a single subplot
ax = fig.add_subplot(1, 1, 1)
# Create a numpy array with one element for each row
ind = np.arange(len(top_state_sectors))
#print(ind)
# Extract the row and column labels as numpy arrays from pandas series
row_labels = top_state_sectors.index.values
column_labels = top_state_sectors.columns.values
for sector_number in range(len(top_state_sectors.columns)):
#print(sector_number)
#print(top_state_sectors.iloc[:, :sector_number])
sector_sums = top_state_sectors.iloc[:, :sector_number].sum(axis='columns')
#print(sector_sums)
ax.bar(ind, top_state_sectors.iloc[:, sector_number], bottom=sector_sums)
# These functions operate on the most recently active subplot; we have only one in this example
plt.xticks(ind, row_labels)
plt.legend(column_labels)
```
There are many, many types of plots and options. See the [matplotlib gallery](https://matplotlib.org/3.1.1/gallery/index.html) for examples.
# Practice
See [this page](https://github.com/HeardLibrary/digital-scholarship/tree/master/data/codegraf) for information about the dataset.
```
url = 'data/flight_data_set.csv'
flights = pd.read_csv(url)
flights.head()
```
Calculate the average values for the carriers and slice out the Minutes of Delay per flight. Create a bar chart of the resulting series.
```
grouped = flights.groupby(['Carrier Name']).mean()
grouped.drop(['Minutes of Delay', 'Number of Flights'], axis='columns', inplace=True)
grouped.sort_values(by='Minutes of Delay per Flight', ascending=True).plot(kind='barh', figsize=(20,10))
```
Recreate the plot, but this time replace `NaN` values with zeros.
```
flights.fillna({'Minutes of Delay per Flight': 0}, inplace=True)
grouped = flights.groupby(['Carrier Name']).mean()
grouped.drop(['Minutes of Delay', 'Number of Flights'], axis='columns', inplace=True)
grouped.sort_values(by='Minutes of Delay per Flight', ascending=True).plot(kind='barh', figsize=(20,10))
#grouped.plot(kind='barh', figsize=(20,10))
```
Convert date column to a datetime object and group by Carrier Name.
```
date_flights = flights.copy()
date_flights['Date'] = pd.to_datetime(date_flights['Date'], format = '%m/%d/%Y')
grouped = date_flights.groupby(['Carrier Name'])
grouped.head()
```
Slice only the Delta data and sum by date. Plot only the Minutes of Delay by date
```
delta = grouped.get_group('Delta')
time_series = delta.groupby('Date').sum()
time_series.drop(['Minutes of Delay per Flight', 'Number of Flights'], axis='columns', inplace=True)
print(time_series.head())
time_series.plot(kind='line', figsize=(20,10))
```
Let's see if this pattern holds across airlines. Group by both Carrier Name and Date rather than selecting only one airline. Limit output to Minutes of Delay data.
```
date_flights = flights.copy()
date_flights['Date'] = pd.to_datetime(date_flights['Date'], format = '%m/%d/%Y')
grouped = date_flights.groupby(['Carrier Name', 'Date']).sum()
grouped.drop(['Minutes of Delay per Flight', 'Number of Flights'], axis='columns', inplace=True)
grouped.head()
```
Unstack Carrier Name so that we get a column for each carrier. Now if we redo the plot, Pandas will plot a line for each carrier.
```
columned = grouped.unstack('Carrier Name')
print(columned.head())
columned.plot(kind='line', figsize=(20,10))
```
Let's compare the number of flights across airlines using a bar chart.
```
grouped = flights.groupby(['Carrier Name']).sum()
grouped.drop(['Minutes of Delay per Flight', 'Minutes of Delay'], axis='columns', inplace=True)
grouped.plot(kind='bar', figsize=(20,10))
```
| github_jupyter |
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
fixed_band_indices = [3]
bandnames = ['u', 'g', 'r', 'i', 'z']
num_fixed_bands = len(fixed_band_indices)
# load stellar model grids
npzfile = np.load('./model_grids.npz')
stellarmodel_grid = npzfile['model_grid']
stellarmodel_grid = stellarmodel_grid[:, ::50, ::10, :] ## UNCOMMENT THAT
plotstrides = 1
gridsize1, gridsize2, numtypes = stellarmodel_grid.shape[1:4]
# logg and Teff grids
loggDA_vec=np.linspace(7., 9.5, gridsize1)
loggDB_vec=np.linspace(7., 9., gridsize1)
temp_vec = np.logspace(np.log10(3000.), np.log10(120000.), gridsize2)
# random linear grids for the GP prior. Will need to specify the logg and T grids! For the GP prior
dim1_grid = np.linspace(0, 1, stellarmodel_grid.shape[1])
dim2_grid = np.linspace(0, 1, stellarmodel_grid.shape[2])
# load data
npzfile = np.load('./WD_data_very_clean.npz')
obsmags = npzfile['obsmags']
nobj, num_bands = obsmags.shape
obsmags_covar_chol = npzfile['obsmags_covar_chol']
obsmags_covar_logdet = npzfile['obsmags_covar_logdet']
obsmags_covar = obsmags_covar_chol[:, :, :] * np.swapaxes(obsmags_covar_chol[:, :, :], 1, 2)
nobj
stellarmodel_grid.shape
from matplotlib.colors import LogNorm
fig, axs = plt.subplots(3, 2, figsize=(10, 10))
axs = axs.ravel()
off = -1
for i in range(num_bands-1):
for j in range(i+1, num_bands-1):
off += 1
axs[off].set_xlabel('$'+bandnames[i]+'-'+bandnames[i+1]+'$')
axs[off].set_ylabel('$'+bandnames[j]+'-'+bandnames[j+1]+'$')
s = np.random.choice(nobj, 100, replace=False)
axs[off].errorbar(obsmags[s, i] - obsmags[s, i+1], obsmags[s, j] - obsmags[s, j+1],
xerr=np.sqrt(obsmags_covar[s, i, i] + obsmags_covar[s, i+1, i+1]),
yerr=np.sqrt(obsmags_covar[s, j, j] + obsmags_covar[s, j+1, j+1]),
fmt = 'o', ms=0, lw=1, c='r'
)
c = ['b', 'k']
for t in range(0, stellarmodel_grid.shape[3], plotstrides):
for g in range(0, stellarmodel_grid.shape[2], plotstrides):
mod1 = stellarmodel_grid[i, :, g, t] - stellarmodel_grid[i+1, :, g, t]
mod2 = stellarmodel_grid[j, :, g, t] - stellarmodel_grid[j+1, :, g, t]
axs[off].errorbar(mod1.ravel(), mod2.ravel(), c=c[t], fmt='-o', ms=2)
fig.tight_layout()
bandnames = ['u', 'g', 'r', 'i', 'z']
from matplotlib.colors import LogNorm
fig, axs = plt.subplots(3, 2, figsize=(10, 10))
axs = axs.ravel()
off = -1
for i in range(num_bands-1):
for j in range(i+1, num_bands-1):
off += 1
axs[off].set_xlabel('$'+bandnames[i]+'-'+bandnames[i+1]+'$')
axs[off].set_ylabel('$'+bandnames[j]+'-'+bandnames[j+1]+'$')
axs[off].hist2d(obsmags[:, i] - obsmags[:, i+1], obsmags[:, j] - obsmags[:, j+1],
50, norm=LogNorm(), range=[[-0.6, 1.5], [-0.6, 1]], cmap='Reds')
c = ['b', 'k']
for t in range(0, stellarmodel_grid.shape[3], plotstrides):
for g in range(0, stellarmodel_grid.shape[2], plotstrides):
mod1 = stellarmodel_grid[i, :, g, t] - stellarmodel_grid[i+1, :, g, t]
mod2 = stellarmodel_grid[j, :, g, t] - stellarmodel_grid[j+1, :, g, t]
axs[off].plot(mod1.ravel(), mod2.ravel(), c=c[t])
fig.tight_layout()
max_correction_magnitude = 0.1
# max amplitude of the correction in magnitude space
# gridsize1: logg
# gridsize2: T
# Grid of stellar models
# Size: num_bands, gridsize1, gridsize2, numtypes
Stellarmodel_grid = tf.placeholder(shape=[num_bands, gridsize1, gridsize2, numtypes], dtype=tf.float32)
# "Lines" of corrections, in the two dimensions
# Defined on R
Corrections_dim1_unbounded = tf.Variable(np.random.randn(num_bands, gridsize1, numtypes)*0.01, dtype=tf.float32)
Corrections_dim2_unbounded = tf.Variable(np.random.randn(num_bands, gridsize2, numtypes)*0.01, dtype=tf.float32)
Dim1_grid = tf.placeholder(shape=[gridsize1, ], dtype=tf.float32)
Dim2_grid = tf.placeholder(shape=[gridsize2, ], dtype=tf.float32)
# We need to set the lengthscale/smoothness of the GP in the two dimensions.
# Those are positive (thus the exponentiation) and will be optimized.
GPlengthscale1 = tf.exp(tf.Variable(0.01, dtype=tf.float32, trainable=True))
GPlengthscale2 = tf.exp(tf.Variable(0.01, dtype=tf.float32, trainable=True))
# The (cholesky decompositions) of the covariance matrices
Diagnoise1 = tf.diag(tf.cast(tf.constant(np.repeat(1e-5, gridsize1)), dtype=tf.float32))
Diagnoise2 = tf.diag(tf.cast(tf.constant(np.repeat(1e-5, gridsize2)), dtype=tf.float32))
Covariance1 = tf.exp(-0.5*((Dim1_grid[:, None] - Dim1_grid[None, :])/GPlengthscale1)**2.0) + Diagnoise1
Covariance2 = tf.exp(-0.5*((Dim2_grid[:, None] - Dim2_grid[None, :])/GPlengthscale2)**2.0) + Diagnoise2
CovarianceChol1 = tf.cholesky(Covariance1)[None, None, :, :] * tf.ones((num_bands, numtypes, 1, 1))
CovarianceChol2 = tf.cholesky(Covariance2)[None, None, :, :] * tf.ones((num_bands, numtypes, 1, 1))
x1 = tf.transpose(Corrections_dim1_unbounded, [0, 2, 1])[:, :, :, None]
x2 = tf.transpose(Corrections_dim2_unbounded, [0, 2, 1])[:, :, :, None]
LogDet1 = tf.linalg.logdet(Covariance1) # scalar
LogDet2 = tf.linalg.logdet(Covariance2) # scalar
# Size: num_bands x numtypes
LogGPpriors1 = -0.5*tf.reduce_sum(x1 * tf.cholesky_solve(CovarianceChol1, x1), axis=(2, 3)) - 0.5*LogDet1
LogGPpriors2 = -0.5*tf.reduce_sum(x2 * tf.cholesky_solve(CovarianceChol2, x2), axis=(2, 3)) - 0.5*LogDet2
# scalars
LogGPprior1 = tf.reduce_sum(LogGPpriors1)
LogGPprior2 = tf.reduce_sum(LogGPpriors2)
# Set the corrections to zero in the bands that are fixed
Fixed_band_indices = tf.placeholder(shape=[num_fixed_bands, ], dtype=tf.int32)
tf.scatter_update(Corrections_dim1_unbounded, Fixed_band_indices, tf.zeros((num_fixed_bands, gridsize1, numtypes)))
tf.scatter_update(Corrections_dim2_unbounded, Fixed_band_indices, tf.zeros((num_fixed_bands, gridsize2, numtypes)))
# Now we map them to a limited space: [-max_correction_magnitude, +max_correction_magnitude]
# (tf.sigmoid maps R on [0, 1])
Corrections_dim1 = max_correction_magnitude * (2*tf.sigmoid(Corrections_dim1_unbounded) - 1)
Corrections_dim2 = max_correction_magnitude * (2*tf.sigmoid(Corrections_dim2_unbounded) - 1)
# Add the line corrections to form a grid
# Correction(logg, T) = Correction(T) + Correction(logg)
# so the grid is in [-2*max_correction_magnitude, 2*max_correction_magnitude]
# Size: num_bands x gridsize1 x gridsize2 x numtypes
Corrections_grid = Corrections_dim1[:, :, None, :] + Corrections_dim2[:, None, :, :]
# Apply them to the stellar models and rotate axes
# Size: gridsize1, gridsize2, numtypes, num_bands
Corrected_stellarmodel_grid_c = Stellarmodel_grid + Corrections_grid
Corrected_stellarmodel_grid = tf.transpose(Corrected_stellarmodel_grid_c, perm=[1, 2, 3, 0])
# Now define the observations
# Size: nobj x num_bands
Obsmags = tf.placeholder(shape=[None, num_bands], dtype=tf.float32)
Obsmags_covar_chol = tf.placeholder(shape=[None, num_bands, num_bands], dtype=tf.float32)
Obsmags_covar_logdet = tf.placeholder(shape=[None, ], dtype=tf.float32)
# Compute the log likelihoods per object and per model element
# Size: nobj, gridsize1, gridsize2, numtypes, num_bands, 1
Delta = Obsmags[:, None, None, None, :, None] - Corrected_stellarmodel_grid[None, :, :, :, :, None]
Cov = Obsmags_covar_chol[:, None, None, None, :, :] * tf.ones((1, gridsize1, gridsize2, numtypes, 1, 1))
if True:# GAUSSIAN CHI2
# Size: nobj, gridsize1, gridsize2, numtypes
Chi2s = tf.reduce_sum(tf.multiply(Delta, tf.cholesky_solve(Cov, Delta)), axis=(4, 5))
# Size: nobj x gridsize1, gridsize2, numtypes
Loglikes = - 0.5 * (Chi2s + Obsmags_covar_logdet[:, None, None, None])
else: # STUDENT T
Nu = tf.Variable(1.0, dtype=tf.float32)
# Size: nobj, gridsize1, gridsize2, numtypes
Nud2 = (Nu + num_bands)/2
Chi2s = tf.reduce_sum(tf.multiply(Delta, tf.cholesky_solve(Cov, Delta)), axis=(4, 5))
Loglikes = tf.lgamma(Nud2) - tf.lgamma(Nu/2) - num_bands/2 * tf.log(Nu) \
- 0.5 * Obsmags_covar_logdet[:, None, None, None] - Nud2 *tf.log(1 + Chi2s / Nu)
# Size: nobj x gridsize1, gridsize2, numtypes
# Finally, compute the log evidence per object and the final log posterior
# Size: nobj
Logevidences = tf.reduce_logsumexp(Loglikes, axis=(1, 2, 3))
# Size: scalar!
MinusLogprob = - tf.reduce_sum(Logevidences, axis=0) - LogGPprior1 - LogGPprior2
num_iterations = 1000
learning_rate = 1e-2
Optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\
.minimize(MinusLogprob)
with tf.Session() as sess:
# initialize variables
sess.run(tf.global_variables_initializer())
# loop: iterations of the optimizer
for i in range(num_iterations):
subset = np.random.choice(nobj, nobj // 100, replace=False)
_, minuslogprob, corrections_dim1, corrections_dim2 =\
sess.run([Optimizer, MinusLogprob, Corrections_dim1, Corrections_dim2],
feed_dict={
Fixed_band_indices: fixed_band_indices,
Stellarmodel_grid: stellarmodel_grid,
Obsmags: obsmags[subset, :],
Obsmags_covar_chol: obsmags_covar_chol[subset, :, :],
Obsmags_covar_logdet: obsmags_covar_logdet[subset],
Dim1_grid: dim1_grid, Dim2_grid: dim2_grid
})
if i % 100 == 0:
print('Iteration', i, ': minus log posterior = ', minuslogprob)
print(sess.run([GPlengthscale1, GPlengthscale2]))
corrected_stellarmodel_grid, = sess.run([Corrected_stellarmodel_grid_c],
feed_dict={
Fixed_band_indices: fixed_band_indices,
Stellarmodel_grid: stellarmodel_grid,
Obsmags: obsmags[subset, :],
Obsmags_covar_chol: obsmags_covar_chol[subset, :, :],
Obsmags_covar_logdet: obsmags_covar_logdet[subset],
Dim1_grid: dim1_grid, Dim2_grid: dim2_grid
})
np.save('corrected_model_grids.npy', corrected_stellarmodel_grid)
np.save('corrections_dim1.npy', corrections_dim1)
np.save('corrections_dim2.npy', corrections_dim2)
STOP
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
corrected_stellarmodel_grid = np.load('corrected_model_grids.npy')
corrections_dim1 = np.load('corrections_dim1.npy')
corrections_dim2 = np.load('corrections_dim2.npy')
fixed_band_indices = [3]
bandnames = ['u', 'g', 'r', 'i', 'z']
num_fixed_bands = len(fixed_band_indices)
# load stellar model grids
npzfile = np.load('./model_grids.npz')
stellarmodel_grid = npzfile['model_grid']
stellarmodel_grid = stellarmodel_grid[:, ::50, ::10, :] ## UNCOMMENT THAT
plotstrides = 1
gridsize1, gridsize2, numtypes = stellarmodel_grid.shape[1:4]
# logg and Teff grids
loggDA_vec=np.linspace(7., 9.5, gridsize1)
loggDB_vec=np.linspace(7., 9., gridsize1)
temp_vec = np.logspace(np.log10(3000.), np.log10(120000.), gridsize2)
# random linear grids for the GP prior. Will need to specify the logg and T grids! For the GP prior
dim1_grid = np.linspace(0, 1, stellarmodel_grid.shape[1])
dim2_grid = np.linspace(0, 1, stellarmodel_grid.shape[2])
# load data
npzfile = np.load('./WD_data_very_clean.npz')
obsmags = npzfile['obsmags']
nobj, num_bands = obsmags.shape
obsmags_covar_chol = npzfile['obsmags_covar_chol']
obsmags_covar_logdet = npzfile['obsmags_covar_logdet']
obsmags_covar = obsmags_covar_chol[:, :, :] * np.swapaxes(obsmags_covar_chol[:, :, :], 1, 2)
# num_bands, gridsize1, numtypes
fig, axs = plt.subplots(num_bands, 2, figsize=(8, 8), sharex=False)
for i in range(num_bands):
axs[i, 0].plot(range(len(dim1_grid)), np.zeros(len(dim1_grid)), ls='--', c='k', label='Type 1')
axs[i, 1].plot(range(len(dim2_grid)), np.zeros(len(dim2_grid)), ls='--', c='k', label='Type 2')
axs[i, 0].plot(range(len(dim1_grid)), corrections_dim1[i, :, 0], label='Type 1')
axs[i, 0].plot(range(len(dim1_grid)), corrections_dim1[i, :, 1], label='Type 2')
axs[i, 1].plot(range(len(dim2_grid)), corrections_dim2[i, :, :])
axs[i, 0].set_ylabel('Corr in band '+str(i+1))
axs[i, 1].set_ylabel('Corr in band '+str(i+1))
axs[-1, 0].set_xlabel('Log g')
axs[-1, 1].set_xlabel('T')
axs[0, 0].legend()
fig.tight_layout()
# TODO: add actual log g and T grids!
# num_bands, gridsize1, numtypes
fig, axs = plt.subplots(num_bands, 2, figsize=(8, 8), sharex=False)
for i in range(num_bands):
axs[i, 0].plot(loggDA_vec, np.zeros(len(dim1_grid)), ls='--', c='k', label='Type 1')
axs[i, 1].plot(temp_vec, np.zeros(len(dim2_grid)), ls='--', c='k', label='Type 2')
axs[i, 0].plot(loggDA_vec, corrections_dim1[i, :, 0], label='Type 1')
axs[i, 0].plot(loggDB_vec, corrections_dim1[i, :, 1], label='Type 2')
axs[i, 1].plot(temp_vec, corrections_dim2[i, :, :])
axs[i, 0].set_ylabel('Corr in band '+str(i+1))
axs[i, 1].set_ylabel('Corr in band '+str(i+1))
axs[-1, 0].set_xlabel('Log g')
axs[-1, 1].set_xlabel('T')
axs[0, 0].legend()
fig.tight_layout()
fig, axs = plt.subplots(6, 2, figsize=(10, 20))
#axs = axs.ravel()
off = -1
def custom_range(x, factor=2):
m = np.mean(x)
s = np.std(x)
return [m - factor*s, m + factor * s]
for i in range(num_bands-1):
for j in range(i+1, num_bands-1):
off += 1
norm = None;#LogNorm()#
rr = [[-0.6, 1.5], [-0.6, 1]]
for t in range(0, stellarmodel_grid.shape[3], plotstrides):
rr = [custom_range(obsmags[:, i] - obsmags[:, i+1]), custom_range(obsmags[:, j] - obsmags[:, j+1])]
axs[off, t].hist2d(obsmags[:, i] - obsmags[:, i+1], obsmags[:, j] - obsmags[:, j+1],
20, norm=norm, range=rr, cmap='Greys', zorder=0)
axs[off, t].set_xlabel('$'+bandnames[i]+'-'+bandnames[i+1]+'$')
axs[off, t].set_ylabel('$'+bandnames[j]+'-'+bandnames[j+1]+'$')
for g in range(0, stellarmodel_grid.shape[2], plotstrides):
mod1 = stellarmodel_grid[i, :, g, t] - stellarmodel_grid[i+1, :, g, t]
mod2 = stellarmodel_grid[j, :, g, t] - stellarmodel_grid[j+1, :, g, t]
axs[off, t].plot(mod1.ravel(), mod2.ravel(), c='blue', zorder=1)
mod1 = corrected_stellarmodel_grid[i, :, g, t] - corrected_stellarmodel_grid[i+1, :, g, t]
mod2 = corrected_stellarmodel_grid[j, :, g, t] - corrected_stellarmodel_grid[j+1, :, g, t]
axs[off, t].plot(mod1.ravel(), mod2.ravel(), c='orange', zorder=2)
fig.tight_layout()
```
| github_jupyter |
# Word Embeddings
**Learning Objectives**
You will learn:
1. How to use Embedding layer
1. How to create a classification model
1. Compile and train the model
1. How to retrieve the trained word embeddings, save them to disk and visualize it.
## Introduction
This notebook contains an introduction to word embeddings. You will train your own word embeddings using a simple Keras model for a sentiment classification task, and then visualize them in the [Embedding Projector](http://projector.tensorflow.org) (shown in the image below).
<img src="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/images/embedding.jpg?raw=1" alt="Screenshot of the embedding projector" width="400"/>
## Representing text as numbers
Machine learning models take vectors (arrays of numbers) as input. When working with text, the first thing you must do is come up with a strategy to convert strings to numbers (or to "vectorize" the text) before feeding it to the model. In this section, you will look at three strategies for doing so.
### One-hot encodings
As a first idea, you might "one-hot" encode each word in your vocabulary. Consider the sentence "The cat sat on the mat". The vocabulary (or unique words) in this sentence is (cat, mat, on, sat, the). To represent each word, you will create a zero vector with length equal to the vocabulary, then place a one in the index that corresponds to the word. This approach is shown in the following diagram.
<img src="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/images/one-hot.png?raw=1" alt="Diagram of one-hot encodings" width="400" />
To create a vector that contains the encoding of the sentence, you could then concatenate the one-hot vectors for each word.
Key point: This approach is inefficient. A one-hot encoded vector is sparse (meaning, most indices are zero). Imagine you have 10,000 words in the vocabulary. To one-hot encode each word, you would create a vector where 99.99% of the elements are zero.
### Encode each word with a unique number
A second approach you might try is to encode each word using a unique number. Continuing the example above, you could assign 1 to "cat", 2 to "mat", and so on. You could then encode the sentence "The cat sat on the mat" as a dense vector like [5, 1, 4, 3, 5, 2]. This approach is efficient. Instead of a sparse vector, you now have a dense one (where all elements are full).
There are two downsides to this approach, however:
* The integer-encoding is arbitrary (it does not capture any relationship between words).
* An integer-encoding can be challenging for a model to interpret. A linear classifier, for example, learns a single weight for each feature. Because there is no relationship between the similarity of any two words and the similarity of their encodings, this feature-weight combination is not meaningful.
### Word embeddings
Word embeddings give us a way to use an efficient, dense representation in which similar words have a similar encoding. Importantly, you do not have to specify this encoding by hand. An embedding is a dense vector of floating point values (the length of the vector is a parameter you specify). Instead of specifying the values for the embedding manually, they are trainable parameters (weights learned by the model during training, in the same way a model learns weights for a dense layer). It is common to see word embeddings that are 8-dimensional (for small datasets), up to 1024-dimensions when working with large datasets. A higher dimensional embedding can capture fine-grained relationships between words, but takes more data to learn.
<img src="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/images/embedding2.png?raw=1" alt="Diagram of an embedding" width="400"/>
Above is a diagram for a word embedding. Each word is represented as a 4-dimensional vector of floating point values. Another way to think of an embedding is as "lookup table". After these weights have been learned, you can encode each word by looking up the dense vector it corresponds to in the table.
Each learning objective will correspond to a __#TODO__ in the [student lab notebook](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/deepdive2/text_classification/labs/word_embeddings.ipynb) -- try to complete that notebook first before reviewing this solution notebook.
## Setup
```
# Use the chown command to change the ownership of repository to user.
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
import io
import os
import re
import shutil
import string
import tensorflow as tf
from datetime import datetime
from tensorflow.keras import Model, Sequential
from tensorflow.keras.layers import Activation, Dense, Embedding, GlobalAveragePooling1D
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
```
This notebook uses TF2.x.
Please check your tensorflow version using the cell below.
```
# Show the currently installed version of TensorFlow
print("TensorFlow version: ",tf.version.VERSION)
```
### Download the IMDb Dataset
You will use the [Large Movie Review Dataset](http://ai.stanford.edu/~amaas/data/sentiment/) through the tutorial. You will train a sentiment classifier model on this dataset and in the process learn embeddings from scratch. To read more about loading a dataset from scratch, see the [Loading text tutorial](../load_data/text.ipynb).
Download the dataset using Keras file utility and take a look at the directories.
```
url = "https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"
dataset = tf.keras.utils.get_file("aclImdb_v1.tar.gz", url,
untar=True, cache_dir='.',
cache_subdir='')
dataset_dir = os.path.join(os.path.dirname(dataset), 'aclImdb')
os.listdir(dataset_dir)
```
Take a look at the `train/` directory. It has `pos` and `neg` folders with movie reviews labelled as positive and negative respectively. You will use reviews from `pos` and `neg` folders to train a binary classification model.
```
train_dir = os.path.join(dataset_dir, 'train')
os.listdir(train_dir)
```
The `train` directory also has additional folders which should be removed before creating training dataset.
```
remove_dir = os.path.join(train_dir, 'unsup')
shutil.rmtree(remove_dir)
```
Next, create a `tf.data.Dataset` using `tf.keras.preprocessing.text_dataset_from_directory`. You can read more about using this utility in this [text classification tutorial](https://www.tensorflow.org/tutorials/keras/text_classification).
Use the `train` directory to create both train and validation datasets with a split of 20% for validation.
```
batch_size = 1024
seed = 123
train_ds = tf.keras.preprocessing.text_dataset_from_directory(
'aclImdb/train', batch_size=batch_size, validation_split=0.2,
subset='training', seed=seed)
val_ds = tf.keras.preprocessing.text_dataset_from_directory(
'aclImdb/train', batch_size=batch_size, validation_split=0.2,
subset='validation', seed=seed)
```
Take a look at a few movie reviews and their labels `(1: positive, 0: negative)` from the train dataset.
```
for text_batch, label_batch in train_ds.take(1):
for i in range(5):
print(label_batch[i].numpy(), text_batch.numpy()[i])
```
### Configure the dataset for performance
These are two important methods you should use when loading data to make sure that I/O does not become blocking.
`.cache()` keeps data in memory after it's loaded off disk. This will ensure the dataset does not become a bottleneck while training your model. If your dataset is too large to fit into memory, you can also use this method to create a performant on-disk cache, which is more efficient to read than many small files.
`.prefetch()` overlaps data preprocessing and model execution while training.
You can learn more about both methods, as well as how to cache data to disk in the [data performance guide](https://www.tensorflow.org/guide/data_performance).
```
AUTOTUNE = tf.data.experimental.AUTOTUNE
train_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
```
## Using the Embedding layer
Keras makes it easy to use word embeddings. Take a look at the [Embedding](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding) layer.
The Embedding layer can be understood as a lookup table that maps from integer indices (which stand for specific words) to dense vectors (their embeddings). The dimensionality (or width) of the embedding is a parameter you can experiment with to see what works well for your problem, much in the same way you would experiment with the number of neurons in a Dense layer.
```
# Embed a 1,000 word vocabulary into 5 dimensions.
# TODO
embedding_layer = tf.keras.layers.Embedding(1000, 5)
```
When you create an Embedding layer, the weights for the embedding are randomly initialized (just like any other layer). During training, they are gradually adjusted via backpropagation. Once trained, the learned word embeddings will roughly encode similarities between words (as they were learned for the specific problem your model is trained on).
If you pass an integer to an embedding layer, the result replaces each integer with the vector from the embedding table:
```
result = embedding_layer(tf.constant([1,2,3]))
result.numpy()
```
For text or sequence problems, the Embedding layer takes a 2D tensor of integers, of shape `(samples, sequence_length)`, where each entry is a sequence of integers. It can embed sequences of variable lengths. You could feed into the embedding layer above batches with shapes `(32, 10)` (batch of 32 sequences of length 10) or `(64, 15)` (batch of 64 sequences of length 15).
The returned tensor has one more axis than the input, the embedding vectors are aligned along the new last axis. Pass it a `(2, 3)` input batch and the output is `(2, 3, N)`
```
result = embedding_layer(tf.constant([[0,1,2],[3,4,5]]))
result.shape
```
When given a batch of sequences as input, an embedding layer returns a 3D floating point tensor, of shape `(samples, sequence_length, embedding_dimensionality)`. To convert from this sequence of variable length to a fixed representation there are a variety of standard approaches. You could use an RNN, Attention, or pooling layer before passing it to a Dense layer. This tutorial uses pooling because it's the simplest. The [Text Classification with an RNN](text_classification_rnn.ipynb) tutorial is a good next step.
## Text preprocessing
Next, define the dataset preprocessing steps required for your sentiment classification model. Initialize a TextVectorization layer with the desired parameters to vectorize movie reviews. You can learn more about using this layer in the [Text Classification](https://www.tensorflow.org/tutorials/keras/text_classification) tutorial.
```
# Create a custom standardization function to strip HTML break tags '<br />'.
def custom_standardization(input_data):
lowercase = tf.strings.lower(input_data)
stripped_html = tf.strings.regex_replace(lowercase, '<br />', ' ')
return tf.strings.regex_replace(stripped_html,
'[%s]' % re.escape(string.punctuation), '')
# Vocabulary size and number of words in a sequence.
vocab_size = 10000
sequence_length = 100
# Use the text vectorization layer to normalize, split, and map strings to
# integers. Note that the layer uses the custom standardization defined above.
# Set maximum_sequence length as all samples are not of the same length.
vectorize_layer = TextVectorization(
standardize=custom_standardization,
max_tokens=vocab_size,
output_mode='int',
output_sequence_length=sequence_length)
# Make a text-only dataset (no labels) and call adapt to build the vocabulary.
text_ds = train_ds.map(lambda x, y: x)
vectorize_layer.adapt(text_ds)
```
## Create a classification model
Use the [Keras Sequential API](../../guide/keras) to define the sentiment classification model. In this case it is a "Continuous bag of words" style model.
* The [`TextVectorization`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization) layer transforms strings into vocabulary indices. You have already initialized `vectorize_layer` as a TextVectorization layer and built it's vocabulary by calling `adapt` on `text_ds`. Now vectorize_layer can be used as the first layer of your end-to-end classification model, feeding transformed strings into the Embedding layer.
* The [`Embedding`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding) layer takes the integer-encoded vocabulary and looks up the embedding vector for each word-index. These vectors are learned as the model trains. The vectors add a dimension to the output array. The resulting dimensions are: `(batch, sequence, embedding)`.
* The [`GlobalAveragePooling1D`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/GlobalAveragePooling1D) layer returns a fixed-length output vector for each example by averaging over the sequence dimension. This allows the model to handle input of variable length, in the simplest way possible.
* The fixed-length output vector is piped through a fully-connected ([`Dense`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense)) layer with 16 hidden units.
* The last layer is densely connected with a single output node.
Caution: This model doesn't use masking, so the zero-padding is used as part of the input and hence the padding length may affect the output. To fix this, see the [masking and padding guide](../../guide/keras/masking_and_padding).
```
embedding_dim=16
# TODO
model = Sequential([
vectorize_layer,
Embedding(vocab_size, embedding_dim, name="embedding"),
GlobalAveragePooling1D(),
Dense(16, activation='relu'),
Dense(1)
])
```
## Compile and train the model
Create a `tf.keras.callbacks.TensorBoard`.
```
# TODO
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir="logs")
```
Compile and train the model using the `Adam` optimizer and `BinaryCrossentropy` loss.
```
# TODO
model.compile(optimizer='adam',
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(
train_ds,
validation_data=val_ds,
epochs=10,
callbacks=[tensorboard_callback])
```
With this approach the model reaches a validation accuracy of around 84% (note that the model is overfitting since training accuracy is higher).
Note: Your results may be a bit different, depending on how weights were randomly initialized before training the embedding layer.
You can look into the model summary to learn more about each layer of the model.
```
model.summary()
```
Visualize the model metrics in TensorBoard.
```
!tensorboard --bind_all --port=8081 --logdir logs
```
Run the following command in **Cloud Shell**:
<code>gcloud beta compute ssh --zone <instance-zone> <notebook-instance-name> --project <project-id> -- -L 8081:localhost:8081</code>
Make sure to replace <instance-zone>, <notebook-instance-name> and <project-id>.
In Cloud Shell, click **Web Preview** > **Change Port** and insert port number **8081**. Click **Change and Preview** to open the TensorBoard.

**To quit the TensorBoard, click Kernel > Interrupt kernel**.
## Retrieve the trained word embeddings and save them to disk
Next, retrieve the word embeddings learned during training. The embeddings are weights of the Embedding layer in the model. The weights matrix is of shape `(vocab_size, embedding_dimension)`.
Obtain the weights from the model using `get_layer()` and `get_weights()`. The `get_vocabulary()` function provides the vocabulary to build a metadata file with one token per line.
```
# TODO
weights = model.get_layer('embedding').get_weights()[0]
vocab = vectorize_layer.get_vocabulary()
```
Write the weights to disk. To use the [Embedding Projector](http://projector.tensorflow.org), you will upload two files in tab separated format: a file of vectors (containing the embedding), and a file of meta data (containing the words).
```
out_v = io.open('vectors.tsv', 'w', encoding='utf-8')
out_m = io.open('metadata.tsv', 'w', encoding='utf-8')
for index, word in enumerate(vocab):
if index == 0: continue # skip 0, it's padding.
vec = weights[index]
out_v.write('\t'.join([str(x) for x in vec]) + "\n")
out_m.write(word + "\n")
out_v.close()
out_m.close()
```
Two files will created as `vectors.tsv` and `metadata.tsv`. Download both files.
```
try:
from google.colab import files
files.download('vectors.tsv')
files.download('metadata.tsv')
except Exception as e:
pass
```
## Visualize the embeddings
To visualize the embeddings, upload them to the embedding projector.
Open the [Embedding Projector](http://projector.tensorflow.org/).
* Click on "Load".
* Upload the two files you created above: `vecs.tsv` and `meta.tsv`.
The embeddings you have trained will now be displayed. You can search for words to find their closest neighbors. For example, try searching for "beautiful". You may see neighbors like "wonderful".
Note: Experimentally, you may be able to produce more interpretable embeddings by using a simpler model. Try deleting the `Dense(16)` layer, retraining the model, and visualizing the embeddings again.
Note: Typically, a much larger dataset is needed to train more interpretable word embeddings. This tutorial uses a small IMDb dataset for the purpose of demonstration.
## Next Steps
This tutorial has shown you how to train and visualize word embeddings from scratch on a small dataset.
* To train word embeddings using Word2Vec algorithm, try the [Word2Vec](https://www.tensorflow.org/tutorials/text/word2vec) tutorial.
* To learn more about advanced text processing, read the [Transformer model for language understanding](https://www.tensorflow.org/tutorials/text/transformer).
| github_jupyter |
# Unit 1: Exploratory Data Analysis on the MovieLens 100k Dataset
In these lessons, we will be working a lot with [pandas](https://pandas.pydata.org/pandas-docs/stable/user_guide/10min.html) and numpy - so please take the time to at least get yourself familiar with it, e.g. with [10 Minutes to Pandas](https://pandas.pydata.org/pandas-docs/stable/user_guide/10min.html).
The [MovieLens](https://grouplens.org/datasets/movielens/) datasets are for recommender systems practitioners and researchers what MNIST is for computer vision people. Of course, the MovieLens datasets are not the only public datasets used in the RecSys community, but one of the most widely used. There are also the
* [Million Song Dataset](http://millionsongdataset.com/)
* [Amazon product review dataset](https://nijianmo.github.io/amazon/index.html)
* [Criteo datasets](https://labs.criteo.com/category/dataset/)
* [Twitter RecSys Challenge 2020](https://recsys-twitter.com/previous_challenge)
* [Spotify Million Playlist Dataset](https://www.aicrowd.com/challenges/spotify-million-playlist-dataset-challenge)
* [YooChoose RecSys Challenge 2015](https://www.kaggle.com/chadgostopp/recsys-challenge-2015)
* [BookCrossings](http://www2.informatik.uni-freiburg.de/~cziegler/BX/) and many more
On _kdnuggets_ you can find a [simple overview](https://www.kdnuggets.com/2016/02/nine-datasets-investigating-recommender-systems.html) of some of them.
MovieLens comes in different sizes regarding the number of movie ratings, user, items. Take a look at the GroupLens website and explore them youself.
```
import numpy as np
import pandas as pd
import seaborn as sns
from recsys_training.data import genres
ml100k_ratings_filepath = '../../data/raw/ml-100k/u.data'
ml100k_item_filepath = '../../data/raw/ml-100k/u.item'
ml100k_user_filepath = '../../data/raw/ml-100k/u.user'
```
## Load Data
```
ratings = pd.read_csv(ml100k_ratings_filepath,
sep='\t',
header=None,
names=['user', 'item', 'rating', 'timestamp'],
engine='python')
items = pd.read_csv(ml100k_item_filepath, sep='|', header=None,
names=['item', 'title', 'release', 'video_release', 'imdb_url']+genres,
engine='python')
users = pd.read_csv(ml100k_user_filepath, sep='|', header=None,
names=['user', 'age', 'gender', 'occupation', 'zip'])
```
## Data Exploration
In this unit, we like to get a better picture of the data we use for making recommendations in the upcoming units. Therefore, let's review some statistics to become confident with the data.

**Task:**
Let's look into the following:
* number of users
* number of items
* rating distribution
* user / item mean ratings
* popularity skewness
* user rating count distribution
* item rating count distribution
* time
* sparsity
* user / item features
### number of users
```
n_users = ratings['user'].unique().shape[0]
n_users
ratings['user'].unique().min()
ratings['user'].unique().max()
```
### number of items
```
n_items = ratings['item'].unique().shape[0]
n_items
ratings['item'].unique().min()
ratings['item'].unique().max()
```
### rating distribution
```
ratings['rating'].value_counts().sort_index()
ratings['rating'].value_counts(normalize=True).sort_index()
sns.barplot(x=ratings['rating'].value_counts(normalize=True).sort_index().index,
y=ratings['rating'].value_counts(normalize=True).sort_index().values)
ratings['rating'].describe()
```
### user rating count distribution
```
quantiles
quantiles = ratings['user'].value_counts(normalize=True).cumsum()
sns.lineplot(np.arange(n_users)/n_users+1/n_users,
quantiles)
```
### item rating count distribution
```
quantiles = ratings['item'].value_counts(normalize=True).cumsum()
sns.lineplot(np.arange(n_items)/n_items+1/n_items,
quantiles)
```
### user mean ratings
```
user_mean_ratings = ratings[['user', 'rating']].groupby('user').mean().reset_index(drop=True)
sns.displot(user_mean_ratings)
```
### item mean ratings
```
item_mean_ratings = ratings[['item', 'rating']].groupby('item').mean().reset_index(drop=True)
sns.displot(item_mean_ratings)
```
### sparsity
```
n_users
n_items
# count the uniquely observed ratings
observed_ratings = ratings[['user', 'item']].drop_duplicates().shape[0]
observed_ratings
potential_ratings = n_users * n_items
potential_ratings
density = observed_ratings / potential_ratings
density
sparsity = 1 - density
sparsity
```
| github_jupyter |
# 函数
- 函数可以用来定义可重复代码,组织和简化
- 一般来说一个函数在实际开发中为一个小功能
- 一个类为一个大功能
- 同样函数的长度不要超过一屏
Python中的所有函数实际上都是有返回值(return None),
如果你没有设置return,那么Python将不显示None.
如果你设置return,那么将返回出return这个值.
## 定义一个函数
def function_name(list of parameters):
do something

- 以前使用的random 或者range 或者print.. 其实都是函数或者类
```
def max_(num1,num2,num3):
if num1>num2:
result1=num1
else:
result1=num2
if num3>result1:
result2=num3
else:
result2=result1
return(result2)
max_(num1=3,num2=5,num3=2)
import random
i=random.randint(1,5)
def cai(n):
if n>i:
return('太大了')
elif n<i:
return('太小了')
elif n==i:
return('正好')
cai(n=4)
```
函数的参数如果有默认值的情况,当你调用该函数的时候:
可以不给予参数值,那么就会走该参数的默认值
否则的话,就走你给予的参数值.
## 调用一个函数
- functionName()
- "()" 就代表调用
```
def h():
print('ikjik')
def b():
h()
b()
def a(f):
f()
(a(b))
def HJN():
print('jjjj')
HJN()
def HJN(name):
print(name,'yuu')
HJN('JJMJ')
def jiou(number):
if number % 2==0:
print('偶数')
else:
print('奇数')
jiou(number=1)
def HJN(name1,name2):
print(name1,'fref')
print(name2,'hsdjs')
HJN(name1='hhh',name2='ijckw')
def HJN(name1,name2='hhjn'):#默认参数只能在最后
print(name1,'fref')
print(name2,'hsdjs')
HJN(name1='hhh')
def HJN():
print('fffff')
```

## 带返回值和不带返回值的函数
- return 返回的内容
- return 返回多个值
- 一般情况下,在多个函数协同完成一个功能的时候,那么将会有返回值
```
def HJN():
print('fffff')
return('100')
HJN()
```

- 当然也可以自定义返回None
## EP:

```
def t():
print('gggg')
def y():
print(t())
y()
def main():
print(min(8,7))
def min(n1,n2):
smallest=n1
if n2<smallest:
smallest=n2
main()
def feizhuliu(name):
print('Hello',name)
feizhuliu(name='wang')
def gggg(*,name,name2,name3='llll'):
print('Hello',name)
gggg(name='wang',name2='haha')
```
## 类型和关键字参数
- 普通参数
- 多个参数
- 默认值参数
- 不定长参数
## 普通参数
## 多个参数
## 默认值参数
## 强制命名
## 不定长参数
- \*args
> - 不定长,来多少装多少,不装也是可以的
- 返回的数据类型是元组
- args 名字是可以修改的,只是我们约定俗成的是args
- \**kwargs
> - 返回的字典
- 输入的一定要是表达式(键值对)
- name,\*args,name2,\**kwargs 使用参数名
```
def joker(*args):
print(args)
joker(1,2,3,4,5,6,555,563)
def max_(*args):
res=0
for i in args:
if i>res:
res=i
return res
max_(1,6,89)
def sum_(*arg):
n=0
for j in arg:
n=n+j
return n
sum_(2,6,3)
def agv_(*arar):
d=0
n=0
for h in arar:
d=d+h
n+=1
f=d/n
return f
agv_(2,3,1)
def ttt(**kwargs):
print(kwargs)
ttt(a=1,b=2,c=3)
def f(*args,**kwargs):
pass
```
## 变量的作用域
- 局部变量 local
- 全局变量 global
- globals 函数返回一个全局变量的字典,包括所有导入的变量
- locals() 函数会以字典类型返回当前位置的全部局部变量。
```
r=1000
def rr():
print(r)
rr()
t=1000
def tt():
global t
t+=1
print(t)
tt()
t=1000
y=12
def tt():
global t,y
t+=1
print(t,y)
num=1000
def tt(num):
num+=100
print(num)
tt()
tt()
r=1000
def rr():
r=100
r+=11
print(r)
rr()
```
## 注意:
- global :在进行赋值操作的时候需要声明
- 官方解释:This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.
- 
```
#统计大写字母的个数和小写字母的个数
def bbb(*arare):
n=0
j=0
k=0
for i in arare:
m=ord(i)
if 65<=m<=90:
n+=1
return n
if 97<=m<=122:
j+=1
return j
if m<65 or m>122:
k+=1
return k
bbb('o','W','k','2')
def bbb(*arare):
daxie=0
xiaoxie=0
shuzi=0
for i in arare:
m=ord(i)
if 65<=m<=90:
daxie+=1
elif 97<=m<=122:
xiaoxie+=1
elif 48<=m<=57:
shuzi+=1
return daxie,xiaoxie,shuzi
bbb('o','W','k','2')
def sum_(n):
res=0
if n%2==0:
for i in range(2,n+1,2):
res +=1/i
else:
for j in range(1,n+1,2):
res+=1/j
return res
sum_(2)
def s(a,count):
sum_=0
n=0
for i in range(count):
n+=1
sum_+=(a*(10**(n-1))+a
return sum_
s(1,2)
def a():
num=input('>>')
n=input('>>')
res=0
for i in range(1,int(n)+1):
print(num*i)
res+=int(num*i)
return res
a()
def aa(a,n):
res=0
for j in range(n):
for i in range(j+1):
res+=a*10**i
return res
aa(1,3)
def ss(n):
m=0
res=0
for i in range(1,n+1):
rres=1
for j in range(1,i+1):
rres*=j
m=m+rres
return m
ss(3)
```
# Homework
- 1

```
def getpentagonalnumber(n):
hang=0
for i in range (1,n):
m=i*(3*i-1)/2
print(int(m),end=' ')
hang+=1
if hang%10==0:
print()
getpentagonalnumber(101)
```
- 2

```
def sumd(number):
d=0
while number>0:
d+=number%10
number=number//10
print(d)
sumd(987)
```
- 3

```
def displaysortednumbers(num1,num2,num3):
num1,num2,num3=eval(input('Enter three numbers: '))
if num1>num2>num3:
print(num1,num2,num3)
if num1>num3>num2:
print(num1,num3,num2)
if num2>num1>num3:
print(num2,num1,num3)
if num2>num3>num1:
print(num2,num3,num1)
if num3>num2>num1:
print(num3,num2,num1)
if num3>num1>num2:
print(num3,num1,num2)
displaysortednumbers(3,8,1)
```
- 4

```
def future(invest,month,years):
```
- 5

```
def printchars(ch1,ch2,numberperline):
m=ord(ch1)
n=ord(ch2)
numberperline=0
for i in range(m,n+1):
zifu=chr(i)
print(zifu,end=' ')
numberperline+=1
if numberperline%10==0:
print()
printchars('I','Z',10)
```
- 6

```
def numberofdays(year1,year2):
for i in range(year1,year2+1):
if (i%4==0 and i%100!=0) or (i%400==0):
print('366')
else:
print('365')
numberofdays(2010,2020)
```
- 7

```
def distance(x1,y1,x2,y2):
m=((x2-x1)**2+(y2-y1)**2)**0.5
return m
distance(1,2,3,3)
```
- 8

```
for i in range(2,50):
for j in range(2,i):
if i%j==0:
break
else:
m=i
for p in range(0,32):
if m==2**p-1:
print(p,m)
```
- 9


```
def datime(time):
time()
time()
```
- 10

```
import random
i=random.randint(1,6)
j=random.randint(1,6)
if i+j==2:
print(i,'+',j,'=',i+j)
print('You lose')
elif i+j==3:
print(i,'+',j,'=',i+j)
print('You lose')
elif i+j==12:
print(i,'+',j,'=',i+j)
print('You lose')
elif i+j==7:
print(i,'+',j,'=',i+j)
print('You win')
elif i+j==11:
print(i,'+',j,'=',i+j)
print('You win')
elif i+j==4:
print(i,'+',j,'=',i+j)
print('point is',i+j)
m=random.randint(1,6)
n=random.randint(1,6)
elif i+j==5:
print(i,'+',j,'=',i+j)
print('point is',i+j)
m=random.randint(1,6)
n=random.randint(1,6)
elif i+j==6:
print(i,'+',j,'=',i+j)
print('point is',i+j)
m=random.randint(1,6)
n=random.randint(1,6)
elif i+j==8:
print(i,'+',j,'=',i+j)
print('point is',i+j)
m=random.randint(1,6)
n=random.randint(1,6)
elif i+j==9:
print(i,'+',j,'=',i+j)
print('point is',i+j)
m=random.randint(1,6)
n=random.randint(1,6)
elif i+j==10:
print(i,'+',j,'=',i+j)
print('point is',i+j)
m=random.randint(1,6)
n=random.randint(1,6)
if m+n==7:
print('You lose')
if m+n==i+j:
print(m,'+',n,'=',m+n)
print('You win')
```
- 11
### 去网上寻找如何用Python代码发送邮件
| github_jupyter |
# Autonomous driving - Car detection
Welcome to your week 3 programming assignment. You will learn about object detection using the very powerful YOLO model. Many of the ideas in this notebook are described in the two YOLO papers: Redmon et al., 2016 (https://arxiv.org/abs/1506.02640) and Redmon and Farhadi, 2016 (https://arxiv.org/abs/1612.08242).
**You will learn to**:
- Use object detection on a car detection dataset
- Deal with bounding boxes
Run the following cell to load the packages and dependencies that are going to be useful for your journey!
```
import argparse
import os
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import scipy.io
import scipy.misc
import numpy as np
import pandas as pd
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import load_model, Model
from yolo_utils import read_classes, read_anchors, generate_colors, preprocess_image, draw_boxes, scale_boxes
from yad2k.models.keras_yolo import yolo_head, yolo_boxes_to_corners, preprocess_true_boxes, yolo_loss, yolo_body
%matplotlib inline
```
**Important Note**: As you can see, we import Keras's backend as K. This means that to use a Keras function in this notebook, you will need to write: `K.function(...)`.
## 1 - Problem Statement
You are working on a self-driving car. As a critical component of this project, you'd like to first build a car detection system. To collect data, you've mounted a camera to the hood (meaning the front) of the car, which takes pictures of the road ahead every few seconds while you drive around.
<center>
<video width="400" height="200" src="nb_images/road_video_compressed2.mp4" type="video/mp4" controls>
</video>
</center>
<caption><center> Pictures taken from a car-mounted camera while driving around Silicon Valley. <br> We would like to especially thank [drive.ai](https://www.drive.ai/) for providing this dataset! Drive.ai is a company building the brains of self-driving vehicles.
</center></caption>
<img src="nb_images/driveai.png" style="width:100px;height:100;">
You've gathered all these images into a folder and have labelled them by drawing bounding boxes around every car you found. Here's an example of what your bounding boxes look like.
<img src="nb_images/box_label.png" style="width:500px;height:250;">
<caption><center> <u> **Figure 1** </u>: **Definition of a box**<br> </center></caption>
If you have 80 classes that you want YOLO to recognize, you can represent the class label $c$ either as an integer from 1 to 80, or as an 80-dimensional vector (with 80 numbers) one component of which is 1 and the rest of which are 0. The video lectures had used the latter representation; in this notebook, we will use both representations, depending on which is more convenient for a particular step.
In this exercise, you will learn how YOLO works, then apply it to car detection. Because the YOLO model is very computationally expensive to train, we will load pre-trained weights for you to use.
## 2 - YOLO
YOLO ("you only look once") is a popular algoritm because it achieves high accuracy while also being able to run in real-time. This algorithm "only looks once" at the image in the sense that it requires only one forward propagation pass through the network to make predictions. After non-max suppression, it then outputs recognized objects together with the bounding boxes.
### 2.1 - Model details
First things to know:
- The **input** is a batch of images of shape (m, 608, 608, 3)
- The **output** is a list of bounding boxes along with the recognized classes. Each bounding box is represented by 6 numbers $(p_c, b_x, b_y, b_h, b_w, c)$ as explained above. If you expand $c$ into an 80-dimensional vector, each bounding box is then represented by 85 numbers.
We will use 5 anchor boxes. So you can think of the YOLO architecture as the following: IMAGE (m, 608, 608, 3) -> DEEP CNN -> ENCODING (m, 19, 19, 5, 85).
Lets look in greater detail at what this encoding represents.
<img src="nb_images/architecture.png" style="width:700px;height:400;">
<caption><center> <u> **Figure 2** </u>: **Encoding architecture for YOLO**<br> </center></caption>
If the center/midpoint of an object falls into a grid cell, that grid cell is responsible for detecting that object.
Since we are using 5 anchor boxes, each of the 19 x19 cells thus encodes information about 5 boxes. Anchor boxes are defined only by their width and height.
For simplicity, we will flatten the last two last dimensions of the shape (19, 19, 5, 85) encoding. So the output of the Deep CNN is (19, 19, 425).
<img src="nb_images/flatten.png" style="width:700px;height:400;">
<caption><center> <u> **Figure 3** </u>: **Flattening the last two last dimensions**<br> </center></caption>
Now, for each box (of each cell) we will compute the following elementwise product and extract a probability that the box contains a certain class.
<img src="nb_images/probability_extraction.png" style="width:700px;height:400;">
<caption><center> <u> **Figure 4** </u>: **Find the class detected by each box**<br> </center></caption>
Here's one way to visualize what YOLO is predicting on an image:
- For each of the 19x19 grid cells, find the maximum of the probability scores (taking a max across both the 5 anchor boxes and across different classes).
- Color that grid cell according to what object that grid cell considers the most likely.
Doing this results in this picture:
<img src="nb_images/proba_map.png" style="width:300px;height:300;">
<caption><center> <u> **Figure 5** </u>: Each of the 19x19 grid cells colored according to which class has the largest predicted probability in that cell.<br> </center></caption>
Note that this visualization isn't a core part of the YOLO algorithm itself for making predictions; it's just a nice way of visualizing an intermediate result of the algorithm.
Another way to visualize YOLO's output is to plot the bounding boxes that it outputs. Doing that results in a visualization like this:
<img src="nb_images/anchor_map.png" style="width:200px;height:200;">
<caption><center> <u> **Figure 6** </u>: Each cell gives you 5 boxes. In total, the model predicts: 19x19x5 = 1805 boxes just by looking once at the image (one forward pass through the network)! Different colors denote different classes. <br> </center></caption>
In the figure above, we plotted only boxes that the model had assigned a high probability to, but this is still too many boxes. You'd like to filter the algorithm's output down to a much smaller number of detected objects. To do so, you'll use non-max suppression. Specifically, you'll carry out these steps:
- Get rid of boxes with a low score (meaning, the box is not very confident about detecting a class)
- Select only one box when several boxes overlap with each other and detect the same object.
### 2.2 - Filtering with a threshold on class scores
You are going to apply a first filter by thresholding. You would like to get rid of any box for which the class "score" is less than a chosen threshold.
The model gives you a total of 19x19x5x85 numbers, with each box described by 85 numbers. It'll be convenient to rearrange the (19,19,5,85) (or (19,19,425)) dimensional tensor into the following variables:
- `box_confidence`: tensor of shape $(19 \times 19, 5, 1)$ containing $p_c$ (confidence probability that there's some object) for each of the 5 boxes predicted in each of the 19x19 cells.
- `boxes`: tensor of shape $(19 \times 19, 5, 4)$ containing $(b_x, b_y, b_h, b_w)$ for each of the 5 boxes per cell.
- `box_class_probs`: tensor of shape $(19 \times 19, 5, 80)$ containing the detection probabilities $(c_1, c_2, ... c_{80})$ for each of the 80 classes for each of the 5 boxes per cell.
**Exercise**: Implement `yolo_filter_boxes()`.
1. Compute box scores by doing the elementwise product as described in Figure 4. The following code may help you choose the right operator:
```python
a = np.random.randn(19*19, 5, 1)
b = np.random.randn(19*19, 5, 80)
c = a * b # shape of c will be (19*19, 5, 80)
```
2. For each box, find:
- the index of the class with the maximum box score ([Hint](https://keras.io/backend/#argmax)) (Be careful with what axis you choose; consider using axis=-1)
- the corresponding box score ([Hint](https://keras.io/backend/#max)) (Be careful with what axis you choose; consider using axis=-1)
3. Create a mask by using a threshold. As a reminder: `([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4)` returns: `[False, True, False, False, True]`. The mask should be True for the boxes you want to keep.
4. Use TensorFlow to apply the mask to box_class_scores, boxes and box_classes to filter out the boxes we don't want. You should be left with just the subset of boxes you want to keep. ([Hint](https://www.tensorflow.org/api_docs/python/tf/boolean_mask))
Reminder: to call a Keras function, you should use `K.function(...)`.
```
# GRADED FUNCTION: yolo_filter_boxes
def yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = .6):
"""Filters YOLO boxes by thresholding on object and class confidence.
Arguments:
box_confidence -- tensor of shape (19, 19, 5, 1)
boxes -- tensor of shape (19, 19, 5, 4)
box_class_probs -- tensor of shape (19, 19, 5, 80)
threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box
Returns:
scores -- tensor of shape (None,), containing the class probability score for selected boxes
boxes -- tensor of shape (None, 4), containing (b_x, b_y, b_h, b_w) coordinates of selected boxes
classes -- tensor of shape (None,), containing the index of the class detected by the selected boxes
Note: "None" is here because you don't know the exact number of selected boxes, as it depends on the threshold.
For example, the actual output size of scores would be (10,) if there are 10 boxes.
"""
# Step 1: Compute box scores
### START CODE HERE ### (≈ 1 line)
box_scores = box_confidence * box_class_probs
### END CODE HERE ###
# Step 2: Find the box_classes thanks to the max box_scores, keep track of the corresponding score
### START CODE HERE ### (≈ 2 lines)
box_classes = K.argmax(box_scores, axis=-1)
box_class_scores = K.max(box_scores, axis=-1)
### END CODE HERE ###
# Step 3: Create a filtering mask based on "box_class_scores" by using "threshold". The mask should have the
# same dimension as box_class_scores, and be True for the boxes you want to keep (with probability >= threshold)
### START CODE HERE ### (≈ 1 line)
filtering_mask = ((box_class_scores) >= threshold)
### END CODE HERE ###
# Step 4: Apply the mask to scores, boxes and classes
### START CODE HERE ### (≈ 3 lines)
scores = tf.boolean_mask(box_class_scores, filtering_mask, name='boolean_mask')
boxes = tf.boolean_mask(boxes, filtering_mask, name='boolean_mask')
classes = tf.boolean_mask(box_classes, filtering_mask, name='boolean_mask')
### END CODE HERE ###
return scores, boxes, classes
with tf.Session() as test_a:
box_confidence = tf.random_normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1)
boxes = tf.random_normal([19, 19, 5, 4], mean=1, stddev=4, seed = 1)
box_class_probs = tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1)
scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = 0.5)
print("scores[2] = " + str(scores[2].eval()))
print("boxes[2] = " + str(boxes[2].eval()))
print("classes[2] = " + str(classes[2].eval()))
print("scores.shape = " + str(scores.shape))
print("boxes.shape = " + str(boxes.shape))
print("classes.shape = " + str(classes.shape))
```
**Expected Output**:
<table>
<tr>
<td>
**scores[2]**
</td>
<td>
10.7506
</td>
</tr>
<tr>
<td>
**boxes[2]**
</td>
<td>
[ 8.42653275 3.27136683 -0.5313437 -4.94137383]
</td>
</tr>
<tr>
<td>
**classes[2]**
</td>
<td>
7
</td>
</tr>
<tr>
<td>
**scores.shape**
</td>
<td>
(?,)
</td>
</tr>
<tr>
<td>
**boxes.shape**
</td>
<td>
(?, 4)
</td>
</tr>
<tr>
<td>
**classes.shape**
</td>
<td>
(?,)
</td>
</tr>
</table>
### 2.3 - Non-max suppression ###
Even after filtering by thresholding over the classes scores, you still end up a lot of overlapping boxes. A second filter for selecting the right boxes is called non-maximum suppression (NMS).
<img src="nb_images/non-max-suppression.png" style="width:500px;height:400;">
<caption><center> <u> **Figure 7** </u>: In this example, the model has predicted 3 cars, but it's actually 3 predictions of the same car. Running non-max suppression (NMS) will select only the most accurate (highest probabiliy) one of the 3 boxes. <br> </center></caption>
Non-max suppression uses the very important function called **"Intersection over Union"**, or IoU.
<img src="nb_images/iou.png" style="width:500px;height:400;">
<caption><center> <u> **Figure 8** </u>: Definition of "Intersection over Union". <br> </center></caption>
**Exercise**: Implement iou(). Some hints:
- In this exercise only, we define a box using its two corners (upper left and lower right): `(x1, y1, x2, y2)` rather than the midpoint and height/width.
- To calculate the area of a rectangle you need to multiply its height `(y2 - y1)` by its width `(x2 - x1)`.
- You'll also need to find the coordinates `(xi1, yi1, xi2, yi2)` of the intersection of two boxes. Remember that:
- xi1 = maximum of the x1 coordinates of the two boxes
- yi1 = maximum of the y1 coordinates of the two boxes
- xi2 = minimum of the x2 coordinates of the two boxes
- yi2 = minimum of the y2 coordinates of the two boxes
- In order to compute the intersection area, you need to make sure the height and width of the intersection are positive, otherwise the intersection area should be zero. Use `max(height, 0)` and `max(width, 0)`.
In this code, we use the convention that (0,0) is the top-left corner of an image, (1,0) is the upper-right corner, and (1,1) the lower-right corner.
```
# GRADED FUNCTION: iou
def iou(box1, box2):
"""Implement the intersection over union (IoU) between box1 and box2
Arguments:
box1 -- first box, list object with coordinates (x1, y1, x2, y2)
box2 -- second box, list object with coordinates (x1, y1, x2, y2)
"""
# Calculate the (y1, x1, y2, x2) coordinates of the intersection of box1 and box2. Calculate its Area.
### START CODE HERE ### (≈ 5 lines)
xi1 = max(box1[0], box2[0])
yi1 = max(box1[1], box2[1])
xi2 = min(box1[2], box2[2])
yi2 = min(box1[3], box2[3])
inter_area = max(yi2 - yi1, 0) * max(xi2 - xi1, 0)
### END CODE HERE ###
# Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B)
### START CODE HERE ### (≈ 3 lines)
box1_area = (box1[3] - box1[1]) * (box1[2] - box1[0])
box2_area = (box2[3] - box2[1]) * (box2[2] - box2[0])
union_area = box1_area + box2_area - inter_area
### END CODE HERE ###
# compute the IoU
### START CODE HERE ### (≈ 1 line)
iou = inter_area / union_area
### END CODE HERE ###
return iou
box1 = (2, 1, 4, 3)
box2 = (1, 2, 3, 4)
print("iou = " + str(iou(box1, box2)))
```
**Expected Output**:
<table>
<tr>
<td>
**iou = **
</td>
<td>
0.14285714285714285
</td>
</tr>
</table>
You are now ready to implement non-max suppression. The key steps are:
1. Select the box that has the highest score.
2. Compute its overlap with all other boxes, and remove boxes that overlap it more than `iou_threshold`.
3. Go back to step 1 and iterate until there's no more boxes with a lower score than the current selected box.
This will remove all boxes that have a large overlap with the selected boxes. Only the "best" boxes remain.
**Exercise**: Implement yolo_non_max_suppression() using TensorFlow. TensorFlow has two built-in functions that are used to implement non-max suppression (so you don't actually need to use your `iou()` implementation):
- [tf.image.non_max_suppression()](https://www.tensorflow.org/api_docs/python/tf/image/non_max_suppression)
- [K.gather()](https://www.tensorflow.org/api_docs/python/tf/keras/backend/gather)
```
# GRADED FUNCTION: yolo_non_max_suppression
def yolo_non_max_suppression(scores, boxes, classes, max_boxes = 10, iou_threshold = 0.5):
"""
Applies Non-max suppression (NMS) to set of boxes
Arguments:
scores -- tensor of shape (None,), output of yolo_filter_boxes()
boxes -- tensor of shape (None, 4), output of yolo_filter_boxes() that have been scaled to the image size (see later)
classes -- tensor of shape (None,), output of yolo_filter_boxes()
max_boxes -- integer, maximum number of predicted boxes you'd like
iou_threshold -- real value, "intersection over union" threshold used for NMS filtering
Returns:
scores -- tensor of shape (, None), predicted score for each box
boxes -- tensor of shape (4, None), predicted box coordinates
classes -- tensor of shape (, None), predicted class for each box
Note: The "None" dimension of the output tensors has obviously to be less than max_boxes. Note also that this
function will transpose the shapes of scores, boxes, classes. This is made for convenience.
"""
max_boxes_tensor = K.variable(max_boxes, dtype='int32') # tensor to be used in tf.image.non_max_suppression()
K.get_session().run(tf.variables_initializer([max_boxes_tensor])) # initialize variable max_boxes_tensor
# Use tf.image.non_max_suppression() to get the list of indices corresponding to boxes you keep
### START CODE HERE ### (≈ 1 line)
nms_indices = tf.image.non_max_suppression(boxes = boxes, scores = scores, max_output_size = max_boxes, iou_threshold = iou_threshold)
### END CODE HERE ###
# Use K.gather() to select only nms_indices from scores, boxes and classes
### START CODE HERE ### (≈ 3 lines)
scores = K.gather(scores, nms_indices)
boxes = K.gather(boxes, nms_indices)
classes = K.gather(classes, nms_indices)
### END CODE HERE ###
return scores, boxes, classes
with tf.Session() as test_b:
scores = tf.random_normal([54,], mean=1, stddev=4, seed = 1)
boxes = tf.random_normal([54, 4], mean=1, stddev=4, seed = 1)
classes = tf.random_normal([54,], mean=1, stddev=4, seed = 1)
scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes)
print("scores[2] = " + str(scores[2].eval()))
print("boxes[2] = " + str(boxes[2].eval()))
print("classes[2] = " + str(classes[2].eval()))
print("scores.shape = " + str(scores.eval().shape))
print("boxes.shape = " + str(boxes.eval().shape))
print("classes.shape = " + str(classes.eval().shape))
```
**Expected Output**:
<table>
<tr>
<td>
**scores[2]**
</td>
<td>
6.9384
</td>
</tr>
<tr>
<td>
**boxes[2]**
</td>
<td>
[-5.299932 3.13798141 4.45036697 0.95942086]
</td>
</tr>
<tr>
<td>
**classes[2]**
</td>
<td>
-2.24527
</td>
</tr>
<tr>
<td>
**scores.shape**
</td>
<td>
(10,)
</td>
</tr>
<tr>
<td>
**boxes.shape**
</td>
<td>
(10, 4)
</td>
</tr>
<tr>
<td>
**classes.shape**
</td>
<td>
(10,)
</td>
</tr>
</table>
### 2.4 Wrapping up the filtering
It's time to implement a function taking the output of the deep CNN (the 19x19x5x85 dimensional encoding) and filtering through all the boxes using the functions you've just implemented.
**Exercise**: Implement `yolo_eval()` which takes the output of the YOLO encoding and filters the boxes using score threshold and NMS. There's just one last implementational detail you have to know. There're a few ways of representing boxes, such as via their corners or via their midpoint and height/width. YOLO converts between a few such formats at different times, using the following functions (which we have provided):
```python
boxes = yolo_boxes_to_corners(box_xy, box_wh)
```
which converts the yolo box coordinates (x,y,w,h) to box corners' coordinates (x1, y1, x2, y2) to fit the input of `yolo_filter_boxes`
```python
boxes = scale_boxes(boxes, image_shape)
```
YOLO's network was trained to run on 608x608 images. If you are testing this data on a different size image--for example, the car detection dataset had 720x1280 images--this step rescales the boxes so that they can be plotted on top of the original 720x1280 image.
Don't worry about these two functions; we'll show you where they need to be called.
```
# GRADED FUNCTION: yolo_eval
def yolo_eval(yolo_outputs, image_shape = (720., 1280.), max_boxes=10, score_threshold=.6, iou_threshold=.5):
"""
Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes.
Arguments:
yolo_outputs -- output of the encoding model (for image_shape of (608, 608, 3)), contains 4 tensors:
box_confidence: tensor of shape (None, 19, 19, 5, 1)
box_xy: tensor of shape (None, 19, 19, 5, 2)
box_wh: tensor of shape (None, 19, 19, 5, 2)
box_class_probs: tensor of shape (None, 19, 19, 5, 80)
image_shape -- tensor of shape (2,) containing the input shape, in this notebook we use (608., 608.) (has to be float32 dtype)
max_boxes -- integer, maximum number of predicted boxes you'd like
score_threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box
iou_threshold -- real value, "intersection over union" threshold used for NMS filtering
Returns:
scores -- tensor of shape (None, ), predicted score for each box
boxes -- tensor of shape (None, 4), predicted box coordinates
classes -- tensor of shape (None,), predicted class for each box
"""
### START CODE HERE ###
# Retrieve outputs of the YOLO model (≈1 line)
box_confidence, box_xy, box_wh, box_class_probs = yolo_outputs[0], yolo_outputs[1], yolo_outputs[2], yolo_outputs[3]
# Convert boxes to be ready for filtering functions
boxes = yolo_boxes_to_corners(box_xy, box_wh)
# Use one of the functions you've implemented to perform Score-filtering with a threshold of score_threshold (≈1 line)
scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = 0.5)
# Scale boxes back to original image shape.
boxes = scale_boxes(boxes, image_shape)
# Use one of the functions you've implemented to perform Non-max suppression with a threshold of iou_threshold (≈1 line)
scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes)
### END CODE HERE ###
return scores, boxes, classes
with tf.Session() as test_b:
yolo_outputs = (tf.random_normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1),
tf.random_normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),
tf.random_normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),
tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1))
scores, boxes, classes = yolo_eval(yolo_outputs)
print("scores[2] = " + str(scores[2].eval()))
print("boxes[2] = " + str(boxes[2].eval()))
print("classes[2] = " + str(classes[2].eval()))
print("scores.shape = " + str(scores.eval().shape))
print("boxes.shape = " + str(boxes.eval().shape))
print("classes.shape = " + str(classes.eval().shape))
```
**Expected Output**:
<table>
<tr>
<td>
**scores[2]**
</td>
<td>
138.791
</td>
</tr>
<tr>
<td>
**boxes[2]**
</td>
<td>
[ 1292.32971191 -278.52166748 3876.98925781 -835.56494141]
</td>
</tr>
<tr>
<td>
**classes[2]**
</td>
<td>
54
</td>
</tr>
<tr>
<td>
**scores.shape**
</td>
<td>
(10,)
</td>
</tr>
<tr>
<td>
**boxes.shape**
</td>
<td>
(10, 4)
</td>
</tr>
<tr>
<td>
**classes.shape**
</td>
<td>
(10,)
</td>
</tr>
</table>
<font color='blue'>
**Summary for YOLO**:
- Input image (608, 608, 3)
- The input image goes through a CNN, resulting in a (19,19,5,85) dimensional output.
- After flattening the last two dimensions, the output is a volume of shape (19, 19, 425):
- Each cell in a 19x19 grid over the input image gives 425 numbers.
- 425 = 5 x 85 because each cell contains predictions for 5 boxes, corresponding to 5 anchor boxes, as seen in lecture.
- 85 = 5 + 80 where 5 is because $(p_c, b_x, b_y, b_h, b_w)$ has 5 numbers, and and 80 is the number of classes we'd like to detect
- You then select only few boxes based on:
- Score-thresholding: throw away boxes that have detected a class with a score less than the threshold
- Non-max suppression: Compute the Intersection over Union and avoid selecting overlapping boxes
- This gives you YOLO's final output.
## 3 - Test YOLO pretrained model on images
In this part, you are going to use a pretrained model and test it on the car detection dataset. As usual, you start by **creating a session to start your graph**. Run the following cell.
```
sess = K.get_session()
```
### 3.1 - Defining classes, anchors and image shape.
Recall that we are trying to detect 80 classes, and are using 5 anchor boxes. We have gathered the information about the 80 classes and 5 boxes in two files "coco_classes.txt" and "yolo_anchors.txt". Let's load these quantities into the model by running the next cell.
The car detection dataset has 720x1280 images, which we've pre-processed into 608x608 images.
```
class_names = read_classes("model_data/coco_classes.txt")
anchors = read_anchors("model_data/yolo_anchors.txt")
image_shape = (720., 1280.)
```
### 3.2 - Loading a pretrained model
Training a YOLO model takes a very long time and requires a fairly large dataset of labelled bounding boxes for a large range of target classes. You are going to load an existing pretrained Keras YOLO model stored in "yolo.h5". (These weights come from the official YOLO website, and were converted using a function written by Allan Zelener. References are at the end of this notebook. Technically, these are the parameters from the "YOLOv2" model, but we will more simply refer to it as "YOLO" in this notebook.) Run the cell below to load the model from this file.
```
yolo_model = load_model("model_data/yolo.h5")
```
This loads the weights of a trained YOLO model. Here's a summary of the layers your model contains.
```
yolo_model.summary()
```
**Note**: On some computers, you may see a warning message from Keras. Don't worry about it if you do--it is fine.
**Reminder**: this model converts a preprocessed batch of input images (shape: (m, 608, 608, 3)) into a tensor of shape (m, 19, 19, 5, 85) as explained in Figure (2).
### 3.3 - Convert output of the model to usable bounding box tensors
The output of `yolo_model` is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. The following cell does that for you.
```
yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))
```
You added `yolo_outputs` to your graph. This set of 4 tensors is ready to be used as input by your `yolo_eval` function.
### 3.4 - Filtering boxes
`yolo_outputs` gave you all the predicted boxes of `yolo_model` in the correct format. You're now ready to perform filtering and select only the best boxes. Lets now call `yolo_eval`, which you had previously implemented, to do this.
```
scores, boxes, classes = yolo_eval(yolo_outputs, image_shape)
```
### 3.5 - Run the graph on an image
Let the fun begin. You have created a (`sess`) graph that can be summarized as follows:
1. <font color='purple'> yolo_model.input </font> is given to `yolo_model`. The model is used to compute the output <font color='purple'> yolo_model.output </font>
2. <font color='purple'> yolo_model.output </font> is processed by `yolo_head`. It gives you <font color='purple'> yolo_outputs </font>
3. <font color='purple'> yolo_outputs </font> goes through a filtering function, `yolo_eval`. It outputs your predictions: <font color='purple'> scores, boxes, classes </font>
**Exercise**: Implement predict() which runs the graph to test YOLO on an image.
You will need to run a TensorFlow session, to have it compute `scores, boxes, classes`.
The code below also uses the following function:
```python
image, image_data = preprocess_image("images/" + image_file, model_image_size = (608, 608))
```
which outputs:
- image: a python (PIL) representation of your image used for drawing boxes. You won't need to use it.
- image_data: a numpy-array representing the image. This will be the input to the CNN.
**Important note**: when a model uses BatchNorm (as is the case in YOLO), you will need to pass an additional placeholder in the feed_dict {K.learning_phase(): 0}.
```
def predict(sess, image_file):
"""
Runs the graph stored in "sess" to predict boxes for "image_file". Prints and plots the preditions.
Arguments:
sess -- your tensorflow/Keras session containing the YOLO graph
image_file -- name of an image stored in the "images" folder.
Returns:
out_scores -- tensor of shape (None, ), scores of the predicted boxes
out_boxes -- tensor of shape (None, 4), coordinates of the predicted boxes
out_classes -- tensor of shape (None, ), class index of the predicted boxes
Note: "None" actually represents the number of predicted boxes, it varies between 0 and max_boxes.
"""
# Preprocess your image
image, image_data = preprocess_image("images/" + image_file, model_image_size = (608, 608))
# Run the session with the correct tensors and choose the correct placeholders in the feed_dict.
# You'll need to use feed_dict={yolo_model.input: ... , K.learning_phase(): 0})
### START CODE HERE ### (≈ 1 line)
out_scores, out_boxes, out_classes = sess.run([scores, boxes, classes], feed_dict={yolo_model.input: image_data, K.learning_phase(): 0})
### END CODE HERE ###
# Print predictions info
print('Found {} boxes for {}'.format(len(out_boxes), image_file))
# Generate colors for drawing bounding boxes.
colors = generate_colors(class_names)
# Draw bounding boxes on the image file
draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)
# Save the predicted bounding box on the image
image.save(os.path.join("out", image_file), quality=90)
# Display the results in the notebook
output_image = scipy.misc.imread(os.path.join("out", image_file))
imshow(output_image)
return out_scores, out_boxes, out_classes
```
Run the following cell on the "test.jpg" image to verify that your function is correct.
```
out_scores, out_boxes, out_classes = predict(sess, "test.jpg")
```
**Expected Output**:
<table>
<tr>
<td>
**Found 7 boxes for test.jpg**
</td>
</tr>
<tr>
<td>
**car**
</td>
<td>
0.60 (925, 285) (1045, 374)
</td>
</tr>
<tr>
<td>
**car**
</td>
<td>
0.66 (706, 279) (786, 350)
</td>
</tr>
<tr>
<td>
**bus**
</td>
<td>
0.67 (5, 266) (220, 407)
</td>
</tr>
<tr>
<td>
**car**
</td>
<td>
0.70 (947, 324) (1280, 705)
</td>
</tr>
<tr>
<td>
**car**
</td>
<td>
0.74 (159, 303) (346, 440)
</td>
</tr>
<tr>
<td>
**car**
</td>
<td>
0.80 (761, 282) (942, 412)
</td>
</tr>
<tr>
<td>
**car**
</td>
<td>
0.89 (367, 300) (745, 648)
</td>
</tr>
</table>
The model you've just run is actually able to detect 80 different classes listed in "coco_classes.txt". To test the model on your own images:
1. Click on "File" in the upper bar of this notebook, then click "Open" to go on your Coursera Hub.
2. Add your image to this Jupyter Notebook's directory, in the "images" folder
3. Write your image's name in the cell above code
4. Run the code and see the output of the algorithm!
If you were to run your session in a for loop over all your images. Here's what you would get:
<center>
<video width="400" height="200" src="nb_images/pred_video_compressed2.mp4" type="video/mp4" controls>
</video>
</center>
<caption><center> Predictions of the YOLO model on pictures taken from a camera while driving around the Silicon Valley <br> Thanks [drive.ai](https://www.drive.ai/) for providing this dataset! </center></caption>
<font color='blue'>
**What you should remember**:
- YOLO is a state-of-the-art object detection model that is fast and accurate
- It runs an input image through a CNN which outputs a 19x19x5x85 dimensional volume.
- The encoding can be seen as a grid where each of the 19x19 cells contains information about 5 boxes.
- You filter through all the boxes using non-max suppression. Specifically:
- Score thresholding on the probability of detecting a class to keep only accurate (high probability) boxes
- Intersection over Union (IoU) thresholding to eliminate overlapping boxes
- Because training a YOLO model from randomly initialized weights is non-trivial and requires a large dataset as well as lot of computation, we used previously trained model parameters in this exercise. If you wish, you can also try fine-tuning the YOLO model with your own dataset, though this would be a fairly non-trivial exercise.
**References**: The ideas presented in this notebook came primarily from the two YOLO papers. The implementation here also took significant inspiration and used many components from Allan Zelener's github repository. The pretrained weights used in this exercise came from the official YOLO website.
- Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi - [You Only Look Once: Unified, Real-Time Object Detection](https://arxiv.org/abs/1506.02640) (2015)
- Joseph Redmon, Ali Farhadi - [YOLO9000: Better, Faster, Stronger](https://arxiv.org/abs/1612.08242) (2016)
- Allan Zelener - [YAD2K: Yet Another Darknet 2 Keras](https://github.com/allanzelener/YAD2K)
- The official YOLO website (https://pjreddie.com/darknet/yolo/)
**Car detection dataset**:
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">The Drive.ai Sample Dataset</span> (provided by drive.ai) is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>. We are especially grateful to Brody Huval, Chih Hu and Rahul Patel for collecting and providing this dataset.
| github_jupyter |
# From Unlabeled Data to a Deployed Machine Learning Model: A SageMaker Ground Truth Demonstration for Image Classification
1. [Introduction](#Introduction)
2. [Run a Ground Truth labeling job (time: about 3h)](#Run-a-Ground-Truth-labeling-job)
1. [Prepare the data](#Prepare-the-data)
2. [Specify the categories](#Specify-the-categories)
3. [Create the instruction template](#Create-the-instruction-template)
4. [Create a private team to test your task [OPTIONAL]](#Create-a-private-team-to-test-your-task-[OPTIONAL])
5. [Define pre-built lambda functions for use in the labeling job](#Define-pre-built-lambda-functions-for-use-in-the-labeling-job)
6. [Submit the Ground Truth job request](#Submit-the-Ground-Truth-job-request)
1. [Verify your task using a private team [OPTIONAL]](#Verify-your-task-using-a-private-team-[OPTIONAL])
7. [Monitor job progress](#Monitor-job-progress)
3. [Analyze Ground Truth labeling job results (time: about 20min)](#Analyze-Ground-Truth-labeling-job-results)
1. [Postprocess the output manifest](#Postprocess-the-output-manifest)
2. [Plot class histograms](#Plot-class-histograms)
3. [Plot annotated images](#Plot-annotated-images)
1. [Plot a small output sample](#Plot-a-small-output-sample)
2. [Plot the full results](#Plot-the-full-results)
4. [Compare Ground Truth results to standard labels (time: about 5min)](#Compare-Ground-Truth-results-to-standard-labels)
1. [Compute accuracy](#Compute-accuracy)
2. [Plot correct and incorrect annotations](#Plot-correct-and-incorrect-annotations)
5. [Train an image classifier using Ground Truth labels (time: about 15min)](#Train-an-image-classifier-using-Ground-Truth-labels)
6. [Deploy the Model (time: about 20min)](#Deploy-the-Model)
1. [Create Model](#Create-Model)
2. [Batch Transform](#Batch-Transform)
3. [Realtime Inference](#Realtime-Inference)
1. [Create Endpoint Configuration](#Create-Endpoint-Configuration)
2. [Create Endpoint](#Create-Endpoint)
3. [Perform Inference](#Perform-Inference)
7. [Review](#Review)
## Introduction
This sample notebook takes you through an end-to-end workflow to demonstrate the functionality of SageMaker Ground Truth. We'll start with an unlabeled image data set, acquire labels for all the images using SageMaker Ground Truth, analyze the results of the labeling job, train an image classifier, host the resulting model, and, finally, use it to make predictions. Before you begin, we highly recommend you start a Ground Truth labeling job through the AWS Console first to familiarize yourself with the workflow. The AWS Console offers less flexibility than the API, but is simple to use.
#### Cost and runtime
You can run this demo in two modes:
1. Set `RUN_FULL_AL_DEMO = True` in the next cell to label 1000 images. This should cost about \$100 given current [Ground Truth pricing scheme](https://aws.amazon.com/sagemaker/groundtruth/pricing/). In order to reduce the cost, we will use Ground Truth's auto-labeling feature. Auto-labeling uses computer vision to learn from human responses and automatically create labels for the easiest images at a cheap price. The total end-to-end runtime should be about 4h.
1. Set `RUN_FULL_AL_DEMO = False` in the next cell to label only 100 images. This should cost about \$15. **Since Ground Truth's auto-labeling feature only kicks in for datasets of 1000 images or more, this cheaper version of the demo will not use it. Some of the analysis plots might look awkward, but you should still be able to see good results on the human-annotated 100 images.**
#### Prerequisites
To run this notebook, you can simply execute each cell one-by-one. To understand what's happening, you'll need:
* An S3 bucket you can write to -- please provide its name in the following cell. The bucket must be in the same region as this SageMaker Notebook instance. You can also change the `EXP_NAME` to any valid S3 prefix. All the files related to this experiment will be stored in that prefix of your bucket.
* The S3 bucket that you use for this demo must have a CORS policy attached. To learn more about this requirement, and how to attach a CORS policy to an S3 bucket, see [CORS Permission Requirement](https://docs.aws.amazon.com/sagemaker/latest/dg/sms-cors-update.html).
* Familiarity with Python and [numpy](http://www.numpy.org/).
* Basic familiarity with [AWS S3](https://docs.aws.amazon.com/s3/index.html),
* Basic understanding of [AWS Sagemaker](https://aws.amazon.com/sagemaker/),
* Basic familiarity with [AWS Command Line Interface (CLI)](https://aws.amazon.com/cli/) -- set it up with credentials to access the AWS account you're running this notebook from. This should work out-of-the-box on SageMaker Jupyter Notebook instances.
This notebook is only tested on a SageMaker notebook instance. The runtimes given are approximate, we used an `ml.m4.xlarge` instance in our tests. However, you can likely run it on a local instance by first executing the cell below on SageMaker, and then copying the `role` string to your local copy of the notebook.
NOTE: This notebook will create/remove subdirectories in its working directory. We recommend to place this notebook in its own directory before running it.
```
%matplotlib inline
%load_ext autoreload
%autoreload 2
import os
from collections import namedtuple
from collections import defaultdict
from collections import Counter
import itertools
import json
import random
import time
import imageio
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from sklearn.metrics import confusion_matrix
import boto3
import sagemaker
from urllib.parse import urlparse
BUCKET = "<< YOUR S3 BUCKET NAME >>"
assert BUCKET != "<< YOUR S3 BUCKET NAME >>", "Please provide a custom S3 bucket name."
EXP_NAME = "ground-truth-ic-demo" # Any valid S3 prefix.
RUN_FULL_AL_DEMO = True # See 'Cost and Runtime' in the Markdown cell above!
# Make sure the bucket is in the same region as this notebook.
role = sagemaker.get_execution_role()
region = boto3.session.Session().region_name
s3 = boto3.client("s3")
bucket_region = s3.head_bucket(Bucket=BUCKET)["ResponseMetadata"]["HTTPHeaders"][
"x-amz-bucket-region"
]
assert (
bucket_region == region
), "You S3 bucket {} and this notebook need to be in the same region.".format(BUCKET)
```
# Run a Ground Truth labeling job
**This section should take about 3h to complete.**
We will first run a labeling job. This involves several steps: collecting the images we want labeled, specifying the possible label categories, creating instructions, and writing a labeling job specification. In addition, we highly recommend to run a (free) mock job using a private workforce before you submit any job to the public workforce. This notebook will explain how to do that as an optional step. Without using a private workforce, this section until completion of your labeling job should take about 3h. However, this may vary depending on the availability of the public annotation workforce.
## Prepare the data
We will first download images and labels of a subset of the [Google Open Images Dataset](https://storage.googleapis.com/openimages/web/index.html). These labels were [carefully verified](https://storage.googleapis.com/openimages/web/factsfigures.html). Later, will compare Ground Truth annotations to these labels. Our dataset will include images in the following categories:
* Musical Instrument (500 images)
* Fruit (370 images)
* Cheetah (50 images)
* Tiger (40 images)
* Snowman (40 images)
If you chose `RUN_FULL_AL_DEMO = False`, then we will choose a subset of 100 images in this dataset. This is a diverse dataset of interesting images, and should be fun for the human annotators to work with. You are free to ask the annotators to annotate any images you wish (as long as the images do not contain adult content; in which case, you must adjust the labeling job request this job produces, please check the Ground Truth documentation).
We will copy these images to our local `BUCKET`, and will create the corresponding *input manifest*. The input manifest is a formatted list of the S3 locations of the images we want Ground Truth to annotate. We will upload this manifest to our S3 `BUCKET`.
#### Disclosure regarding the Open Images Dataset V4:
Open Images Dataset V4 is created by Google Inc. We have not modified the images or the accompanying annotations. You can obtain the images and the annotations [here](https://storage.googleapis.com/openimages/web/download.html). The annotations are licensed by Google Inc. under [CC BY 4.0](https://creativecommons.org/licenses/by/2.0/) license. The images are listed as having a [CC BY 2.0](https://creativecommons.org/licenses/by/2.0/) license. The following paper describes Open Images V4 in depth: from the data collection and annotation to detailed statistics about the data and evaluation of models trained on it.
A. Kuznetsova, H. Rom, N. Alldrin, J. Uijlings, I. Krasin, J. Pont-Tuset, S. Kamali, S. Popov, M. Malloci, T. Duerig, and V. Ferrari.
*The Open Images Dataset V4: Unified image classification, object detection, and visual relationship detection at scale.* arXiv:1811.00982, 2018. ([link to PDF](https://arxiv.org/abs/1811.00982))
```
# Download and process the Open Images annotations.
!wget https://storage.googleapis.com/openimages/2018_04/test/test-annotations-human-imagelabels-boxable.csv -O openimgs-annotations.csv
with open("openimgs-annotations.csv", "r") as f:
all_labels = [line.strip().split(",") for line in f.readlines()]
# Extract image ids in each of our desired classes.
ims = {}
ims["Musical Instrument"] = [
label[0] for label in all_labels if (label[2] == "/m/04szw" and label[3] == "1")
][:500]
ims["Fruit"] = [label[0] for label in all_labels if (label[2] == "/m/02xwb" and label[3] == "1")][
:371
]
ims["Fruit"].remove(
"02a54f6864478101"
) # This image contains personal information, let's remove it from our dataset.
ims["Cheetah"] = [label[0] for label in all_labels if (label[2] == "/m/0cd4d" and label[3] == "1")][
:50
]
ims["Tiger"] = [label[0] for label in all_labels if (label[2] == "/m/07dm6" and label[3] == "1")][
:40
]
ims["Snowman"] = [
label[0] for label in all_labels if (label[2] == "/m/0152hh" and label[3] == "1")
][:40]
num_classes = len(ims)
# If running the short version of the demo, reduce each class count 10 times.
for key in ims.keys():
if RUN_FULL_AL_DEMO is False:
ims[key] = set(ims[key][: int(len(ims[key]) / 10)])
else:
ims[key] = set(ims[key])
# Copy the images to our local bucket.
s3 = boto3.client("s3")
for img_id, img in enumerate(itertools.chain.from_iterable(ims.values())):
if (img_id + 1) % 10 == 0:
print("Copying image {} / {}".format((img_id + 1), 1000))
copy_source = {"Bucket": "open-images-dataset", "Key": "test/{}.jpg".format(img)}
s3.copy(copy_source, BUCKET, "{}/images/{}.jpg".format(EXP_NAME, img))
# Create and upload the input manifest.
manifest_name = "input.manifest"
with open(manifest_name, "w") as f:
for img in itertools.chain.from_iterable(ims.values()):
img_path = "s3://{}/{}/images/{}.jpg".format(BUCKET, EXP_NAME, img)
f.write('{"source-ref": "' + img_path + '"}\n')
s3.upload_file(manifest_name, BUCKET, EXP_NAME + "/" + manifest_name)
```
After running the cell above, you should be able to go to `s3://BUCKET/EXP_NAME/images` in [S3 console](https://console.aws.amazon.com/s3/) and see a thousand images. We recommend you inspect the contents of these images! You can download them all to a local machine using the AWS CLI.
## Specify the categories
To run an image classification labeling job, you need to decide on a set of classes the annotators can choose from.
In our case, this list is `["Musical Instrument", "Fruit", "Cheetah", "Tiger", "Snowman"]`. In your own job you can choose any list of up to 10 classes. We recommend the classes to be as unambiguous and concrete as possible. The categories should be mutually exclusive, with only one correct label per image. In addition, be careful to make the task as *objective* as possible, unless of course your intention is to obtain subjective labels.
* Example good category lists: `["Human", "No Human"]`, `["Golden Retriever", "Labrador", "English Bulldog", "German Shepherd"]`, `["Car", "Train", "Ship", "Pedestrian"]`.
* Example bad category lists: `["Prominent object", "Not prominent"]` (meaning unclear), `["Beautiful", "Ugly"]` (subjective), `["Dog", "Animal", "Car"]` (not mutually exclusive).
To work with Ground Truth, this list needs to be converted to a .json file and uploaded to the S3 `BUCKET`.
*Note: The ordering of the labels or classes in the template governs the class indices that you will see downstream in the output manifest (this numbering is zero-indexed). In other words, the class that appears second in the template will correspond to class "1" in the output. At the end of this demonstration, we will train a model and make predictions, and this class ordering is instrumental to interpreting the results.*
```
CLASS_LIST = list(ims.keys())
print("Label space is {}".format(CLASS_LIST))
json_body = {"labels": [{"label": label} for label in CLASS_LIST]}
with open("class_labels.json", "w") as f:
json.dump(json_body, f)
s3.upload_file("class_labels.json", BUCKET, EXP_NAME + "/class_labels.json")
```
You should now see `class_labels.json` in `s3://BUCKET/EXP_NAME/`.
## Create the instruction template
Part or all of your images will be annotated by human annotators. It is **essential** to provide good instructions that help the annotators give you the annotations you want. Good instructions are:
1. Concise. We recommend limiting verbal/textual instruction to two sentences, and focusing on clear visuals.
2. Visual. In the case of image classification, we recommend providing one labeled image in each of the classes as part of the instruction.
When used through the AWS Console, Ground Truth helps you create the instructions using a visual wizard. When using the API, you need to create an HTML template for your instructions. Below, we prepare a very simple but effective template and upload it to your S3 bucket.
NOTE: If you use any images in your template (as we do), they need to be publicly accessible. You can enable public access to files in your S3 bucket through the S3 Console, as described in [S3 Documentation](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/set-object-permissions.html).
#### Testing your instructions
It is very easy to create broken instructions. This might cause your labeling job to fail. However, it might also cause your job to complete with meaningless results (when the annotators have no idea what to do, or the instructions are plain wrong). We *highly recommend* that you verify that your task is correct in two ways:
1. The following cell creates and uploads a file called `instructions.template` to S3. It also creates `instructions.html` that you can open in a local browser window. Please do so and inspect the resulting web page; it should correspond to what you want your annotators to see (except the actual image to annotate will not be visible).
2. Run your job in a private workforce, which is a way to run a mock labeling job. We describe how to do it in [Verify your task using a private team [OPTIONAL]](#Verify-your-task-using-a-private-team-[OPTIONAL]).
```
img_examples = [
"https://s3.amazonaws.com/open-images-dataset/test/{}".format(img_id)
for img_id in [
"0634825fc1dcc96b.jpg",
"0415b6a36f3381ed.jpg",
"8582cc08068e2d0f.jpg",
"8728e9fa662a8921.jpg",
"926d31e8cde9055e.jpg",
]
]
def make_template(test_template=False, save_fname="instructions.template"):
template = r"""<script src="https://assets.crowd.aws/crowd-html-elements.js"></script>
<crowd-form>
<crowd-image-classifier
name="crowd-image-classifier"
src="{{{{ task.input.taskObject | grant_read_access }}}}"
header="Dear Annotator, please tell me what you can see in the image. Thank you!"
categories="{categories_str}"
>
<full-instructions header="Image classification instructions">
</full-instructions>
<short-instructions>
<p>Dear Annotator, please tell me whether what you can see in the image. Thank you!</p>
<p><img src="{}" style="max-width:100%">
<br>Example "Musical Instrument". </p>
<p><img src="{}" style="max-width:100%">
<br>Example "Fruit".</p>
<p><img src="{}" style="max-width:100%">
<br>Example "Cheetah". </p>
<p><img src="{}" style="max-width:100%">
<br>Example "Tiger". </p>
<p><img src="{}" style="max-width:100%">
<br>Example "Snowman". </p>
</short-instructions>
</crowd-image-classifier>
</crowd-form>""".format(
*img_examples,
categories_str=str(CLASS_LIST)
if test_template
else "{{ task.input.labels | to_json | escape }}",
)
with open(save_fname, "w") as f:
f.write(template)
if test_template is False:
print(template)
make_template(test_template=True, save_fname="instructions.html")
make_template(test_template=False, save_fname="instructions.template")
s3.upload_file("instructions.template", BUCKET, EXP_NAME + "/instructions.template")
```
You should now be able to find your template in `s3://BUCKET/EXP_NAME/instructions.template`.
## Create a private team to test your task [OPTIONAL]
This step requires you to use the AWS Console. However, we **highly recommend** that you follow it, especially when creating your own task with a custom dataset, label set, and template.
We will create a `private workteam` and add only one user (you) to it. Then, we will modify the Ground Truth API job request to send the task to that workforce. You will then be able to see your annotation job exactly as the public annotators would see it. You can even annotate the whole dataset yourself!
To create a private team:
1. Go to `AWS Console > Amazon SageMaker > Labeling workforces`
2. Click "Private" and then "Create private team".
3. Enter the desired name for your private workteam.
4. Enter your own email address in the "Email addresses" section.
5. Enter the name of your organization and a contact email to administrate the private workteam.
6. Click "Create Private Team".
7. The AWS Console should now return to `AWS Console > Amazon SageMaker > Labeling workforces`. Your newly created team should be visible under "Private teams". Next to it you will see an `ARN` which is a long string that looks like `arn:aws:sagemaker:region-name-123456:workteam/private-crowd/team-name`. Copy this ARN in the cell below.
8. You should get an email from `no-reply@verificationemail.com` that contains your workforce username and password.
9. In `AWS Console > Amazon SageMaker > Labeling workforces`, click on the URL in `Labeling portal sign-in URL`. Use the email/password combination from Step 8 to log in (you will be asked to create a new, non-default password).
That's it! This is your private worker's interface. When we create a verification task in [Verify your task using a private team](#Verify-your-task-using-a-private-team-[OPTIONAL]) below, your task should appear in this window. You can invite your colleagues to participate in the labeling job by clicking the "Invite new workers" button.
The [SageMaker Ground Truth documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/sms-workforce-management-private.html) has more details on the management of private workteams.
```
private_workteam_arn = "<< your private workteam ARN here >>"
```
## Define pre-built lambda functions for use in the labeling job
Before we submit the request, we need to define the ARNs for four key components of the labeling job: 1) the workteam, 2) the annotation consolidation Lambda function, 3) the pre-labeling task Lambda function, and 4) the machine learning algorithm to perform auto-annotation. These functions are defined by strings with region names and AWS service account numbers, so we will define a mapping below that will enable you to run this notebook in any of our supported regions.
See the official documentation for the available ARNs:
* [Documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/sms-workforce-management-public.html) for a discussion of the workteam ARN definition. There is only one valid selection if you choose to use the public workfofce; if you elect to use a private workteam, you should check the corresponding ARN for the workteam.
* [Documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/API_HumanTaskConfig.html#SageMaker-Type-HumanTaskConfig-PreHumanTaskLambdaArn) for available pre-human ARNs for other workflows.
* [Documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/API_AnnotationConsolidationConfig.html#SageMaker-Type-AnnotationConsolidationConfig-AnnotationConsolidationLambdaArn) for available annotation consolidation ANRs for other workflows.
* [Documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/API_LabelingJobAlgorithmsConfig.html#SageMaker-Type-LabelingJobAlgorithmsConfig-LabelingJobAlgorithmSpecificationArn) for available auto-labeling ARNs for other workflows.
```
# Specify ARNs for resources needed to run an image classification job.
ac_arn_map = {
"us-west-2": "081040173940",
"us-east-1": "432418664414",
"us-east-2": "266458841044",
"eu-west-1": "568282634449",
"ap-northeast-1": "477331159723",
}
prehuman_arn = "arn:aws:lambda:{}:{}:function:PRE-ImageMultiClass".format(
region, ac_arn_map[region]
)
acs_arn = "arn:aws:lambda:{}:{}:function:ACS-ImageMultiClass".format(region, ac_arn_map[region])
labeling_algorithm_specification_arn = "arn:aws:sagemaker:{}:027400017018:labeling-job-algorithm-specification/image-classification".format(
region
)
workteam_arn = "arn:aws:sagemaker:{}:394669845002:workteam/public-crowd/default".format(region)
```
## Submit the Ground Truth job request
The API starts a Ground Truth job by submitting a request. The request contains the
full configuration of the annotation task, and allows you to modify the fine details of
the job that are fixed to default values when you use the AWS Console. The parameters that make up the request are described in more detail in the [SageMaker Ground Truth documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/API_CreateLabelingJob.html).
After you submit the request, you should be able to see the job in your AWS Console, at `Amazon SageMaker > Labeling Jobs`.
You can track the progress of the job there. This job will take several hours to complete. If your job
is larger (say 100,000 images), the speed and cost benefit of auto-labeling should be larger.
### Verify your task using a private team [OPTIONAL]
If you chose to follow the steps in [Create a private team](#Create-a-private-team-to-test-your-task-[OPTIONAL]), then you can first verify that your task runs as expected. To do this:
1. Set VERIFY_USING_PRIVATE_WORKFORCE to True in the cell below.
2. Run the next two cells. This will define the task and submit it to the private workforce (to you).
3. After a few minutes, you should be able to see your task in your private workforce interface [Create a private team](#Create-a-private-team-to-test-your-task-[OPTIONAL]).
Please verify that the task appears as you want it to appear.
4. If everything is in order, change `VERIFY_USING_PRIVATE_WORKFORCE` to `False` and rerun the cell below to start the real annotation task!
```
VERIFY_USING_PRIVATE_WORKFORCE = False
USE_AUTO_LABELING = True
task_description = "What do you see: a {}?".format(" a ".join(CLASS_LIST))
task_keywords = ["image", "classification", "humans"]
task_title = task_description
job_name = "ground-truth-demo-" + str(int(time.time()))
human_task_config = {
"AnnotationConsolidationConfig": {
"AnnotationConsolidationLambdaArn": acs_arn,
},
"PreHumanTaskLambdaArn": prehuman_arn,
"MaxConcurrentTaskCount": 200, # 200 images will be sent at a time to the workteam.
"NumberOfHumanWorkersPerDataObject": 3, # 3 separate workers will be required to label each image.
"TaskAvailabilityLifetimeInSeconds": 21600, # Your worteam has 6 hours to complete all pending tasks.
"TaskDescription": task_description,
"TaskKeywords": task_keywords,
"TaskTimeLimitInSeconds": 300, # Each image must be labeled within 5 minutes.
"TaskTitle": task_title,
"UiConfig": {
"UiTemplateS3Uri": "s3://{}/{}/instructions.template".format(BUCKET, EXP_NAME),
},
}
if not VERIFY_USING_PRIVATE_WORKFORCE:
human_task_config["PublicWorkforceTaskPrice"] = {
"AmountInUsd": {
"Dollars": 0,
"Cents": 1,
"TenthFractionsOfACent": 2,
}
}
human_task_config["WorkteamArn"] = workteam_arn
else:
human_task_config["WorkteamArn"] = private_workteam_arn
ground_truth_request = {
"InputConfig": {
"DataSource": {
"S3DataSource": {
"ManifestS3Uri": "s3://{}/{}/{}".format(BUCKET, EXP_NAME, manifest_name),
}
},
"DataAttributes": {
"ContentClassifiers": ["FreeOfPersonallyIdentifiableInformation", "FreeOfAdultContent"]
},
},
"OutputConfig": {
"S3OutputPath": "s3://{}/{}/output/".format(BUCKET, EXP_NAME),
},
"HumanTaskConfig": human_task_config,
"LabelingJobName": job_name,
"RoleArn": role,
"LabelAttributeName": "category",
"LabelCategoryConfigS3Uri": "s3://{}/{}/class_labels.json".format(BUCKET, EXP_NAME),
}
if USE_AUTO_LABELING and RUN_FULL_AL_DEMO:
ground_truth_request["LabelingJobAlgorithmsConfig"] = {
"LabelingJobAlgorithmSpecificationArn": labeling_algorithm_specification_arn
}
sagemaker_client = boto3.client("sagemaker")
sagemaker_client.create_labeling_job(**ground_truth_request)
```
## Monitor job progress
A Ground Truth job can take a few hours to complete (if your dataset is larger than 10000 images, it can take much longer than that!). One way to monitor the job's progress is through AWS Console. In this notebook, we will use Ground Truth output files and Cloud Watch logs in order to monitor the progress. You can re-evaluate the next two cells repeatedly.
You can re-evaluate the next cell repeatedly. It sends a `describe_labelging_job` request which should tell you whether the job is completed or not. If it is, then 'LabelingJobStatus' will be 'Completed'.
```
sagemaker_client.describe_labeling_job(LabelingJobName=job_name)
```
The next cell extract detailed information on how your job is doing to-date. You can re-evaluate it at any time. It should give you:
* The number of human and machine-annotated images in each category across the iterations of your labeling job.
* The training curves of any neural network training jobs launched by Ground Truth **(only if you are running with `RUN_FULL_AL_DEMO=True`)**.
* The cost of the human- and machine-annotatoed labels.
To understand the pricing, study [the pricing doc](https://aws.amazon.com/sagemaker/groundtruth/pricing/) carefully. In our case, each human label costs `$0.08 + 3 * $0.012 = $0.116` and each auto-label costs `$0.08`. There is also a small added cost of using SageMaker instances for neural net training and inference during auto-labeling. However, this should be insignificant compared the other costs.
If `RUN_FULL_AL_DEMO==True`, then the job will proceed in multiple iterations.
* Iteration 1: Ground Truth will send out 10 images as 'probes' for human annotation. If these are succesfully annotated, proceed to Iteration 2.
* Iteration 2: Send out a batch of `MaxConcurrentTaskCount - 10` (in our case, 190) images for human annotation to obtain an active learning training batch.
* Iteration 3: Send out another batch of 200 images for human annotation to obtain an active learning validation set.
* Iteration 4a: Train a neural net to do auto-labeling. Auto-label as many datapoints as possible.
* Iteration 4b: If there is any data leftover, send out at most 200 images for human annotation.
* Repeat Iteration 4a and 4b until all data is annotated.
If `RUN_FULL_AL_DEMO==False`, only Iterations 1 and 2 will happen.
```
from datetime import datetime
import glob
import shutil
HUMAN_PRICE = 0.116
AUTO_PRICE = 0.08
try:
os.makedirs('ic_output_data/', exist_ok=False)
except FileExistsError:
shutil.rmtree('ic_output_data/')
S3_OUTPUT = boto3.client('sagemaker').describe_labeling_job(LabelingJobName=job_name)[
'OutputConfig']['S3OutputPath'] + job_name
# Download human annotation data.
!aws s3 cp {S3_OUTPUT + '/annotations/worker-response'} ic_output_data/worker-response --recursive --quiet
worker_times = []
worker_ids = []
# Collect the times and worker ids of all the annotation events to-date.
for annot_fname in glob.glob('ic_output_data/worker-response/**', recursive=True):
if annot_fname.endswith('json'):
with open(annot_fname, 'r') as f:
annot_data = json.load(f)
for answer in annot_data['answers']:
annot_time = datetime.strptime(
answer['submissionTime'], '%Y-%m-%dT%H:%M:%SZ')
annot_id = answer['workerId']
worker_times.append(annot_time)
worker_ids.append(annot_id)
sort_ids = np.argsort(worker_times)
worker_times = np.array(worker_times)[sort_ids]
worker_ids = np.array(worker_ids)[sort_ids]
cumulative_n_annots = np.cumsum([1 for _ in worker_times])
# Count the number of annotations per unique worker id.
annots_per_worker = np.zeros(worker_ids.size)
ids_store = set()
for worker_id_id, worker_id in enumerate(worker_ids):
ids_store.add(worker_id)
annots_per_worker[worker_id_id] = float(
cumulative_n_annots[worker_id_id]) / len(ids_store)
# Count number of human annotations in each class each iteration.
!aws s3 cp {S3_OUTPUT + '/annotations/consolidated-annotation/consolidation-response'} ic_output_data/consolidation-response --recursive --quiet
consolidated_classes = defaultdict(list)
consolidation_times = {}
consolidated_cost_times = []
for consolidated_fname in glob.glob('ic_output_data/consolidation-response/**', recursive=True):
if consolidated_fname.endswith('json'):
iter_id = int(consolidated_fname.split('/')[-2][-1])
# Store the time of the most recent consolidation event as iteration time.
iter_time = datetime.strptime(consolidated_fname.split('/')[-1], '%Y-%m-%d_%H:%M:%S.json')
if iter_id in consolidation_times:
consolidation_times[iter_id] = max(consolidation_times[iter_id], iter_time)
else:
consolidation_times[iter_id] = iter_time
consolidated_cost_times.append(iter_time)
with open(consolidated_fname, 'r') as f:
consolidated_data = json.load(f)
for consolidation in consolidated_data:
consolidation_class = consolidation['consolidatedAnnotation']['content'][
'category-metadata']['class-name']
consolidated_classes[iter_id].append(consolidation_class)
total_human_labels = sum([len(annots) for annots in consolidated_classes.values()])
# Count the number of machine iterations in each class each iteration.
!aws s3 cp {S3_OUTPUT + '/activelearning'} ic_output_data/activelearning --recursive --quiet
auto_classes = defaultdict(list)
auto_times = {}
auto_cost_times = []
for auto_fname in glob.glob('ic_output_data/activelearning/**', recursive=True):
if auto_fname.endswith('auto_annotator_output.txt'):
iter_id = int(auto_fname.split('/')[-3])
with open(auto_fname, 'r') as f:
annots = [' '.join(l.split()[1:]) for l in f.readlines()]
for annot in annots:
annot = json.loads(annot)
time_str = annot['category-metadata']['creation-date']
auto_time = datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S.%f')
auto_class = annot['category-metadata']['class-name']
auto_classes[iter_id].append(auto_class)
if iter_id in auto_times:
auto_times[iter_id] = max(auto_times[iter_id], auto_time)
else:
auto_times[iter_id] = auto_time
auto_cost_times.append(auto_time)
total_auto_labels = sum([len(annots) for annots in auto_classes.values()])
n_iters = max(len(auto_times), len(consolidation_times))
def get_training_job_data(training_job_name):
logclient = boto3.client('logs')
log_group_name = '/aws/sagemaker/TrainingJobs'
log_stream_name = logclient.describe_log_streams(logGroupName=log_group_name,
logStreamNamePrefix=training_job_name)['logStreams'][0]['logStreamName']
train_log = logclient.get_log_events(
logGroupName=log_group_name,
logStreamName=log_stream_name,
startFromHead=True
)
events = train_log['events']
next_token = train_log['nextForwardToken']
while True:
train_log = logclient.get_log_events(
logGroupName=log_group_name,
logStreamName=log_stream_name,
startFromHead=True,
nextToken=next_token
)
if train_log['nextForwardToken'] == next_token:
break
events = events + train_log['events']
errors = []
for event in events:
msg = event['message']
if 'Final configuration' in msg:
num_samples = int(msg.split('num_training_samples\': u\'')[1].split('\'')[0])
elif 'Validation-accuracy' in msg:
errors.append(float(msg.split('Validation-accuracy=')[1]))
errors = 1 - np.array(errors)
return num_samples, errors
training_data = !aws s3 ls {S3_OUTPUT + '/training/'} --recursive
training_sizes = []
training_errors = []
training_iters = []
for line in training_data:
if line.split('/')[-1] == 'model.tar.gz':
training_job_name = line.split('/')[-3]
n_samples, errors = get_training_job_data(training_job_name)
training_sizes.append(n_samples)
training_errors.append(errors)
training_iters.append(int(line.split('/')[-5]))
plt.figure(facecolor='white', figsize=(14, 4), dpi=100)
ax = plt.subplot(131)
plt.title('Label counts ({} human, {} auto)'.format(
total_human_labels, total_auto_labels))
cmap = plt.get_cmap('coolwarm')
for iter_id in consolidated_classes.keys():
bottom = 0
class_counter = Counter(consolidated_classes[iter_id])
for cname_id, cname in enumerate(CLASS_LIST):
if iter_id == 1:
plt.bar(iter_id, class_counter[cname], width=.4, bottom=bottom,
label=cname, color=cmap(cname_id / float(len(CLASS_LIST)-1)))
else:
plt.bar(iter_id, class_counter[cname], width=.4, bottom=bottom,
color=cmap(cname_id / float(len(CLASS_LIST)-1)))
bottom += class_counter[cname]
for iter_id in auto_classes.keys():
bottom = 0
class_counter = Counter(auto_classes[iter_id])
for cname_id, cname in enumerate(CLASS_LIST):
plt.bar(iter_id + .4, class_counter[cname], width=.4, bottom=bottom, color=cmap(cname_id / float(len(CLASS_LIST)-1)))
bottom += class_counter[cname]
tick_labels_human = ['Iter {}, human'.format(iter_id + 1) for iter_id in range(n_iters)]
tick_labels_auto = ['Iter {}, auto'.format(iter_id + 1) for iter_id in range(n_iters)]
tick_locations_human = np.arange(n_iters) + 1
tick_locations_auto = tick_locations_human + .4
tick_labels = np.concatenate([[tick_labels_human[idx], tick_labels_auto[idx]] for idx in range(n_iters)])
tick_locations = np.concatenate([[tick_locations_human[idx], tick_locations_auto[idx]] for idx in range(n_iters)])
plt.xticks(tick_locations, tick_labels, rotation=90)
plt.legend()
plt.ylabel('Count')
ax = plt.subplot(132)
total_human = 0
total_auto = 0
for iter_id in range(1, n_iters + 1):
cost_human = len(consolidated_classes[iter_id]) * HUMAN_PRICE
cost_auto = len(auto_classes[iter_id]) * AUTO_PRICE
total_human += cost_human
total_auto += cost_auto
plt.bar(iter_id, cost_human, width=.8, color='gray',
hatch='/', edgecolor='k', label='human' if iter_id==1 else None)
plt.bar(iter_id, cost_auto, bottom=cost_human,
width=.8, color='gray', edgecolor='k', label='auto' if iter_id==1 else None)
plt.title('Annotation costs (\${:.2f} human, \${:.2f} auto)'.format(
total_human, total_auto))
plt.xlabel('Iter')
plt.ylabel('Cost in dollars')
plt.legend()
if len(training_sizes) > 0:
plt.subplot(133)
plt.title('Active learning training curves')
plt.grid(True)
cmap = plt.get_cmap('coolwarm')
n_all = len(training_sizes)
for iter_id_id, (iter_id, size, errs) in enumerate(zip(training_iters, training_sizes, training_errors)):
plt.plot(errs, label='Iter {}, auto'.format(iter_id + 1), color=cmap(iter_id_id / max(1, (n_all-1))))
plt.legend()
plt.xscale('log')
plt.xlabel('Training epoch')
plt.ylabel('Validation error')
```
# Analyze Ground Truth labeling job results
**This section should take about 20min to complete.**
After the job finishes running (**make sure `sagemaker_client.describe_labeling_job` shows the job is complete!**), it is time to analyze the results. The plots in the [Monitor job progress](#Monitor-job-progress) section form part of the analysis. In this section, we will gain additional insights into the results, all contained in the `output manifest`. You can find the location of the output manifest under `AWS Console > SageMaker > Labeling Jobs > [name of your job]`. We will obtain it programmatically in the cell below.
## Postprocess the output manifest
Now that the job is complete, we will download the output manifest manfiest and postprocess it to form four arrays:
* `img_uris` contains the S3 URIs of all the images that Ground Truth annotated.
* `labels` contains Ground Truth's labels for each image in `img_uris`.
* `confidences` contains the confidence of each label in `labels`.
* `human` is a flag array that contains 1 at indices corresponding to images annotated by human annotators, and 0 at indices corresponding to images annotated by Ground Truth's automated data labeling.
```
# Load the output manifest's annotations.
OUTPUT_MANIFEST = "s3://{}/{}/output/{}/manifests/output/output.manifest".format(
BUCKET, EXP_NAME, job_name
)
!aws s3 cp {OUTPUT_MANIFEST} 'output.manifest'
with open("output.manifest", "r") as f:
output = [json.loads(line.strip()) for line in f.readlines()]
# Create data arrays.
img_uris = [None] * len(output)
confidences = np.zeros(len(output))
groundtruth_labels = [None] * len(output)
human = np.zeros(len(output))
# Find the job name the manifest corresponds to.
keys = list(output[0].keys())
metakey = keys[np.where([("-metadata" in k) for k in keys])[0][0]]
jobname = metakey[:-9]
# Extract the data.
for datum_id, datum in enumerate(output):
img_uris[datum_id] = datum["source-ref"]
groundtruth_labels[datum_id] = str(datum[metakey]["class-name"])
confidences[datum_id] = datum[metakey]["confidence"]
human[datum_id] = int(datum[metakey]["human-annotated"] == "yes")
groundtruth_labels = np.array(groundtruth_labels)
```
## Plot class histograms
Now, let's plot the class histograms. The next cell should produce three subplots:
* The Left subplot shows the number of images annotated as belonging to each visual category. The categories will be sorted from the most to the least numerous. Each bar is divided into a 'human' and 'machine' part which shows how many images were annotated as given category by human annotators and by the automated data labeling mechanism.
* The Middle subplot is the same as Left, except y-axis is in log-scale. This helps visualize unbalanced datasets where some categories contain orders of magnitude more images than other.
* The Right subplot shows the average confidence of images in each category, separately for human and auto-annotated images.
```
# Compute the number of annotations in each class.
n_classes = len(set(groundtruth_labels))
sorted_clnames, class_sizes = zip(*Counter(groundtruth_labels).most_common(n_classes))
# Find ids of human-annotated images.
human_sizes = [human[groundtruth_labels == clname].sum() for clname in sorted_clnames]
class_sizes = np.array(class_sizes)
human_sizes = np.array(human_sizes)
# Compute the average annotation confidence per class.
human_confidences = np.array(
[confidences[np.logical_and(groundtruth_labels == clname, human)] for clname in sorted_clnames]
)
machine_confidences = [
confidences[np.logical_and(groundtruth_labels == clname, 1 - human)]
for clname in sorted_clnames
]
# If there is no images annotated as a specific class, set the average class confidence to 0.
for class_id in range(n_classes):
if human_confidences[class_id].size == 0:
human_confidences[class_id] = np.array([0])
if machine_confidences[class_id].size == 0:
machine_confidences[class_id] = np.array([0])
plt.figure(figsize=(9, 3), facecolor="white", dpi=100)
plt.subplot(1, 3, 1)
plt.title("Annotation histogram")
plt.bar(range(n_classes), human_sizes, color="gray", hatch="/", edgecolor="k", label="human")
plt.bar(
range(n_classes),
class_sizes - human_sizes,
bottom=human_sizes,
color="gray",
edgecolor="k",
label="machine",
)
plt.xticks(range(n_classes), sorted_clnames, rotation=90)
plt.ylabel("Annotation Count")
plt.legend()
plt.subplot(1, 3, 2)
plt.title("Annotation histogram (logscale)")
plt.bar(range(n_classes), human_sizes, color="gray", hatch="/", edgecolor="k", label="human")
plt.bar(
range(n_classes),
class_sizes - human_sizes,
bottom=human_sizes,
color="gray",
edgecolor="k",
label="machine",
)
plt.xticks(range(n_classes), sorted_clnames, rotation=90)
plt.yscale("log")
plt.subplot(1, 3, 3)
plt.title("Mean confidences")
plt.bar(
np.arange(n_classes),
[conf.mean() for conf in human_confidences],
color="gray",
hatch="/",
edgecolor="k",
width=0.4,
)
plt.bar(
np.arange(n_classes) + 0.4,
[conf.mean() for conf in machine_confidences],
color="gray",
edgecolor="k",
width=0.4,
)
plt.xticks(range(n_classes), sorted_clnames, rotation=90);
```
## Plot annotated images
In any data science task, it is crucial to plot and inspect the results to check they make sense. In order to do this, we will
1. Download the input images that Ground Truth annotated.
2. Split them by annotated category and whether the annotation was done by human or the auto-labeling mechanism.
3. Plot images in each category and human/auto-annoated class.
We will download the input images to `LOCAL_IMAGE_DIR` you can choose in the next cell. Note that if this directory already contains images with the same filenames as your Ground Truth input images, we will not re-download the images.
If your dataset is large and you do not wish to download and plot **all** the images, simply set `DATASET_SIZE` to a small number. We will pick a random subset of your data for plotting.
```
LOCAL_IMG_DIR = '<< choose a local directory name to download the images to >>' # Replace with the name of a local directory to store images.
assert LOCAL_IMG_DIR != '<< choose a local directory name to download the images to >>', 'Please provide a local directory name'
DATASET_SIZE = len(img_uris) # Change this to a reasonable number if your dataset much larger than 10K images.
subset_ids = np.random.choice(range(len(img_uris)), DATASET_SIZE, replace=False)
img_uris = [img_uris[idx] for idx in subset_ids]
groundtruth_labels = groundtruth_labels[subset_ids]
confidences = confidences[subset_ids]
human = human[subset_ids]
img_fnames = [None] * len(output)
for img_uri_id, img_uri in enumerate(img_uris):
target_fname = os.path.join(
LOCAL_IMG_DIR, img_uri.split('/')[-1])
if not os.path.isfile(target_fname):
!aws s3 cp {img_uri} {target_fname}
img_fnames[img_uri_id] = target_fname
```
### Plot a small output sample
The following cell will create two figures. The first plots `N_SHOW` images in each category, as annotated by humans. The second plots `N_SHOW` images in each category, as annotated by the auto-labeling mechanism.
If any category contains less than `N_SHOW` images, that row will not be displayed. By default, `N_SHOW = 10`, but feel free to change this to any other small number.
```
N_SHOW = 10
plt.figure(figsize=(3 * N_SHOW, 2 + 3 * n_classes), facecolor="white", dpi=60)
for class_name_id, class_name in enumerate(sorted_clnames):
class_ids = np.where(np.logical_and(np.array(groundtruth_labels) == class_name, human))[0]
try:
show_ids = class_ids[:N_SHOW]
except ValueError:
print("Not enough human annotations to show for class: {}".format(class_name))
continue
for show_id_id, show_id in enumerate(show_ids):
plt.subplot2grid((n_classes, N_SHOW), (class_name_id, show_id_id))
plt.title("Human Label: " + class_name)
plt.imshow(imageio.imread(img_fnames[show_id])) # image_fnames
plt.axis("off")
plt.tight_layout()
plt.figure(figsize=(3 * N_SHOW, 2 + 3 * n_classes), facecolor="white", dpi=100)
for class_name_id, class_name in enumerate(sorted_clnames):
class_ids = np.where(np.logical_and(np.array(groundtruth_labels) == class_name, 1 - human))[0]
try:
show_ids = np.random.choice(class_ids, N_SHOW, replace=False)
except ValueError:
print("Not enough machine annotations to show for class: {}".format(class_name))
continue
for show_id_id, show_id in enumerate(show_ids):
plt.subplot2grid((n_classes, N_SHOW), (class_name_id, show_id_id))
plt.title("Auto Label: " + class_name)
plt.imshow(imageio.imread(img_fnames[show_id]))
plt.axis("off")
plt.tight_layout()
```
### Plot the full results
Finally, we plot all the results to a large pdf file. The pdf (called `ground_truth.pdf`) will display 100 images per page. Each page will contain images belonging to the same category, and annotated either by human annotators or by the auto-labeling mechanism. You can use this pdf to investigate exactly which images were annotated as which class at a glance.
This might take a while, and the resulting pdf might be very large. For a dataset of 1K images, the process takes only a minute and creates a 10MB-large pdf. You can set `N_SHOW_PER_CLASS` to a small number if you want to limit the max number of examples shown in each category.
```
N_SHOW_PER_CLASS = np.inf
plt.figure(figsize=(10, 10), facecolor="white", dpi=100)
with PdfPages("ground_truth.pdf") as pdf:
for class_name in sorted_clnames:
# Plot images annotated as class_name by humans.
plt.clf()
plt.text(0.1, 0.5, s="Images annotated as {} by humans".format(class_name), fontsize=20)
plt.axis("off")
class_ids = np.where(np.logical_and(np.array(groundtruth_labels) == class_name, human))[0]
for img_id_id, img_id in enumerate(class_ids):
if img_id_id == N_SHOW_PER_CLASS:
break
if img_id_id % 100 == 0:
pdf.savefig()
plt.clf()
print(
"Plotting human annotations of {}, {}/{}...".format(
class_name, (img_id_id + 1), min(len(class_ids), N_SHOW_PER_CLASS)
)
)
plt.subplot(10, 10, (img_id_id % 100) + 1)
plt.imshow(imageio.imread(img_fnames[img_id]), aspect="auto")
plt.axis("off")
pdf.savefig()
# Plot images annotated as class_name by machines.
plt.clf()
plt.text(0.1, 0.5, s="Images annotated as {} by machines".format(class_name), fontsize=20)
plt.axis("off")
class_ids = np.where(np.logical_and(np.array(groundtruth_labels) == class_name, 1 - human))[
0
]
for img_id_id, img_id in enumerate(class_ids):
if img_id_id == N_SHOW_PER_CLASS:
break
if img_id_id % 100 == 0:
pdf.savefig()
plt.clf()
print(
"Plotting machine annotations of {}, {}/{}...".format(
class_name, (img_id_id + 1), min(len(class_ids), N_SHOW_PER_CLASS)
)
)
plt.subplot(10, 10, (img_id_id % 100) + 1)
plt.imshow(imageio.imread(img_fnames[img_id]), aspect="auto")
plt.axis("off")
pdf.savefig()
plt.clf()
```
# Compare Ground Truth results to known, pre-labeled data
**This section should take about 5 minutes to complete.**
Sometimes (for example, when benchmarking the system) we have an alternative set of data labels available.
For example, the Open Images data has already been carefully annotated by a professional annotation workforce.
This allows us to perform additional analysis that compares Ground Truth labels to the known, pre-labeled data.
When doing so, it is important to bear in mind that any image labels created by humans
will most likely not be 100% accurate. For this reason, it is better to think of labeling accuracy as
"adherence to a particular standard / set of labels" rather than "how good (in absolute terms) are the Ground Truth labels."
## Compute accuracy
In this cell, we will calculate the accuracy of Ground Truth labels with respect to the standard labels.
In [Prepare the data](#Prepare-the-data), we created the `ims` dictionary that specifies which image belongs to each category.
We will convert it to an array `standard_labels` such that `standard_labels[i]` contains the label of the `i-th` image, and
should ideally correspond to `groundtruth_labels[i]`.
This will allow us to plot confusion matrices to assess how well the Ground Truth labels adhere to the standard labels. We plot a confusion matrix for the total dataset, and separate matrices for human annotations and auto-annotations.
```
def plot_confusion_matrix(
cm, classes, title="Confusion matrix", normalize=False, cmap=plt.cm.Blues
):
if normalize:
cm = cm.astype("float") / cm.sum(axis=1)[:, np.newaxis]
plt.imshow(cm, interpolation="nearest", cmap=cmap)
plt.title(title)
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=90)
plt.yticks(tick_marks, classes)
fmt = "d" if normalize else "d"
thresh = cm.max() / 2.0
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(
j,
i,
format(cm[i, j].astype(int), fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black",
)
plt.ylabel("True label")
plt.xlabel("Predicted label")
plt.tight_layout()
# Convert the 'ims' dictionary (which maps class names to images) to a list of image classes.
standard_labels = []
for img_uri in img_uris:
img_uri = img_uri.split("/")[-1].split(".")[0]
standard_label = [cname for cname, imgs_in_cname in ims.items() if img_uri in imgs_in_cname][0]
standard_labels.append(standard_label)
standard_labels = np.array(standard_labels)
# Plot a confusion matrix for the full dataset.
plt.figure(facecolor="white", figsize=(12, 4), dpi=100)
plt.subplot(131)
mean_err = 100 - np.mean(standard_labels == groundtruth_labels) * 100
cnf_matrix = confusion_matrix(standard_labels, groundtruth_labels)
np.set_printoptions(precision=2)
plot_confusion_matrix(
cnf_matrix,
classes=sorted(ims.keys()),
title="Full annotation set error {:.2f}%".format(mean_err),
normalize=False,
)
# Plot a confusion matrix for human-annotated Ground Truth labels.
plt.subplot(132)
mean_err = 100 - np.mean(standard_labels[human == 1.0] == groundtruth_labels[human == 1.0]) * 100
cnf_matrix = confusion_matrix(standard_labels[human == 1.0], groundtruth_labels[human == 1.0])
np.set_printoptions(precision=2)
plot_confusion_matrix(
cnf_matrix,
classes=sorted(ims.keys()),
title="Human annotation set (size {}) error {:.2f}%".format(int(sum(human)), mean_err),
normalize=False,
)
# Plot a confusion matrix for auto-annotated Ground Truth labels.
if sum(human == 0.0) > 0:
plt.subplot(133)
mean_err = (
100 - np.mean(standard_labels[human == 0.0] == groundtruth_labels[human == 0.0]) * 100
)
cnf_matrix = confusion_matrix(standard_labels[human == 0.0], groundtruth_labels[human == 0.0])
np.set_printoptions(precision=2)
plot_confusion_matrix(
cnf_matrix,
classes=sorted(ims.keys()),
title="Auto-annotation set (size {}) error {:.2f}%".format(
int(len(human) - sum(human)), mean_err
),
normalize=False,
)
```
## Plot correct and incorrect annotations
This cell repeats the plot from Plot the full results. However, it sorts the predictions into correct and incorrect, and indicates the standard label of all the incorrect predictions.
```
N_SHOW_PER_CLASS = np.inf
plt.figure(figsize=(10, 10), facecolor="white", dpi=100)
with PdfPages("ground_truth_benchmark.pdf") as pdf:
for class_name in sorted_clnames:
human_ids = np.where(np.logical_and(np.array(groundtruth_labels) == class_name, human))[0]
auto_ids = np.where(np.logical_and(np.array(groundtruth_labels) == class_name, 1 - human))[
0
]
for class_ids_id, class_ids in enumerate([human_ids, auto_ids]):
plt.clf()
plt.text(
0.1,
0.5,
s="Images annotated as {} by {}".format(
class_name, "humans" if class_ids_id == 0 else "machines"
),
fontsize=20,
)
plt.axis("off")
good_ids = class_ids[
np.where(standard_labels[class_ids] == groundtruth_labels[class_ids])[0]
]
bad_ids = class_ids[
np.where(standard_labels[class_ids] != groundtruth_labels[class_ids])[0]
]
for img_id_id, img_id in enumerate(np.concatenate([good_ids, bad_ids])):
if img_id_id == N_SHOW_PER_CLASS:
break
if img_id_id % 100 == 0:
pdf.savefig()
plt.clf()
print(
"Plotting annotations of {}, {}/{}...".format(
class_name, img_id_id, min(len(class_ids), N_SHOW_PER_CLASS)
)
)
ax = plt.subplot(10, 10, (img_id_id % 100) + 1)
plt.imshow(imageio.imread(img_fnames[img_id]), aspect="auto")
plt.axis("off")
if img_id_id < len(good_ids):
# Draw a green border around the image.
rec = matplotlib.patches.Rectangle(
(0, 0), 1, 1, lw=10, edgecolor="green", fill=False, transform=ax.transAxes
)
else:
# Draw a red border around the image.
rec = matplotlib.patches.Rectangle(
(0, 0), 1, 1, lw=10, edgecolor="red", fill=False, transform=ax.transAxes
)
ax.add_patch(rec)
pdf.savefig()
plt.clf()
```
# Train an image classifier using Ground Truth labels
At this stage, we have fully labeled our dataset and we can train a machine learning model to classify images based on the categories we previously defined. We'll do so using the **augmented manifest** output of our labeling job - no additional file translation or manipulation required! For a more complete description of the augmented manifest, see our other [example notebook](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/ground_truth_labeling_jobs/object_detection_augmented_manifest_training/object_detection_augmented_manifest_training.ipynb).
**NOTE:** Training neural networks to high accuracy often requires a careful choice of hyperparameters. In this case, we hand-picked hyperparameters that work reasonably well for this dataset. The neural net should have accuracy of about **60% if you're using 100 datapoints, and over 95% if you're using 1000 datapoints.**. To train neural networks on novel data, consider using [SageMaker's model tuning / hyperparameter optimization algorithms](https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-how-it-works.html).
First, we'll split our augmented manifest into a training set and a validation set using an 80/20 split.
```
with open("output.manifest", "r") as f:
output = [json.loads(line) for line in f.readlines()]
# Shuffle output in place.
np.random.shuffle(output)
dataset_size = len(output)
train_test_split_index = round(dataset_size * 0.8)
train_data = output[:train_test_split_index]
validation_data = output[train_test_split_index:]
num_training_samples = 0
with open("train.manifest", "w") as f:
for line in train_data:
f.write(json.dumps(line))
f.write("\n")
num_training_samples += 1
with open("validation.manifest", "w") as f:
for line in validation_data:
f.write(json.dumps(line))
f.write("\n")
```
Next, we'll upload these manifest files to the previously defined S3 bucket so that they can be used in the training job.
```
s3.upload_file("train.manifest", BUCKET, EXP_NAME + "/train.manifest")
s3.upload_file("validation.manifest", BUCKET, EXP_NAME + "/validation.manifest")
# Create unique job name
nn_job_name_prefix = "groundtruth-augmented-manifest-demo"
timestamp = time.strftime("-%Y-%m-%d-%H-%M-%S", time.gmtime())
nn_job_name = nn_job_name_prefix + timestamp
training_image = sagemaker.amazon.amazon_estimator.get_image_uri(
boto3.Session().region_name, "image-classification", repo_version="latest"
)
training_params = {
"AlgorithmSpecification": {"TrainingImage": training_image, "TrainingInputMode": "Pipe"},
"RoleArn": role,
"OutputDataConfig": {"S3OutputPath": "s3://{}/{}/output/".format(BUCKET, EXP_NAME)},
"ResourceConfig": {"InstanceCount": 1, "InstanceType": "ml.p3.2xlarge", "VolumeSizeInGB": 50},
"TrainingJobName": nn_job_name,
"HyperParameters": {
"epochs": "30",
"image_shape": "3,224,224",
"learning_rate": "0.01",
"lr_scheduler_step": "10,20",
"mini_batch_size": "32",
"num_classes": str(num_classes),
"num_layers": "18",
"num_training_samples": str(num_training_samples),
"resize": "224",
"use_pretrained_model": "1",
},
"StoppingCondition": {"MaxRuntimeInSeconds": 86400},
"InputDataConfig": [
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "AugmentedManifestFile",
"S3Uri": "s3://{}/{}/{}".format(BUCKET, EXP_NAME, "train.manifest"),
"S3DataDistributionType": "FullyReplicated",
"AttributeNames": ["source-ref", "category"],
}
},
"ContentType": "application/x-recordio",
"RecordWrapperType": "RecordIO",
"CompressionType": "None",
},
{
"ChannelName": "validation",
"DataSource": {
"S3DataSource": {
"S3DataType": "AugmentedManifestFile",
"S3Uri": "s3://{}/{}/{}".format(BUCKET, EXP_NAME, "validation.manifest"),
"S3DataDistributionType": "FullyReplicated",
"AttributeNames": ["source-ref", "category"],
}
},
"ContentType": "application/x-recordio",
"RecordWrapperType": "RecordIO",
"CompressionType": "None",
},
],
}
```
Now we create the SageMaker training job.
```
sagemaker_client = boto3.client("sagemaker")
sagemaker_client.create_training_job(**training_params)
# Confirm that the training job has started
print("Transform job started")
while True:
status = sagemaker_client.describe_training_job(TrainingJobName=nn_job_name)[
"TrainingJobStatus"
]
if status == "Completed":
print("Transform job ended with status: " + status)
break
if status == "Failed":
message = response["FailureReason"]
print("Transform failed with the following error: {}".format(message))
raise Exception("Transform job failed")
time.sleep(30)
```
# Deploy the Model
Now that we've fully labeled our dataset and have a trained model, we want to use the model to perform inference.
Image classification only supports encoded .jpg and .png image formats as inference input for now. The output is the probability values for all classes encoded in JSON format, or in JSON Lines format for batch transform.
This section involves several steps,
Create Model - Create model for the training output
Batch Transform - Create a transform job to perform batch inference.
Host the model for realtime inference - Create an inference endpoint and perform realtime inference.
## Create Model
```
timestamp = time.strftime("-%Y-%m-%d-%H-%M-%S", time.gmtime())
model_name = "groundtruth-demo-ic-model" + timestamp
print(model_name)
info = sagemaker_client.describe_training_job(TrainingJobName=nn_job_name)
model_data = info["ModelArtifacts"]["S3ModelArtifacts"]
print(model_data)
primary_container = {
"Image": training_image,
"ModelDataUrl": model_data,
}
create_model_response = sagemaker_client.create_model(
ModelName=model_name, ExecutionRoleArn=role, PrimaryContainer=primary_container
)
print(create_model_response["ModelArn"])
```
## Batch Transform
We now create a SageMaker Batch Transform job using the model created above to perform batch prediction.
### Download Test Data
First, let's download a test image that has been held out from the training and validation data.
```
timestamp = time.strftime('-%Y-%m-%d-%H-%M-%S', time.gmtime())
batch_job_name = "image-classification-model" + timestamp
batch_input = 's3://{}/{}/test/'.format(BUCKET, EXP_NAME)
batch_output = 's3://{}/{}/{}/output/'.format(BUCKET, EXP_NAME, batch_job_name)
# Copy two images from each class, unseen by the neural net, to a local bucket.
test_images = []
for class_id in ['/m/04szw', '/m/02xwb', '/m/0cd4d', '/m/07dm6', '/m/0152hh']:
test_images.extend([label[0] + '.jpg' for label in all_labels if (label[2] == class_id and label[3] == '1')][-2:])
!aws s3 rm $batch_input --recursive
for test_img in test_images:
!aws s3 cp s3://open-images-dataset/test/{test_img} {batch_input}
request = {
"TransformJobName": batch_job_name,
"ModelName": model_name,
"MaxConcurrentTransforms": 16,
"MaxPayloadInMB": 6,
"BatchStrategy": "SingleRecord",
"TransformOutput": {
"S3OutputPath": "s3://{}/{}/{}/output/".format(BUCKET, EXP_NAME, batch_job_name)
},
"TransformInput": {
"DataSource": {"S3DataSource": {"S3DataType": "S3Prefix", "S3Uri": batch_input}},
"ContentType": "application/x-image",
"SplitType": "None",
"CompressionType": "None",
},
"TransformResources": {"InstanceType": "ml.p2.xlarge", "InstanceCount": 1},
}
print("Transform job name: {}".format(batch_job_name))
sagemaker_client = boto3.client("sagemaker")
sagemaker_client.create_transform_job(**request)
print("Created Transform job with name: ", batch_job_name)
while True:
response = sagemaker_client.describe_transform_job(TransformJobName=batch_job_name)
status = response["TransformJobStatus"]
if status == "Completed":
print("Transform job ended with status: " + status)
break
if status == "Failed":
message = response["FailureReason"]
print("Transform failed with the following error: {}".format(message))
raise Exception("Transform job failed")
time.sleep(30)
```
After the job completes, let's inspect the prediction results.
```
def get_label(out_fname):
!aws s3 cp {out_fname} .
print(out_fname)
with open(out_fname.split('/')[-1]) as f:
data = json.load(f)
index = np.argmax(data['prediction'])
probability = data['prediction'][index]
print("Result: label - " + CLASS_LIST[index] + ", probability - " + str(probability))
input_fname = out_fname.split('/')[-1][:-4]
return CLASS_LIST[index], probability, input_fname
# Show prediction results.
!rm test_inputs/*
plt.figure(facecolor='white', figsize=(7, 15), dpi=100)
outputs = !aws s3 ls {batch_output}
outputs = [get_label(batch_output + prefix.split()[-1]) for prefix in outputs]
outputs.sort(key=lambda pred: pred[1], reverse=True)
for fname_id, (pred_cname, pred_conf, pred_fname) in enumerate(outputs):
!aws s3 cp {batch_input}{pred_fname} test_inputs/{pred_fname}
plt.subplot(5, 2, fname_id+1)
img = imageio.imread('test_inputs/{}'.format(pred_fname))
plt.imshow(img)
plt.axis('off')
plt.title('{}\nconfidence={:.2f}'.format(pred_cname, pred_conf))
if RUN_FULL_AL_DEMO:
warning = ''
else:
warning = ('\nNOTE: In this small demo we only used 80 images to train the neural network.\n'
'The predictions will be far from perfect! Set RUN_FULL_AL_DEMO=True to see properly trained results.')
plt.suptitle('Predictions sorted by confidence.{}'.format(warning))
```
## Realtime Inference
We now host the model with an endpoint and perform realtime inference.
This section involves several steps,
Create endpoint configuration - Create a configuration defining an endpoint.
Create endpoint - Use the configuration to create an inference endpoint.
Perform inference - Perform inference on some input data using the endpoint.
Clean up - Delete the endpoint and model
## Create Endpoint Configuration
```
timestamp = time.strftime("-%Y-%m-%d-%H-%M-%S", time.gmtime())
endpoint_config_name = job_name + "-epc" + timestamp
endpoint_config_response = sagemaker_client.create_endpoint_config(
EndpointConfigName=endpoint_config_name,
ProductionVariants=[
{
"InstanceType": "ml.m4.xlarge",
"InitialInstanceCount": 1,
"ModelName": model_name,
"VariantName": "AllTraffic",
}
],
)
print("Endpoint configuration name: {}".format(endpoint_config_name))
print("Endpoint configuration arn: {}".format(endpoint_config_response["EndpointConfigArn"]))
```
## Create Endpoint
Lastly, the customer creates the endpoint that serves up the model, through specifying the name and configuration defined above. The end result is an endpoint that can be validated and incorporated into production applications. This takes about 10 minutes to complete.
```
timestamp = time.strftime("-%Y-%m-%d-%H-%M-%S", time.gmtime())
endpoint_name = job_name + "-ep" + timestamp
print("Endpoint name: {}".format(endpoint_name))
endpoint_params = {
"EndpointName": endpoint_name,
"EndpointConfigName": endpoint_config_name,
}
endpoint_response = sagemaker_client.create_endpoint(**endpoint_params)
print("EndpointArn = {}".format(endpoint_response["EndpointArn"]))
# get the status of the endpoint
response = sagemaker_client.describe_endpoint(EndpointName=endpoint_name)
status = response["EndpointStatus"]
print("EndpointStatus = {}".format(status))
# wait until the status has changed
sagemaker_client.get_waiter("endpoint_in_service").wait(EndpointName=endpoint_name)
# print the status of the endpoint
endpoint_response = sagemaker_client.describe_endpoint(EndpointName=endpoint_name)
status = endpoint_response["EndpointStatus"]
print("Endpoint creation ended with EndpointStatus = {}".format(status))
if status != "InService":
raise Exception("Endpoint creation failed.")
with open("test_inputs/{}".format(test_images[0]), "rb") as f:
payload = f.read()
payload = bytearray(payload)
client = boto3.client("sagemaker-runtime")
response = client.invoke_endpoint(
EndpointName=endpoint_name, ContentType="application/x-image", Body=payload
)
# `response` comes in a json format, let's unpack it.
result = json.loads(response["Body"].read())
# The result outputs the probabilities for all classes.
# Find the class with maximum probability and print the class name.
print("Model prediction is: {}".format(CLASS_LIST[np.argmax(result)]))
```
Finally, let's clean up and delete this endpoint.
```
sagemaker_client.delete_endpoint(EndpointName=endpoint_name)
```
# Review
We covered a lot of ground in this notebook! Let's recap what we accomplished. First we started with an unlabeled dataset (technically, the dataset was previously labeled by the authors of the dataset, but we discarded the original labels for the purposes of this demonstration). Next, we created a SageMake Ground Truth labeling job and generated new labels for all of the images in our dataset. Then we split this file into a training set and a validation set and trained a SageMaker image classification model. Finally, we created a hosted model endpoint and used it to make a live prediction for a held-out image in the original dataset.
| github_jupyter |
```
import numpy as np
from scipy.stats import norm
from scipy.optimize import minimize, rosen
import sklearn.gaussian_process as gp
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import ConstantKernel, Matern, WhiteKernel, RBF,ExpSineSquared
import math
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
lbound = -1
rbound = 2
X = np.arange(lbound,rbound, 0.01).reshape(-1, 1)
def function(X,noise=0):
# return (-np.sin(3*X[:,0]) - X[:,0]**2 + 0.7*X[:,0] + noise * np.random.randn(*X[:,0].shape)).reshape(-1,1)
# return (math.pow((x2-5.1/(4*math.pow(3.14,2))*math.pow(x1,2)+5/3.14*x1-6),2)+10*(1-1/(8*3.14))*math.cos(x1)+10)
def func(x):
return (math.pow((x[1]-5.1/(4*math.pow(3.14,2))*math.pow(x[0],2)+5/3.14*x[0]-6),2)+10*(1-1/(8*3.14))*math.cos(x[0])+10)
return np.apply_along_axis(func, 1, X).reshape(-1,1)
function(np.array([[-0.36,1],[5,1]]))
a = np.linspace(-10,10,1000)
X = np.zeros((1000000,2))
c=0
for i in a:
for j in a:
X[c,0] = i
X[c,1] = j
c+=1
# a = a.reshape(-1,1)
l = function(X)
print(np.max(l),np.argmax(l))
function(np.array([[-100,-100]]))
# l
## return probability of improvement for random sample/s X
def PI(X,X_t,gpr,e):
y_t = gpr.predict(X_t)
X= np.expand_dims(X,axis=0)
y,std = gpr.predict(X,return_std=True)
std = std.reshape(-1,1)
best_y = np.max(y_t)
return norm.cdf((y-best_y-e)/std)
def EI(X,X_t,gpr,e):
y_t = gpr.predict(X_t)
X= np.expand_dims(X,axis=0)
y,std = gpr.predict(X,return_std=True)
std = std.reshape(-1,1)
best_y = np.max(y_t)
a = (y-best_y-e)
ei = a*norm.cdf(a/std) + std*norm.pdf(a/std)
ei[std==0] = 0
return ei
## function to get next point that optimise aquisition function
def next_acquisition_point(X_t,gpr,e,trials,acq_func,lbound,rbound,d):
min_val = 1
min_x = None
def min_obj(x):
return -acq_func(x,X_t,gpr,e)
random_starts = np.random.uniform(lbound,rbound,size=(trials,d))
bounds = np.zeros((d,2))
bounds[:,0] = lbound
bounds[:,1] = rbound
for st in random_starts:
# print(np.expand_dims(st, axis=0))
# print(X_t)
candidate = minimize(min_obj,x0=np.expand_dims(st, axis=0),bounds=bounds,method='L-BFGS-B')
if candidate.fun < min_val:
min_val = candidate.fun
min_x = candidate.x
return np.expand_dims(min_x,axis=0)
```
**Simple BO**
```
## Using BO for function optimisation
def get_optimum(acq_func,D=25,runs=10,iters=200):
best_val = 2013.9256356583692 #0.500270129755324
# iters = 30
dp = np.zeros((runs,iters))
for run in range(runs):
print("run no. - "+str(run))
# kernel = ConstantKernel(1.0) * WhiteKernel() + ConstantKernel(1.0) * RBF() + 1.0 * ExpSineSquared()
kernel = ConstantKernel(1.0) * Matern(length_scale=1.0, nu=2.5)
gpr = GaussianProcessRegressor(kernel=kernel, alpha=0.3**2)
# X_t = np.array([[-0.9]])
X_t = np.random.uniform(-10,10,size=(1,D))
# X_t[0,0] = -0.9
y_t = function(X_t)
optimality_gap = best_val-y_t[0,0]
dp[run,0] = optimality_gap
for i in range(1,iters):
# print(i)
gpr.fit(X_t,y_t)
X_next = next_acquisition_point(X_t,gpr,0.005,2,acq_func,-10,10,D)
y_next = function(X_next)
X_t = np.concatenate((X_t,X_next),axis=0)
y_t = np.concatenate((y_t,y_next),axis=0)
if best_val-y_t[i,0] < optimality_gap:
optimality_gap = best_val-y_t[i,0]
dp[run,i] = optimality_gap
if runs==1:
print(X_t)
print(y_t)
return dp
# dp_PI = get_optimum(PI,50,1)
dp_EI = get_optimum(EI,50,10,100)
```
**Random search**
```
def random_search(runs,D,iters=200):
best_val = 2013.9256356583692 #0.500270129755324
# iters = 30
dp = np.zeros((runs,iters))
for run in range(10):
# X_t = np.array([[-0.9]])
X_t = np.random.uniform(-10,10,size=(1,D))
# X_t[0,0] = -0.9
y_t = function(X_t)
# print(y_t)
optimality_gap = best_val-y_t[0,0]
dp[run,0] = optimality_gap
for i in range(1,iters):
X_next = np.random.uniform(-10,10,size=(1,D))
y_next = function(X_next)
X_t = np.concatenate((X_t,X_next),axis=0)
y_t = np.concatenate((y_t,y_next),axis=0)
if best_val-y_t[i,0] < optimality_gap:
optimality_gap = best_val-y_t[i,0]
dp[run,i] = optimality_gap
return dp
dp_random = random_search(10,50)
```
**REMBO**
```
def get_proj_matrix(D,d,hypersphere=0):
A = np.random.normal(0,1,(D,d))
if hypersphere==1:
for row in range(D):
N = np.linalg.norm(A[row,:])
A[row,:] = A[row,:]/N
return A
def projection_func(x):
x[x<-1] = -1
x[x>1] = 1
return x
def scale(x,bounds):
mu = (bounds[:,0]+bounds[:,1])/2
diff = (bounds[:,1]-bounds[:,0])/2
new_x = mu+diff*x
return new_x
scale(np.array([1,0]),np.array([[-1,2],[-1,2]]))
def rembo_optima(acq_func,d_e=2,D=25,runs=4,eps=10,max_iter=100):
best_val =2013.9256356583692 # 0.500270129755324
iters = int(max_iter/runs)
dp = np.zeros((eps,max_iter))
max_dp = np.zeros((eps,max_iter))
for ep in range(eps):
c=0
print("run no. - "+str(ep))
for run in range(runs):
# kernel = ConstantKernel(1.0) * WhiteKernel() + ConstantKernel(1.0) * RBF() + 1.0 * ExpSineSquared()
kernel = ConstantKernel(1.0) * Matern(length_scale=1.0, nu=2.5)
gpr = GaussianProcessRegressor(kernel=kernel, alpha=0.3**2)
# X_t = np.array([[-0.9]])
X_t = np.random.uniform(-math.sqrt(d_e),math.sqrt(d_e),size=(1,d_e))
A = get_proj_matrix(D,d_e,1)
p_X_t = projection_func((A @ X_t.T).T)
# print(p_X_t)
bounds = np.zeros((D,2))
bounds[:,0] = -10
bounds[:,1] = 10
y_t = function(scale(p_X_t,bounds))
# print(y_t)
optimality_gap = best_val-y_t[0,0]
if c==0:
dp[ep,0] = optimality_gap
max_dp[ep,0] = y_t[0,0]
else:
dp[ep,c] = min(optimality_gap,dp[ep,c-1])
max_dp[ep,c] = max(y_t[0,0],max_dp[ep,c-1])
c+=1
for i in range(1,iters):
# print(i)
# print(X_t)
# print(y_t)
# print(i)
gpr.fit(X_t,y_t)
X_next = next_acquisition_point(X_t,gpr,0.005,2,acq_func,-math.sqrt(d_e),math.sqrt(d_e),d_e)
# print(X_next)
p_X_next = projection_func((A @ X_next.T).T)
# print(p_X_next)
y_next = function(scale(p_X_next,bounds))
# print(y_next)
X_t = np.concatenate((X_t,X_next),axis=0)
y_t = np.concatenate((y_t,y_next),axis=0)
# if best_val-y_t[i,0] < optimality_gap:
# optimality_gap = best_val-y_t[i,0]
dp[ep,c] = min(best_val-y_t[i,0],dp[ep,c-1])
max_dp[ep,c] = max(y_t[i,0],max_dp[ep,c-1])
c+=1
# dp[run,i] = optimality_gap
if iters==1:
print(X_t)
print(y_t)
return dp,max_dp
dp_rembo,max_dp = rembo_optima(EI,3,50,1,10,100)
print(dp_rembo)
print(max_dp)
## plot showing optimality gap between max value obtained in each iteration and best value that can be obtained in the bound for two different aquisition functions - PI and EI.
iters=100
# x = range(iters)
# y = []
# y1 = []
# y2 = []
# for i in range(iters):
# mean = np.mean(dp_PI[:,i])
# std = np.std(dp_PI[:,i])
# dev_up = np.max(dp_PI[:,i])
# dev_down = np.min(dp_PI[:,i])
# y.append(mean)
# y1.append(mean-std/4)
# y2.append(mean+std/4)
# # y1.append(dev_up)
# y2.append(dev_down)
fig = plt.figure(num=1, figsize=(15, 15), dpi=80, facecolor='w', edgecolor='k')
ax = fig.add_subplot(111)
# ax.fill_between(x, y1, y2, color="red", alpha=0.4,label='PI')
# ax.plot(x,y,'--',color='red')
x = range(iters)
y = []
y1 = []
y2 = []
for i in range(iters):
mean = np.mean(dp_EI[:,i])
std = np.std(dp_EI[:,i])
dev_up = np.max(dp_EI[:,i])
dev_down = np.min(dp_EI[:,i])
y.append(mean)
y1.append(mean-std/4)
y2.append(mean+std/4)
ax.fill_between(x, y1, y2, color="blue", alpha=0.4,label = 'EI')
ax.plot(x,y,'--',color='blue')
ax.legend(loc='upper right', borderpad=1, labelspacing=1,prop={'size':15})
ax.set_ylabel("Optimality Gap")
ax.set_xlabel("Iteration no.")
x = range(iters)
y = []
y1 = []
y2 = []
for i in range(iters):
mean = np.mean(dp_random[:,i])
std = np.std(dp_random[:,i])
dev_up = np.max(dp_random[:,i])
dev_down = np.min(dp_random[:,i])
y.append(mean)
y1.append(mean-std/4)
y2.append(mean+std/4)
ax.fill_between(x, y1, y2, color="violet", alpha=0.4,label = 'Random search')
ax.plot(x,y,'--',color='violet',label='Random search')
ax.legend(loc='upper right', borderpad=1, labelspacing=1,prop={'size':15})
ax.set_ylabel("Optimality Gap")
ax.set_xlabel("Iteration no.")
x = range(iters)
y = []
y1 = []
y2 = []
for i in range(iters):
mean = np.mean(dp_rembo[:,i])
std = np.std(dp_rembo[:,i])
dev_up = np.max(dp_rembo[:,i])
dev_down = np.min(dp_rembo[:,i])
y.append(mean)
y1.append(mean-std/4)
y2.append(mean+std/4)
ax.fill_between(x, y1, y2, color="yellow", alpha=0.4,label = 'REMBO')
ax.plot(x,y,'--',color='green',label='REMBO')
ax.legend(loc='upper right', borderpad=1, labelspacing=1,prop={'size':15})
ax.set_ylabel("Optimality Gap")
ax.set_xlabel("Iteration no.")
ax.set_title("FIgure shows different techniques efficiency for BO in 25 dimensional feature space(intrinsic dimension = 1)")
##
plt.show(1)
print(dp_rembo[:,99])
print(dp_random[:,99])
```
| github_jupyter |
```
import rekall
from rekall.video_interval_collection import VideoIntervalCollection
from esper.rekall import intrvllists_to_result
from esper.prelude import *
```
# Frame Version
```
def frame_result(video_ids_to_frame_nums, window = 0):
materialized_result = []
for video_id in video_ids_to_frame_nums:
frame_nums = video_ids_to_frame_nums[video_id]
for frame_num in frame_nums:
for f in range(frame_num - window, frame_num + window + 1):
materialized_result.append({
'video': video_id,
'min_frame': f,
'objects': [{
'id': 0,
'type': 'bbox',
'bbox_x1': 0.01,
'bbox_x2': .99,
'bbox_y1': 0.01,
'bbox_y2': 1.01,
'gender_id': 2
}] if f == frame_num else []
})
return {'type': 'frames', 'count': 0, 'result': [{
'type': 'flat', 'label': '', 'elements': [mr]
} for mr in materialized_result]}
missed_frames = []
for i in range(5):
with open('/app/data/failure_cases/metal_frame_only/{}_fold.pkl'.format(i + 1), 'rb') as f:
missed_frames += pickle.load(f)
collected_bad_frames = collect(missed_frames, lambda tup: tup[0][0])
# show missed boundaries
esper_widget(frame_result({
video_id: [
tup[0][1]
for tup in collected_bad_frames[video_id] if tup[0][2] == 1
]
for video_id in collected_bad_frames
}, window=1),jupyter_keybindings=True, max_width=965, thumbnail_size=1.25, results_per_page=99,)
# show incorrectly guessed boundaries
esper_widget(frame_result({
video_id: [
tup[0][1]
for tup in collected_bad_frames[video_id] if tup[0][2] == 2
]
for video_id in collected_bad_frames
}, window=1),jupyter_keybindings=True,max_width=965, thumbnail_size=1.25, results_per_page=99,)
```
# Window Version
STILL TDB
```
bad_intervals = [(34, (9456, 9472, 1)),
(34, (9464, 9480, 1)),
(34, (9624, 9640, 2)),
(34, (9632, 9648, 2)),
(34, (9640, 9656, 2)),
(34, (9672, 9688, 2)),
(34, (9680, 9696, 2)),
(34, (9928, 9944, 2)),
(34, (9936, 9952, 2)),
(34, (10016, 10032, 1)),
(34, (10024, 10040, 1)),
(34, (10504, 10520, 2)),
(34, (10512, 10528, 2)),
(148, (157824, 157840, 1)),
(148, (157832, 157848, 1)),
(148, (157888, 157904, 1)),
(148, (157896, 157912, 1)),
(148, (158336, 158352, 2)),
(148, (158344, 158360, 2)),
(172, (153088, 153104, 2)),
(172, (153096, 153112, 2)),
(172, (153120, 153136, 1)),
(172, (153128, 153144, 1)),
(172, (153288, 153304, 2)),
(172, (153296, 153312, 2)),
(172, (153304, 153320, 2)),
(172, (153312, 153328, 2)),
(172, (153352, 153368, 1)),
(172, (153360, 153376, 1)),
(172, (153400, 153416, 1)),
(172, (153408, 153424, 1)),
(172, (153512, 153528, 1)),
(172, (153520, 153536, 1)),
(172, (153576, 153592, 1)),
(172, (153584, 153600, 1)),
(172, (153720, 153736, 1)),
(172, (153776, 153792, 1)),
(172, (153784, 153800, 1)),
(172, (154016, 154032, 1)),
(172, (154032, 154048, 2)),
(172, (154104, 154120, 1)),
(172, (154112, 154128, 1)),
(172, (154200, 154216, 2)),
(172, (154208, 154224, 2)),
(172, (154216, 154232, 2)),
(172, (154232, 154248, 2)),
(172, (154240, 154256, 2)),
(172, (154296, 154312, 2)),
(172, (154312, 154328, 2)),
(172, (154320, 154336, 2)),
(172, (154400, 154416, 1)),
(172, (154408, 154424, 1)),
(172, (154448, 154464, 2)),
(172, (154456, 154472, 2)),
(181, (44088, 44104, 2)),
(181, (44096, 44112, 2)),
(181, (44160, 44176, 2)),
(181, (44168, 44184, 2)),
(181, (44176, 44192, 2)),
(181, (44184, 44200, 2)),
(181, (44248, 44264, 1)),
(181, (44256, 44272, 1)),
(181, (44288, 44304, 1)),
(181, (44296, 44312, 1)),
(181, (44920, 44936, 2)),
(181, (44928, 44944, 2)),
(201, (117744, 117760, 2)),
(201, (117752, 117768, 2)),
(201, (118288, 118304, 2)),
(201, (118296, 118312, 2)),
(248, (59672, 59688, 2)),
(248, (59680, 59696, 2)),
(308, (67424, 67440, 2)),
(308, (67656, 67672, 2)),
(308, (67664, 67680, 2)),
(557, (35832, 35848, 2)),
(557, (35840, 35856, 2)),
(557, (35848, 35864, 2)),
(557, (36272, 36288, 2)),
(577, (84000, 84016, 2)),
(577, (84008, 84024, 2)),
(585, (39712, 39728, 2)),
(585, (40904, 40920, 2)),
(585, (40912, 40928, 2))]
bad_intervals_collected = collect(bad_intervals, kfn=lambda vid_intrvl: vid_intrvl[0])
missed_intervals = VideoIntervalCollection({
video_id: [
vid_intrvl[1]
for vid_intrvl in bad_intervals_collected[video_id] if vid_intrvl[1][2] == 1
]
for video_id in bad_intervals_collected
})
incorrect_intervals = VideoIntervalCollection({
video_id: [
vid_intrvl[1]
for vid_intrvl in bad_intervals_collected[video_id] if vid_intrvl[1][2] == 2
]
for video_id in bad_intervals_collected
})
esper_widget(intrvllists_to_result(missed_intervals), jupyter_keybindings=True)
esper_widget(intrvllists_to_result(incorrect_intervals), jupyter_keybindings=True)
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
columns = ['cnt', 'timestamp', 't1', 't2', 'hum', 'wind_speed', 'weather_code', 'is_holiday', 'is_weekend', 'season']
df = pd.read_csv('data.csv', usecols=columns)
df['timestamp'] = df['timestamp'].str.slice(10,13)
df['timestamp'] = df['timestamp'].astype(int).astype(str)
from sklearn.model_selection import train_test_split
df['cnt']=np.log1p(df['cnt'])
df_train_full, df_test = train_test_split(df, test_size=0.2, random_state=42)
df_train, df_val = train_test_split(df_train_full, test_size=0.25, random_state=42)
df_train = df_train.reset_index(drop=True)
df_val = df_val.reset_index(drop=True)
df_test = df_test.reset_index(drop=True)
y_train = df_train.cnt.values
y_val = df_val.cnt.values
y_test = df_test.cnt.values
del df_train['cnt']
del df_val['cnt']
del df_test['cnt']
from sklearn.feature_extraction import DictVectorizer
train_dict = df_train.to_dict(orient='records')
dv = DictVectorizer(sparse=False)
dv.fit(train_dict)
X_train = dv.transform(train_dict)
val_dict = df_val.to_dict(orient='records')
dv = DictVectorizer(sparse=False)
dv.fit(val_dict)
X_val = dv.transform(val_dict)
plt.figure(figsize=(15,10))
sns.heatmap(df.corr(),annot=True,linewidths=.5, cmap="Blues")
plt.title('Heatmap showing correlations between data')
plt.show()
df.corr().unstack().sort_values(ascending = False)
from sklearn.metrics import mean_squared_log_error
def rmse(y_true, y_pred):
return(np.sqrt(mean_squared_log_error(y_true, y_pred)))
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import export_text
dt = DecisionTreeRegressor(max_depth=1)
dt.fit(X_train, y_train)
print(export_text(dt, feature_names=dv.get_feature_names()))
from sklearn.ensemble import RandomForestRegressor
scores = []
ns = [10, 20, 30, 40, 50, 100]
for n in ns:
rf = RandomForestRegressor(n_estimators = n, random_state = 1, n_jobs = -1)
rf.fit(X_train, y_train)
y_pred = rf.predict(X_val)
score = rmse(y_val, y_pred)
scores.append((n,score))
df_scores = pd.DataFrame(scores, columns=['n_estimators', 'rmse'])
plt.plot(df_scores.n_estimators, df_scores.rmse)
from sklearn.ensemble import RandomForestRegressor
scores = []
depths = [10, 15, 20, 25, 50, 100]
n = 100
for d in depths:
rf = RandomForestRegressor(n_estimators = n, max_depth = d, random_state = 1, n_jobs = -1)
rf.fit(X_train, y_train)
y_pred = rf.predict(X_val)
score = rmse(y_val, y_pred)
scores.append((d,score))
df_scores = pd.DataFrame(scores, columns=['max_depth', 'rmse'])
plt.plot(df_scores.max_depth, df_scores.rmse)
d = 100
rf = RandomForestRegressor(n_estimators = n, max_depth = d, random_state = 1, n_jobs = -1)
rf.fit(X_train, y_train)
y_pred = rf.predict(X_val)
print(rmse(y_val, y_pred))
import xgboost as xgb
features = dv.get_feature_names()
dtrain = xgb.DMatrix(X_train, label=y_train, feature_names=features)
dval = xgb.DMatrix(X_val, label=y_val, feature_names=features)
xgb_params = {
'eta': 0.3,
'max_depth': 6,
'min_child_weight': 1,
'objective': 'reg:squarederror',
'nthread': 8,
'seed': 1,
'verbosity': 1,
}
watchlist = [(dtrain, 'train'), (dval, 'val')]
scores = []
etas = [0.01, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3]
for eta in etas:
xgb_params['eta'] = eta
model = xgb.train(xgb_params, dtrain, num_boost_round=100, evals = watchlist)
y_pred = model.predict(dval)
rmse_score = rmse(y_val, y_pred)
scores.append((eta,rmse_score))
df_scores = pd.DataFrame(scores, columns=['eta', 'rmse'])
plt.plot(df_scores.eta, df_scores.rmse)
scores = []
max_depth = [5, 10 , 15, 20]
for depth in max_depth:
xgb_params['eta'] = 0.3
xgb_params['max_depths'] = depth
model = xgb.train(xgb_params, dtrain, num_boost_round=100, evals = watchlist)
y_pred = model.predict(dval)
rmse_score = rmse(y_val, y_pred)
scores.append((depth,rmse_score))
df_scores = pd.DataFrame(scores, columns=['max_depth', 'rmse'])
plt.plot(df_scores.max_depth, df_scores.rmse)
scores = []
min_child_weights = [5, 6 , 7, 8, 9, 10]
for weight in min_child_weights:
xgb_params['min_child_weights'] = weight
model = xgb.train(xgb_params, dtrain, num_boost_round=100, evals = watchlist)
y_pred = model.predict(dval)
rmse_score = rmse(y_val, y_pred)
scores.append((weight,rmse_score))
df_scores = pd.DataFrame(scores, columns=['min_child_weights', 'rmse'])
plt.plot(df_scores.min_child_weights, df_scores.rmse)
```
| github_jupyter |
# Transfer Learning
In this notebook, you'll learn how to use pre-trained networks to solved challenging problems in computer vision. Specifically, you'll use networks trained on [ImageNet](http://www.image-net.org/) [available from torchvision](http://pytorch.org/docs/0.3.0/torchvision/models.html).
ImageNet is a massive dataset with over 1 million labeled images in 1000 categories. It's used to train deep neural networks using an architecture called convolutional layers. I'm not going to get into the details of convolutional networks here, but if you want to learn more about them, please [watch this](https://www.youtube.com/watch?v=2-Ol7ZB0MmU).
Once trained, these models work astonishingly well as feature detectors for images they weren't trained on. Using a pre-trained network on images not in the training set is called transfer learning. Here we'll use transfer learning to train a network that can classify our cat and dog photos with near perfect accuracy.
With `torchvision.models` you can download these pre-trained networks and use them in your applications. We'll include `models` in our imports now.
```
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
```
Most of the pretrained models require the input to be 224x224 images. Also, we'll need to match the normalization used when the models were trained. Each color channel was normalized separately, the means are `[0.485, 0.456, 0.406]` and the standard deviations are `[0.229, 0.224, 0.225]`.
```
data_dir = '/home/ivlabs/users/akshay/datasets/Cat_Dog_data'
# TODO: Define transforms for the training data and testing data
train_transforms = transforms.Compose([transforms.RandomRotation(30),
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])])
test_transforms = transforms.Compose([transforms.Resize(255),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])])
# Pass transforms in here, then run the next cell to see how the transforms look
train_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)
test_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)
trainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
testloader = torch.utils.data.DataLoader(test_data, batch_size=64)
```
We can load in a model such as [DenseNet](http://pytorch.org/docs/0.3.0/torchvision/models.html#id5). Let's print out the model architecture so we can see what's going on.
```
model = models.densenet121(pretrained=True)
model
```
This model is built out of two main parts, the features and the classifier. The features part is a stack of convolutional layers and overall works as a feature detector that can be fed into a classifier. The classifier part is a single fully-connected layer `(classifier): Linear(in_features=1024, out_features=1000)`. This layer was trained on the ImageNet dataset, so it won't work for our specific problem. That means we need to replace the classifier, but the features will work perfectly on their own. In general, I think about pre-trained networks as amazingly good feature detectors that can be used as the input for simple feed-forward classifiers.
```
# Freeze parameters so we don't backprop through them
for param in model.parameters():
param.requires_grad = False
from collections import OrderedDict
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(1024, 512)),
('relu', nn.ReLU()),
('fc2', nn.Linear(512, 2)),
('output', nn.LogSoftmax(dim=1))
]))
model.classifier = classifier
```
With our model built, we need to train the classifier. However, now we're using a **really deep** neural network. If you try to train this on a CPU like normal, it will take a long, long time. Instead, we're going to use the GPU to do the calculations. The linear algebra computations are done in parallel on the GPU leading to 100x increased training speeds. It's also possible to train on multiple GPUs, further decreasing training time.
PyTorch, along with pretty much every other deep learning framework, uses [CUDA](https://developer.nvidia.com/cuda-zone) to efficiently compute the forward and backwards passes on the GPU. In PyTorch, you move your model parameters and other tensors to the GPU memory using `model.to('cuda')`. You can move them back from the GPU with `model.to('cpu')` which you'll commonly do when you need to operate on the network output outside of PyTorch. As a demonstration of the increased speed, I'll compare how long it takes to perform a forward and backward pass with and without a GPU.
```
import time
for device in ['cpu', 'cuda']:
criterion = nn.NLLLoss()
# Only train the classifier parameters, feature parameters are frozen
optimizer = optim.Adam(model.classifier.parameters(), lr=0.001)
model.to(device)
for ii, (inputs, labels) in enumerate(trainloader):
# Move input and label tensors to the GPU
inputs, labels = inputs.to(device), labels.to(device)
start = time.time()
outputs = model.forward(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if ii==3:
break
print(f"Device = {device}; Time per batch: {(time.time() - start)/3:.3f} seconds")
```
You can write device agnostic code which will automatically use CUDA if it's enabled like so:
```python
# at beginning of the script
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
...
# then whenever you get a new Tensor or Module
# this won't copy if they are already on the desired device
input = data.to(device)
model = MyModule(...).to(device)
```
From here, I'll let you finish training the model. The process is the same as before except now your model is much more powerful. You should get better than 95% accuracy easily.
>**Exercise:** Train a pretrained models to classify the cat and dog images. Continue with the DenseNet model, or try ResNet, it's also a good model to try out first. Make sure you are only training the classifier and the parameters for the features part are frozen.
```
## TODO: Use a pretrained model to classify the cat and dog images
from torch.autograd import Variable
cuda = torch.cuda.is_available()
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.classifier.parameters(), lr = 1e-3)
epochs = 5
if cuda:
model.cuda()
for i in range(epochs):
running_loss = 0
steps = 0
for batch_id, (images, labels) in enumerate(trainloader):
model.train()
steps += 1
if cuda:
images, labels = images.cuda(), labels.cuda()
outputs = model.forward(images)
optimizer.zero_grad()
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if steps % 5 == 0:
accuracy = 0
test_loss = 0
model.eval()
for batch_id, (images, labels) in enumerate(testloader):
if cuda:
images, labels = images.cuda(), labels.cuda()
logps = model(images)
loss = criterion(logps, labels)
test_loss += loss.item()
ps = torch.exp(logps)
top_ps, top_class = ps.topk(1, dim = 1)
equality = top_class == labels.view(*top_class.shape)
accuracy += torch.mean(equality.float()).item()
print("Epoch: {}/{}.. ".format(i+1, epochs),
"Training Loss: {:.3f}.. ".format(running_loss/len(trainloader)),
"Test Loss: {:.3f}.. ".format(test_loss/len(testloader)),
"Test Accuracy: {:.3f}".format(accuracy/len(testloader)))
running_loss = 0
```
| github_jupyter |
```
from __future__ import print_function
import numpy as np
from bqplot import (
Axis, ColorAxis, LinearScale, DateScale, DateColorScale, OrdinalScale,
OrdinalColorScale, ColorScale, Scatter, Lines, Figure, Tooltip
)
import ipywidgets as widgets
```
# Exercise: Using one plot as a control for another
Although [bqplot](https://github.com/bloomberg/bqplot) is a versatile plotting package, one of its unique strengths is that the plot is a widget. Plot elements, like the position of points on the graph, can be monitored for changes like any other widget trait.
The example in this notebook graphs a Fourier sine series using [bqplot](https://github.com/bloomberg/bqplot) to graph the series and a separate [bqplot](https://github.com/bloomberg/bqplot) to allow users to sest the amplitude of the terms in the series.
## Final widget will look like this:
<img src="images/plot-as-control.gif" width="50%">
## Define the function that calculates the Fourier series
Though in a real application the plot range and number of points should perhaps be configurable via a widget, for this example they are hard coded.
```
def fourier_series(amplitudes):
"""
Compute the fourier sine series given a set of amplitudes. The
period of the fundamental of the series is 1 and the series is
generated for two periods.
"""
period = 1.0
x = np.linspace(0, 2 * period, num=1000)
y = np.sum(a * np.sin(2 * np.pi * (n + 1) * x / period)
for n, a in enumerate(amplitudes))
return x, y
```
The number of Fourier components in the series should probably also be user-configurable; for the sake of simplicity it is hard coded here. We also define some test data so we can look at plot for setting the amplitudes before we connect it up to the plot of the Fourier series sum.
```
N_fourier_components = 10
x_data = np.arange(N_fourier_components) + 1
y_data = np.random.uniform(low=-1, high=1, size=N_fourier_components)
```
## Create the amplitude control
We will create both this and the plot of the series using the "Grammar of Graphics" interface to bqplot. That makes it easier to treat the plot as a widget.
Please read through and execute the example below.
```
# Start by defining a scale for each axis
sc_x = LinearScale()
# The amplitudes are limited to ±1 for this example...
sc_y = LinearScale(min=-1.0, max=1.0)
# You can create a Scatter object without supplying the data at this
# point. It is here so we can see how the control looks.
scat = Scatter(x=x_data, y=y_data,
scales={'x': sc_x, 'y': sc_y},
colors=['orange'],
# This is what makes this plot interactive
enable_move=True)
# Only allow points to be moved vertically...
scat.restrict_y = True
# Define the axes themselves
ax_x = Axis(scale=sc_x)
ax_y = Axis(scale=sc_y, tick_format='0.2f', orientation='vertical')
# The graph itself...
amplitude_control = Figure(marks=[scat], axes=[ax_x, ax_y],
title='Fourier amplitudes')
# This width is chosen just to make the plot fit nicely with
# another. Change it if you want.
amplitude_control.layout.width = '400px'
# Let's see what this looks like...
amplitude_control
```
Try dragging the points on the graph around. Print the $y$-data from the plot (`scat.y`) and the original data below you they should be different.
## Set up some initial conditions
To test our sine series plot it is helpful to start with a simple-to-understand series: just the fundmental, with amplitude 1.
```
# Add some test data to make view the result
initial_amplitudes = np.zeros(10)
initial_amplitudes[0] = 1.0
```
## Create the plot of the Fourier series
As above, we create the plot using the Grammar of Graphics interface.
```
lin_x = LinearScale()
lin_y = LinearScale()
# Note that here, unlike above, we do not set the initial data.
line = Lines(scales={'x': lin_x, 'y': lin_y}, colors=['orange'],
enable_move=False)
ax_x = Axis(scale=lin_x)
ax_y = Axis(scale=lin_y, tick_format='0.2f', orientation='vertical')
result = Figure(marks=[line], axes=[ax_x, ax_y],
title='Fourier sine series',
# Honestly, I just like the way the animation looks.
# Value is in milliseconds.
animation_duration=500)
# Size as you wish...
result.layout.width = '400px'
# Calculate the fourier series....
line.x, line.y = fourier_series(initial_amplitudes)
# Let's take a look!
result
```
### Set the amplitude control to match this initial case
Note that you can access the `scat` object from the `Figure` widget. Each line, scatter or other mark on the plot is in the list at `.marks`.
```
amplitude_control.marks[0].y = initial_amplitudes
```
## You make the widget out of `amplitude_control` and `result`
See the animation above for a reminder of the target. Dragging the amplitudes will *not* change the sine series yet.
```
# %load solutions/bqplot-as-control/box-widget.py
box = widgets.HBox(children=[amplitude_control, result])
box
```
## Looks good, connect things up
Fill in the body of the function below, which will be observed by `amplitude_control`. You should call `fourier_series` and set the appropriate line properties.
```
# %load solutions/bqplot-as-control/update_line.py
def update_line(change):
pass # fill in
# React to changes in the y value....
amplitude_control.marks[0].observe(update_line, names=['y'])
```
| github_jupyter |
# Demo 2
This demo is about advanced model architectures and the incorporation of MR-specific knowledge. We will look at how to implement an interactive (unrolled) architecture of the reconstruction network. Then, we will consider an essential element of the incorporated MR-specific knowledge - data consistency.
Let us define all required imports here:
```
import torch
import numpy as np
import matplotlib.pyplot as plt
from torch import nn
from typing import List
```
## Part 1. Iterative architecture
The following blocks show **not runnable pseudocode** for an iterative model architecture. Note that iterative architecture can have two embodiments: rolled and unrolled.
- In the first case, the same reconstruction block is reused on all iterations. It helps to reduce the model footprint in exchange for limited performance capabilities.
- An unrolled architecture uses different recon blocks on various stages of reconstruction. It increases network capacity and generally leads to better performance. However, such models and more data-hungry, and their memory footprint is significantly larger.
```
# Pseudo code
# ReconBlock can be a U-Net model considered in the previous demo
class ReconBlock(nn.Module):
def __init__(self) -> None:
super(ReconBlock, self).__init__()
self.downsample = []
self.upsample = []
def forward(image: torch.Tensor) -> torch.Tensor:
return self.downsample(self.upsample(image))
# Pseudo code, very complex in reality
class IterativeModel(nn.Module):
def __init__(self, recon_blocks: List[nn.Module], data_consistency: nn.Module, num_iterations: int,
iterative_type: str = 'unrolled') -> None:
""" Class-constructor for the iterative reconstruction model.
Args:
recon_blocks: collection of recon blocks. Contains a single block in case of 'rolled' iterative type
data_consistency: mr-specific operation
num_iterations: number of iterations with a single block in case of 'rolled' iterative type
iterative_type: either 'rolled' or 'unrolled'
"""
super(IterativeModel, self).__init__()
self.recon_blocks = recon_blocks
self.data_consistency = data_consistency
self.iterative_type = iterative_type
self.num_iterations = num_iterations
def __forward__(self, image: torch.Tensor) -> torch.Tensor:
# In case of unrolled reconstruction, sequentially apply reconstruction blocks.
# Apply data consistency between recon blocks
if self.iterative_type == 'unrolled':
for block in self.recon_blocks:
recon = block(image)
correction = self.data_consistency(recon)
image = recon - correction
# In case of unrolled reconstruction, apply the same recon block 'self.num_iterations' times.
# Apply data consistency between recon blocks
elif self.iterative_type == 'rolled':
block = self.recon_blocks[0]
for _ in range(self.num_iterations):
recon = block(image)
correction = self.data_consistency(recon)
image = recon - correction
```
## Part 2. Data consistency
In this part, we will consider all operations required to implement data consistency. Recall that data consistency is an MR knowledge-inspired operation. The idea behind data consistency is to undo unnecessary corrections made by the reconstruction network.
First, let us load the data that we generated in the previous demo.
```
# Load data from the previous demo
recon = np.load('out/recon_4.npy')
target = np.load('out/target.npy')
mask = np.load('out/mask.npy')
zero_filled = np.load('out/zero_filled_4.npy')
kspace = np.load('out/kspace.npy')
```
Visualize loaded data.
```
plt.figure(figsize=(24, 18))
plt.subplot(1, 4, 1)
ones = np.ones((mask.shape[0], mask.shape[0]))
mask_to_show = mask * ones
plt.imshow(mask_to_show, cmap='gray')
plt.title('Sampling mask R=4', fontsize=17)
plt.subplot(1, 4, 2)
plt.imshow(zero_filled[0], cmap='gray')
plt.title('Zero-filled image R=4', fontsize=17)
plt.subplot(1, 4, 3)
plt.imshow(recon, cmap='gray')
plt.title('U-Net recon R=4', fontsize=17)
plt.subplot(1, 4, 4)
plt.imshow(target, cmap='gray')
plt.title('Target', fontsize=17)
plt.show()
```
As in the first demo, we define some utility functions that will be used later. Some of them are taken from the first demo and should already be familiar to you.
```
def to_two_channel_complex(data: torch.Tensor) -> torch.Tensor:
""" Change data representation from one channel complex-valued to two channers real valued """
real = data.real
imag = data.imag
result = torch.empty((*data.shape, 2), dtype=torch.float32)
result[..., 0] = real
result[..., 1] = imag
return result
def complex_abs(data: torch.Tensor, keepdim: bool = False) -> torch.Tensor:
""" Convert complex image to a magnitude image (projection from complex to a real plane) """
assert data.size(-1) == 2
return (data ** 2).sum(dim=-1, keepdim=keepdim).sqrt()
def image_to_kspace(image: torch.Tensor) -> torch.Tensor:
""" Convert image to the corresponding k-space using Fourier transforms """
image_shifted = torch.fft.fftshift(image)
kspace_shifted = torch.fft.fft2(image_shifted)
kspace = torch.fft.ifftshift(kspace_shifted)
return kspace
def single_coil_kspace_to_image(kspace: torch.Tensor) -> torch.Tensor:
""" Convert k-space to the corresponding image using Fourier transforms """
kspace_shifted = torch.fft.ifftshift(kspace)
image_shifted = torch.fft.ifft2(kspace_shifted)
image = torch.fft.fftshift(image_shifted).real
return image
```
Now, let us implement all steps of the data consistency operation:
### Step 1: compute reverted sampling mask
```
reverted_mask_to_show = (mask_to_show - 1) * -1
plt.imshow(reverted_mask_to_show, cmap='gray')
plt.show()
```
### Step 2: prepare recon k-space
Note that the output of the U-Net reconstruction model contains vertical lines, which are leftovers from the initial undersampling. These lines indicate imperfections of obtained reconstruction.
```
# As before we:
# 1) go to k-space using Fourier transforms
# 2) convent complex-valued matrix into two channel real-valued tensor
# 3) convert complex to magnitude
recon_kspace = complex_abs(to_two_channel_complex(image_to_kspace(torch.from_numpy(recon))))
plt.imshow(torch.log(recon_kspace), cmap='gray')
plt.title('Recon k-space R=4', fontsize=15)
plt.show()
```
### Step 3: compute the unnecessary correction in k-space
Get this by pixel-wise multiplication with the reverted mask.
```
offset = 48
recon_kspace_consistent = reverted_mask_to_show * recon_kspace.numpy()
plt.imshow(np.log(recon_kspace_consistent + 1e-8), cmap='gray')
plt.show()
```
Now we can apply the resulting data consistency term in two different ways:
1. Subtract it from the recon k-space to explicitly remove corrections
2. Provide the data consistency as an additional input to the next reconstruction block to help the model compensate for it (soft data consistency)
| github_jupyter |
Labeled Revision Mock
===
Mocking labeled revisions so that rev-scoring can be applied.
See also: CrossTimeSampling2.ipynb
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import mwapi
import mwxml
import mwxml.utilities
import mwcli
import mwreverts
import oresapi
import mwparserfromhell
import os
import requests
from tqdm import tqdm
import bz2
import gzip
import json
import re
import hashlib
from datetime import datetime
import nltk
import scipy.stats
import para
from itertools import groupby
from collections import Counter
import time
git_root_dir = !git rev-parse --show-toplevel
git_root_dir = git_root_dir[0]
git_root_dir
labeled_revisions_filepath = os.path.join(git_root_dir, "data/raw/editquality/datasets/enwiki.labeled_revisions.20k_2015.json")
assert os.path.exists(labeled_revisions_filepath)
!head -n 3 {labeled_revisions_filepath}
revisions_features_filepath = os.path.join(git_root_dir, "data/raw/editquality/datasets/enwiki.labeled_revisions.20k_2015.damaging.tsv")
assert os.path.exists(labeled_revisions_filepath)
training_data_rev_ids = []
with open(labeled_revisions_filepath, 'r') as infile:
for line in infile:
rev = json.loads(line)
rev_id = rev['rev_id']
training_data_rev_ids.append(rev_id)
len(training_data_rev_ids)
# labeled_revisions.20k_2015 text retrieval
# This approach uses mwapi, but it seems not to work for some reason
assert False
session = mwapi.Session("https://en.wikipedia.org/w/api.php",
timeout=5.0,
user_agent="LabeledRevisionMock/0.0 (github.com/levon003/wiki-ores-feedback; levon003@umn.edu) mwapi/0.5.1")
splits = np.array_split(training_data_rev_ids, int(len(training_data_rev_ids) / 50) + 1)
results = []
for rev_id_list in tqdm(splits):
assert len(rev_id_list) <= 50
params = {
'action': 'query',
'format': 'json',
'formatversion': '2',
'revids': "|".join([str(rev_id) for rev_id in rev_id_list]),
'prop': 'revisions',
'rvprop': 'ids|timestamp|user|comment|content|tags',
'rvslots': 'main',
# 'maxlag': 5
}
awaiting_result = True
while awaiting_result:
try:
result = session.get(params)
except requests.exceptions.Timeout as timeout_ex:
print(timeout_ex)
print("Timeout waiting for response. Waiting and trying again...")
time.sleep(5)
except mwapi.errors.APIError as ex:
print(ex)
print("Maxlag at:", datetime.now())
# https://www.mediawiki.org/wiki/Manual:Maxlag_parameter
print("Server response exceeded maxlag time; waiting before retry.")
time.sleep(5)
results.append(result)
time.sleep(0.01)
# labeled_revisions.20k_2015 text retrieval
headers = {
'User-Agent': 'LabeledRevisionMock/0.0 (github.com/levon003/wiki-ores-feedback; levon003@umn.edu) requests/2.22.0',
'From': 'levon003@umn.edu'
}
splits = np.array_split(training_data_rev_ids, int(len(training_data_rev_ids) / 50) + 1)
results = []
for rev_id_list in tqdm(splits):
assert len(rev_id_list) <= 50
params = {
'action': 'query',
'format': 'json',
'formatversion': '2',
'revids': "|".join([str(rev_id) for rev_id in rev_id_list]),
'prop': 'revisions',
'rvprop': 'ids|timestamp|user|comment|content|tags',
'rvslots': 'main',
'maxlag': 5
}
awaiting_result = True
while awaiting_result:
response = requests.get("https://en.wikipedia.org/w/api.php", params=params, headers=headers)
if response.ok:
result = response.json()
if 'error' in result:
print(result['error'])
print("Maxlag at:", datetime.now())
# https://www.mediawiki.org/wiki/Manual:Maxlag_parameter
else:
results.append(result)
break
else:
print("Error:", response)
print("Server response error; waiting before retry.")
time.sleep(5)
time.sleep(0.01) # this is completely unnecessary I think; sequential requests without waiting is fine
# all batches complete?
assert np.all([result['batchcomplete'] for result in results])
results = [result['query'] for result in results]
len(results)
# Save the retrieved data
working_dir = os.path.join(git_root_dir, "data/derived/labeled-revs")
os.makedirs(working_dir, exist_ok=True)
output_filepath = os.path.join(working_dir, 'labeled_revisions.20k_2015.content.ndjson')
with open(output_filepath, 'w') as outfile:
for result in results:
outfile.write(json.dumps(result) + "\n")
print("Finished.")
# Load in the labeled revisions content data
labeled_revs_dir = os.path.join(git_root_dir, "data/derived/labeled-revs")
labeled_revs_filepath = os.path.join(labeled_revs_dir, 'labeled_revisions.20k_2015.content.ndjson')
results = []
with open(labeled_revs_filepath, 'r') as infile:
for line in infile:
result = json.loads(line)
results.append(result)
len(results)
results[0].keys()
# 520 total "bad" rev_ids, with bad revisions appearing in 73% of query batches
len(results[0]['badrevids'].keys())
badrevids_count_list = []
badrevids_total = 0
for result in results:
if 'badrevids' in result:
badrevids_count = len(result['badrevids'].keys())
badrevids_total += badrevids_count
badrevids_count_list.append(badrevids_count)
else:
badrevids_count_list.append(0)
badrevids_count_list = np.array(badrevids_count_list)
badrevids_total, np.sum(badrevids_count_list > 0) / len(results)
revision_timestamps = []
for result in results:
for page in result['pages']:
for rev in page['revisions']:
page_id = page['pageid']
rev_id = rev['revid']
rev_timestamp_str = rev['timestamp']
rev_timestamp = int(datetime.strptime(rev_timestamp_str, "%Y-%m-%dT%H:%M:%SZ").timestamp())
revision_timestamps.append(rev_timestamp)
revision_timestamps = np.array(revision_timestamps)
plt.hist(revision_timestamps, bins=100)
xticks, _ = plt.xticks()
plt.xticks(xticks,
[datetime.utcfromtimestamp(xtick).strftime("%Y-%m-%d") for xtick in xticks],
rotation='vertical')
plt.show()
days = [int(datetime.utcfromtimestamp(rt).strftime("%Y%m%d")) for rt in revision_timestamps]
mc = Counter(days).most_common()
for day, count in sorted(mc, key=lambda tup: tup[0])[:10]:
print(f"{day} ({count}) " + "="*count)
print("<snip>")
for day, count in sorted(mc, key=lambda tup: tup[0])[-10:]:
print(f"{day} ({count}) " + "="*count)
mc[:10]
features_df = pd.read_csv(revisions_features_filepath, sep='\t', header=0)
len(features_df)
rev_list = []
revisions_with_cache_filepath = os.path.join(git_root_dir, "data/raw/editquality/datasets/enwiki.labeled_revisions.w_cache.20k_2015.json")
with open(revisions_with_cache_filepath, 'r') as infile:
for line in infile:
rev = json.loads(line)
rev_list.append({
'rev_id': rev['rev_id'],
'damaging': rev['damaging'],
'goodfaith': rev['goodfaith']
})
df = pd.DataFrame(rev_list)
len(df)
df.head()
df = pd.concat([df, features_df], axis=1)
df.head()
rev_ids_with_content = set()
for result in results:
for page in result['pages']:
for rev in page['revisions']:
rev_id = rev['revid']
rev_ids_with_content.add(rev_id)
df['has_content'] = df.rev_id.map(lambda rev_id: rev_id in rev_ids_with_content)
len(rev_ids_with_content)
f"{np.sum(df.has_content)} / {len(df)} ({np.sum(df.has_content) / len(df)*100:.2f}%) training revisions have associated content."
```
### Construct rev_id sample
```
raw_data_dir = "/export/scratch2/wiki_data"
derived_data_dir = os.path.join(git_root_dir, "data", "derived")
# read in the sample dataframe
revision_sample_dir = os.path.join(derived_data_dir, 'revision_sample')
sample2_filepath = os.path.join(revision_sample_dir, 'sample2_1M.pkl')
rev_df = pd.read_pickle(sample2_filepath)
len(rev_df)
rev_df.head()
mock_template = '{"rev_id": %d, "auto_labeled": false, "damaging": false, "goodfaith": true, "autolabel": {}}'
working_dir = os.path.join(git_root_dir, "data/derived/labeled-revs")
mock_rev_filepath = os.path.join(working_dir, "sample2.mock.json")
with open(mock_rev_filepath, 'w') as outfile:
for rev_id in rev_df.rev_id:
line = mock_template % rev_id
outfile.write(line + "\n")
print("Finished.")
!head -n 3 {mock_rev_filepath}
mock_rev_filepath
```
From the `revscoring` repo, using the `wiki-revscoring` conda environment, I ran:
```
cat /export/scratch2/levon003/repos/wiki-ores-feedback/data/derived/labeled-revs/sample2.mock.json | revscoring extract editquality.feature_lists.enwiki.damaging editquality.feature_lists.enwiki.goodfaith --host https://en.wikipedia.org --extractors 32 --verbose > /export/scratch2/levon003/repos/wiki-ores-feedback/data/derived/labeled-revs/sample2.mock.w_cache.json
revscoring dump_cache --input /export/scratch2/levon003/repos/wiki-ores-feedback/data/derived/labeled-revs/sample2.mock.w_cache.json --output /export/scratch2/levon003/repos/wiki-ores-feedback/data/derived/labeled-revs/sample2.mock.damaging.tsv --verbose editquality.feature_lists.enwiki.damaging damaging
```
```
# copied from bash commands above
mock_features_filepath = "/export/scratch2/levon003/repos/wiki-ores-feedback/data/derived/labeled-revs/sample1.mock.damaging.tsv"
mock_features_df = pd.read_csv(mock_features_filepath, sep='\t', header=0)
len(mock_features_df)
features_df.shape
```
| github_jupyter |
```
import os
os.chdir('..')
```
# Packages
```
import datetime
data_datetime = datetime.datetime(2020, 5, 28)
from nlp import preprocessing
import pandas as pd
import numpy as np
import copy
import matplotlib.pyplot as plt
import time
from sklearn.decomposition import TruncatedSVD # SVD for sparse matrices
from sklearn.preprocessing import normalize # normalization for sparse matrices
```
# Functions
```
dpi = 300
```
# Read in Small Data (metadata)
```
x = pd.read_csv('big_data/metadata_20-05-28.csv')
print(len(x))
del x
metadata = pd.read_csv('big_data/metadata_20-05-28.csv')
print(len(metadata))
metadata = metadata[pd.isnull(metadata['abstract']) == False].reset_index(drop=True)
print(len(metadata))
```
Using the search query to focus on abstracts:
**"COVID-19"** OR Coronavirus OR "Corona virus" OR **"2019-nCoV"** OR "SARS-CoV" OR "MERS-CoV" OR “Severe Acute Respiratory Syndrome” OR “Middle East Respiratory Syndrome”
```
metadata = metadata[metadata['abstract'].str.lower().str.contains(
"covid-19|coronavirus|coronavirus|corona virus|2019-ncov|sars-cov|mers-cov|severe acute respiratory syndrome|middle east respiratory syndrome|sars-cov-2") |
metadata['abstract'].str.contains("MERS")
]
print(len(metadata))
count = sum(metadata['abstract'].str.contains('COVID|2019-nCoV|SARS-CoV-2'))
print('There are ' + str(count) + ' articles mentioning COVID.')
covid_article_indexes = np.argwhere(np.array(metadata['abstract'].str.contains('COVID|2019-nCoV|SARS-CoV-2'))).T[0]
mers_article_indexes = np.argwhere(np.array(metadata['abstract'].str.contains('MER|middle east| Middle East'))).T[0]
sars_article_indexes = np.argwhere(np.array(metadata['abstract'].str.contains('SARS'))).T[0]
```
# Traditional ML
## Preprocessing
Preprocess text
```
t = time.time()
preprocessor = preprocessing.Preprocessor(metadata['abstract'])
preprocessor.preprocess(lemmatize=True, stopwords=['abstract'], min_token_length=3)
print(time.time() - t)
```
Preprocess for bigrams
```
preprocessor.get_bigrams_from_preprocessed()
```
Create key NLP objects for word counts
```
preprocessor.create_nlp_items_from_preprocessed_df(no_below=2, verbose=True)
dictionary, bow_corpus, tfidf, corpus_tfidf, tfidf_sparse = (preprocessor.dictionary_,
preprocessor.bow_corpus_,
preprocessor.tfidf_,
preprocessor.corpus_tfidf_,
preprocessor.tfidf_sparse_)
```
## PCA
## Implementation
```
# tfidf_sparse_norm = normalize(tfidf_sparse, norm='l1', axis=1)
truncatedsvd = TruncatedSVD(n_components = 30, algorithm = 'randomized', random_state = 20)
# pca = PCA(n_components = 100, svd_solver = 'randomized', random_state = 20)
# transformed = truncatedsvd.fit_transform(tfidf_sparse_norm)
transformed = truncatedsvd.fit_transform(tfidf_sparse)
plt.title('Explained Variance Ratio')
plt.plot(np.cumsum(truncatedsvd.explained_variance_ratio_)[0:30])
plt.ylim(0, 1.01)
print(truncatedsvd.explained_variance_ratio_)
xscale_log_addition = 0.1
c_0, c_1 = 1, 2
#===== Set boundaries to remove outliers
f = 0.01 # dimension factor
p = 0.5 #percentile
width = np.percentile(transformed[:,c_0], 100 - p) - np.percentile(transformed[:,c_0], p)
height = np.percentile(transformed[:,c_1], 100 - p) - np.percentile(transformed[:,c_1], p)
left, right = np.percentile(transformed[:,c_0], p) - f * width, np.percentile(transformed[:,c_0], 100 - p) + f * width
low, high = np.percentile(transformed[:,c_1], p) - f * height, np.percentile(transformed[:,c_1], 100 - p) + f * height
#=====
fig, ax = plt.subplots()
not_covid = (np.isin(np.array(list(range(len(transformed)))), covid_article_indexes) == False)
plt.scatter(transformed[not_covid,c_0],
transformed[not_covid,c_1], alpha=0.1, label='non-COVID-19 Literature')
plt.scatter(transformed[covid_article_indexes,c_0],
transformed[covid_article_indexes,c_1], alpha=0.05, label='COVID-19 Literature')
# plt.xlim(left, right); plt.ylim(low, high)
# plt.title('COVID-19 and Non-COVID-19 Literature', size=18)
plt.xlabel('Principal Component ' + str(c_0 + 1), size=14)
plt.ylabel('Principal Component ' + str(c_1 + 1), size=14)
plt.xticks([]); plt.yticks([])
leg=plt.legend(loc='upper right')
for lh in leg.legendHandles:
lh.set_alpha(1)
plt.text(0.05, 0.95, 'A', transform=ax.transAxes, fontsize=16, fontweight='bold', va='top')
# fig.savefig('Paper/Figures/2a.png', dpi=dpi)
plt.show()
fig, ax = plt.subplots()
not_covid = (np.isin(np.array(list(range(len(transformed)))), covid_article_indexes) == False)
plt.scatter(transformed[not_covid,c_0],
transformed[not_covid,c_1], alpha=0.05, label='non-COVID-19 Literature')
# plt.title('Non-COVID-19 Literature', size=18)
plt.xlabel('Principal Component ' + str(c_0 + 1), size=14)
plt.ylabel('Principal Component ' + str(c_1 + 1), size=14)
plt.xticks([]); plt.yticks([])
# plt.xlim(left, right); plt.ylim(low, high)
# plt.legend()
plt.text(0.925, 0.95, 'B', transform=ax.transAxes, fontsize=16, fontweight='bold', va='top')
# fig.savefig('Paper/Figures/2b.png', dpi=dpi)
plt.show()
fig, ax = plt.subplots()
plt.scatter(transformed[sars_article_indexes,c_0],
transformed[sars_article_indexes,c_1], alpha=0.05, label='SARS-CoV', zorder=1)
plt.scatter(transformed[mers_article_indexes,c_0],
transformed[mers_article_indexes,c_1], alpha=0.05, label='MERS-CoV', c='C2', zorder=2)
plt.scatter(transformed[covid_article_indexes,c_0],
transformed[covid_article_indexes,c_1], alpha=0.05, label='SARS-CoV-2', c='C1', zorder=3)
# plt.title('Literature of Various Diseases', size=18)
plt.xlabel('Principal Component ' + str(c_0 + 1), size=14)
plt.ylabel('Principal Component ' + str(c_1 + 1), size=14)
plt.xticks([]); plt.yticks([])
leg=plt.legend()
for lh in leg.legendHandles:
lh.set_alpha(1)
# plt.xlim(left, right); plt.ylim(low, high)
# fig.savefig('Paper/Figures/3.png', dpi=dpi)
plt.show()
```
Identifying PCs that separate COVID/non-COVID literature
```
n_bins = 50
panel_set = [
[0.05, 0.95, 'A'],
[0.925, 0.95, 'B'],
[0.05, 0.1, 'C'],
[0.925, 0.1, 'D']
]
for c in range(10):
fig, ax = plt.subplots()
_, _, _ = plt.hist(transformed[np.setdiff1d(list(range(len(transformed))), covid_article_indexes), c]
, density=True, alpha=1., bins=50, label='Non-COVID-19 Articles')
_, _, _ = plt.hist(transformed[covid_article_indexes, c], density=True,
alpha=0.7, bins=50, label='COVID-19 Articles')
# plt.title('Distribution of Articles on Principal Component ' + str(c + 1), size=14)
plt.xticks([]); plt.yticks([])
plt.ylabel('Normalized Density', size=12)
plt.xlabel('Principal Component ' + str(c + 1) + ' Projection Value', size=12)
if c == 2:
ax.annotate("Mostly non-COVID-19 abstracts", xy=(0.32, 0.2), xytext=(0.105, 8), arrowprops=dict(arrowstyle="->"))
if c < 4: # label & save only first few figs
plt.text(panel_set[c][0], panel_set[c][1], panel_set[c][2],
transform=ax.transAxes, fontsize=16, fontweight='bold', va='top')
if c == 0:
plt.legend()
plt.savefig('Paper/Figures/1' + panel_set[c][2] + '.png', dpi=dpi)
plt.show()
c = 1
fig, ax = plt.subplots()
_, _, _ = plt.hist(transformed[sars_article_indexes, c]
, density=True, alpha=1., bins=50, label='SARS-CoV', color='black')
_, _, _ = plt.hist(transformed[covid_article_indexes, c], density=True,
alpha=0.7, bins=50, label='SARS-CoV-2', zorder=20, color='tab:orange')
_, _, _ = plt.hist(transformed[mers_article_indexes, c]
, density=True, alpha=.7, bins=50, label='MERS-CoV', color='tab:blue')
# plt.title('Distribution of Articles on Principal Component ' + str(c + 1), size=14)
plt.xticks([]); plt.yticks([])
plt.ylabel('Normalized Density', size=12)
plt.xlabel('Principal Component ' + str(c + 1) + ' Projection Value', size=12)
plt.legend()
plt.savefig('Paper/Figures/2.png', dpi=dpi)
plt.show()
```
## Analysis
```
def get_top_words_and_scores(svd, dictionary, c, n, visual=True):
word_ids_sorted = np.argsort(np.abs(svd.components_[c]))[::-1]
top_words_and_scores = [[dictionary[word_ids_sorted[i]], svd.components_[c, word_ids_sorted[i]]] for i in range(n)]
top_words_and_scores = pd.DataFrame(
top_words_and_scores,columns=['word', 'component_score']).sort_values('component_score')
if visual:
%matplotlib inline
%matplotlib inline
fig, ax = plt.subplots(figsize=(18,6.5))
plt.bar(height=top_words_and_scores['component_score'], x=top_words_and_scores['word'])
plt.xticks(rotation=90, size=14)
plt.xlabel("Lemmatized Term", size=16)
plt.ylabel("Component " + str(c + 1) + ' Value', size=16)
# plt.title("Top " + str(n) + " Words' Values of Principal Component " + str(c+1), size=20)
plt.gcf().subplots_adjust(bottom=0.375) # without this, xlabel is cut off when fig is saved
return top_words_and_scores, fig, ax
else:
return top_words_and_scores
panel_lst = ['a', 'b']; panel_cnt = 0
panel_set = [
[0.025, 0.95, 'A'],
[0.025, 0.95, 'B']
]
for i in range(10):
top_words_and_scores, fig, ax = get_top_words_and_scores(truncatedsvd, dictionary, i, 50, visual=True)
if i in [c_0, c_1]:
# plt.text(panel_set[panel_cnt][0], panel_set[panel_cnt][1], panel_set[panel_cnt][2],
# transform=ax.transAxes, fontsize=28, fontweight='bold', va='top')
# fig.savefig('Paper/Figures/4' + panel_lst[panel_cnt] + '.png', dpi=dpi)
plt.title('Top 50 Words Component Values on PC' + str(i + 1), size=20)
fig.savefig('Paper/Figures/3' + '.png', dpi=dpi)
panel_cnt += 1
break
plt.show()
c_a, c_b = c_0, c_1
metadata['component_a'] = transformed[:,c_0] * 10**6
metadata['component_b'] = transformed[:,c_1] * 10**6
metadata['component_a_percentile'] = metadata['component_a'].rank(pct=True)
metadata['component_b_percentile'] = metadata['component_b'].rank(pct=True)
metadata['abstract_COVID'] = metadata['abstract'].str.contains('COVID')
```
Word analysis
```
covid_or_not = False
word = 'spike protein'
total = sum(metadata['abstract_COVID'] == covid_or_not)
total_subset = sum((metadata['abstract_COVID'] == covid_or_not) & (metadata['abstract'].str.lower().str.contains(word)))
print(total_subset / total)
```
Automated word analysis including bigrams
```
c = c_0
total_covid = sum(metadata['abstract_COVID'] == True)
total_not_covid = sum(metadata['abstract_COVID'] == False)
word_analysis_df = copy.deepcopy(metadata[['abstract_COVID']])
word_list = get_top_words_and_scores(truncatedsvd, dictionary, c, 50, visual=False)
covid_pcts = []; not_covid_pcts = []
for word in word_list['word']:
word_analysis_df['contains_word'] = [word in doc for doc in preprocessor.preprocessed_text_]
total_subset = sum((word_analysis_df['abstract_COVID']) & (word_analysis_df['contains_word'] ))
covid_pcts.append(round(total_subset / total_covid * 100, 1))
total_subset = sum((word_analysis_df['abstract_COVID'] == False) & (word_analysis_df['contains_word'] ))
not_covid_pcts.append(round(total_subset / total_not_covid * 100, 1))
word_analysis = pd.DataFrame(np.array([word_list['word'], word_list['component_score'], covid_pcts, not_covid_pcts]).T,
columns = ['word', 'component_' + str(c + 1) + '_score','covid_pcts', 'not_covid_pcts'])
word_analysis
word_analysis.to_csv('big_data/top-word-analysis-pc2.csv', index=False)
panel = 'A'
fig, ax = plt.subplots(figsize=(18,6.5))
plt.bar(np.arange(len(word_analysis['word'])) + 0.4,
word_analysis['not_covid_pcts'],
label='non-COVID-19 Abstracts', width=0.4)
plt.bar(np.arange(len(word_analysis['word'])),
word_analysis['covid_pcts'],
label='COVID-19 Abstracts', width=0.4)
plt.xticks(np.arange(len(word_analysis['word'])), word_analysis['word'], rotation=90, size=14)
plt.xlabel('Lemmatized Key Term Sorted by PC' + str(c + 1) + ' Component Value', size=16)
plt.ylabel('% of Abstracts Mentioning Word', size=16)
plt.title('Frequency of Key Terms (PC' + str(c + 1) + ') Across Abstracts', size=20)
plt.legend(fontsize=14, loc='upper right')
plt.gcf().subplots_adjust(bottom=0.375)
# plt.text(0.0125, 0.95, panel, transform=ax.transAxes, fontsize=28, fontweight='bold', va='top')
fig.savefig('Paper/Figures/4.png', dpi=dpi)
# fig.savefig('Paper/Figures/5' + '.png', dpi=dpi)
plt.show()
```
Analysis of abstracts over time
```
metadata_dt_analysis = copy.deepcopy(metadata)
metadata_dt_analysis['converted_datetime'] = pd.to_datetime(metadata_dt_analysis['publish_time'], errors='coerce') # if format fails to parse, return NaT
metadata_dt_analysis = metadata_dt_analysis.sort_values('converted_datetime')
metadata_dt_analysis = metadata_dt_analysis[pd.isnull(metadata_dt_analysis['converted_datetime']) == False] # drop abstracts w/ null
metadata_dt_analysis = metadata_dt_analysis[metadata_dt_analysis['converted_datetime'] <= data_datetime] # drop those with impossible datetimes
# Key problems:
# 2020 date times (~250 articles)
# A couple of articles with no date time
# A couple of articles with impossible date times
covid_abstracts = metadata_dt_analysis[metadata_dt_analysis['abstract_COVID']]
covid_abstracts = covid_abstracts[covid_abstracts['converted_datetime'] >
datetime.datetime(2020, 1, 1)] # drop those with only '2020' as datetime
c = 1
c_all = [c_0, c_1]; c_index = np.argwhere(c == np.array(c_all)).T[0][0]
panel_key = ['a', 'b']
panel = panel_key[c_index]
fig, ax = plt.subplots(figsize=(7, 7))
covid_normalizer_df = metadata_dt_analysis[metadata_dt_analysis['abstract_COVID']] # use this to normalize cumsums for abstracts with just 2020 as date
for lower in np.array(list(range(5))) / 10 * 2:
upper = lower + 0.2
boolean = np.logical_and(covid_abstracts['component_' + panel + '_percentile'] >= lower,
covid_abstracts['component_' + panel + '_percentile'] <= upper)
normalize_boolean = np.logical_and(covid_normalizer_df['component_' + panel + '_percentile'] >= lower,
covid_normalizer_df['component_' + panel + '_percentile'] <= upper)
norm_factor = np.sum(normalize_boolean) / np.sum(boolean)
plt.plot(covid_abstracts[boolean]['converted_datetime'],
np.cumsum(np.repeat(1, len(covid_abstracts[boolean]))) * norm_factor,
label=str(int(lower*100)) + 'th-' + str(int(upper*100)) + 'th percentile'
)
plt.xticks(rotation=45)
plt.xlabel('Date', size=14)
plt.ylabel('Count of Abstracts', size=14)
# plt.title('Release of COVID-19 Abstracts Over Time (PC3)', size=18)
# plt.yscale('log')
legend = ax.legend(title='PC' + str(c + 1) + ' Projection Value')
plt.setp(legend.get_title(),fontsize='x-large')
plt.text(0.025, 0.70, panel.upper(), transform=ax.transAxes, fontsize=28, fontweight='bold', va='top')
plt.gcf().subplots_adjust(bottom=0.15)
fig.savefig('Paper/Figures/6' + panel + '.png', dpi=dpi)
# fig.savefig('Paper/Figures/7' + '.png', dpi=dpi)
plt.show()
```
Tracking rxiv articles over time (not peer reviewed stuff)
```
plt.figure(figsize=(7, 7))
boolean = covid_abstracts['source_x'].isin(['biorxiv', 'medrxiv'])
plt.plot(covid_abstracts[boolean]['converted_datetime'],
np.cumsum(np.repeat(1, len(covid_abstracts[boolean]))), label='rxiv Articles'
)
boolean = boolean == False
plt.plot(covid_abstracts[boolean]['converted_datetime'],
np.cumsum(np.repeat(1, len(covid_abstracts[boolean]))), label='Other Articles'
)
plt.xticks(rotation=45)
plt.yscale('log')
plt.legend()
plt.title('COVID Articles')
plt.figure(figsize=(7, 7))
non_covid_abstracts = metadata_dt_analysis[metadata_dt_analysis['abstract_COVID'] == False]
boolean = non_covid_abstracts['source_x'].isin(['biorxiv', 'medrxiv'])
plt.plot(non_covid_abstracts[boolean]['converted_datetime'],
np.cumsum(np.repeat(1, len(non_covid_abstracts[boolean]))), label='rxiv Articles'
)
boolean = boolean == False
plt.plot(non_covid_abstracts[boolean]['converted_datetime'],
np.cumsum(np.repeat(1, len(non_covid_abstracts[boolean]))), label='Other Articles'
)
plt.xticks(rotation=45)
plt.yscale('log')
plt.legend()
plt.title('Non-COVID Articles')
```
# Write to file
```
metadata.columns
metadata_small = metadata[[
'title', 'doi', 'pmcid', 'pubmed_id', 'abstract', 'publish_time', 'journal',
'component_a', 'component_b', 'component_a_percentile', 'component_b_percentile', 'abstract_COVID'
]]
metadata_small.to_csv('big_data/metadata_PCAed_subsetted', sep='|', index=False)
metadata_small
```
| github_jupyter |
<a href="https://colab.research.google.com/github/bibekuchiha/Data-Cleaning-with-Pandas/blob/master/Cleaning%20US%20Census%20Data/%20Cleaning_US_Census_Data.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
#Cleaning US Census Data
```
#Importing datasets
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import glob
```
Using glob, loop through the census files available and load them into DataFrames. Then, concatenate all of those DataFrames together into one DataFrame
```
us_census = glob.glob('states*.csv')
df_list = []
for filename in us_census:
data = pd.read_csv(filename)
df_list.append(data)
df = pd.concat(df_list)
df.head()
#checking the columns in dataset
print(df.columns)
```
Use regex to turn the Income column into a format that is ready for conversion into a numerical type.
```
df['Income'] = df.Income.replace('[/$]', '', regex=True)
df.head()
#converting the income column into numeric value
df.Income = pd.to_numeric(df.Income)
print(df.dtypes)
```
Look at the GenderPop column. We are going to want to separate this into two columns, the Men column, and the Women column.
```
gender_split = df.GenderPop.str.split('_')
df['Men'] = gender_split.str.get(0)
df['Women'] = gender_split.str.get(1)
```
There is still an M or an F character in each entry! We should remove those before we convert.
```
df['Men'] = df.Men.str[:-1]
df['Women'] = df.Women.str[:-1]
df.Men = pd.to_numeric(df.Men)
df.Women = pd.to_numeric(df.Women)
df.head()
#checking duplicates in state column
duplicates = df.duplicated(subset=['State'])
print(duplicates.value_counts())
#Drop those duplicates
df = df.drop_duplicates()
plt.scatter(df.Women, df.Income)
plt.xlabel('Women')
plt.ylabel('Income')
plt.show()
print(df.columns)
#removing % sign and converting columns into numeric value
df['Hispanic'] = df.Hispanic.str[:-1]
df['Hispanic'] = pd.to_numeric(df.Hispanic)
df['White'] = df.White.str[:-1]
df['White'] = pd.to_numeric(df.White)
df['Black'] = df.Black.str[:-1]
df['Black'] = pd.to_numeric(df.Black)
df['Native'] = df.Native.str[:-1]
df['Native'] = pd.to_numeric(df.Native)
df['Asian'] = df.Asian.str[:-1]
df['Asian'] = pd.to_numeric(df.Asian)
df['Pacific'] = df.Pacific.str[:-1]
df['Pacific'] = pd.to_numeric(df.Pacific)
df = df.fillna(value={
'Hispanic': df.Hispanic.mean(),
'White': df.White.mean(),
'Black': df.Black.mean(),
'Native': df.Native.mean(),
'Asian': df.Asian.mean(),
'Pacific': df.Pacific.mean(),
})
plt.hist(df['Hispanic'])
plt.title('Hispanic')
plt.show()
plt.hist(df['White'])
plt.title('White')
plt.show()
plt.cla()
plt.hist(df['Black'])
plt.title('Black')
plt.show()
plt.cla()
plt.hist(df['Native'])
plt.title('Native')
plt.show()
plt.cla()
plt.hist(df['Pacific'])
plt.title('Pacific')
plt.show()
plt.cla()
plt.hist(df['Asian'])
plt.title('Asian')
plt.show()
print(df.head())
print(df.dtypes)
```
| github_jupyter |
# ProjectQ Mapper Tutorial
The aim of this short tutorial is to give an introduction to the ProjectQ mappers.
ProjectQ allows a user to write a quantum program in a high-level language. For example, one can apply quantum operations on n-qubits, e.g., `QFT`, and the compiler will decompose this operations into two-qubit and single-qubit gates. See the [compiler_tutorial](https://github.com/ProjectQ-Framework/ProjectQ/tree/develop/examples) for an introduction.
After decomposing a quantum program into two-qubit and single-qubit gates which a quantum computer supports, we have to take the physical layout of these qubits into account. Two-qubit gates are only possible if the qubits are next to each other. For example the qubits could be arranged in a linear chain or a two-dimensional grid and only nearest neighbour qubits can perform a two-qubit gate. ProjectQ uses **mappers** which move the positions of the qubits close to each other using `Swap` operations in order that we can execute a two-qubit gate.
The implementation and some results of ProjectQ's mappers are discussed in [our paper (section 3C)](https://arxiv.org/abs/1806.01861)
## Example: Mapping to a linear chain
Let's look at an example of a quantum fourier transform (`QFT`) compiled into single-qubit gates and `CNOT`s. First, we look at the resources required if the qubits have an *all-to-all* connectivity, i.e., any pairs of qubits can execute a `CNOT`:
```
import projectq
from projectq.backends import ResourceCounter
from projectq.ops import CNOT, QFT
from projectq.setups import restrictedgateset
engine_list = restrictedgateset.get_engine_list(one_qubit_gates="any",
two_qubit_gates=(CNOT,))
resource_counter = ResourceCounter()
eng = projectq.MainEngine(backend=resource_counter, engine_list=engine_list)
qureg = eng.allocate_qureg(15)
QFT | qureg
eng.flush()
print(resource_counter)
```
Now let's assume our qubits are arrange on a linear chain, we can use an already [predefined compiler setup](http://projectq.readthedocs.io/en/latest/projectq.setups.html#module-projectq.setups.linear) to compile to this architecture:
```
from projectq.setups import linear
engine_list2 = linear.get_engine_list(num_qubits=15, cyclic=False,
one_qubit_gates="any",
two_qubit_gates=(CNOT,))
resource_counter2 = ResourceCounter()
eng2 = projectq.MainEngine(backend=resource_counter2, engine_list=engine_list2)
qureg2 = eng2.allocate_qureg(15)
QFT | qureg2
eng2.flush()
print(resource_counter2)
```
One can see that once we restricted the hardware to a linear chain, the same program requires a lot more `CNOT` (also called `CX`) gates. This is due to additionals `Swap` operations to move the qubits around (a `Swap` gate can be constructed out of three `CX` gates).
## Example: Mapping to a two-dimensional grid
ProjectQ also has a [predefined setup](http://projectq.readthedocs.io/en/latest/projectq.setups.html#module-projectq.setups.grid) to map to a two-dimensional grid.
```
from projectq.setups import grid
engine_list3 = grid.get_engine_list(num_rows=3, num_columns=5,
one_qubit_gates="any",
two_qubit_gates=(CNOT,))
resource_counter3 = ResourceCounter()
eng3 = projectq.MainEngine(backend=resource_counter3, engine_list=engine_list3)
qureg3 = eng3.allocate_qureg(15)
QFT | qureg3
eng3.flush()
print(resource_counter3)
```
We can see that mapping a `QFT` to a two-dimensional grid layout requires fewer `CX` gates than mapping to a linear chain as expected.
## Inspecting the current mapping of logical qubits to physical qubits
A qubit which you obtain by calling the `allocate_qubit()` function of the compiler (`MainEngine`) is just an abstract objects which has a unique ID.
```
from projectq.backends import CommandPrinter
from projectq.ops import X, Swap
engine_list4 = linear.get_engine_list(num_qubits=3, cyclic=False,
one_qubit_gates="any",
two_qubit_gates=(CNOT, Swap))
eng4 = projectq.MainEngine(backend=CommandPrinter(), engine_list=engine_list4)
# For instructional purposes we change that the eng4 gives logical ids starting
# from 10. This could e.g. be the case if a previous part of the program
# already allocated 10 qubits
eng4._qubit_idx = 10
qubit0 = eng4.allocate_qubit()
qubit1 = eng4.allocate_qubit()
qubit2 = eng4.allocate_qubit()
X | qubit0
# Remember that allocate_qubit returns a quantum register (Qureg) of size 1,
# so accessing the qubit requires qubit[0]
print("This logical qubit0 has the unique ID: {}".format(qubit0[0].id))
print("This logical qubit1 has the unique ID: {}".format(qubit1[0].id))
print("This logical qubit2 has the unique ID: {}".format(qubit2[0].id))
eng4.flush()
```
As we can see `qubit0` has a logical ID equal to 10. The *LinearMapper* in this compiler setup then places these qubits on a linear chain with the following physical qubit ID ordering:
0 -- 1 -- 2
where -- indicates that these two qubits can perform a `CNOT` gate. If you are interested in knowing where a specific logical qubit is currently placed, you can access this information via the `current_mapping` property of the mapper:
```
# eng.mapper gives back the mapper in the engine_list
current_mapping = eng4.mapper.current_mapping
# current_mapping is a dictionary with keys being the
# logical qubit ids and the values being the physical ids on
# on the linear chain
print("Physical location of qubit0: {}".format(current_mapping[qubit0[0].id]))
print("Physical location of qubit1: {}".format(current_mapping[qubit1[0].id]))
print("Physical location of qubit2: {}".format(current_mapping[qubit2[0].id]))
```
Suppose we now perform a `CNOT` between `qubit0` and `qubit2`, then the mapper needs to swap these two qubits close to each other to perform the operation:
```
CNOT | (qubit0, qubit2)
eng4.flush()
# Get current mapping:
current_mapping = eng4.mapper.current_mapping
print("\nPhysical location of qubit0: {}".format(current_mapping[qubit0[0].id]))
print("Physical location of qubit1: {}".format(current_mapping[qubit1[0].id]))
print("Physical location of qubit2: {}".format(current_mapping[qubit2[0].id]))
```
We see that the compiler added a `Swap` gate to change the location of the logical qubits in this chain so that the CNOT can be performed.
## Measurements, probabilities, and amplitudes
While the compiler automatically remaps logical qubits to different physical locations, how does this affect the high-level programmer?
The short answer is not at all.
If you want to measure a logical qubit, just apply a measurement gate as before and the compiler will automatically find the correct physical qubit to measure:
```
from projectq.backends import Simulator
from projectq.ops import Measure
engine_list5 = linear.get_engine_list(num_qubits=3, cyclic=False,
one_qubit_gates="any",
two_qubit_gates=(CNOT, Swap))
eng5 = projectq.MainEngine(backend=Simulator(), engine_list=engine_list5)
qubit0 = eng5.allocate_qubit()
qubit1 = eng5.allocate_qubit()
qubit2 = eng5.allocate_qubit()
X | qubit0
Measure | qubit0
eng5.flush()
print("qubit0 was measured in state: {}".format(int(qubit0)))
```
All the simulator functionalities, e.g., `get_probability` or `get_amplitude` work as usual because they take logical qubits as arguments so the programmer does not need to worry about at which physical location `qubit0` is at the moment:
```
eng5.backend.get_probability('1', qubit0)
```
| github_jupyter |
# Exploring Data with Python
A significant part of a a data scientist's role is to explore, analyze, and visualize data. There's a wide range of tools and programming languages that they can use to do this; and of of the most popular approaches is to use Jupyter notebooks (like this one) and Python.
Python is a flexible programming language that is used in a wide range of scenarios; from web applications to device programming. It's extremely popular in the data science and machine learning community because of the many packages it supports for data analysis and visualization.
In this notebook, we'll explore some of these packages, and apply basic techniques to analyze data. This is not intended to be a comprehensive Python programming exercise; or even a deep dive into data analysis. Rather, it's intended as a crash course in some of the common ways in which data scientists can use Python to work with data.
> **Note**: If you've never used the Jupyter Notebooks environment before, there are a few things you should be aware of:
>
> - Notebooks are made up of *cells*. Some cells (like this one) contain *markdown* text, while others (like the one beneath this one) contain code.
> - The notebook is connected to a Python *kernel* (you can see which one at the top right of the page - if you're running this notebook in an Azure Machine Learning compute instance it should be connected to the **Python 3.6 - AzureML** kernel). If you stop the kernel or disconnect from the server (for example, by closing and reopening the notebook, or ending and resuming your session), the output from cells that have been run will still be displayed; but any variables or functions defined in those cells will have been lost - you must rerun the cells before running any subsequent cells that depend on them.
> - You can run each code cell by using the **► Run** button. The **◯** symbol next to the kernel name at the top right will briefly turn to **⚫** while the cell runs before turning back to **◯**.
> - The output from each code cell will be displayed immediately below the cell.
> - Even though the code cells can be run individually, some variables used in the code are global to the notebook. That means that you should run all of the code cells <u>**in order**</u>. There may be dependencies between code cells, so if you skip a cell, subsequent cells might not run correctly.
## Exploring data arrays with NumPy
Lets start by looking at some simple data.
Suppose a college takes a sample of student grades for a data science class.
Run the code in the cell below by clicking the **► Run** button to see the data.
```
data = [50,50,47,97,49,3,53,42,26,74,82,62,37,15,70,27,36,35,48,52,63,64]
print(data)
```
The data has been loaded into a Python **list** structure, which is a good data type for general data manipulation, but not optimized for numeric analysis. For that, we're going to use the **NumPy** package, which includes specific data types and functions for working with *Num*bers in *Py*thon.
Run the cell below to load the data into a NumPy **array**.
```
import numpy as np
grades = np.array(data)
print(grades)
```
Just in case you're wondering about the differences between a **list** and a NumPy **array**, let's compare how these data types behave when we use them in an expression that multiplies them by 2.
```
print (type(data),'x 2:', data * 2)
print('---')
print (type(grades),'x 2:', grades * 2)
```
Note that multiplying a list by 2 creates a new list of twice the length with the original sequence of list elements repeated. Multiplying a NumPy array on the other hand performs an element-wise calculation in which the array behaves like a *vector*, so we end up with an array of the same size in which each element has been multiplied by 2.
The key takeaway from this is that NumPy arrays are specifically designed to support mathematical operations on numeric data - which makes them more useful for data analysis than a generic list.
You might have spotted that the class type for the numpy array above is a **numpy.ndarray**. The **nd** indicates that this is a structure that can consists of multiple *dimensions* (it can have *n* dimensions). Our specific instance has a single dimension of student grades.
Run the cell below to view the **shape** of the array.
```
grades.shape
```
The shape confirms that this array has only one dimension, which contains 22 elements (there are 22 grades in the original list). You can access the individual elements in the array by their zero-based ordinal position. Let's get the first element (the one in position 0).
```
grades[0]
```
Alright, now you know your way around a NumPy array, it's time to perform some analysis of the grades data.
You can apply aggregations across the elements in the array, so let's find the simple average grade (in other words, the *mean* grade value).
```
grades.mean()
```
So the mean grade is just around 50 - more or less in the middle of the possible range from 0 to 100.
Let's add a second set of data for the same students, this time recording the typical number of hours per week they devoted to studying.
```
# Define an array of study hours
study_hours = [10.0,11.5,9.0,16.0,9.25,1.0,11.5,9.0,8.5,14.5,15.5,
13.75,9.0,8.0,15.5,8.0,9.0,6.0,10.0,12.0,12.5,12.0]
# Create a 2D array (an array of arrays)
student_data = np.array([study_hours, grades])
# display the array
student_data
```
Now the data consists of a 2-dimensional array - an array of arrays. Let's look at its shape.
```
# Show shape of 2D array
student_data.shape
```
The **student_data** array contains two elements, each of which is an array containing 22 elements.
To navigate this structure, you need to specify the position of each element in the hierarchy. So to find the first value in the first array (which contains the study hours data), you can use the following code.
```
# Show the first element of the first element
student_data[0][0]
```
Now you have a multidimensional array containing both the student's study time and grade information, which you can use to compare data. For example, how does the mean study time compare to the mean grade?
```
# Get the mean value of each sub-array
avg_study = student_data[0].mean()
avg_grade = student_data[1].mean()
print('Average study hours: {:.2f}\nAverage grade: {:.2f}'.format(avg_study, avg_grade))
```
## Exploring tabular data with Pandas
While NumPy provides a lot of the functionality you need to work with numbers, and specifically arrays of numeric values; when you start to deal with two-dimensional tables of data, the **Pandas** package offers a more convenient structure to work with - the **DataFrame**.
Run the following cell to import the Pandas library and create a DataFrame with three columns. The first column is a list of student names, and the second and third columns are the NumPy arrays containing the study time and grade data.
```
import pandas as pd
df_students = pd.DataFrame({'Name': ['Dan', 'Joann', 'Pedro', 'Rosie', 'Ethan', 'Vicky', 'Frederic', 'Jimmie',
'Rhonda', 'Giovanni', 'Francesca', 'Rajab', 'Naiyana', 'Kian', 'Jenny',
'Jakeem','Helena','Ismat','Anila','Skye','Daniel','Aisha'],
'StudyHours':student_data[0],
'Grade':student_data[1]})
df_students
```
Note that in addition to the columns you specified, the DataFrame includes an *index* to unique identify each row. We could have specified the index explicitly, and assigned any kind of appropriate value (for example, an email address); but because we didn't specify an index, one has been created with a unique integer value for each row.
### Finding and filtering data in a DataFrame
You can use the DataFrame's **loc** method to retrieve data for a specific index value, like this.
```
# Get the data for index value 5
df_students.loc[5]
```
You can also get the data at a range of index values, like this:
```
# Get the rows with index values from 0 to 5
df_students.loc[0:5]
```
In addition to being able to use the **loc** method to find rows based on the index, you can use the **iloc** method to find rows based on their ordinal position in the DataFrame (regardless of the index):
```
# Get data in the first five rows
df_students.iloc[0:5]
```
Look carefully at the `iloc[0:5]` results, and compare them to the `loc[0:5]` results you obtained previously. Can you spot the difference?
The **loc** method returned rows with index *label* in the list of values from *0* to *5* - which includes *0*, *1*, *2*, *3*, *4*, and *5* (six rows). However, the **iloc** method returns the rows in the *positions* included in the range 0 to 5, and since integer ranges don't include the upper-bound value, this includes positions *0*, *1*, *2*, *3*, and *4* (five rows).
**iloc** identifies data values in a DataFrame by *position*, which extends beyond rows to columns. So for example, you can use it to find the values for the columns in positions 1 and 2 in row 0, like this:
```
df_students.iloc[0,[1,2]]
```
Let's return to the **loc** method, and see how it works with columns. Remember that **loc** is used to locate data items based on index values rather than positions. In the absence of an explicit index column, the rows in our dataframe are indexed as integer values, but the columns are identified by name:
```
df_students.loc[0,'Grade']
```
Here's another useful trick. You can use the **loc** method to find indexed rows based on a filtering expression that references named columns other than the index, like this:
```
df_students.loc[df_students['Name']=='Aisha']
```
Actually, you don't need to explicitly use the **loc** method to do this - you can simply apply a DataFrame filtering expression, like this:
```
df_students[df_students['Name']=='Aisha']
```
And for good measure, you can achieve the same results by using the DataFrame's **query** method, like this:
```
df_students.query('Name=="Aisha"')
```
The three previous examples underline an occassionally confusing truth about working with Pandas. Often, there are multiple ways to achieve the same results. Another example of this is the way you refer to a DataFrame column name. You can specify the column name as a named index value (as in the `df_students['Name']` examples we've seen so far), or you can use the column as a property of the DataFrame, like this:
```
df_students[df_students.Name == 'Aisha']
```
### Loading a DataFrame from a file
We constructed the DataFrame from some existing arrays. However, in many real-world scenarios, data is loaded from sources such as files. Let's replace the student grades DataFrame with the contents of a text file.
```
df_students = pd.read_csv('data/grades.csv',delimiter=',',header='infer')
df_students.head()
```
The DataFrame's **read_csv** method is used to load data from text files. As you can see in the example code, you can specify options such as the column delimiter and which row (if any) contains column headers (in this case, the delimiter is a comma and the first row contains the column names - these are the default settings, so the parameters could have been omitted).
### Handling missing values
One of the most common issues data scientists need to deal with is incomplete or missing data. So how would we know that the DataFrame contains missing values? You can use the **isnull** method to identify which individual values are null, like this:
```
df_students.isnull()
```
Of course, with a larger DataFrame, it would be inefficient to review all of the rows and columns individually; so we can get the sum of missing values for each column, like this:
```
df_students.isnull().sum()
```
So now we know that there's one missing **StudyHours** value, and two missing **Grade** values.
To see them in context, we can filter the dataframe to include only rows where any of the columns (axis 1 of the DataFrame) are null.
```
df_students[df_students.isnull().any(axis=1)]
```
When the DataFrame is retrieved, the missing numeric values show up as **NaN** (*not a number*).
So now that we've found the null values, what can we do about them?
One common approach is to *impute* replacement values. For example, if the number of study hours is missing, we could just assume that the student studied for an average amount of time and replace the missing value with the mean study hours. To do this, we can use the **fillna** method, like this:
```
df_students.StudyHours = df_students.StudyHours.fillna(df_students.StudyHours.mean())
df_students
```
Alternatively, it might be important to ensure that you only use data you know to be absolutely correct; so you can drop rows or columns that contains null values by using the **dropna** method. In this case, we'll remove rows (axis 0 of the DataFrame) where any of the columns contain null values.
```
df_students = df_students.dropna(axis=0, how='any')
df_students
```
### Explore data in the DataFrame
Now that we've cleaned up the missing values, we're ready to explore the data in the DataFrame. Let's start by comparing the mean study hours and grades.
```
# Get the mean study hours using to column name as an index
mean_study = df_students['StudyHours'].mean()
# Get the mean grade using the column name as a property (just to make the point!)
mean_grade = df_students.Grade.mean()
# Print the mean study hours and mean grade
print('Average weekly study hours: {:.2f}\nAverage grade: {:.2f}'.format(mean_study, mean_grade))
```
OK, let's filter the DataFrame to find only the students who studied for more than the average amount of time.
```
# Get students who studied for the mean or more hours
df_students[df_students.StudyHours > mean_study]
```
Note that the filtered result is itself a DataFrame, so you can work with its columns just like any other DataFrame.
For example, let's find the average grade for students who undertook more than the average amount of study time.
```
# What was their mean grade?
df_students[df_students.StudyHours > mean_study].Grade.mean()
```
Let's assume that the passing grade for the course is 60.
We can use that information to add a new column to the DataFrame, indicating whether or not each student passed.
First, we'll create a Pandas **Series** containing the pass/fail indicator (True or False), and then we'll concatenate that series as a new column (axis 1) in the DataFrame.
```
passes = pd.Series(df_students['Grade'] >= 60)
df_students = pd.concat([df_students, passes.rename("Pass")], axis=1)
df_students
```
DataFrames are designed for tabular data, and you can use them to perform many of the kinds of data analytics operation you can do in a relational database; such as grouping and aggregating tables of data.
For example, you can use the **groupby** method to group the student data into groups based on the **Pass** column you added previously, and count the number of names in each group - in other words, you can determine how many students passed and failed.
```
print(df_students.groupby(df_students.Pass).Name.count())
```
You can aggregate multiple fields in a group using any available aggregation function. For example, you can find the mean study time and grade for the groups of students who passed and failed the course.
```
print(df_students.groupby(df_students.Pass)['StudyHours', 'Grade'].mean())
```
DataFrames are amazingly versatile, and make it easy to manipulate data. Many DataFrame operations return a new copy of the DataFrame; so if you want to modify a DataFrame but keep the existing variable, you need to assign the result of the operation to the existing variable. For example, the following code sorts the student data into descending order of Grade, and assigns the resulting sorted DataFrame to the original **df_students** variable.
```
# Create a DataFrame with the data sorted by Grade (descending)
df_students = df_students.sort_values('Grade', ascending=False)
# Show the DataFrame
df_students
```
## Visualizing data with Matplotlib
DataFrames provide a great way to explore and analyze tabular data, but sometimes a picture is worth a thousand rows and columns. The **Matplotlib** library provides the foundation for plotting data visualizations that can greatly enhance your ability the analyze the data.
Let's start with a simple bar chart that shows the grade of each student.
```
# Ensure plots are displayed inline in the notebook
%matplotlib inline
from matplotlib import pyplot as plt
# Create a bar plot of name vs grade
plt.bar(x=df_students.Name, height=df_students.Grade)
# Display the plot
plt.show()
```
Well, that worked; but the chart could use some improvements to make it clearer what we're looking at.
Note that you used the **pyplot** class from Matplotlib to plot the chart. This class provides a whole bunch of ways to improve the visual elements of the plot. For example, the following code:
- Specifies the color of the bar chart.
- Adds a title to the chart (so we know what it represents)
- Adds labels to the X and Y (so we know which axis shows which data)
- Adds a grid (to make it easier to determine the values for the bars)
- Rotates the X markers (so we can read them)
```
# Create a bar plot of name vs grade
plt.bar(x=df_students.Name, height=df_students.Grade, color='orange')
# Customize the chart
plt.title('Student Grades')
plt.xlabel('Student')
plt.ylabel('Grade')
plt.grid(color='#95a5a6', linestyle='--', linewidth=2, axis='y', alpha=0.7)
plt.xticks(rotation=90)
# Display the plot
plt.show()
```
A plot is technically contained with a **Figure**. In the previous examples, the figure was created implicitly for you; but you can create it explicitly. For example, the following code creates a figure with a specific size.
```
# Create a Figure
fig = plt.figure(figsize=(8,3))
# Create a bar plot of name vs grade
plt.bar(x=df_students.Name, height=df_students.Grade, color='orange')
# Customize the chart
plt.title('Student Grades')
plt.xlabel('Student')
plt.ylabel('Grade')
plt.grid(color='#95a5a6', linestyle='--', linewidth=2, axis='y', alpha=0.7)
plt.xticks(rotation=90)
# Show the figure
plt.show()
```
A figure can contain multiple subplots, each on its own *axis*.
For example, the following code creates a figure with two subplots - one is a bar chart showing student grades, and the other is a pie chart comparing the number of passing grades to non-passing grades.
```
# Create a figure for 2 subplots (1 row, 2 columns)
fig, ax = plt.subplots(1, 2, figsize = (10,4))
# Create a bar plot of name vs grade on the first axis
ax[0].bar(x=df_students.Name, height=df_students.Grade, color='orange')
ax[0].set_title('Grades')
ax[0].set_xticklabels(df_students.Name, rotation=90)
# Create a pie chart of pass counts on the second axis
pass_counts = df_students['Pass'].value_counts()
ax[1].pie(pass_counts, labels=pass_counts)
ax[1].set_title('Passing Grades')
ax[1].legend(pass_counts.keys().tolist())
# Add a title to the Figure
fig.suptitle('Student Data')
# Show the figure
fig.show()
```
Until now, you've used methods of the Matplotlib.pyplot object to plot charts. However, Matplotlib is so foundational to graphics in Python that many packages, including Pandas, provide methods that abstract the underlying Matplotlib functions and simplify plotting. For example, the DataFrame provides its own methods for plotting data, as shown in the following example to plot a bar chart of study hours.
```
df_students.plot.bar(x='Name', y='StudyHours', color='teal', figsize=(6,4))
```
## Getting started with statistical analysis
Now that you know how to use Python to manipulate and visualize data, you can start analyzing it.
A lot of data science is rooted in *statistics*, so we'll explore some basic statistical techniques.
> **Note**: This is <u>not</u> intended to teach you statistics - that's much too big a topic for this notebook. It will however introduce you to some statistical concepts and techniques that data scientists use as they explore data in preparation for machine learning modeling.
### Descriptive statistics and data distribution
When examining a *variable* (for example a sample of student grades), data scientists are particularly interested in its *distribution* (in other words, how are all the different grade values spread across the sample). The starting point for this exploration is often to visualize the data as a histogram, and see how frequently each value for the variable occurs.
```
# Get the variable to examine
var_data = df_students['Grade']
# Create a Figure
fig = plt.figure(figsize=(10,4))
# Plot a histogram
plt.hist(var_data)
# Add titles and labels
plt.title('Data Distribution')
plt.xlabel('Value')
plt.ylabel('Frequency')
# Show the figure
fig.show()
```
The histogram for grades is a symmetric shape, where the most frequently occurring grades tend to be in the middle of the range (around 50), with fewer grades at the extreme ends of the scale.
#### Measures of central tendency
To understand the distribution better, we can examine so-called *measures of central tendency*; which is a fancy way of describing statistics that represent the "middle" of the data. The goal of this is to try to find a "typical" value. Common ways to define the middle of the data include:
- The *mean*: A simple average based on adding together all of the values in the sample set, and then dividing the total by the number of samples.
- The *median*: The value in the middle of the range of all of the sample values.
- The *mode*: The most commonly occuring value in the sample set<sup>\*</sup>.
Let's calculate these values, along with the minimum and maximum values for comparison, and show them on the histogram.
> <sup>\*</sup>Of course, in some sample sets , there may be a tie for the most common value - in which case the dataset is described as *bimodal* or even *multimodal*.
```
# Get the variable to examine
var = df_students['Grade']
# Get statistics
min_val = var.min()
max_val = var.max()
mean_val = var.mean()
med_val = var.median()
mod_val = var.mode()[0]
print('Minimum:{:.2f}\nMean:{:.2f}\nMedian:{:.2f}\nMode:{:.2f}\nMaximum:{:.2f}\n'.format(min_val,
mean_val,
med_val,
mod_val,
max_val))
# Create a Figure
fig = plt.figure(figsize=(10,4))
# Plot a histogram
plt.hist(var)
# Add lines for the statistics
plt.axvline(x=min_val, color = 'gray', linestyle='dashed', linewidth = 2)
plt.axvline(x=mean_val, color = 'cyan', linestyle='dashed', linewidth = 2)
plt.axvline(x=med_val, color = 'red', linestyle='dashed', linewidth = 2)
plt.axvline(x=mod_val, color = 'yellow', linestyle='dashed', linewidth = 2)
plt.axvline(x=max_val, color = 'gray', linestyle='dashed', linewidth = 2)
# Add titles and labels
plt.title('Data Distribution')
plt.xlabel('Value')
plt.ylabel('Frequency')
# Show the figure
fig.show()
```
For the grade data, the mean, median, and mode all seem to be more or less in the middle of the minimum and maximum, at around 50.
Another way to visualize the distribution of a variable is to use a *box* plot (sometimes called a *box-and-whiskers* plot). Let's create one for the grade data.
```
# Get the variable to examine
var = df_students['Grade']
# Create a Figure
fig = plt.figure(figsize=(10,4))
# Plot a histogram
plt.boxplot(var)
# Add titles and labels
plt.title('Data Distribution')
# Show the figure
fig.show()
```
The box plot shows the distribution of the grade values in a different format to the histogram. The *box* part of the plot shows where the inner two *quartiles* of the data reside - so in this case, half of the grades are between approximately 36 and 63. The *whiskers* extending from the box show the outer two quartiles; so the other half of the grades in this case are between 0 and 36 or 63 and 100. The line in the box indicates the *median* value.
It's often useful to combine histograms and box plots, with the box plot's orientation changed to align it with the histogram (in some ways, it can be helpful to think of the histogram as a "front elevation" view of the distribution, and the box plot as a "plan" view of the distribution from above.)
```
# Create a function that we can re-use
def show_distribution(var_data):
from matplotlib import pyplot as plt
# Get statistics
min_val = var_data.min()
max_val = var_data.max()
mean_val = var_data.mean()
med_val = var_data.median()
mod_val = var_data.mode()[0]
print('Minimum:{:.2f}\nMean:{:.2f}\nMedian:{:.2f}\nMode:{:.2f}\nMaximum:{:.2f}\n'.format(min_val,
mean_val,
med_val,
mod_val,
max_val))
# Create a figure for 2 subplots (2 rows, 1 column)
fig, ax = plt.subplots(2, 1, figsize = (10,4))
# Plot the histogram
ax[0].hist(var_data)
ax[0].set_ylabel('Frequency')
# Add lines for the mean, median, and mode
ax[0].axvline(x=min_val, color = 'gray', linestyle='dashed', linewidth = 2)
ax[0].axvline(x=mean_val, color = 'cyan', linestyle='dashed', linewidth = 2)
ax[0].axvline(x=med_val, color = 'red', linestyle='dashed', linewidth = 2)
ax[0].axvline(x=mod_val, color = 'yellow', linestyle='dashed', linewidth = 2)
ax[0].axvline(x=max_val, color = 'gray', linestyle='dashed', linewidth = 2)
# Plot the boxplot
ax[1].boxplot(var_data, vert=False)
ax[1].set_xlabel('Value')
# Add a title to the Figure
fig.suptitle('Data Distribution')
# Show the figure
fig.show()
# Get the variable to examine
col = df_students['Grade']
# Call the function
show_distribution(col)
```
All of the measurements of central tendency are right in the middle of the data distribution, which is symmetric with values becoming progressively lower in both directions from the middle.
To explore this distribution in more detail, you need to understand that statistics is fundamentally about taking *samples* of data and using probability functions to extrapolate information about the full *population* of data. For example, the student data consists of 22 samples, and for each sample there is a grade value. You can think of each sample grade as a variable that's been randomly selected from the set of all grades awarded for this course. With enough of these random variables, you can calculate something called a *probability density function*, which estimates the distribution of grades for the full population.
The Pandas DataFrame class provides a helpful plot function to show this density.
```
def show_density(var_data):
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(10,4))
# Plot density
var_data.plot.density()
# Add titles and labels
plt.title('Data Density')
# Show the mean, median, and mode
plt.axvline(x=var_data.mean(), color = 'cyan', linestyle='dashed', linewidth = 2)
plt.axvline(x=var_data.median(), color = 'red', linestyle='dashed', linewidth = 2)
plt.axvline(x=var_data.mode()[0], color = 'yellow', linestyle='dashed', linewidth = 2)
# Show the figure
plt.show()
# Get the density of Grade
col = df_students['Grade']
show_density(col)
```
As expected from the histogram of the sample, the density shows the characteristic 'bell curve" of what statisticians call a *normal* distribution with the mean and mode at the center and symmetric tails.
Now let's take a look at the distribution of the study hours data.
```
# Get the variable to examine
col = df_students['StudyHours']
# Call the function
show_distribution(col)
```
The distribution of the study time data is significantly different from that of the grades.
Note that the whiskers of the box plot only extend to around 6.0, indicating that the vast majority of the first quarter of the data is above this value. The minimum is marked with an **o**, indicating that it is statistically an *outlier* - a value that lies significantly outside the range of the rest of the distribution.
Outliers can occur for many reasons. Maybe a student meant to record "10" hours of study time, but entered "1" and missed the "0". Or maybe the student was abnormally lazy when it comes to studying! Either way, it's a statistical anomaly that doesn't represent a typical student. Let's see what the distribution looks like without it.
```
# Get the variable to examine
col = df_students[df_students.StudyHours>1]['StudyHours']
# Call the function
show_distribution(col)
```
In this example, the dataset is small enough to clearly see that the value **1** is an outlier for the **StudyHours** column, so you can exclude it explicitly. In most real-world cases, it's easier to consider outliers as being values that fall below or above percentiles within which most of the data lie. For example, the following code uses the Pandas **quantile** function to exclude observations below the 0.01th percentile (the value above which 99% of the data reside).
```
q01 = df_students.StudyHours.quantile(0.01)
# Get the variable to examine
col = df_students[df_students.StudyHours>q01]['StudyHours']
# Call the function
show_distribution(col)
```
> **Tip**: You can also eliminate outliers at the upper end of the distribution by defining a threshold at a high percentile value - for example, you could use the **quantile** function to find the 0.99 percentile below which 99% of the data reside.
With the outliers removed, the box plot shows all data within the four quartiles. Note that the distribution is not symmetric like it is for the grade data though - there are some students with very high study times of around 16 hours, but the bulk of the data is between 7 and 13 hours; The few extremely high values pull the mean towards the higher end of the scale.
Let's look at the density for this distribution.
```
# Get the density of StudyHours
show_density(col)
```
This kind of distribution is called *right skewed*. The mass of the data is on the left side of the distribution, creating a long tail to the right because of the values at the extreme high end; which pull the mean to the right.
#### Measures of variance
So now we have a good idea where the middle of the grade and study hours data distributions are. However, there's another aspect of the distributions we should examine: how much variability is there in the data?
Typical statistics that measure variability in the data include:
- **Range**: The difference between the maximum and minimum. There's no built-in function for this, but it's easy to calculate using the **min** and **max** functions.
- **Variance**: The average of the squared difference from the mean. You can use the built-in **var** function to find this.
- **Standard Deviation**: The square root of the variance. You can use the built-in **std** function to find this.
```
for col_name in ['Grade','StudyHours']:
col = df_students[col_name]
rng = col.max() - col.min()
var = col.var()
std = col.std()
print('\n{}:\n - Range: {:.2f}\n - Variance: {:.2f}\n - Std.Dev: {:.2f}'.format(col_name, rng, var, std))
```
Of these statistics, the standard deviation is generally the most useful. It provides a measure of variance in the data on the same scale as the data itself (so grade points for the Grade distribution and hours for the StudyHours distribution). The higher the standard deviation, the more variance there is when comparing values in the distribution to the distribution mean - in other words, the data is more spread out.
When working with a *normal* distribution, the standard deviation works with the particular characteristics of a normal distribution to provide even greater insight. Run the cell below to see the relationship between standard deviations and the data in the normal distribution.
```
import scipy.stats as stats
# Get the Grade column
col = df_students['Grade']
# get the density
density = stats.gaussian_kde(col)
# Plot the density
col.plot.density()
# Get the mean and standard deviation
s = col.std()
m = col.mean()
# Annotate 1 stdev
x1 = [m-s, m+s]
y1 = density(x1)
plt.plot(x1,y1, color='magenta')
plt.annotate('1 std (68.26%)', (x1[1],y1[1]))
# Annotate 2 stdevs
x2 = [m-(s*2), m+(s*2)]
y2 = density(x2)
plt.plot(x2,y2, color='green')
plt.annotate('2 std (95.45%)', (x2[1],y2[1]))
# Annotate 3 stdevs
x3 = [m-(s*3), m+(s*3)]
y3 = density(x3)
plt.plot(x3,y3, color='orange')
plt.annotate('3 std (99.73%)', (x3[1],y3[1]))
# Show the location of the mean
plt.axvline(col.mean(), color='cyan', linestyle='dashed', linewidth=1)
plt.axis('off')
plt.show()
```
The horizontal lines show the percentage of data within 1, 2, and 3 standard deviations of the mean (plus or minus).
In any normal distribution:
- Approximately 68.26% of values fall within one standard deviation from the mean.
- Approximately 95.45% of values fall within two standard deviations from the mean.
- Approximately 99.73% of values fall within three standard deviations from the mean.
So, since we know that the mean grade is 49.18, the standard deviation is 21.74, and distribution of grades is approximately normal; we can calculate that 68.26% of students should achieve a grade between 27.44 and 70.92.
The descriptive statistics we've used to understand the distribution of the student data variables are the basis of statistical analysis; and because they're such an important part of exploring your data, there's a built-in **Describe** method of the DataFrame object that returns the main descriptive statistics for all numeric columns.
```
df_students.describe()
```
## Comparing data
Now that you know something about the statistical distribution of the data in your dataset, you're ready to examine your data to identify any apparent relationships between variables.
First of all, let's get rid of any rows that contain outliers so that we have a sample that is representative of a typical class of students. We identified that the StudyHours column contains some outliers with extremely low values, so we'll remove those rows.
```
df_sample = df_students[df_students['StudyHours']>1]
df_sample
```
### Comparing numeric and categorical variables
The data includes two *numeric* variables (**StudyHours** and **Grade**) and two *categorical* variables (**Name** and **Pass**). Let's start by comparing the numeric **StudyHours** column to the categorical **Pass** column to see if there's an apparent relationship between the number of hours studied and a passing grade.
To make this comparison, let's create box plots showing the distribution of StudyHours for each possible Pass value (true and false).
```
df_sample.boxplot(column='StudyHours', by='Pass', figsize=(8,5))
```
Comparing the StudyHours distributions, it's immediately apparent (if not particularly surprising) that students who passed the course tended to study for more hours than students who didn't. So if you wanted to predict whether or not a student is likely to pass the course, the amount of time they spend studying may be a good predictive feature.
### Comparing numeric variables
Now let's compare two numeric variables. We'll start by creating a bar chart that shows both grade and study hours.
```
# Create a bar plot of name vs grade and study hours
df_sample.plot(x='Name', y=['Grade','StudyHours'], kind='bar', figsize=(8,5))
```
The chart shows bars for both grade and study hours for each student; but it's not easy to compare because the values are on different scales. Grades are measured in grade points, and range from 3 to 97; while study time is measured in hours and ranges from 1 to 16.
A common technique when dealing with numeric data in different scales is to *normalize* the data so that the values retain their proportional distribution, but are measured on the same scale. To accomplish this, we'll use a technique called *MinMax* scaling that distributes the values proportionally on a scale of 0 to 1. You could write the code to apply this transformation; but the **Scikit-Learn** library provides a scaler to do it for you.
```
from sklearn.preprocessing import MinMaxScaler
# Get a scaler object
scaler = MinMaxScaler()
# Create a new dataframe for the scaled values
df_normalized = df_sample[['Name', 'Grade', 'StudyHours']].copy()
# Normalize the numeric columns
df_normalized[['Grade','StudyHours']] = scaler.fit_transform(df_normalized[['Grade','StudyHours']])
# Plot the normalized values
df_normalized.plot(x='Name', y=['Grade','StudyHours'], kind='bar', figsize=(8,5))
```
With the data normalized, it's easier to see an apparent relationship between grade and study time. It's not an exact match, but it definitely seems like students with higher grades tend to have studied more.
So there seems to be a correlation between study time and grade; and in fact, there's a statistical *correlation* measurement we can use to quantify the relationship between these columns.
```
df_normalized.Grade.corr(df_normalized.StudyHours)
```
The correlation statistic is a value between -1 and 1 that indicates the strength of a relationship. Values above 0 indicate a *positive* correlation (high values of one variable tend to coincide with high values of the other), while values below 0 indicate a *negative* correlation (high values of one variable tend to coincide with low values of the other). In this case, the correlation value is close to 1; showing a strongly positive correlation between study time and grade.
> **Note**: Data scientists often quote the maxim "*correlation* is not *causation*". In other words, as tempting as it might be, you shouldn't interpret the statistical correlation as explaining *why* one of the values is high. In the case of the student data, the statistics demonstrates that students with high grades tend to also have high amounts of study time; but this is not the same as proving that they achieved high grades *because* they studied a lot. The statistic could equally be used as evidence to support the nonsensical conclusion that the students studied a lot *because* their grades were going to be high.
Another way to visualise the apparent correlation between two numeric columns is to use a *scatter* plot.
```
# Create a scatter plot
df_sample.plot.scatter(title='Study Time vs Grade', x='StudyHours', y='Grade')
```
Again, it looks like there's a discernible pattern in which the students who studied the most hours are also the students who got the highest grades.
We can see this more clearly by adding a *regression* line (or a *line of best fit*) to the plot that shows the general trend in the data. To do this, we'll use a statistical technique called *least squares regression*.
> **Warning - Math Ahead!**
>
> Cast your mind back to when you were learning how to solve linear equations in school, and recall that the *slope-intercept* form of a linear equation looks like this:
>
> \begin{equation}y = mx + b\end{equation}
>
> In this equation, *y* and *x* are the coordinate variables, *m* is the slope of the line, and *b* is the y-intercept (where the line goes through the Y-axis).
>
> In the case of our scatter plot for our student data, we already have our values for *x* (*StudyHours*) and *y* (*Grade*), so we just need to calculate the intercept and slope of the straight line that lies closest to those points. Then we can form a linear equation that calculates a new *y* value on that line for each of our *x* (*StudyHours*) values - to avoid confusion, we'll call this new *y* value *f(x)* (because it's the output from a linear equation ***f***unction based on *x*). The difference between the original *y* (*Grade*) value and the *f(x)* value is the *error* between our regression line and the actual *Grade* achieved by the student. Our goal is to calculate the slope and intercept for a line with the lowest overall error.
>
> Specifically, we define the overall error by taking the error for each point, squaring it, and adding all the squared errors together. The line of best fit is the line that gives us the lowest value for the sum of the squared errors - hence the name *least squares regression*.
Fortunately, you don't need to code the regression calculation yourself - the **SciPy** package includes a **stats** class that provides a **linregress** method to do the hard work for you. This returns (among other things) the coefficients you need for the slope equation - slope (*m*) and intercept (*b*) based on a given pair of variable samples you want to compare.
```
from scipy import stats
#
df_regression = df_sample[['Grade', 'StudyHours']].copy()
# Get the regression slope and intercept
m, b, r, p, se = stats.linregress(df_regression['StudyHours'], df_regression['Grade'])
print('slope: {:.4f}\ny-intercept: {:.4f}'.format(m,b))
print('so...\n f(x) = {:.4f}x + {:.4f}'.format(m,b))
# Use the function (mx + b) to calculate f(x) for each x (StudyHours) value
df_regression['fx'] = (m * df_regression['StudyHours']) + b
# Calculate the error between f(x) and the actual y (Grade) value
df_regression['error'] = df_regression['fx'] - df_regression['Grade']
# Create a scatter plot of Grade vs Salary
df_regression.plot.scatter(x='StudyHours', y='Grade')
# Plot the regression line
plt.plot(df_regression['StudyHours'],df_regression['fx'], color='cyan')
# Display the plot
plt.show()
```
Note that this time, the code plotted two distinct things - the scatter plot of the sample study hours and grades is plotted as before, and then a line of best fit based on the least squares regression coefficients is plotted.
The slope and intercept coefficients calculated for the regression line are shown above the plot.
The line is based on the ***f*(x)** values calculated for each **StudyHours** value. Run the following cell to see a table that includes the following values:
- The **StudyHours** for each student.
- The **Grade** achieved by each student.
- The ***f(x)*** value calculated using the regression line coefficients.
- The *error* between the calculated ***f(x)*** value and the actual **Grade** value.
Some of the errors, particularly at the extreme ends, and quite large (up to over 17.5 grade points); but in general, the line is pretty close to the actual grades.
```
# Show the original x,y values, the f(x) value, and the error
df_regression[['StudyHours', 'Grade', 'fx', 'error']]
```
### Using the regression coefficients for prediction
Now that you have the regression coefficients for the study time and grade relationship, you can use them in a function to estimate the expected grade for a given amount of study.
```
# Define a function based on our regression coefficients
def f(x):
m = 6.3134
b = -17.9164
return m*x + b
study_time = 14
# Get f(x) for study time
prediction = f(study_time)
# Grade can't be less than 0 or more than 100
expected_grade = max(0,min(100,prediction))
#Print the estimated grade
print ('Studying for {} hours per week may result in a grade of {:.0f}'.format(study_time, expected_grade))
```
So by applying statistics to sample data, you've determined a relationship between study time and grade; and encapsulated that relationship in a general function that can be used to predict a grade for a given amount of study time.
This technique is in fact the basic premise of machine learning. You can take a set of sample data that includes one or more *features* (in this case, the number of hours studied) and a known *label* value (in this case, the grade achieved) and use the sample data to derive a function that calculates predicted label values for any given set of features.
## Further Reading
To learn more about the Python packages you explored in this notebook, see the following documentation:
- [NumPy](https://numpy.org/doc/stable/)
- [Pandas](https://pandas.pydata.org/pandas-docs/stable/)
- [Matplotlib](https://matplotlib.org/contents.html)
## Challenge: Analyze Flight Data
If this notebook has inspired you to try exploring data for yourself, why not take on the challenge of a real-world dataset containing flight records from the US Department of Transportation? You'll find the challenge in the [/challenges/01 - Flights Challenge.ipynb](./challenges/01%20-%20Flights%20Challenge.ipynb) notebook!
> **Note**: The time to complete this optional challenge is not included in the estimated time for this exercise - you can spend as little or as much time on it as you like!
| github_jupyter |
# Primary Model Pipeline
```
import collections
import pandas as pd
import numpy as np
import time
import os
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
from tensorflow.keras.models import load_model
from tensorflow.keras.utils import plot_model
import matplotlib.pyplot as plt
from scipy import signal
pd.set_option('display.max_columns', 500)
os.environ['HDF5_USE_FILE_LOCKING'] = 'FALSE'
tf.__version__
```
### Load Datasets and Clean
In this configuration the relevant data set should be loaded from the same folder as the notebook
```
df = pd.read_csv('/nfs/2018/j/jcruz-y-/neurotron_datasets/joined/joined_data_106979_24-Oct-19_17:31_jose_all_1.csv')
```
The data consists of timestamps from the two hardware devices and a diff between them. When the two hardware data streams were stitched together an effor was made to minimize this diff, but the driver configuration did not easily permit eliminating it. This information is included to understand the accuracy of the data, but will not be used during the training.
The time data is followed by the 8 channels from the Myo, this data will be used as input features.
This is followed by the 63 positional points from the Leap cameras. These will be used as labels.
```
df.head()
df = df.drop(labels=["Leap timestamp", "timestamp diff", "emg timestamp"], axis=1)
df.describe()
```
### FFT
**Transforming to spectrograms**
```
# y axis corresponds to frequencies (units are hz?)
# x axis corresponds to times (units are samples?)
# Each square corresponds to the magnitude (the absolute value the wave differs from 0)
shape = (6, 21, 8)
flat_dim = shape[0]*shape[1]*shape[2]
nperseg = 10
noverlap = 8
reshape = (-1, shape[0], shape[1], shape[2])
j = 0
i = 0
dir_num = 0
df_train_g = pd.DataFrame()
#Spectrogram hyperparameters
nperseg=40 #increasing nperseg increases frequency resolution and decreases time res
noverlap=11 #increasing time resolution requires increasing overlap
window = 'hann' #hann provides good time and frequency resolution properties
#Spectrogram
frequencies, times, spec = signal.spectrogram(x=df['ch1'][24:48],
fs=50, nperseg=nperseg,
noverlap=noverlap, window=window)
print('frequencies', frequencies.shape)
print('times', times.shape)
#print(spec)
#Subplot 1
fig = plt.figure(figsize=(14, 8))
ax1 = fig.add_subplot(211)
ax1 = plt.pcolormesh(times, frequencies, spec)
ax1 = plt.show
#Subplot 2
frequencies, times, spec = signal.spectrogram(x=df['ch2'][24:48], fs=50, nperseg=nperseg, noverlap=noverlap, window=window)
log_spec = np.log(spec)
fig = plt.figure(figsize=(14, 8))
ax1 = fig.add_subplot(211)
ax1 = plt.pcolormesh(times, frequencies, spec)
ax1 = plt.show
#Subplot 3
frequencies, times, spec = signal.spectrogram(x=df['ch3'][24:48], fs=50, nperseg=nperseg, noverlap=noverlap, window=window)
log_spec = np.log(spec)
fig = plt.figure(figsize=(14, 8))
ax1 = fig.add_subplot(211)
ax1 = plt.pcolormesh(times, frequencies, spec)
ax1 = plt.show
#Subplot 4
frequencies, times, spec = signal.spectrogram(x=df['ch4'][24:48], fs=50, nperseg=nperseg, noverlap=noverlap, window=window)
log_spec = np.log(spec)
fig = plt.figure(figsize=(14, 8))
ax1 = fig.add_subplot(211)
ax1 = plt.pcolormesh(times, frequencies, spec)
ax1 = plt.show
#Subplot 5
frequencies, times, spec = signal.spectrogram(x=df['ch5'][24:48], fs=50, nperseg=nperseg, noverlap=noverlap, window=window)
log_spec = np.log(spec)
fig = plt.figure(figsize=(14, 8))
ax1 = fig.add_subplot(211)
ax1 = plt.pcolormesh(times, frequencies, spec)
ax1 = plt.show
#Subplot 6
frequencies, times, spec = signal.spectrogram(x=df['ch6'][24:48], fs=50, nperseg=nperseg, noverlap=noverlap, window=window)
log_spec = np.log(spec)
fig = plt.figure(figsize=(14, 8))
ax1 = fig.add_subplot(211)
ax1 = plt.pcolormesh(times, frequencies, spec)
ax1 = plt.show
#Subplot 7
frequencies, times, spec = signal.spectrogram(x=df['ch7'][24:48], fs=50, nperseg=nperseg, noverlap=noverlap, window=window)
log_spec = np.log(spec)
fig = plt.figure(figsize=(14, 8))
ax1 = fig.add_subplot(211)
ax1 = plt.pcolormesh(times, frequencies, spec)
ax1 = plt.show
#Subplot 8
frequencies, times, spec = signal.spectrogram(x=df['ch8'][24:48], fs=50, nperseg=nperseg, noverlap=noverlap, window=window)
log_spec = np.log(spec)
fig = plt.figure(figsize=(14, 8))
ax1 = fig.add_subplot(211)
ax1 = plt.pcolormesh(times, frequencies, spec)
ax1 = plt.show
#Specs and Shapes
#print('label:', label_dir)
#print('file:', file)
print('spec_shape:', spec.shape)
print('frequencies_shape:', frequencies.shape)
print('times_shape:', times.shape)
channels = ['ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6', 'ch7', 'ch8']
shape = (7, 13, 8)
flat_dim = shape[0]*shape[1]*shape[2]
nperseg = 12
noverlap = 11
reshape = (-1, shape[0], shape[1], shape[2])
j = 1
i = 0
dir_num = 0
df_train_g = pd.DataFrame()
img = np.zeros(shape)
k = 0
num_samples = len(df)
x_shape = (num_samples, 7, 13, 8)
x1_train = np.zeros(x_shape)
for i in range(len(df) - 24):
for j in range(8):
frequencies, times, spec = signal.spectrogram(x=df[channels[j]][k:k+24], fs=50,
nperseg=nperseg, noverlap=noverlap,
window='hann')
log_spec = np.log(spec)
img[:,:,j] = spec
j = j + 1
x1_train[i,:,:,:] = img
i = i + 1
k = k + 1
if i == 4457:
print(df.iloc[i,:])
print(i)
print(x1_train.shape)
flat = np.reshape(x1_train, (num_samples, flat_dim))
df_train1 = pd.DataFrame(data=flat)
df_train_g = df_train_g.append(df_train1, ignore_index=True)
df_train_g.head()
def preprocess_features(x_train):
shape = (7, 13, 8)
reshape = (-1, shape[0], shape[1], shape[2])
x_train = x_train.replace(-np.inf, 0)
x_train = x_train.replace(np.inf, 0)
#x_train = np.log(x_train.values)
x_train = x_train.values
x_train_norm = x_train.reshape(reshape)
return x_train_norm
features = preprocess_features(df_train_g)
```
```
features.shape
labels = df.loc[:, 'Wrist x':].values
```
## Conv_LSTM
```
seq_length = 24
def reshape_overlap_samples(seq_length, feats, labels):
samples = feats.shape[0] - (seq_length - 1) # all samples except the last sequence
shape = (24, 7, 13, 8)
new_f = np.zeros(shape=(samples, 24, 7, 13, 8))
print(new_f.shape)
new_l = labels[seq_length - 1:]
queue = collections.deque(feats[:seq_length])
new_f[0] = np.array(queue)
j = 1
for i in range(seq_length, feats.shape[0]):
queue.popleft()
queue.append(feats[i])
new_f[j] = np.array(queue)
j += 1
return (new_f, new_l)
features_ol, labels_ol = reshape_overlap_samples(seq_length, features, labels)
print(features_ol.shape)
print(labels_ol.shape)
def create_model(input_shape):
inputlayer = Input(shape=input_shape)
norm_input = BatchNormalization()(inputlayer)
model = ConvLSTM2D(16, kernel_size=2, padding='same', activation='relu', return_sequences=True)(norm_input)
model = Dropout(rate=0.3)(model)
#model = ConvLSTM2D(16, kernel_size=2, padding='same', activation='relu', return_sequences=True)(model)
#model = Dropout(rate=0.5)(model)
#model = ConvLSTM2D(32, kernel_size=2, padding='same', activation='relu', return_sequences=True)(model)
#model = Dropout(rate=0.5)(model)
model = ConvLSTM2D(32, kernel_size=2, padding='same', activation='relu', return_sequences=False)(model)
model = Dropout(rate=0.3)(model)
#model = ConvLSTM2D(128, kernel_size=2, padding='same', activation='relu', return_sequences=True)(model)
#model = Dropout(rate=0.5)(model)
#model = ConvLSTM2D(128, kernel_size=2, padding='same', activation='relu', return_sequences=False)(model)
#model = Dropout(rate=0.5)(model)
model = Flatten()(model)
#mode1 = BatchNormalization()(Dense(128, activation='relu')(model))
mode1 = BatchNormalization()(Dense(128, activation='relu')(model))
model = Dense(63, activation='None')(model)
#dense_5 = Dense(63, activation='relu')(model)
#model = TimeDistributed(MaxPooling2D(pool_size=(2, 2)))(model)
#model = Dropout(rate=0.2)(model)
#model = ConvLSTM2D(64, kernel_size=3, padding='same', activation='relu')(model)
#model = ConvLSTM2D(64, kernel_size=3, padding='same', activation='relu')(model)
#model = TimeDistributed(MaxPooling2D(pool_size=(2, 2)))(model)
#model = Dropout(rate=0.2)(model)
#model = Conv2D(128, kernel_size=3, padding='same', activation='relu')(model)
#model = Conv2D(128, kernel_size=3, padding='same', activation='relu')(model)
#model = TimeDistributed(MaxPooling2D(pool_size=(1, 1)))(model)
#model = Flatten()(model)
#dense_1 = BatchNormalization()(Dense(128, activation='relu')(model))
#dense_2 = BatchNormalization()(Dense(128, activation='relu')(dense_1))
#dense_1 = Dense(nclass, activation='softmax')(dense_1)
#lstm layers
#inputs = Input(shape=(None, 128), name="inputs")(dense_2)
#lstm_0 = LSTM(100, return_sequences=True, name="lstm_0")(dense_2)
#do = Dropout(0.4)(lstm_0)
#lstm_1 = LSTM(100, return_sequences=True, name="lstm_1")(do)
#do_2 = Dropout(0.4)(lstm_1)
#lstm_1 = LSTM(100, return_sequences=False, name="lstm_1")(do_2)
#dense_3 = Dense(128, activation='relu', name="dense_3")(lstm_1)
#dense_4 = BatchNormalization()(Dense(128, activation='relu')(dense_3))
#dense_5 = Dense(128, activation='relu')(dense_4)
#dense_6 = BatchNormalization()(Dense(128, activation='relu')(dense_5))
#dense_5 = Dense(64, activation='relu')(dense_4)
#model_fc.add(Dense(100, input_dim=64))
#model_fc.add(Activation('relu'))
#model_fc.add(BatchNormalization())
#model_fc.add(Dropout(0.2))
#model_fc.add(Dense(64, input_dim=64))
#model_fc.add(Activation('relu'))
#model_fc.add(Dropout(0.2))
#model_fc.add(Dense(63, input_dim=64))
#decoder layers
#decoder_0 = decoder.get_layer("decoder_0")(lstm_out)
#decoder_0.trainable = False
#decoder_1 = decoder.get_layer("decoder_1")(decoder_0)
#decoder_1.trainable = False
#decoder_output = decoder.get_layer("decoder_output")(decoder_1)
#decoder_output.trainable = False
model = Model(inputs=inputlayer, outputs=model)
#model = Model(inputs, decoder_output, name="model_v1")
return model
shape = (24, 7, 13, 8)
model = create_model(shape)
model.summary()
optimizer = tf.keras.optimizers.Adam(lr=0.001)
model.compile(optimizer=optimizer, loss='mse')
model.evaluate(features_ol, labels_ol, verbose=1)
history = model.fit(features_ol, labels_ol, batch_size=seq_length, epochs=2
, verbose=1, validation_split=0.2, shuffle=False)
# Plot training & validation loss values
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
```
## CNN + LSTM
```
def create_model(input_shape):
inputlayer = Input(shape=input_shape)
norm_input = BatchNormalization()(inputlayer)
model = TimeDistributed(Conv2D(32, kernel_size=2, padding='same', activation='relu'))(norm_input)
model = TimeDistributed(Conv2D(32, kernel_size=2, padding='same', activation='relu'))(model)
model = BatchNormalization()(model)
#model = BatchNormalization()(TimeDistributed(Dense(128, activation='relu')(model)))
model = TimeDistributed(Flatten())(model)
model = LSTM(64, activation='relu', return_sequences=True)(model)
model = LSTM(64, activation='relu', return_sequences=False)(model)
model = BatchNormalization()(Dense(63, activation='relu')(model))
dense = Dense(63, activation='relu')(model)
#norm_input = BatchNormalization()(inputlayer)
#model = Conv2D(32, kernel_size=2, padding='same', activation='relu')(norm_input)
#model = Conv2D(32, kernel_size=2, padding='same', activation='relu')(model)
#model = MaxPooling2D(pool_size=(2, 2))(model)
#model = Dropout(rate=0.2)(model)
#model = Conv2D(64, kernel_size=3, padding='same', activation='relu')(model)
#model = Conv2D(64, kernel_size=3, padding='same', activation='relu')(model)
#model = MaxPooling2D(pool_size=(2, 2))(model)
#model = Dropout(rate=0.2)(model)
#vmodel = Conv2D(128, kernel_size=3, padding='same', activation='relu')(model)
#model = Conv2D(128, kernel_size=3, padding='same', activation='relu')(model)
#model = MaxPooling2D(pool_size=(1, 1))(model)
#model = Flatten()(model)
#dense_1 = BatchNormalization()(Dense(128, activation='relu')(model))
#dense_2 = BatchNormalization()(Dense(128, activation='relu')(dense_1))
#dense_1 = Dense(nclass, activation='softmax')(dense_1)
#lstm layers
#inputs = Input(shape=(None, 128))(dense_2)
#dense_3 = Dense(128, activation='relu', name="dense_3")(dense_2)
#lstm_0 = LSTM(100, input_shape=(128,), return_sequences=True, name="lstm_0")(dense_3)
#do = Dropout(0.4)(lstm_0)
#stm_1 = LSTM(100, return_sequences=True, name="lstm_1")(do)
#do_2 = Dropout(0.4)(lstm_0)
#lstm_1 = LSTM(100, return_sequences=False, name="lstm_1")(do_2)
#dense_3 = Dense(128, activation='relu', name="dense_3")(lstm_1)
#dense_4 = BatchNormalization()(Dense(128, activation='relu')(dense_3))
#dense_5 = Dense(128, activation='relu')(dense_4)
#dense_6 = BatchNormalization()(Dense(128, activation='relu')(dense_5))
#dense_5 = Dense(64, activation='relu')(dense_4)
#model_fc.add(Dense(100, input_dim=64))
#model_fc.add(Activation('relu'))
#model_fc.add(BatchNormalization())
#model_fc.add(Dropout(0.2))
#model_fc.add(Dense(64, input_dim=64))
#model_fc.add(Activation('relu'))
#model_fc.add(Dropout(0.2))
#model_fc.add(Dense(63, input_dim=64))
#decoder layers
#decoder_0 = decoder.get_layer("decoder_0")(lstm_out)
#decoder_0.trainable = False
#decoder_1 = decoder.get_layer("decoder_1")(decoder_0)
#decoder_1.trainable = False
#decoder_output = decoder.get_layer("decoder_output")(decoder_1)
#decoder_output.trainable = False
model = Model(inputs=inputlayer, outputs=dense)
#model = Model(inputs, decoder_output, name="model_v1")
return model
print(shape)
model = create_model((24, 7, 13, 8))
model.summary()
model.compile(optimizer='Adam', loss='mse')
history = model.fit(features_ol, labels_ol, batch_size=seq_length, epochs=5, verbose=1, validation_split=0.2)
```
## conv_lstm_2d
```
#lstm layers
inputs = Input(shape=(None, 8), name="inputs")
lstm_0 = ConvLSTM2D(100, return_sequences=True, name="lstm_0")(inputs)
do = Dropout(0.4)(lstm_0)
lstm_1 = ConvLSTM2D(100, return_sequences=False, name="lstm_1")(do)
do_2 = Dropout(0.4)(lstm_0)
lstm_1 = ConvLSTM2D(100, return_sequences=False, name="lstm_1")(do_2)
lstm_out = Dense(9, activation=None, name="lstm_out")(lstm_1)
#decoder layers
decoder_0 = decoder.get_layer("decoder_0")(lstm_out)
decoder_0.trainable = False
decoder_1 = decoder.get_layer("decoder_1")(decoder_0)
decoder_1.trainable = False
decoder_output = decoder.get_layer("decoder_output")(decoder_1)
decoder_output.trainable = False
model = Model(inputs, decoder_output, name="model_v1")
optimizer = tf.keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.00, amsgrad=False)
model.compile(optimizer=optimizer, loss='mse')
model.summary()
```
## Autoencoder
The final pipeline will pass the data into an LSTM and then into an autoencoder to expand features into the 63 point space. This autoencoder will be trained first below:
```
feature_ar = df.loc[:, 'ch1':'ch8'].values
label_ar = df.loc[:, 'Wrist x':].values
feature_ar.shape
label_ar.shape
```
Build the autoencoder structure:
```
encoding_dim = 9 #dimensionality of 'feature' vector
a_fn = None
# Full autoencoder
input_vec = Input(shape=(63,))
dense_0 = Dense(32, activation=a_fn)(input_vec)
dense_1 = Dense(16, activation=a_fn)(dense_0)
encoded = Dense(encoding_dim, activation=a_fn)(dense_1)
dense_2 = Dense(32, activation=a_fn, name='decoder_0')(encoded)
dense_3 = Dense(16, activation=a_fn, name='decoder_1')(dense_2)
decoded = Dense(63, activation=a_fn, name='decoder_output')(dense_3)
autoencoder = Model(input_vec, decoded)
# Encoder from autoencoder
encoder = Model(input_vec, encoded)
# Decoder from autoencoder layers
decoder_input = Input(shape=(encoding_dim,), name='encoded_input')
decode_0 = autoencoder.layers[-3](decoder_input)
decode_1 = autoencoder.layers[-2](decode_0)
decode_output = autoencoder.layers[-1](decode_1)
decoder = Model(decoder_input, decode_output, name='decoder')
# Train Autoencoder
optimizer = tf.keras.optimizers.Adam(lr=0.0005, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
autoencoder.compile(optimizer=optimizer, loss='mean_squared_error')
autoencoder.summary()
autoencoder.evaluate(label_ar, label_ar)
```
From the above evaluation the initial untrained loss is around 2500.
Now train the model:
```
ret = autoencoder.fit(label_ar, label_ar, batch_size=312, epochs=3, verbose=1, validation_split=0.2)
```
Now the encoder - decoder pair will be tested seperately for loss:
```
encoded_vec = encoder.predict(label_ar)
decoded_vec = decoder.predict(encoded_vec)
#compilation is only to enable evaluation
decoder.compile(optimizer='adam', loss='mse')
decoder.evaluate(encoded_vec, label_ar)
print(encoded_vec.shape)
print(decoded_vec.shape)
```
## LSTM
Here the lstm will be trained. The 8 channels of sEMG data will be processed by the LSTM, which will return a vector of 9 complex features. These will then be processed by the autoencoder, trained in the previous section, to create the 63 hand coordinates.
To train the sequential recurrent LSTM the data will be grouped into 'sequences' of 24 steps in time. The LSTM will be trained with many sequence groups.
```
seq_length = 24
def overlap_samples(seq_length, feats, labels):
new_l = labels[seq_length - 1:]
feat_list = [feats[i:i + seq_length] for i in range(feats.shape[0] - seq_length + 1)]
new_f = np.array(feat_list)
return new_f, new_l
features, labels = overlap_samples(seq_length, feature_ar, label_ar)
print(features.shape)
print(labels.shape)
```
### Attention
**This model will incorporate a component of attention**
### Model from phillip peremy
https://github.com/philipperemy/keras-attention-mechanism/blob/master/attention_lstm.py
Attention vector
Also, sometimes the time series can be N-dimensional. It could be interesting to have one atention vector per dimension. Let's
Attention can just then be a softmax applied to an output of something?
The permute function switches the positions of the axis and the dims argument tells how you want the final positions to be.
For example, if x is 4-dimensional and of the shape (None, 2, 4, 5, 8) - (None is the batch size here) and if you specify dims = (3, 2, 1, 4), then the following four steps will take place:
1. Third dimension will move to first
2. Second dimension will move to second
3. First dimension will move to third
4. Fourth dimension will move to fourth
Remember, the indexing starts at 1 and not 0. The dimension zero is the batch size. So finally the output
**RepeatVector**
Repeats the input vector n times
```
INPUT_DIM = 2
TIME_STEPS = 20
# if True, the attention vector is shared across the input_dimensions where the attention is applied.
SINGLE_ATTENTION_VECTOR = False
APPLY_ATTENTION_BEFORE_LSTM = False
def attention_3d_block(inputs):
# inputs.shape = (batch_size, time_steps, input_dim)
input_dim = int(inputs.shape[2])
a = Permute((2, 1))(inputs)
a = Reshape((input_dim, TIME_STEPS))(a) # this line is not useful. It's just to know which dimension is what.
a = Dense(TIME_STEPS, activation='softmax')(a)
if SINGLE_ATTENTION_VECTOR:
a = Lambda(lambda x: K.mean(x, axis=1), name='dim_reduction')(a)
a = RepeatVector(input_dim)(a)
a_probs = Permute((2, 1), name='attention_vec')(a)
output_attention_mul = Add()([inputs, a_probs])
return output_attention_mul
def model_attention_applied_after_lstm():
inputs = Input(shape=(TIME_STEPS, INPUT_DIM,))
lstm_units = 32
lstm_out = LSTM(lstm_units, return_sequences=True)(inputs)
attention_mul = attention_3d_block(lstm_out)
attention_mul = Flatten()(attention_mul)
output = Dense(1, activation='sigmoid')(attention_mul)
model = Model(inputs, output)
return model
model = model_attention_applied_after_lstm()
model.summary()
#from keras.layers.core import*
#from keras.models import Sequential
input_dim = 32
hidden = 32
#The LSTM model - output_shape = (batch, step, hidden)
model1 = Sequential()
model_fc.add(LSTM(64, return_sequences=True, input_shape=(seq_length, 8)))
model1.add(LSTM(input_dim=input_dim, output_dim=hidden, input_length=step, return_sequences=True))
#The weight model - actual output shape = (batch, step)
# after reshape : output_shape = (batch, step, hidden)
model2 = Sequential()
model2.add(Dense(input_dim=input_dim, output_dim=step))
model2.add(Activation('softmax')) # Learn a probability distribution over each step.
#Reshape to match LSTM's output shape, so that we can do element-wise multiplication.
model2.add(RepeatVector(hidden))
model2.add(Permute(2, 1))
#The final model which gives the weighted sum:
model = Sequential()
model.add(Merge([model1, model2], 'mul')) # Multiply each element with corresponding weight a[i][j][k] * b[i][j]
model.add(TimeDistributedMerge('sum')) # Sum the weighted elements.
model.compile(loss='mse', optimizer='sgd')
#lstm layers
inputs = Input(shape=(None, 8), name="inputs")
lstm_0 = LSTM(100, return_sequences=True, name="lstm_0")(inputs)
do = Dropout(0.4)(lstm_0)
lstm_1 = LSTM(100, return_sequences=False, name="lstm_1")(do)
do_2 = Dropout(0.4)(lstm_0)
lstm_1 = LSTM(100, return_sequences=False, name="lstm_1")(do_2)
attention = Dense(1, activation='tanh')(lstm_1)
attention = Flatten()(attention)
attention = Activation('softmax')(attention)
attention = RepeatVector(100)(attention)
attention = Permute([2, 1])(attention)
sent_representation = merge([lstm_1, attention])
attention = Activation('softmax')(attention)
lstm_out = Dense(9, activation=None, name="lstm_out")(sent_representation)
#decoder layers
decoder_0 = decoder.get_layer("decoder_0")(lstm_out)
decoder_0.trainable = False
decoder_1 = decoder.get_layer("decoder_1")(decoder_0)
decoder_1.trainable = False
decoder_output = decoder.get_layer("decoder_output")(decoder_1)
decoder_output.trainable = False
model = Model(inputs, decoder_output, name="model_v1")
optimizer = tf.keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.00, amsgrad=False)
model.compile(optimizer=optimizer, loss='mse')
model.summary()
```
### LSTM model
```
#lstm layers
inputs = Input(shape=(None, 8), name="inputs")
lstm_0 = LSTM(100, return_sequences=True, name="lstm_0")(inputs)
do = Dropout(0.4)(lstm_0)
lstm_1 = LSTM(100, return_sequences=False, name="lstm_1")(do)
do_2 = Dropout(0.4)(lstm_0)
lstm_1 = LSTM(100, return_sequences=False, name="lstm_1")(do_2)
lstm_out = Dense(9, activation=None, name="lstm_out")(lstm_1)
#decoder layers
decoder_0 = decoder.get_layer("decoder_0")(lstm_out)
decoder_0.trainable = False
decoder_1 = decoder.get_layer("decoder_1")(decoder_0)
decoder_1.trainable = False
decoder_output = decoder.get_layer("decoder_output")(decoder_1)
decoder_output.trainable = False
model = Model(inputs, decoder_output, name="model_v1")
optimizer = tf.keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.00, amsgrad=False)
model.compile(optimizer=optimizer, loss='mse')
model.summary()
model.evaluate(features, labels, verbose=1)
history = model.fit(features, labels, batch_size=seq_length, epochs=4, verbose=1, validation_split=0.2)
model.save('AE_jose_mega_val_loss_600_model.h5')
```
### Visualize Model Error
Plot the validation loss over the training epochs:
```
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.legend(['Train', 'Test'])
```
Plotting the errors for each field below shows that the 'y' coordinates for each figure generally have the largest error and the errors growing rapidly approaching the tips of the fingers.
```
preds = model.predict(features)
error = labels - preds
sq_error = error * error
avg_error = np.mean(sq_error, axis=0)
plt.figure(figsize=(15, 10))
plt.xticks(rotation=90)
plt.ylabel('Prediction Error (mm)')
bar = plt.bar(df.columns[8:], avg_error)
for i in range(0,63,3):
bar[i].set_color('coral')
bar[i+1].set_color('olivedrab')
plt.show()
```
## LSTM with Fully Connected Layers
Below is a test using a model with several dense layers after the LSTM layers, instead of using the pretrained autoencoder.
```
model_fc = tf.keras.models.Sequential()
model_fc.add(LSTM(64, return_sequences=True, input_shape=(seq_length, 8)))
model_fc.add(Dropout(0.2))
model_fc.add(LSTM(64))
model_fc.add(BatchNormalization())
model_fc.add(Dense(100, input_dim=64))
model_fc.add(Activation('relu'))
model_fc.add(BatchNormalization())
model_fc.add(Dropout(0.2))
model_fc.add(Dense(64, input_dim=64))
model_fc.add(Activation('relu'))
model_fc.add(Dropout(0.2))
model_fc.add(Dense(63, input_dim=64))
model_fc.compile(optimizer='Adam', loss='mse')
history = model_fc.fit(features, labels, batch_size=seq_length, epochs=5, verbose=1, validation_split=0.2)
model_fc.save('FC_model_jose_finger_4.h5')
```
### Visual Model Error
```
preds = model_fc.predict(features)
error = labels - preds
sq_error = error * error
avg_error = np.mean(sq_error, axis=0)
plt.figure(figsize=(15, 10))
plt.xticks(rotation=90)
plt.ylabel('Prediction Error (mm)')
bar = plt.bar(df.columns[8:], avg_error)
for i in range(0,63,3):
bar[i].set_color('coral')
bar[i+1].set_color('olivedrab')
plt.show()
```
## Training the Model On Tips Only
In an attempt to improve the accuracy of prediction of the fingertips the above models are modified and trained only using the fingertip position data to understand if this simplification yields an improvement. This is done on both of the architectures tested above.
### Autoencoder Architecture
```
encoding_dim = 9 #dimensionality of 'feature' vector
a_fn = None
# Full autoencoder
input_vec = Input(shape=(18,))
dense_0 = Dense(32, activation=a_fn)(input_vec)
dense_1 = Dense(16, activation=a_fn)(dense_0)
encoded = Dense(encoding_dim, activation=a_fn)(dense_1)
dense_2 = Dense(32, activation=a_fn, name='decoder_0')(encoded)
dense_3 = Dense(16, activation=a_fn, name='decoder_1')(dense_2)
decoded = Dense(18, activation=a_fn, name='decoder_output')(dense_3)
autoencoder = Model(input_vec, decoded)
# Encoder from autoencoder
encoder = Model(input_vec, encoded)
# Decoder from autoencoder layers
decoder_input = Input(shape=(encoding_dim,), name='encoded_input')
decode_0 = autoencoder.layers[-3](decoder_input)
decode_1 = autoencoder.layers[-2](decode_0)
decode_output = autoencoder.layers[-1](decode_1)
decoder = Model(decoder_input, decode_output, name='decoder')
# Train Autoencoder
optimizer = tf.keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
autoencoder.compile(optimizer=optimizer, loss='mean_squared_error')
label_ar_t = label_ar[:,[0,1,2,12,13,14,24,25,26,36,37,38,48,49,50,60,61,62]]
label_ar_t.shape
ret = autoencoder.fit(label_ar_t, label_ar_t, batch_size=512, epochs=30, verbose=1, validation_split=0.2)
```
Create a smaller labels vector with only the tip and wrist x,y,z:
```
labels_tip = labels[:,[0,1,2,12,13,14,24,25,26,36,37,38,48,49,50,60,61,62]]
labels_tip.shape
#lstm layers
inputs = Input(shape=(None, 8), name="inputs")
lstm_0 = LSTM(64, return_sequences=True, name="lstm_0")(inputs)
do = Dropout(0.2)(lstm_0)
lstm_1 = LSTM(64, return_sequences=False, name="lstm_1")(do)
lstm_out = Dense(9, activation=None, name="lstm_out")(lstm_1)
#decoder layers
decoder_0 = decoder.get_layer("decoder_0")(lstm_out)
decoder_0.trainable = False
decoder_1 = decoder.get_layer("decoder_1")(decoder_0)
decoder_1.trainable = False
decoder_output = decoder.get_layer("decoder_output")(decoder_1)
decoder_output.trainable = False
model = Model(inputs, decoder_output, name="model_v1")
optimizer = tf.keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.00, amsgrad=False)
model.compile(optimizer=optimizer, loss='mse')
model.summary()
history = model.fit(features, labels_tip, batch_size=seq_length, epochs=4, verbose=1, validation_split=0.2)
```
### Visual Model Error
Model error for the reduced Autoencoder architecture:
```
preds = model.predict(features)
error = labels_tip - preds
sq_error = error * error
avg_error = np.mean(sq_error, axis=0)
plt.figure(figsize=(15, 10))
plt.xticks(rotation=90)
plt.ylabel('Prediction Error (mm)')
bar = plt.bar(df.columns[8:][[0,1,2,12,13,14,24,25,26,36,37,38,48,49,50,60,61,62]], avg_error)
for i in range(0,18,3):
bar[i].set_color('coral')
bar[i+1].set_color('olivedrab')
plt.show()
```
### Tips only with FC Architecture
```
model_fc = tf.keras.models.Sequential()
model_fc.add(LSTM(64, return_sequences=True, input_shape=(seq_length, 8)))
model_fc.add(Dropout(0.2))
model_fc.add(LSTM(64))
model_fc.add(BatchNormalization())
model_fc.add(Dense(100, input_dim=64))
model_fc.add(Activation('relu'))
model_fc.add(BatchNormalization())
model_fc.add(Dropout(0.2))
model_fc.add(Dense(64, input_dim=64))
model_fc.add(Activation('relu'))
model_fc.add(Dropout(0.2))
model_fc.add(Dense(18, input_dim=64))
model_fc.summary()
model_fc.compile(optimizer='Adam', loss='mse')
history = model_fc.fit(features, labels_tip, batch_size=seq_length, epochs=9, verbose=1, validation_split=0.2)
```
### Visual Model Error
A similar visualizion is now done on this new more restricted model. These errors show 20% - 25% improvement on fingertip y position.
```
preds = model_fc.predict(features)
error = labels_tip - preds
sq_error = error * error
avg_error = np.mean(sq_error, axis=0)
plt.figure(figsize=(15, 10))
plt.xticks(rotation=90)
plt.ylabel('Prediction Error (mm)')
bar = plt.bar(df.columns[8:][[0,1,2,12,13,14,24,25,26,36,37,38,48,49,50,60,61,62]], avg_error)
for i in range(0,18,3):
bar[i].set_color('coral')
bar[i+1].set_color('olivedrab')
plt.show()
```
| github_jupyter |
# Train and Test a Logistic Regression Model
```
#install libraries
!pip install --upgrade pip
!pip install --upgrade scikit-learn
!pip install seaborn
!pip install pandas
import pandas as pd
import numpy as np
import pickle
from sklearn.metrics import auc, plot_confusion_matrix, plot_roc_curve, roc_auc_score
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
import seaborn as sns
import matplotlib.pyplot as plt
with open('numeric_columns.pickle', 'rb') as f:
nu_cols = pickle.load(f)
```
# Calculate optimal hyperparameters using grid search cross validation on one set of the complete data
- 5-fold cross validation
- use only the training set (keep the test set separate until after the final model has been built)
```
# fix random seed for reproducibility
seed = 78
np.random.seed(seed)
tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)
fig1, ax1 = plt.subplots()
imp = 5
with open('complete' + str(imp) + '.pickle', 'rb') as f:
dataset = pickle.load(f)
#dataset = dataset.iloc[0:100,:]
X_train = dataset[dataset.subset <= 6].copy().sort_values(by = 'usrds_id')
del dataset
y_train = np.array(X_train.pop('died_in_90'))
scaler = StandardScaler()
X_train[nu_cols] = scaler.fit_transform(X_train[nu_cols])
X_train = np.array(X_train.drop(columns=['subset','usrds_id','impnum']))
print('scaled shape train ' + str(X_train.shape))
lr_model = LogisticRegression()
param_grid = [{
'penalty':['l1','l2','elasticnet'],
'C': np.logspace(-3, 3, 10, 20),
'max_iter': [500, 1000, 1500],
'class_weight' :['balanced'],
#'solver':['saga']
}]
clf = GridSearchCV(
lr_model,
param_grid=param_grid,
cv=5,
verbose=True,
n_jobs=-1,
scoring='average_precision'
)
best_clf = clf.fit(X_train, y_train)
# save model
with open('2021_LR_cv_clf_imp_'+str(imp)+'.pickle', 'wb') as picklefile:
pickle.dump(clf,picklefile)
pred_proba_onc_train = clf.predict_proba(X_train)[:,1]
train_score = roc_auc_score(y_train, pred_proba_onc_train)
viz = plot_roc_curve(clf, X_train, y_train,
name='ROC imputation {}'.format(i),
alpha=0.3, lw=1, ax=ax1)
interp_tpr = np.interp(mean_fpr, viz.fpr, viz.tpr)
interp_tpr[0] = 0.0
tprs.append(interp_tpr)
aucs.append(viz.roc_auc)
print("ROC AUC on training data: {}".format(train_score))
print('best params /n ' )
print(clf.best_params_)
print('best score /n' )
print(clf.best_score_)
ax1.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',
label='Chance', alpha=.8)
mean_tpr = np.mean(tprs, axis=0)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
std_auc = np.std(aucs)
ax1.plot(mean_fpr, mean_tpr, color='b',
label=r'Mean ROC (AUC = %0.2f $\pm$ %0.2f)' % (mean_auc, std_auc),
lw=2, alpha=.8)
std_tpr = np.std(tprs, axis=0)
tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
ax1.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,
label=r'$\pm$ 1 std. dev.')
ax1.set(xlim=[-0.05, 1.05], ylim=[-0.05, 1.05],
title="Receiver operating characteristic")
ax1.legend(loc="lower right")
plt.show()
```
# Train and Test an LR model
- based on the best params from the previous step
- run the model for each of the 5 imputed datasets
- save the model
- plot figures
```
with open('2021_LR_cv_clf_imp_5.pickle', 'rb') as f:
clf = pickle.load(f)
clf.best_params_
seed = 78
np.random.seed(seed)
tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)
fig, ax = plt.subplots()
i=0
for i in range(5):
imp=i+1
with open('./complete' + str(imp) + '.pickle', 'rb') as f:
dataset = pickle.load(f)
train_x = dataset[dataset.subset <= 6].copy().sort_values(by = 'usrds_id')
test_x = dataset[dataset.subset > 6].copy().sort_values(by = 'usrds_id')
del dataset
train_y = np.array(train_x.pop('died_in_90'))
test_y = np.array(test_x.pop('died_in_90'))
scaler = StandardScaler()
train_x[nu_cols] = scaler.fit_transform(train_x[nu_cols])
train_x = np.array(train_x.drop(columns=['subset','usrds_id','impnum']))
print('scaled shape train ' + str(train_x.shape))
test_x[nu_cols] = scaler.transform(test_x[nu_cols])
test_x = np.array(test_x.drop(columns=['subset','usrds_id','impnum']))
print('scaled shape test ' + str(test_x.shape))
lr_model_final = LogisticRegression(C=0.1,
penalty='l2',
max_iter=1000,
solver='saga',
class_weight='balanced',
n_jobs=-1,
verbose=1,
random_state=499)
logistic_model_final = lr_model_final.fit(train_x, train_y)
# model evaluation
pred_proba_onc_test = logistic_model_final.predict_proba(test_x)#[:,1]
#save the predictions from each imputation
with open('2021_final_LR_model_test_pred_proba_imp_' + str(imp) + '.pickle', 'wb') as picklefile:
pickle.dump(pred_proba_onc_test, picklefile)
test_score = roc_auc_score(test_y, pred_proba_onc_test[:,1])
print("AVG precision on test data: {}".format(test_score))
LR_Y_pred = logistic_model_final.predict(test_x)
fig3 = plt.figure(figsize=(8, 8));
plot_cm = plot_confusion_matrix(
logistic_model_final, test_x, test_y,
cmap=plt.cm.Greens);
plt.show()
with open('2021_final_LR_model.pickle', 'wb') as picklefile:
pickle.dump(logistic_model_final,picklefile)
```
| github_jupyter |
# 卷积神经网络 Convolutional Neural Networks
<img src="https://raw.githubusercontent.com/GokuMohandas/practicalAI/master/images/logo.png" width=150>
本课程中,我们将学习基本的卷积神经网络(CNN),并应用到自然语言(NLP)处理中。CNN 常用于图像处理,并且有很多[例子](https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html)。但我们专注于将它用于文本数据,也有惊人的效果。
In this lesson we will learn the basics of Convolutional Neural Networks (CNNs) applied to text for natural language processing (NLP) tasks. CNNs are traditionally used on images and there are plenty of [tutorials](https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html) that cover this. But we're going to focus on using CNN on text data which yields amazing results.
# 总览 Overview
[论文](https://arxiv.org/abs/1510.03820)中图表展示了句子中的词如何进行一维卷积计算。
The diagram below from this [paper](https://arxiv.org/abs/1510.03820) shows how 1D convolution is applied to the words in a sentence.
<img src="https://raw.githubusercontent.com/GokuMohandas/practicalAI/master/images/cnn_text.png" width=500>
* **目的:** 检测输入数据的空间结构。Detect spatial substructure from input data.
* **优点:**
* 权重数量小(共享)Small number of weights (shared)
* 可并行的 Parallelizable
* 检测空间结构(特征提取)Detects spatial substrcutures (feature extractors)
* 通过滤波器可翻译的 Interpretable via filters
* 可用于图像、文本、时间序列等 Used for in images/text/time-series etc.
* **缺点:**
* 很多超参数(核大小,步幅等)Many hyperparameters (kernel size, strides, etc.)
* 输入宽度必须相同(图像维度,文本长度等)Inputs have to be of same width (image dimensions, text length, etc.)
* **其他:**
* 很多深度 CNN 框架持续更新 SOTA 性能 Lot's of deep CNN architectures constantly updated for SOTA performance
# 滤波器 Filters
CNN 的核心是滤波器(权重,核等),它通过对输入进行卷积计算,提取相关特征。虽然滤波器是随机初始化的,但可以学习从输入选取有意义的特征,有助于优化目标。我们将通过不寻常的方式介绍 CNN,聚焦应用于二维文本数据。每个输入有多个词组成,我们使用独热编码(one-hot encoder)表示每个词,得到一个二维输入。每个滤波器代表一个特征,我们将应用滤波器到其他输入,捕获相同特征。这也称为参数共享。
At the core of CNNs are filters (weights, kernels, etc.) which convolve (slide) across our input to extract relevant features. The filters are initialized randomly but learn to pick up meaningful features from the input that aid in optimizing for the objective. We're going to teach CNNs in an unorthodox method where we entirely focus on applying it to 2D text data. Each input is composed of words and we will be representing each word as one-hot encoded vector which gives us our 2D input. The intuition here is that each filter represents a feature and we will use this filter on other inputs to capture the same feature. This is known as parameter sharing.
<img src="https://raw.githubusercontent.com/GokuMohandas/madewithml/master/images/conv.gif" width=400>
```
# Loading PyTorch library
!pip3 install torch
import torch
import torch.nn as nn
```
我们的输入是一组二维文本数据。设定输入有64个样本,其中每个样本有8个词,每个词用一个长度为10的数组(词汇量为10的独热编码)表示。这样输入的体积为(64,8,10)。[Python CNN 模块](https://pytorch.org/docs/stable/nn.html#convolution-functions)倾向于输入的通道维度(本例中是一个独热编码向量)在第2个位置,所以我们的输入维度是(64,10,8)。
Our inputs are a batch of 2D text data. Let's make an input with 64 samples, where each sample has 8 words and each word is represented by a array of 10 values (one hot encoded with vocab size of 10). This gives our inputs the size (64, 8, 10). The [PyTorch CNN modules](https://pytorch.org/docs/stable/nn.html#convolution-functions) prefer inputs to have the channel dim (one hot vector dim in our case) to be in the second position, so our inputs are of shape (64, 10, 8).
<img src="https://raw.githubusercontent.com/GokuMohandas/madewithml/master/images/cnn_text1.png" width=400>
```
# Assume all our inputs have the same # of words
batch_size = 64
sequence_size = 8 # words per input
one_hot_size = 10 # vocab size (num_input_channels)
x = torch.randn(batch_size, one_hot_size, sequence_size)
print("Size: {}".format(x.shape))
```
使用滤波器对输入进行卷积运算。为了简单一点,我们使用5个(1,2)的滤波器,深度和通道数相同(独热编码大小)。这样,滤波器维度是(5,2,10)。但是如上所述, PyTorch 更倾向于通道维度在第2个位置,所以滤波器维度是(5,10,2)。
We want to convolve on this input using filters. For simplicity we will use just 5 filters that is of size (1, 2) and has the same depth as the number of channels (one_hot_size). This gives our filter a shape of (5, 2, 10) but recall that PyTorch CNN modules prefer to have the channel dim (one hot vector dim in our case) to be in the second position so the filter is of shape (5, 10, 2).
<img src="https://raw.githubusercontent.com/GokuMohandas/practicalAI/master/images/cnn_text2.png" width=400>
```
# Create filters for a conv layer
out_channels = 5 # of filters
kernel_size = 2 # filters size 2
conv1 = nn.Conv1d(in_channels=one_hot_size, out_channels=out_channels, kernel_size=kernel_size)
print("Size: {}".format(conv1.weight.shape))
print("Filter size: {}".format(conv1.kernel_size[0]))
print("Padding: {}".format(conv1.padding[0]))
print("Stride: {}".format(conv1.stride[0]))
```
我们在输入上使用这个滤波器,得到(64,5,7)的输出。64是样本大小,5是通道维度(因为使用了5个滤波器),7是卷积输出,因为:
$\frac{W - F + 2P}{S} + 1 = \frac{8 - 2 + 2(0)}{1} + 1 = 7$
其中:
* W:输入宽度
* F:滤波器大小
* P:填充
* S:步幅
When we apply this filter on our inputs, we receive an output of shape (64, 5, 7). We get 64 for the batch size, 5 for the channel dim because we used 5 filters and 7 for the conv outputs because:
$\frac{W - F + 2P}{S} + 1 = \frac{8 - 2 + 2(0)}{1} + 1 = 7$
where:
* W: width of each input
* F: filter size
* P: padding
* S: stride
<img src="https://raw.githubusercontent.com/GokuMohandas/practicalAI/master/images/cnn_text3.png" width=400>
```
# Convolve using filters
conv_output = conv1(x)
print("Size: {}".format(conv_output.shape))
```
# 池化 Pooling
对输入进行卷积计算的结果是一个特征映射。因为卷积和重叠,特征映射有很多冗余信息。池化是一种降维的方式。池化可以是一定接收域的最大值,平局值等。
The result of convolving filters on an input is a feature map. Due to the nature of convolution and overlaps, our feature map will have lots of redundant information. Pooling is a way to summarize a high-dimensional feature map into a lower dimensional one for simplified downstream computation. The pooling operation can be the max value, average, etc. in a certain receptive field.
<img src="https://raw.githubusercontent.com/GokuMohandas/practicalAI/master/images/pool.jpeg" width=450>
```
# Max pooling
kernel_size = 2
pool1 = nn.MaxPool1d(kernel_size=kernel_size, stride=2, padding=0)
pool_output = pool1(conv_output)
print("Size: {}".format(pool_output.shape))
```
$\frac{W-F}{S} + 1 = \frac{7-2}{2} + 1 = \text{floor }(2.5) + 1 = 3$
# CNN 文本处理 CNNs on text
我们正在用卷积神经网络处理文本数据,进行词级别的卷积计算,获取有用的n-grams(一种语言模型)。
你可以把这个配置用于[时间序列](https://arxiv.org/abs/1807.10707) 数据或者与其他神经网络相结合。对于文本数据,我们会建立不同大小的滤波器,(1,2),(1,3)和(1,4),他们用于不同 n-gram 的特征选取器。把输出拼接起来,输入到一个全连接网络。本例中,我们使用字符级的一维卷积。在 [embeddings notebook](https://colab.research.google.com/github/GokuMohandas/practicalAI/blob/master/notebooks/12_Embeddings.ipynb),我们在词级中应用了一维卷积。
**词嵌入**:捕获相邻词汇的临时联系,使得相似单词有相似意义。
**字符嵌入**:创建一个字符级别映射。例如"toy"和“toys”彼此接近。
We're going use convolutional neural networks on text data which typically involves convolving on the character level representation of the text to capture meaningful n-grams.
You can easily use this set up for [time series](https://arxiv.org/abs/1807.10707) data or [combine it](https://arxiv.org/abs/1808.04928) with other networks. For text data, we will create filters of varying kernel sizes (1,2), (1,3), and (1,4) which act as feature selectors of varying n-gram sizes. The outputs are concated and fed into a fully-connected layer for class predictions. In our example, we will be applying 1D convolutions on letter in a word. In the [embeddings notebook](https://colab.research.google.com/github/GokuMohandas/practicalAI/blob/master/notebooks/12_Embeddings.ipynb), we will apply 1D convolutions on words in a sentence.
**Word embeddings**: capture the temporal correlations among
adjacent tokens so that similar words have similar representations. Ex. "New Jersey" is close to "NJ" is close to "Garden State", etc.
**Char embeddings**: create representations that map words at a character level. Ex. "toy" and "toys" will be close to each other.
# 配置 Set up
```
import os
from argparse import Namespace
import collections
import copy
import json
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import re
import torch
# Set Numpy and PyTorch seeds
def set_seeds(seed, cuda):
np.random.seed(seed)
torch.manual_seed(seed)
if cuda:
torch.cuda.manual_seed_all(seed)
# Creating directories
def create_dirs(dirpath):
if not os.path.exists(dirpath):
os.makedirs(dirpath)
# Arguments
args = Namespace(
seed=1234,
cuda=False,
shuffle=True,
#data_file="names.csv",
data_file="names.csv",
vectorizer_file="vectorizer.json",
model_state_file="model.pth",
save_dir="names",
train_size=0.7,
val_size=0.15,
test_size=0.15,
num_epochs=20,
early_stopping_criteria=5,
learning_rate=1e-3,
batch_size=64,
num_filters=100,
dropout_p=0.1,
)
# Set seeds
set_seeds(seed=args.seed, cuda=args.cuda)
# Create save dir
create_dirs(args.save_dir)
# Expand filepaths
args.vectorizer_file = os.path.join(args.save_dir, args.vectorizer_file)
args.model_state_file = os.path.join(args.save_dir, args.model_state_file)
# Check CUDA
if not torch.cuda.is_available():
args.cuda = False
args.device = torch.device("cuda" if args.cuda else "cpu")
print("Using CUDA: {}".format(args.cuda))
```
# 数据 Data
```
import re
import urllib
# Upload data from GitHub to notebook's local drive
#url = "https://raw.githubusercontent.com/GokuMohandas/practicalAI/master/data/surnames.csv"
#url = "https://raw.githubusercontent.com/GokuMohandas/madewithml/main/datasets/surnames.csv"
#response = urllib.request.urlopen(url)
#html = response.read()
#with open(args.data_file, 'wb') as fp:
# fp.write(html)
# Raw data
#df = pd.read_csv(args.data_file, header=0)
df = pd.read_csv("/Users/xupeng/AI/practicalAI-cn/data/surnames.csv", header=0)
df.head()
# Split by nationality
by_nationality = collections.defaultdict(list)
for _, row in df.iterrows():
by_nationality[row.nationality].append(row.to_dict())
for nationality in by_nationality:
print ("{0}: {1}".format(nationality, len(by_nationality[nationality])))
# Create split data
final_list = []
for _, item_list in sorted(by_nationality.items()):
if args.shuffle:
np.random.shuffle(item_list)
n = len(item_list)
n_train = int(args.train_size*n)
n_val = int(args.val_size*n)
n_test = int(args.test_size*n)
# Give data point a split attribute
for item in item_list[:n_train]:
item['split'] = 'train'
for item in item_list[n_train:n_train+n_val]:
item['split'] = 'val'
for item in item_list[n_train+n_val:]:
item['split'] = 'test'
# Add to final list
final_list.extend(item_list)
# df with split datasets
split_df = pd.DataFrame(final_list)
split_df["split"].value_counts()
# Preprocessing
def preprocess_text(text):
text = ' '.join(word.lower() for word in text.split(" "))
text = re.sub(r"([.,!?])", r" \1 ", text)
text = re.sub(r"[^a-zA-Z.,!?]+", r" ", text)
return text
split_df.surname = split_df.surname.apply(preprocess_text)
split_df.head()
```
# 词汇表 Vocabulary
```
class Vocabulary(object):
def __init__(self, token_to_idx=None, add_unk=True, unk_token="<UNK>"):
# Token to index
if token_to_idx is None:
token_to_idx = {}
self.token_to_idx = token_to_idx
# Index to token
self.idx_to_token = {idx: token \
for token, idx in self.token_to_idx.items()}
# Add unknown token
self.add_unk = add_unk
self.unk_token = unk_token
if self.add_unk:
self.unk_index = self.add_token(self.unk_token)
def to_serializable(self):
return {'token_to_idx': self.token_to_idx,
'add_unk': self.add_unk, 'unk_token': self.unk_token}
@classmethod
def from_serializable(cls, contents):
return cls(**contents)
def add_token(self, token):
if token in self.token_to_idx:
index = self.token_to_idx[token]
else:
index = len(self.token_to_idx)
self.token_to_idx[token] = index
self.idx_to_token[index] = token
return index
def add_tokens(self, tokens):
return [self.add_token[token] for token in tokens]
def lookup_token(self, token):
if self.add_unk:
index = self.token_to_idx.get(token, self.unk_index)
else:
index = self.token_to_idx[token]
return index
def lookup_index(self, index):
if index not in self.idx_to_token:
raise KeyError("the index (%d) is not in the Vocabulary" % index)
return self.idx_to_token[index]
def __str__(self):
return "<Vocabulary(size=%d)>" % len(self)
def __len__(self):
return len(self.token_to_idx)
# Vocabulary instance
nationality_vocab = Vocabulary(add_unk=False)
for index, row in df.iterrows():
nationality_vocab.add_token(row.nationality)
print (nationality_vocab) # __str__
index = nationality_vocab.lookup_token("English")
print (index)
print (nationality_vocab.lookup_index(index))
```
# 向量化 Vectorizer
```
class SurnameVectorizer(object):
def __init__(self, surname_vocab, nationality_vocab):
self.surname_vocab = surname_vocab
self.nationality_vocab = nationality_vocab
def vectorize(self, surname):
one_hot_matrix_size = (len(surname), len(self.surname_vocab))
one_hot_matrix = np.zeros(one_hot_matrix_size, dtype=np.float32)
for position_index, character in enumerate(surname):
character_index = self.surname_vocab.lookup_token(character)
one_hot_matrix[position_index][character_index] = 1
return one_hot_matrix
def unvectorize(self, one_hot_matrix):
len_name = len(one_hot_matrix)
indices = np.zeros(len_name)
for i in range(len_name):
indices[i] = np.where(one_hot_matrix[i]==1)[0][0]
surname = [self.surname_vocab.lookup_index(index) for index in indices]
return surname
@classmethod
def from_dataframe(cls, df):
surname_vocab = Vocabulary(add_unk=True)
nationality_vocab = Vocabulary(add_unk=False)
# Create vocabularies
for index, row in df.iterrows():
for letter in row.surname: # char-level tokenization
surname_vocab.add_token(letter)
nationality_vocab.add_token(row.nationality)
return cls(surname_vocab, nationality_vocab)
@classmethod
def from_serializable(cls, contents):
surname_vocab = Vocabulary.from_serializable(contents['surname_vocab'])
nationality_vocab = Vocabulary.from_serializable(contents['nationality_vocab'])
return cls(surname_vocab, nationality_vocab)
def to_serializable(self):
return {'surname_vocab': self.surname_vocab.to_serializable(),
'nationality_vocab': self.nationality_vocab.to_serializable()}
# Vectorizer instance
vectorizer = SurnameVectorizer.from_dataframe(split_df)
print (vectorizer.surname_vocab)
print (vectorizer.nationality_vocab)
vectorized_surname = vectorizer.vectorize(preprocess_text("goku"))
print (np.shape(vectorized_surname))
print (vectorized_surname)
print (vectorizer.unvectorize(vectorized_surname))
```
**Note**: Unlike the bagged ont-hot encoding method in the MLP notebook, we are able to preserve the semantic structure of the surnames. We are able to use one-hot encoding here because we are using characters but when we process text with large vocabularies, this method simply can't scale. We'll explore embedding based methods in subsequent notebooks.
# 数据集 Dataset
```
from torch.utils.data import Dataset, DataLoader
class SurnameDataset(Dataset):
def __init__(self, df, vectorizer):
self.df = df
self.vectorizer = vectorizer
# Data splits
self.train_df = self.df[self.df.split=='train']
self.train_size = len(self.train_df)
self.val_df = self.df[self.df.split=='val']
self.val_size = len(self.val_df)
self.test_df = self.df[self.df.split=='test']
self.test_size = len(self.test_df)
self.lookup_dict = {'train': (self.train_df, self.train_size),
'val': (self.val_df, self.val_size),
'test': (self.test_df, self.test_size)}
self.set_split('train')
# Class weights (for imbalances)
class_counts = df.nationality.value_counts().to_dict()
def sort_key(item):
return self.vectorizer.nationality_vocab.lookup_token(item[0])
sorted_counts = sorted(class_counts.items(), key=sort_key)
frequencies = [count for _, count in sorted_counts]
self.class_weights = 1.0 / torch.tensor(frequencies, dtype=torch.float32)
@classmethod
def load_dataset_and_make_vectorizer(cls, df):
train_df = df[df.split=='train']
return cls(df, SurnameVectorizer.from_dataframe(train_df))
@classmethod
def load_dataset_and_load_vectorizer(cls, df, vectorizer_filepath):
vectorizer = cls.load_vectorizer_only(vectorizer_filepath)
return cls(df, vectorizer)
def load_vectorizer_only(vectorizer_filepath):
with open(vectorizer_filepath) as fp:
return SurnameVectorizer.from_serializable(json.load(fp))
def save_vectorizer(self, vectorizer_filepath):
with open(vectorizer_filepath, "w") as fp:
json.dump(self.vectorizer.to_serializable(), fp)
def set_split(self, split="train"):
self.target_split = split
self.target_df, self.target_size = self.lookup_dict[split]
def __str__(self):
return "<Dataset(split={0}, size={1})".format(
self.target_split, self.target_size)
def __len__(self):
return self.target_size
def __getitem__(self, index):
row = self.target_df.iloc[index]
surname_vector = self.vectorizer.vectorize(row.surname)
nationality_index = self.vectorizer.nationality_vocab.lookup_token(row.nationality)
return {'surname': surname_vector, 'nationality': nationality_index}
def get_num_batches(self, batch_size):
return len(self) // batch_size
def generate_batches(self, batch_size, collate_fn, shuffle=True,
drop_last=True, device="cpu"):
dataloader = DataLoader(dataset=self, batch_size=batch_size,
collate_fn=collate_fn, shuffle=shuffle,
drop_last=drop_last)
for data_dict in dataloader:
out_data_dict = {}
for name, tensor in data_dict.items():
out_data_dict[name] = data_dict[name].to(device)
yield out_data_dict
# Dataset instance
dataset = SurnameDataset.load_dataset_and_make_vectorizer(split_df)
print (dataset) # __str__
print (np.shape(dataset[5]['surname'])) # __getitem__
print (dataset.class_weights)
```
# 模型 Model
```
import torch.nn as nn
import torch.nn.functional as F
class SurnameModel(nn.Module):
def __init__(self, num_input_channels, num_output_channels, num_classes, dropout_p):
super(SurnameModel, self).__init__()
# Conv weights
self.conv = nn.ModuleList([nn.Conv1d(num_input_channels, num_output_channels,
kernel_size=f) for f in [2,3,4]])
self.dropout = nn.Dropout(dropout_p)
# FC weights
self.fc1 = nn.Linear(num_output_channels*3, num_classes)
def forward(self, x, channel_first=False, apply_softmax=False):
# Rearrange input so num_input_channels is in dim 1 (N, C, L)
if not channel_first:
x = x.transpose(1, 2)
# Conv outputs
z = [conv(x) for conv in self.conv]
z = [F.max_pool1d(zz, zz.size(2)).squeeze(2) for zz in z]
z = [F.relu(zz) for zz in z]
# Concat conv outputs
z = torch.cat(z, 1)
z = self.dropout(z)
# FC layer
y_pred = self.fc1(z)
if apply_softmax:
y_pred = F.softmax(y_pred, dim=1)
return y_pred
```
# 训练 Training
**填充:** 输入必须有相同的维度。我们的向量器把输入向量化,但是特殊的批次中,我们可能碰到不同大小的输入。解决方法是找到最长的输入,把其他的填充到这个长度。通常,数量最小的输入批次,用0向量填充。
我们使用 Trainer 类中的 pad_seq 函数,由 collate_fn 触发,传递到 Dataset 类中的 generate_batches 函数。基本上,批次生成器产生样本,我们使用 collate_fn 确定最大的输入,填充批次中的其他输入,得到一个统一的输入维度。
**Padding:** the inputs in a particular batch must all have the same shape. Our vectorizer converts the tokens into a vectorizer form but in a particular batch, we can have inputs of various sizes. The solution is to determine the longest input in a particular batch and pad all the other inputs to match that length. Usually, the smaller inputs in the batch are padded with zero vectors.
We do this using the pad_seq function in the Trainer class which is invoked by the collate_fn which is passed to generate_batches function in the Dataset class. Essentially, the batch generater generates samples into a batch and we use the collate_fn to determine the largest input and pad all the other inputs in the batch to get a uniform input shape.
```
import torch.optim as optim
class Trainer(object):
def __init__(self, dataset, model, model_state_file, save_dir, device, shuffle,
num_epochs, batch_size, learning_rate, early_stopping_criteria):
self.dataset = dataset
self.class_weights = dataset.class_weights.to(device)
self.model = model.to(device)
self.save_dir = save_dir
self.device = device
self.shuffle = shuffle
self.num_epochs = num_epochs
self.batch_size = batch_size
self.loss_func = nn.CrossEntropyLoss(self.class_weights)
self.optimizer = optim.Adam(self.model.parameters(), lr=learning_rate)
self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(
optimizer=self.optimizer, mode='min', factor=0.5, patience=1)
self.train_state = {
'done_training': False,
'stop_early': False,
'early_stopping_step': 0,
'early_stopping_best_val': 1e8,
'early_stopping_criteria': early_stopping_criteria,
'learning_rate': learning_rate,
'epoch_index': 0,
'train_loss': [],
'train_acc': [],
'val_loss': [],
'val_acc': [],
'test_loss': -1,
'test_acc': -1,
'model_filename': model_state_file}
def update_train_state(self):
# Verbose
print ("[EPOCH]: {0} | [LR]: {1} | [TRAIN LOSS]: {2:.2f} | [TRAIN ACC]: {3:.1f}% | [VAL LOSS]: {4:.2f} | [VAL ACC]: {5:.1f}%".format(
self.train_state['epoch_index'], self.train_state['learning_rate'],
self.train_state['train_loss'][-1], self.train_state['train_acc'][-1],
self.train_state['val_loss'][-1], self.train_state['val_acc'][-1]))
# Save one model at least
if self.train_state['epoch_index'] == 0:
torch.save(self.model.state_dict(), self.train_state['model_filename'])
self.train_state['stop_early'] = False
# Save model if performance improved
elif self.train_state['epoch_index'] >= 1:
loss_tm1, loss_t = self.train_state['val_loss'][-2:]
# If loss worsened
if loss_t >= self.train_state['early_stopping_best_val']:
# Update step
self.train_state['early_stopping_step'] += 1
# Loss decreased
else:
# Save the best model
if loss_t < self.train_state['early_stopping_best_val']:
torch.save(self.model.state_dict(), self.train_state['model_filename'])
# Reset early stopping step
self.train_state['early_stopping_step'] = 0
# Stop early ?
self.train_state['stop_early'] = self.train_state['early_stopping_step'] \
>= self.train_state['early_stopping_criteria']
return self.train_state
def compute_accuracy(self, y_pred, y_target):
_, y_pred_indices = y_pred.max(dim=1)
n_correct = torch.eq(y_pred_indices, y_target).sum().item()
return n_correct / len(y_pred_indices) * 100
def pad_seq(self, seq, length):
vector = np.zeros((length, len(self.dataset.vectorizer.surname_vocab)),
dtype=np.int64)
for i in range(len(seq)):
vector[i] = seq[i]
return vector
def collate_fn(self, batch):
# Make a deep copy
batch_copy = copy.deepcopy(batch)
processed_batch = {"surname": [], "nationality": []}
# Get max sequence length
max_seq_len = max([len(sample["surname"]) for sample in batch_copy])
# Pad
for i, sample in enumerate(batch_copy):
seq = sample["surname"]
nationality = sample["nationality"]
padded_seq = self.pad_seq(seq, max_seq_len)
processed_batch["surname"].append(padded_seq)
processed_batch["nationality"].append(nationality)
# Convert to appropriate tensor types
processed_batch["surname"] = torch.FloatTensor(
processed_batch["surname"]) # need float for conv operations
processed_batch["nationality"] = torch.LongTensor(
processed_batch["nationality"])
return processed_batch
def run_train_loop(self):
for epoch_index in range(self.num_epochs):
self.train_state['epoch_index'] = epoch_index
# Iterate over train dataset
# initialize batch generator, set loss and acc to 0, set train mode on
self.dataset.set_split('train')
batch_generator = self.dataset.generate_batches(
batch_size=self.batch_size, collate_fn=self.collate_fn,
shuffle=self.shuffle, device=self.device)
running_loss = 0.0
running_acc = 0.0
self.model.train()
for batch_index, batch_dict in enumerate(batch_generator):
# zero the gradients
self.optimizer.zero_grad()
# compute the output
y_pred = self.model(batch_dict['surname'])
# compute the loss
loss = self.loss_func(y_pred, batch_dict['nationality'])
loss_t = loss.item()
running_loss += (loss_t - running_loss) / (batch_index + 1)
# compute gradients using loss
loss.backward()
# use optimizer to take a gradient step
self.optimizer.step()
# compute the accuracy
acc_t = self.compute_accuracy(y_pred, batch_dict['nationality'])
running_acc += (acc_t - running_acc) / (batch_index + 1)
self.train_state['train_loss'].append(running_loss)
self.train_state['train_acc'].append(running_acc)
# Iterate over val dataset
# initialize batch generator, set loss and acc to 0; set eval mode on
self.dataset.set_split('val')
batch_generator = self.dataset.generate_batches(
batch_size=self.batch_size, collate_fn=self.collate_fn,
shuffle=self.shuffle, device=self.device)
running_loss = 0.
running_acc = 0.
self.model.eval()
for batch_index, batch_dict in enumerate(batch_generator):
# compute the output
y_pred = self.model(batch_dict['surname'])
# compute the loss
loss = self.loss_func(y_pred, batch_dict['nationality'])
loss_t = loss.to("cpu").item()
running_loss += (loss_t - running_loss) / (batch_index + 1)
# compute the accuracy
acc_t = self.compute_accuracy(y_pred, batch_dict['nationality'])
running_acc += (acc_t - running_acc) / (batch_index + 1)
self.train_state['val_loss'].append(running_loss)
self.train_state['val_acc'].append(running_acc)
self.train_state = self.update_train_state()
self.scheduler.step(self.train_state['val_loss'][-1])
if self.train_state['stop_early']:
break
def run_test_loop(self):
# initialize batch generator, set loss and acc to 0; set eval mode on
self.dataset.set_split('test')
batch_generator = self.dataset.generate_batches(
batch_size=self.batch_size, collate_fn=self.collate_fn,
shuffle=self.shuffle, device=self.device)
running_loss = 0.0
running_acc = 0.0
self.model.eval()
for batch_index, batch_dict in enumerate(batch_generator):
# compute the output
y_pred = self.model(batch_dict['surname'])
# compute the loss
loss = self.loss_func(y_pred, batch_dict['nationality'])
loss_t = loss.item()
running_loss += (loss_t - running_loss) / (batch_index + 1)
# compute the accuracy
acc_t = self.compute_accuracy(y_pred, batch_dict['nationality'])
running_acc += (acc_t - running_acc) / (batch_index + 1)
self.train_state['test_loss'] = running_loss
self.train_state['test_acc'] = running_acc
def plot_performance(self):
# Figure size
plt.figure(figsize=(15,5))
# Plot Loss
plt.subplot(1, 2, 1)
plt.title("Loss")
plt.plot(trainer.train_state["train_loss"], label="train")
plt.plot(trainer.train_state["val_loss"], label="val")
plt.legend(loc='upper right')
# Plot Accuracy
plt.subplot(1, 2, 2)
plt.title("Accuracy")
plt.plot(trainer.train_state["train_acc"], label="train")
plt.plot(trainer.train_state["val_acc"], label="val")
plt.legend(loc='lower right')
# Save figure
plt.savefig(os.path.join(self.save_dir, "performance.png"))
# Show plots
plt.show()
def save_train_state(self):
self.train_state["done_training"] = True
with open(os.path.join(self.save_dir, "train_state.json"), "w") as fp:
json.dump(self.train_state, fp)
# Initialization
dataset = SurnameDataset.load_dataset_and_make_vectorizer(split_df)
dataset.save_vectorizer(args.vectorizer_file)
vectorizer = dataset.vectorizer
model = SurnameModel(num_input_channels=len(vectorizer.surname_vocab),
num_output_channels=args.num_filters,
num_classes=len(vectorizer.nationality_vocab),
dropout_p=args.dropout_p)
print (model.named_modules)
# Train
trainer = Trainer(dataset=dataset, model=model,
model_state_file=args.model_state_file,
save_dir=args.save_dir, device=args.device,
shuffle=args.shuffle, num_epochs=args.num_epochs,
batch_size=args.batch_size, learning_rate=args.learning_rate,
early_stopping_criteria=args.early_stopping_criteria)
trainer.run_train_loop()
# Plot performance
trainer.plot_performance()
# Test performance
trainer.run_test_loop()
print("Test loss: {0:.2f}".format(trainer.train_state['test_loss']))
print("Test Accuracy: {0:.1f}%".format(trainer.train_state['test_acc']))
# Save all results
trainer.save_train_state()
```
# 预测 Inference
```
class Inference(object):
def __init__(self, model, vectorizer, device="cpu"):
self.model = model.to(device)
self.vectorizer = vectorizer
self.device = device
def predict_nationality(self, dataset):
# Batch generator
batch_generator = dataset.generate_batches(
batch_size=len(dataset), shuffle=False, device=self.device)
self.model.eval()
# Predict
for batch_index, batch_dict in enumerate(batch_generator):
# compute the output
y_pred = self.model(batch_dict['surname'], apply_softmax=True)
# Top k nationalities
y_prob, indices = torch.topk(y_pred, k=len(self.vectorizer.nationality_vocab))
probabilities = y_prob.detach().to('cpu').numpy()[0]
indices = indices.detach().to('cpu').numpy()[0]
results = []
for probability, index in zip(probabilities, indices):
nationality = self.vectorizer.nationality_vocab.lookup_index(index)
results.append({'nationality': nationality, 'probability': probability})
return results
# Load vectorizer
with open(args.vectorizer_file) as fp:
vectorizer = SurnameVectorizer.from_serializable(json.load(fp))
# Load the model
model = SurnameModel(num_input_channels=len(vectorizer.surname_vocab),
num_output_channels=args.num_filters,
num_classes=len(vectorizer.nationality_vocab),
dropout_p=args.dropout_p)
model.load_state_dict(torch.load(args.model_state_file))
print (model.named_modules)
# Initialize
inference = Inference(model=model, vectorizer=vectorizer, device=args.device)
class InferenceDataset(Dataset):
def __init__(self, df, vectorizer):
self.df = df
self.vectorizer = vectorizer
self.target_size = len(self.df)
def __str__(self):
return "<Dataset(size={1})>".format(self.target_size)
def __len__(self):
return self.target_size
def __getitem__(self, index):
row = self.df.iloc[index]
surname_vector = self.vectorizer.vectorize(row.surname)
return {'surname': surname_vector}
def get_num_batches(self, batch_size):
return len(self) // batch_size
def generate_batches(self, batch_size, shuffle=True, drop_last=False, device="cpu"):
dataloader = DataLoader(dataset=self, batch_size=batch_size,
shuffle=shuffle, drop_last=drop_last)
for data_dict in dataloader:
out_data_dict = {}
for name, tensor in data_dict.items():
out_data_dict[name] = data_dict[name].to(device)
yield out_data_dict
# Inference
surname = input("Enter a surname to classify: ")
infer_df = pd.DataFrame([surname], columns=['surname'])
infer_df.surname = infer_df.surname.apply(preprocess_text)
infer_dataset = InferenceDataset(infer_df, vectorizer)
results = inference.predict_nationality(dataset=infer_dataset)
results
```
# 批量正则化 Batch normalization
尽管我们对输入做了标准化,有零平均值和单元方差,帮助收敛。在训练过程中,输入随着穿过不同层和非线性化,也在变化。这也称为内变量移位,它使训练变慢,并且需要更小的学习率。解决方法是[批量正则化](https://arxiv.org/abs/1502.03167)(batchnorm) ,把正则化作为模型架构的一部分。这使得我们可以使用更大的学习率,或的更好的性能,速度更快。
$ BN = \frac{a - \mu_{x}}{\sqrt{\sigma^2_{x} + \epsilon}} * \gamma + \beta $
其中:
* $a$ = 激活函数 | $\in \mathbb{R}^{NXH}$ ($N$ 是样本数, $H$ 是隐含层维度)
* $ \mu_{x}$ = 每个隐含层均值 | $\in \mathbb{R}^{1XH}$
* $\sigma^2_{x}$ = 每个隐含层方差 | $\in \mathbb{R}^{1XH}$
* $\epsilon$ = 噪声
* $\gamma$ = 比例参数(已学习的参数)
* $\beta$ = 移位参数 (已学习的参数)
Even though we standardized our inputs to have zero mean and unit variance to aid with convergence, our inputs change during training as they go through the different layers and nonlinearities. This is known as internal covariate shift and it slows down training and requires us to use smaller learning rates. The solution is [batch normalization](https://arxiv.org/abs/1502.03167) (batchnorm) which makes normalization a part of the model's architecture. This allows us to use much higher learning rates and get better performance, faster.
$ BN = \frac{a - \mu_{x}}{\sqrt{\sigma^2_{x} + \epsilon}} * \gamma + \beta $
where:
* $a$ = activation | $\in \mathbb{R}^{NXH}$ ($N$ is the number of samples, $H$ is the hidden dim)
* $ \mu_{x}$ = mean of each hidden | $\in \mathbb{R}^{1XH}$
* $\sigma^2_{x}$ = variance of each hidden | $\in \mathbb{R}^{1XH}$
* $\epsilon$ = noise
* $\gamma$ = scale parameter (learned parameter)
* $\beta$ = shift parameter (learned parameter)
但是在非线性操作之前,激活函数进行零平均值和单元方差的意义是什么呢?它不是整个激活矩阵都有的属性,只是替代了应用于隐含层维度(本例中是 num_output_channels)的批量正则化。所以计算了每个批次所有样本在每个隐含层的均值和方差。同样的,batchnorm 使用计算的训练中激活函数均值和方差。然而,测试时,因为模型使用训练中保存的均值和方差,可能使模型不准确。PyTorch 的 [BatchNorm](https://pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d) 会全部自动处理。
But what does it mean for our activations to have zero mean and unit variance before the nonlinearity operation. It doesn't mean that the entire activation matrix has this property but instead batchnorm is applied on the hidden (num_output_channels in our case) dimension. So each hidden's mean and variance is calculated using all samples across the batch. Also, batchnorm uses the calcualted mean and variance of the activations in the batch during training. However, during test, the sample size could be skewed so the model uses the saved population mean and variance from training. PyTorch's [BatchNorm](https://pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d) class takes care of all of this for us automatically.
<img src="https://raw.githubusercontent.com/GokuMohandas/practicalAI/master/images/batchnorm.png" width=400>
```
# Model with batch normalization
class SurnameModel_BN(nn.Module):
def __init__(self, num_input_channels, num_output_channels, num_classes, dropout_p):
super(SurnameModel_BN, self).__init__()
# Conv weights
self.conv = nn.ModuleList([nn.Conv1d(num_input_channels, num_output_channels,
kernel_size=f) for f in [2,3,4]])
self.conv_bn = nn.ModuleList([nn.BatchNorm1d(num_output_channels) # define batchnorms
for i in range(3)])
self.dropout = nn.Dropout(dropout_p)
# FC weights
self.fc1 = nn.Linear(num_output_channels*3, num_classes)
def forward(self, x, channel_first=False, apply_softmax=False):
# Rearrange input so num_input_channels is in dim 1 (N, C, L)
if not channel_first:
x = x.transpose(1, 2)
# Conv outputs
z = [F.relu(conv_bn(conv(x))) for conv, conv_bn in zip(self.conv, self.conv_bn)]
z = [F.max_pool1d(zz, zz.size(2)).squeeze(2) for zz in z]
# Concat conv outputs
z = torch.cat(z, 1)
z = self.dropout(z)
# FC layer
y_pred = self.fc1(z)
if apply_softmax:
y_pred = F.softmax(y_pred, dim=1)
return y_pred
# Initialization
dataset = SurnameDataset.load_dataset_and_make_vectorizer(split_df)
dataset.save_vectorizer(args.vectorizer_file)
vectorizer = dataset.vectorizer
model = SurnameModel_BN(num_input_channels=len(vectorizer.surname_vocab),
num_output_channels=args.num_filters,
num_classes=len(vectorizer.nationality_vocab),
dropout_p=args.dropout_p)
print (model.named_modules)
```
You can train this model with batch normalization and you'll notice that the validation results improve by ~2-5%.
```
# Train
trainer = Trainer(dataset=dataset, model=model,
model_state_file=args.model_state_file,
save_dir=args.save_dir, device=args.device,
shuffle=args.shuffle, num_epochs=args.num_epochs,
batch_size=args.batch_size, learning_rate=args.learning_rate,
early_stopping_criteria=args.early_stopping_criteria)
trainer.run_train_loop()
# Plot performance
trainer.plot_performance()
# Test performance
trainer.run_test_loop()
print("Test loss: {0:.2f}".format(trainer.train_state['test_loss']))
print("Test Accuracy: {0:.1f}%".format(trainer.train_state['test_acc']))
```
# 待完善 TODO
* 图像分类例子
* 切片
* 深度 CNN 架构
* 小的 3X3 滤波器
* 填充和步幅的细节(控制接收域,使每个像素作为滤波器中心)
* 嵌套网络(1x1 卷积)
* 残差连接/残差块
* 可解释性(n-grams 火)
* image classification example
* segmentation
* deep CNN architectures
* small 3X3 filters
* details on padding and stride (control receptive field, make every pixel the center of the filter, etc.)
* network-in-network (1x1 conv)
* residual connections / residual block
* interpretability (which n-grams fire)
| github_jupyter |
# Sampling of Signals
*This Jupyter notebook is part of a [collection of notebooks](../index.ipynb) in the bachelors module Signals and Systems, Comunications Engineering, Universität Rostock. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).*
## Ideal Sampling and Reconstruction
[Digital signal processors](https://en.wikipedia.org/wiki/Digital_signal_processor) and general purpose processors can only perform arithmetic operations within a limited number range. So far we considered continuous signals which are continuous with respect to time and its amplitude values. Such signals cannot be handled by processors in a straightforward manner. In order to obtain a digital representation of a continuous signal, a discretization has to be performed both in time and amplitude. The former is known as [*sampling*](https://en.wikipedia.org/wiki/Sampling_%28signal_processing%29), the latter as [*quantization*](https://en.wikipedia.org/wiki/Quantization_%28signal_processing%29). Sampling refers to the process of picking amplitude values from a continuous signal at discrete time-instants. The sampled signal is referred to as *discrete signal*. Quantization refers to the process of mapping a continuous amplitude to a countable set of amplitude values. The quantized signal is referred to as *quantized signal*. A signal which is discrete and quantized is termed a *digital signal*. This is illustrated in the following

The order of sampling and quantization can be exchanged under the assumption that both are memoryless processes. Only digital signals can be handled by digital signal or general purpose processors. The sampling of signals is discussed as a first step towards a digital signal.
### Model of Ideal Sampling
A continuous signal $x(t)$ is sampled by taking its amplitude values at given time-instants. These time-instants can be chosen arbitrary in time, but most common are equidistant sampling schemes. The process of sampling is modeled by multiplying the continuous signal with a series of Dirac impulses. This constitutes an idealized model since Dirac impulses cannot be realized in practice.
For equidistant sampling of a continuous signal $x(t)$ with sampling interval $T$, the sampled signal $x_\text{s}(t)$ reads
\begin{equation}
x_\text{s}(t) = \sum_{k = - \infty}^{\infty} x(t) \cdot \delta(t - k T) = \sum_{k = - \infty}^{\infty} x(k T) \cdot \delta(t - k T)
\end{equation}
where the [multiplication property](../continuous_signals/standard_signals.ipynb#Dirac-Impulse) of the Dirac impulse was used for the last equality. The sampled signal is composed from a series of equidistant Dirac impulse which are weighted by the amplitude values of the continuous signal taken at their time-instants.

The series of Dirac impulse is represented conveniently by the [Dirac comb](../periodic_signals/spectrum.ipynb#The-Dirac-Comb). Rewriting the sampled signal yields
\begin{equation}
x_\text{s}(t) = x(t) \cdot \frac{1}{T} {\bot \!\! \bot \!\! \bot} \left( \frac{t}{T} \right)
\end{equation}
The process of sampling can be modeled by multipyling the continuous signal $x(t)$ with a Dirac comb. The samples $x(k T)$ for $k \in \mathbb{Z}$ of the continuous signal constitute the [discrete (-time) signal](https://en.wikipedia.org/wiki/Discrete-time_signal) $x[k] := x(k T)$. The question arises if and under which conditions the samples $x[k]$ fully represent the continuous signal and allow for a reconstruction of the analog signal. In order to investigate this, the spectrum of the sampled signal is derived.
### Spectrum of Sampled Signal
The spectrum $X_\text{s}(j \omega) = \mathcal{F} \{ x_\text{s}(t) \}$ of the sampled signal $x_\text{s}(t)$ is derived by applying the [multiplication theorem](../fourier_transform/theorems.ipynb#Multiplication-Theorem) to the representation of the sampled signal using the Dirac comb
\begin{equation}
\begin{split}
X_\text{s}(j \omega) &= \frac{1}{2 \pi} X(j \omega) * {\bot \!\! \bot \!\! \bot} \left( \frac{\omega}{\omega_\text{s}} \right) \\
&= \frac{1}{2 \pi} X(j \omega) * \frac{2 \pi}{T} \sum_{\mu = - \infty}^{\infty} \delta(\omega - \mu \omega_\text{s}) \\
&= \frac{1}{T} \sum_{\mu = - \infty}^{\infty} X \left(j (\omega - \mu \omega_\text{s}) \right)
\end{split}
\end{equation}
where $X(j \omega) = \mathcal{F} \{ x(t) \}$ denotes the Fourier transform of the continuous signal, $\omega_\text{s} = 2 \pi \, f_\text{s}$ the angluar sampling frequency and $f_\text{s} = \frac{1}{T}$ the sampling frequency. The second equality results from the definition of the Dirac comb and the scaling property of the Dirac impulse, the third from its sifting property. The spectrum of the sampled signal consists of a superposition of shifted copies of the spectrum of the continuous signal. The resulting spectrum is periodic with a period of $\omega_\text{s}$. It can be concluded, that equidistant sampling generates repetitions of the spectrum of the continuous signal.
The spectrum $X_\text{s}(j \omega)$ of a sampled signal is illustrated at the example of a real-valued low-pass signal. A low-pass signal $x(t)$ is a signal with band-limited spectrum
\begin{equation}
X(j \omega) = 0 \qquad \text{for } |\omega| > \omega_\text{u}
\end{equation}
where $\omega_\text{u}$ denotes its upper frequency limit. For ease of illustration, the generic spectrum of a continuous real-valued low-pass signal is depicted by a triangle-shaped spectrum

The spectrum of the sampled signal is constructed by superimposing shifted copies of the spectrum of the continuous low-pass signal $X(j \omega)$ at multiples of $\omega_\text{s}$

It can be concluded from the illustration, that
* the shifted copies of $X(j \omega)$ do not overlap if $\omega_\text{u} < \frac{\omega_\text{s}}{2}$. For $|\omega| < \omega_\text{u}$ the spectrum of the continuous signal is not affected by overlapping
* for $\omega_\text{u} > \frac{\omega_\text{s}}{2}$ overlapping occurs which changes the spectrum of the continuous signal within $|\omega| < \omega_\text{u}$
### Ideal Reconstruction
The question arises if and under which conditions the continuous signal can be recovered from the sampled signal. Above consideration revealed that the spectrum $X_\text{s}(j \omega)$ of the sampled signal contains the unaltered spectrum of the continuous signal $X(j \omega)$ if $\omega_\text{u} < \frac{\omega_\text{s}}{2}$. Hence, the continuous signal can be reconstructed from the sampled signal by extracting the spectrum of the continuous signal from the spectrum of the sampled signal. This can be done by applying an [ideal low-pass](../system_properties/idealized_systems.ipynb#Ideal-Low-Pass) with cut-off frequency $\omega_\text{c} = \frac{\omega_{s}}{2}$. This is illustrated in the following

where the blue line represents the spectrum of the sampled signal and the red line the spectrum of the ideal low-pass. The transfer function $H(j \omega)$ of the low-pass reads
\begin{equation}
H(j \omega) = T \cdot \text{rect} \left( \frac{\omega}{\omega_\text{s}} \right)
\end{equation}
Its impulse response $h(t)$ is yielded by inverse Fourier transform of the transfer function
\begin{equation}
h(t) = \text{sinc} \left( \frac{\pi t}{T} \right)
\end{equation}
The reconstructed signal $y(t)$ is given by convolving the sampled signal $x_\text{s}(t)$ with the impulse response of the low-pass filter. This yields
\begin{align}
y(t) &= x_\text{s}(t) * h(t) \\
&= \left( \sum_{k = - \infty}^{\infty} x(k T) \cdot \delta(t - k T) \right) * \text{sinc} \left( \frac{\pi t}{T} \right) \\
&= \sum_{k = - \infty}^{\infty} x(k T) \cdot \text{sinc} \left( \frac{\pi}{T} (t - k T) \right)
\end{align}
where for the last equality the fact was exploited that $x(k T)$ is independent of the time $t$ for which the convolution is performed. The reconstructed signal is given by a weighted superposition of shifted sinc functions. Their weights are given by the samples $x(k T)$ of the continuous signal. The reconstruction is illustrated in the following figure

The black boxes show the samples $x(k T)$ of the continuous signal, the blue line the reconstructed signal $y(t)$, the gray lines the weighted sinc functions. The sinc function for $k = 0$ is highlighted in red. The amplitudes $x(k T)$ at the sampled positions are reconstructed perfectly since
\begin{equation}
\text{sinc} ( \frac{\pi}{T} (t - k T) ) = \begin{cases}
\text{sinc}(0) = 1 & \text{for } t=k T \\
\text{sinc}(n \pi) = 0 & \text{for } t=(k+n) T \quad , n \in \mathbb{Z} \notin \{0\}
\end{cases}
\end{equation}
The amplitude values in between the sampling positions $t = k T$ are given by superimposing the shifted sinc functions. The process of computing values in between given sampling points is termed [*interpolation*](https://en.wikipedia.org/wiki/Interpolation). The reconstruction of the sampled signal is performed by interpolating the discrete amplitude values $x(k T)$. The sinc function is the optimal interpolator for band-limited signals.
### Aliasing
So far the case was discussed when no overlaps occur in the spectrum of the sampled signal. Hence when the upper frequency limit $\omega_\text{u}$ of the real-valued low-pass signal is lower than $\frac{\omega_\text{s}}{2}$. Here a perfect reconstruction of the continuous signal $x(t)$ from its discrete counterpart $x[k]$ is possible. However when this condition is not met, the repetitions of the spectrum of the continuous signal overlap. This is illustrated in the following

In this case no perfect reconstruction of the continuous signal by low-pass filtering (interpolation) of the sampled signal is possible. The spectrum within the pass-band of the low-pass contains additional contributions from the repeated spectrum of the continuous signal. These contributions are known as [aliasing](https://en.wikipedia.org/wiki/Aliasing). It becomes evident from above discussion of ideal reconstruction that the amplitude values are reconstructed correctly at the time-instants $k T$. However, in between these time-instants the reconstructed signal $y(t)$ differs from the sampled signal $x(t)$ if aliasing is present.
### Sampling Theorem for Low-Pass Signals
It can be concluded from above discussion of sampling, that a sufficient condition for the perfect reconstruction of a real-valued low-pass signal $x(t)$ is given as
\begin{equation}
\omega_\text{s} \geq 2 \cdot \omega_\text{c}
\end{equation}
The minimum sampling frequency has to be chosen as double the highest frequency present in the continuous signal. This condition is known as [*Nyquist–Shannon sampling theorem*](https://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem). Only if this condition is fulfilled, all information contained in a low-pass signal $x(t)$ is represented by its samples $x[k] = x(k T)$.
Depending on the relation between the sampling frequency $\omega_\text{s}$ and the upper frequency limit $\omega_\text{u}$ of the low-pass signal, three different cases can be distinguished
* oversampling $\omega_\text{s} > 2 \cdot \omega_\text{c}$
* critical sampling $\omega_\text{s} = 2 \cdot \omega_\text{c}$
* undersampling $\omega_\text{s} < 2 \cdot \omega_\text{c}$
In practical applications sampling is always oversampled to some degree since the ideal low-pass used to reconstruct the continuous signal cannot be realized. Examples for sampling rates in audio are
| Application | Sampling frequency $f_\text{s}$ |
|---|:---:|
| Telephone service | Narrowband: 8 kHz, Wideband: 16 kHz |
| [Compact Disc (CD)](https://en.wikipedia.org/wiki/Compact_disc) | [44.1 kHz](https://en.wikipedia.org/wiki/44,100_Hz) |
| [DVD-Audio](https://en.wikipedia.org/wiki/DVD-Audio) | 44.1, 48, 88.2, 96, 176.4, 192 kHz |
### Example: Ideal Sampling and Reconstruction of a Cosine Signal
The ideal sampling and reconstruction of an analog signal $x(t)$ is illustrated in the following. For ease of illustration a cosine signal $x(t) = \cos(\omega_0 t)$ is considered. First, two `Python` functions are defined which ideally sample the signal $x(t)$ at equidistant time-instants $t = k T$ and compute the reconstructed signal $y(t)$ from the samples by applying an ideal low-pass.
```
import sympy as sym
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
sym.init_printing()
t = sym.symbols('t', real=True)
k = sym.symbols('k', integer=True)
def ideal_sampling(x, k, w_s):
kappa = sym.symbols('kappa')
xs = sym.lambdify(kappa, x.subs(t, kappa * 2 * sym.pi / w_s))
return [xs(kappa) for kappa in k]
def ideal_reconstruction(xs, k, w_s):
T = 2*sym.pi/w_s
return sum(xs[n] * sym.sinc(sym.pi / T * (t - k[n] * T)) for n in range(len(k)))
```
Furthermore a helper function for plotting of the sampled and reconstructed signal is defined.
```
def plot_signals(xs, y, w_s, k):
plt.stem(k*2*np.pi/w_s, xs)
plt.xlabel('$t$ in s')
plt.ylabel('$x_s[k] = x_s(kT)$')
plt.axis([0, 5, -1.2, 1.2])
sym.plot(y, (t, 0, 5), xlabel='$t$', ylabel='$y(t)$', ylim=(-1.2, 1.2))
```
Now the continuous signal $x(t) = \cos(\omega_0 t)$ to be sampled and reconstructed is defined and plotted for $\omega_0 = 5$.
```
w_0 = 5
x = sym.cos(w_0 * t)
sym.plot(x, (t, 0, 5), xlabel=r'$t$', ylabel=r'$x(t)$')
```
First the case of oversampling $\omega_\text{s} > 2 \cdot \omega_0$ with $\omega_\text{s} = 50$ is illustrated
```
k = np.arange(-100, 100)
w_s = 50
xs = ideal_sampling(x, k, w_s)
y = ideal_reconstruction(xs, k, w_s)
plot_signals(xs, y, w_s, k)
```
Then the case of critical sampling $\omega_\text{s} = 2 \cdot \omega_0$ with $\omega_\text{s} = 10$ is illustrated
```
w_s = 10
xs = ideal_sampling(x, k, w_s)
y = ideal_reconstruction(xs, k, w_s)
plot_signals(xs, y, w_s, k)
```
Finally the case of undersampling $\omega_\text{s} < 2 \cdot \omega_0$ with $\omega_\text{s} = 7$ is illustrated
```
w_s = 7
xs = ideal_sampling(x, k, w_s)
y = ideal_reconstruction(xs, k, w_s)
plot_signals(xs, y, w_s, k)
```
**Exercise**
* Derive the spectrum of the reconstructed signal for the sampling of $x = \cos(\omega_0 t)$ with sampling frequency $\omega_s$ by calculating
* the spectrum $X(j \omega)$ of the continuous signal
* the spectrum $X_\text{s}(j \omega)$ of the sampled signal
* the spectrum $Y(j \omega)$ of the reconstructed signal for the case of over-, critial- and undersampling
* the reconstructed signal $y(t)$ for the case of over-, critial- and undersampling
* Reevaluate above example with $x(t) = \text{rect}(t - \frac{3}{2})$.
* Hint: Define the signal by `x = sym.Heaviside(t-1) - sym.Heaviside(t-2)`
* Is a perfect reconstruction possible? If not, why?
**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, Continuous- and Discrete-Time Signals and Systems - Theory and Computational Examples*.
| github_jupyter |
In the first course in this step, Machine Learning Fundamentals, we walked through the full machine learning workflow using the k-nearest neighbors algorithm. K-nearest neighbors works by finding similar, labelled examples from the training set for each instance in the test set and uses them to predict the label. K-nearest neighbors is known as an instance-based learning algorithm because it relies completely on previous instances to make predictions. The k-nearest neighbors algorithm doesn't try to understand or capture the relationship between the feature columns and the target column.
Because the entire training dataset is used to find a new instance's nearest neighbors to make label predictions, this algorithm doesn't scale well to medium and larger datasets. If we have a million instances in our training data set and we want to make predictions for a hundred thousand new instances, we'd have to sort the million instances in the training set by Euclidean distance for each instance.
# Model Based Learning
To get familiar with this machine learning approach, we'll work with a dataset on sold houses in Ames, Iowa. Each row in the dataset describes the properties of a single house as well as the amount it was sold for. In this course, we'll build models that predict the final sale price from its other attributes. Specifically, we'll explore the following questions:
- Which properties of a house most affect the final sale price?
- How effectively can we predict the sale price from just its properties?
This dataset was originally compiled by [Dean De Cock](http://www.truman.edu/faculty-staff/decock/) for the primary purpose of having a high quality dataset for regression. You can read more about his process and motivation [here](https://doi.org/10.1080/10691898.2011.11889627) and download the dataset [here](https://dsserver-prod-resources-1.s3.amazonaws.com/235/AmesHousing.txt). There is also a data dictionary [here](http://www.amstat.org/publications/jse/v19n3/decock/DataDocumentation.txt).
Here are some of the columns:
- `Lot Area`: Lot size in square feet.
- `Overall Qual`: Rates the overall material and finish of the house.
- `Overall Cond`: Rates the overall condition of the house.
- `Year Built`: Original construction date.
- `Low Qual Fin SF`: Low quality finished square feet (all floors).
- `Full Bath`: Full bathrooms above grade.
- `Fireplaces`: Number of fireplaces.
Let's start by generating `train` and `test` datasets and getting more familiar with the data.
```
import pandas as pd
data = pd.read_csv('AmesHousing.txt', delimiter="\t")
train = data[0:1460]
test = data[1460:]
print(train.info())
target = 'SalePrice'
```
We'll start by understanding the univariate case of linear regression, also known as simple linear regression. The following equation is the general form of the simple linear regression model.
${^y} = a_1x_1 + a_0$
${^y}$ represents the target column while $x_1$ represents the feature column we choose to use in our model. These values are independent of the dataset. On the other hand, $a_1$ and $a_0$ represent the parameter values that are specific to the dataset.
The goal of simple linear regression is to find the optimal parameter values that best describe the relationship between the feature column and the target column.
Steps:
- Create a figure with dimensions 7 x 15 containing three scatter plots in a single column:
- The first plot should plot the `Garage Area` column on the x-axis against the `SalePrice` column on the y-axis.
- The second one should plot the `Gr Liv Area` column on the x-axis against the `SalePrice` column on the y-axis.
- The third one should plot the `Overall Cond` column on the x-axis against the `SalePrice` column on the y-axis.
From the data dictionary mentioned above:
- `Garage Area` (Continuous): Size of garage in square feet
- `Gr Liv Area` (Continuous): Above grade (ground) living area square feet
- `Overall Cond` (Ordinal): Rates the overall condition of the house on a scale of 1 to 10 with 10 being the best
Also we find the following note:
#### Potential Pitfalls (Outliers): Although all known errors were corrected in the data, no observations have been removed due to unusual values and all final residential sales from the initial data set are included in the data presented with this article. There are five observations that an instructor may wish to remove from the data set before giving it to students (a plot of SALE PRICE versus GR LIV AREA will quickly indicate these points). Three of them are true outliers (Partial Sales that likely don’t represent actual market values) and two of them are simply unusual sales (very large houses priced relatively appropriately). I would recommend removing any houses with more than 4000 square feet from the data set (which eliminates these five unusual observations) before assigning it to students.
```
import matplotlib.pyplot as plt
# For prettier plots.
import seaborn
fig = plt.figure(figsize=(7,15))
ax1 = fig.add_subplot(3, 1, 1)
ax2 = fig.add_subplot(3, 1, 2)
ax3 = fig.add_subplot(3, 1, 3)
train.plot(x="Garage Area", y="SalePrice", ax=ax1, kind="scatter")
train.plot(x="Gr Liv Area", y="SalePrice", ax=ax2, kind="scatter")
train.plot(x="Overall Cond", y="SalePrice", ax=ax3, kind="scatter")
plt.show()
```
We can tell that the `Gr Liv Area` feature correlates the most with the `SalePrice` column. We can confirm this by calculating the correlation between pairs of these columns using the `pandas.DataFrame.corr()` method:
```
print(train[['Garage Area', 'Gr Liv Area', 'Overall Cond', 'SalePrice']].corr())
```
The correlation between Gr Liv Area and SalePrice is around 0.709, which is the highest. Recall that the closer the correlation coefficient is to 1.0, the stronger the correlation.
#### Residual Sum Of Squares - Least Squares
To find the optimal parameters for a linear regression model, we want to optimize the model's residual sum of squares (or RSS). If you recall, residual (often referred to as errors) describes the difference between the predicted values for the target column (\hat{y}) and the true values (y).
We want this difference to be as small as possible. Calculating RSS involves summing the squared errors.
If you recall, the calculation for RSS _seems_ very similar to the calculation for MSE (mean squared error)
Let's now use `scikit-learn` to find the optimal parameter values for our model. The scikit-learn library was designed to easily swap and try different models. Because we're familiar with the scikit-learn workflow for k-nearest neighbors, switching to using linear regression is straightforward.
Instead of working with the `sklearn.neighbors.KNeighborsRegressors` class, we work with the `sklearn.linear_model.LinearRegression` class. The LinearRegression class also has it's own `fit()` method. Specific to this model, however, are the `coef_` and `intercept_` attributes, which return $a1$
($a1$ to $an$ if it were a multivariate regression model) and $a0$ accordingly.
Steps:
- Import and instantiate a linear regression model.
- Fit a linear regression model that uses the feature and target columns we explored in the last 2 screens. Use the default arguments.
- Display the coefficient and intercept of the fitted model using the `coef_` and `intercept_` attributes.
- Assign $a1$ to a1 and $a0$ to a0.
```
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(train[['Gr Liv Area']], train['SalePrice'])
print(lr.coef_)
print(lr.intercept_)
a0 = lr.intercept_
a1 = lr.coef_
```
In the last step, we fit a univariate linear regression model between the Gr Liv Area and SalePrice columns. We then displayed the single coefficient and the residual value. If we refer back to the format of our linear regression model, the fitted model can be represented as:
$y^ = 116.86624683$x1$ + 5366.821710056043$
One way to interpret this model is "for every 1 square foot increase in above ground living area, we can expect the home's value to increase by approximately 116.87 dollars".
We can now use the `predict()` method to predict the labels using the training data and compare them with the actual labels. To quantify the fit, we can use `mean squared error`. Let's also perform simple validation by making predictions on the test set and calculate the MSE value for those predictions as well.
Steps:
- Use the fitted model to make predictions on both the training and test sets.
- Calculate the `RMSE` value for the predictions on the training set and assign to `train_rmse`.
- Calculate the `RMSE` value for the predictions on the test set and assign to `test_rmse`.
```
import numpy as np
lr = LinearRegression()
lr.fit(train[['Gr Liv Area']], train['SalePrice'])
from sklearn.metrics import mean_squared_error
train_predictions = lr.predict(train[['Gr Liv Area']])
test_predictions = lr.predict(test[['Gr Liv Area']])
train_mse = mean_squared_error(train_predictions, train['SalePrice'])
test_mse = mean_squared_error(test_predictions, test['SalePrice'])
train_rmse = np.sqrt(train_mse)
test_rmse = np.sqrt(test_mse)
print(train_rmse)
print(test_rmse)
```
### Multiple Linear Regression
Now that we've explored the basics of simple linear regression, we can extend what we've learned to the multivariate case (often called multiple linear regression). A multiple linear regression model allows us to capture the relationship between multiple feature columns and the target column.
When using multiple features, the main challenge is selecting relevant features. In a later mission in this course, we'll dive into some approaches for feature selection. For now, let's train a model using the following columns from the dataset to see how train and test RMSE values are improved.
- `Overall Cond`
- `Gr Liv Area`
Steps:
- Train a linear regression model using the columns in `cols`.
- Use the fitted model to make predictions on both the training and test dataset.
- Calculate the RMSE value for the predictions on the training set and assign to `train_rmse_2`.
- Calculate the RMSE value for the predictions on the test set and assign to `test_rmse_2`.
```
cols = ['Overall Cond', 'Gr Liv Area']
lr.fit(train[cols], train['SalePrice'])
train_predictions = lr.predict(train[cols])
test_predictions = lr.predict(test[cols])
train_rmse_2 = np.sqrt(mean_squared_error(train_predictions, train['SalePrice']))
test_rmse_2 = np.sqrt(mean_squared_error(test_predictions, test['SalePrice']))
print(train_rmse_2)
print(test_rmse_2)
```
## Missing Values
In the machine learning workflow, once we've selected the model we want to use, selecting the appropriate features for that model is the next important step. In this mission, we'll explore how to use correlation between features and the target column, correlation between features, and variance of features to select features. We'll continue working with the same housing dataset from the last mission.
We'll specifically focus on selecting from feature columns that don't have any missing values or don't need to be transformed to be useful (e.g. columns like `Year Built` and `Year Remod/Add`). We'll explore how to deal with both of these in a later mission in this course.
To start, let's look at which columns fall into either of these two categories.
```
numerical_train = train.select_dtypes(include=['int', 'float'])
numerical_train = numerical_train.drop(['PID', 'Year Built', 'Year Remod/Add', 'Garage Yr Blt', 'Mo Sold', 'Yr Sold'], axis=1)
null_series = numerical_train.isnull().sum()
full_cols_series = null_series[null_series == 0]
print(full_cols_series)
len(full_cols_series)
# Correlating Feature cols with Target cols
train_subset = train[full_cols_series.index]
corrmat = train_subset.corr()
sorted_corrs = corrmat['SalePrice'].abs().sort_values()
print(sorted_corrs)
```
## Visualization - Correlation Matrix Heatmap
We now have a decent list of candidate features to use in our model, sorted by how strongly they're correlated with the `SalePrice` column. For now, let's keep only the features that have a correlation of `0.3` or higher. This cutoff is a bit arbitrary and, in general, it's a good idea to experiment with this cutoff. For example, you can train and test models using different cutoffs and see where your model stops improving.
The next thing we need to look for is for potential collinearity between some of these feature columns. Collinearity is when 2 feature columns are highly correlated and stand the risk of duplicating information. If we have 2 features that convey the same information using 2 different measures or metrics, we don't need to keep both.
While we can check for collinearity between 2 columns using the correlation matrix, we run the risk of information overload. We can instead generate a correlation matrix heatmap using Seaborn to visually compare the correlations and look for problematic pairwise feature correlations. Because we're looking for outlier values in the heatmap, this visual representation is easier
```
import seaborn as sns
strong_corrs = sorted_corrs[sorted_corrs > 0.3]
corrmat = train_subset[strong_corrs.index].corr()
sns.heatmap(corrmat)
```
### Train and Test Model
Based on the correlation matrix heatmap, we can tell that the following pairs of columns are strongly correlated:
- `Gr Liv Area` and `TotRms AbvGrd`
- `Garage Area` and `Garage Cars`
If we read the descriptions of these columns from the data documentation, we can tell that each pair of columns reflects very similar information. Because `Gr Liv Area` and `Garage Area` are continuous variables that capture more nuance, let's drop the `TotRms AbvGrd` and `Garage Cars`.
Steps:
- Filter the test data frame so it only contains the columns from `final_corr_cols.index`. Then, drop the row containing missing values and assign the result to clean_test
- Build a linear regression model using the features in features.
- Calculate the RMSE on the test and train sets.
- Assign the train RMSE to `train_rmse` and the test RMSE to `test_rmse`.
```
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import numpy as np
final_corr_cols = strong_corrs.drop(['Garage Cars', 'TotRms AbvGrd'])
features = final_corr_cols.drop(['SalePrice']).index
target = 'SalePrice'
clean_test = test[final_corr_cols.index].dropna()
lr = LinearRegression()
lr.fit(train[features], train['SalePrice'])
train_predictions = lr.predict(train[features])
test_predictions = lr.predict(clean_test[features])
train_mse = mean_squared_error(train_predictions, train[target])
test_mse = mean_squared_error(test_predictions, clean_test[target])
train_rmse = np.sqrt(train_mse)
test_rmse = np.sqrt(test_mse)
print(train_rmse)
print(test_rmse)
```
### Removing Low Variance Features
The last technique we'll explore is removing features with low variance. When the values in a feature column have low variance, they don't meaningfully contribute to the model's predictive capability. On the extreme end, let's imagine a column with a variance of `0`. This would mean that all of the values in that column were exactly the same. This means that the column isn't informative and isn't going to help the model make better predictions.
To make apples to apples comparisons between columns, we need to rescale all of the columns to vary between `0` and `1`. Then, we can set a cutoff value for variance and remove features that have less than that variance amount. This is known as min-max scaling or as rescaling.
Steps:
- Select the columns in features from the train data frame. Rescale each of the columns so the values range from `0` to `1`, by using `train[features]` instead of
in the formula above. Assign the result to `unit_train`.
- Calculate and display the column minimum and maximum values of `unit_train` to ensure that all values range from 0 to 1.
- Use the `DataFrame.var` method to compute the variance of these columns, sort the resulting series by its values, and assign to `sorted_vars`.
- Print `sorted_vars`.
```
unit_train = (train[features] - train[features].min())/(train[features].max() - train[features].min())
print(unit_train.min())
print(unit_train.max())
# Confirmed: the min and max values are 0.0 and 1.0 respectively
sorted_vars = unit_train.var().sort_values()
print(sorted_vars)
```
### Final Model
Let's set a cutoff variance of 0.015, remove the Open Porch SF feature, and train and test a model using the remaining features.
```
clean_test = test[final_corr_cols.index].dropna()
features = features.drop('Open Porch SF')
lr = LinearRegression()
lr.fit(train[features], train['SalePrice'])
train_predictions = lr.predict(train[features])
test_predictions = lr.predict(clean_test[features])
train_mse = mean_squared_error(train_predictions, train[target])
test_mse = mean_squared_error(test_predictions, clean_test[target])
train_rmse_2 = np.sqrt(train_mse)
test_rmse_2 = np.sqrt(test_mse)
print(train_rmse_2)
print(test_rmse_2)
```
We were able to improve the RMSE value to approximately 40591 by removing the Open Porch SF feature.
This is most likely the furthest we can go without transforming and utilizing the other features in the dataset so we'll stop here for now.
In the next 2 missions, we'll explore 2 different ways of fitting models. Afterwards, we'll explore ways to clean and engineer new features from the existing features to improve model accuracy even further.
### Gradient Descent
The gradient descent algorithm works by iteratively trying different parameter values until the model with the lowest mean squared error is found. Gradient descent is a commonly used optimization technique for other models as well, like neural networks.
A function that we optimize through minimization is known as a cost function or sometimes as the loss function.
```
# Derivative of the cost function
def derivative(a1, xi_list, yi_list):
len_data = len(xi_list)
error = 0
for i in range(0, len_data):
error += xi_list[i]*(a1*xi_list[i] - yi_list[i])
deriv = 2*error/len_data
return deriv
def gradient_descent(xi_list, yi_list, max_iterations, alpha, a1_initial):
a1_list = [a1_initial]
for i in range(0, max_iterations):
a1 = a1_list[i]
deriv = derivative(a1, xi_list, yi_list)
a1_new = a1 - alpha*deriv
a1_list.append(a1_new)
return(a1_list)
param_iterations = gradient_descent(train['Gr Liv Area'], train['SalePrice'], 20, .0000003, 150)
final_param = param_iterations[-1]
print(param_iterations, final_param)
# Gradient of the cost function
def a1_derivative(a0, a1, xi_list, yi_list):
len_data = len(xi_list)
error = 0
for i in range(0, len_data):
error += xi_list[i]*(a0 + a1*xi_list[i] - yi_list[i])
deriv = 2*error/len_data
return deriv
def a0_derivative(a0, a1, xi_list, yi_list):
len_data = len(xi_list)
error = 0
for i in range(0, len_data):
error += a0 + a1*xi_list[i] - yi_list[i]
deriv = 2*error/len_data
return deriv
def gradient_descent(xi_list, yi_list, max_iterations, alpha, a1_initial, a0_initial):
a1_list = [a1_initial]
a0_list = [a0_initial]
for i in range(0, max_iterations):
a1 = a1_list[i]
a0 = a0_list[i]
a1_deriv = a1_derivative(a0, a1, xi_list, yi_list)
a0_deriv = a0_derivative(a0, a1, xi_list, yi_list)
a1_new = a1 - alpha*a1_deriv
a0_new = a0 - alpha*a0_deriv
a1_list.append(a1_new)
a0_list.append(a0_new)
return(a0_list, a1_list)
a0_params, a1_params = gradient_descent(train['Gr Liv Area'], train['SalePrice'], 20, .0000003, 150, 1000)
print(a0_params, a1_params)
```
### Ordinary Least Squares - OLS
scikit-learn uses OLS under the hood when you call fit() on a LinearRegression instance
- Select just the features in features from the training set and assign to `X`.
- Select the SalePrice column from the training set and assign to `y`.
- Use the OLS estimation formula to return the optimal parameter values. Store the estimation to the variable `ols_estimation`
```
data = pd.read_csv('AmesHousing.txt', delimiter="\t")
train = data[0:1460]
test = data[1460:]
features = ['Wood Deck SF', 'Fireplaces', 'Full Bath', '1st Flr SF', 'Garage Area',
'Gr Liv Area', 'Overall Qual']
X = train[features]
y = train['SalePrice']
first_term = np.linalg.inv(
np.dot(
np.transpose(X),
X
)
)
second_term = np.dot(
np.transpose(X),
y
)
ols_estimation = np.dot(first_term, second_term)
print(ols_estimation)
```
Unlike gradient descent, OLS estimation provides what is known as a closed form solution to the problem of finding the optimal parameter values. A closed form solution is one where a solution can be computed arithmetically with a predictable amount of mathematical operations. Gradient descent, on the other hand, is an algorithmic approach that can require a different number of iterations (and therefore a different number of mathematical operations) based on the initial parameter values, the learning rate, etc. While the approach is different, both techniques share the high level objective of minimizing the cost function.
The biggest limitation is that OLS estimation is computationally expensive when the data is large. This is because computing a matrix inverse has a computational complexity of approximately O(n^3).
OLS is commonly used when the number of elements in the dataset (and therefore the matrix that's inverted) is less than a few million elements.
On larger datasets, gradient descent is used because it's much more flexible.
For many practical problems, we can set a threshold accuracy value (or a set number of iterations) and use a "good enough" solution. This is especially useful when iterating and trying different features in our model.
### Processing and Transforming Features
To understand how linear regression works, we've stuck to using features from the training dataset that contained no missing values and were already in a convenient numeric representation. In this mission, we'll explore how to transform some of the remaining features so we can use them in our model. Broadly, the process of processing and creating new features is known as feature engineering. Feature engineering is a bit of an art and having knowledge in the specific domain (in this case real estate) can help you create better features. In this mission, we'll focus on some domain-independent strategies that work for all problems.
In the first half of this mission, we'll focus only on columns that contain no missing values but still aren't in the proper format to use in a linear regression model. In the latter half of this mission, we'll explore some ways to deal with missing values.
```
data = pd.read_csv('AmesHousing.txt', delimiter="\t")
train = data[0:1460]
test = data[1460:]
train_null_counts = train.isnull().sum()
print(train_null_counts)
# data frame no missing values
df_no_mv = train[train_null_counts[train_null_counts==0].index]
df_no_mv.head
```
### Categorical features
You'll notice that some of the columns in the data frame df_no_mv contain string values. If these columns contain only a limited set of uniuqe values, they're known as categorical features.
```
print(train['Utilities'].value_counts())
print(train['Street'].value_counts())
print(train['House Style'].value_counts())
```
To use these features in our model, we need to transform them into numerical representations.
Thankfully, pandas makes this easy because the library has a special categorical data type.
We can convert any column that contains no missing values (or an error will be thrown) to the categorical data type using the `pandas.Series.astype()` method
```
text_cols = df_no_mv.select_dtypes(include=['object']).columns
for col in text_cols:
print(col+":", len(train[col].unique()))
for col in text_cols:
train[col] = train[col].astype('category')
train['Utilities'].cat.codes.value_counts()
```
### Dummy Coding
Because the original values for the first 4 rows were `AllPub`, in the new scheme, they contain the binary value for true (`1`) in the `Utilities_AllPub` column and `0` for the other 2 columns.
Pandas thankfully has a convenience function to help us apply this transformation for all of the text columns called `pandas.get_dummies()`.
- Convert all of the columns in text_cols from the train data frame into dummy columns.
- Delete the original columns from text_cols from the train data frame.
```
dummy_cols = pd.DataFrame()
for col in text_cols:
col_dummies = pd.get_dummies(train[col])
train = pd.concat([train, col_dummies], axis=1)
del train[col]
```
### Transforming Improper Numerical Features
```
print(train[['Year Remod/Add', 'Year Built']])
```
Main issues:
- Year values aren't representative of how old a house is
- The Year Remod/Add column doesn't actually provide useful information for a linear regression model
```
train['years_until_remod'] = train['Year Remod/Add'] - train['Year Built']
train.head()
```
### Missing Values
When values are missing in a column, there are two main approaches we can take:
- Remove rows containing missing values for specific columns
- Pro: Rows containing missing values are removed, leaving only clean data for modeling
- Con: Entire observations from the training set are removed, which can reduce overall prediction accuracy
- Impute (or replace) missing values using a descriptive statistic from the column
- Pro: Missing values are replaced with potentially similar estimates, preserving the rest of the observation in the model.
- Con: Depending on the approach, we may be adding noisy data for the model to learn
Given that we only have 1460 training examples (with ~80 potentially useful features), we don't want to remove any of these rows from the dataset. Let's instead focus on imputation techniques.
We'll focus on columns that contain at least 1 missing value but less than 365 missing values (or 25% of the number of rows in the training set). There's no strict threshold, and many people instead use a 50% cutoff (if half the values in a column are missing, it's automatically dropped). Having some domain knowledge can help with determining an acceptable cutoff value.
```
data = pd.read_csv('AmesHousing.txt', delimiter="\t")
train = data[0:1460]
test = data[1460:]
train_null_counts = train.isnull().sum()
df_missing_values = train[train_null_counts[(train_null_counts>0) & (train_null_counts<584)].index]
print(df_missing_values.isnull().sum())
print(df_missing_values.dtypes)
```
### Imputing missing values
About half of the columns in `df_missing_values` are string columns (object data type), while about half are float64 columns. For numerical columns with missing values, a common strategy is to compute the mean, median, or mode of each column and replace all missing values in that column with that value.
Because imputation is a common task, pandas contains a `pandas.DataFrame.fillna()` method that we can use for this. If we pass in a value, all of the missing values (`NaN`) in the data frame are replaced by that value
```
float_cols = df_missing_values.select_dtypes(include=['float'])
float_cols = float_cols.fillna(float_cols.mean())
print(float_cols.isnull().sum())
```
| github_jupyter |
# Riskfolio-Lib Tutorial:
<br>__[Financionerioncios](https://financioneroncios.wordpress.com)__
<br>__[Orenji](https://www.orenj-i.net)__
<br>__[Riskfolio-Lib](https://riskfolio-lib.readthedocs.io/en/latest/)__
<br>__[Dany Cajas](https://www.linkedin.com/in/dany-cajas/)__
<a href='https://ko-fi.com/B0B833SXD' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://cdn.ko-fi.com/cdn/kofi1.png?v=2' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>
## Tutorial 22: Logarithmic Mean Risk Optimization (Kelly Criterion)
## 1. Downloading the data:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
import warnings
warnings.filterwarnings("ignore")
pd.options.display.float_format = '{:.4%}'.format
# Date range
start = '2000-01-01'
end = '2019-12-31'
# Tickers of assets
assets = ['AIG', 'AKAM', 'ALXN', 'AMT', 'APA', 'BA', 'BAX', 'BKNG',
'BMY', 'CMCSA', 'CNP', 'CPB', 'DE', 'MO', 'MSFT', 'NI',
'NKTR', 'NTAP', 'PCAR', 'PSA', 'REGN', 'SBAC', 'SEE', 'T',
'TGT', 'TMO', 'TTWO']
assets.sort()
# Downloading data
data = yf.download(assets, start = start, end = end)
data = data.loc[:,('Adj Close', slice(None))]
data.columns = assets
# Calculating returns
#Y = data[assets].pct_change().dropna()
Y = data[assets].copy()
Y = Y.resample('M').last().pct_change().dropna()
print(Y.shape)
display(Y.head())
```
## 2. Estimating Logarithmic Mean Variance Portfolios
### 2.1 Calculating the portfolio that maximizes Risk Adjusted Return.
```
import riskfolio as rp
# Building the portfolio object
port = rp.Portfolio(returns=Y)
# Calculating optimal portfolio
# Select method and estimate input parameters:
method_mu='hist' # Method to estimate expected returns based on historical data.
method_cov='hist' # Method to estimate covariance matrix based on historical data.
port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=0.94)
# Estimate optimal portfolio:
port.solvers = ['MOSEK']
model='Classic' # Could be Classic (historical), BL (Black Litterman) or FM (Factor Model)
rm = 'MV' # Risk measure used, this time will be variance
obj = 'Sharpe' # Objective function, could be MinRisk, MaxRet, Utility or Sharpe
hist = True # Use historical scenarios for risk measures that depend on scenarios
rf = 0 # Risk free rate
l = 0 # Risk aversion factor, only useful when obj is 'Utility'
w_1 = port.optimization(model=model, rm=rm, obj=obj, kelly=False, rf=rf, l=l, hist=hist)
w_2 = port.optimization(model=model, rm=rm, obj=obj, kelly='approx', rf=rf, l=l, hist=hist)
w_3 = port.optimization(model=model, rm=rm, obj=obj, kelly='exact', rf=rf, l=l, hist=hist)
w = pd.concat([w_1, w_2, w_3], axis=1)
w.columns = ['Arithmetic', 'Log Approx', 'Log Exact']
display(w)
fig, ax = plt.subplots(figsize=(14,6))
w.plot(kind='bar', ax = ax)
returns = port.returns
cov = port.cov
y = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_1.to_numpy()))
x = rp.Sharpe_Risk(w_1, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
print("Risk Adjusted Return:")
print("Arithmetic", (y/x).item() * 12**0.5)
y = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_2.to_numpy()))
x = rp.Sharpe_Risk(w_2, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
print("Log Approx", (y/x).item() * 12**0.5)
y = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_3.to_numpy()))
x = rp.Sharpe_Risk(w_3, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
print("Log Exact", (y/x).item() * 12**0.5)
```
### 2.2 Calculate efficient frontier
```
points = 40 # Number of points of the frontier
frontier = port.efficient_frontier(model=model, rm=rm, kelly="exact", points=points, rf=rf, hist=hist)
display(frontier.T.head())
# Plotting the efficient frontier
label = 'Max Risk Adjusted Log Return Portfolio' # Title of point
mu = port.mu # Expected returns
cov = port.cov # Covariance matrix
returns = port.returns # Returns of the assets
fig, ax = plt.subplots(figsize=(10,6))
rp.plot_frontier(w_frontier=frontier,
mu=mu,
cov=cov,
returns=returns,
rm=rm,
kelly=True,
rf=rf,
alpha=0.05,
cmap='viridis',
w=w_2,
label=label,
marker='*',
s=16,
c='r',
height=6,
width=10,
ax=ax)
y1 = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_1.to_numpy())) * 252
x1 = rp.Sharpe_Risk(w_1, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05) * 252**0.5
y2 = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_2.to_numpy())) * 252
x2 = rp.Sharpe_Risk(w_2, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05) * 252**0.5
ax.scatter(x=x1,
y=y1,
marker="^",
s=8**2,
c="b",
label="Max Risk Adjusted Arithmetic Return Portfolio")
ax.scatter(x=x2,
y=y2,
marker="v",
s=8**2,
c="c",
label="Max Risk Adjusted Approx Log Return Portfolio")
plt.legend()
```
## 2. Estimating Logarithmic Mean EVaR Portfolios
### 2.1 Calculating the portfolio that maximizes Risk Adjusted Return.
```
rm = 'EVaR' # Risk measure
w_1 = port.optimization(model=model, rm=rm, obj=obj, kelly=False, rf=rf, l=l, hist=hist)
w_2 = port.optimization(model=model, rm=rm, obj=obj, kelly='approx', rf=rf, l=l, hist=hist)
w_3 = port.optimization(model=model, rm=rm, obj=obj, kelly='exact', rf=rf, l=l, hist=hist)
w = pd.concat([w_1, w_2, w_3], axis=1)
w.columns = ['Arithmetic', 'Log Approx', 'Log Exact']
display(w)
fig, ax = plt.subplots(figsize=(14,6))
w.plot(kind='bar', ax = ax)
returns = port.returns
cov = port.cov
y = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_1.to_numpy()))
x = rp.Sharpe_Risk(w_1, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
print("Risk Adjusted Return:")
print("Arithmetic", (y/x).item() * 12**0.5)
y = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_2.to_numpy()))
x = rp.Sharpe_Risk(w_2, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
print("Log Approx", (y/x).item() * 12**0.5)
y = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_3.to_numpy()))
x = rp.Sharpe_Risk(w_3, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
print("Log Exact", (y/x).item() * 12**0.5)
```
### 3.2 Calculate efficient frontier
```
points = 40 # Number of points of the frontier
frontier = port.efficient_frontier(model=model, rm=rm, kelly="exact", points=points, rf=rf, hist=hist)
display(frontier.T.head())
# Plotting the efficient frontier
label = 'Max Risk Adjusted Log Return Portfolio' # Title of point
mu = port.mu # Expected returns
cov = port.cov # Covariance matrix
returns = port.returns # Returns of the assets
fig, ax = plt.subplots(figsize=(10,6))
rp.plot_frontier(w_frontier=frontier,
mu=mu,
cov=cov,
returns=returns,
rm=rm,
kelly=True,
rf=rf,
alpha=0.05,
cmap='viridis',
w=w_3,
label=label,
marker='*',
s=16,
c='r',
height=6,
width=10,
t_factor=12,
ax=ax)
y1 = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_1.to_numpy())) * 12
x1 = rp.Sharpe_Risk(w_1, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05) * 12**0.5
y2 = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_2.to_numpy())) * 12
x2 = rp.Sharpe_Risk(w_2, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05) * 12**0.5
ax.scatter(x=x1,
y=y1,
marker="^",
s=8**2,
c="b",
label="Max Risk Adjusted Arithmetic Return Portfolio")
ax.scatter(x=x2,
y=y2,
marker="v",
s=8**2,
c="c",
label="Max Risk Adjusted Approx Log Return Portfolio")
plt.legend()
```
## 3. Estimating Logarithmic Mean EDaR Portfolios
### 3.1 Calculating the portfolio that maximizes Risk Adjusted Return.
```
rm = 'EDaR' # Risk measure
w_1 = port.optimization(model=model, rm=rm, obj=obj, kelly=False, rf=rf, l=l, hist=hist)
w_2 = port.optimization(model=model, rm=rm, obj=obj, kelly='approx', rf=rf, l=l, hist=hist)
w_3 = port.optimization(model=model, rm=rm, obj=obj, kelly='exact', rf=rf, l=l, hist=hist)
w = pd.concat([w_1, w_2, w_3], axis=1)
w.columns = ['Arithmetic', 'Log Approx', 'Log Exact']
display(w)
fig, ax = plt.subplots(figsize=(14,6))
w.plot(kind='bar', ax = ax)
returns = port.returns
cov = port.cov
y = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_1.to_numpy()))
x = rp.Sharpe_Risk(w_1, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
print("Risk Adjusted Return:")
print("Arithmetic", (y/x).item() * 12)
y = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_2.to_numpy()))
x = rp.Sharpe_Risk(w_2, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
print("Log Approx", (y/x).item() * 12)
y = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_3.to_numpy()))
x = rp.Sharpe_Risk(w_3, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
print("Log Exact", (y/x).item() * 12)
```
### 3.2 Calculate efficient frontier
```
points = 40 # Number of points of the frontier
frontier = port.efficient_frontier(model=model, rm=rm, kelly="exact", points=points, rf=rf, hist=hist)
display(frontier.T.head())
# Plotting the efficient frontier
label = 'Max Risk Adjusted Log Return Portfolio' # Title of point
mu = port.mu # Expected returns
cov = port.cov # Covariance matrix
returns = port.returns # Returns of the assets
fig, ax = plt.subplots(figsize=(10,6))
rp.plot_frontier(w_frontier=frontier,
mu=mu,
cov=cov,
returns=returns,
rm=rm,
kelly=True,
rf=rf,
alpha=0.05,
cmap='viridis',
w=w_3,
label=label,
marker='*',
s=16,
c='r',
height=6,
width=10,
t_factor=12,
ax=ax)
y1 = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_1.to_numpy())) * 12
x1 = rp.Sharpe_Risk(w_1, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
y2 = 1/(returns.shape[0]) * np.sum(np.log(1 + returns @ w_2.to_numpy())) * 12
x2 = rp.Sharpe_Risk(w_2, cov=cov, returns=returns, rm=rm, rf=rf, alpha=0.05)
ax.scatter(x=x1,
y=y1,
marker="^",
s=8**2,
c="b",
label="Max Risk Adjusted Arithmetic Return Portfolio")
ax.scatter(x=x2,
y=y2,
marker="v",
s=8**2,
c="c",
label="Max Risk Adjusted Approx Log Return Portfolio")
plt.legend()
```
| github_jupyter |
```
import os
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
from matplotlib import colors
from eofs.xarray import Eof
import tensorflow as tf
import gpflow
from esem import gp_model
import seaborn as sns
import cartopy.crs as ccrs
from utils import *
```
### Prepare data
```
# List of dataset to use for training
train_files = ["ssp126", "ssp585", "historical", "hist-GHG"]
# Create training and testing arrays
X_train = pd.concat([create_predictor_data(file) for file in train_files])
y_train_tas = np.vstack([create_predictdand_data(file)['tas'].values.reshape(-1, 96 * 144)
for file in train_files])
X_test = create_predictor_data('ssp245')
Y_test = xr.open_dataset(data_path + 'outputs_ssp245.nc').compute()
tas_truth = Y_test["tas"].mean('member')
# Drop rows including nans
nan_train_mask = X_train.isna().any(axis=1).values
X_train = X_train.dropna(axis=0, how='any')
y_train_tas = y_train_tas[~nan_train_mask]
assert len(X_train) == len(y_train_tas)
nan_test_mask = X_test.isna().any(axis=1).values
X_test = X_test.dropna(axis=0, how='any')
tas_truth = tas_truth[~nan_test_mask]
# Standardize predictor fields requiring standardization (non-EOFs)
train_CO2_mean, train_CO2_std = X_train['CO2'].mean(), X_train['CO2'].std()
train_CH4_mean, train_CH4_std = X_train['CH4'].mean(), X_train['CH4'].std()
X_train.CO2 = (X_train.CO2 - train_CO2_mean) / train_CO2_std
X_train.CH4 = (X_train.CH4 - train_CH4_mean) / train_CH4_std
X_test.CO2 = (X_test.CO2 - train_CO2_mean) / train_CO2_std
X_test.CH4 = (X_test.CH4 - train_CH4_mean) / train_CH4_std
# Standardize predictand fields
train_tas_mean, train_tas_std = y_train_tas.mean(), y_train_tas.std()
y_train_tas = (y_train_tas - train_tas_mean) / train_tas_std
```
### Prepare model
```
# Make kernel
kernel_CO2 = gpflow.kernels.Matern32(active_dims=[0])
kernel_CH4 = gpflow.kernels.Matern32(active_dims=[1])
kernel_BC = gpflow.kernels.Matern32(lengthscales=5 * [1.], active_dims=[2, 3, 4, 5, 6])
kernel_SO2 = gpflow.kernels.Matern32(lengthscales=5 * [1.], active_dims=[7, 8, 9, 10, 11])
kernel = kernel_CO2 + kernel_CH4 + kernel_BC + kernel_SO2
# Make model
np.random.seed(5)
mean = gpflow.mean_functions.Constant()
model = gpflow.models.GPR(data=(X_train.astype(np.float64),
y_train_tas.astype(np.float64)),
kernel=kernel,
mean_function=mean)
# Define optimizer
opt = gpflow.optimizers.Scipy()
# Train model
opt.minimize(model.training_loss,
variables=model.trainable_variables,
options=dict(disp=True, maxiter=1000))
```
### Predict on testing set
```
# predict
standard_posterior_mean, standard_posterior_var = model.predict_y(X_test.values)
posterior_mean = standard_posterior_mean * train_tas_std + train_tas_mean
posterior_std = np.sqrt(standard_posterior_var) * train_tas_std
# put output back into xarray format for calculating RMSE/plotting
posterior_tas = np.reshape(posterior_mean, [86, 96, 144])
posterior_tas_std = np.reshape(posterior_std, [86, 96, 144])
posterior_tas_data = xr.DataArray(posterior_tas, dims=tas_truth.dims, coords=tas_truth.coords)
posterior_tas_std_data = xr.DataArray(posterior_tas_std, dims=tas_truth.dims, coords=tas_truth.coords)
# Compute RMSEs
print(f"RMSE at 2050: {get_rmse(tas_truth[35], posterior_tas_data[35])}")
print(f"RMSE at 2100: {get_rmse(tas_truth[85], posterior_tas_data[85])}")
print(f"RMSE 2045-2055: {get_rmse(tas_truth[30:41], posterior_tas_data[30:41]).mean()}")
print(f"RMSE 2090-2100: {get_rmse(tas_truth[75:], posterior_tas_data[75:]).mean()}")
print(f"RMSE 2050-2100: {get_rmse(tas_truth[35:], posterior_tas_data[35:]).mean()}")
# plotting predictions
divnorm = colors.TwoSlopeNorm(vmin=-2., vcenter=0., vmax=5)
diffnorm = colors.TwoSlopeNorm(vmin=-2., vcenter=0., vmax=2)
## Temperature
proj = ccrs.PlateCarree()
fig = plt.figure(figsize=(18, 3))
fig.suptitle('Temperature')
# Test
plt.subplot(131, projection=proj)
tas_truth.sel(time=slice(2050,None)).mean('time').plot(cmap="coolwarm", norm=divnorm,
cbar_kwargs={"label":"Temperature change / K"})
plt.gca().coastlines()
plt.setp(plt.gca(), title='True')
# Emulator
plt.subplot(132, projection=proj)
posterior_tas_data.sel(time=slice(2050,None)).mean('time').plot(cmap="coolwarm", norm=divnorm,
cbar_kwargs={"label":"Temperature change / K"})
plt.gca().coastlines()
plt.setp(plt.gca(), title='GP posterior mean')
# Difference
difference = tas_truth - posterior_tas_data
plt.subplot(133, projection=proj)
difference.sel(time=slice(2050,None)).mean('time').plot(cmap="bwr", norm=diffnorm,
cbar_kwargs={"label":"Temperature change / K"})
plt.gca().coastlines()
plt.setp(plt.gca(), title='Difference')
```
__Feature importance__
- Mostly CO2
- Really just CO2
- Small noise variance
```
model
# Save predictions
posterior_tas_data.to_netcdf('climatebench-gp-posterior-mean-tas-test-2019-2100.nc')
posterior_tas_std_data.to_netcdf('climatebench-gp-posterior-std-tas-test-2019-2100.nc')
```
| github_jupyter |
[🥭 Mango Markets](https://mango.markets/) support is available at: [Docs](https://docs.mango.markets/) | [Discord](https://discord.gg/67jySBhxrg) | [Twitter](https://twitter.com/mangomarkets) | [Github](https://github.com/blockworks-foundation) | [Email](mailto:hello@blockworks.foundation)
[](https://mybinder.org/v2/gh/blockworks-foundation/mango-explorer-examples/HEAD?labpath=RawTransactions.ipynb) [Run this code](https://mybinder.org/v2/gh/blockworks-foundation/mango-explorer-examples/HEAD?labpath=RawTransactions.ipynb) on Binder.
_🏃♀️ To run this notebook press the ⏩ icon in the toolbar above._
# 🥭 Raw Transactions
`mango-explorer` uses `CombinableInstructions` throughout. This might be a problem if you're trying to integrate with other systems that use Solana's own `Transaction`s and `Instruction`s.
This example is nearly identical to the [CombinableInstructions](CombinalbleInstructions.ipynb) example, except that the execution of the place/crank/settle instructions uses raw `Transaction` and `TransactionInstruction` objects instead of `CombinableInstructions`' `execute()` method.
## Identical Prologue
This section of code is identical to the [CombinableInstructions](CombinalbleInstructions.ipynb) example.
```
import decimal
import mango
# Use our hard-coded devnet wallet for DeekipCw5jz7UgQbtUbHQckTYGKXWaPQV4xY93DaiM6h.
# For real-world use you'd load the bytes from the environment or a file.
wallet = mango.Wallet(bytes([67,218,68,118,140,171,228,222,8,29,48,61,255,114,49,226,239,89,151,110,29,136,149,118,97,189,163,8,23,88,246,35,187,241,107,226,47,155,40,162,3,222,98,203,176,230,34,49,45,8,253,77,136,241,34,4,80,227,234,174,103,11,124,146]))
# Signers are effectively an empty CombinableInstruction that only carries the keys for
# signing transactions
signers: mango.CombinableInstructions = mango.CombinableInstructions.from_wallet(wallet)
# Create a 'devnet' Context
context = mango.ContextBuilder.build(cluster_name="devnet")
# Load the wallet's account
group = mango.Group.load(context)
accounts = mango.Account.load_all_for_owner(context, wallet.address, group)
account = accounts[0]
# Create the right MarketOperations from the Market. We use this as an easy way to display orders.
market_operations = mango.operations(context, wallet, account, "SOL-PERP", dry_run=False)
print("Orders (initial):")
print(market_operations.load_orderbook())
# Create the right MarketInstructionBuilder from the Market
market_instructions = mango.instruction_builder(context, wallet, account, "SOL-PERP", dry_run=False)
# Go on - try to buy 1 SOL for $10.
client_id = context.generate_client_id()
order = mango.Order.from_values(side=mango.Side.BUY,
price=decimal.Decimal(10),
quantity=decimal.Decimal(1),
order_type=mango.OrderType.POST_ONLY).with_update(client_id=client_id)
```
## Raw Transaction And TransactionInstructions
This is the section of code that is different to the [CombinableInstructions](CombinalbleInstructions.ipynb) example.
Note that `market_instructions` is still used to build `CombinableInstructions` - it's the native way `mango-explorer` works - but they're then 'unwrapped'.
`CombinableInstructions` maintains a list of `TransactionInstruction`s in its `instructions` property. You can just add them to a `Transaction`s instructions by calling `extend()` on the transaction's `instructions`, for example:
```
tx.instructions.extend(combinable_instruction.instructions)
```
Signing the transaction can be done by extracting the signers from the `CombinableInstructions`' `signers` property:
```
signers = []
signers.extend(combinable_instruction.signers)
...
context.client.send_transaction(tx, *signers)
```
In the common case, where there's only the wallet signer, you can just do:
```
context.client.send_transaction(tx, wallet.keypair)
```
```
print("\n\nPlacing order:\n", order)
# Build the individual CombinableInstructions. You could add others here - the marketmaker adds in
# order cancellations and optional MNGO redeem instructions.
place_order = market_instructions.build_place_order_instructions(order)
crank = market_instructions.build_crank_instructions([])
settle = market_instructions.build_settle_instructions()
# Instead of combining them like this:
# (signers + place_order + crank + settle).execute(context)
# We now need to build the Transaction and add the Instructions and signers manually.
# Import here so the above code block really is identical to the CombinableInstructions example.
from solana.transaction import Transaction
transaction = Transaction()
transaction.instructions.extend(place_order.instructions)
transaction.instructions.extend(crank.instructions)
transaction.instructions.extend(settle.instructions)
print("Sending transaction:", transaction)
transaction_signature = context.client.send_transaction(transaction, wallet.keypair)
place_signatures = [transaction_signature]
```
## Identical Epilogue
This section is also identical to the [CombinableInstructions](CombinalbleInstructions.ipynb) example.
```
print("Waiting for place order transaction to confirm...\n")
mango.WebSocketTransactionMonitor.wait_for_all(
context.client.cluster_ws_url, place_signatures, commitment="processed"
)
print("\n\nOrders (including our new order):")
print(market_operations.load_orderbook())
cancel_signatures = market_operations.cancel_order(order)
print("\n\ncancel_signatures:\n\t", cancel_signatures)
print("Waiting for cancel order transaction to confirm...\n")
mango.WebSocketTransactionMonitor.wait_for_all(
context.client.cluster_ws_url, cancel_signatures, commitment="processed"
)
print("\n\nOrders (without our order):")
print(market_operations.load_orderbook())
context.dispose()
print("Example complete.")
```
| github_jupyter |
# はじめに
静的な場合の有限要素法問題における変位は以下のような連立方程式をとくことにより得られます。
$KU=F$
$HU=R$
ここで、$K$は剛性行列、$U$は変位ベクトルです。
一方、$F$は外力ベクトル(NEUMANN条件)であり、$HU=R$は固定端やローラー条件(DIRICHLET条件)です。
この資料は三脚のメッシュをpythonでインポートし、境界条件を設定し剛性行列$K$と外力ベクトル$F$を作成して変位$U$を計算する過程を説明したものです。
# インストールとモジュールのインポート
## インストール方法
### Linux(Ubuntu)
まずはGetfem++のpythonインターフェースのモジュールをインポートします。Ubuntu系のOSではインストールコマンドは
`$ sudo apt-get update; sudo apt-get install python-getfem++`
です。さらに、境界条件設定に使うためnumpyをインポートします。numpyはpython-getfem++と依存関係にあるため、自動的にインストールされます。インストールが終わったら、結果出力とGUI表示のため、gmshとipython-notebookをインストールしましょう。
`$ sudo apt-get install gmsh python-pip; sudo pip install notebook`
このファイルがあるディレクトリに移動
`$ ipython notebook`
で、Ipython Notebookを起動した後このファイルを開いてください。
### Windows
Python 2.7系の32bit版をインストール(Getfem++のWindows版が32bit版しかないので、32bit版でないと動かない)
https://www.python.org/ftp/python/2.7.10/python-2.7.10.msi
以下のファイルで、Python2.7系のGetfem++モジュールをインストールします。
http://download.gna.org/getfem/misc/getfem_python-4.1.win32-py2.7.exe
あとは、パスを通したpipコマンドで、numpyとipythonをインストールします。
管理者権限のコマンドライン
> pip install notebook
> pip install numpy
numpyのインストールはCコンパイラが必要になるので、メッセージをよく読みインストールをしてください。
## モジュールのインポート
慣例的にGetfem++はgfとしてインポートし、numpyはnpとしてインポートします。
```
import getfem as gf
import numpy as np
```
# パラメータの設定
まずはパラメータを設定します。この例では、このファイルからの相対パスが './mesh/tripod.mesh'であるメッシュファイルを使用します。メッシュは四面体要素です。ヤング係数$E = 1.0\times10^3$、ポアソン比$\nu = 0.3$とします。
```
file_msh = './mesh/tripod.mesh'
E = 1e3
Nu = 0.3
Lambda = E*Nu/((1+Nu)*(1-2*Nu))
Mu = E/(2*(1+Nu))
```
# メッシュの読み込み
メッシュを外部ファイルから読み込みます。メッシュの入力データはGetfem++の独自のフォーマットになっていますが、解読は容易だと思います。
```
m = gf.Mesh('load',file_msh)
m.set('optimize_structure')
```
次のコマンドで、mに設定したメッシュをgmshのスクリプトでpng画像に打ち出し確認します。
```
m.export_to_pos('./pos/m.pos')
```
以下のようにipythonの機能を使用して、システムのコマンドラインでの操作を行いIpython上に画像を表示してみます。もちろん、gmshで直接posファイルを表示することもできます。
```
%%writefile gscript
Print "./png/m.png";
Exit;
!gmsh ./pos/m.pos gscript
from IPython.core.display import Image
Image('./png/m.png')
```
これは横から見たメッシュ図です。三脚のメッシュであることがわかります。今回はこの頂点部分に荷重(NEUMANN条件)、下端に固定条件(DIRICHLET条件)を与え変位を計算することにします。
# FEMと立体求積法の設定
変数mにセットされたメッシュからそれぞれ変位応答格納用の変数と各節点データ操作用の変数を作成しておきます。GetFEM++の特徴として積分法の選択肢の多さがあります。
```
mfu = gf.MeshFem(m,3) # displacement
mfd = gf.MeshFem(m,1) # data
```
mfuとmfdにはそれぞれLagrange要素$Q_3$と$Q_1$が入ります。$Q_3$は変位用、$Q_1$はMises応力などのデータ用に準備したものです。
FEM手法として古典的なLagrange要素$P_k$を割り当てます。
| degree | dimension | d.o.f. number | class | vectorial | $\tau$-equivalent | Polynomial |
|:--------------------:|:--------------------:|:------------------------------------:|:------------:|:------------------------:|:------------------------:|:------------:|
| $K,0\leq K\leq255$ | $P,1\leq K\leq255$ | $\dfrac{\left(K+P\right)!}{K!P!}$ | $C^0$ | No$\left(Q=1\right)$ | Yes$\left(M=Id\right)$ | Yes |
```
mfu.set_fem(gf.Fem('FEM_PK(3,1)'))
mfd.set_fem(gf.Fem('FEM_PK(3,0)'))
```
立体求積法には15積分点・5次のtetrahedronを使用します。
<img src="./image/getfemlistintmethodtetrahedron5.png">
```
mim = gf.MeshIm(m,gf.Integ('IM_TETRAHEDRON(5)'))
```
# 領域の定義
次に領域を定義し、境界条件を設定する布石とします。今回は三脚の上端にNEUMANN条件を、下端にDIRICHLET条件を設定します。
大き流れとしては以下の通りです。
* 節点の座標を取得
* 節点が領域に属しているかの真偽表の配列を作成
* 領域に属している節点のみ節点番号を抜き出す
* 節点番号から要素の面の情報を抜き出す
* 要素番号と面番号の情報を元に領域に番号をつける
## 節点の座標を取得
メッシュmの節点の座標を出力するためには、m.pts()を使用します。この関数により行方向がXYZ軸、列方向が各節点を意味している座標の配列が得られます。
```
P = m.pts()
print P
```
Gmshで先ほど出力したメッシュを確認してみるとY座標が最大になっている部分に三脚の上端が、Y座標が最小になっている部分に三脚の下端があることがわかります。それぞれの座標をPで確認しておきましょう。
```
print 'Ymax = ', P[1,:].max()
print 'Ymin = ', P[1,:].min()
```
## 節点が領域に属しているかの真偽表の配列を作成
Y座標上の最大値と最小値がわかりましたので、その部分に節点が属しているかの真偽表の配列を作ります。頂部(ctop)は最大値$13$との差が$10^{-6}$の場合に節点が領域に含まれているとみなし、下端は最小値$-10$との差が$10^{-6}$の場合に領域に属しているとみなします。
```
ctop = (abs(P[1,:] - 13) < 1e-6)
print 'ctop = ', ctop
cbot = (abs(P[1,:] + 10) < 1e-6)
print 'cbot = ', cbot
```
## 領域に属している節点のみ節点番号を抜き出す
次に領域に属している節点のみ節点番号を抜き出します。意図した操作はNumpyのcompress関数とPythonのrange関数で可能です。ちなみに、m.nbptsはメッシュmの節点数(Number of Points)を意味しています。
```
pidtop = np.compress(ctop,range(0,m.nbpts()))
pidbot = np.compress(cbot,range(0,m.nbpts()))
print 'pidtop = ', pidtop
print 'pidbot = ', pidbot
```
# 節点番号から要素の面の情報を抜き出す
次に節点番号から要素の面を格納した配列を作成します。この操作はメッシュmに対してm.faces_from_pid()の関数で操作可能です。この配列には1行目に要素番号、2行目に要素内での面番号を格納しています。
```
ftop = m.faces_from_pid(pidtop)
fbot = m.faces_from_pid(pidbot)
print 'ftop = ', ftop
print 'fbot = ', fbot
```
## 要素番号と面番号の情報を元に領域に番号をつける
最後に、面の情報を元にメッシュmに境界領域を作成し付番します。使用する関数はm.set_regionです。
```
NEUMANN_BOUNDARY = 1
DIRICHLET_BOUNDARY = 2
m.set_region(NEUMANN_BOUNDARY,ftop)
m.set_region(DIRICHLET_BOUNDARY,fbot)
```
# 外力ベクトルと剛性マトリックスの組み立て
以上で設定した条件を使用して外力ベクトルと剛性行列を設定します。
```
nbd = mfd.nbdof()
F = gf.asm_boundary_source(NEUMANN_BOUNDARY, mim, mfu, mfd, np.repeat([[0],[-100],[0]],nbd,1))
K = gf.asm_linear_elasticity(mim, mfu, mfd, np.repeat([Lambda], nbd), np.repeat([Mu], nbd))
sl = gf.Slice(('boundary',), mfu, 1)
sl.export_to_pos('./pos/F.pos',mfu,F,'F')
%%writefile gscript
Print "./png/F.png";
Exit;
!gmsh ./pos/F.pos gscript
from IPython.core.display import Image
Image('./png/F.png')
```
# 固定条件の設定
DIRICHLET条件(固定端条件)の設定をします。DIRICHLET条件は以下のような式で表される境界条件です。
$HU = R$
固定条件を与える場合は対象領域の節点に
$\left[\begin{array}{ccc}
1\\
& 1\\
& & 1
\end{array}\right]\left\{ \begin{array}{c}
U_{x}\\
U_{y}\\
U_{z}
\end{array}\right\} =\left\{ \begin{array}{c}
0\\
0\\
0
\end{array}\right\} $
の関係を与える必要があります。すなわち、対象領域のみに
$H=\left[\begin{array}{ccc}
1\\
& 1\\
& & 1
\end{array}\right]$、$R=\left\{ \begin{array}{c}
0\\
0\\
0
\end{array}\right\} $
になる行列を与えてれる関数が必要です。それが以下のgf.asm_dirichlet関数です。
```
(H,R) = gf.asm_dirichlet(DIRICHLET_BOUNDARY, mim, mfu, mfd, mfd.eval('[[1,0,0],[0,1,0],[0,0,1]]'), mfd.eval('[0,0,0]'))
```
さて、Getfem++では、はじめにご説明した連立方程式の問題を以下のように言い換えます。
$KU = F$ ただし、$HU = R$
$\Downarrow$
$(N^TKN)U^* = N^TF$ ただし、$U = NU^* + U_0$
この$N$は例えば条件が固定端の場合にはその自由度の行と列を削除する効果があります。この$N$と$U_0$は次の関数で計算できます。
```
(N,U0) = H.dirichlet_nullspace(R)
Nt = gf.Spmat('copy',N)
Nt.transpose()
KK = Nt*K*N
FF = Nt*(F-K*U0)
```
# 変位の計算
以上で計算するべき連立方程式の剛性行列と外力ベクトルが定まりましたので、連立方程式を解きます。Getfem++のモジュールで剛性行列からプリコンディショナーを用意し、CG法を利用して変位を計算します。
```
P = gf.Precond('ildlt',KK)
UU = gf.linsolve_cg(KK,FF,P)
U = N*UU+U0
```
# ポスト処理
以上で計算した変位をポスト処理結果として出力します。まずスライスモジュールを使用して、メッシュの外側の部分のみ抜き出します。次にスライスオブジェクトに変位の計算結果と凡例を渡して、posファイルに出力します。これで、'Displacement'と凡例のあるposファイルが'./pos/m_result.pos'というファイルに出力されたことになります。
```
sl = gf.Slice(('boundary',), mfu, 1)
sl.export_to_pos('./pos/m_result.pos', mfu, U, 'Displacement')
%%writefile gscript
Print "./png/m_result.png";
Exit;
!gmsh ./pos/m_result.pos gscript
from IPython.core.display import Image
Image('./png/m_result.png')
```
# 結果の可視化
以上の様にそれぞれの方向から見た変位の計算結果をコンターで可視化することが可能です。sl.export_to_posという別の関数を使えばParaviewでvtkファイルによる可視化も可能です。(ただし、VTKファイル出力はWindows上ではうまくいきません。テキストファイル出力のgmshが安定しています。)
# まとめ
以上、メッシュの読み込みから要素と積分点の設定、領域と境界条件の定義から変位の計算のポスト出力までを行いました。もともと、Pythonは行列の操作がとても簡単であるため、Getfem++のモジュールを使用することにより有限要素法の実施が可能です。
今後の話題として以下のようなものを用意しています。
* Pythonによる有限要素法の固有値解析(構造)
* Pythonによる時刻歴応答解析(構造)
| github_jupyter |
# Project 2: Chapter 2 - Working with Lists
## Lists can hold any kind of object
```
empty_list = []
int_list = [1,2,3,4,5]
float_list = [1.0, 2.0, 3.0, 4.0, 5.0]
string_list = ["Many words", "impoverished meaning"]
mixed_list = [1, 2.0, "Mix it up"]
print(empty_list)
print(int_list)
print(float_list)
print(string_list)
print(mixed_list)
```
Let's check the types of objects in the last list.
```
type(mixed_list)
```
To access elements in a list, you must call the index which starts from 0 and counts upward with each additional element.
```
mixed_list[0], type(mixed_list[0])
mixed_list[1], type(mixed_list[1])
mixed_list[2], type(mixed_list[2])
```
## Concatenate lists
```
list1 = [4,6,32,6,7,98]
list2 = [1,6,3,7,89,0]
join_lists = list1 + list2
list1
list2
join_lists
```
Remember this is just like concatenating strings
```
str1 = "Some string"
str2 = "Another string to concatenate with str1"
join_strings = str1 + str2
join_strings
join_strings[2]
```
## List slices
Suppose that you want to call a subset of a list or string. You can do this by using calling lst[start: end]
```
join_lists
join_lists[:5]
join_lists[0:5]
join_strings[:5]
join_strings[0:5]
join_strings[5:]
```
If you call lst[-1], it will access the last element in the list.
```
join_lists[-1], join_strings[-1]
```
You can count from the end of the list using the negative sign (-). If you count backword after the first colon, this will call all except for the last i elements for a command lst[:-i].
```
join_lists[:-1], join_strings[:-1]
join_lists[:-5], join_strings[:-5]
```
## For Loops
```
list1 = [1,2,3,4,5]
list2 = [6,5,4,3,100]
print("list1:", list1)
print("list2:", list2)
# create a blank list that we will use to generate the same
# results that we achieved using the + sign: concatenation
concat_list = []
len_list1 = len(list1)
len_list2 = len(list2)
# first let's concatenate
for i in range(0,len_list1):
concat_list.append(list1[i])
print(i, list1[i])
print(concat_list)
for i in range(0, len_list2):
print(i, list2[i])
concat_list.append(list2[i])
print(concat_list, list1 + list2)
sum_list = []
if len_list1 == len_list2:
for i in range(len_list1):
sum_list.append(list1[i] + list2[i])
print("sum_list (append):", sum_list)
sum_list = []
if len_list1 == len_list2:
for i in range(0, len_list1 - 1):
# lst.insert(index, value)
sum_list.insert(i, list1[i] + list2[i])
print("sum_list (insert):", sum_list)
1 == 1
1 != 1 # =/=
if 1 == 1:
print("statement is", 1 == 1)
for i in range(10):
print("i ==", i, "i < 5:", i < 5)
list1 = [5,
4,
8,
0,
3,
5]
list2 = ["red",
"blue",
"orange",
"white",
"grey",
"black"]
print(list1)
print(list2)
sorted_list1 = sorted(list1)#, reverse = True)
sorted_list2 = sorted(list2)
sorted_list1[::-1], sorted_list2[::2]
list3 = ["1", 22, "3", 23, "5"]
try:
sorted_list3 = sorted(list3)
except:
print("TypeError: unorderable types: str < int")
# generator function creates list using for loop
# within the list created
alpha_list3 = [str(val) for val in list3]
num_list3 = []
for val in list3:
num_list3.append(int(val))
print(alpha_list3)
print(num_list3)
sorted(alpha_list3), sorted(num_list3)
```
You can nest loops, meaning that you can add a loop within a loop.
```
print("i", "j", "k")
i_list = list(range(3))
j_list = list(range(5))
k_list = list(range(4))
for i in range(3):
for j in range(5):
for k in range(4):
print(i, j, k)
print(i_list, j_list, k_list, sep = "\n")
```
| github_jupyter |
<a href="https://colab.research.google.com/github/satyajitghana/TSAI-DeepNLP-END2.0/blob/main/10_Seq2Seq_Attention/seq2seq-translation/seq2seq-translation-batched.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# Practical PyTorch: Translation with a Sequence to Sequence Network and Attention
In this project we will be teaching a neural network to translate from French to English.
```
[KEY: > input, = target, < output]
> il est en train de peindre un tableau .
= he is painting a picture .
< he is painting a picture .
> pourquoi ne pas essayer ce vin delicieux ?
= why not try that delicious wine ?
< why not try that delicious wine ?
> elle n est pas poete mais romanciere .
= she is not a poet but a novelist .
< she not not a poet but a novelist .
> vous etes trop maigre .
= you re too skinny .
< you re all alone .
```
... to varying degrees of success.
This is made possible by the simple but powerful idea of the [sequence to sequence network](http://arxiv.org/abs/1409.3215), in which two recurrent neural networks work together to transform one sequence to another. An encoder network condenses an input sequence into a single vector, and a decoder network unfolds that vector into a new sequence.
To improve upon this model we'll use an [attention mechanism](https://arxiv.org/abs/1409.0473), which lets the decoder learn to focus over a specific range of the input sequence.
# Sequence to Sequence Learning
A [Sequence to Sequence network](http://arxiv.org/abs/1409.3215), or seq2seq network, or [Encoder Decoder network](https://arxiv.org/pdf/1406.1078v3.pdf), is a model consisting of two separate RNNs called the **encoder** and **decoder**. The encoder reads an input sequence one item at a time, and outputs a vector at each step. The final output of the encoder is kept as the **context** vector. The decoder uses this context vector to produce a sequence of outputs one step at a time.

When using a single RNN, there is a one-to-one relationship between inputs and outputs. We would quickly run into problems with different sequence orders and lengths that are common during translation. Consider the simple sentence "Je ne suis pas le chat noir" → "I am not the black cat". Many of the words have a pretty direct translation, like "chat" → "cat". However the differing grammars cause words to be in different orders, e.g. "chat noir" and "black cat". There is also the "ne ... pas" → "not" construction that makes the two sentences have different lengths.
With the seq2seq model, by encoding many inputs into one vector, and decoding from one vector into many outputs, we are freed from the constraints of sequence order and length. The encoded sequence is represented by a single vector, a single point in some N dimensional space of sequences. In an ideal case, this point can be considered the "meaning" of the sequence.
This idea can be extended beyond sequences. Image captioning tasks take an [image as input, and output a description](https://arxiv.org/abs/1411.4555) of the image (img2seq). Some image generation tasks take a [description as input and output a generated image](https://arxiv.org/abs/1511.02793) (seq2img). These models can be referred to more generally as "encoder decoder" networks.
## The Attention Mechanism
The fixed-length vector carries the burden of encoding the the entire "meaning" of the input sequence, no matter how long that may be. With all the variance in language, this is a very hard problem. Imagine two nearly identical sentences, twenty words long, with only one word different. Both the encoders and decoders must be nuanced enough to represent that change as a very slightly different point in space.
The **attention mechanism** [introduced by Bahdanau et al.](https://arxiv.org/abs/1409.0473) addresses this by giving the decoder a way to "pay attention" to parts of the input, rather than relying on a single vector. For every step the decoder can select a different part of the input sentence to consider.

Attention is calculated using the current hidden state and each encoder output, resulting in a vector the same size as the input sequence, called the *attention weights*. These weights are multiplied by the encoder outputs to create a weighted sum of encoder outputs, which is called the *context* vector. The context vector and hidden state are used to predict the next output element.

# Requirements
You will need [PyTorch](http://pytorch.org/) to build and train the models, and [matplotlib](https://matplotlib.org/) for plotting training and visualizing attention outputs later. The rest are builtin Python libraries.
```
import unicodedata
import string
import re
import random
import time
import datetime
import math
import socket
hostname = socket.gethostname()
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence#, masked_cross_entropy
from masked_cross_entropy import *
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
%matplotlib inline
```
Here we will also define a constant to decide whether to use the GPU (with CUDA specifically) or the CPU. **If you don't have a GPU, set this to `False`**. Later when we create tensors, this variable will be used to decide whether we keep them on CPU or move them to GPU.
```
USE_CUDA = True
```
## Loading data files
The data for this project is a set of many thousands of English to French translation pairs.
[This question on Open Data Stack Exchange](http://opendata.stackexchange.com/questions/3888/dataset-of-sentences-translated-into-many-languages) pointed me to the open translation site http://tatoeba.org/ which has downloads available at http://tatoeba.org/eng/downloads - and better yet, someone did the extra work of splitting language pairs into individual text files here: http://www.manythings.org/anki/
The English to French pairs are too big to include in the repo, so download `fra-eng.zip`, extract the text file in there, and rename it to `data/eng-fra.txt` before continuing (for some reason the zipfile is named backwards). The file is a tab separated list of translation pairs:
```
I am cold. Je suis froid.
```
Similar to the character encoding used in the character-level RNN tutorials, we will be representing each word in a language as a one-hot vector, or giant vector of zeros except for a single one (at the index of the word). Compared to the dozens of characters that might exist in a language, there are many many more words, so the encoding vector is much larger. We will however cheat a bit and trim the data to only use a few thousand words per language.
### Indexing words
We'll need a unique index per word to use as the inputs and targets of the networks later. To keep track of all this we will use a helper class called `Lang` which has word → index (`word2index`) and index → word (`index2word`) dictionaries, as well as a count of each word (`word2count`). This class includes a function `trim(min_count)` to remove rare words once they are all counted.
```
PAD_token = 0
SOS_token = 1
EOS_token = 2
class Lang:
def __init__(self, name):
self.name = name
self.trimmed = False
self.word2index = {}
self.word2count = {}
self.index2word = {0: "PAD", 1: "SOS", 2: "EOS"}
self.n_words = 3 # Count default tokens
def index_words(self, sentence):
for word in sentence.split(' '):
self.index_word(word)
def index_word(self, word):
if word not in self.word2index:
self.word2index[word] = self.n_words
self.word2count[word] = 1
self.index2word[self.n_words] = word
self.n_words += 1
else:
self.word2count[word] += 1
# Remove words below a certain count threshold
def trim(self, min_count):
if self.trimmed: return
self.trimmed = True
keep_words = []
for k, v in self.word2count.items():
if v >= min_count:
keep_words.append(k)
print('keep_words %s / %s = %.4f' % (
len(keep_words), len(self.word2index), len(keep_words) / len(self.word2index)
))
# Reinitialize dictionaries
self.word2index = {}
self.word2count = {}
self.index2word = {0: "PAD", 1: "SOS", 2: "EOS"}
self.n_words = 3 # Count default tokens
for word in keep_words:
self.index_word(word)
```
### Reading and decoding files
The files are all in Unicode, to simplify we will turn Unicode characters to ASCII, make everything lowercase, and trim most punctuation.
```
# Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427
def unicode_to_ascii(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn'
)
# Lowercase, trim, and remove non-letter characters
def normalize_string(s):
s = unicode_to_ascii(s.lower().strip())
s = re.sub(r"([,.!?])", r" \1 ", s)
s = re.sub(r"[^a-zA-Z,.!?]+", r" ", s)
s = re.sub(r"\s+", r" ", s).strip()
return s
```
To read the data file we will split the file into lines, and then split lines into pairs. The files are all English → Other Language, so if we want to translate from Other Language → English I added the `reverse` flag to reverse the pairs.
```
def read_langs(lang1, lang2, reverse=False):
print("Reading lines...")
# Read the file and split into lines
# filename = '../data/%s-%s.txt' % (lang1, lang2)
filename = '../%s-%s.txt' % (lang1, lang2)
lines = open(filename).read().strip().split('\n')
# Split every line into pairs and normalize
pairs = [[normalize_string(s) for s in l.split('\t')] for l in lines]
# Reverse pairs, make Lang instances
if reverse:
pairs = [list(reversed(p)) for p in pairs]
input_lang = Lang(lang2)
output_lang = Lang(lang1)
else:
input_lang = Lang(lang1)
output_lang = Lang(lang2)
return input_lang, output_lang, pairs
MIN_LENGTH = 3
MAX_LENGTH = 25
def filter_pairs(pairs):
filtered_pairs = []
for pair in pairs:
if len(pair[0]) >= MIN_LENGTH and len(pair[0]) <= MAX_LENGTH \
and len(pair[1]) >= MIN_LENGTH and len(pair[1]) <= MAX_LENGTH:
filtered_pairs.append(pair)
return filtered_pairs
```
The full process for preparing the data is:
* Read text file and split into lines
* Split lines into pairs and normalize
* Filter to pairs of a certain length
* Make word lists from sentences in pairs
```
def prepare_data(lang1_name, lang2_name, reverse=False):
input_lang, output_lang, pairs = read_langs(lang1_name, lang2_name, reverse)
print("Read %d sentence pairs" % len(pairs))
pairs = filter_pairs(pairs)
print("Filtered to %d pairs" % len(pairs))
print("Indexing words...")
for pair in pairs:
input_lang.index_words(pair[0])
output_lang.index_words(pair[1])
print('Indexed %d words in input language, %d words in output' % (input_lang.n_words, output_lang.n_words))
return input_lang, output_lang, pairs
input_lang, output_lang, pairs = prepare_data('eng', 'fra', True)
```
### Filtering vocabularies
To get something that trains in under an hour, we'll trim the data set a bit. First we will use the `trim` function on each language (defined above) to only include words that are repeated a certain amount of times through the dataset (this softens the difficulty of learning a correct translation for words that don't appear often).
```
MIN_COUNT = 5
input_lang.trim(MIN_COUNT)
output_lang.trim(MIN_COUNT)
```
### Filtering pairs
Now we will go back to the set of all sentence pairs and remove those with unknown words.
```
keep_pairs = []
for pair in pairs:
input_sentence = pair[0]
output_sentence = pair[1]
keep_input = True
keep_output = True
for word in input_sentence.split(' '):
if word not in input_lang.word2index:
keep_input = False
break
for word in output_sentence.split(' '):
if word not in output_lang.word2index:
keep_output = False
break
# Remove if pair doesn't match input and output conditions
if keep_input and keep_output:
keep_pairs.append(pair)
print("Trimmed from %d pairs to %d, %.4f of total" % (len(pairs), len(keep_pairs), len(keep_pairs) / len(pairs)))
pairs = keep_pairs
```
## Turning training data into Tensors
To train we need to turn the sentences into something the neural network can understand, which of course means numbers. Each sentence will be split into words and turned into a `LongTensor` which represents the index (from the Lang indexes made earlier) of each word. While creating these tensors we will also append the EOS token to signal that the sentence is over.

```
# Return a list of indexes, one for each word in the sentence, plus EOS
def indexes_from_sentence(lang, sentence):
return [lang.word2index[word] for word in sentence.split(' ')] + [EOS_token]
```
We can make better use of the GPU by training on batches of many sequences at once, but doing so brings up the question of how to deal with sequences of varying lengths. The simple solution is to "pad" the shorter sentences with some padding symbol (in this case `0`), and ignore these padded spots when calculating the loss.

```
# Pad a with the PAD symbol
def pad_seq(seq, max_length):
seq += [PAD_token for i in range(max_length - len(seq))]
return seq
```
To create a Variable for a full batch of inputs (and targets) we get a random sample of sequences and pad them all to the length of the longest sequence. We'll keep track of the lengths of each batch in order to un-pad later.
Initializing a `LongTensor` with an array (batches) of arrays (sequences) gives us a `(batch_size x max_len)` tensor - selecting the first dimension gives you a single batch, which is a full sequence. When training the model we'll want a single time step at once, so we'll transpose to `(max_len x batch_size)`. Now selecting along the first dimension returns a single time step across batches.

```
def random_batch(batch_size):
input_seqs = []
target_seqs = []
# Choose random pairs
for i in range(batch_size):
pair = random.choice(pairs)
input_seqs.append(indexes_from_sentence(input_lang, pair[0]))
target_seqs.append(indexes_from_sentence(output_lang, pair[1]))
# Zip into pairs, sort by length (descending), unzip
seq_pairs = sorted(zip(input_seqs, target_seqs), key=lambda p: len(p[0]), reverse=True)
input_seqs, target_seqs = zip(*seq_pairs)
# For input and target sequences, get array of lengths and pad with 0s to max length
input_lengths = [len(s) for s in input_seqs]
input_padded = [pad_seq(s, max(input_lengths)) for s in input_seqs]
target_lengths = [len(s) for s in target_seqs]
target_padded = [pad_seq(s, max(target_lengths)) for s in target_seqs]
# Turn padded arrays into (batch_size x max_len) tensors, transpose into (max_len x batch_size)
input_var = Variable(torch.LongTensor(input_padded)).transpose(0, 1)
target_var = Variable(torch.LongTensor(target_padded)).transpose(0, 1)
if USE_CUDA:
input_var = input_var.cuda()
target_var = target_var.cuda()
return input_var, input_lengths, target_var, target_lengths
```
We can test this to see that it will return a `(max_len x batch_size)` tensor for input and target sentences, along with a corresponding list of batch lenghts for each (which we will use for masking later).
```
random_batch(2)
```
# Building the models
## The Encoder
<img src="https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/images/encoder-network.png?raw=1" style="float: right" />
The encoder will take a batch of word sequences, a `LongTensor` of size `(max_len x batch_size)`, and output an encoding for each word, a `FloatTensor` of size `(max_len x batch_size x hidden_size)`.
The word inputs are fed through an [embedding layer `nn.Embedding`](http://pytorch.org/docs/nn.html#embedding) to create an embedding for each word, with size `seq_len x hidden_size` (as if it was a batch of words). This is resized to `seq_len x 1 x hidden_size` to fit the expected input of the [GRU layer `nn.GRU`](http://pytorch.org/docs/nn.html#gru). The GRU will return both an output sequence of size `seq_len x hidden_size`.
```
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size, n_layers=1, dropout=0.1):
super(EncoderRNN, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.n_layers = n_layers
self.dropout = dropout
self.embedding = nn.Embedding(input_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=self.dropout, bidirectional=True)
def forward(self, input_seqs, input_lengths, hidden=None):
# Note: we run this all at once (over multiple batches of multiple sequences)
embedded = self.embedding(input_seqs)
packed = torch.nn.utils.rnn.pack_padded_sequence(embedded, input_lengths)
outputs, hidden = self.gru(packed, hidden)
outputs, output_lengths = torch.nn.utils.rnn.pad_packed_sequence(outputs) # unpack (back to padded)
outputs = outputs[:, :, :self.hidden_size] + outputs[:, : ,self.hidden_size:] # Sum bidirectional outputs
return outputs, hidden
```
## Attention Decoder
### Interpreting the Bahdanau et al. model
[Neural Machine Translation by Jointly Learning to Align and Translate](https://arxiv.org/abs/1409.0473) (Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio) introduced the idea of using attention for seq2seq translation.
Each decoder output is conditioned on the previous outputs and some $\mathbf x$, where $\mathbf x$ consists of the current hidden state (which takes into account previous outputs) and the attention "context", which is calculated below. The function $g$ is a fully-connected layer with a nonlinear activation, which takes as input the values $y_{i-1}$, $s_i$, and $c_i$ concatenated.
$$
p(y_i \mid \{y_1,...,y_{i-1}\},\mathbf{x}) = g(y_{i-1}, s_i, c_i)
$$
The current hidden state $s_i$ is calculated by an RNN $f$ with the last hidden state $s_{i-1}$, last decoder output value $y_{i-1}$, and context vector $c_i$.
In the code, the RNN will be a `nn.GRU` layer, the hidden state $s_i$ will be called `hidden`, the output $y_i$ called `output`, and context $c_i$ called `context`.
$$
s_i = f(s_{i-1}, y_{i-1}, c_i)
$$
The context vector $c_i$ is a weighted sum of all encoder outputs, where each weight $a_{ij}$ is the amount of "attention" paid to the corresponding encoder output $h_j$.
$$
c_i = \sum_{j=1}^{T_x} a_{ij} h_j
$$
... where each weight $a_{ij}$ is a normalized (over all steps) attention "energy" $e_{ij}$ ...
$$
a_{ij} = \dfrac{exp(e_{ij})}{\sum_{k=1}^{T} exp(e_{ik})}
$$
... where each attention energy is calculated with some function $a$ (such as another linear layer) using the last hidden state $s_{i-1}$ and that particular encoder output $h_j$:
$$
e_{ij} = a(s_{i-1}, h_j)
$$
### Interpreting the Luong et al. models
[Effective Approaches to Attention-based Neural Machine Translation](https://arxiv.org/abs/1508.04025) (Minh-Thang Luong, Hieu Pham, Christopher D. Manning) describe a few more attention models that offer improvements and simplifications. They describe a few "global attention" models, the distinction between them being the way the attention scores are calculated.
The general form of the attention calculation relies on the target (decoder) side hidden state and corresponding source (encoder) side state, normalized over all states to get values summing to 1:
$$
a_t(s) = align(h_t, \bar h_s) = \dfrac{exp(score(h_t, \bar h_s))}{\sum_{s'} exp(score(h_t, \bar h_{s'}))}
$$
The specific "score" function that compares two states is either *dot*, a simple dot product between the states; *general*, a a dot product between the decoder hidden state and a linear transform of the encoder state; or *concat*, a dot product between a new parameter $v_a$ and a linear transform of the states concatenated together.
$$
score(h_t, \bar h_s) =
\begin{cases}
h_t ^\top \bar h_s & dot \\
h_t ^\top \textbf{W}_a \bar h_s & general \\
v_a ^\top \textbf{W}_a [ h_t ; \bar h_s ] & concat
\end{cases}
$$
The modular definition of these scoring functions gives us an opportunity to build specific attention module that can switch between the different score methods. The input to this module is always the hidden state (of the decoder RNN) and set of encoder outputs.
### Implementing an attention module
```
class Attn(nn.Module):
def __init__(self, method, hidden_size):
super(Attn, self).__init__()
self.method = method
self.hidden_size = hidden_size
if self.method == 'general':
self.attn = nn.Linear(self.hidden_size, hidden_size)
elif self.method == 'concat':
self.attn = nn.Linear(self.hidden_size * 2, hidden_size)
self.v = nn.Parameter(torch.FloatTensor(1, hidden_size))
def forward(self, hidden, encoder_outputs):
max_len = encoder_outputs.size(0)
this_batch_size = encoder_outputs.size(1)
# Create variable to store attention energies
attn_energies = Variable(torch.zeros(this_batch_size, max_len)) # B x S
if USE_CUDA:
attn_energies = attn_energies.cuda()
# For each batch of encoder outputs
for b in range(this_batch_size):
# Calculate energy for each encoder output
for i in range(max_len):
attn_energies[b, i] = self.score(hidden[:, b], encoder_outputs[i, b].unsqueeze(0))
# Normalize energies to weights in range 0 to 1, resize to 1 x B x S
return F.softmax(attn_energies).unsqueeze(1)
def score(self, hidden, encoder_output):
if self.method == 'dot':
energy = hidden.dot(encoder_output)
return energy
elif self.method == 'general':
energy = self.attn(encoder_output)
energy = hidden.dot(energy)
return energy
elif self.method == 'concat':
energy = self.attn(torch.cat((hidden, encoder_output), 1))
energy = self.v.dot(energy)
return energy
```
### Implementing the Bahdanau et al. model
In summary our decoder should consist of four main parts - an embedding layer turning an input word into a vector; a layer to calculate the attention energy per encoder output; a RNN layer; and an output layer.
The decoder's inputs are the last RNN hidden state $s_{i-1}$, last output $y_{i-1}$, and all encoder outputs $h_*$.
* embedding layer with inputs $y_{i-1}$
* `embedded = embedding(last_rnn_output)`
* attention layer $a$ with inputs $(s_{i-1}, h_j)$ and outputs $e_{ij}$, normalized to create $a_{ij}$
* `attn_energies[j] = attn_layer(last_hidden, encoder_outputs[j])`
* `attn_weights = normalize(attn_energies)`
* context vector $c_i$ as an attention-weighted average of encoder outputs
* `context = sum(attn_weights * encoder_outputs)`
* RNN layer(s) $f$ with inputs $(s_{i-1}, y_{i-1}, c_i)$ and internal hidden state, outputting $s_i$
* `rnn_input = concat(embedded, context)`
* `rnn_output, rnn_hidden = rnn(rnn_input, last_hidden)`
* an output layer $g$ with inputs $(y_{i-1}, s_i, c_i)$, outputting $y_i$
* `output = out(embedded, rnn_output, context)`
```
class BahdanauAttnDecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size, n_layers=1, dropout_p=0.1):
super(BahdanauAttnDecoderRNN, self).__init__()
# Define parameters
self.hidden_size = hidden_size
self.output_size = output_size
self.n_layers = n_layers
self.dropout_p = dropout_p
self.max_length = max_length
# Define layers
self.embedding = nn.Embedding(output_size, hidden_size)
self.dropout = nn.Dropout(dropout_p)
self.attn = Attn('concat', hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=dropout_p)
self.out = nn.Linear(hidden_size, output_size)
def forward(self, word_input, last_hidden, encoder_outputs):
# Note: we run this one step at a time
# TODO: FIX BATCHING
# Get the embedding of the current input word (last output word)
word_embedded = self.embedding(word_input).view(1, 1, -1) # S=1 x B x N
word_embedded = self.dropout(word_embedded)
# Calculate attention weights and apply to encoder outputs
attn_weights = self.attn(last_hidden[-1], encoder_outputs)
context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # B x 1 x N
context = context.transpose(0, 1) # 1 x B x N
# Combine embedded input word and attended context, run through RNN
rnn_input = torch.cat((word_embedded, context), 2)
output, hidden = self.gru(rnn_input, last_hidden)
# Final output layer
output = output.squeeze(0) # B x N
output = F.log_softmax(self.out(torch.cat((output, context), 1)))
# Return final output, hidden state, and attention weights (for visualization)
return output, hidden, attn_weights
```
Now we can build a decoder that plugs this Attn module in after the RNN to calculate attention weights, and apply those weights to the encoder outputs to get a context vector.
```
class LuongAttnDecoderRNN(nn.Module):
def __init__(self, attn_model, hidden_size, output_size, n_layers=1, dropout=0.1):
super(LuongAttnDecoderRNN, self).__init__()
# Keep for reference
self.attn_model = attn_model
self.hidden_size = hidden_size
self.output_size = output_size
self.n_layers = n_layers
self.dropout = dropout
# Define layers
self.embedding = nn.Embedding(output_size, hidden_size)
self.embedding_dropout = nn.Dropout(dropout)
self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=dropout)
self.concat = nn.Linear(hidden_size * 2, hidden_size)
self.out = nn.Linear(hidden_size, output_size)
# Choose attention model
if attn_model != 'none':
self.attn = Attn(attn_model, hidden_size)
def forward(self, input_seq, last_hidden, encoder_outputs):
# Note: we run this one step at a time
# Get the embedding of the current input word (last output word)
batch_size = input_seq.size(0)
embedded = self.embedding(input_seq)
embedded = self.embedding_dropout(embedded)
embedded = embedded.view(1, batch_size, self.hidden_size) # S=1 x B x N
# Get current hidden state from input word and last hidden state
rnn_output, hidden = self.gru(embedded, last_hidden)
# Calculate attention from current RNN state and all encoder outputs;
# apply to encoder outputs to get weighted average
attn_weights = self.attn(rnn_output, encoder_outputs)
context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # B x S=1 x N
# Attentional vector using the RNN hidden state and context vector
# concatenated together (Luong eq. 5)
rnn_output = rnn_output.squeeze(0) # S=1 x B x N -> B x N
context = context.squeeze(1) # B x S=1 x N -> B x N
concat_input = torch.cat((rnn_output, context), 1)
concat_output = F.tanh(self.concat(concat_input))
# Finally predict next token (Luong eq. 6, without softmax)
output = self.out(concat_output)
# Return final output, hidden state, and attention weights (for visualization)
return output, hidden, attn_weights
```
## Testing the models
To make sure the encoder and decoder modules are working (and working together) we'll do a full test with a small batch.
```
small_batch_size = 3
input_batches, input_lengths, target_batches, target_lengths = random_batch(small_batch_size)
print('input_batches', input_batches.size()) # (max_len x batch_size)
print('target_batches', target_batches.size()) # (max_len x batch_size)
```
Create models with a small size (a good idea for eyeball inspection):
```
small_hidden_size = 8
small_n_layers = 2
encoder_test = EncoderRNN(input_lang.n_words, small_hidden_size, small_n_layers)
decoder_test = LuongAttnDecoderRNN('general', small_hidden_size, output_lang.n_words, small_n_layers)
if USE_CUDA:
encoder_test.cuda()
decoder_test.cuda()
```
To test the encoder, run the input batch through to get per-batch encoder outputs:
```
encoder_outputs, encoder_hidden = encoder_test(input_batches, input_lengths, None)
print('encoder_outputs', encoder_outputs.size()) # max_len x batch_size x hidden_size
print('encoder_hidden', encoder_hidden.size()) # n_layers * 2 x batch_size x hidden_size
```
Then starting with a SOS token, run word tokens through the decoder to get each next word token. Instead of doing this with the whole sequence, it is done one at a time, to support using it's own predictions to make the next prediction. This will be one time step at a time, but batched per time step. In order to get this to work for short padded sequences, the batch size is going to get smaller each time.
```
max_target_length = max(target_lengths)
# Prepare decoder input and outputs
decoder_input = Variable(torch.LongTensor([SOS_token] * small_batch_size))
decoder_hidden = encoder_hidden[:decoder_test.n_layers] # Use last (forward) hidden state from encoder
all_decoder_outputs = Variable(torch.zeros(max_target_length, small_batch_size, decoder_test.output_size))
if USE_CUDA:
all_decoder_outputs = all_decoder_outputs.cuda()
decoder_input = decoder_input.cuda()
# Run through decoder one time step at a time
for t in range(max_target_length):
decoder_output, decoder_hidden, decoder_attn = decoder_test(
decoder_input, decoder_hidden, encoder_outputs
)
all_decoder_outputs[t] = decoder_output # Store this step's outputs
decoder_input = target_batches[t] # Next input is current target
# Test masked cross entropy loss
loss = masked_cross_entropy(
all_decoder_outputs.transpose(0, 1).contiguous(),
target_batches.transpose(0, 1).contiguous(),
target_lengths
)
print('loss', loss.data[0])
```
# Training
## Defining a training iteration
To train we first run the input sentence through the encoder word by word, and keep track of every output and the latest hidden state. Next the decoder is given the last hidden state of the decoder as its first hidden state, and the `<SOS>` token as its first input. From there we iterate to predict a next token from the decoder.
### Teacher Forcing vs. Scheduled Sampling
"Teacher Forcing", or maximum likelihood sampling, means using the real target outputs as each next input when training. The alternative is using the decoder's own guess as the next input. Using teacher forcing may cause the network to converge faster, but [when the trained network is exploited, it may exhibit instability](http://minds.jacobs-university.de/sites/default/files/uploads/papers/ESNTutorialRev.pdf).
You can observe outputs of teacher-forced networks that read with coherent grammar but wander far from the correct translation - you could think of it as having learned how to listen to the teacher's instructions, without learning how to venture out on its own.
The solution to the teacher-forcing "problem" is known as [Scheduled Sampling](https://arxiv.org/abs/1506.03099), which simply alternates between using the target values and predicted values when training. We will randomly choose to use teacher forcing with an if statement while training - sometimes we'll feed use real target as the input (ignoring the decoder's output), sometimes we'll use the decoder's output.
```
def train(input_batches, input_lengths, target_batches, target_lengths, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):
# Zero gradients of both optimizers
encoder_optimizer.zero_grad()
decoder_optimizer.zero_grad()
loss = 0 # Added onto for each word
# Run words through encoder
encoder_outputs, encoder_hidden = encoder(input_batches, input_lengths, None)
# Prepare input and output variables
decoder_input = Variable(torch.LongTensor([SOS_token] * batch_size))
decoder_hidden = encoder_hidden[:decoder.n_layers] # Use last (forward) hidden state from encoder
max_target_length = max(target_lengths)
all_decoder_outputs = Variable(torch.zeros(max_target_length, batch_size, decoder.output_size))
# Move new Variables to CUDA
if USE_CUDA:
decoder_input = decoder_input.cuda()
all_decoder_outputs = all_decoder_outputs.cuda()
# Run through decoder one time step at a time
for t in range(max_target_length):
decoder_output, decoder_hidden, decoder_attn = decoder(
decoder_input, decoder_hidden, encoder_outputs
)
all_decoder_outputs[t] = decoder_output
decoder_input = target_batches[t] # Next input is current target
# Loss calculation and backpropagation
loss = masked_cross_entropy(
all_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq
target_batches.transpose(0, 1).contiguous(), # -> batch x seq
target_lengths
)
loss.backward()
# Clip gradient norms
ec = torch.nn.utils.clip_grad_norm(encoder.parameters(), clip)
dc = torch.nn.utils.clip_grad_norm(decoder.parameters(), clip)
# Update parameters with optimizers
encoder_optimizer.step()
decoder_optimizer.step()
return loss.data[0], ec, dc
```
## Running training
With everything in place we can actually initialize a network and start training.
To start, we initialize models, optimizers, a loss function (criterion), and set up variables for plotting and tracking progress:
```
# Configure models
attn_model = 'dot'
hidden_size = 500
n_layers = 2
dropout = 0.1
batch_size = 100
batch_size = 50
# Configure training/optimization
clip = 50.0
teacher_forcing_ratio = 0.5
learning_rate = 0.0001
decoder_learning_ratio = 5.0
n_epochs = 50000
epoch = 0
plot_every = 20
print_every = 100
evaluate_every = 1000
# Initialize models
encoder = EncoderRNN(input_lang.n_words, hidden_size, n_layers, dropout=dropout)
decoder = LuongAttnDecoderRNN(attn_model, hidden_size, output_lang.n_words, n_layers, dropout=dropout)
# Initialize optimizers and criterion
encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)
decoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate * decoder_learning_ratio)
criterion = nn.CrossEntropyLoss()
# Move models to GPU
if USE_CUDA:
encoder.cuda()
decoder.cuda()
import sconce
job = sconce.Job('seq2seq-translate', {
'attn_model': attn_model,
'n_layers': n_layers,
'dropout': dropout,
'hidden_size': hidden_size,
'learning_rate': learning_rate,
'clip': clip,
'teacher_forcing_ratio': teacher_forcing_ratio,
'decoder_learning_ratio': decoder_learning_ratio,
})
job.plot_every = plot_every
job.log_every = print_every
# Keep track of time elapsed and running averages
start = time.time()
plot_losses = []
print_loss_total = 0 # Reset every print_every
plot_loss_total = 0 # Reset every plot_every
```
Plus helper functions to print time elapsed and estimated time remaining, given the current time and progress.
```
def as_minutes(s):
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
def time_since(since, percent):
now = time.time()
s = now - since
es = s / (percent)
rs = es - s
return '%s (- %s)' % (as_minutes(s), as_minutes(rs))
```
# Evaluating the network
Evaluation is mostly the same as training, but there are no targets. Instead we always feed the decoder's predictions back to itself. Every time it predicts a word, we add it to the output string. If it predicts the EOS token we stop there. We also store the decoder's attention outputs for each step to display later.
```
def evaluate(input_seq, max_length=MAX_LENGTH):
input_lengths = [len(input_seq)]
input_seqs = [indexes_from_sentence(input_lang, input_seq)]
input_batches = Variable(torch.LongTensor(input_seqs), volatile=True).transpose(0, 1)
if USE_CUDA:
input_batches = input_batches.cuda()
# Set to not-training mode to disable dropout
encoder.train(False)
decoder.train(False)
# Run through encoder
encoder_outputs, encoder_hidden = encoder(input_batches, input_lengths, None)
# Create starting vectors for decoder
decoder_input = Variable(torch.LongTensor([SOS_token]), volatile=True) # SOS
decoder_hidden = encoder_hidden[:decoder.n_layers] # Use last (forward) hidden state from encoder
if USE_CUDA:
decoder_input = decoder_input.cuda()
# Store output words and attention states
decoded_words = []
decoder_attentions = torch.zeros(max_length + 1, max_length + 1)
# Run through decoder
for di in range(max_length):
decoder_output, decoder_hidden, decoder_attention = decoder(
decoder_input, decoder_hidden, encoder_outputs
)
decoder_attentions[di,:decoder_attention.size(2)] += decoder_attention.squeeze(0).squeeze(0).cpu().data
# Choose top word from output
topv, topi = decoder_output.data.topk(1)
ni = topi[0][0]
if ni == EOS_token:
decoded_words.append('<EOS>')
break
else:
decoded_words.append(output_lang.index2word[ni])
# Next input is chosen word
decoder_input = Variable(torch.LongTensor([ni]))
if USE_CUDA: decoder_input = decoder_input.cuda()
# Set back to training mode
encoder.train(True)
decoder.train(True)
return decoded_words, decoder_attentions[:di+1, :len(encoder_outputs)]
```
We can evaluate random sentences from the training set and print out the input, target, and output to make some subjective quality judgements:
```
def evaluate_randomly():
[input_sentence, target_sentence] = random.choice(pairs)
evaluate_and_show_attention(input_sentence, target_sentence)
```
# Visualizing attention
A useful property of the attention mechanism is its highly interpretable outputs. Because it is used to weight specific encoder outputs of the input sequence, we can imagine looking where the network is focused most at each time step.
You could simply run `plt.matshow(attentions)` to see attention output displayed as a matrix, with the columns being input steps and rows being output steps:
```
import io
import torchvision
from PIL import Image
import visdom
vis = visdom.Visdom()
def show_plot_visdom():
buf = io.BytesIO()
plt.savefig(buf)
buf.seek(0)
attn_win = 'attention (%s)' % hostname
vis.image(torchvision.transforms.ToTensor()(Image.open(buf)), win=attn_win, opts={'title': attn_win})
```
For a better viewing experience we will do the extra work of adding axes and labels:
```
def show_attention(input_sentence, output_words, attentions):
# Set up figure with colorbar
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(attentions.numpy(), cmap='bone')
fig.colorbar(cax)
# Set up axes
ax.set_xticklabels([''] + input_sentence.split(' ') + ['<EOS>'], rotation=90)
ax.set_yticklabels([''] + output_words)
# Show label at every tick
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
show_plot_visdom()
plt.show()
plt.close()
def evaluate_and_show_attention(input_sentence, target_sentence=None):
output_words, attentions = evaluate(input_sentence)
output_sentence = ' '.join(output_words)
print('>', input_sentence)
if target_sentence is not None:
print('=', target_sentence)
print('<', output_sentence)
show_attention(input_sentence, output_words, attentions)
# Show input, target, output text in visdom
win = 'evaluted (%s)' % hostname
text = '<p>> %s</p><p>= %s</p><p>< %s</p>' % (input_sentence, target_sentence, output_sentence)
vis.text(text, win=win, opts={'title': win})
```
# Putting it all together
**TODO** Run `train_epochs` for `n_epochs`
To actually train, we call the train function many times, printing a summary as we go.
*Note:* If you're running this notebook you can **train, interrupt, evaluate, and come back to continue training**. Simply run the notebook starting from the following cell (running from the previous cell will reset the models).
```
# Begin!
ecs = []
dcs = []
eca = 0
dca = 0
while epoch < n_epochs:
epoch += 1
# Get training data for this cycle
input_batches, input_lengths, target_batches, target_lengths = random_batch(batch_size)
# Run the train function
loss, ec, dc = train(
input_batches, input_lengths, target_batches, target_lengths,
encoder, decoder,
encoder_optimizer, decoder_optimizer, criterion
)
# Keep track of loss
print_loss_total += loss
plot_loss_total += loss
eca += ec
dca += dc
job.record(epoch, loss)
if epoch % print_every == 0:
print_loss_avg = print_loss_total / print_every
print_loss_total = 0
print_summary = '%s (%d %d%%) %.4f' % (time_since(start, epoch / n_epochs), epoch, epoch / n_epochs * 100, print_loss_avg)
print(print_summary)
if epoch % evaluate_every == 0:
evaluate_randomly()
if epoch % plot_every == 0:
plot_loss_avg = plot_loss_total / plot_every
plot_losses.append(plot_loss_avg)
plot_loss_total = 0
# TODO: Running average helper
ecs.append(eca / plot_every)
dcs.append(dca / plot_every)
ecs_win = 'encoder grad (%s)' % hostname
dcs_win = 'decoder grad (%s)' % hostname
vis.line(np.array(ecs), win=ecs_win, opts={'title': ecs_win})
vis.line(np.array(dcs), win=dcs_win, opts={'title': dcs_win})
eca = 0
dca = 0
```
## Plotting training loss
Plotting is done with matplotlib, using the array `plot_losses` that was created while training.
```
def show_plot(points):
plt.figure()
fig, ax = plt.subplots()
loc = ticker.MultipleLocator(base=0.2) # put ticks at regular intervals
ax.yaxis.set_major_locator(loc)
plt.plot(points)
show_plot(plot_losses)
output_words, attentions = evaluate("je suis trop froid .")
plt.matshow(attentions.numpy())
show_plot_visdom()
evaluate_and_show_attention("elle a cinq ans de moins que moi .")
evaluate_and_show_attention("elle est trop petit .")
evaluate_and_show_attention("je ne crains pas de mourir .")
evaluate_and_show_attention("c est un jeune directeur plein de talent .")
evaluate_and_show_attention("est le chien vert aujourd hui ?")
evaluate_and_show_attention("le chat me parle .")
evaluate_and_show_attention("des centaines de personnes furent arretees ici .")
evaluate_and_show_attention("des centaines de chiens furent arretees ici .")
evaluate_and_show_attention("ce fromage est prepare a partir de lait de chevre .")
```
# Exercises
* Try with a different dataset
* Another language pair
* Human → Machine (e.g. IOT commands)
* Chat → Response
* Question → Answer
* Replace the embedding pre-trained word embeddings such as word2vec or GloVe
* Try with more layers, more hidden units, and more sentences. Compare the training time and results.
* If you use a translation file where pairs have two of the same phrase (`I am test \t I am test`), you can use this as an autoencoder. Try this:
* Train as an autoencoder
* Save only the Encoder network
* Train a new Decoder for translation from there
```
```
| github_jupyter |
```
#### ALL NOTEBOOK SHOULD HAVE SOME VERSION OF THIS #####################################
########################################################################################
%load_ext autoreload
%autoreload 2
import os
import sys
currentdir = os.getcwd()
# go to root directory. change the # of os.path.dirnames based on where currentdir is
parentdir = os.path.dirname(currentdir)
# chek where I'm at. if I go too far up the tree, go back
if 'Protein-Purification-Model-Public' not in parentdir: parentdir = currentdir
if parentdir not in sys.path: sys.path.insert(0,parentdir)
########################################################################################
import utils
import visualization.simple_data_vis as vis
import surrogate_models.nn_defs as engine
import kerastuner as kt
import matplotlib.pyplot as plt
import tensorflow as tf
import pickle
# load data from just-private/data
filename = 'mol_res_scan_results_7.csv'
data = utils.load_data(parentdir, filename)
# since currently data is just one big dataframe, select model inputs as X and purity, yield as Y
x = [*data.columns[:2],*data.columns[4:]]
y = data.columns[2:4]
# split data into train and test
trains, tests = utils.data_pipeline([data,], x_data=x, y_data=y)
# define models to test out
dnn = engine.create_deterministic_nn(
feature_names = x,
target_names = y,
hidden_units = [16,8,4],
name = 'DNN_'+filename[:-4]
)
models = [dnn]
dnn.summary()
# train all the models under the same conditions
learning_rate = 0.01
epochs = 100
optimizer = 'Adam' # change manually or come up with dictionary?
losses = ['mean_squared_error']
loss_weights = (1/trains[0][0][1].mean().div(trains[0][0][1].mean().max())).round(2).to_dict() # pretty much correcting for mean
histories = {}
for m,l in zip(models,losses):
histories[utils.get_model_name(m,filename)] = engine.run_experiment(
model = m,
loss = {y[0]:l,y[1]:l},
loss_weights = loss_weights,
optimizer = tf.keras.optimizers.Adam,
learning_rate = learning_rate,
num_epochs = epochs,
train_dataset = trains[0][0],
test_dataset = tests[0][0],
verbose = 0,
log = 0
)
settings = {'learning_rate' : learning_rate,
'epochs' : epochs,
'optimizer': optimizer,
'loss_weights': loss_weights,
'dataset' : filename}
# check model predictions
vis.scatter_hats(models, trains[0][0], tests[0][0], settings, n_points = 25);
model_dir = utils.save_model(parentdir, dnn, settings)
saved_model, saved_settings = utils.load_model(model_dir)
vis.scatter_hats([saved_model], trains[0][0], tests[0][0], saved_settings, n_points = 25);
```
| github_jupyter |
## Dimensionality Reduction
The use of various methods for dimensionality reduction is investigated. The code is based based on examples provided by scikit-learn. The main change is that instead I use a dataset consisting of audio features for the task of genre classification. They are calculated using Marsyas, an open source software for audio analysis. The points are colored in terms of their class membership. There are three genres each represented by a 100 tracks (instances) or points in this case. The genres are classical, jazz and metal.
```
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from sklearn import datasets
from sklearn.mixture import GaussianMixture
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import MinMaxScaler
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.manifold import Isomap
from sklearn.manifold import LocallyLinearEmbedding
from sklearn.manifold import MDS
from sklearn.manifold import TSNE
```
### Principal Component Analysis
In PCA the data is projected in a lower dimensional space. In this case the data loaded contains a full set of features. There are 300 instances and each instances has 120 features. After PCA we retain the first three PCA directions effectively reducing the dimensionality from 120 to 3. As can be seen from the 3D scatter plot
where the points are visualized with color based on their corresponding genre, the structure of the data in terms of genre is visible.
```
(X, y) = datasets.load_svmlight_file("data/3genres_full.arff.libsvm")
print(X.shape)
print(y.shape)
X = X.toarray()
X = MinMaxScaler().fit_transform(X)
target_names = ['classical', 'jazz', 'metal']
colors = ['navy', 'turquoise', 'darkorange']
def plot_scatter(X, title):
lw = 2
#fig = plt.figure(1, figsize=(8, 6))
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
plt.scatter(X[y == i, 0], X[y == i, 1], color=color, alpha=.8,
lw=lw, label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title(title)
plt.show()
# Two dimensional PCA
X_pca = PCA(n_components=2).fit_transform(X)
plot_scatter(X_pca, 'PCA')
# Two dimensional LDA
lda = LinearDiscriminantAnalysis(n_components=2)
X_lda = lda.fit_transform(X,y)
plot_scatter(X_lda, 'LDA')
# Isomap
n_neighbors = 30
X_iso = Isomap(n_neighbors, n_components=2).fit_transform(X)
plot_scatter(X_iso, 'ISOMAP')
# Locally Linear Embedding
clf = LocallyLinearEmbedding(n_neighbors, n_components=2,
method='standard')
X_lle = clf.fit_transform(X)
plot_scatter(X_lle, 'LLE')
clf = MDS(n_components=2, n_init=1, max_iter=100)
X_mds = clf.fit_transform(X)
plot_scatter(X_mds, 'MDS')
tsne = TSNE(n_components=2, init='pca', random_state=0)
X_tsne = tsne.fit_transform(X)
plot_scatter(X_tsne, 'TSNE')
# To getter a better understanding of interaction of the dimensions
# plot the first three PCA dimensions
fig = plt.figure(1, figsize=(8, 6))
ax = Axes3D(fig, elev=-150, azim=110)
X_reduced = PCA(n_components=3).fit_transform(X)
ax.scatter(X_reduced[:, 0], X_reduced[:, 1], X_reduced[:, 2], c=y,
cmap=plt.cm.Set1, edgecolor='k', s=40)
ax.set_title("First three PCA directions")
ax.set_xlabel("1st eigenvector")
ax.w_xaxis.set_ticklabels([])
ax.set_ylabel("2nd eigenvector")
ax.w_yaxis.set_ticklabels([])
ax.set_zlabel("3rd eigenvector")
ax.w_zaxis.set_ticklabels([])
plt.show()
tsne = TSNE(n_components=3, init='pca', random_state=0)
print("Starting TSNE computation")
X_tsne = tsne.fit_transform(X)
print("Computation of TSNE finished")
fig = plt.figure(1, figsize=(8, 6))
ax = Axes3D(fig, elev=-150, azim=110)
ax.scatter(X_tsne[:, 0], X_tsne[:, 1], X_tsne[:, 2], c=y,
cmap=plt.cm.Set1, edgecolor='k', s=40)
ax.set_title("TSNE")
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
plt.show()
```
| github_jupyter |
# Estimating the effect of a Member Rewards program
An example on how DoWhy can be used to estimate the effect of a subscription or a rewards program for customers.
Suppose that a website has a membership rewards program where customers receive additional benefits if they sign up. How do we know if the program is effective? Here the relevant causal question is:
> What is the impact of offering the membership rewards program on total sales?
And the equivalent counterfactual question is,
> If the current members had not signed up for the program, how much less would they have spent on the website?
In formal language, we are interested in the Average Treatment Effect on the Treated (ATT).
## I. Formulating the causal model
Suppose that the rewards program was introduced in January 2019. The outcome variable is the total spends at the end of the year.
We have data on all monthly transactions of every user and on the time of signup for those who chose to signup for the rewards program. Here's what the data looks like.
```
# Creating some simulated data for our example example
import pandas as pd
import numpy as np
num_users = 10000
num_months = 12
signup_months = np.random.choice(np.arange(1, num_months), num_users) * np.random.randint(0,2, size=num_users)
df = pd.DataFrame({
'user_id': np.repeat(np.arange(num_users), num_months),
'signup_month': np.repeat(signup_months, num_months), # signup month == 0 means customer did not sign up
'month': np.tile(np.arange(1, num_months+1), num_users), # months are from 1 to 12
'spend': np.random.poisson(500, num_users*num_months) #np.random.beta(a=2, b=5, size=num_users * num_months)*1000 # centered at 500
})
# Assigning a treatment value based on the signup month
df["treatment"] = (1-(df["signup_month"]==0)).astype(bool)
# Simulating effect of month (monotonically increasing--customers buy the most in December)
df["spend"] = df["spend"] - df["month"]*10
# The treatment effect (simulating a simple treatment effect of 100)
after_signup = (df["signup_month"] < df["month"]) & (df["signup_month"] !=0)
df.loc[after_signup,"spend"] = df[after_signup]["spend"] + 100
df
```
### The importance of time
Time plays a crucial role in modeling this problem.
Rewards signup can affect the future transactions, but not those that happened before it. In fact, the transaction prior to the rewards signup can be assumed to cause the rewards signup decision. Therefore we can split up the variables for each user in terms of
1) Activity prior to the treatment (causes the treatment)
2) Activity after the treatment (is the outcome of applying treatment)
Of course, many important variables that affect signup and total spend are missing (e.g., the type of products bought, length of a user's account, geography, etc.). So we'll need a node denoting `Unobserved Confounders`.
Below is the causal graph for a user who signed up in month `i=3`. The analysis will be similar for any `i`.
```
import os, sys
sys.path.append(os.path.abspath("../../../"))
import dowhy
# Setting the signup month (for ease of analysis)
i = 6
causal_graph = """digraph {
treatment[label="Program Signup in month i"];
pre_spends;
post_spends;
Z->treatment;
U[label="Unobserved Confounders"];
pre_spends -> treatment;
treatment->post_spends;
signup_month->post_spends; signup_month->pre_spends;
signup_month->treatment;
U->treatment; U->pre_spends; U->post_spends;
}"""
# Post-process the data based on the graph and the month of the treatment (signup)
df_i_signupmonth = df[df.signup_month.isin([0,i])].groupby(["user_id", "signup_month", "treatment"]).apply(
lambda x: pd.Series({'pre_spends': np.sum(np.where(x.month < i, x.spend,0))/np.sum(np.where(x.month<i, 1,0)),
'post_spends': np.sum(np.where(x.month > i, x.spend,0))/np.sum(np.where(x.month>i, 1,0)) })
).reset_index()
print(df_i_signupmonth)
model = dowhy.CausalModel(data=df_i_signupmonth,
graph=causal_graph.replace("\n", " "),
treatment="treatment",
outcome="post_spends")
model.view_model()
from IPython.display import Image, display
display(Image(filename="causal_model.png"))
```
More generally, we can include any activity data for the customer in the above graph. All prior- and post-activity data will occupy the same place (and have the same edges) as the Amount spent node (prior and post respectively).
## II. Identifying the causal effect
For the sake of this example, let us assume that unobserved confounding does not play a big part.
```
identified_estimand = model.identify_effect(proceed_when_unidentifiable=True)
print(identified_estimand)
```
Based on the graph, DoWhy determines that the signup month and amount spent in the pre-treatment months (`signup_month`, `pre_spend`) needs to be conditioned on.
## III. Estimating the effect
We now estimate the effect based on the backdoor estimand, setting the target units to "att".
```
estimate = model.estimate_effect(identified_estimand,
method_name="backdoor1.propensity_score_matching",
target_units="att")
print(estimate)
```
The analysis tells us the Average Treatment Effect on the Treated (ATT). That is, the average effect on total spend for the customers that signed up for the Rewards Program in month `i=3` (compared to the case where they had not signed up). We can similarly calculate the effects for customers who signed up in any other month by changing the value of `i`(line 2 above) and then rerunning the analysis.
Note that the estimation suffers from left and right-censoring.
1. **Left-censoring**: If a customer signs up in the first month, we do not have enough transaction history to match them to similar customers who did not sign up (and thus apply the backdoor identified estimand).
2. **Right-censoring**: If a customer signs up in the last month, we do not enough *future* (post-treatment) transactions to estimate the outcome after signup.
Thus, even if the effect of signup was the same across all months, the *estimated effects* may be different by month of signup, due to lack of data (and thus high variance in estimated pre-treatment or post-treatment transactions activity).
## IV. Refuting the estimate
We refute the estimate using the placebo treatment refuter. This refuter substitutes the treatment by an independent random variable and checks whether our estimate now goes to zero (it should!).
```
refutation = model.refute_estimate(identified_estimand, estimate, method_name="placebo_treatment_refuter",
placebo_type="permute", num_simulations=2)
print(refutation)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content-dl/blob/main/tutorials/W1D5_Regularization/student/W1D5_Tutorial1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Tutorial 1: Regularization techniques part 1
**Week 1, Day 5: Regularization**
**By Neuromatch Academy**
__Content creators:__ Ravi Teja Konkimalla, Mohitrajhu Lingan Kumaraian, Kevin Machado Gamboa, Kelson Shilling-Scrivo, Lyle Ungar
__Content reviewers:__ Piyush Chauhan, Kelson Shilling-Scrivo
__Content editors:__ Roberto Guidotti, Spiros Chavlis
__Production editors:__ Saeed Salehi, 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
1. Big ANNs are efficient universal approximators due to their adaptive basis functions
2. ANNs memorize some but generalize well
3. Regularization as shrinkage of overparameterized models: early stopping
```
#@markdown Tutorial slides
#@markdown
# you should link the slides for all tutorial videos here (we will store pdfs on osf)
from IPython.display import HTML
HTML('<iframe src="https://docs.google.com/presentation/d/1N9aguIPiBSjzo0ToqPi5uwwG8ChY6_E3/embed?start=false&loop=false&delayms=3000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>')
```
---
# Setup
Note that some of the code for today can take up to an hour to run. We have therefore "hidden" the code and shown the resulting outputs.
```
# Imports
import time
import copy
import torch
import pathlib
import random
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from tqdm.auto import tqdm
from __future__ import print_function
from IPython.display import HTML, display
from torchvision import datasets, transforms
from torchvision.datasets import ImageFolder
# @title Figure Settings
import ipywidgets as widgets
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/content-creation/main/nma.mplstyle")
# @title Loading Animal Faces data
%%capture
!rm -r AnimalFaces32x32/
!git clone https://github.com/arashash/AnimalFaces32x32
!rm -r afhq/
!unzip ./AnimalFaces32x32/afhq_32x32.zip
# @title Loading Animal Faces Randomized data
%%capture
!rm -r Animal_faces_random/
!git clone https://github.com/Ravi3191/Animal_faces_random.git
!rm -r afhq_random_32x32/
!unzip ./Animal_faces_random/afhq_random_32x32.zip
!rm -r afhq_10_32x32/
!unzip ./Animal_faces_random/afhq_10_32x32.zip
# @title Plotting functions
def imshow(img):
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.axis(False)
plt.show()
def plot_weights(norm, labels, ws, title='Weight Size Measurement'):
plt.figure(figsize=[8, 6])
plt.title(title)
plt.ylabel('Frobenius Norm Value')
plt.xlabel('Model Layers')
plt.bar(labels, ws)
plt.axhline(y=norm,
linewidth=1,
color='r',
ls='--',
label='Total Model F-Norm')
plt.legend()
plt.show()
def early_stop_plot(train_acc_earlystop, val_acc_earlystop, best_epoch):
plt.figure(figsize=(8, 6))
plt.plot(val_acc_earlystop,label='Val - Early',c='red',ls = 'dashed')
plt.plot(train_acc_earlystop,label='Train - Early',c='red',ls = 'solid')
plt.axvline(x=best_epoch, c='green', ls='dashed',
label='Epoch for Max Val Accuracy')
plt.title('Early Stopping')
plt.ylabel('Accuracy (%)')
plt.xlabel('Epoch')
plt.legend()
plt.show()
#@title Seeding for Reproducibility
def set_seed(seed=None, seed_torch=True):
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.')
# In case that `DataLoader` is used
def seed_worker(worker_id):
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
set_seed(seed=90108, seed_torch=False)
#@title Set device (GPU or CPU). Execute `set_device()`
# inform the user if the notebook uses GPU or CPU.
def set_device():
device = "cuda" if torch.cuda.is_available() else "cpu"
if device != "cuda":
print("WARNING: For this notebook to perform best, "
"if possible, in the menu under `Runtime` -> "
"`Change runtime type.` select `GPU` ")
else:
print("GPU is enabled in this notebook.")
return device
set_device()
```
**Ensure you're running a GPU notebook:**
From "Runtime" in the drop-down menu above, click "Change runtime type". Ensure that "Hardware Accelerator" says "GPU".
**Ensure you can save:** From "File", click "Save a copy in Drive"
```
# Seed parameter
# Notice that changing this values some results may not be identical
# with the solutions
SEED = 2021
```
Let's start the tutorial by defining some functions which we will use frequently today, such as: `AnimalNet`, `train`, `test` and `main`.
```
# Network Class - Animal Faces
class AnimalNet(nn.Module):
def __init__(self):
super(AnimalNet, self).__init__()
self.fc1 = nn.Linear(3 * 32 * 32, 128)
self.fc2 = nn.Linear(128, 32)
self.fc3 = nn.Linear(32, 3)
def forward(self, x):
x = x.view(x.shape[0],-1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
output = F.log_softmax(x, dim=1)
return output
```
The train function takes in the current model, along with the train_loader and loss function, and updates the parameters for a single pass of the entire dataset. The test function takes in the current model after every epoch and calculates the accuracy on the test dataset.
```
def train(args, model, device, train_loader, optimizer,
reg_function1=None, reg_function2=None, criterion=F.nll_loss):
"""
Trains the current inpur model using the data
from Train_loader and Updates parameters for a single pass
"""
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
if reg_function1 is None:
loss = criterion(output, target)
elif reg_function2 is None:
loss = criterion(output, target)+args['lambda']*reg_function1(model)
else:
loss = criterion(output, target) + args['lambda1']*reg_function1(model) + args['lambda2']*reg_function2(model)
loss.backward()
optimizer.step()
def test(model, device, test_loader, criterion=F.nll_loss):
"""
Tests the current Model
"""
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += criterion(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
return 100. * correct / len(test_loader.dataset)
def main(args, model, train_loader, val_loader,
reg_function1=None, reg_function2=None):
"""
Trains the model with train_loader and tests the learned model using val_loader
"""
use_cuda = not args['no_cuda'] and torch.cuda.is_available()
device = set_device()
model = model.to(device)
optimizer = optim.SGD(model.parameters(), lr=args['lr'],
momentum=args['momentum'])
val_acc_list, train_acc_list,param_norm_list = [], [], []
for epoch in tqdm(range(args['epochs'])):
train(args, model, device, train_loader, optimizer,
reg_function1=reg_function1, reg_function2=reg_function2)
train_acc = test(model,device,train_loader)
val_acc = test(model,device,val_loader)
param_norm = calculate_frobenius_norm(model)
train_acc_list.append(train_acc)
val_acc_list.append(val_acc)
param_norm_list.append(param_norm)
return val_acc_list, train_acc_list, param_norm_list, model, 0
```
---
#Section 1: Regularization is Shrinkage
```
#@title Video 1: Introduction to Regularization
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"", 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"bc1nsP4htVg", 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)
```
A key idea of neural nets, is that they use models that are "too complex" - complex enough to fit all the noise in the data. One then needs to "regularize" them to make the models fit complex enough, but not too complex. The more complex the model, the better it fits the training data, but if it is too complex, it generalizes less well; it memorizes the training data but is less accurate on future test data.
```
#@title Video 2: Regularization as Shrinkage
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"", 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"B4CsCKViB3k", 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)
```
One way to think about Regularization is to think in terms of the magnitude of the overall weights of the model. A model with big weights can fit more data perfectly, wheras a model with smaller weights tends to underperform on the train set but it can suprisingly do very well on the test set. Having the weights too small can also be an issue an it can then underfit the model.
This week we use the sum of Frobenius Norm of all the tensors in the model as a measure of the "size of the model".
##Coding Exercise 1: Frobenius Norm
Before we start, let's define the Frobenius norm, sometimes also called the Euclidean norm of an $m×n$ matrix $A$ as the square root of the sum of the absolute squares of its elements.
\begin{equation}
||A||_F= \sqrt{\sum_{i=1}^m\sum_{j=1}^n|a_{ij}|^2}
\end{equation}
This is just a measure of how big the matrix is, analagous to how big a vector is.
**Hint:** Use functions `model.parameters()` or `model.named_parameters()`
```
def calculate_frobenius_norm(model):
####################################################################
# Fill in all missing code below (...),
# then remove or comment the line below to test your function
raise NotImplementedError("Define `calculate_frobenius_norm` function")
####################################################################
norm = 0.0
# Sum the square of all parameters
for param in model.parameters():
norm += ...
# Take a square root of the sum of squares of all the parameters
norm = ...
return norm
# Seed added for reproducibility
set_seed(seed=SEED)
## uncomment below to test your code
# net = nn.Linear(10, 1)
# print(f'Frobenius Norm of Single Linear Layer: {calculate_frobenius_norm(net)}')
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D5_Regularization/solutions/W1D5_Tutorial1_Solution_bcc74b44.py)
```
Random seed 2021 has been set.
Frobenius Norm of Single Linear Layer: 0.6572162508964539
```
Apart from calculating the weight size for an entire model, we could also determine the weight size in every layer. For this, we can modify our `calculate_frobenius_norm` function as shown below.
**Have a look how it works!!**
```
# Frobenius Norm per Layer
def calculate_frobenius_norm(model):
# initialization of variables
norm, ws, labels = 0.0, [], []
# Sum all the parameters
for name, parameters in model.named_parameters():
p = torch.sum(parameters**2)
norm += p
ws.append((p**0.5).cpu().detach().numpy())
labels.append(name)
# Take a square root of the sum of squares of all the parameters
norm = (norm**0.5).cpu().detach().numpy()
return norm, ws, labels
set_seed(SEED)
net = nn.Linear(10,1)
norm, ws, labels = calculate_frobenius_norm(net)
print(f'Frobenius Norm of Single Linear Layer: {norm:.4f}')
# Plots the weights
plot_weights(norm, labels, ws)
```
Using the last function `calculate_frobenius_norm`, we can also obtain the Frobenius Norm per layer for a whole NN model and use the `plot_weigts` function to visualize them.
```
# Creates a new model
model = AnimalNet()
# Calculates the forbenius norm per layer
norm, ws, labels = calculate_frobenius_norm(model)
print(f'Frobenius Norm of Models weights: {norm:.4f}')
# Plots the weights
plot_weights(norm, labels, ws)
```
---
#Section 2: Overfitting
```
#@title Video 3: Overfitting
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"", 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"RlaGyRKP2nY", 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)
```
## Section 2.1: Visualizing Overfitting
Let's create some synthetic dataset that we will use to illustrate overfitting in neural networks.
```
# creating train data
# input
X = torch.rand((10, 1))
# output
Y = 2*X + 2*torch.empty((X.shape[0], 1)).normal_(mean=0, std=1) # adding small error in the data
#visualizing trian data
plt.figure(figsize=(8, 6))
plt.scatter(X.numpy(),Y.numpy())
plt.xlabel('input (x)')
plt.ylabel('output(y)')
plt.title('toy dataset')
plt.show()
#creating test dataset
X_test = torch.linspace(0, 1, 40)
X_test = X_test.reshape((40, 1, 1))
```
Let's create an overparametrized Neural Network that can fit on the dataset that we just created and train it.
First, let's build the model architecture:
```
# Network Class - 2D
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(1, 300)
self.fc2 = nn.Linear(300, 500)
self.fc3 = nn.Linear(500, 1)
def forward(self, x):
x = F.leaky_relu(self.fc1(x))
x = F.leaky_relu(self.fc2(x))
output = self.fc3(x)
return output
```
Next, let's define the different parameters for training our model:
```
# train the network on toy dataset
model = Net()
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr = 1e-4)
iters = 0
# Calculates frobenius before training
normi, wsi, label = calculate_frobenius_norm(model)
```
At this point, we can now train our model.
```
# initializing variables
# losses
train_loss = []
test_loss = []
# model norm
model_norm = []
# Initializing variables to store weights
norm_per_layer = []
max_epochs = 10000
running_predictions = np.empty((40, int(max_epochs / 500 + 1)))
for epoch in tqdm(range(max_epochs)):
# frobenius norm per epoch
norm, pl, layer_names = calculate_frobenius_norm(model)
# training
model_norm.append(norm)
norm_per_layer.append(pl)
model.train()
optimizer.zero_grad()
predictions = model(X)
loss = criterion(predictions, Y)
loss.backward()
optimizer.step()
train_loss.append(loss.data)
model.eval()
Y_test = model(X_test)
loss = criterion(Y_test, 2*X_test)
test_loss.append(loss.data)
if (epoch % 500 == 0 or epoch == max_epochs - 1):
running_predictions[:, iters] = Y_test[:, 0, 0].detach().numpy()
iters += 1
```
Now that we have finished training, let's see how the model has evolved over the training process.
```
#@title Animation (Run Me!)
# create a figure and axes
fig = plt.figure(figsize=(14, 5))
ax1 = plt.subplot(121)
ax2 = plt.subplot(122)
# organizing subplots
plot1, = ax1.plot([],[])
plot2 = ax2.bar([], [])
def frame(i):
ax1.clear()
title1 = ax1.set_title('')
ax1.set_xlabel("Input(x)")
ax1.set_ylabel("Output(y)")
ax2.clear()
ax2.set_xlabel('Layer names')
ax2.set_ylabel('Frobenius norm')
title2 = ax2.set_title('Weight Measurement: Forbenius Norm')
ax1.scatter(X.numpy(),Y.numpy())
plot1 = ax1.plot(X_test[:,0,:].detach().numpy(), running_predictions[:,i])
title1.set_text(f'Epochs: {i * 500}')
plot2 = ax2.bar(label, norm_per_layer[i*500])
plt.axhline(y=model_norm[i*500], linewidth=1,
color='r', ls='--',
label=f'Norm: {model_norm[i*500]:.2f}')
plt.legend()
return plot1, plot2
anim = animation.FuncAnimation(fig, frame, frames=range(20),
blit=False, repeat=False, repeat_delay=10000)
html_anim = HTML(anim.to_html5_video());
plt.close()
display(html_anim)
#@title Plot the train and test losses
plt.figure(figsize=(8, 6))
plt.plot(train_loss,label='train_loss')
plt.plot(test_loss,label='test_loss')
plt.ylabel('loss')
plt.xlabel('epochs')
plt.title('loss vs epoch')
plt.legend()
plt.show()
```
### Think! 2.1: Interpreting losses
Regarding the train and test graph above, discuss among yourselves:
* What trend do you see w.r.t to train and test losses ( Where do you see the minimum of these losses?)
* What does it tell us about the model we trained?
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D5_Regularization/solutions/W1D5_Tutorial1_Solution_141a7a50.py)
Now let's visualize the Frobenious norm of the model as we trained. You should see that the value of weights increases over the epochs.
```
#@title Frobenious norm of the model
plt.figure(figsize=(8, 6))
plt.plot(model_norm)
plt.ylabel('norm of the model')
plt.xlabel('epochs')
plt.title('Size of the model vs Epochs') # Change title to Frobenious norm of the model
plt.show()
```
Finally, you can compare the Frobenius norm per layer in the model, before and after training.
```
#@title Frobenius norm per layer before and after training
normf, wsf, label = calculate_frobenius_norm(model)
plot_weights(float(normi), label, wsi, title='Weight Size Before Training')
plot_weights(float(normf), label, wsf, title='Weight Size After Training')
```
## Section 2.2: Overfitting on Test Dataset
In principle we should not touch our test set until after we have chosen all our hyperparameters. Were we to use the test data in the model selection process, there is a risk that we might overfit the test data. Then we would be in serious trouble. If we overfit our training data, there is always the evaluation on test data to keep us honest. But if we overfit the test data, how would we ever know?
Note that there is another kind of overfitting: you do "honest" fitting on one set of images or posts, or medical records, but it may not generalize to other sets of images, posts or medical records.
#### Validation Dataset
A common practice to address this problem is to split our data in three ways, using a validation dataset (or validation set) to tune the hyperparameters. Ideally, we would only touch the test data once, to assess the very best model or to compare a small number of models to each other, real-world test data is seldom discarded after just one use.
---
# Section 3: Memorization
Given sufficiently large networks and enough training, Neural Networks can acheive almost 100% train accuracy.
In this section we train three MLPs; one each on:
1. Animal Faces Dataset
2. A Completely Noisy Dataset (Random Shuffling of all labels)
3. A partially Noisy Dataset (Random Shuffling of 15% labels)
Now, think for a couple of minutes as to what the train and test accuracies of each of these models might be, given that you train for sufficient time and use a powerful network.
First, let's create the required dataloaders for all three datasets. Notice how we split the data. We train on a fraction of the dataset as it will be faster to train and will overfit more clearly.
```
# Dataloaders for the Dataset
batch_size = 128
classes = ('cat', 'dog', 'wild')
# defining number of examples for train, val test
len_train, len_val, len_test = 100, 100, 14430
train_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
data_path = pathlib.Path('.')/'afhq' # using pathlib to be compatible with all OS's
img_dataset = ImageFolder(data_path/'train', transform=train_transform)
# For reproducibility
g = torch.Generator()
g.manual_seed(SEED)
# Dataloaders for the Original Dataset
img_train_data, img_val_data,_ = torch.utils.data.random_split(img_dataset,
[len_train,
len_val,
len_test])
# Creating train_loader and Val_loader
train_loader = torch.utils.data.DataLoader(img_train_data,
batch_size=batch_size,
worker_init_fn=seed_worker,
generator=g)
val_loader = torch.utils.data.DataLoader(img_val_data,
batch_size=1000,
worker_init_fn=seed_worker,
generator=g)
# Dataloaders for the Random Dataset
# splitting randomized data into training and validation data
data_path = pathlib.Path('.')/'afhq_random_32x32/afhq_random' # using pathlib to be compatible with all OS's
img_dataset = ImageFolder(data_path/'train', transform=train_transform)
random_img_train_data, random_img_val_data,_ = torch.utils.data.random_split(img_dataset, [len_train, len_val, len_test])
# Randomized train and validation dataloader
rand_train_loader = torch.utils.data.DataLoader(random_img_train_data,
batch_size=batch_size,
num_workers=0,
worker_init_fn=seed_worker,
generator=g)
rand_val_loader = torch.utils.data.DataLoader(random_img_val_data,
batch_size=1000,
num_workers=0,
worker_init_fn=seed_worker,
generator=g)
# Dataloaders for the Partially Random Dataset
# Splitting data between training and validation dataset for partially randomized data
data_path = pathlib.Path('.')/'afhq_10_32x32/afhq_10' # using pathlib to be compatible with all OS's
img_dataset = ImageFolder(data_path/'train', transform=train_transform)
partially_random_train_data, partially_random_val_data,_ = torch.utils.data.random_split(img_dataset, [len_train, len_val, len_test])
# Training and Validation loader for partially randomized data
partial_rand_train_loader = torch.utils.data.DataLoader(partially_random_train_data,
batch_size=batch_size,
num_workers=0,
worker_init_fn=seed_worker,
generator=g)
partial_rand_val_loader = torch.utils.data.DataLoader(partially_random_val_data,
batch_size=1000,
num_workers=0,
worker_init_fn=seed_worker,
generator=g)
```
Now let's define a model which has many parameters compared to the training dataset size, and train it on these datasets.
```
# Network Class - Animal Faces
class BigAnimalNet(nn.Module):
def __init__(self):
super(BigAnimalNet, self).__init__()
self.fc1 = nn.Linear(3*32*32, 124)
self.fc2 = nn.Linear(124, 64)
self.fc3 = nn.Linear(64, 3)
def forward(self, x):
x = x.view(x.shape[0], -1)
x = F.leaky_relu(self.fc1(x))
x = F.leaky_relu(self.fc2(x))
x = self.fc3(x)
output = F.log_softmax(x, dim=1)
return output
```
Before training our `BigAnimalNet()`, calculate the Frobenius norm again.
```
model = BigAnimalNet()
normi, wsi, label = calculate_frobenius_norm(model)
```
Now, train our `BigAnimalNet()` model
```
# Here we have 100 true train data.
args = {
'epochs': 200,
'lr': 5e-3,
'momentum': 0.9,
'no_cuda': False,
}
acc_dict = {}
start_time = time.time()
val_acc_pure, train_acc_pure, _, model ,_ = main(args=args,
model=model,
train_loader=train_loader,
val_loader=val_loader)
end_time = time.time()
print("Time to memorize the dataset:",end_time - start_time)
# # Train and Test accuracy plot
plt.figure(figsize=(8, 6))
plt.plot(val_acc_pure, label='Val Accuracy Pure', c='red', ls='dashed')
plt.plot(train_acc_pure, label='Train Accuracy Pure', c='red', ls='solid')
plt.axhline(y=max(val_acc_pure), c='green', ls='dashed',
label='max Val accuracy pure')
plt.title('Memorization')
plt.ylabel('Accuracy (%)')
plt.xlabel('Epoch')
plt.legend()
plt.show()
#@markdown #### Frobenius norm for AnimalNet before and after training
normf, wsf, label = calculate_frobenius_norm(model)
plot_weights(float(normi), label, wsi, title='Weight Size Before Training')
plot_weights(float(normf), label, wsf, title='Weight Size After Training')
```
##Coding Exercise 2: Data Visualizer
Before we train the model on a data with random labels, let's visualize and verify for ourselves that the data is random. Here, we have classes = ("cat", "dog", "wild").
**Hint:** Use `.permute()` method. `plt.imshow()` expects imput to be in numpy format and in the format (Px, Py, 3), where Px and Py are the number of pixels along axis x and y respectively.
```
def visualize_data(dataloader):
####################################################################
# Fill in all missing code below (...),
# then remove or comment the line below to test your function
# The dataloader here gives out mini batches of 100 data points.
raise NotImplementedError("Complete the Visualize_random_data function")
####################################################################
for idx, (data,label) in enumerate(dataloader):
plt.figure(idx)
# Choose the datapoint you would like to visualize
index = ...
# choose that datapoint using index and permute the dimensions
# and bring the pixel values between [0,1]
data = ...
# Convert the torch tensor into numpy
data = ...
plt.imshow(data)
plt.axis(False)
image_class = classes[...]
print(f'The image belongs to : {image_class}')
plt.show()
## uncomment to run the function
# visualize_data(rand_train_loader)
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D5_Regularization/solutions/W1D5_Tutorial1_Solution_83bd9281.py)
*Example output:*
<img alt='Solution hint' align='left' width=832.0 height=832.0 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W1D5_Regularization/static/W1D5_Tutorial1_Solution_83bd9281_1.png>
Now let's train the network on the shuffled data and see if it memorizes.
```
# Here we have 100 completely shuffled train data.
args = {
'epochs': 200,
'lr': 5e-3,
'momentum': 0.9,
'no_cuda': False
}
acc_dict = {}
model = BigAnimalNet()
val_acc_random, train_acc_random, _,model,_ = main(args,
model,
rand_train_loader,
val_loader)
# Train and Test accuracy plot
plt.figure(figsize=(8, 6))
plt.plot(val_acc_random, label='Val Accuracy random', c='red', ls='dashed')
plt.plot(train_acc_random, label='Train Accuracy random', c='red', ls='solid')
plt.axhline(y=max(val_acc_random), c='green', ls='dashed', label='Max Val Accuracy random')
plt.title('Memorization')
plt.ylabel('Accuracy (%)')
plt.xlabel('Epoch')
plt.legend()
plt.show()
```
Finally lets train on a partially shuffled dataset where 15% of the labels are noisy.
```
# Here we have 100 partially shuffled train data.
args = {
'epochs': 200,
'lr': 5e-3,
'momentum': 0.9,
'no_cuda': False,
}
acc_dict = {}
model = BigAnimalNet()
val_acc_shuffle, train_acc_shuffle, _,_,_ = main(args,
model,
partial_rand_train_loader,
val_loader)
# train and test acc plot
plt.figure(figsize=(8, 6))
plt.plot(val_acc_shuffle, label='Val Accuracy shuffle', c='red', ls='dashed')
plt.plot(train_acc_shuffle, label='Train Accuracy shuffle', c='red', ls='solid')
plt.axhline(y=max(val_acc_shuffle), c='green', ls='dashed', label='Max Val Accuracy shuffle')
plt.title('Memorization')
plt.ylabel('Accuracy (%)')
plt.xlabel('Epoch')
plt.legend()
plt.show()
#@markdown #### Plotting them all together (Run Me!)
plt.figure(figsize=(8, 6))
plt.plot(val_acc_pure,label='Val - Pure',c='red',ls = 'dashed')
plt.plot(train_acc_pure,label='Train - Pure',c='red',ls = 'solid')
plt.plot(val_acc_random,label='Val - Random',c='blue',ls = 'dashed')
plt.plot(train_acc_random,label='Train - Random',c='blue',ls = 'solid')
plt.plot(val_acc_shuffle, label='Val - shuffle', c='y', ls='dashed')
plt.plot(train_acc_shuffle, label='Train - shuffle', c='y', ls='solid')
plt.title('Memorization')
plt.ylabel('Accuracy (%)')
plt.xlabel('Epoch')
plt.legend()
plt.show()
```
## Think! 2: Does it Generalize?
Given that the Neural Network fit/memorize the training data perfectly:
* Do you think it generalizes well?
* What makes you think it does or doesn't?
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D5_Regularization/solutions/W1D5_Tutorial1_Solution_8f1d49a8.py)
Isn't it supprising to see that the NN was able to acheive 100% training accuracy on randomly shuffled labels? This is one of the reasons why training accuracy is not a good indicator of model performance.
Also it is interesting to note that sometimes the model trained on slightly shuffled data does slightly better than the one trained on pure data. Shuffling some of the data is a form of regularization--one of many ways of adding noise to the training data.
---
# Section 4: Early Stopping
```
#@title Video 4: Early Stopping
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"", 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"GA6J-50GCWs", 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)
```
Now that we have established that the validation accuracy reaches the peak well before the model overfits, we want to somehow stop the training early. You should have also observed from the above plots that the train/test loss on real data is not very smooth and hence you might guess that the choice of epoch can play a very large role on the val/test accuracy of your model.
Early stopping stops training when the validation accuracies stop increasing.
<center><img src="https://images.deepai.org/glossary-terms/early-stopping-machine-learning-5422207.jpg" alt="Overfitting" width="600"/></center>
## Coding Exercise 3: Early Stopping
Reimplement the main function to include early stopping as described above. Then run the code below to validate your implementation.
```
def early_stopping_main(args, model, train_loader, val_loader):
####################################################################
# Fill in all missing code below (...),
# then remove or comment the line below to test your function
raise NotImplementedError("Complete the early_stopping_main function")
####################################################################
use_cuda = not args['no_cuda'] and torch.cuda.is_available()
device = torch.device('cuda' if use_cuda else 'cpu')
model = model.to(device)
optimizer = optim.SGD(model.parameters(),
lr=args['lr'],
momentum=args['momentum'])
best_acc = 0.0
best_epoch = 0
# Number of successive epochs that you want to wait before stopping training process
patience = 20
# Keps track of number of epochs during which the val_acc was less than best_acc
wait = 0
val_acc_list, train_acc_list = [], []
for epoch in tqdm(range(args['epochs'])):
# train the model
...
# calculate training accuracy
train_acc = ...
# calculate validation accuracy
val_acc = ...
if (val_acc > best_acc):
best_acc = val_acc
best_epoch = epoch
best_model = copy.deepcopy(model)
wait = 0
else:
wait += 1
if (wait > patience):
print(f'early stopped on epoch: {epoch}')
break
train_acc_list.append(train_acc)
val_acc_list.append(val_acc)
return val_acc_list, train_acc_list, best_model, best_epoch
args = {
'epochs': 200,
'lr': 5e-4,
'momentum': 0.99,
'no_cuda': False,
}
model = AnimalNet()
## Uncomment to test
# val_acc_earlystop, train_acc_earlystop, _, best_epoch = early_stopping_main(args, model, train_loader, val_loader)
# print(f'Maximum Validation Accuracy is reached at epoch: {best_epoch:2d}')
# early_stop_plot(train_acc_earlystop, val_acc_earlystop, best_epoch)
```
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D5_Regularization/solutions/W1D5_Tutorial1_Solution_dd5edfb8.py)
*Example output:*
<img alt='Solution hint' align='left' width=1120.0 height=832.0 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W1D5_Regularization/static/W1D5_Tutorial1_Solution_dd5edfb8_2.png>
## Think! 3: Early Stopping
Discuss among your pod why or why not:
* Do you think early stopping can be harmful for training your network?
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D5_Regularization/solutions/W1D5_Tutorial1_Solution_683d27d3.py)
| github_jupyter |
```
# default_exp callback
```
# Callbacks
> Callbacks for predicting within AdaptNLP using the fastai framework
```
#hide
from nbverbose.showdoc import *
#export
from fastcore.basics import store_attr
from fastcore.meta import delegates
from fastai.callback.core import Callback, CancelBatchException
from transformers import PreTrainedModel
#export
class GatherInputsCallback(Callback):
"""
Prepares basic input dictionary for HuggingFace Transformers
This `Callback` generates a very basic dictionary consisting of `input_ids`,
`attention_masks`, and `token_type_ids`, and saves it to the attribute `self.learn.inputs`.
If further data is expected or needed from the batch, the additional Callback(s) should have
an order of -2
"""
order = -3
def before_validate(self):
"""
Sets the number of inputs in `self.dls`
"""
x = self.dl.one_batch()
self.learn.dls.n_inp = len(x)
def before_batch(self):
"""
Turns `self.xb` from a tuple to a dictionary of either
`{"input_ids", "attention_masks", "token_type_ids"}`d
or
`{"input_ids", "attention_masks"}`
"""
inputs = {
"input_ids":self.learn.xb[0],
"attention_mask":self.learn.xb[1]
}
if len(self.learn.xb) > 2:
inputs["token_type_ids"] = self.learn.xb[2]
self.learn.inputs = inputs
show_doc(GatherInputsCallback.before_validate)
show_doc(GatherInputsCallback.before_batch)
#export
class SetInputsCallback(Callback):
"""
Callback which runs after `GatherInputsCallback` that sets `self.learn.xb`
"""
order = -1
def __init__(
self,
as_dict=False # Whether to leave `self.xb` as a dictionary of values
): store_attr()
def before_batch(self):
"""
Set `self.learn.xb` to `self.learn.inputs.values()`
"""
if not self.as_dict:
self.learn.xb = list(self.learn.inputs.values())
else:
self.learn.xb = self.learn.inputs
show_doc(SetInputsCallback.before_batch)
#export
class GeneratorCallback(Callback):
"""
Callback used for models that utilize `self.model.generate`
"""
@delegates(PreTrainedModel.generate)
def __init__(
self,
num_beams:int, # Number of beams for beam search
min_length:int, # Minimal length of the sequence generated
max_length:int, # Maximum length of the sequence generated
early_stopping:bool, # Whether to do early stopping
**kwargs
):
store_attr()
self.kwargs = kwargs
def before_batch(self):
"""
Run model-specific inference
"""
pred = self.learn.model.generate(
input_ids = self.xb['input_ids'],
attention_mask = self.xb['attention_mask'],
num_beams = self.num_beams,
min_length = self.min_length,
max_length = self.max_length,
early_stopping = self.early_stopping,
**self.kwargs
)
self.learn.pred = pred
raise CancelBatchException # skip original model inference
show_doc(GeneratorCallback)
```
| github_jupyter |
# Softmax Classification
### Architecture
* Relu in hidden layers and softmax in the output layer
* Number of layers and number of units in each layer can be set using `layers_dims` hyper-parameter
* Uses softmax cross entropy for loss computation
### Dependencies
* Numpy
* Matplotlib (for plotting cost curves)
## Import dependencies
```
import numpy as np
from utils.sc_utils import load_data, plot_training
```
## Parameters Initialization
```
def initialize_parameters(layers_dims):
'''
Arguments:
layers_dims -- a list of dimensions of each layer of our network
Returns:
parameters -- a dictionary containing weights and biases of the network
'''
parameters = {}
for l in range(len(layers_dims)-1):
parameters['W' + str(l+1)] = np.random.randn(layers_dims[l+1], layers_dims[l]) * 0.01
parameters['b' + str(l+1)] = np.zeros([layers_dims[l+1], 1])
return parameters
```
## Forward Propogation
```
def relu(X):
return np.maximum(X, 0)
def softmax(X):
t = np.exp(X)
return t / np.sum(t, axis=0)
def forward_propogation(A, parameters):
'''
Implement the forward propogation in the network
Arguments:
A -- input to the network
parameters -- a dictionary containing weights and biases of the network
Returns:
A -- Post activation value of the last layer
caches -- cache of all activation values, required for backpropogation
'''
L = len(parameters) // 2 # no. of layers
caches = {}
for l in range(L):
W = parameters['W' + str(l+1)]
b = parameters['b' + str(l+1)]
Z = np.dot(W, A) + b
A = relu(Z) if l<L-1 else softmax(Z) # relu in hidden layers and sigmoid in output layer
caches['A' + str(l+1)] = A
caches['Z' + str(l+1)] = Z
return A, caches
```
## Cost Computation
```
def compute_cost(AL, Y):
"""
Implement the cost function for the network
Arguments:
AL -- probability vector corresponding to the label predictions, shape (10, number of examples)
Y -- true "label" vector, shape (10, number of examples)
Returns:
cost -- cross-entropy cost
"""
m = Y.shape[1]
cost = -1 / m * np.sum(Y * np.log(AL))
cost = np.squeeze(cost)
assert(cost.shape == ())
return cost
```
## Backward Propogation
```
def relu_backward(grad_A, Z):
grad_A[Z<=0] = 0
return grad_A
def backward_propogation(X, Y, AL, caches, parameters):
'''
Implement Backpropogation
Arguments:
Al -- Activations of last layer
Y -- True labels of data
caches -- dictionary containing values of A and Z of each layer
parameters -- dictionary containing parameters of the network
Returns
grads -- dictionary containing gradients of the network parameters
'''
grads = {}
m = Y.shape[1]
L = len(parameters) // 2
grad_Z = 1/m * (AL - Y)
for l in reversed(range(1, L)):
grads['W' + str(l+1)] = np.dot(grad_Z, caches['A' + str(l)].T)
grads['b' + str(l+1)] = np.sum(grad_Z, axis=1, keepdims=True)
assert(grads['W' + str(l+1)].shape == parameters['W' + str(l+1)].shape)
assert(grads['b' + str(l+1)].shape == parameters['b' + str(l+1)].shape)
grad_A = np.dot(parameters['W' + str(l+1)].T, grad_Z)
grad_Z = relu_backward(grad_A, caches['Z' + str(l)])
#for first layer
grads['W1'] = np.dot(grad_Z, X.T)
grads['b1'] = np.sum(grad_Z, axis=1, keepdims=True)
assert(grads['W1'].shape == parameters['W1'].shape)
assert(grads['b1'].shape == parameters['b1'].shape)
return grads
```
## Parameters Update
```
def update_parameters(parameters, grads, learning_rate):
'''
Update parameters of the network using gradient descent
Arguments:
paramters -- dictionary containing weights and biases of the network
grads -- dictionary containing the gradients of the parameters
learning_rate -- rate of gradient descent
Returns
parameters -- dictionary containing updated parameters
'''
L = len(parameters)//2
for l in reversed(range(L-1)):
parameters['W'+str(l+1)] -= learning_rate * grads['W' + str(l+1)]
parameters['b'+str(l+1)] -= learning_rate * grads['b' + str(l+1)]
return parameters
```
## Model
```
def Model(X, Y, X_val, Y_val, layers_dims, epochs, learning_rate):
parameters = initialize_parameters(layers_dims)
costs_train = []
costs_val = []
for epoch in range(epochs+1):
AL, caches = forward_propogation(X, parameters)
cost = compute_cost(AL, Y)
grads = backward_propogation(X, Y, AL, caches, parameters)
parameters = update_parameters(parameters, grads, learning_rate)
# compute validation cost
AL_val, _ = forward_propogation(X_val, parameters)
cost_val = compute_cost(AL_val, Y_val)
costs_train.append(cost)
costs_val.append(cost_val)
if epoch%10 == 0:
print('Epoch:', epoch, 'Cost: %0.3f' % cost, '- Val Cost: %0.3f' % cost_val)
plot_training(costs_train, costs_val)
return parameters
```
## Implementing the model on MNIST
```
'''
Load MNIST dataset, Find the code in utils/sc_utils.py
'''
train, val = load_data()
X_train, Y_train = train
X_val, Y_val = val
print(X_train.shape, Y_train.shape, X_val.shape, Y_val.shape)
# hyper-parameters, let's take these values for our example!
epochs = 500
learning_rate = 0.5
layers_dims = [784, 512, 128, 10]
parameters = Model(X_train, Y_train, X_val, Y_val, layers_dims, epochs, learning_rate)
```
| github_jupyter |
```
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
%autosave 0
```
*This notebook is part of course materials for CS 345: Machine Learning Foundations and Practice at Colorado State University.
Original versions were created by Asa Ben-Hur.
The content is availabe [on GitHub](https://github.com/asabenhur/CS345).*
*The text is released under the [CC BY-SA license](https://creativecommons.org/licenses/by-sa/4.0/), and code is released under the [MIT license](https://opensource.org/licenses/MIT).*
<img style="padding: 10px; float:right;" alt="CC-BY-SA icon.svg in public domain" src="https://upload.wikimedia.org/wikipedia/commons/d/d0/CC-BY-SA_icon.svg" width="125">
<a href="https://colab.research.google.com/github//asabenhur/CS345/blob/master/notebooks/module07_01_probability.ipynb">
<img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a>
# A primer in probability
Because of the inherent uncertainty and noise in observations of the real world, probability theory plays an important role in machine learning. This notebook serves as a brief reminder of some of the important concepts.
Probability is a mathematical framework for expressing uncertainty about the outcome of events.
We often encode this uncertainty in a variable, called a **random variable**. A Random variable is a variable whose possible values are the possible outcomes of a random phenomenon.
**Example.** the outcome of a coin toss or a roll of a die.
The possible outcomes of a random variable $X$, e.g. one that models a coin toss are represented with the notation:
$$
p(X = \mathrm{heads}) = 0.5
$$
**Definition.**
The probabilities of all possible values that a random variable can take are its **distribution**. For a coin toss it is the numbers
$$
p(X = \mathrm{heads}) = 0.5,~ p(X = \mathrm{tails}) = 0.5
$$
As a shorthand, we often use the notation $p(\mathrm{heads})$ instead of $p(X = \mathrm{heads})$.
The sum of the probability of all events must equal 1.
So if the probability of heads is 0.5, then the probability of tails (the only other possible outcome) is given by
$$
p(X = \mathrm{tails}) = 1 − p(X = \mathrm{heads}) = 0.5
$$
More generally, if a random variable takes on the values $x_i$, then we have that
$$
\sum_{i}^{}p(x_i)=1
$$
For example in our coin toss example:
```
# random variable that describes the outcome of a toin toss
p={'heads':0.5,'tails':0.5}
sum(p.values())
```
**Example.** Rolling a die. Each value has a probability of 1/6.
We can simulate a roll of a die using Numpy:
```
rng = np.random.default_rng()
rng.integers(1, 7)
```
By simulating the die many times we can estimate those probabilities. We can observe that the estimates become better with increasing number of tries:
```
few_rolls = rng.integers(1,7,size=100)
many_rolls = rng.integers(1,7,size=1000000)
few_counts = np.histogram(few_rolls, bins=np.arange(.5, 7.5))[0]
many_counts = np.histogram(many_rolls, bins=np.arange(.5, 7.5))[0]
fig, (ax1, ax2) = plt.subplots(1,2,figsize=(8,3))
ax1.bar(np.arange(1,7), few_counts)
ax2.bar(np.arange(1,7), many_counts);
```
### Joint probability distribution
The joint probability distribution for two variables $X,Y$ is a table whose entries are $p(x_i,y_j)$.
In the case of binary variables, the joint probability distribution is a $2\times2$ table.
**Example.** Two coin tosses.
The joint probability distribution for two random variables can be represented as a table that lists the probabilities for each pair of events. In our coin tosses examples we have following table:
| Toss | Toss2 = heads | Toss2 = tails |
| :-----------------|:-------------:| :------------:|
| **Toss1 = heads** | 0.25 | 0.25 |
| **Toss1 = tail** | 0.25 | 0.25 |
This holds true, because all possible outcomes are equally likely.
### Marginal probability
We compute the marginal probability by summing over all variables we are not interested in:
$$ p(x)=\sum_{j}^{}p(x,y_j) $$
We can compute the marginal for our coin toss example:
| Toss | Toss2 = heads | Toss2 = tails | Marginal |
| :-------------|:-------------:| :----------:| :------------: |
| **Toss1 = heads** | 0.25 | 0.25 | 0.50 |
| **Toss1 = tail** | 0.25 | 0.25 | 0.50 |
| **Marginal** | 0.50 | 0.50 | 1.0 |
### Conditional probability
The conditional probability of $Y$ given $X$ is defined by:
$$p(y|x)=\frac{p(y,x)}{p(x)}$$
### The product rule
The product rule is a direct consequence of the definition of conditional probability:
$$ p(x,y)=p(y|x)p(x) $$
### Independence
Random variables $X$ and $Y$ are independent if $p(y|x) = p(y)$ for all values $x$ of $X$ and all values $y$ of $Y$.
Plugging this into the product rule, we obtain that two variables are independent if $p(x,y) = p(x) p(y)$.
**Example.** Let's revisit our coin toss example, which is has the following table:
| Toss | Toss2 = heads | Toss2 = tails |
| :-----------------|:-------------:| :------------:|
| **Toss1 = heads** | 0.25 | 0.25 |
| **Toss1 = tail** | 0.25 | 0.25 |
Since the coin tosses are independent, each element in the table is the product of the individual probabilities.
**Example**. Consider the following game of dice: Roll a die four times. If a six comes up one or more times, I win. What is the probability that I win?
This game is famously attributed to [Chevalier de Méré](https://en.wikipedia.org/wiki/Antoine_Gombaud), who from his experience, found this to be a lucrative game. However, he did not know just how likely he is to win. He asked the famous mathematician Blaise Pascal for help.
First let us simulate this game in Numpy (no for loops!)
```
num_games = 100000
rng = np.random.default_rng()
rolls = rng.integers(1, 7, size=(num_games, 4))
sixes_per_game = (rolls==6).sum(axis=1)
print('fraction of games won: ', np.sum(sixes_per_game >= 1)/num_games)
```
We can compare this to the analytical solution to the problem: the four rolls are independent, therefore the probability of not getting a six in all four rolls is $(5/6)^4$. The event of interest, is its complement, with a probability of $1-(5/6)^4$. Let's compare the resulting number with our simulation:
```
1-(5/6)**4
```
**Example:** weather in two nearby cities (based on an example from [machinelearningmastery.com](https://machinelearningmastery.com/how-to-calculate-joint-marginal-and-conditional-probability/)).
As a more interesting example, let's consider weather in two cities that are a not so far from each other. The weather (sunny/cloudy/rainy) in each city is not indepedent of the weather in the other. Suppose the joint probability distribution is the following (constructed, say out of observations of the weather across 20 days):
| Weather | w2=Sunny | w2=Cloudy | w2=Rainy |
| :-------------|:---------:| :--------:| :-------:|
| **w1=Sunny** | 6/20 | 2/20 | 0/20 |
| **w1=Cloudy** | 1/20 | 5/20 | 2/20 |
| **w1=Rainy** | 0/20 | 1/20 | 3/20 |
We can add to this table the marginal probabilities:
| Weather | w2=Sunny | w2=Cloudy | w2=Rainy | Marginal |
| :-------------|:---------:| :--------:| :-------:| :----------:|
| **w1=Sunny** | 6/20 | 2/20 | 0/20 | 8/20 |
| **w1=Cloudy** | 1/20 | 5/20 | 2/20 | 8/20 |
| **w1=Rainy** | 0/20 | 1/20 | 3/20 | 4/20 |
| **Marginal** | 7/20 | 8/20 | 5/20 | 20/20 |
Now let's compute probability of it being sunny in city 2, given that it is sunny in city 1.
$$
p(\mathrm{w1}=\mathrm{sunny} | \mathrm{w2}=\mathrm{sunny}) = \frac{p(\mathrm{w1}=\mathrm{sunny}, \mathrm{w2}=\mathrm{sunny})}{p(\mathrm{w2}=\mathrm{sunny})} = \frac{6/20}{7/20} = 6/7
$$
Compare that to $p(\mathrm{w1}=\mathrm{sunny}) = 8/20$. This illustrates that knowing that city 2 is sunny makes it much more likely that city 1 is also sunny. These events are clearly not independent!
### Continuous probability distributions
Continuous random variables can take on any real number. The canonical example is the Gaussian (aka normal) distribution. The standard normal distribution (mean equal to zero and standard deviation equal to 1) has the following probability distribution:
$$f(x) = \frac{1}{\sqrt{2 \pi}}e^{-x^2/2}$$
Let's simulate that in Numpy:
```
sample = rng.standard_normal(size=(10000,))
plt.hist(sample, 100, density=True, alpha=0.5);
x = np.linspace(-4, 4, 1000)
normal = (1/np.sqrt(2*np.pi))*np.exp(-x**2/2)
plt.plot(x,normal, label=r'$\frac{1}{\sqrt{2 \pi}}e^{-x^2/2}$');
plt.legend(fontsize='16');
```
| github_jupyter |
# Задание 2.1 - Нейронные сети
В этом задании вы реализуете и натренируете настоящую нейроную сеть своими руками!
В некотором смысле это будет расширением прошлого задания - нам нужно просто составить несколько линейных классификаторов вместе!
<img src="https://i.redd.it/n9fgba8b0qr01.png" alt="Stack_more_layers" width="400px"/>
```
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
from dataset import load_svhn, random_split_train_val
from gradient_check import check_layer_gradient, check_layer_param_gradient, check_model_gradient
from layers import FullyConnectedLayer, ReLULayer
from model import TwoLayerNet
from trainer import Trainer, Dataset
from optim import SGD, MomentumSGD
from metrics import multiclass_accuracy
```
# Загружаем данные
И разделяем их на training и validation.
```
def prepare_for_neural_network(train_X, test_X):
train_flat = train_X.reshape(train_X.shape[0], -1).astype(np.float) / 255.0
test_flat = test_X.reshape(test_X.shape[0], -1).astype(np.float) / 255.0
# Subtract mean
mean_image = np.mean(train_flat, axis = 0)
train_flat -= mean_image
test_flat -= mean_image
return train_flat, test_flat
train_X, train_y, test_X, test_y = load_svhn("data", max_train=10000, max_test=1000)
train_X, test_X = prepare_for_neural_network(train_X, test_X)
# Split train into train and val
train_X, train_y, val_X, val_y = random_split_train_val(train_X, train_y, num_val = 1000)
```
# Как всегда, начинаем с кирпичиков
Мы будем реализовывать необходимые нам слои по очереди. Каждый слой должен реализовать:
- прямой проход (forward pass), который генерирует выход слоя по входу и запоминает необходимые данные
- обратный проход (backward pass), который получает градиент по выходу слоя и вычисляет градиент по входу и по параметрам
Начнем с ReLU, у которого параметров нет.
```
# TODO: Implement ReLULayer layer in layers.py
# Note: you'll need to copy implementation of the gradient_check function from the previous assignment
X = np.array([[1,-2,3],
[-1, 2, 0.1]
])
assert check_layer_gradient(ReLULayer(), X)
```
А теперь реализуем полносвязный слой (fully connected layer), у которого будет два массива параметров: W (weights) и B (bias).
Все параметры наши слои будут использовать для параметров специальный класс `Param`, в котором будут храниться значения параметров и градиенты этих параметров, вычисляемые во время обратного прохода.
Это даст возможность аккумулировать (суммировать) градиенты из разных частей функции потерь, например, из cross-entropy loss и regularization loss.
```
# TODO: Implement FullyConnected layer forward and backward methods
assert check_layer_gradient(FullyConnectedLayer(3, 4), X)
# TODO: Implement storing gradients for W and B
assert check_layer_param_gradient(FullyConnectedLayer(3, 4), X, 'W')
assert check_layer_param_gradient(FullyConnectedLayer(3, 4), X, 'B')
```
## Создаем нейронную сеть
Теперь мы реализуем простейшую нейронную сеть с двумя полносвязным слоями и нелинейностью ReLU. Реализуйте функцию `compute_loss_and_gradients`, она должна запустить прямой и обратный проход через оба слоя для вычисления градиентов.
Не забудьте реализовать очистку градиентов в начале функции.
```
# TODO: In model.py, implement compute_loss_and_gradients function
model = TwoLayerNet(n_input = train_X.shape[1], n_output = 10, hidden_layer_size = 3, reg = 0)
loss = model.compute_loss_and_gradients(train_X[:2], train_y[:2])
# TODO Now implement backward pass and aggregate all of the params
check_model_gradient(model, train_X[:2], train_y[:2])
```
Теперь добавьте к модели регуляризацию - она должна прибавляться к loss и делать свой вклад в градиенты.
```
# TODO Now implement l2 regularization in the forward and backward pass
model_with_reg = TwoLayerNet(n_input = train_X.shape[1], n_output = 10, hidden_layer_size = 3, reg = 1e1)
loss_with_reg = model_with_reg.compute_loss_and_gradients(train_X[:2], train_y[:2])
assert loss_with_reg > loss and not np.isclose(loss_with_reg, loss), \
"Loss with regularization (%2.4f) should be higher than without it (%2.4f)!" % (loss, loss_with_reg)
check_model_gradient(model_with_reg, train_X[:2], train_y[:2])
```
Также реализуем функцию предсказания (вычисления значения) модели на новых данных.
Какое значение точности мы ожидаем увидеть до начала тренировки?
```
# Finally, implement predict function!
# TODO: Implement predict function
# What would be the value we expect?
multiclass_accuracy(model_with_reg.predict(train_X[:30]), train_y[:30])
```
# Допишем код для процесса тренировки
```
model = TwoLayerNet(n_input = train_X.shape[1], n_output = 10, hidden_layer_size = 100, reg = 1e1)
dataset = Dataset(train_X, train_y, val_X, val_y)
trainer = Trainer(model, dataset, SGD())
# TODO Implement missing pieces in Trainer.fit function
# You should expect loss to go down and train and val accuracy go up for every epoch
loss_history, train_history, val_history = trainer.fit()
plt.plot(train_history)
plt.plot(val_history)
```
# Улучшаем процесс тренировки
Мы реализуем несколько ключевых оптимизаций, необходимых для тренировки современных нейросетей.
## Уменьшение скорости обучения (learning rate decay)
Одна из необходимых оптимизаций во время тренировки нейронных сетей - постепенное уменьшение скорости обучения по мере тренировки.
Один из стандартных методов - уменьшение скорости обучения (learning rate) каждые N эпох на коэффициент d (часто называемый decay). Значения N и d, как всегда, являются гиперпараметрами и должны подбираться на основе эффективности на проверочных данных (validation data).
В нашем случае N будет равным 1.
```
# TODO Implement learning rate decay inside Trainer.fit method
# Decay should happen once per epoch
model = TwoLayerNet(n_input = train_X.shape[1], n_output = 10, hidden_layer_size = 100, reg = 1e-1)
dataset = Dataset(train_X, train_y, val_X, val_y)
trainer = Trainer(model, dataset, SGD(), learning_rate_decay=0.99)
initial_learning_rate = trainer.learning_rate
loss_history, train_history, val_history = trainer.fit()
assert trainer.learning_rate < initial_learning_rate, "Learning rate should've been reduced"
assert trainer.learning_rate > 0.5*initial_learning_rate, "Learning rate shouldn'tve been reduced that much!"
```
# Накопление импульса (Momentum SGD)
Другой большой класс оптимизаций - использование более эффективных методов градиентного спуска. Мы реализуем один из них - накопление импульса (Momentum SGD).
Этот метод хранит скорость движения, использует градиент для ее изменения на каждом шаге, и изменяет веса пропорционально значению скорости.
(Физическая аналогия: Вместо скорости градиенты теперь будут задавать ускорение, но будет присутствовать сила трения.)
```
velocity = momentum * velocity - learning_rate * gradient
w = w + velocity
```
`momentum` здесь коэффициент затухания, который тоже является гиперпараметром (к счастью, для него часто есть хорошее значение по умолчанию, типичный диапазон -- 0.8-0.99).
Несколько полезных ссылок, где метод разбирается более подробно:
http://cs231n.github.io/neural-networks-3/#sgd
https://distill.pub/2017/momentum/
```
# TODO: Implement MomentumSGD.update function in optim.py
model = TwoLayerNet(n_input = train_X.shape[1], n_output = 10, hidden_layer_size = 100, reg = 1e-1)
dataset = Dataset(train_X, train_y, val_X, val_y)
trainer = Trainer(model, dataset, MomentumSGD(), learning_rate=1e-4, learning_rate_decay=0.99)
# You should see even better results than before!
loss_history, train_history, val_history = trainer.fit()
```
# Ну что, давайте уже тренировать сеть!
## Последний тест - переобучимся (overfit) на маленьком наборе данных
Хороший способ проверить, все ли реализовано корректно - переобучить сеть на маленьком наборе данных.
Наша модель обладает достаточной мощностью, чтобы приблизить маленький набор данных идеально, поэтому мы ожидаем, что на нем мы быстро дойдем до 100% точности на тренировочном наборе.
Если этого не происходит, то где-то была допущена ошибка!
```
data_size = 15
model = TwoLayerNet(n_input = train_X.shape[1], n_output = 10, hidden_layer_size = 100, reg = 1e-1)
dataset = Dataset(train_X[:data_size], train_y[:data_size], val_X[:data_size], val_y[:data_size])
trainer = Trainer(model, dataset, SGD(), learning_rate=1e-1, num_epochs=150, batch_size=5)
# You should expect this to reach 1.0 training accuracy
loss_history, train_history, val_history = trainer.fit()
```
Теперь найдем гипепараметры, для которых этот процесс сходится быстрее.
Если все реализовано корректно, то существуют параметры, при которых процесс сходится в **20** эпох или еще быстрее.
Найдите их!
```
# Now, tweak some hyper parameters and make it train to 1.0 accuracy in 20 epochs or less
model = TwoLayerNet(n_input = train_X.shape[1], n_output = 10, hidden_layer_size = 100, reg = 1e-1)
dataset = Dataset(train_X[:data_size], train_y[:data_size], val_X[:data_size], val_y[:data_size])
# TODO: Change any hyperparamers or optimizators to reach training accuracy in 20 epochs
trainer = Trainer(model, dataset, SGD(), learning_rate=1e-1, num_epochs=20, batch_size=5)
loss_history, train_history, val_history = trainer.fit()
```
# Итак, основное мероприятие!
Натренируйте лучшую нейросеть! Можно добавлять и изменять параметры, менять количество нейронов в слоях сети и как угодно экспериментировать.
Добейтесь точности лучше **40%** на validation set.
```
# Let's train the best one-hidden-layer network we can
learning_rates = 1e-4
reg_strength = 1e-3
learning_rate_decay = 0.999
hidden_layer_size = 128
num_epochs = 200
batch_size = 64
best_classifier = None
best_val_accuracy = None
loss_history = []
train_history = []
val_history = []
# TODO find the best hyperparameters to train the network
# Don't hesitate to add new values to the arrays above, perform experiments, use any tricks you want
# You should expect to get to at least 40% of valudation accuracy
# Save loss/train/history of the best classifier to the variables above
print('best validation accuracy achieved: %f' % best_val_accuracy)
plt.figure(figsize=(15, 7))
plt.subplot(211)
plt.title("Loss")
plt.plot(loss_history)
plt.subplot(212)
plt.title("Train/validation accuracy")
plt.plot(train_history)
plt.plot(val_history)
```
# Как обычно, посмотрим, как наша лучшая модель работает на тестовых данных
```
test_pred = best_classifier.predict(test_X)
test_accuracy = multiclass_accuracy(test_pred, test_y)
print('Neural net test set accuracy: %f' % (test_accuracy, ))
```
| github_jupyter |
# Browse BBBC021 and pick outlier images to exclude from train/val/test splits
Note that we are only sifting through the images from molecules of known mechanism of action (MoA)
# Preamble and imports
```
%load_ext autoreload
%autoreload 2
import holoviews as hv
import hvplot.pandas
import hvplot.xarray
import janitor
import numpy as np
import pandas as pd
import torch
import umap
import panel as pn
import xarray as xr
from pytorch_hcs.datasets import BBBC021DataModule
from pytorch_hcs.models import ResNet18
from tqdm.notebook import tqdm
from pathlib import Path
hv.extension('bokeh')
from pybbbc import BBBC021
bbbc021 = BBBC021()
```
# Data path
```
data_path = Path("data")
data_path
all_embedding_df = pd.read_parquet(data_path / 'umap_results.parquet')
all_embedding_df
```
# Select the UMAP configuration we want
```
embedding_df = (
all_embedding_df.query('dataset == "BBBC021" and metric == "euclidean" and n_neighbors == 500 and densmap == True and supervised == False')
.copy()
.reset_index(drop=True)
)
embedding_df
hover_cols = [
"image_idx",
"moa",
"compound",
"concentration",
]
groups = ["weights", "metric", "n_neighbors", "densmap", "supervised"]
kwargs = dict(
x="umap_x",
y="umap_y",
hover_cols=hover_cols,
alpha=0.25,
aspect="equal",
cmap="glasbey",
colorbar=False,
width=900,
height=550,
)
(
embedding_df.query('moa != "null"').hvplot.scatter(
c="moa", title="UMAP embedding", **kwargs
)
)
def ecdf(data):
data_sorted = np.sort(data)
# calculate the proportional values of samples
p = np.arange(len(data)) / (len(data) - 1)
return data_sorted, p
from sklearn.neighbors import NearestNeighbors
nbrs = NearestNeighbors(n_neighbors=8)
nbrs.fit(embedding_df[["umap_x", "umap_y"]])
distances, indexes = nbrs.kneighbors(embedding_df[["umap_x", "umap_y"]])
distances = distances[:, 1:]
avg_distances = distances.mean(1)
labeled_embedding_df = embedding_df.add_columns(
outlier_score=avg_distances,
)
cdf_x, cdf_y = ecdf(avg_distances)
(
hv.Curve(
avg_distances,
kdims="BBBC021 image index",
vdims="distance",
label="Average kNN distance for BBBC021 image UMAP projections",
).opts(width=1000)
+ hv.Histogram(
np.histogram(avg_distances, bins=200), kdims="distance"
).opts(width=1000)
+ hv.Curve((cdf_x, cdf_y), kdims="distance", vdims="ECDF").opts(width=1000)
).cols(1)
outlier_df = labeled_embedding_df.sort_values("outlier_score", ascending=False)
outlier_order = outlier_df["image_idx"].values
outlier_scores = outlier_df["outlier_score"].values
def make_layout(image_idx):
image, metadata = bbbc021[outlier_order[image_idx]]
# prefix = f"{metadata.compound.compound} @ {metadata.compound.concentration:.2e} μM, {metadata.compound.moa}"
prefix = f"{metadata.compound.compound}, {metadata.compound.moa}, {outlier_scores[image_idx]}"
plots = []
cmaps = ["fire", "kg", "kb"]
for channel_idx, im_channel in enumerate(image):
plot = hv.Image(
im_channel,
bounds=(0, 0, im_channel.shape[1], im_channel.shape[0]),
label=f"{prefix} | {bbbc021.CHANNELS[channel_idx]}",
).opts(cmap=cmaps[channel_idx])
plots.append(plot)
plots.append(
hv.RGB(
image.transpose(1, 2, 0),
bounds=(0, 0, im_channel.shape[1], im_channel.shape[0]),
label="Channel overlay",
)
)
return hv.Layout(plots).cols(2)
hv.DynamicMap(make_layout, kdims="image").redim.range(
image=(0, len(bbbc021) - 1)
).opts(hv.opts.Image(frame_width=450, aspect='equal'), hv.opts.RGB(frame_width=450, aspect='equal'))
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
from joblib import dump, load
from matplotlib.dates import (YEARLY, DateFormatter,
rrulewrapper, RRuleLocator, drange)
import datetime
import seaborn as sns
import re
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer#nltk.download('wordnet')
import string
from nltk.stem.porter import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
#set working directory
os.chdir(r"C:\Users\mese4\Documents\The Data incubator\project\2020-08-05")
#open metadata from CORD-19 database
df = pd.read_csv('metadata.csv', encoding='ISO-8859-1')
df.head()
#set up time
rule = rrulewrapper(YEARLY, byeaster=1, interval=1)
loc = RRuleLocator(rule)
formatter = DateFormatter('%m/%d/%y')
#create Preprint/peer-reviewed tag
#Drop NAN from abstracts
df_source = df['source_x']
def preprint(a):
if 'BioRxiv' in a :
return 'Preprint'
elif 'MedRxiv' in a:
return 'Preprint'
elif 'ArXiv' in a:
return 'Preprint'
else:
return 'Peer-Review'
pre_pr = [preprint(n) for n in df_source]
df_abs = pd.DataFrame(pre_pr,columns =['preprint'])
df['preprint'] = df_abs #Add preprint tagg to original df
df_19 = df[(df['publish_time'] > '2019-12-01')] #Cut-off date
#convert time to datatime for ploting propouses
df['publish_time'] = pd.to_datetime(df['publish_time'], errors='coerce')
df_19['year'] = df['publish_time'].dt.year #get year column
df_19['month'] = df['publish_time'].dt.month #get month column
#mont_year column
df_19 ['year_month'] = df_19['year'].map(str) + '-' + df_19['month'].map(str)
#Drop rows with abstracts = NaN/emty
df_19 = df_19.dropna(subset = ['abstract'])
df_19.head()
sns.set_context("talk")
sns.set_style('darkgrid')
g = sns.catplot(x="year_month", hue="preprint",
data=df_19, kind="count",
height=5, aspect=5)
#Lemmanisation
dataset=df_19
##Creating a list of stop words and adding custom stopwords
stop_words = set(stopwords.words("english"))
new_words = ["using", "show", 'covid','patient','the','we','in','disease','patients','treatment','viral','data','including','coronavirus','health','study',"result",'unknown','2555','method','infection','day','case','however','moreover','conclusion','virus','patient', "large", "also", "iv", "one",'nan', "new", "previously", "shown",'recently','promising']
stop_words = stop_words.union(new_words)
#Double check that abstracts are strings
dataset['abstract_'] = dataset['abstract'].astype(str)
corpus = []
for i in range(0, len(dataset['abstract_'])):
text = dataset['abstract_'].iloc[i]
text = text.split()
##Stemming
ps = PorterStemmer() #Lemmatisation
lem = WordNetLemmatizer()
text = [lem.lemmatize(word) for word in text if not word.lower() in
stop_words]
text = " ".join(text)
corpus.append(text)
#add corpus back to the df and drop Nan
dataset['corpus'] = corpus
dataset = dataset.dropna(subset = ['corpus'])
#CORD19_processed creates a lighet df to iterate over
CORD19_processed = dataset[['cord_uid','publish_time','preprint','corpus']]
CORD19_processed = CORD19_processed.reset_index()
CORD19_processed.to_csv('CORD19_processed.csv',encoding='utf-8')
#You can create a subset for training/optimisation
df_sub=CORD19_processed.sample(n = 100) #create a subsample for training propouses
df_sub.to_csv('df_sub.csv',encoding='utf-8')
df_sub.head()
```
| github_jupyter |
<h1> Training on Cloud ML Engine </h1>
This notebook illustrates distributed training and hyperparameter tuning on Cloud ML Engine.
```
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import tensorflow as tf
print(tf.__version__)
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
os.environ['TFVERSION'] = '1.8'
%bash
gcloud config set project $PROJECT
gcloud config set compute/region $REGION
%%bash
if ! gsutil ls | grep -q gs://${BUCKET}/; then
gsutil mb -l ${REGION} gs://${BUCKET}
# copy canonical set of preprocessed files if you didn't do previous notebook
gsutil -m cp -R gs://cloud-training-demos/babyweight gs://${BUCKET}
fi
%bash
gsutil ls gs://${BUCKET}/babyweight/preproc/*-00000*
```
Now that we have the TensorFlow code working on a subset of the data, we can package the TensorFlow code up as a Python module and train it on Cloud ML Engine.
<p>
<h2> Train on Cloud ML Engine </h2>
<p>
Training on Cloud ML Engine requires:
<ol>
<li> Making the code a Python package
<li> Using gcloud to submit the training code to Cloud ML Engine
</ol>
## Lab Task 1
The following code edits babyweight/trainer/task.py.
```
%writefile babyweight/trainer/task.py
import argparse
import json
import os
import model
import tensorflow as tf
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--bucket',
help = 'GCS path to data. We assume that data is in gs://BUCKET/babyweight/preproc/',
required = True
)
parser.add_argument(
'--output_dir',
help = 'GCS location to write checkpoints and export models',
required = True
)
parser.add_argument(
'--batch_size',
help = 'Number of examples to compute gradient over.',
type = int,
default = 512
)
parser.add_argument(
'--job-dir',
help = 'this model ignores this field, but it is required by gcloud',
default = 'junk'
)
parser.add_argument(
'--nnsize',
help = 'Hidden layer sizes to use for DNN feature columns -- provide space-separated layers',
nargs = '+',
type = int,
default=[128, 32, 4]
)
parser.add_argument(
'--nembeds',
help = 'Embedding size of a cross of n key real-valued parameters',
type = int,
default = 3
)
## TODO 1: add the new arguments here
parser.add_argument(
'--train_examples',
help = 'Number of examples (in thousands) to run the training job over. If this is more than actual # of examples available, it cycles through them. So specifying 1000 here when you have only 100k examples makes this 10 epochs.',
type = int,
default = 5000
)
parser.add_argument(
'--pattern',
help = 'Specify a pattern that has to be in input files. For example 00001-of will process only one shard',
default = 'of'
)
parser.add_argument(
'--eval_steps',
help = 'Positive number of steps for which to evaluate model. Default to None, which means to evaluate until input_fn raises an end-of-input exception',
type = int,
default = None
)
## parse all arguments
args = parser.parse_args()
arguments = args.__dict__
# unused args provided by service
arguments.pop('job_dir', None)
arguments.pop('job-dir', None)
## assign the arguments to the model variables
output_dir = arguments.pop('output_dir')
model.BUCKET = arguments.pop('bucket')
model.BATCH_SIZE = arguments.pop('batch_size')
model.TRAIN_STEPS = (arguments.pop('train_examples') * 1000) / model.BATCH_SIZE
model.EVAL_STEPS = arguments.pop('eval_steps')
print ("Will train for {} steps using batch_size={}".format(model.TRAIN_STEPS, model.BATCH_SIZE))
model.PATTERN = arguments.pop('pattern')
model.NEMBEDS= arguments.pop('nembeds')
model.NNSIZE = arguments.pop('nnsize')
print ("Will use DNN size of {}".format(model.NNSIZE))
# Append trial_id to path if we are doing hptuning
# This code can be removed if you are not using hyperparameter tuning
output_dir = os.path.join(
output_dir,
json.loads(
os.environ.get('TF_CONFIG', '{}')
).get('task', {}).get('trial', '')
)
# Run the training job
model.train_and_evaluate(output_dir)
```
## Lab Task 2
The following code edits babyweight/trainer/model.py.
```
%writefile babyweight/trainer/model.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
BUCKET = None # set from task.py
PATTERN = 'of' # gets all files
# Determine CSV, label, and key columns
CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',')
LABEL_COLUMN = 'weight_pounds'
KEY_COLUMN = 'key'
# Set default values for each CSV column
DEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], ['nokey']]
# Define some hyperparameters
TRAIN_STEPS = 10000
EVAL_STEPS = None
BATCH_SIZE = 512
NEMBEDS = 3
NNSIZE = [64, 16, 4]
# Create an input function reading a file using the Dataset API
# Then provide the results to the Estimator API
def read_dataset(prefix, mode, batch_size):
def _input_fn():
def decode_csv(value_column):
columns = tf.decode_csv(value_column, record_defaults=DEFAULTS)
features = dict(zip(CSV_COLUMNS, columns))
label = features.pop(LABEL_COLUMN)
return features, label
# Use prefix to create file path
file_path = 'gs://{}/babyweight/preproc/{}*{}*'.format(BUCKET, prefix, PATTERN)
# Create list of files that match pattern
file_list = tf.gfile.Glob(file_path)
# Create dataset from file list
dataset = (tf.data.TextLineDataset(file_list) # Read text file
.map(decode_csv)) # Transform each elem by applying decode_csv fn
if mode == tf.estimator.ModeKeys.TRAIN:
num_epochs = None # indefinitely
dataset = dataset.shuffle(buffer_size = 10 * batch_size)
else:
num_epochs = 1 # end-of-input after this
dataset = dataset.repeat(num_epochs).batch(batch_size)
return dataset.make_one_shot_iterator().get_next()
return _input_fn
# Define feature columns
def get_wide_deep():
# Define column types
is_male,mother_age,plurality,gestation_weeks = \
[\
tf.feature_column.categorical_column_with_vocabulary_list('is_male',
['True', 'False', 'Unknown']),
tf.feature_column.numeric_column('mother_age'),
tf.feature_column.categorical_column_with_vocabulary_list('plurality',
['Single(1)', 'Twins(2)', 'Triplets(3)',
'Quadruplets(4)', 'Quintuplets(5)','Multiple(2+)']),
tf.feature_column.numeric_column('gestation_weeks')
]
# Discretize
age_buckets = tf.feature_column.bucketized_column(mother_age,
boundaries=np.arange(15,45,1).tolist())
gestation_buckets = tf.feature_column.bucketized_column(gestation_weeks,
boundaries=np.arange(17,47,1).tolist())
# Sparse columns are wide, have a linear relationship with the output
wide = [is_male,
plurality,
age_buckets,
gestation_buckets]
# Feature cross all the wide columns and embed into a lower dimension
crossed = tf.feature_column.crossed_column(wide, hash_bucket_size=20000)
embed = tf.feature_column.embedding_column(crossed, NEMBEDS)
# Continuous columns are deep, have a complex relationship with the output
deep = [mother_age,
gestation_weeks,
embed]
return wide, deep
# Create serving input function to be able to serve predictions later using provided inputs
def serving_input_fn():
feature_placeholders = {
'is_male': tf.placeholder(tf.string, [None]),
'mother_age': tf.placeholder(tf.float32, [None]),
'plurality': tf.placeholder(tf.string, [None]),
'gestation_weeks': tf.placeholder(tf.float32, [None]),
KEY_COLUMN: tf.placeholder_with_default(tf.constant(['nokey']), [None])
}
features = {
key: tf.expand_dims(tensor, -1)
for key, tensor in feature_placeholders.items()
}
return tf.estimator.export.ServingInputReceiver(features, feature_placeholders)
# create metric for hyperparameter tuning
def my_rmse(labels, predictions):
pred_values = predictions['predictions']
return {'rmse': tf.metrics.root_mean_squared_error(labels, pred_values)}
# Create estimator to train and evaluate
def train_and_evaluate(output_dir):
wide, deep = get_wide_deep()
EVAL_INTERVAL = 300 # seconds
## TODO 2a: set the save_checkpoints_secs to the EVAL_INTERVAL
run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL,
keep_checkpoint_max = 3)
## TODO 2b: change the dnn_hidden_units to NNSIZE
estimator = tf.estimator.DNNLinearCombinedRegressor(
model_dir = output_dir,
linear_feature_columns = wide,
dnn_feature_columns = deep,
dnn_hidden_units = NNSIZE,
config = run_config)
# illustrates how to add an extra metric
estimator = tf.contrib.estimator.add_metrics(estimator, my_rmse)
# for batch prediction, you need a key associated with each instance
estimator = tf.contrib.estimator.forward_features(estimator, KEY_COLUMN)
## TODO 2c: Set the third argument of read_dataset to BATCH_SIZE
## TODO 2d: and set max_steps to TRAIN_STEPS
train_spec = tf.estimator.TrainSpec(
input_fn = read_dataset('train', tf.estimator.ModeKeys.TRAIN, BATCH_SIZE),
max_steps = TRAIN_STEPS)
exporter = tf.estimator.LatestExporter('exporter', serving_input_fn, exports_to_keep=None)
## TODO 2e: Lastly, set steps equal to EVAL_STEPS
eval_spec = tf.estimator.EvalSpec(
input_fn = read_dataset('eval', tf.estimator.ModeKeys.EVAL, 2**15), # no need to batch in eval
steps = EVAL_STEPS,
start_delay_secs = 60, # start evaluating after N seconds
throttle_secs = EVAL_INTERVAL, # evaluate every N seconds
exporters = exporter)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
```
## Lab Task 3
After moving the code to a package, make sure it works standalone. (Note the --pattern and --train_examples lines so that I am not trying to boil the ocean on my laptop). Even then, this takes about <b>3 minutes</b> in which you won't see any output ...
```
%bash
echo "bucket=${BUCKET}"
rm -rf babyweight_trained
export PYTHONPATH=${PYTHONPATH}:${PWD}/babyweight
python -m trainer.task \
--bucket=${BUCKET} \
--output_dir=babyweight_trained \
--job-dir=./tmp \
--pattern="00000-of-" --train_examples=1 --eval_steps=1
```
## Lab Task 4
The JSON below represents an input into your prediction model. Write the input.json file below with the next cell, then run the prediction locally to assess whether it produces predictions correctly.
```
%writefile inputs.json
{"key": "b1", "is_male": "True", "mother_age": 26.0, "plurality": "Single(1)", "gestation_weeks": 39}
{"key": "g1", "is_male": "False", "mother_age": 26.0, "plurality": "Single(1)", "gestation_weeks": 39}
%bash
MODEL_LOCATION=$(ls -d $(pwd)/babyweight_trained/export/exporter/* | tail -1)
echo $MODEL_LOCATION
gcloud ml-engine local predict --model-dir=$MODEL_LOCATION --json-instances=inputs.json
```
## Lab Task 5
Once the code works in standalone mode, you can run it on Cloud ML Engine. Because this is on the entire dataset, it will take a while. The training run took about <b> an hour </b> for me. You can monitor the job from the GCP console in the Cloud Machine Learning Engine section.
```
%bash
OUTDIR=gs://${BUCKET}/babyweight/trained_model
JOBNAME=babyweight_$(date -u +%y%m%d_%H%M%S)
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
gcloud ml-engine jobs submit training $JOBNAME \
--region=$REGION \
--module-name=trainer.task \
--package-path=$(pwd)/babyweight/trainer \
--job-dir=$OUTDIR \
--staging-bucket=gs://$BUCKET \
--scale-tier=STANDARD_1 \
--runtime-version=$TFVERSION \
-- \
--bucket=${BUCKET} \
--output_dir=${OUTDIR} \
--train_examples=200000
```
When I ran it, I used train_examples=2000000. When training finished, I filtered in the Stackdriver log on the word "dict" and saw that the last line was:
<pre>
Saving dict for global step 5714290: average_loss = 1.06473, global_step = 5714290, loss = 34882.4, rmse = 1.03186
</pre>
The final RMSE was 1.03 pounds.
```
from google.datalab.ml import TensorBoard
TensorBoard().start('gs://{}/babyweight/trained_model'.format(BUCKET))
for pid in TensorBoard.list()['pid']:
TensorBoard().stop(pid)
print 'Stopped TensorBoard with pid {}'.format(pid)
```
<h2> Hyperparameter tuning </h2>
<p>
All of these are command-line parameters to my program. To do hyperparameter tuning, create hyperparam.xml and pass it as --configFile.
This step will take <b>1 hour</b> -- you can increase maxParallelTrials or reduce maxTrials to get it done faster. Since maxParallelTrials is the number of initial seeds to start searching from, you don't want it to be too large; otherwise, all you have is a random search.
```
%writefile hyperparam.yaml
trainingInput:
scaleTier: STANDARD_1
hyperparameters:
hyperparameterMetricTag: rmse
goal: MINIMIZE
maxTrials: 20
maxParallelTrials: 5
enableTrialEarlyStopping: True
params:
- parameterName: batch_size
type: INTEGER
minValue: 8
maxValue: 512
scaleType: UNIT_LOG_SCALE
- parameterName: nembeds
type: INTEGER
minValue: 3
maxValue: 30
scaleType: UNIT_LINEAR_SCALE
- parameterName: nnsize
type: INTEGER
minValue: 64
maxValue: 512
scaleType: UNIT_LOG_SCALE
%bash
OUTDIR=gs://${BUCKET}/babyweight/hyperparam
JOBNAME=babyweight_$(date -u +%y%m%d_%H%M%S)
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
gcloud ml-engine jobs submit training $JOBNAME \
--region=$REGION \
--module-name=trainer.task \
--package-path=$(pwd)/babyweight/trainer \
--job-dir=$OUTDIR \
--staging-bucket=gs://$BUCKET \
--scale-tier=STANDARD_1 \
--config=hyperparam.yaml \
--runtime-version=$TFVERSION \
-- \
--bucket=${BUCKET} \
--output_dir=${OUTDIR} \
--eval_steps=10 \
--train_examples=20000
```
<h2> Repeat training </h2>
<p>
This time with tuned parameters (note last line)
```
%bash
OUTDIR=gs://${BUCKET}/babyweight/trained_model_tuned
JOBNAME=babyweight_$(date -u +%y%m%d_%H%M%S)
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
gcloud ml-engine jobs submit training $JOBNAME \
--region=$REGION \
--module-name=trainer.task \
--package-path=$(pwd)/babyweight/trainer \
--job-dir=$OUTDIR \
--staging-bucket=gs://$BUCKET \
--scale-tier=STANDARD_1 \
--runtime-version=$TFVERSION \
-- \
--bucket=${BUCKET} \
--output_dir=${OUTDIR} \
--train_examples=20000 --batch_size=35 --nembeds=16 --nnsize=281
```
Copyright 2017 Google Inc. 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
| github_jupyter |
# Featurize Spectra from XY files into polynomial coefficient files.
Generates polynomial featurized XY files; takes as input XY files and produces files with polynomial fits performed.
## This notebook requires that the TRIXS repo is in your Python path.
That can be found here: https://github.com/TRI-AMDD/trixs.
```
# Set where the spectral data (XY files) are
storage_directory = './spectral_data'
# Define what transition metal oxides will be covered
target_elements_groups=[('Ti','O'),('V','O'),('Cr','O'),
('Mn','O'),('Fe','O'),('Co','O'),
('Ni','O'),('Cu','O')]
target_metals = set(['Co','Ni','Fe','Cr','V','Mn','Cu','Ti'])
target_elements_sets =[set(pair) for pair in target_elements_groups]
# Colors for later plotting!
colors_by_pair = {('Ti','O'):'orangered',
('V','O'):'darkorange',
('Cr','O'):'gold',
('Mn','O'):'seagreen',
('Fe','O'):'dodgerblue',
('Co','O'):'navy',
('Ni','O'):'rebeccapurple',
('Cu','O'):"mediumvioletred"}
import os
for figure_write_folder in ['./figures_feffnorm','./figures_maxnorm']:
try:
os.mkdir(figure_write_folder)
except OSError as error:
pass
```
# Import Relevant Functions
```
import sys
import matplotlib
import json
import numpy as np
import matplotlib.pyplot as plt
#sys.path.append(os.path.join(os.getcwd(), '..')) # TRIXS path if not automatically detected
from trixs.spectra.core import XAS_Spectrum
from trixs.spectra.spectrum_featurize import polynomialize_by_idx, gauge_polynomial_error
from tqdm.notebook import tqdm
```
## Define helper functions for quality control of spectra
```
def prune_outliers(mu):
"""
Given an absorption spectra, check on three unphysical ways we saw FEFF spectra behave for a small
number of outlying data sets:
1. A strange absorption pattern in which the absorption increases, rather than decays, in the XAFS region
2. Unusually high absorption value
3. A spuriously high peak-- larger than the edge's peak-- in the pre-edge region.
"""
if mu[-1]==np.max(mu):
return False
if np.max(mu)>3:
return False
if np.max(mu) in mu[:10]:
return False
return True
def test_poly_error_fit(X_set,idxs,x_domain,error_bound=.1, use_norm = True):
"""
Test multiple polynomials to see how their error compars to a cutoff bound
"""
idx_keep = []
for spec,idx in zip(X_set,idxs):
within_bound = one_shot_poly_error_fit(x_domain,spec,
use_norm=use_norm,error_bound=error_bound)
if not within_bound:
continue
idx_keep.append(idx)
print("Dropped {}".format(len(idxs)-len(idx_keep)))
return idx_keep
def one_shot_poly_error_fit(x_domain, mu,use_norm = True, error_bound = .1):
"""
Test one polynomial fit to an XAS spectrum to see if the error exceeds a given cutoff.
"""
if use_norm:
poly_set = polynomialize_by_idx(x_domain,mu/np.max(mu),N=20,deg=3,label_type='frac')
else:
poly_set = polynomialize_by_idx(x_domain,mu,N=20,deg=3,label_type='frac')
for poly in poly_set:
poly.error = gauge_polynomial_error(poly.x,poly.y,poly,error='abs')
if poly.error>.1:
return False
return True
```
## Load relevant data
```
data_by_pair = {pair:[] for pair in target_elements_groups}
for pair in target_elements_groups:
file_target = storage_directory+f'/{pair[0]}_XY.json'
with open(file_target,'r') as f:
data_by_pair[pair] = [json.loads(line) for line in f.readlines()]
```
# Perform Polynomial Fits
```
polynomials_by_pair = {pair:[] for pair in target_elements_groups}
for max_normalized in [True,False]:
norm_str = 'max' if max_normalized else 'feff'
for pair in target_elements_groups:
if max_normalized:
target_file = storage_directory + '/{}_{}norm_polynomial_XY.json'.format(pair[0],norm_str)
else:
target_file = storage_directory + '/{}_{}norm_polynomial_XY.json'.format(pair[0],norm_str)
with open(target_file,'w') as f:
errors = []
# Tally spectra which do not pass outlier, data suitability,
# or polynomial featurization fidelity criteria
ineligible = 0
outliers = 0
unfeaturized = 0
written = 0
cond_nums = []
for dat in tqdm(data_by_pair[pair],desc=pair[0]):
if not (dat.get('bader') or dat.get('coordination') in [4,5,6]):
ineligible +=1
continue
cur_spec = XAS_Spectrum(dat['E'],dat['mu'])
if not prune_outliers(cur_spec.y):
outliers +=1
continue
if not one_shot_poly_error_fit(cur_spec.x,cur_spec.y,use_norm=True,error_bound=.1):
unfeaturized +=1
continue
if max_normalized:
cur_spec.normalize('max')
cur_cond_nums = []
cur_errors = []
poly_set = {}
peak = cur_spec.get_peak_idx()
labeled_coefficients = {}
labeled_coefficients['peak'] = int(peak)
labeled_coefficients['random'] = np.random.uniform(0,1)
for n in [4,5,10,20]:
poly_set[n] = polynomialize_by_idx(cur_spec.x,cur_spec.y,N=n,deg=3,label_type='frac')
for poly in poly_set[n]:
cur_cond_nums.append(max(poly.full_data[2])/min(poly.full_data[2]))
cond_nums.append(cur_cond_nums[-1])
for i, coef in enumerate(poly.coef):
coefficient_label = 'loc:all,'+poly.label +',coef:' +str(i)
labeled_coefficients[coefficient_label] = coef
if n == 20:
poly.error = gauge_polynomial_error(poly.x,poly.y,poly,error='abs')
cur_errors.append(poly.error)
errors+=cur_errors
dat['labeled_coefficients'] = labeled_coefficients
write_data = {}
if not dat.get('labeled_coefficients', False):
continue
write_data['labeled_coefficients'] = dat['labeled_coefficients']
write_data['coordination'] = dat['coordination']
write_data['one_hot_coord'] = dat['one_hot_coord']
write_data['bader'] = dat['bader']
write_data['guessed_oxy'] = dat.get('guessed_oxy',None)
write_data['nn_indexes'] = dat.get('nn_indexes')
write_data['nn_species'] =dat.get('nn_species')
write_data['nn_dists'] = dat.get('nn_dists')
write_data['avg_nn_dists'] = np.mean(dat.get('nn_dists'))
write_data['nn_min-max'] = dat.get('nn_min-max')
write_data['mp_baders'] = dat.get('mp_baders')
write_data['oqmd_baders'] = dat.get('oqmd_baders')
write_data['valid_bader'] = dat.get('valid_bader')
f.write(json.dumps(write_data) + '\n')
written +=1
print(f"For {pair}: Ineligible:{ineligible}, Outliered: {outliers}, Excluded: {unfeaturized}")
norm_str = 'max' if max_normalized else 'feff'
norm_title = 'Max-Normalized' if max_normalized else 'FEFF Normalized'
plt.hist(errors,bins=20,color=colors_by_pair[pair])
plt.title(f"Error Distribution\nfor 20-Fold Polynomial Fits on {norm_title} {pair[0]}\n ({written}/{written+unfeaturized} Used)")
plt.xlabel("Sum of Abs. Error")
plt.yscale('log')
plt.ylabel("Total Number of Polynomials")
plt.savefig(f"./figures_{norm_str}norm/{pair[0]}_{norm_str}_poly_errors.pdf".format(pair[0],norm_str),format='pdf',dpi=300,bbox_inches='tight',transparent=True)
plt.show()
```
| github_jupyter |
# Quantifying ecological resistance and resilience
Reference: https://www.ncbi.nlm.nih.gov/pubmed/29477443/
**Housekeeping**
```
library(emmeans)
library(ggplot2)
library(ggpubr)
library(MASS)
library(nlme)
library(philentropy)
library(reshape2)
library(Rmisc)
library(scales)
library(vegan)
```
**Read in data**
```
species_composition = read.table("../../../data/amplicon/rel_abund.txt",
sep = "\t",
header = T,
row.names = 1)
metadata = read.table("../../../data/amplicon/meta.txt",
sep = "\t",
header = T,
row.names = 1)
# inspect
head(species_composition)
head(metadata)
```
**Compute community divergence over time within subtreatments using KL divergence**
Compute KL divergence between all samples
```
KL_divergence = KL(as.matrix(species_composition))
rownames(KL_divergence) = rownames(species_composition)
colnames(KL_divergence) = rownames(species_composition)
# inspect
head(KL_divergence)
```
Extract divergence values for each community over time compared to pre-disturbance state (before antibiotic pulse vs. after pulse / after recovery)
```
# use metadata to create data frame for community over time containing sample identifier
metadata$ID = rownames(metadata)
metadata2 = dcast(metadata,
Replicate + Streptomycin + Immigration ~ Day,
value.var = "ID")
metadata2 = na.omit(metadata2)
metadata2$post_disturbance = NA
metadata2$post_recovery = NA
# loop over sample identifiers to add corresponding KL divergence values
for(i in 1:nrow(metadata2)){
a = metadata2[i, 4]
b = metadata2[i, 5]
c = metadata2[i, 6]
metadata2[i, "post_disturbance"] = KL_divergence[rownames(KL_divergence) == a, colnames(KL_divergence) == b]
metadata2[i, "post_recovery"] = KL_divergence[rownames(KL_divergence) == a, colnames(KL_divergence) == c]
}
# inspect
head(metadata2)
```
Convert to narrow format for plotting
```
KL = melt(metadata2[,-c(4:6)], id.vars = c("Replicate", "Streptomycin", "Immigration"))
colnames(KL) = c("Replicate", "Streptomycin", "Immigration", "Recovery_time", "System_state")
KL$Recovery_time = as.numeric(as.character(ifelse(KL$Recovery_time == "post_disturbance", 0, 16)))
# inspect
head(KL)
```
Edit factors for plotting
```
KL$Streptomycin = factor(KL$Streptomycin, levels = c(0, 4, 16, 128),
labels = c("No", "Low", "Intermediate", "High"))
KL$Immigration = ifelse(KL$Immigration == 0, "No immigration", "Immigration")
KL$Immigration = factor(KL$Immigration,
levels = c("No immigration", "Immigration"))
p1 = ggplot(KL, aes(factor(Recovery_time), System_state,
colour = factor(Streptomycin))) +
facet_grid(~Immigration) +
geom_boxplot(outlier.shape = NA) +
geom_point(position = position_jitterdodge()) +
scale_color_manual(values = c("#D3D3D3", "#cd6090", "#8f4364", "#522639")) +
scale_fill_manual(values = c("#D3D3D3", "#cd6090", "#8f4364", "#522639")) +
ylab("KL divergence relative to\npre-disturbance state") +
scale_x_discrete(breaks = c(0,16), labels = c("Post-\ndisturbance", "Post-\nrecovery")) +
labs(colour = "Antibiotic level", fill = "Antibiotic level") +
theme_classic() +
theme(strip.background = element_rect(colour = "white", fill = "white"),
strip.text = element_text(size = 16),
axis.title.x = element_blank(),
axis.text.x = element_text(size = 16, color = "black"),
axis.title.y = element_text(size = 16, color = "black"),
axis.text.y = element_text(size = 16, color = "black"),
legend.text = element_text(size = 16, color = "black"),
legend.title = element_text(size = 16, color = "black"),
plot.margin=unit(c(5.5, 5.5, 5.5, 15), "points"))
p1
```
**Stats for KL divergence**
Create statistical model
```
# add sample id
KL$Sample = paste(KL$Streptomycin, KL$Immigration, KL$Replicate, sep = "_")
# let's use generalized least squares models that account for repeated measures
# define basic model
M1 = gls(System_state ~ Streptomycin + Immigration + Recovery_time,
data = KL,
correlation = corAR1(form = ~ 1 | Sample),
method = "ML")
# use stepwise model selection to find best model
M2 = stepAIC(M1,
scope = list(upper = ~Streptomycin * Immigration * Recovery_time, lower = ~1),
trace = FALSE)
# let's also try with streptomycin dependent variance structure
M3 = gls(System_state ~ Streptomycin + Immigration + Recovery_time,
data = KL,
weights = varIdent(form = ~1 | Streptomycin),
correlation = corAR1(form = ~ 1 | Sample),
method = "ML")
M4 = stepAIC(M3,
scope = list(upper = ~Streptomycin * Immigration * Recovery_time, lower = ~1),
trace = FALSE)
# let's compare models with and without streptomycin specific variance structure
anova(M2, M3) # M3 better
```
Model validation
```
# homogeneity: residuals vs. predicted values
E1 = resid(M3)
F1 = fitted(M3)
par(mfrow = c(1, 1))
plot(x = F1,
y = E1,
xlab = "Fitted values",
ylab = "Residuals")
abline(v = 0, lwd = 2, col = 2)
abline(h = 0, lty = 2, col = 1)
# homogeneity/independence: residuals vs. covariates
plot( x = KL$Streptomycin,
y = E1,
xlab = "Streptomycin",
ylab = "Pearson residuals",
cex.lab = 1.5)
abline(h = 0, lty = 2)
plot( x = KL$Immigration,
y = E1,
xlab = "Immigration",
ylab = "Pearson residuals",
cex.lab = 1.5)
abline(h = 0, lty = 2)
plot( x = KL$Recovery_time,
y = E1,
xlab = "Time",
ylab = "Pearson residuals",
cex.lab = 1.5)
abline(h = 0, lty = 2)
# normality
par(mfrow = c(1, 1))
hist(E1, breaks = 10)
```
Model inspection
```
anova(M3)
# antibiotic, immigration and recovery time all significant
# pairwise contrasts for antibiotic levels
comm.emm.s = emmeans(M3, pairwise ~ Streptomycin)
pairs(comm.emm.s)
```
**Combined KL divergence with diversity plot**
Compute Shannon index as a proxy for diversity
```
diversity = diversity(species_composition, "shannon")
# merge with metadata
diversity = data.frame(Diversity = diversity, metadata)
# inspect
head(diversity)
```
Subset to post-disturbance time point (day 32)
```
diversity_post_disturbance = diversity[diversity$Day == 32,]
# inspect
head(diversity_post_disturbance)
```
Preparation for plotting
```
# edit factors
diversity_post_disturbance$Immigration = as.factor(ifelse(diversity_post_disturbance$Immigration == 0,
"Absent", "Present"))
diversity_post_disturbance$Streptomycin = factor(diversity_post_disturbance$Streptomycin,
levels = c("0", "4", "16", "128"),
labels = c("No", "Low", "Intermediate", "High"))
# define color palette
mypalette = c("#D3D3D3", "#cd6090", "#8f4364", "#522639")
```
Plot code
```
p2 = ggplot(diversity_post_disturbance, aes(x = Streptomycin, y = Diversity, colour = Streptomycin)) +
geom_boxplot(outlier.shape = NA) +
geom_point(position = position_jitterdodge()) +
scale_colour_manual(values = mypalette) +
scale_fill_manual(values = mypalette) +
xlab("Antibiotic level") +
ylab("Diversity (Shannon entropy)") +
theme_classic() +
theme(legend.position = "none") +
xlab("Post-\ndisturbance") +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.title.x = element_text(size = 16, color = "black"),
axis.text.y = element_text(size = 16, color = "black"),
axis.title.y = element_text(size = 16, color = "black"),
plot.margin=unit(c(30, 5.5, 5.5, 5.5), "points"))
p2
```
Create multipanel figure
```
ggarrange(p2, p1,
labels = c("A", "B"),
widths = c(0.5, 2.2),
ncol = 2,
nrow = 1,
font.label = list(size = 16))
```
**Save plot**
```
# ggsave("../../../manuscript/figures/comm_response.pdf", width = 11.5, height = 4)
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import json
import matplotlib
import matplotlib.pyplot as plt
# import get_sentiment_score as gss
#load dataset
df = pd.read_csv('data/raw_data/tmdb_5000_credits.csv')
df.head() #view data
score = np.zeros(len(df.index)) #initalize scores
castsize = np.zeros(len(df.index), dtype=int) #initialize case sizes
g =[0]*len(df.index) #initialize gender list for all movies
wanttoweight = True #do you want to weight lead roles?
for m in df.index: #loop over all movies
m_all = True #debug boolean
#extract movie
cast = json.loads(df['cast'][m]) #extract cast from dataset
castsize[m] = len(cast) #number of cast members
gendernos = np.zeros(castsize[m])
if castsize[m] == 0 or castsize[m] == []: #no cast listed
score[m] = np.nan #nan for no cast
m_all = False #debug boolean
else:
if wanttoweight:
#asymmetrical sigmoidal curve fit from https://mycurvefit.com/
weights = [ 0.00557557 + (1.002644 - 0.00557557)/(1 + (x/1.794024)**8.661941)**0.5556762
for x in np.linspace(1,10,20)] #weight lead roles more (up to 20 roles)
else:
weights = np.ones(20)
if castsize[m] > 20: #more than 20 memebrs in cast
ind = range(0,20)
else: #less than 20 members in cast
ind = range(0,castsize[m])
for c in ind: #loop over all cast members
gendernos[c] = cast[c]['gender']
if cast[c]['gender'] == 1: #female
score[m] = score[m] + weights[c] #female cast members boost score
m_all = False #debug boolean
elif cast[c]['gender'] != 2: #not female nor male gender number
weights[c] = 0; #discount entry
score[m] = score[m]/sum(weights[:c+1]) #take the weighted average of the score
g[m] = gendernos #store gender numbers into gender list
if score[m] == np.inf:
score[m] = np.nan
m_all = False #debug boolean
#DEBUGGING ONLY
#if m_all:
#score[m] = -1
#put scores into dataframe
df['gender diversity score'] = score
df
sentiment_df = pd.read_csv('data/sentiment_scores.csv')
df = df.set_index('movie_id')
for index, row in sentiment_df.iterrows():
curr_movie_id = sentiment_df.at[index,'movie_id']
sentiment_score = sentiment_df.at[index, "sentiment_score"]
df.at[curr_movie_id, "sentiment_score"] = sentiment_score
#extract nan values to find real score
score_real = score[np.argwhere(~np.isnan(score))]
len(score_real) #check size of real values
#plot results of all movies
n_bins = 20
fig, ax = plt.subplots()
n, bins, patches = plt.hist(score_real, bins=n_bins, alpha=0.35, edgecolor='k')
ax.set(xlabel='gender diversity score', ylabel='number of movies',
title='Histogram of Gender Diversity Score')
ax.grid()
mean = plt.axvline(score_real.mean(), color='r', linestyle='dashed', linewidth=1)
median = plt.axvline(np.percentile(score_real,50), color='k', linestyle='dashed', linewidth=1)
#plt.axvline(np.percentile(score_real,25), color='r', linestyle='dashed', linewidth=1)
#plt.axvline(np.percentile(score_real,75), color='r', linestyle='dashed', linewidth=1)
ninety = plt.axvline(np.percentile(score_real,90), color='k', linestyle='dashed', linewidth=1)
ten = plt.axvline(np.percentile(score_real,10), color='k', linestyle='dashed', linewidth=1)
ax.legend((mean, median, ninety, ten), ('mean','median','90%','10%'))
#create subset
df_subset = pd.DataFrame(columns=list(df)) #initialize
df_real = df.dropna() #get rid of nans
strata = 10 #how many data strata do we want?
subsetno = 100 #how large do we want the subset to be
edges = np.linspace(0,1,strata+1) #edges of data strata
for i in range(0,strata):
df_temp = df_real[(df_real['gender diversity score'] > edges[i]) &
(df_real['gender diversity score'] < edges[i+1])]
temp_ind = np.round(np.linspace(0,len(df_temp)-1,subsetno/strata))
df_subset = pd.concat([df_subset,
df_temp.sort_values(by=['gender diversity score']).iloc[temp_ind,:].reset_index(drop=True)],
ignore_index=True)
df_subset = df_subset.drop_duplicates()
df_subset
#json.loads(df_subset['cast'][4]) #if you want to query a specific movie
len(df_subset)
#plot subset results
subset_scores = df_subset['gender diversity score'][:]
n_bins = 20
fig, ax = plt.subplots()
n, bins, patches = plt.hist(subset_scores, bins=n_bins, alpha=0.35, edgecolor='k')
ax.set(xlabel='gender diversity score', ylabel='number of movies',
title='Histogram of Gender Diversity Score (Subset)')
ax.grid()
mean = plt.axvline(subset_scores.mean(), color='r', linestyle='dashed', linewidth=1)
median = plt.axvline(np.percentile(subset_scores,50), color='k', linestyle='dashed', linewidth=1)
#plt.axvline(np.percentile(subset_scores,25), color='r', linestyle='dashed', linewidth=1)
#plt.axvline(np.percentile(subset_scores,75), color='r', linestyle='dashed', linewidth=1)
ninety = plt.axvline(np.percentile(subset_scores,90), color='k', linestyle='dashed', linewidth=1)
ten = plt.axvline(np.percentile(subset_scores,10), color='k', linestyle='dashed', linewidth=1)
ax.legend((mean, median, ninety, ten), ('mean','median','90%','10%'))
max(castsizes_real)
#plot cast distribution
castsizes_real = castsize[np.argwhere(~np.isnan(castsize))]
binwidth =10
n_bins = range(0, int(10*np.floor(max(castsizes_real)/10)) + binwidth, binwidth)
fig, ax = plt.subplots()
n, bins, patches = plt.hist(castsizes_real, bins=n_bins, alpha=0.35, edgecolor='k', facecolor='g')
ax.set(xlabel='cast size', ylabel='number of movies',
title='Histogram of Cast Size')
ax.grid()
mean = plt.axvline(castsizes_real.mean(), color='r', linestyle='dashed', linewidth=1)
median = plt.axvline(np.percentile(castsizes_real,50), color='k', linestyle='dashed', linewidth=1)
#plt.axvline(np.percentile(castsizes_real,25), color='r', linestyle='dashed', linewidth=1)
#plt.axvline(np.percentile(castsizes_real,75), color='r', linestyle='dashed', linewidth=1)
ninety = plt.axvline(np.percentile(castsizes_real,90), color='k', linestyle='dashed', linewidth=1)
ten = plt.axvline(np.percentile(castsizes_real,10), color='k', linestyle='dashed', linewidth=1)
ax.legend((mean, median, ninety, ten), ('mean','median','90%','10%'))
#save subset
df_subset.to_csv('data/imdb_subset_100_10strats')
df_subset
```
| github_jupyter |
# Visualisation
```
%matplotlib inline
from IPython.display import IFrame
import numpy as np
from geopandas import read_file
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
```
### Data
```
db = pd.DataFrame(read_file('../data/bh.gpkg').drop('geometry', axis=1))
db.info()
db.head()
```
### Simple and quick
```
db['Average Monthly Wage'].plot.hist(alpha=0.5, color='red')
```
To note:
- Grammar is `.plot.hist`
- End line with `;` to avoid matplotlib print
```
db['Average Monthly Wage'].plot.kde();
# Subset to municipalities (by jobs)
largest = db.set_index('NM_MUNICIP')\
['Total Jobs']\
.sort_values()\
.tail()
largest
largest.plot.bar(color='orange');
```
To note:
* Pull out column and sort its values
* Pipe into bar chart
---
**CHALLENGE**
Create a bar plot for the five most productive municipalities (as expressed by average wage
---
```
db.plot.scatter('Total Jobs', 'Average Monthly Wage')
```
To note:
* Peak into correlation
* Runs into problems if too many dots
---
**CHALLENGE**
* Explore the distribution of jobs and establishments
* Consider the relationship between industry diversity and average wages
---
### A bit more sophisticated
`seaborn` to the rescue!
```
sns.distplot(db['Average Monthly Wage'], kde=True, rug=True);
```
To note:
* Histogram + KDE + rugs (each of them optional!)
Try and play around with different arguments! (Tip: check the [official documentation](https://seaborn.pydata.org/generated/seaborn.distplot.html)).
```
sns.relplot(x='Total Jobs', y='Average Monthly Wage', data=db);
sns.jointplot(x='Total Jobs', y='Average Monthly Wage',
data=db, kind='hex');
sns.relplot(x='l_jobs', y='l_wage',
data=db.assign(l_jobs=np.log(db['Total Jobs']))\
.assign(l_wage=np.log(db['Average Monthly Wage'])));
sns.regplot(x='l_jobs', y='l_wage',
data=db.assign(l_jobs=np.log(db['Total Jobs']))\
.assign(l_wage=np.log(db['Average Monthly Wage'])));
```
---
**CHALLENGE**
Explore the other options of `jointplot` in the [documentation](https://seaborn.pydata.org/generated/seaborn.jointplot.html) and try to use the function to create KDE surface.
---
### Categorical visualizations
* Get quantiles of the size
```
qtl = pd.qcut(db['Total Jobs'], 5,
labels=['XS', 'S', 'M', 'L', 'XL'])
qtl.head()
```
---
```
sns.stripplot(x='Size', y='Average Monthly Wage',
data=db.assign(Size=qtl));
```
**CHALLENGE** - Try to get a similar plot for industry diversity.
```
sns.stripplot(x='Size', y='Average Monthly Wage',
data=db.assign(Size=qtl),
alpha=0.25);
sns.swarmplot(x='Size', y='Average Monthly Wage',
data=db.assign(Size=qtl));
```
To note:
* With larger datasets, it's hard to see any pattern
* This is true even if you jitter the points around to avoid overlap and/or you play with transparency (`alpha`)
* Algorithms to separate out dots exist but they're computationally intensive and can only do so much
### Visualisation *"a-la carte"*
#### One
```
f, ax = plt.subplots(1)
ax.scatter(np.log(db['Total Jobs']),
np.log(db['Average Monthly Wage']))
plt.show()
f, ax = plt.subplots(1)
sns.kdeplot(np.log(db['Total Jobs']),
np.log(db['Average Monthly Wage']),
shade=True, ax=ax)
ax.scatter(np.log(db['Total Jobs']),
np.log(db['Average Monthly Wage']),
c='orange', s=2)
plt.show()
f, ax = plt.subplots(1, figsize=(12, 12))
sns.kdeplot(np.log(db['Total Jobs']),
np.log(db['Average Monthly Wage']),
shade=True, ax=ax)
ax.set_axis_off()
plt.show()
f, ax = plt.subplots(1, figsize=(6, 6))
ax.hexbin(np.log(db['Total Jobs']),
np.log(db['Average Monthly Wage']),
gridsize=10, alpha=0.75)
ax.scatter(np.log(db['Total Jobs']),
np.log(db['Average Monthly Wage']),
c='orange', s=2)
#plt.savefig('myfig.jpg', dpi=900)
plt.show()
```
#### Two or more
```
f, axs = plt.subplots(1, 2, figsize=(12, 6))
sns.distplot(db['Total Jobs'], kde=False, rug=True, ax=axs[0])
sns.distplot(db['Total Establishments'],
hist=False, kde=True, rug=True, ax=axs[1])
plt.tight_layout()
plt.show()
```
**CHALLENGE** - Create a visualisation with three subplots:
1. Histogram of Total Jobs
1. Scatter plot of Total Jobs Vs Average Monthly Wage
1. Histogram of Average Monthly Wage
---
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Geographic Data Science with Python - UFMG'19</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://github.com/darribas/gds_ufmg19" property="cc:attributionName" rel="cc:attributionURL">Dani Arribas-Bel</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>.
| github_jupyter |
##### Copyright 2019 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
```
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
```
# Multilingual Universal Sentence Encoder Q&A Retrieval
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/hub/tutorials/retrieval_with_tf_hub_universal_encoder_qa"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/retrieval_with_tf_hub_universal_encoder_qa.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/hub/blob/master/examples/colab/retrieval_with_tf_hub_universal_encoder_qa.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/hub/examples/colab/retrieval_with_tf_hub_universal_encoder_qa.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
This is a demo for using [Univeral Encoder Multilingual Q&A model](https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/3) for question-answer retrieval of text, illustrating the use of **question_encoder** and **response_encoder** of the model. We use sentences from [SQuAD](https://rajpurkar.github.io/SQuAD-explorer/) paragraphs as the demo dataset, each sentence and its context (the text surrounding the sentence) is encoded into high dimension embeddings with the **response_encoder**. These embeddings are stored in an index built using the [simpleneighbors](https://pypi.org/project/simpleneighbors/) library for question-answer retrieval.
On retrieval a random question is selected from the [SQuAD](https://rajpurkar.github.io/SQuAD-explorer/) dataset and encoded into high dimension embedding with the **question_encoder** and query the simpleneighbors index returning a list of approximate nearest neighbors in semantic space.
### More models
You can find all currently hosted text embedding models [here](https://tfhub.dev/s?module-type=text-embedding) and all models that have been trained on SQuAD as well [here](https://tfhub.dev/s?dataset=squad).
## Setup
```
%%capture
#@title Setup Environment
# Install the latest Tensorflow version.
!pip install -q tensorflow_text
!pip install -q simpleneighbors[annoy]
!pip install -q nltk
!pip install -q tqdm
#@title Setup common imports and functions
import json
import nltk
import os
import pprint
import random
import simpleneighbors
import urllib
from IPython.display import HTML, display
from tqdm.notebook import tqdm
import tensorflow.compat.v2 as tf
import tensorflow_hub as hub
from tensorflow_text import SentencepieceTokenizer
nltk.download('punkt')
def download_squad(url):
return json.load(urllib.request.urlopen(url))
def extract_sentences_from_squad_json(squad):
all_sentences = []
for data in squad['data']:
for paragraph in data['paragraphs']:
sentences = nltk.tokenize.sent_tokenize(paragraph['context'])
all_sentences.extend(zip(sentences, [paragraph['context']] * len(sentences)))
return list(set(all_sentences)) # remove duplicates
def extract_questions_from_squad_json(squad):
questions = []
for data in squad['data']:
for paragraph in data['paragraphs']:
for qas in paragraph['qas']:
if qas['answers']:
questions.append((qas['question'], qas['answers'][0]['text']))
return list(set(questions))
def output_with_highlight(text, highlight):
output = "<li> "
i = text.find(highlight)
while True:
if i == -1:
output += text
break
output += text[0:i]
output += '<b>'+text[i:i+len(highlight)]+'</b>'
text = text[i+len(highlight):]
i = text.find(highlight)
return output + "</li>\n"
def display_nearest_neighbors(query_text, answer_text=None):
query_embedding = model.signatures['question_encoder'](tf.constant([query_text]))['outputs'][0]
search_results = index.nearest(query_embedding, n=num_results)
if answer_text:
result_md = '''
<p>Random Question from SQuAD:</p>
<p> <b>%s</b></p>
<p>Answer:</p>
<p> <b>%s</b></p>
''' % (query_text , answer_text)
else:
result_md = '''
<p>Question:</p>
<p> <b>%s</b></p>
''' % query_text
result_md += '''
<p>Retrieved sentences :
<ol>
'''
if answer_text:
for s in search_results:
result_md += output_with_highlight(s, answer_text)
else:
for s in search_results:
result_md += '<li>' + s + '</li>\n'
result_md += "</ol>"
display(HTML(result_md))
```
Run the following code block to download and extract the SQuAD dataset into:
* **sentences** is a list of (text, context) tuples - each paragraph from the SQuAD dataset are splitted into sentences using nltk library and the sentence and paragraph text forms the (text, context) tuple.
* **questions** is a list of (question, answer) tuples.
Note: You can use this demo to index the SQuAD train dataset or the smaller dev dataset (1.1 or 2.0) by selecting the **squad_url** below.
```
#@title Download and extract SQuAD data
squad_url = 'https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json' #@param ["https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v2.0.json", "https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v2.0.json", "https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v1.1.json", "https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json"]
squad_json = download_squad(squad_url)
sentences = extract_sentences_from_squad_json(squad_json)
questions = extract_questions_from_squad_json(squad_json)
print("%s sentences, %s questions extracted from SQuAD %s" % (len(sentences), len(questions), squad_url))
print("\nExample sentence and context:\n")
sentence = random.choice(sentences)
print("sentence:\n")
pprint.pprint(sentence[0])
print("\ncontext:\n")
pprint.pprint(sentence[1])
print()
```
The following code block setup the tensorflow graph **g** and **session** with the [Univeral Encoder Multilingual Q&A model](https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/3)'s **question_encoder** and **response_encoder** signatures.
```
#@title Load model from tensorflow hub
module_url = "https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/3" #@param ["https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/3", "https://tfhub.dev/google/universal-sentence-encoder-qa/3"]
model = hub.load(module_url)
```
The following code block compute the embeddings for all the text, context tuples and store them in a [simpleneighbors](https://pypi.org/project/simpleneighbors/) index using the **response_encoder**.
```
#@title Compute embeddings and build simpleneighbors index
batch_size = 100
encodings = model.signatures['response_encoder'](
input=tf.constant([sentences[0][0]]),
context=tf.constant([sentences[0][1]]))
index = simpleneighbors.SimpleNeighbors(
len(encodings['outputs'][0]), metric='angular')
print('Computing embeddings for %s sentences' % len(sentences))
slices = zip(*(iter(sentences),) * batch_size)
num_batches = int(len(sentences) / batch_size)
for s in tqdm(slices, total=num_batches):
response_batch = list([r for r, c in s])
context_batch = list([c for r, c in s])
encodings = model.signatures['response_encoder'](
input=tf.constant(response_batch),
context=tf.constant(context_batch)
)
for batch_index, batch in enumerate(response_batch):
index.add_one(batch, encodings['outputs'][batch_index])
index.build()
print('simpleneighbors index for %s sentences built.' % len(sentences))
```
On retrieval, the question is encoded using the **question_encoder** and the question embedding is used to query the simpleneighbors index.
```
#@title Retrieve nearest neighbors for a random question from SQuAD
num_results = 25 #@param {type:"slider", min:5, max:40, step:1}
query = random.choice(questions)
display_nearest_neighbors(query[0], query[1])
```
| github_jupyter |
```
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all' # default is ‘last_expr'
%load_ext autoreload
%autoreload 2
import sys
sys.path.append('/home/mink/notebooks/CameraTraps') # append this repo to PYTHONPATH
import json
import os
from collections import Counter, defaultdict
from random import sample
import math
from copy import deepcopy
from shutil import copyfile
from multiprocessing.pool import ThreadPool
from tqdm import tqdm
from unidecode import unidecode
from data_management.megadb.schema import sequences_schema_check
from data_management.megadb.converters.cct_to_megadb import make_cct_embedded, process_sequences, write_json
```
# saola_private
```
dataset_name = 'saola_private'
container_root = '/mink_disk_0/camtraps/swg-camera-traps-private/'
path_prefix = 'private'
path_to_output = f'/home/mink/camtraps/data/megadb_jsons/{dataset_name}.json'
path_to_output_temp = f'/home/mink/camtraps/data/megadb_jsons/{dataset_name}_temp.json'
```
## Step 0 - Add an entry to the `datasets` table
Done
## Step 1 - Prepare the `sequence` objects to insert into the database
### Step 1a - If you have metadata in COCO Camera Traps (CCT) format already...
```
# path to the CCT json, or a loaded json object
path_to_image_cct = '/mink_disk_0/camtraps/megadetectorv5_annotation_prep/swg_camera_traps.json' # set to None if not available
path_to_bbox_cct = None
assert not (path_to_image_cct is None and path_to_bbox_cct is None)
%%time
embedded = make_cct_embedded(image_db=path_to_image_cct, bbox_db=path_to_bbox_cct)
```
In the following step, properties will be moved to the highest level that is still correct, i.e. if a property at the image-level always has the smae value for all images in a sequence, it will be moved to be a sequence-level property.
If a sequence-level property has the same value throughout this dataset (often 'rights holder'), it will be removed from the `sequence` objects. A message about this will be printed, and you should add that property and its (constant) value to this dataset's entry in the `datasets` table.
```
%%time
sequences = process_sequences(embedded, dataset_name)
private_sequences = [] # actually public/private was decided at the image level
for seq in sequences:
private_images = [im for im in seq['images'] if im['file'].startswith('private/')]
if len(private_images) > 0:
for im in private_images:
im['file'] = im['file'].split('private/')[1]
seq['images'] = private_images
private_sequences.append(seq)
len(private_sequences)
locations = set()
for seq in private_sequences:
locations.add(seq['location'])
len(locations)
sample(private_sequences, 2)
```
## Step 2 - Pass the schema check
```
%%time
sequences_schema_check.sequences_schema_check(private_sequences)
with open(path_to_output_temp, 'w', encoding='utf-8') as f:
json.dump(private_sequences, f, ensure_ascii=False)
```
### Step 2b - Sample
```
private_sequences_good = []
locations_good = set()
for seq in private_sequences:
include = True
for im in seq['images']:
if im['class'][0] in ['ignore', 'empty', 'problem', 'blurred']:
include = False
if include:
private_sequences_good.append(seq)
locations_good.add(seq['location'])
len(private_sequences_good)
len(locations_good)
sample(private_sequences_good, 1)
sequences_short = []
locations_sampled = set()
for seq in private_sequences_good:
seq['images'] = seq['images'][:3]
sequences_short.append(seq)
locations_sampled.add(seq['location'])
num_images = sum([len(seq['images']) for seq in sequences_short])
num_images
len(locations_sampled)
```
### Step 2c - Download the sampled images
```
list_to_download = []
for seq in sequences_short:
for im in seq['images']:
list_to_download.append('private/' + im['file'] + '\n')
len(list_to_download)
list_to_download[-10]
with open('/mink_disk_0/camtraps/megadetectorv5_annotation_prep/batch_12_lists/saola_private_files.txt', 'w') as f:
f.writelines(list_to_download)
```
### Step 2d - Copy to flat folder
```
path_pairs = []
for seq in tqdm(sequences_short):
seq_id = seq['seq_id']
for im in seq['images']:
frame = im['frame_num']
src_path = os.path.join(container_root, path_prefix, im['file'])
dst_path = os.path.join('/mink_disk_0/camtraps/imerit12g',
f'{dataset_name}.seq{seq_id}.frame{frame}.jpg')
path_pairs.append((src_path, dst_path))
len(path_pairs)
sample(path_pairs, 2)
%%time
def copy_file(src_path, dst_path):
if not os.path.exists(dst_path):
return copyfile(src_path, dst_path)
else:
return None
with ThreadPool(12) as pool:
dst_paths = pool.starmap(copy_file, path_pairs)
```
| github_jupyter |
# Report and plots `fig:threshold__tradeoff__fine-tune`
```
import os
import tqdm
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import warnings
warnings.simplefilter("ignore")
```
For this experiment we take the specified bunch of experiments,
and using run fine-tune stages for varying thresholds.
```
from cplxpaper.auto.utils import load_manifest
from cplxpaper.auto.utils import get_stage_snapshot
from cplxpaper.auto.parameter_grid import get_params, set_params
def prepare_manifest(base):
"""Prepare the manifest for testing effects of threshold on `fine-tune`."""
config = load_manifest(base)
# clear device and threshold
config.update({
"__name__": "Impact of the treshold on fine-tune on MusicNet",
"device": None,
"threshold": None,
})
# remove `dense` stage completely
del config["stages"]["dense"]
# cold start `sparsify` from the base experiment, disable training
config["stages"]["sparsify"].update({
# cold restart
"snapshot": get_stage_snapshot("sparsify", base),
# skip training
"n_epochs": 0,
})
# ensure `fine-tune` restarts the optim, but inherits the weights
config["stages"]["fine-tune"].update({
"reset": False,
"restart": True,
"snapshot": None,
})
# manually reset stage order
config["stage-order"] = ["sparsify", "fine-tune"]# list(config["stages"].keys())
return config
```
This generator exists in many places, and should eventually be imported form a single place:
* cplxpaper.auto.reports.\_\_main\_\_
* cplxpaper.auto.reports.utils
```
from cplxpaper.auto.utils import verify_experiment
def enumerate_experiments(manifests):
"""Return the experiment associated with each manifest."""
for manifest, ext in map(os.path.splitext, manifests):
path, name = os.path.split(manifest)
if ext != ".json" or name.startswith("."):
continue
experiment = os.path.join(path, name)
if not verify_experiment(experiment):
continue
yield experiment
```
<br>
## Prepare the report
```
PREFIX, dry_run = "addendum__", False
report = "./grids/musicnet__threshold__fine-tune.pk"
experiments = [
# 1/200
'./grids/grid-fast/musicnet-fast__00/musicnet[003]-097.json', # ARD
'./grids/grid-fast/musicnet-fast__01/musicnet[001]-045.json',
'./grids/grid-fast/musicnet-fast__02/musicnet[004]-123.json',
'./grids/grid-fast/musicnet-fast__03/musicnet[002]-071.json',
'./grids/grid-fast/musicnet-fast__04/musicnet[000]-019.json',
'./grids/grid-fast/musicnet-fast__00/musicnet[003]-084.json', # VD
'./grids/grid-fast/musicnet-fast__01/musicnet[001]-032.json',
'./grids/grid-fast/musicnet-fast__02/musicnet[004]-110.json',
'./grids/grid-fast/musicnet-fast__03/musicnet[002]-058.json',
'./grids/grid-fast/musicnet-fast__04/musicnet[000]-006.json',
# 1/20
'./grids/grid-fast/musicnet-fast__00/musicnet[003]-101.json', # ARD
'./grids/grid-fast/musicnet-fast__01/musicnet[001]-049.json',
'./grids/grid-fast/musicnet-fast__02/musicnet[004]-127.json',
'./grids/grid-fast/musicnet-fast__03/musicnet[002]-075.json',
'./grids/grid-fast/musicnet-fast__04/musicnet[000]-023.json',
'./grids/grid-fast/musicnet-fast__00/musicnet[003]-088.json', # VD
'./grids/grid-fast/musicnet-fast__01/musicnet[001]-036.json',
'./grids/grid-fast/musicnet-fast__02/musicnet[004]-114.json',
'./grids/grid-fast/musicnet-fast__03/musicnet[002]-062.json',
'./grids/grid-fast/musicnet-fast__04/musicnet[000]-010.json',
]
```
<br>
```
assert False, '''Run cells below to create a grid for this experiment.'''
```
<br>
Enumerate the base experiments, the final sparsity of which to test.
```
report = os.path.normpath(os.path.abspath(report))
folder = os.path.abspath(os.path.join(
".", "grids", "musicnet__threshold__fine-tune"
))
bash = f"{folder}.sh"
os.makedirs(folder, exist_ok=False)
```
For each base experiment we create a small grid of varying thresholds:
* we take $\tau$ from ~the same array as the `kind = "threshold"` report~ a coarser array
* $\{\pm\tfrac{k}4\colon k=0..24\}$ is too fine and too wide
- 980 experiments ~ 20 days 4x2
* but eventually use `kind = "trade-off"` report builder
```
# taus = [i / 4 for i in range(-24, 24 + 1)]
taus = [i / 2 for i in range(-8, 8 + 1)]
```
Create a pseudo-grid: cold start from a snapshot, drop irrelevant
parameters, and then `fine-tune`
```
import json
import copy
from cplxpaper.auto.parameter_grid import set_params
for experiment in enumerate_experiments(map(os.path.abspath, experiments)):
name = os.path.basename(experiment)
config = prepare_manifest(experiment)
for i, tau in enumerate(taus):
local = set_params(copy.deepcopy(config), **{
"threshold": tau
})
manifest = os.path.join(folder, f"{name}__tau{i:02d}.json")
if not dry_run:
json.dump(local, open(manifest, "w"), indent=2)
```
Pick a name for the report pickle and compile a **bash** script for
building the threshold figure for each of epxeriment in the list above.
```
import stat
devspec = """--devices "cuda:0" "cuda:1" "cuda:2" "cuda:3" --per-device 2"""
with open(bash, "w") as fout:
# experiment execution
fout.write(f"""python -m cplxpaper.auto {devspec} "{folder}"\n""")
fout.write("\n")
# report analysis
fout.write(f"""python -m cplxpaper.auto.reports {devspec} "trade-off" "{report}" "{folder}"\n""")
# allow exc and keep r/w
os.chmod(bash, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR)
bash
```
<br>
```
assert False, '''Run all below to make the figure.'''
```
<br>
## Build the table
Load the report constructed on the selected experiments.
```
from cplxpaper.auto.reports.utils import restore
from cplxpaper.auto.parameter_grid import reconstruct_grid
def build_report(filename):
report = tqdm.tqdm(restore(filename), desc="analyzing report data")
workers, results = zip(*report)
if not results:
return {}, []
# compute the grid and flatten the manifests
experiments, options, *results = zip(*results)
full_grid, flat_options = reconstruct_grid(options)
return full_grid, [*zip(experiments, flat_options, *results)]
```
Extract the score from the scorers' output.
```
from cplxpaper.auto.reports.utils import dict_get_one
def get_score(score):
# something is horribly wrong if this fails...
assert score["pre-fine-tune"]["sparsity"] == score["post-fine-tune"]["sparsity"]
metrics = {k: dict_get_one(v, "pooled_average_precision", "accuracy")
for k, v in score.items()}
n_zer, n_par = map(sum, zip(*score["pre-fine-tune"]["sparsity"].values()))
return {
**metrics,
"compression": n_par / (n_par - n_zer)
}
```
Evaluate several grids and join them
```
raw_grid, output = build_report(report)
```
Alter the recovered grid
```
grid = set(field for field in raw_grid
if not any(map(field.__contains__, {
# service fields
"__name__", "__timestamp__", "__version__", "device",
# ignore global model class settings
"model__cls",
# upcast is a service variable, which only complex models have
# and it is usually mirrored in `features` settings.
"__upcast"
})))
grid.update({
"stages__sparsify__model__cls",
"stages__sparsify__objective__kl_div",
"threshold" # ensure threshold is included
})
```
Index by the experiment **grid--folder** and prepare fields
```
experiments, options, *rest = zip(*output)
# experiment paths are absolute!
df = pd.DataFrame(experiments, columns=["experiment",])
df = df["experiment"].str.replace(os.path.commonpath(experiments), "*")\
.str.extract("^(?P<grid>.*)/(?P<experiment>[^/]*)$", expand=True)
master_index = df.set_index(["grid", "experiment"]).index
```
Gradually construct the table of options
```
parameters = pd.DataFrame(index=master_index)
```
Assign proper tags to models
```
from cplxpaper.auto.reports.utils import get_model_tag
def patched_get_model_tag(opt):
tag = get_model_tag(opt)
# Legacy model patch: if not specified then True (see `musicnet.models.base`)
cls = tag["model"]
if "DeepConvNet" in cls and opt.get("model__legacy", True):
cls += " k3"
return {**tag, "model": cls}
grid = [k for k in grid if not k.startswith((
"model__",
"stages__sparsify__model__"
))]
parameters = parameters.join(pd.DataFrame([
*map(patched_get_model_tag, options)
], index=master_index))
```
Other fields' preprocessing.
```
assert 'dataset' not in grid
assert 'features' not in grid
```
Only the essential experiment parameters should have remained by now.
```
parameters = parameters.join(pd.DataFrame([
{g: opt[g] for g in grid} for opt in options
], index=master_index))
grid
```
Now collect the metrics. We need:
* **accuracy** performance on `dense`, `pre-fine-tune` and `post-fine-tune`
* **compression rate** from a `fine-tune` stage
```
scores, *tail = rest
assert not tail
metrics = pd.DataFrame([
get_score(dict_get_one(score, "test", "test-256")) for score in scores
], index=master_index)
```
Join the tables and rename unfotunate columns.
```
df_main = parameters.join(metrics).rename(columns={
"stages__sparsify__objective__kl_div": "kl_div",
"stages__sparsify__snapshot": "snapshot"
})
df_main["snapshot"] = df_main["snapshot"].str.replace(os.path.commonpath(df_main["snapshot"].to_list()), "*")
df_main = df_main.set_index(["snapshot", "threshold"])
```
<br>
## Create the threshold plot
Decide on the target folder and computation cache.
```
report_name = "figure__musicnet__threshold__fine-tune"
report_target = os.path.normpath(os.path.abspath(os.path.join(
"../../assets", report_name
)))
```
A service plotting function to darkern the specified colour
```
from matplotlib.ticker import FormatStrFormatter, FuncFormatter
def darker(color, a=0.5):
"""Adapted from this stackoverflow question_.
.. _question: https://stackoverflow.com/questions/37765197/
"""
from matplotlib.colors import to_rgb
from colorsys import rgb_to_hls, hls_to_rgb
h, l, s = rgb_to_hls(*to_rgb(color))
return hls_to_rgb(h, max(0, min(a * l, 1)), s)
```
Group by all fileds except for `threshold`:
* `model`, `kind`, `method`, `dataset`, `features` and `kl_div`
```
print([f for f in parameters.columns if "kl_div" not in f])
fields = [
'method',
'model',
'kind',
'kl_div'
]
```
Handle colours
```
def kind_model_method_color(kind, model, method, kl_div):
return { # VD/ARD
# tab10 colours are paired! use this to keep similar models distinguishable
("C" , "DeepConvNet", "VD", 1/200): "C0",
("C" , "DeepConvNet", "ARD", 1/200): "C1",
("C" , "DeepConvNet", "VD", 1/20): "C2",
("C" , "DeepConvNet", "ARD", 1/20): "C3",
("C" , "DeepConvNet", "VD", 1/2000): "C4",
("C" , "DeepConvNet", "ARD", 1/2000): "C5",
}[kind, model, method, kl_div]
```
Threshold-compression map $\tau \mapsto c(\tau)$ is a monotonic decreasing,
hence can be inverted and used to parameterize the performance curve.
So we plot below
$$
(c(\tau), p(\tau))_{\tau \in T}
= (x, p\circ c^{-1}(x))_{x \in c(T)}
\,, $$
```
def make_plot(ax, df):
ax.set_xscale('log')
ax.set_xlim(41, 2000)
ax.set_ylim(0.55, 0.75)
ax.axvspan(50, 500, color="k", alpha=0.05, zorder=-10)
ax.set_ylabel('average precision')
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, p: f'$\\times${int(x):d}'))
# group by tau and experiment spec and plot
grouper, legend = df.groupby(fields), []
for key, df in grouper:
df = df[["post-fine-tune", "pre-fine-tune", "compression"]].sort_index()
label = dict(zip(fields, key))
# harmonic mean for comression
compression = 1. / (1. / df['compression']).mean(level=-1)
m, min_, max_ = df.mean(level=-1), df.min(level=-1), df.max(level=-1)
for field, marker in zip(['pre-fine-tune', 'post-fine-tune'], ['o', '*']):
perf = m[field]
line, = ax.plot(compression, perf, alpha=1.0, zorder=20,
marker=marker, lw=2, markersize=4,
markeredgecolor='k', markeredgewidth=0.5)
tau = ax.scatter(compression[[-0.5]], perf[[-0.5]], s=20, zorder=30, lw=2,
marker='s', c=['k'])
ax.fill_between(compression, min_[field], max_[field], lw=0,
color=darker(line.get_color(), 1.4), alpha=0.25, zorder=20)
legend.append((line, "{field} ($C\!\!=\!\!{kl_div}$)".format(field=field, **label)))
# breakpoint()
for i, t in enumerate(compression.index):
if t not in (-3., +3.):
continue
p = max(m.loc[t, 'pre-fine-tune'], m.loc[t, 'post-fine-tune'])
ax.annotate(fr'$\tau\!\!=\!\!\!{t:+.0f}$', (compression[t], p), size='small',
xytext=(-5, 5), zorder=20, textcoords='offset points')
z, a = m['post-fine-tune'], m['pre-fine-tune']
ax.quiver(compression, a, compression * 0, z - a,
angles='xy', scale_units='xy', scale=1.,
width=0.005, alpha=0.125)
ax.axhline(0.729, color="k", alpha=0.125, zorder=-10, lw=2)
ax.annotate("Trabelsi et al. (2018)", xy=(300, 0.729), xycoords='data',
xytext=(300, 0.73), textcoords='data', alpha=0.75)
legend.append((tau, r'$\tau\!\!=\!\!-\frac{1}{2}$'))
handles, labels = zip(*legend)
ax.legend(handles, labels, ncol=1, fontsize='small')
ax.grid(axis='y', alpha=0.15)
```
Decide on the target folder and computation cache.
```
report_name = "figure__musicnet__threshold__{kind}__{model}.pdf"
report_target = os.path.normpath(os.path.abspath(os.path.join(
"../../assets", report_name
)))
for (kind, model), df in df_main.groupby(['kind', 'model']):
# fig, axes = plt.subplots(1, 2, figsize=(8, 3), dpi=300, sharey=True)
fig, axes = plt.subplots(2, 1, figsize=(6, 6), dpi=300, sharex=True)
for ax, (method, df_method) in zip(axes, df.groupby(['method'])):
# ax.set_title(f"Threshold effect on performance of {kind}-{method} for {model} (MusicNet)")
ax.set_title(f"{kind}-{method} for {model} (MusicNet)")
make_plot(ax, df_method)
plt.xlabel('compression')
plt.tight_layout()
fig.savefig(report_target.format(**locals()), dpi=300)
# plt.show()
plt.close()
assert False
```
<br>
Older plot
```
report_name = "figure__musicnet__threshold.pdf"
report_target = os.path.normpath(os.path.abspath(os.path.join(
"../../assets", report_name
)))
```
Make a crude plot
```
fig, (ax_l, ax_r) = plt.subplots(2, 1, figsize=(8, 5), dpi=300, sharex=True)
fig.patch.set_alpha(1.0)
# ax_r = ax_l.twinx()
ax_l.set_title("The effect of $\\tau$ on performance and compression (MusicNet)")
# set up limits and axis labels
ax_l.set_ylabel("Average Precision")
ax_r.set_ylabel("$\\times$ compression")
ax_r.set_yscale("log")
ax_r.set_xlabel("Threshold $\\tau$")
ax_l.set_xlim(-3.6125, 3.6125)
ax_l.set_ylim(0.55, 0.75)
ax_r.set_ylim(40, 2000)
# Trabelsi et al. (2018)
ax_l.axhline(0.729, color="k", alpha=0.25, zorder=-10, lw=1)
ax_l.annotate("Trabelsi et al. (2018)", xy=(0, 0.75), xycoords='data',
xytext=(0.05, 0.935), textcoords='axes fraction', alpha=0.75)
# group by tau and experiment spec and plot
grouper = df_main.groupby(fields)
for key, df in tqdm.tqdm(grouper, desc="populating plots"):
df = df[["post-fine-tune", "pre-fine-tune", "compression"]].sort_index()
label = dict(zip(fields, key))
m, min_, max_ = df.mean(level=-1), df.min(level=-1), df.max(level=-1)
color = kind_model_method_color(**label)
for ax, field, marker in zip([ax_l, ax_r], ["post-fine-tune", "compression"], ["", "o"]):
ax.fill_between(m.index, min_[field], max_[field],
color=darker(color, 1.4), alpha=0.25, zorder=20)
ax.plot(m[field], c=color, alpha=1.0, marker=marker, markersize=4,
label="{kind} {model} {method} ($C={kl_div}$)".format(**label),
zorder=25)
ax_l.fill_between(m.index, min_["pre-fine-tune"], max_["pre-fine-tune"],
color=darker(color, 1.4), alpha=0.25, zorder=10)
ax_l.plot(m["pre-fine-tune"], c=color, alpha=1.0, marker="x", markersize=4,
# label="{kind} {model} {method} ($C={kl_div}$)".format(**label),
zorder=15)
ax_l.legend(ncol=1, loc=(0.55, .05)) # loc="center right")
ax_l.axvline(-0.5, c="k", lw=2, zorder=2)
ax_r.axvline(-0.5, c="k", lw=2, zorder=2)
# ax_r.grid(axis='y', which='both')
# ax_l.grid(axis='y', which='both')
plt.tight_layout(h_pad=-0.55)
fig.savefig(report_target, dpi=300)
# plt.show()
plt.close()
```
<br>
| github_jupyter |
# Whitening versus standardizing
```
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
```
First, just read in data, and take a peek. The data can be found on [GitHub](https://github.com/ppham27/MLaPP-solutions/blob/master/chap04/heightWeightData.txt).
```
raw_data = pd.read_csv("heightWeightData.txt", header=None, names=["gender", "height", "weight"])
raw_data.info()
raw_data.head()
```
We're told that for gender, 1 is male, and 2 is female. Part (a) says to extract the height/weight data corresponding to the males. Then, we fit a 2d Gaussian to the male data, using the empirical mean and covariance. Then, we'll plot this data.
Let's extract the males first.
```
male_data = raw_data[raw_data.gender == 1]
male_data.head()
```
Next, we'll calculate the empirical mean and covariance.
```
mu_male = male_data.mean(axis=0)[1:].as_matrix() # remove gender
male_mean_diff = male_data.iloc[:,1:].as_matrix() - mu_male
covariance_male = np.dot(male_mean_diff.T, male_mean_diff)/len(male_data)
print(mu_male)
print(covariance_male)
```
Let's plot the data now.
```
plt.figure(figsize=(6,6))
plt.plot(male_data.height, male_data.weight, 'ko')
plt.axis([60,80,120,285])
plt.title('raw')
plt.xlabel('height')
plt.ylabel('weight')
plt.axes().set_aspect(0.2)
plt.grid(True)
plt.show()
```
Let $\mathbf{x} \sim \mathcal{N}\left(\boldsymbol\mu, \Sigma\right)$, where $\mathbf{x} \in \mathbb{R}^p$. We can write $\Sigma = SDS^\intercal$ by the spectral theorem, where the columns of $S$ are orthonormal eigenvectors, and $D$ is a diagonal matrix of eigenvectors, $\lambda_1, \lambda_2,\ldots,\lambda_n$.
$\mathbf{x}$ has probability mass function,
\begin{equation}
f(\mathbf{x}) = \frac{1}{(2\pi)^{p/2}\sqrt{\det{\Sigma}}}\exp\left(-\frac{1}{2}\left(\mathbf{x}-\boldsymbol\mu\right)^\intercal\Sigma^{-1}\left(\mathbf{x}-\boldsymbol\mu\right)\right).
\end{equation}
Note that $S^\intercal S = I$, and $S^{-1} = S^\intercal$. This implies that
\begin{equation}
\Sigma^{-1} = \left(SDS^\intercal\right)^{-1} = \left(S^\intercal\right)^{-1}D^{-1}S^{-1} = SD^{-1}S^\intercal.
\end{equation}
Let $\mathbf{y} = S^\intercal\left(\mathbf{x}-\boldsymbol\mu\right)$.
Then, we have that
\begin{align}
\left(\mathbf{x}-\boldsymbol\mu\right)^\intercal\Sigma^{-1}\left(\mathbf{x}-\boldsymbol\mu\right)
&= \left(\mathbf{x}-\boldsymbol\mu\right)^\intercal S D^{-1} S^\intercal\left(\mathbf{x}-\boldsymbol\mu\right) \\
&= \left(S^\intercal\left(\mathbf{x}-\boldsymbol\mu\right)\right)^\intercal D^{-1} S^\intercal\left(\mathbf{x}-\boldsymbol\mu\right) \\
&= \mathbf{y}^\intercal D^{-1} \mathbf{y}.
\end{align}
Moreover, $\mathbf{x} = S\mathbf{y} + \boldsymbol\mu$, so $D\mathbf{x}(\mathbf{y}) = S$, and so $\det D\mathbf{x}(\mathbf{y}) = 1$. Changing variables, the probability density function for $\mathbf{y}$ is
\begin{equation}
f(\mathbf{y}) = \frac{1}{(2\pi)^{p/2}\sqrt{\det D}}\exp\left(-\frac{1}{2}\mathbf{y}^\intercal D^{-1} \mathbf{y}\right)
= \frac{1}{(2\pi)^{p/2}\sqrt{\prod_{j=1}^p\lambda_j}}\exp\left(-\frac{1}{2}\sum_{j=1}^p \frac{y_j^2}{\lambda_j}\right) = \prod_{j=1}^p\frac{1}{\sqrt{2\pi\lambda_j}}\exp\left(-\frac{1}{2}\frac{y_j^2}{\lambda_j}\right).
\end{equation}
Thus, $\mathbf{y} \sim \mathcal{N}\left(\mathbf{0}, D\right)$, and the coordinates of $\mathbf{y}$ are independent, with $y_i \mathcal{N}\left(0, \lambda_j\right)$. Now, the level curves of $f$ correspond to the hyperellipsoids
\begin{equation}
\sum_{j=1}^p \frac{y_j^2}{\lambda_j} = \sum_{j=1}^p \left(\frac{y_j}{\sqrt{\lambda_j}}\right)^2 = c.
\end{equation}
$\frac{y_j}{\sqrt{\lambda_j}} \sim \mathcal{N}(0, 1)$, so $\sum_{j=1}^p \frac{y_j^2}{\lambda_j} \sim \chi^2_p$, and so a $95\%$ confidence region would be
\begin{equation}
\sum_{j=1}^p \frac{y_j^2}{\lambda_j} \leq F_{\chi^2_p}^{-1}(0.95),
\end{equation}
where $F$ is the cumulative distribution function. For our $p = 2$ case, $F_{\chi^2_p}^{-1}(0.95) \approx 5.991.$ Now $\mathbf{y}$ our coordinates with respect to a orthonormal eigenbasis. Since $\mathbf{x} = S\mathbf{y} + \boldsymbol\mu$, the confidence region is a rotated hyperellipsoid centered at $\boldsymbol\mu$ with semi-axes along the eigenvectors of $\Sigma$. Let's plot this hyperellipsoid along with the indexed data.
```
def calculate_2d_gaussian_confidence_region(mu, Sigma, p = 0.95, points = 200):
"""
Returns a points x 2 numpy.ndarray of the confidence region.
Keyword arguments:
mu -- mean
Sigma -- covariance matrix
p -- percent confidence
points -- number of points to interpolate
"""
assert(len(mu) == len(Sigma))
assert(np.all(Sigma == Sigma.T))
eigenvalues, S = np.linalg.eig(Sigma)
S = S[:,eigenvalues.argsort()[::-1]]
eigenvalues = eigenvalues[eigenvalues.argsort()[::-1]]
theta = np.linspace(0, 2*np.pi, num = points)
x = np.sqrt(eigenvalues[0]*stats.chi2.ppf(p, df=2))*np.cos(theta)
y = np.sqrt(eigenvalues[1]*stats.chi2.ppf(p, df=2))*np.sin(theta)
return np.dot(S, np.array([x,y])).T + mu
def plot_raw_males(ax=None):
if ax == None:
ax = plt.gca()
gaussian_fit_male = calculate_2d_gaussian_confidence_region(mu_male, covariance_male, p = 0.95, points = 100)
ax.axis([60,80,90,285])
ax.set_title('raw')
ax.set_xlabel('height')
ax.set_ylabel('weight')
for row in male_data.itertuples():
ax.text(row.height, row.weight, row.Index, horizontalalignment='center', verticalalignment='center')
ax.set_aspect(0.2)
ax.plot(gaussian_fit_male[:,0], gaussian_fit_male[:,1], linewidth=3, color='red')
ax.plot(mu_male[0], mu_male[1], 'rx', markersize=10, markeredgewidth=3)
ax.grid(True)
plt.figure(figsize=(8,8))
plot_raw_males(plt.gca())
plt.show()
```
For part (b) says to do the same thing with standardized data.
```
def standardize(x, mean, sd):
"""Standardizes assuming x is normally distributed."""
return (x - mean)/sd
def plot_standardized_males(ax=None):
if ax == None:
ax = plt.gca()
gaussian_fit_male = calculate_2d_gaussian_confidence_region(mu_male, covariance_male, p = 0.95, points = 100)
ax.set_title('standardized')
ax.set_xlabel('height')
ax.set_ylabel('weight')
ax.plot(standardize(male_data.height, mu_male[0], np.sqrt(covariance_male[0,0])),
standardize(male_data.weight, mu_male[1], np.sqrt(covariance_male[1,1])),
" ")
for row in male_data.itertuples():
ax.text(standardize(row.height, mu_male[0], np.sqrt(covariance_male[0,0])),
standardize(row.weight, mu_male[1], np.sqrt(covariance_male[1,1])),
row.Index, horizontalalignment='center', verticalalignment='center')
ax.set_aspect('equal')
ax.plot(standardize(gaussian_fit_male[:,0], mu_male[0], np.sqrt(covariance_male[0,0])),
standardize(gaussian_fit_male[:,1], mu_male[1], np.sqrt(covariance_male[1,1])),
linewidth=3, color='red')
ax.plot(0, 0, 'rx', markersize=10, markeredgewidth=3)
ax.grid(True)
plt.figure(figsize=(8,8))
plot_standardized_males()
plt.show()
```
Part (c) deals with *whitening* or *sphereing* the data. This involves transforming the data so that the dimensions are uncorrelated and have equal variances along the axes. Recall that
\begin{equation}
\mathbf{y} = S^\intercal\left(\mathbf{x} - \boldsymbol\mu\right) \sim \mathcal{N}\left(\mathbf{0}, D\right),
\end{equation}
so this transformation accomplishes the tasks of making the dimensions uncorrelated. Now, to make the variances equal simply multiply by $\sqrt{D^{-1}}$, which is easy to compute since $D$ is diagonal and positive definite, so our transformation is
\begin{equation}
\mathbf{y}^\prime = \sqrt{D^{-1}}\mathbf{y} = \sqrt{D^{-1}}S^\intercal\left(\mathbf{x} - \boldsymbol\mu\right)
\sim \mathcal{N}\left(\mathbf{0}, I\right).
\end{equation}
Let's plot this.
```
def whiten(X, mu, Sigma):
assert(len(mu) == len(Sigma))
assert(np.all(Sigma == Sigma.T))
eigenvalues, S = np.linalg.eig(Sigma)
S = S[:,eigenvalues.argsort()[::-1]]
eigenvalues = eigenvalues[eigenvalues.argsort()[::-1]]
inverse_precision = np.diag(1/np.sqrt(eigenvalues))
return np.dot(np.dot(X - mu, S), inverse_precision)
def plot_whitened_males(ax=None):
if ax == None:
ax = plt.gca()
gaussian_fit_male = calculate_2d_gaussian_confidence_region(mu_male, covariance_male, p = 0.95, points = 100)
whitened_gaussian_fit_male = whiten(gaussian_fit_male, mu_male, covariance_male)
ax.set_title('whitened')
ax.set_xlabel('height')
ax.set_ylabel('weight')
whitened_male_data = whiten(np.array([male_data.height, male_data.weight]).T, mu_male, covariance_male)
ax.plot(whitened_male_data[:,0], whitened_male_data[:,1], " ")
for i in range(len(whitened_male_data)):
ax.text(whitened_male_data[i, 0], whitened_male_data[i, 1],
male_data.index[i], horizontalalignment='center', verticalalignment='center')
ax.set_aspect('equal')
ax.plot(whitened_gaussian_fit_male[:,0], whitened_gaussian_fit_male[:,1],
linewidth=3, color='red')
ax.plot(0, 0, 'rx', markersize=10, markeredgewidth=3)
ax.grid(True)
plt.figure(figsize=(8,8))
plot_whitened_males()
plt.show()
```
Now, we can plot all three figures together just like in the textbook.
```
fig = plt.figure(figsize=(20,8))
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)
plot_raw_males(ax1)
plot_standardized_males(ax2)
plot_whitened_males(ax3)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W1D3_ModelFitting/W1D3_Tutorial5.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Tutorial 5: Model Selection: Bias-variance trade-off
**Week 1, Day 3: Model Fitting**
**By Neuromatch Academy**
**Content creators**: Pierre-Étienne Fiquet, Anqi Wu, Alex Hyafil with help from Ella Batty
**Content reviewers**: Lina Teichmann, Patrick Mineault, Michael Waskom
**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
This is Tutorial 5 of a series on fitting models to data. We start with simple linear regression, using least squares optimization (Tutorial 1) and Maximum Likelihood Estimation (Tutorial 2). We will use bootstrapping to build confidence intervals around the inferred linear model parameters (Tutorial 3). We'll finish our exploration of regression models by generalizing to multiple linear regression and polynomial regression (Tutorial 4). We end by learning how to choose between these various models. We discuss the bias-variance trade-off (Tutorial 5) and Cross Validation for model selection (Tutorial 6).
In this tutorial, we will learn about the bias-variance tradeoff and see it in action using polynomial regression models.
Tutorial objectives:
* Understand difference between test and train data
* Compare train and test error for models of varying complexity
* Understand how bias-variance tradeoff relates to what model we choose
```
# @title Video 1: Bias Variance Tradeoff
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="BV1dg4y1v7wP", 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="NcUH_seBcVw", 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)
```
---
# Setup
```
import numpy as np
import matplotlib.pyplot as plt
#@title Figure Settings
%config InlineBackend.figure_format = 'retina'
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle")
#@title Helper functions
def ordinary_least_squares(x, y):
"""Ordinary least squares estimator for linear regression.
Args:
x (ndarray): design matrix of shape (n_samples, n_regressors)
y (ndarray): vector of measurements of shape (n_samples)
Returns:
ndarray: estimated parameter values of shape (n_regressors)
"""
return np.linalg.inv(x.T @ x) @ x.T @ y
def make_design_matrix(x, order):
"""Create the design matrix of inputs for use in polynomial regression
Args:
x (ndarray): input vector of shape (n_samples)
order (scalar): polynomial regression order
Returns:
ndarray: design matrix for polynomial regression of shape (samples, order+1)
"""
# Broadcast to shape (n x 1) so dimensions work
if x.ndim == 1:
x = x[:, None]
#if x has more than one feature, we don't want multiple columns of ones so we assign
# x^0 here
design_matrix = np.ones((x.shape[0],1))
# Loop through rest of degrees and stack columns
for degree in range(1, order+1):
design_matrix = np.hstack((design_matrix, x**degree))
return design_matrix
def solve_poly_reg(x, y, max_order):
"""Fit a polynomial regression model for each order 0 through max_order.
Args:
x (ndarray): input vector of shape (n_samples)
y (ndarray): vector of measurements of shape (n_samples)
max_order (scalar): max order for polynomial fits
Returns:
dict: fitted weights for each polynomial model (dict key is order)
"""
# Create a dictionary with polynomial order as keys, and np array of theta
# (weights) as the values
theta_hats = {}
# Loop over polynomial orders from 0 through max_order
for order in range(max_order+1):
X = make_design_matrix(x, order)
this_theta = ordinary_least_squares(X, y)
theta_hats[order] = this_theta
return theta_hats
```
---
# Section 1: Train vs test data
The data used for the fitting procedure for a given model is the **training data**. In tutorial 4, we computed MSE on the training data of our polynomial regression models and compared training MSE across models. An additional important type of data is **test data**. This is held-out data that is not used (in any way) during the fitting procedure. When fitting models, we often want to consider both the train error (the quality of prediction on the training data) and the test error (the quality of prediction on the test data) as we will see in the next section.
We will generate some noisy data for use in this tutorial using a similar process as in Tutorial 4.However, now we will also generate test data. We want to see how our model generalizes beyond the range of values see in the training phase. To accomplish this, we will generate x from a wider range of values ([-3, 3]). We then plot the train and test data together.
```
#@title
#@markdown Execute this cell to simulate both training and test data
### Generate training data
np.random.seed(0)
n_train_samples = 50
x_train = np.random.uniform(-2, 2.5, n_train_samples) # sample from a uniform distribution over [-2, 2.5)
noise = np.random.randn(n_train_samples) # sample from a standard normal distribution
y_train = x_train**2 - x_train - 2 + noise
### Generate testing data
n_test_samples = 20
x_test = np.random.uniform(-3, 3, n_test_samples) # sample from a uniform distribution over [-2, 2.5)
noise = np.random.randn(n_test_samples) # sample from a standard normal distribution
y_test = x_test**2 - x_test - 2 + noise
## Plot both train and test data
fig, ax = plt.subplots()
plt.title('Training & Test Data')
plt.plot(x_train, y_train, '.', markersize=15, label='Training')
plt.plot(x_test, y_test, 'g+', markersize=15, label='Test')
plt.legend()
plt.xlabel('x')
plt.ylabel('y');
```
---
# Section 2: Bias-variance tradeoff
Finding a good model can be difficult. One of the most important concepts to keep in mind when modeling is the **bias-variance tradeoff**.
**Bias** is the difference between the prediction of the model and the corresponding true output variables you are trying to predict. Models with high bias will not fit the training data well since the predictions are quite different from the true data. These high bias models are overly simplified - they do not have enough parameters and complexity to accurately capture the patterns in the data and are thus **underfitting**.
**Variance** refers to the variability of model predictions for a given input. Essentially, do the model predictions change a lot with changes in the exact training data used? Models with high variance are highly dependent on the exact training data used - they will not generalize well to test data. These high variance models are **overfitting** to the data.
In essence:
* High bias, low variance models have high train and test error.
* Low bias, high variance models have low train error, high test error
* Low bias, low variance models have low train and test error
As we can see from this list, we ideally want low bias and low variance models! These goals can be in conflict though - models with enough complexity to have low bias also tend to overfit and depend on the training data more. We need to decide on the correct tradeoff.
In this section, we will see the bias-variance tradeoff in action with polynomial regression models of different orders.
Graphical illustration of bias and variance.
(Source: http://scott.fortmann-roe.com/docs/BiasVariance.html)

We will first fit polynomial regression models of orders 0-5 on our simulated training data just as we did in Tutorial 4.
```
#@title
#@markdown Execute this cell to estimate theta_hats
max_order = 5
theta_hats = solve_poly_reg(x_train, y_train, max_order)
```
### Exercise 1: Compute and compare train vs test error
We will use MSE as our error metric again. Compute MSE on training data ($x_{train},y_{train}$) and test data ($x_{test}, y_{test}$) for each polynomial regression model (orders 0-5). Since you already developed code in T4 Exercise 4 for evaluating fit polynomials, we have ported that here into the function ``evaluate_poly_reg`` for your use.
*Please think about after completing exercise before reading the following text! Do you think the order 0 model has high or low bias? High or low variance? How about the order 5 model?*
```
def evaluate_poly_reg(x, y, theta_hats, max_order):
""" Evaluates MSE of polynomial regression models on data
Args:
x (ndarray): input vector of shape (n_samples)
y (ndarray): vector of measurements of shape (n_samples)
theta_hats (dict): fitted weights for each polynomial model (dict key is order)
max_order (scalar): max order of polynomial fit
Returns
(ndarray): mean squared error for each order, shape (max_order)
"""
mse = np.zeros((max_order + 1))
for order in range(0, max_order + 1):
X_design = make_design_matrix(x, order)
y_hat = np.dot(X_design, theta_hats[order])
residuals = y - y_hat
mse[order] = np.mean(residuals ** 2)
return mse
def compute_mse(x_train,x_test,y_train,y_test,theta_hats,max_order):
"""Compute MSE on training data and test data.
Args:
x_train(ndarray): training data input vector of shape (n_samples)
x_test(ndarray): test data input vector of shape (n_samples)
y_train(ndarray): training vector of measurements of shape (n_samples)
y_test(ndarray): test vector of measurements of shape (n_samples)
theta_hats(dict): fitted weights for each polynomial model (dict key is order)
max_order (scalar): max order of polynomial fit
Returns:
ndarray, ndarray: MSE error on training data and test data for each order
"""
#######################################################
## TODO for students: calculate mse error for both sets
## Hint: look back at tutorial 5 where we calculated MSE
# Fill out function and remove
raise NotImplementedError("Student excercise: calculate mse for train and test set")
#######################################################
mse_train = ...
mse_test = ...
return mse_train, mse_test
#Uncomment below to test your function
# mse_train, mse_test = compute_mse(x_train, x_test, y_train, y_test, theta_hats, max_order)
fig, ax = plt.subplots()
width = .35
# ax.bar(np.arange(max_order + 1) - width / 2, mse_train, width, label="train MSE")
# ax.bar(np.arange(max_order + 1) + width / 2, mse_test , width, label="test MSE")
ax.legend()
ax.set(xlabel='Polynomial order', ylabel='MSE', title ='Comparing polynomial fits');
# to_remove solution
def compute_mse(x_train,x_test,y_train,y_test,theta_hats,max_order):
"""Compute MSE on training data and test data.
Args:
x_train(ndarray): training data input vector of shape (n_samples)
x_test(ndarray): test vector of shape (n_samples)
y_train(ndarray): training vector of measurements of shape (n_samples)
y_test(ndarray): test vector of measurements of shape (n_samples)
theta_hats(dict): fitted weights for each polynomial model (dict key is order)
max_order (scalar): max order of polynomial fit
Returns:
ndarray, ndarray: MSE error on training data and test data for each order
"""
mse_train = evaluate_poly_reg(x_train, y_train, theta_hats, max_order)
mse_test = evaluate_poly_reg(x_test, y_test, theta_hats, max_order)
return mse_train, mse_test
mse_train, mse_test = compute_mse(x_train, x_test, y_train, y_test, theta_hats, max_order)
with plt.xkcd():
fig, ax = plt.subplots()
width = .35
ax.bar(np.arange(max_order + 1) - width / 2, mse_train, width, label="train MSE")
ax.bar(np.arange(max_order + 1) + width / 2, mse_test , width, label="test MSE")
ax.legend()
ax.set(xlabel='Polynomial order', ylabel='MSE', title ='Comparing polynomial fits');
```
As we can see from the plot above, more complex models (higher order polynomials) have lower MSE for training data. The overly simplified models (orders 0 and 1) have high MSE on the training data. As we add complexity to the model, we go from high bias to low bias.
The MSE on test data follows a different pattern. The best test MSE is for an order 2 model - this makes sense as the data was generated with an order 2 model. Both simpler models and more complex models have higher test MSE.
So to recap:
Order 0 model: High bias, low variance
Order 5 model: Low bias, high variance
Order 2 model: Just right, low bias, low variance
---
# Summary
- Training data is the data used for fitting, test data is held-out data.
- We need to strike the right balance between bias and variance. Ideally we want to find a model with optimal model complexity that has both low bias and low variance
- Too complex models have low bias and high variance.
- Too simple models have high bias and low variance.
**Note**
- Bias and variance are very important concepts in modern machine learning, but it has recently been observed that they do not necessaruly trade off (see for example the phenomenon and theory of "double descent")
**Further readings:**
- [The elements of statistical learning](https://web.stanford.edu/~hastie/ElemStatLearn/) by Hastie, Tibshirani and Friedman
---
# Appendix
## Bonus Exercise
Prove the bias-variance decomposition for MSE
$$
\mathrm{E}_{x}\left[(y-\hat{y}(x ; \theta))^{2}\right]=\left(\operatorname{Bias}_{x}[\hat{y}(x ; \theta)]\right)^{2}+\operatorname{Var}_{x}[\hat{y}(x ; \theta)]+\sigma^{2}
$$where
$$\operatorname{Bias}_{x}[\hat{y}(x ; \theta)]=\mathrm{E}_{x}[\hat{y}(x ; \theta)]-y
$$and
$$\operatorname{Var}_{x}[\hat{y}(x ; \theta)]=\mathrm{E}_{x}\left[\hat{y}(x ; \theta)^{2}\right]-\mathrm{E}_{x}[\hat{y}(x ; \theta)]^{2}
$$
Hint: use $$\operatorname{Var}[X]=\mathrm{E}\left[X^{2}\right]-(\mathrm{E}[X])^{2}$$
| github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/polynomial.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/Image/polynomial.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=Image/polynomial.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/Image/polynomial.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 magic command `%%capture` can be used to hide output from a specific cell.
```
# %%capture
# !pip install earthengine-api
# !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. Uncomment the line `ee.Authenticate()`
if you are running this notebook for this first time or if you are getting an authentication error.
```
# 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
```
# Applies a non-linear contrast enhancement to a MODIS image using
# function -0.2 + 2.4x - 1.2x^2.
# Load a MODIS image and apply the scaling factor.
img = ee.Image('MODIS/006/MOD09GA/2012_03_09') \
.select(['sur_refl_b01', 'sur_refl_b04', 'sur_refl_b03']) \
.multiply(0.0001)
# Apply the polynomial enhancement.
adj = img.polynomial([-0.2, 2.4, -1.2])
Map.setCenter(-107.24304, 35.78663, 8)
Map.addLayer(img, {'min': 0, 'max': 1}, 'original')
Map.addLayer(adj, {'min': 0, 'max': 1}, 'adjusted')
```
## Display Earth Engine data layers
```
Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map
```
| github_jupyter |
In this notebook we stage some data in GCS buckets for cloud-based training. We could do all of this in the main notebook but it's not too relevant for the demo itself, so we are breaking it out and only running it once.
# Setup GCP environment
* Your project id is the *unique* string that identifies your project (not the project name). You can find this from the GCP Console dashboard's Home page. My dashboard reads: <b>Project ID:</b> cloud-training-demos
* Cloud training often involves saving and restoring model files. Therefore, we should <b>create a single-region bucket</b>. If you don't have a bucket already, I suggest that you create one from the GCP console (because it will dynamically check whether the bucket name you want is available)
<b>Change the cell below</b> to reflect your Project ID and bucket name.
```
%%bash
source activate py2env
conda install -y pytz
pip uninstall -y google-cloud-dataflow
pip install --upgrade apache-beam[gcp]
PROJECT = 'rostlab-181304' # CHANGE THIS
BUCKET = 'rostlab-181304-ml' # REPLACE WITH YOUR BUCKET NAME. Use a regional bucket in the region you selected.
REGION = 'us-central1' # Choose an available region for Cloud MLE from https://cloud.google.com/ml-engine/docs/regions.
import datalab.bigquery as bq
import os
import shutil
import apache_beam as beam
import warnings
warnings.filterwarnings('ignore')
# for bash
os.environ['PROJECT'] = PROJECT
os.environ['BUCKET'] = BUCKET
os.environ['REGION'] = REGION
## ensure we're using python2 env
os.environ['CLOUDSDK_PYTHON'] = 'python2'
%%bash
## ensure gcloud is up to date
gcloud components update
gcloud config set project $PROJECT
gcloud config set compute/region $REGION
## ensure we predict locally with our current Python environment
gcloud config set ml_engine/local_python `which python`
```
## Specifying query to pull the data
Let's pull out a few extra columns from the timestamp.
```
def create_query(phase, EVERY_N):
if EVERY_N == None:
EVERY_N = 4 #use full dataset
#select and pre-process fields
base_query = """
SELECT
(tolls_amount + fare_amount) AS fare_amount,
DAYOFWEEK(pickup_datetime) AS dayofweek,
HOUR(pickup_datetime) AS hourofday,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_count*1.0 AS passengers,
CONCAT(STRING(pickup_datetime), STRING(pickup_longitude), STRING(pickup_latitude), STRING(dropoff_latitude), STRING(dropoff_longitude)) AS key
FROM
[nyc-tlc:yellow.trips]
WHERE
trip_distance > 0
AND fare_amount >= 2.5
AND pickup_longitude > -78
AND pickup_longitude < -70
AND dropoff_longitude > -78
AND dropoff_longitude < -70
AND pickup_latitude > 37
AND pickup_latitude < 45
AND dropoff_latitude > 37
AND dropoff_latitude < 45
AND passenger_count > 0
"""
#add subsampling criteria by modding with hashkey
if phase == 'train':
query = "{} AND ABS(HASH(pickup_datetime)) % {} < 2".format(base_query,EVERY_N)
elif phase == 'valid':
query = "{} AND ABS(HASH(pickup_datetime)) % {} == 2".format(base_query,EVERY_N)
elif phase == 'test':
query = "{} AND ABS(HASH(pickup_datetime)) % {} == 3".format(base_query,EVERY_N)
return query
print(create_query('valid', 100)) #example query using 1% of data
```
Preprocessing Dataflow job from BigQuery This code reads from BigQuery and saves the data as-is on Google Cloud Storage. We can do additional preprocessing and cleanup inside Dataflow, but then we'll have to remember to repeat that prepreprocessing during inference. It is better to use tf.transform which will do this book-keeping for you, or to do preprocessing within your TensorFlow model. We will look at this in future notebooks. For now, we are simply moving data from BigQuery to CSV using Dataflow.
While we could read from BQ directly from TensorFlow (See: https://www.tensorflow.org/api_docs/python/tf/contrib/cloud/BigQueryReader), it is quite convenient to export to CSV and do the training off CSV. Let's use Dataflow to do this at scale.
Because we are running this on the Cloud, you should go to the GCP Console (https://console.cloud.google.com/dataflow) to look at the status of the job. It will take several minutes for the preprocessing job to launch.
```
%%bash
if gsutil ls | grep -q gs://${BUCKET}/taxifare/taxi_preproc/; then
gsutil -m rm -rf gs://$BUCKET/taxifare/taxi_preproc/
fi
import datetime
####
# Arguments:
# -rowdict: Dictionary. The beam bigquery reader returns a PCollection in
# which each row is represented as a python dictionary
# Returns:
# -rowstring: a comma separated string representation of the record with dayofweek
# converted from int to string (e.g. 3 --> Tue)
####
def to_csv(rowdict):
days = ['null', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
CSV_COLUMNS = 'fare_amount,dayofweek,hourofday,pickuplon,pickuplat,dropofflon,dropofflat,passengers,key'.split(',')
rowdict['dayofweek'] = days[rowdict['dayofweek']]
rowstring = ','.join([str(rowdict[k]) for k in CSV_COLUMNS])
return rowstring
####
# Arguments:
# -EVERY_N: Integer. Sample one out of every N rows from the full dataset.
# Larger values will yield smaller sample
# -RUNNER: 'DirectRunner' or 'DataflowRunner'. Specfy to run the pipeline
# locally or on Google Cloud respectively.
# Side-effects:
# -Creates and executes dataflow pipeline.
# See https://beam.apache.org/documentation/programming-guide/#creating-a-pipeline
####
def preprocess(EVERY_N, RUNNER):
job_name = 'preprocess-taxifeatures' + '-' + datetime.datetime.now().strftime('%y%m%d-%H%M%S')
print('Launching Dataflow job {} ... hang on'.format(job_name))
OUTPUT_DIR = 'gs://{0}/taxifare/taxi_preproc/'.format(BUCKET)
#dictionary of pipeline options
options = {
'staging_location': os.path.join(OUTPUT_DIR, 'tmp', 'staging'),
'temp_location': os.path.join(OUTPUT_DIR, 'tmp'),
'job_name': 'preprocess-taxifeatures' + '-' + datetime.datetime.now().strftime('%y%m%d-%H%M%S'),
'project': PROJECT,
'runner': RUNNER
}
#instantiate PipelineOptions object using options dictionary
opts = beam.pipeline.PipelineOptions(flags=[], **options)
#instantantiate Pipeline object using PipelineOptions
with beam.Pipeline(options=opts) as p:
for phase in ['train', 'valid']:
query = create_query(phase, EVERY_N)
outfile = os.path.join(OUTPUT_DIR, '{}.csv'.format(phase))
(
p | 'read_{}'.format(phase) >> beam.io.Read(beam.io.BigQuerySource(query=query))
| 'tocsv_{}'.format(phase) >> beam.Map(to_csv)
| 'write_{}'.format(phase) >> beam.io.Write(beam.io.WriteToText(outfile))
)
print("Done")
```
Run pipeline locally. This takes up to <b>5 minutes</b>. You will see a message "Done" when it is done.
```
preprocess(50*10000, 'DirectRunner')
%%bash
gsutil ls -l gs://$BUCKET/taxifare/taxi_preproc/
```
## Run Beam pipeline on Cloud Dataflow
Run pipleline on cloud on a larger sample size.
```
%%bash
if gsutil ls | grep -q gs://${BUCKET}/taxifare/taxi_preproc/; then
gsutil -m rm -rf gs://$BUCKET/taxifare/taxi_preproc/
fi
preprocess(20*100, 'DataflowRunner')
#change first arg to None to preprocess full dataset
```
Once the job completes, observe the files created in Google Cloud Storage
```
%%bash
gsutil ls -l gs://$BUCKET/taxifare/taxi_preproc/
%%bash
#print first 10 lines of first shard of train.csv
gsutil cat "gs://$BUCKET/taxifare/taxi_preproc/train.csv-00000-of-*" | head
```
Copyright 2016 Google Inc. 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
| github_jupyter |
# Introduction to Tensorboard
This Jupyter is copied from [tensorboard_tutorial](https://pytorch.org/tutorials/intermediate/tensorboard_tutorial.html) from pytorch
```
import os
import torch
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
## Folder Configuration
ROOT = "runs/"
if not os.path.exists(ROOT):
os.makedirs(ROOT)
```
Visualizing Models, Data, and Training with TensorBoard
====================================================
In the [60 Minute Blitz](https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html),
we show you how to load in data,
feed it through a model we define as a subclass of ``nn.Module``,
train this model on training data, and test it on test data.
To see what's happening, we print out some statistics as the model
is training to get a sense for whether training is progressing.
However, we can do much better than that: PyTorch integrates with
TensorBoard, a tool designed for visualizing the results of neural
network training runs. This tutorial illustrates some of its
functionality, using the
[Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist)
which can be read into PyTorch using `torchvision.datasets`.
In this tutorial, we'll learn how to:
1. Read in data and with appropriate transforms (nearly identical to the prior tutorial).
2. Set up TensorBoard.
3. Write to TensorBoard.
4. Inspect a model architecture using TensorBoard.
5. Use TensorBoard to create interactive versions of the visualizations we created in last tutorial, with less code
Specifically, on point #5, we'll see:
* A couple of ways to inspect our training data
* How to track our model's performance as it trains
* How to assess our model's performance once it is trained.
We'll begin with similar boilerplate code as in the [CIFAR-10 tutorial](https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html):
```
# imports
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# datasets
trainset = torchvision.datasets.FashionMNIST('./data',
download=True,
train=True,
transform=transform)
testset = torchvision.datasets.FashionMNIST('./data',
download=True,
train=False,
transform=transform)
# dataloaders
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
shuffle=True, num_workers=2)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
shuffle=False, num_workers=2)
# constant for classes
classes = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot')
# helper function to show an image
# (used in the `plot_classes_preds` function below)
def matplotlib_imshow(img, one_channel=False):
if one_channel:
img = img.mean(dim=0)
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
if one_channel:
plt.imshow(npimg, cmap="Greys")
else:
plt.imshow(np.transpose(npimg, (1, 2, 0)))
```
We'll define a similar model architecture from that tutorial, making only
minor modifications to account for the fact that the images are now
one channel instead of three and 28x28 instead of 32x32:
```
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 4 * 4, 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 * 4 * 4)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
```
We'll define the same ``optimizer`` and ``criterion`` from before:
```
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
```
## 1. TensorBoard setup
Now we'll set up TensorBoard, importing ``tensorboard`` from ``torch.utils`` and defining a
``SummaryWriter``, our key object for writing information to TensorBoard.
```
from torch.utils.tensorboard import SummaryWriter
# default `log_dir` is "runs" - we'll be more specific here
writer = SummaryWriter(ROOT)
```
Note that this line alone creates a ``runs/fashion_mnist_experiment_1``
folder.
## 2. Writing to TensorBoard
Now let's write an image to our TensorBoard - specifically, a grid -
using [make_grid](https://pytorch.org/docs/stable/torchvision/utils.html#torchvision.utils.make_grid)
```
# get some random training images
dataiter = iter(trainloader)
images, labels = dataiter.next()
# create grid of images
img_grid = torchvision.utils.make_grid(images)
# show images
matplotlib_imshow(img_grid, one_channel=True)
# write to tensorboard
writer.add_image('four_fashion_mnist_images', img_grid)
```
Now running<br>
`%tensorboard --logdir runs`<br>
from the command line and then navigating to https://localhost:6006 should show the following.
```
%load_ext tensorboard
%tensorboard --logdir runs
```
## 3. Inspect the model using TensorBoard
One of TensorBoard’s strengths is its ability to visualize complex model structures. Let’s visualize the model we built.
```
writer.add_graph(net, images)
writer.close()
```
Now upon refreshing TensorBoard you should see a “Graphs” tab that looks like this:
Go ahead and double click on “Net” to see it expand, seeing a detailed view of the individual operations that make up the model.
TensorBoard has a very handy feature for visualizing high dimensional data such as image data in a lower dimensional space; we’ll cover this next.
## 4. Adding a “Projector” to TensorBoard
We can visualize the lower dimensional representation of higher
dimensional data via the [add_embedding](https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter.add_embedding)
```
# helper function
def select_n_random(data, labels, n=100):
'''
Selects n random datapoints and their corresponding labels from a dataset
'''
assert len(data) == len(labels)
perm = torch.randperm(len(data))
return data[perm][:n], labels[perm][:n]
# select random images and their target indices
images, labels = select_n_random(trainset.data, trainset.targets)
# get the class labels for each image
class_labels = [classes[lab] for lab in labels]
# log embeddings
features = images.view(-1, 28 * 28)
writer.add_embedding(features,
metadata=class_labels,
label_img=images.unsqueeze(1))
writer.close()
```
Now in the “Projector” tab of TensorBoard, you can see these 100 images - each of which is 784 dimensional - projected down into three dimensional space. Furthermore, this is interactive: you can click and drag to rotate the three dimensional projection. Finally, a couple of tips to make the visualization easier to see: select “color: label” on the top left, as well as enabling “night mode”, which will make the images easier to see since their background is white:
Now we’ve thoroughly inspected our data, let’s show how TensorBoard can make tracking model training and evaluation clearer, starting with training.
## 5. Tracking model training with TensorBoard
In the previous example, we simply printed the model’s running loss every 2000 iterations. Now, we’ll instead log the running loss to TensorBoard, along with a view into the predictions the model is making via the plot_classes_preds function.
```
# helper functions
def images_to_probs(net, images):
'''
Generates predictions and corresponding probabilities from a trained
network and a list of images
'''
output = net(images)
# convert output probabilities to predicted class
_, preds_tensor = torch.max(output, 1)
preds = np.squeeze(preds_tensor.numpy())
return preds, [F.softmax(el, dim=0)[i].item() for i, el in zip(preds, output)]
def plot_classes_preds(net, images, labels):
'''
Generates matplotlib Figure using a trained network, along with images
and labels from a batch, that shows the network's top prediction along
with its probability, alongside the actual label, coloring this
information based on whether the prediction was correct or not.
Uses the "images_to_probs" function.
'''
preds, probs = images_to_probs(net, images)
# plot the images in the batch, along with predicted and true labels
fig = plt.figure(figsize=(12, 48))
for idx in np.arange(4):
ax = fig.add_subplot(1, 4, idx+1, xticks=[], yticks=[])
matplotlib_imshow(images[idx], one_channel=True)
ax.set_title("{0}, {1:.1f}%\n(label: {2})".format(
classes[preds[idx]],
probs[idx] * 100.0,
classes[labels[idx]]),
color=("green" if preds[idx]==labels[idx].item() else "red"))
return fig
```
Finally, let’s train the model using the same model training code from the prior tutorial, but writing results to TensorBoard every 1000 batches instead of printing to console; this is done using the add_scalar function.
In addition, as we train, we’ll generate an image showing the model’s predictions vs. the actual results on the four images included in that batch.
```
running_loss = 0.0
for epoch in range(1): # loop over the dataset multiple times
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 1000 == 999: # every 1000 mini-batches...
# ...log the running loss
writer.add_scalar('training loss',
running_loss / 1000,
epoch * len(trainloader) + i)
# ...log a Matplotlib Figure showing the model's predictions on a
# random mini-batch
writer.add_figure('predictions vs. actuals',
plot_classes_preds(net, inputs, labels),
global_step=epoch * len(trainloader) + i)
running_loss = 0.0
print('Finished Training')
```
You can now look at the scalars tab to see the running loss plotted over the 15,000 iterations of training:<br>
In addition, we can look at the predictions the model made on arbitrary batches throughout learning. See the “Images” tab and scroll down under the “predictions vs. actuals” visualization to see this; this shows us that, for example, after just 3000 training iterations, the model was already able to distinguish between visually distinct classes such as shirts, sneakers, and coats, though it isn’t as confident as it becomes later on in training:<br>
In the prior tutorial, we looked at per-class accuracy once the model had been trained; here, we’ll use TensorBoard to plot precision-recall curves (good explanation here) for each class.
## 6. Assessing trained models with TensorBoard
```
# 1. gets the probability predictions in a test_size x num_classes Tensor
# 2. gets the preds in a test_size Tensor
# takes ~10 seconds to run
class_probs = []
class_preds = []
with torch.no_grad():
for data in testloader:
images, labels = data
output = net(images)
class_probs_batch = [F.softmax(el, dim=0) for el in output]
_, class_preds_batch = torch.max(output, 1)
class_probs.append(class_probs_batch)
class_preds.append(class_preds_batch)
test_probs = torch.cat([torch.stack(batch) for batch in class_probs])
test_preds = torch.cat(class_preds)
# helper function
def add_pr_curve_tensorboard(class_index, test_probs, test_preds, global_step=0):
'''
Takes in a "class_index" from 0 to 9 and plots the corresponding
precision-recall curve
'''
tensorboard_preds = test_preds == class_index
tensorboard_probs = test_probs[:, class_index]
writer.add_pr_curve(classes[class_index],
tensorboard_preds,
tensorboard_probs,
global_step=global_step)
writer.close()
# plot all the pr curves
for i in range(len(classes)):
add_pr_curve_tensorboard(i, test_probs, test_preds)
```
You will now see a “PR Curves” tab that contains the precision-recall curves for each class. Go ahead and poke around; you’ll see that on some classes the model has nearly 100% “area under the curve”, whereas on others this area is lower:

And that’s an intro to TensorBoard and PyTorch’s integration with it. Of course, you could do everything TensorBoard does in your Jupyter Notebook, but with TensorBoard, you gets visuals that are interactive by default.
```
from tensorboard import notebook
notebook.display(port=6006, height=1000)
```
| github_jupyter |
# Finding the edge of one pinture using Quantum Paralelism
This notebook is based on the paper:
[Yao, X.-W.](https://arxiv.org/abs/1801.01465), et al. (2017). Quantum Image Processing and Its Application to Edge Detection: Theory and Experiment. Physical Review X, 7(3), 031041. http://doi.org/10.1103/PhysRevX.7.031041
The main objective of this algorithm is to find the edge of one image. This means, given the image:
<img src="./Images/C.png">
the objective is to find its edges to get this other image:
<img src="./Images/C_EDGES.png">
The algorithm has the next steps:
1. Load the image as a matrix os (n,m) elements $c_{ij}$
$$D=\begin{bmatrix}
d_{11} & d_{12} & \cdots&d_{1j}&\cdots&d_{1m} \\
d_{21} & d_{22} & \cdots&d_{2j}&\cdots &d_{2m} \\
\vdots&&\ddots&\vdots&\ddots&\vdots\\
d_{i1} & d_{i2} & \cdots&d_{ij}&\cdots &d_{im} \\
\vdots&&\ddots&\vdots&\ddots&\vdots\\
d_{n1} & d_{n2} & \cdots&d_{nj}&\cdots &d_{nm} \\
\end{bmatrix}$$
2. Convert the array in a vector of N=n\*m elements
$$C=\begin{bmatrix}
d_{11} \\
d_{21} \\
\vdots\\
d_{ij} \\
d_{(i+1) j} \\
\vdots\\
d_{nm} \\
\end{bmatrix}=
\begin{bmatrix}
c_{0} \\
c_{1} \\
\vdots\\
c_{N-2} \\
c_{N-1} \\
\end{bmatrix}
$$
3. Map this vector to one qureg of $q=log_2(N)$ qubits as
$${\lvert}\phi(C){\rangle}=\frac{1}{{\left\lVert C \right\rVert}^2}\sum_{k=0}^{N-1}c_{k}{\lvert}k{\rangle}$$
4. Apply a Hadamard gate to the last qubit
$$(I^{\otimes q-1}\otimes H)\lvert\phi(C)\rangle=\begin{bmatrix}
c_{0}+c_{1} \\
c_{0}-c_{1} \\
\vdots\\
c_{N-2}+c_{N-1}\\
c_{N-2}-c_{N-1}\\
\end{bmatrix}$$
So, even elements will be close to 0 if two pixels have near values -in the case of black and white images, they must be 0- and will have values different of 0 if they are borders. Measuring the last qubit, if the result is 1, the final states $\lvert k \rangle$ (states representing odd natural numbers), encode the pixels of the boundaries.
```
%matplotlib inline
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from numpy import linalg as LA
from qiskit import *
import qiskit.tools.jupyter
%qiskit_version_table
```
Load the image. Because it is too large, rescale it.
```
A=Image.open("Images/cesga_unha_tinta.jpg").convert("1")
maxsize=(A.size[0]//4,A.size[1]//4)
A.thumbnail(maxsize, Image.ANTIALIAS)
im_arr = (np.array(A)==False).astype(np.int8)
plt.imshow(im_arr, cmap='Greys' )
```
Because even after rescaling the image is to large to simulate, crop it around **C**
```
im_crop=im_arr[46:120,265:320]
#im_crop=im_arr[46:60,265:300]
plt.imshow(im_crop, cmap='Greys' )
```
Calculate the number of qubits needed to store all the image. Remember that n qubits can store $N=2^ n$ complex numbers. As consequence, to store m\*n pixels, a qureg of $q=\log_2(n*m)$ qubits is used
```
number_of_qubits=int(np.ceil(np.log2(im_crop.shape[0]*im_crop.shape[1])))
print(number_of_qubits)
```
Create a vector with the number of elements that number_of_qubits can store
```
Vector=np.zeros((2**number_of_qubits))
print("Print %d qubits can store %d elements."%(number_of_qubits,Vector.shape[0]))
```
Now, map the image to the first elements of this vector
```
shape=im_crop.shape[0]*im_crop.shape[1]
Vector[0:shape]=im_crop.reshape((shape))
```
Because the norm of the amplitudes of one quantum state must be one, we must convert this vector to a normalized one, dividing each element by the norm of the vector.
```
from numpy import linalg as LA
norma=LA.norm(Vector)
Vnorma=Vector/norma
```
Allocate one qureg with the number of needed qubits.
```
circuit=QuantumCircuit(number_of_qubits,number_of_qubits,name="EDGE")
qreg=circuit.qregs[0]
```
Now, use the operation [Custom](https://qiskit.org/documentation/api/qiskit.aqua.components.initial_states.Custom.html) to generate the quantum circuit to map the Vnorma vector to one quantum state. This operation will generate the set of gates to transform the initial state $\lvert 0 \rangle^{\otimes q}$ to the desired final state $\lvert \phi \rangle$.
```
from qiskit.aqua.components.initial_states import Custom
import numpy as np
CreateState=Custom(number_of_qubits,state_vector=Vnorma)
inputCir=circuit+CreateState.construct_circuit(mode='circuit', register=qreg)
def Display(string):
from IPython.display import display, Markdown
display(Markdown(string))
def VectorToLatex(A,Format='{:.4f}'):
a="\\begin{bmatrix}"
for i in range(A.shape[0]):
a=a+Format.format(A[i])
a=a+"\\\\"
a=a+"\\end{bmatrix}"
return(a)
def MatrixToLatex(A,Format='{:.4f}'):
a="\\begin{bmatrix}"
for i in range(A.shape[0]):
for j in range(A.shape[1]):
if ((j+1)%A.shape[1])==0:
a=a+Format.format(A[i,j])
else:
a=a+Format.format(A[i,j])+"&"
if ((i+1)%A.shape[0])!=0:
a=a+"\\\\"
a=a+"\\end{bmatrix}"
return(a)
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(inputCir.copy(), simulator).result()
statevector = result.get_statevector(inputCir)
#plot_state_city(statevector, title='Bell state')
fig,ax=plt.subplots(1,2,figsize=(10,3))
ax[0].plot(statevector,"r*",label="State")
ax[0].legend()
ax[0].set_ylabel("Amplitude")
ax[1].plot(Vnorma,"*",label="Vnorma")
ax[1].legend()
fig,ax=plt.subplots(1,2,figsize=(20,3))
ax[0].plot(statevector,"r-",label="State")
ax[0].legend()
ax[0].set_ylabel("Amplitude")
ax[1].plot(Vnorma,"-",label="Vnorma")
ax[1].legend()
IMOutput=np.round((statevector[0:im_crop.shape[0]*im_crop.shape[1]]).real*norma)
plt.imshow(IMOutput.reshape((im_crop.shape[0],im_crop.shape[1])), cmap='Greys')
```
Now, apply the Hadamard gate to the last qubit.
```
inputCir.h(0)
```
In the real case, a large number of measurements of the final state have to be done to obtain the probabilities of the final state. In fact, the algorithm needs to measure the last qubit and, when the results is one, the result state is the solution.However, in the simulator, you can recover them directly, and take only those that are due to last state equal to 1, this means, the natural odd numbers.
```
inputCir.measure(inputCir.qregs[0],inputCir.cregs[0])
simulator = Aer.get_backend('qasm_simulator')
# Execute and get counts
result = execute(inputCir.copy(), simulator,shots=shape).result()
resultado=result.get_counts(inputCir)
resultado
for i in range(1,2**number_of_qubits,2):
state=np.binary_repr(i,width=number_of_qubits)
try:
print(state,resultado[state])
except:
pass
Vout=np.zeros(shape)
for i in range(1,shape,2):
bits=np.binary_repr(i,width=number_of_qubits)
try:
Vout[i]=resultado[bits]
print(bits,resultado[bits])
except:
pass
fig,ax=plt.subplots(1,3,figsize=(12,3))
ax[0].plot(Vout,"r*",label="Final state")
ax[0].set_title("Final state")
ax[0].set_ylabel("Counts")
ax[1].plot(Vnorma,"*",label="Vnorma")
ax[1].set_title("Vnorma")
IMOutputOdd=np.round((Vout)*norma)
IMOutput=np.round(Vout*0)
IMOutput[0::2]=IMOutputOdd[1::2]
ax[2].imshow(IMOutput.reshape((im_crop.shape[0],im_crop.shape[1])), cmap='Greys')
ax[2].set_title("New transformed image")
```
OK. Look the final result after applying a single gate. Remember that only even elements are needed
Only half of the borders have been calculated. To calculate the even borders, the algorithm must be executed permuting the input vector by one position.
```
Veven=np.take(Vnorma,range(1,len(Vnorma)+1),mode="warp")
circuit=QuantumCircuit(number_of_qubits,number_of_qubits,name="EDGE")
qreg=circuit.qregs[0]
import numpy as np
CreateState=Custom(number_of_qubits,state_vector=Veven)
inputCir=circuit+CreateState.construct_circuit(mode='circuit', register=qreg)
inputCir.h(0)
inputCir.measure(inputCir.qregs[0],inputCir.cregs[0])
simulator = Aer.get_backend('qasm_simulator')
# Execute and get counts
result = execute(inputCir.copy(), simulator,shots=shape).result()
resultado=result.get_counts(inputCir)
Vouteven=np.zeros(shape)
for i in range(1,shape,2):
bits=np.binary_repr(i,width=number_of_qubits)
try:
Vouteven[i]=resultado[bits]
print(bits,resultado[bits])
except:
pass
fig,ax=plt.subplots(1,3,figsize=(12,3))
ax[0].plot(Vouteven,"r*",label="Final state")
ax[0].set_title("Final state")
ax[0].set_ylabel("Counts")
ax[1].plot(Vnorma,"*",label="Vnorma")
ax[1].set_title("Vnorma")
IMOutputeven=np.round((Vouteven>0))
IMOutput=np.round(Vouteven*0)
IMOutput[0::2]=IMOutputeven[1::2]
ax[2].imshow(IMOutput.reshape((im_crop.shape[0],im_crop.shape[1])), cmap='Greys')
ax[2].set_title("New transformed image")
IMOutputEven=np.round((Vouteven)*norma)
IMOutput=np.zeros(shape)
IMOutput[1:-1:2]=(IMOutputEven[1:-1:2]>0)
IMOutput[0::2]=(IMOutputOdd[1::2]>0)
plt.imshow(IMOutput.reshape((im_crop.shape[0],im_crop.shape[1])), cmap='Greys')
```
| github_jupyter |
```
import matplotlib.pyplot as plt
%matplotlib widget
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.pyplot as plt
import chemiscope
from widget_code_input import WidgetCodeInput
from ipywidgets import Textarea
from iam_utils import *
import ase
from ase.io import read, write
#### AVOID folding of output cell
%%html
<style>
.output_wrapper, .output {
height:auto !important;
max-height:4000px; /* your desired max-height here */
}
.output_scroll {
box-shadow:none !important;
webkit-box-shadow:none !important;
}
</style>
data_dump = WidgetDataDumper(prefix="module_03")
display(data_dump)
module_summary = Textarea("general comments on this module", layout=Layout(width="100%"))
data_dump.register_field("module-summary", module_summary, "value")
display(module_summary)
```
_Reference textbook / figure credits: Giuseppe Grosso, Giuseppe Parravicini, "Solid-state physics", Chapter IX_
# Lattice dynamics of a one-dimensional crystal
Consider a one-dimensional crystal with lattice parameter $a$, so that the positions of atoms in the ideal lattice are $r_n=na$. Each atom may be displaced by a finite amount $u_n$ from the ideal position, so that the actual atomic positions are $r_n=na+u_n$.
<img src="figures/TBC-linear-chain.png" width="500" height="250" />
_Figure credit: Grosso,Parravicini, "Solid state physics"_
The energy can be computed in terms of a Taylor expansion: if $na$ are equilibrium lattice positions, $\partial E/\partial u_n = 0$ and so the lowest-order term involves the matrix of second derivatives,
$$
E(\mathbf{u}) \approx E_0 + \frac{1}{2} \sum_{ij} \left.\frac{\partial^2 E}{\partial u_i \partial u_j}\right|_{\mathbf{u}=0} u_i u_j
$$
The matrix of second derivatives $D_{ij} \equiv \left.{\partial^2 E}/{\partial u_i \partial u_j}\right|_{\mathbf{u}=0}$ is usually called the *matrix of force constants*, and defines the response of the crystal to perturbations of the atomic positions.
The force acting on the atoms when they are displaced from their equilibrium position is given by $\mathbf{f}=-\partial E/\partial \mathbf{u}$.
<span style="color:blue"> **01** Write down the expression in terms of the elements of $\mathbf{D}$ and $\mathbf{u}$, for a general system.
Consider the case of a 1D bond between two atoms, that keeps them at a distance $d$, with a spring constant $k$. The energy can be written as $E=k(x_1-x_2-d)^2/2$. How would you write this in terms of displacements and a $\mathbf{D}$ matrix? </span>
```
ex01_txt = Textarea("enter your answer", layout=Layout(width="100%"))
data_dump.register_field("ex01-answer", ex01_txt, "value")
display(ex01_txt)
```
<span style="color:blue"> **02** Write a function that computes the energy and the forces for a lattice containing two atoms, with displacements $u_0$ and $u_1$. Check that the function gives the correct results by validating your input. </span>
```
# set upt the code widget window
ex01_wci = WidgetCodeInput(
function_name="lattice_energy_force",
function_parameters="D_00, D_01, D_10, D_11, u_0, u_1",
docstring="""
Computes energy and force associated with a given displacement of two atoms in a harmonic lattice.
:param D_ij: elements of the matrix of second derivatives
:param u_i: atomic displacements
:return: A tuple containing the lattice energy and the force, (E, f_0, f_1)
""",
function_body="""
# Write your solution, and test it by moving the sliders
e = 0.0 # write the potential energy function here
f = [0, 0] # write the force function here
return e, f[0], f[1]
"""
)
data_dump.register_field("ex02-function", ex01_wci, "function_body")
def draw_forces(ax, D_00, D_01, D_10, D_11, u_0, u_1 ):
ax.add_artist(plt.Circle((0+u_0, 0), 0.1, color='red'))
ax.add_artist(plt.Circle((1+u_1, 0), 0.1, color='red'))
ax.add_artist(plt.Line2D([-0.05,0.05], [-0.05, 0.05], color='k'))
ax.add_artist(plt.Line2D([-0.05,0.05], [0.05, -0.05], color='k'))
ax.add_artist(plt.Line2D([1-0.05,1+0.05], [-0.05, 0.05], color='k'))
ax.add_artist(plt.Line2D([1-0.05,1+0.05], [0.05, -0.05], color='k'))
U, f0, f1 = ex01_wci.get_function_object()(D_00, D_01, D_10, D_11, u_0, u_1)
if f0**2>1e-6:
arr0 = mpl.patches.FancyArrow(0+u_0,0,f0,0,width=0.02)
ax.add_artist(arr0)
if f1**2>1e-6:
arr1 = mpl.patches.FancyArrow(1+u_1,0,f1,0,width=0.02)
ax.add_artist(arr1)
ax.set_xlim(-0.5,1.5)
ax.set_xlabel("x/a")
ax.set_ylim(-0.5,0.5)
ax.yaxis.set_ticks([])
ax.set_aspect('equal')
p = WidgetPlot(draw_forces, WidgetParbox(D_00 = (1.0, -2, 2, 0.1, r'$D_{00}$'),
D_01 = (-1.0, -2, 2, 0.1, r'$D_{01}$'),
D_10 = (-1.0, -2, 2, 0.1, r'$D_{10}$'),
D_11 = (1.0, -2, 2, 0.1, r'$D_{11}$'),
u_0 = (-0.1, -0.2, 0.2, 0.01, r'$u_0$'),
u_1 = (0.05, -0.2, 0.2, 0.01, r'$u_0$'),
));
display(p)
ex01_wcc = WidgetCodeCheck(ex01_wci, ref_values =
{
(0,0,0,0,0,0) : (0,0,0),
(1,2,3,4,0,0) : (0,0,0),
(0,0,0,0,1,2) : (0,0,0),
(1,2,3,4,1,2) : (13.5,-6,-10.5),
(1,-1,-1,1,1,1) : (0,0,0),
(1,1,1,1,1,1) : (2,-2,-2),
(1,0,0,1,1,-1) : (1, -1, 1)
}, demo = p)
display(ex01_wcc)
```
<span style="color:blue"> **03** Set the values of the matrix of force constants to large random values, and then adjust the displacement values so that both atoms have the same displacement $u_0=u_1>0$.
What do you observe? Is this a physical behavior if these two atoms represent a cell in a periodic system?
</span>
```
ex03_txt = Textarea("enter your answer", layout=Layout(width="100%"))
data_dump.register_field("ex03-answer", ex03_txt, "value")
display(ex03_txt)
```
# Properties of the matrix of force constants
When the matrix of force constants describes the interactions in a periodic crystal, it must fulfill several physical conditions:
* The matrix is symmetric $D_{ij}=D_{ji}$
* The elements only depend on the separation between the atoms, $D_{ij} \equiv -K_{|i-j|}$. $\mathbf{K}$ is called the matrix of force constants.
* The matrix must satisfy a condition called *acoustic sum rule* (ASR), $\sum_i D_{ij} = 0$
<span style="color:blue"> **04** Write the expression for the energy of a structure with two atoms, with a $\mathbf{D}$ matrix that fulfills the acoustic sum rule. What happens if the two atoms are displaced by the same amount?
You can go back to the previous exercise, and enter a set of values consistent with the ASR and visualize the effect in practice.
</span>
```
ex04_txt = Textarea("enter your answer", layout=Layout(width="100%"))
data_dump.register_field("ex04-answer", ex04_txt, "value")
display(ex04_txt)
```
# The dispersion relation
We look for a way to express the time dependence of the lattice vibrations, $u_n(t)$. The lattice vibrations must satisfy Newton's equation, which implies that $m\ddot{u}_i=f_i = -\sum_j D_{ij} u_j$.
To solve this in the most general way possible, we express $u_n(t)$ on a plane wave basis,
$$
u_n(t) = \int \,d\omega dq \hat{u}(q,\omega) e^{\mathrm{i} (q n a - \omega t)}.
$$
Given the periodicity of the lattice, one only needs to consider $-\pi/a < q < \pi/a$.
By substituting into the equations of motion, and noting that both the time derivative and the sum over the matrix of force constants are linear operations that commute with the integration, one sees that the only way to ensure a consistent solution for any $\hat{u}(q,\omega)$ is to have
$$
m \omega^2 e^{\mathrm{i} (q i a - \omega t)} = \sum_j D_{ij} e^{\mathrm{i} (q j a - \omega t)},
$$
that is, there is a *dispersion relation* that links $q$ and $\omega$, $m \omega(q)^2 = -\sum_j K_{j} e^{-\mathrm{i} q j a}$.
<span style="color:blue"> **05** Write the function that computes $m \omega(q)^2$ given the force constants $K_{1\ldots 4}$, and plot the frequencies of the lattice vibrations as a function of the wavevector. You can check your solution by comparing the value of the function you computed (red line) with a reference implementation (dashed gray line) </span>
Hints:
* When you change the function, move the sliders to update the plot
* You will need [functions from numpy](https://numpy.org/doc/stable/reference/routines.math.html), that you can access with `np.XXXX` from the function body
* The sum extends to negative values of $j$. Ask yourself what should be the value of $K_{-j}$ given the properties of the matrix of force constants.
* What happens if you combine the terms $j$ and $-j$? Is the dispersion relation real?
* Don't forget there is also a $K_0$! Use the acoustic sum rule to determine its value
```
# set upt the code widget window
ex02_wci = WidgetCodeInput(
function_name="m_omega_square",
function_parameters="K_1, K_2, K_3, K_4, qa",
docstring="""
Computes the dispersion relation for a one-dimensional lattice given the first four force constants
:param K_i: force constants
:param qa: wavevector to compute the dispersion relation (multiplied by the lattice parameter, so it is adimensional)
:return: the value of m * omega**2
""",
function_body="""
# Write your solution, and test it by moving the sliders
import numpy as np
return 0.0
"""
)
data_dump.register_field("ex05-function", ex02_wci, "function_body")
def reference_func_02(K_1, K_2, K_3, K_4, q):
K_0 = -2*(K_1+K_2)-K_3-K_4-K_4-K_3; return -(K_0 + 2*K_1 * np.cos(q*1)+2*K_2 * (2*np.cos(q)**2 - 1)
+2*K_3 * np.cos(q*3)+2*K_4 * (np.cos(q)**4+np.sin(q)**4-6*np.cos(q)**2*np.sin(q)**2 ) )
def plot_freq(ax, K_1, K_2, K_3, K_4):
q = np.linspace(-np.pi, np.pi, 200)
w2ref = reference_func_02( K_1, K_2, K_3, K_4, q)
user_function = ex02_wci.get_function_object()
w2 = [ user_function(K_1, K_2, K_3, K_4, qa) for qa in q]
ax.plot(q, np.sqrt(np.abs(w2))*np.sign(w2ref), 'r', linewidth=2)
ax.plot(q, np.sqrt(np.abs(w2ref))*np.sign(w2ref), 'k--')
ax.set_xlim(-np.pi, np.pi)
ax.set_xlabel("q a")
ax.set_ylim(-1,4)
ax.set_ylabel(r"$\omega\sqrt{m}$")
a = WidgetPlot(plot_freq, WidgetParbox(K_1 = (1.0, -2, 2, 0.1, r'$K_{1}$'),
K_2 = (0.0, -2, 2, 0.1, r'$K_{2}$'),
K_3 = (0.0, -2, 2, 0.1, r'$K_{3}$'),
K_4 = (0.0, -2, 2, 0.1, r'$K_{4}$'),
));
ex02_wcc = WidgetCodeCheck(ex02_wci, ref_values = {
x: reference_func_02(*x) for x in [ (1,2,3,4,0), (1,2,3,4,1), (1,1,1,1,0.5), (-1,1,-2,2,0.25) ]
}, demo = a)
display(ex02_wcc)
```
Make sure the reference implementation matches your function for all values of the force constants.
Observe what happens as you change the parameters.
<span style="color:blue"> **06** Why does it make sense to truncate the expansion at $K_4$? Do you expect the force constants to increase or decrease as $j$ gets larger? Hint: go back to look at the expression of the force acting on atom $0$. How does it depend on the displacement of atom $j$? </span>
```
ex06_txt = Textarea("enter your answer", layout=Layout(width="100%"))
data_dump.register_field("ex06-answer", ex06_txt, "value")
display(ex06_txt)
```
Note that the plot visualizes $\operatorname{sign}(\omega^2) \sqrt{|m\omega^2|}$, so negative values on the plot correspond to so-called *imaginary frequencies*, i.e. values of $q$ for which $\omega^2$ is negative. Move around the sliders to get some negative lobes
<span style='color: blue'> **07** How will the energy change if you introduce a distortion with a periodicity corresponding to a $q$ associated with a negative $\omega^2$? What does this imply in terms of the stability of the crystal? </span>
```
ex07_txt = Textarea("enter your answer", layout=Layout(width="100%"))
data_dump.register_field("ex07-answer", ex07_txt, "value")
display(ex07_txt)
```
# Lattice with a basis - The Diatomic spring chain
Consider a one-dimensional lattice with two non-equivalent atoms of masses $M_1$ and $M_2$ in a unit cell of lattice parameter $a_0$. The atoms of mass $M_1$ occupy the sublattice positions $R_{n}^{(1)}$ = $na_0$ and can be displaced by an amount $u_n$, while the atoms of mass $M_2$ occupy the sublattice positions $R_{n}^{(2)}$ = $(n + 1/2)a_0$ and can be displaced by an amount $v_n$.
<img src="figures/Diatomic_dynamics.png" width="700" height="250" />
_Figure credit: Grosso,Parravicini, "Solid state physics"_
The classical equations of motion for the two types of particles are then given by:
$$
M_1\ddot{u}_n = -K(2u_n - v_{n-1}-v_n) \\
M_2\ddot{v}_n = -K(2v_n - u_n - u_{n+1})
$$
To solve this we express $u_n(t)$ and $v_n(t)$ as:
$$
u_n(t) = A_1 e^{i(qna_0 −ωt)}\\
v_n(t) = A_2 e^{i(qna_0 + qa_0/2 −ωt)}
$$
Which gives
$$
-M_1\omega^2A_1 = -K(2A_1 - A_2e^{-iqa_0/2}-A_2e^{iqa_0/2}) \\
-M_2\omega^2A_2 = -K(2A_2 - A_1e^{-iqa_0/2}-A_1e^{iqa_0/2})
$$
This can be written in the matrix form as:
$$
\begin{equation}
\begin{bmatrix}
2K-M_1\omega^2 & -2K \cos(qa_0/2) \\
-2K \cos(qa_0/2) & 2K-M_2\omega^2
\end{bmatrix}
\begin{bmatrix}
A_1 \\
A_2
\end{bmatrix}
= 0
\end{equation}
$$
For this equation, a nontrivial solution exists only if the determinant of the matrix is zero. This leads us to the equation:
$$
(2K-M_1\omega^2)(2K-M_2\omega^2) - 4C^2 \cos^2(qa_0/2)=0
$$
which is a quadratic equation in $\omega^2$, hence,
$$
\omega^2 = K \left( \frac{1}{M_1}+\frac{1}{M_2} \right) \pm K\sqrt{\left( \frac{1}{M_1}+\frac{1}{M_2} \right)^2 - \frac{4\sin^2(qa_0/2)}{M_1 M_2}}
$$
These two values of $\omega$ gives us the dispersion relations, that are illustrated in the figure given below.
```
#for dispersion relation in diatomic lattice
def diatomic_dispersion(K, M_1, M_2, q):
w1 = K*(1/M_1 + 1/M_2) + K*(np.sqrt((1/M_1 + 1/M_2)**2 - (4*(np.sin(q/2))**2)/(M_1*M_2)))
w2 = K*(1/M_1 + 1/M_2) - K*(np.sqrt((1/M_1 + 1/M_2)**2 - (4*(np.sin(q/2))**2)/(M_1*M_2)))
w = [w1, w2]
return w
def plot_omega(ax, K, M_1, M_2):
q = np.linspace(-1, 1, 200)
w_plus = diatomic_dispersion(K, M_1, M_2, q*np.pi)[0]
w_minus = diatomic_dispersion(K, M_1, M_2, q*np.pi)[1]
ax.plot(q, np.sqrt(np.abs(w_plus))*np.sign(w_plus), 'r', linewidth=2)
ax.plot(q, np.sqrt(np.abs(w_minus))*np.sign(w_minus), 'b', linewidth=2)
ax.set_xlim(-1,1)
ax.set_xlabel("$q a_0/\pi$")
ax.set_ylim(-0.1,1.8)
ax.set_ylabel("$\omega$")
A = WidgetPlot(plot_omega, WidgetParbox(M_1 = (9.0, 1, 20, 1, r'$M_{1}$'),
M_2 = (3.0, 1, 20, 1, r'$M_{2}$'),
K = (1.0, 0.1, 2, 0.1, r'$K$'),
));
display(A)
```
The two solutions are associated with two _branches_. The lower one is called _acoustic branch_ and the upper one is called _optical branch_, with a frequency gap between them.
<span style='color: blue'> **08** Play around with the parameters. How does the gap change with mass? What happens when $M_1$ = $M_2$? Explain your observations by relating these results to the monoatomic case. </span>
```
ex08_txt = Textarea("enter your answer", layout=Layout(width="100%"))
data_dump.register_field("ex08-answer", ex08_txt, "value")
display(ex08_txt)
```
| github_jupyter |
# Time Series Blog Notebook with Custom Calendar
This notebook executes an end to end time series analysis using the Amazon FinSpace time series framework and included analytics functions. The notebook will process Equity TAQ data (provided to FinSpace by AlgoSeek LLC) and runs that data through the framework to generate Volatility and Bollinger bad data and plots.
This notebook goes beyond the original blog notebook in that it uses the [pandas_market_calendar](https://pypi.org/project/pandas-market-calendars/) library to create a custom calendar for use in the 'Fill and Filter' stage of the time series data pipeline.
```
%local
from aws.finspace.cluster import FinSpaceClusterManager
# if this was already run, no need to run again
if 'finspace_clusters' not in globals():
finspace_clusters = FinSpaceClusterManager()
finspace_clusters.auto_connect()
else:
print(f'connected to cluster: {finspace_clusters.get_connected_cluster_id()}')
```
# Collect and Summarize Timebars
Time bars are obtained by sampling information at fixed time intervals, e.g., once every minute.
**Series:** Time Series Data Engineering and Analysis
As part of the big data timeseries processing workflow FinSpace supports, shows how one takes raw, uneven in time events of TAQ data and collects them into a performant derived dataset of collected bars of data.
## Timeseries Workflow
Raw Events → **\[Collect bars → Summarize bars → Fill Missing → Prepare → Analytics\]**

```
#####----------------------------------------------------------
##### REPLACE WITH CORRECT IDS!
##### Dataset: "US Equity TAQ Sample - AMZN 6 Months - Sample"
#####
#####----------------------------------------------------------
dataset_id = ''
view_id = ''
# python imports
import time
import datetime
import pprint
import pandas as pd
import matplotlib.pyplot as plt
import pyspark.sql.functions as F
import pyspark.sql.types as T
# FinSpace imports
from aws.finspace.timeseries.spark.util import string_to_timestamp_micros
from aws.finspace.timeseries.spark.windows import create_time_bars, compute_analytics_on_features, compute_features_on_time_bars
from aws.finspace.timeseries.spark.spec import BarInputSpec, TimeBarSpec
from aws.finspace.timeseries.spark.summarizer import *
from aws.finspace.timeseries.spark.analytics import *
from aws.finspace.timeseries.finance.calendars import *
from aws.finspace.timeseries.spark.prepare import *
# Date range
start_date = datetime.datetime(2019, 10, 1)
end_date = datetime.datetime(2019, 12, 31)
barNum = 1
barUnit = "minute"
barWidth = f"{barNum} {barUnit}"
```
# Python Helpers
These classes help with FinSpace service calls and use boto3 APIs.
```
# %load ../Utilities/finspace.py
import datetime
import time
import boto3
import os
import pandas as pd
import urllib
from urllib.parse import urlparse
from botocore.config import Config
from boto3.session import Session
# Base FinSpace class
class FinSpace:
def __init__(
self,
config=Config(retries={'max_attempts': 3, 'mode': 'standard'}),
boto_session: Session = None,
dev_overrides: dict = None,
service_name = 'finspace-data'):
"""
To configure this class object, simply instantiate with no-arg if hitting prod endpoint, or else override it:
e.g.
`hab = FinSpaceAnalyticsManager(region_name = 'us-east-1',
dev_overrides = {'hfs_endpoint': 'https://39g32x40jk.execute-api.us-east-1.amazonaws.com/alpha'})`
"""
self.hfs_endpoint = None
self.region_name = None
if dev_overrides is not None:
if 'hfs_endpoint' in dev_overrides:
self.hfs_endpoint = dev_overrides['hfs_endpoint']
if 'region_name' in dev_overrides:
self.region_name = dev_overrides['region_name']
else:
if boto_session is not None:
self.region_name = boto_session.region_name
else:
self.region_name = self.get_region_name()
self.config = config
self._boto3_session = boto3.session.Session(region_name=self.region_name) if boto_session is None else boto_session
print(f"service_name: {service_name}")
print(f"endpoint: {self.hfs_endpoint}")
print(f"region_name: {self.region_name}")
self.client = self._boto3_session.client(service_name, endpoint_url=self.hfs_endpoint, config=self.config)
@staticmethod
def get_region_name():
req = urllib.request.Request("http://169.254.169.254/latest/meta-data/placement/region")
with urllib.request.urlopen(req) as response:
return response.read().decode("utf-8")
# --------------------------------------
# Utility Functions
# --------------------------------------
@staticmethod
def get_list(all_list: dir, name: str):
"""
Search for name found in the all_list dir and return that list of things.
Removes repetitive code found in functions that call boto apis then search for the expected returned items
:param all_list: list of things to search
:type: dir:
:param name: name to search for in all_lists
:type: str
:return: list of items found in name
"""
r = []
# is the given name found, is found, add to list
if name in all_list:
for s in all_list[name]:
r.append(s)
# return the list
return r
# --------------------------------------
# Classification Functions
# --------------------------------------
def list_classifications(self):
"""
Return list of all classifications
:return: all classifications
"""
all_list = self.client.list_classifications(sort='NAME')
return self.get_list(all_list, 'classifications')
def classification_names(self):
"""
Get the classifications names
:return list of classifications names only
"""
classification_names = []
all_classifications = self.list_classifications()
for c in all_classifications:
classification_names.append(c['name'])
return classification_names
def classification(self, name: str):
"""
Exact name search for a classification of the given name
:param name: name of the classification to find
:type: str
:return
"""
all_classifications = self.list_classifications()
existing_classification = next((c for c in all_classifications if c['name'].lower() == name.lower()), None)
if existing_classification:
return existing_classification
def describe_classification(self, classification_id: str):
"""
Calls the describe classification API function and only returns the taxonomy portion of the response.
:param classification_id: the GUID of the classification to get description of
:type: str
"""
resp = None
taxonomy_details_resp = self.client.describe_taxonomy(taxonomyId=classification_id)
if 'taxonomy' in taxonomy_details_resp:
resp = taxonomy_details_resp['taxonomy']
return (resp)
def create_classification(self, classification_definition):
resp = self.client.create_taxonomy(taxonomyDefinition=classification_definition)
taxonomy_id = resp["taxonomyId"]
return (taxonomy_id)
def delete_classification(self, classification_id):
resp = self.client.delete_taxonomy(taxonomyId=classification_id)
if resp['ResponseMetadata']['HTTPStatusCode'] != 200:
return resp
return True
# --------------------------------------
# Attribute Set Functions
# --------------------------------------
def list_attribute_sets(self):
"""
Get list of all dataset_types in the system
:return: list of dataset types
"""
resp = self.client.list_dataset_types()
results = resp['datasetTypeSummaries']
while "nextToken" in resp:
resp = self.client.list_dataset_types(nextToken=resp['nextToken'])
results.extend(resp['datasetTypeSummaries'])
return (results)
def attribute_set_names(self):
"""
Get the list of all dataset type names
:return list of all dataset type names
"""
dataset_type_names = []
all_dataset_types = self.list_dataset_types()
for c in all_dataset_types:
dataset_type_names.append(c['name'])
return dataset_type_names
def attribute_set(self, name: str):
"""
Exact name search for a dataset type of the given name
:param name: name of the dataset type to find
:type: str
:return
"""
all_dataset_types = self.list_dataset_types()
existing_dataset_type = next((c for c in all_dataset_types if c['name'].lower() == name.lower()), None)
if existing_dataset_type:
return existing_dataset_type
def describe_attribute_set(self, attribute_set_id: str):
"""
Calls the describe dataset type API function and only returns the dataset type portion of the response.
:param attribute_set_id: the GUID of the dataset type to get description of
:type: str
"""
resp = None
dataset_type_details_resp = self.client.describe_dataset_type(datasetTypeId=attribute_set_id)
if 'datasetType' in dataset_type_details_resp:
resp = dataset_type_details_resp['datasetType']
return (resp)
def create_attribute_set(self, attribute_set_def):
resp = self.client.create_dataset_type(datasetTypeDefinition=attribute_set_def)
att_id = resp["datasetTypeId"]
return (att_id)
def delete_attribute_set(self, attribute_set_id: str):
resp = self.client.delete_attribute_set(attributeSetId=attribute_set_id)
if resp['ResponseMetadata']['HTTPStatusCode'] != 200:
return resp
return True
def associate_attribute_set(self, att_name: str, att_values: list, dataset_id: str):
# get the attribute set by name, will need its id
att_set = self.attribute_set(att_name)
# get the dataset's information, will need the arn
dataset = self.describe_dataset_details(dataset_id=dataset_id)
# disassociate any existing relationship
try:
self.client.dissociate_dataset_from_dataset_type(datasetArn=dataset['arn'],
datasetTypeId=att_set['id'])
except:
print("Nothing to disassociate")
self.client.associate_dataset_with_dataset_type(datasetArn=dataset['arn'], datasetTypeId=att_set['id'])
ret = self.client.update_dataset_type_context(datasetArn=dataset['arn'], datasetTypeId=att_set['id'],
values=att_values)
return ret
# --------------------------------------
# Permission Group Functions
# --------------------------------------
def list_permission_groups(self, max_results: int):
all_perms = self.client.list_permission_groups(MaxResults=max_results)
return (self.get_list(all_perms, 'permissionGroups'))
def permission_group(self, name):
all_groups = self.list_permission_groups(max_results = 100)
existing_group = next((c for c in all_groups if c['name'].lower() == name.lower()), None)
if existing_group:
return existing_group
def describe_permission_group(self, permission_group_id: str):
resp = None
perm_resp = self.client.describe_permission_group(permissionGroupId=permission_group_id)
if 'permissionGroup' in perm_resp:
resp = perm_resp['permissionGroup']
return (resp)
# --------------------------------------
# Dataset Functions
# --------------------------------------
def describe_dataset_details(self, dataset_id: str):
"""
Calls the describe dataset details API function and only returns the dataset details portion of the response.
:param dataset_id: the GUID of the dataset to get description of
:type: str
"""
resp = None
dataset_details_resp = self.client.describe_dataset_details(datasetId=dataset_id)
if 'dataset' in dataset_details_resp:
resp = dataset_details_resp["dataset"]
return (resp)
def create_dataset(self, name: str, description: str, permission_group_id: str, dataset_permissions: [], kind: str,
owner_info, schema):
"""
Create a dataset
Warning, dataset names are not unique, be sure to check for the same name dataset before creating a new one
:param name: Name of the dataset
:type: str
:param description: Description of the dataset
:type: str
:param permission_group_id: permission group for the dataset
:type: str
:param dataset_permissions: permissions for the group on the dataset
:param kind: Kind of dataset, choices: TABULAR
:type: str
:param owner_info: owner information for the dataset
:param schema: Schema of the dataset
:return: the dataset_id of the created dataset
"""
if dataset_permissions:
request_dataset_permissions = [{"permission": permissionName} for permissionName in dataset_permissions]
else:
request_dataset_permissions = []
response = self.client.create_dataset(name=name,
permissionGroupId = permission_group_id,
datasetPermissions = request_dataset_permissions,
kind=kind,
description = description.replace('\n', ' '),
ownerInfo = owner_info,
schema = schema)
return response["datasetId"]
def ingest_from_s3(self,
s3_location: str,
dataset_id: str,
change_type: str,
wait_for_completion: bool = True,
format_type: str = "CSV",
format_params: dict = {'separator': ',', 'withHeader': 'true'}):
"""
Creates a changeset and ingests the data given in the S3 location into the changeset
:param s3_location: the source location of the data for the changeset, will be copied into the changeset
:stype: str
:param dataset_id: the identifier of the containing dataset for the changeset to be created for this data
:type: str
:param change_type: What is the kind of changetype? "APPEND", "REPLACE" are the choices
:type: str
:param wait_for_completion: Boolean, should the function wait for the operation to complete?
:type: str
:param format_type: format type, CSV, PARQUET, XML, JSON
:type: str
:param format_params: dictionary of format parameters
:type: dict
:return: the id of the changeset created
"""
create_changeset_response = self.client.create_changeset(
datasetId=dataset_id,
changeType=change_type,
sourceType='S3',
sourceParams={'s3SourcePath': s3_location},
formatType=format_type.upper(),
formatParams=format_params
)
changeset_id = create_changeset_response['changeset']['id']
if wait_for_completion:
self.wait_for_ingestion(dataset_id, changeset_id)
return changeset_id
def describe_changeset(self, dataset_id: str, changeset_id: str):
"""
Function to get a description of the the givn changeset for the given dataset
:param dataset_id: identifier of the dataset
:type: str
:param changeset_id: the idenfitier of the changeset
:type: str
:return: all information about the changeset, if found
"""
describe_changeset_resp = self.client.describe_changeset(datasetId=dataset_id, id=changeset_id)
return describe_changeset_resp['changeset']
def create_as_of_view(self, dataset_id: str, as_of_date: datetime, destination_type: str,
partition_columns: list = [], sort_columns: list = [], destination_properties: dict = {},
wait_for_completion: bool = True):
"""
Creates an 'as of' static view up to and including the requested 'as of' date provided.
:param dataset_id: identifier of the dataset
:type: str
:param as_of_date: as of date, will include changesets up to this date/time in the view
:type: datetime
:param destination_type: destination type
:type: str
:param partition_columns: columns to partition the data by for the created view
:type: list
:param sort_columns: column to sort the view by
:type: list
:param destination_properties: destination properties
:type: dict
:param wait_for_completion: should the function wait for the system to create the view?
:type: bool
:return str: GUID of the created view if successful
"""
create_materialized_view_resp = self.client.create_materialized_snapshot(
datasetId=dataset_id,
asOfTimestamp=as_of_date,
destinationType=destination_type,
partitionColumns=partition_columns,
sortColumns=sort_columns,
autoUpdate=False,
destinationProperties=destination_properties
)
view_id = create_materialized_view_resp['id']
if wait_for_completion:
self.wait_for_view(dataset_id=dataset_id, view_id=view_id)
return view_id
def create_auto_update_view(self, dataset_id: str, destination_type: str,
partition_columns=[], sort_columns=[], destination_properties={},
wait_for_completion=True):
"""
Creates an auto-updating view of the given dataset
:param dataset_id: identifier of the dataset
:type: str
:param destination_type: destination type
:type: str
:param partition_columns: columns to partition the data by for the created view
:type: list
:param sort_columns: column to sort the view by
:type: list
:param destination_properties: destination properties
:type: str
:param wait_for_completion: should the function wait for the system to create the view?
:type: bool
:return str: GUID of the created view if successful
"""
create_materialized_view_resp = self.client.create_materialized_snapshot(
datasetId=dataset_id,
destinationType=destination_type,
partitionColumns=partition_columns,
sortColumns=sort_columns,
autoUpdate=True,
destinationProperties=destination_properties
)
view_id = create_materialized_view_resp['id']
if wait_for_completion:
self.wait_for_view(dataset_id=dataset_id, view_id=view_id)
return view_id
def wait_for_ingestion(self, dataset_id: str, changeset_id: str, sleep_sec=10):
"""
function that will continuously poll the changeset creation to ensure it completes or fails before returning.
:param dataset_id: GUID of the dataset
:type: str
:param changeset_id: GUID of the changeset
:type: str
:param sleep_sec: seconds to wait between checks
:type: int
"""
while True:
status = self.describe_changeset(dataset_id=dataset_id, changeset_id=changeset_id)['status']
if status == 'SUCCESS':
print(f"Changeset complete")
break
elif status == 'PENDING' or status == 'RUNNING':
print(f"Changeset status is still PENDING, waiting {sleep_sec} sec ...")
time.sleep(sleep_sec)
continue
else:
raise Exception(f"Bad changeset status: {status}, failing now.")
def wait_for_view(self, dataset_id: str, view_id: str, sleep_sec=10):
"""
function that will continuously poll the view creation to ensure it completes or fails before returning.
:param dataset_id: GUID of the dataset
:type: str
:param view_id: GUID of the view
:type: str
:param sleep_sec: seconds to wait between checks
:type: int
"""
while True:
list_views_resp = self.client.list_materialization_snapshots(datasetId=dataset_id, maxResults=100)
matched_views = list(filter(lambda d: d['id'] == view_id, list_views_resp['materializationSnapshots']))
if len(matched_views) != 1:
size = len(matched_views)
raise Exception(f"Unexpected error: found {size} views that match the view Id: {view_id}")
status = matched_views[0]['status']
if status == 'SUCCESS':
print(f"View complete")
break
elif status == 'PENDING' or status == 'RUNNING':
print(f"View status is still PENDING, continue to wait till finish...")
time.sleep(sleep_sec)
continue
else:
raise Exception(f"Bad view status: {status}, failing now.")
def list_changesets(self, dataset_id: str):
resp = self.client.list_changesets(datasetId=dataset_id, sortKey='CREATE_TIMESTAMP')
results = resp['changesets']
while "nextToken" in resp:
resp = self.client.list_changesets(datasetId=dataset_id, sortKey='CREATE_TIMESTAMP',
nextToken=resp['nextToken'])
results.extend(resp['changesets'])
return (results)
def list_views(self, dataset_id: str, max_results=50):
resp = self.client.list_materialization_snapshots(datasetId=dataset_id, maxResults=max_results)
results = resp['materializationSnapshots']
while "nextToken" in resp:
resp = self.client.list_materialization_snapshots(datasetId=dataset_id, maxResults=max_results,
nextToken=resp['nextToken'])
results.extend(resp['materializationSnapshots'])
return (results)
def list_datasets(self, max_results: int):
all_datasets = self.client.list_datasets(maxResults=max_results)
return (self.get_list(all_datasets, 'datasets'))
def list_dataset_types(self):
resp = self.client.list_dataset_types(sort='NAME')
results = resp['datasetTypeSummaries']
while "nextToken" in resp:
resp = self.client.list_dataset_types(sort='NAME', nextToken=resp['nextToken'])
results.extend(resp['datasetTypeSummaries'])
return (results)
@staticmethod
def get_execution_role():
"""
Convenience function from SageMaker to get the execution role of the user of the sagemaker studio notebook
:return: the ARN of the execution role in the sagemaker studio notebook
"""
import sagemaker as sm
e_role = sm.get_execution_role()
return (f"{e_role}")
def get_user_ingestion_info(self):
return (self.client.get_user_ingestion_info())
def upload_pandas(self, data_frame: pd.DataFrame):
import awswrangler as wr
resp = self.client.get_working_location(locationType='INGESTION')
upload_location = resp['s3Uri']
wr.s3.to_parquet(data_frame, f"{upload_location}data.parquet", index=False, boto3_session=self._boto3_session)
return upload_location
def ingest_pandas(self, data_frame: pd.DataFrame, dataset_id: str, change_type: str, wait_for_completion=True):
print("Uploading the pandas dataframe ...")
upload_location = self.upload_pandas(data_frame)
print("Data upload finished. Ingesting data ...")
return self.ingest_from_s3(upload_location, dataset_id, change_type, wait_for_completion, format_type='PARQUET')
def read_view_as_pandas(self, dataset_id: str, view_id: str):
"""
Returns a pandas dataframe the view of the given dataset. Views in FinSpace can be quite large, be careful!
:param dataset_id:
:param view_id:
:return: Pandas dataframe with all data of the view
"""
import awswrangler as wr # use awswrangler to read the table
# @todo: switch to DescribeMateriliazation when available in HFS
views = self.list_views(dataset_id=dataset_id, max_results=50)
filtered = [v for v in views if v['id'] == view_id]
if len(filtered) == 0:
raise Exception('No such view found')
if len(filtered) > 1:
raise Exception('Internal Server error')
view = filtered[0]
# 0. Ensure view is ready to be read
if (view['status'] != 'SUCCESS'):
status = view['status']
print(f'view run status is not ready: {status}. Returning empty.')
return
glue_db_name = view['destinationTypeProperties']['databaseName']
glue_table_name = view['destinationTypeProperties']['tableName']
# determine if the table has partitions first, different way to read is there are partitions
p = wr.catalog.get_partitions(table=glue_table_name, database=glue_db_name, boto3_session=self._boto3_session)
def no_filter(partitions):
if len(partitions.keys()) > 0:
return True
return False
df = None
if len(p) == 0:
df = wr.s3.read_parquet_table(table=glue_table_name, database=glue_db_name,
boto3_session=self._boto3_session)
else:
spath = wr.catalog.get_table_location(table=glue_table_name, database=glue_db_name,
boto3_session=self._boto3_session)
cpath = wr.s3.list_directories(f"{spath}/*", boto3_session=self._boto3_session)
read_path = f"{spath}/"
# just one? Read it
if len(cpath) == 1:
read_path = cpath[0]
df = wr.s3.read_parquet(read_path, dataset=True, partition_filter=no_filter,
boto3_session=self._boto3_session)
# Query Glue table directly with wrangler
return df
@staticmethod
def get_schema_from_pandas(df: pd.DataFrame):
"""
Returns the FinSpace schema columns from the given pandas dataframe.
:param df: pandas dataframe to interrogate for the schema
:return: FinSpace column schema list
"""
# for translation to FinSpace's schema
# 'STRING'|'CHAR'|'INTEGER'|'TINYINT'|'SMALLINT'|'BIGINT'|'FLOAT'|'DOUBLE'|'DATE'|'DATETIME'|'BOOLEAN'|'BINARY'
DoubleType = "DOUBLE"
FloatType = "FLOAT"
DateType = "DATE"
StringType = "STRING"
IntegerType = "INTEGER"
LongType = "BIGINT"
BooleanType = "BOOLEAN"
TimestampType = "DATETIME"
hab_columns = []
for name in dict(df.dtypes):
p_type = df.dtypes[name]
switcher = {
"float64": DoubleType,
"int64": IntegerType,
"datetime64[ns, UTC]": TimestampType,
"datetime64[ns]": DateType
}
habType = switcher.get(str(p_type), StringType)
hab_columns.append({
"dataType": habType,
"name": name,
"description": ""
})
return (hab_columns)
@staticmethod
def get_date_cols(df: pd.DataFrame):
"""
Returns which are the data columns found in the pandas dataframe.
Pandas does the hard work to figure out which of the columns can be considered to be date columns.
:param df: pandas dataframe to interrogate for the schema
:return: list of column names that can be parsed as dates by pandas
"""
date_cols = []
for name in dict(df.dtypes):
p_type = df.dtypes[name]
if str(p_type).startswith("date"):
date_cols.append(name)
return (date_cols)
def get_best_schema_from_csv(self, path, is_s3=True, read_rows=500, sep=','):
"""
Uses multiple reads of the file with pandas to determine schema of the referenced files.
Files are expected to be csv.
:param path: path to the files to read
:type: str
:param is_s3: True if the path is s3; False if filesystem
:type: bool
:param read_rows: number of rows to sample for determining schema
:param sep:
:return dict: schema for FinSpace
"""
#
# best efforts to determine the schema, sight unseen
import awswrangler as wr
# 1: get the base schema
df1 = None
if is_s3:
df1 = wr.s3.read_csv(path, nrows=read_rows, sep=sep)
else:
df1 = pd.read_csv(path, nrows=read_rows, sep=sep)
num_cols = len(df1.columns)
# with number of columns, try to infer dates
df2 = None
if is_s3:
df2 = wr.s3.read_csv(path, parse_dates=list(range(0, num_cols)), infer_datetime_format=True,
nrows=read_rows, sep=sep)
else:
df2 = pd.read_csv(path, parse_dates=list(range(0, num_cols)), infer_datetime_format=True, nrows=read_rows,
sep=sep)
date_cols = self.get_date_cols(df2)
# with dates known, parse the file fully
df = None
if is_s3:
df = wr.s3.read_csv(path, parse_dates=date_cols, infer_datetime_format=True, nrows=read_rows, sep=sep)
else:
df = pd.read_csv(path, parse_dates=date_cols, infer_datetime_format=True, nrows=read_rows, sep=sep)
schema_cols = self.get_schema_from_pandas(df)
return (schema_cols)
def s3_upload_file(self, source_file: str, s3_destination: str):
"""
Uploads a local file (full path) to the s3 destination given (expected form: s3://<bucket>/<prefix>/).
The filename will have spaces replaced with _.
:param source_file: path of file to upload
:param s3_destination: full path to where to save the file
:type: str
"""
hab_s3_client = self._boto3_session.client(service_name='s3')
o = urlparse(s3_destination)
bucket = o.netloc
prefix = o.path.lstrip('/')
fname = os.path.basename(source_file)
hab_s3_client.upload_file(source_file, bucket, f"{prefix}{fname.replace(' ', '_')}")
def list_objects(self, s3_location: str):
"""
lists the objects found at the s3_location. Strips out the boto API response header,
just returns the contents of the location. Internally uses the list_objects_v2.
:param s3_location: path, starting with s3:// to get the list of objects from
:type: str
"""
o = urlparse(s3_location)
bucket = o.netloc
prefix = o.path.lstrip('/')
results = []
hab_s3_client = self._boto3_session.client(service_name='s3')
paginator = hab_s3_client.get_paginator('list_objects_v2')
pages = paginator.paginate(Bucket=bucket, Prefix=prefix)
for page in pages:
if 'Contents' in page:
results.extend(page['Contents'])
return (results)
def list_clusters(self, status: str = None):
"""
Lists current clusters and their statuses
:param status: status to filter for
:return dict: list of clusters
"""
resp = self.client.list_clusters()
clusters = []
if 'clusters' not in resp:
return (clusters)
for c in resp['clusters']:
if status is None:
clusters.append(c)
else:
if c['clusterStatus']['state'] in status:
clusters.append(c)
return (clusters)
def get_cluster(self, cluster_id):
"""
Resize the given cluster to desired template
:param cluster_id: cluster id
"""
clusters = self.list_clusters()
for c in clusters:
if c['clusterId'] == cluster_id:
return (c)
return (None)
def update_cluster(self, cluster_id: str, template: str):
"""
Resize the given cluster to desired template
:param cluster_id: cluster id
:param template: target template to resize to
"""
cluster = self.get_cluster(cluster_id=cluster_id)
if cluster['currentTemplate'] == template:
print(f"Already using template: {template}")
return (cluster)
self.client.update_cluster(clusterId=cluster_id, template=template)
return (self.get_cluster(cluster_id=cluster_id))
def wait_for_status(self, clusterId: str, status: str, sleep_sec=10, max_wait_sec=900):
"""
Function polls service until cluster is in desired status.
:param clusterId: the cluster's ID
:param status: desired status for clsuter to reach
:
"""
total_wait = 0
while True and total_wait < max_wait_sec:
resp = self.client.list_clusters()
this_cluster = None
# is this the cluster?
for c in resp['clusters']:
if clusterId == c['clusterId']:
this_cluster = c
if this_cluster is None:
print(f"clusterId:{clusterId} not found")
return (None)
this_status = this_cluster['clusterStatus']['state']
if this_status.upper() != status.upper():
print(f"Cluster status is {this_status}, waiting {sleep_sec} sec ...")
time.sleep(sleep_sec)
total_wait = total_wait + sleep_sec
continue
else:
return (this_cluster)
def get_working_location(self, locationType='SAGEMAKER'):
resp = None
location = self.client.get_working_location(locationType=locationType)
if 's3Uri' in location:
resp = location['s3Uri']
return (resp)
# %load ../Utilities/finspace_spark.py
import datetime
import time
import boto3
from botocore.config import Config
# FinSpace class with Spark bindings
class SparkFinSpace(FinSpace):
import pyspark
def __init__(
self,
spark: pyspark.sql.session.SparkSession = None,
config = Config(retries = {'max_attempts': 0, 'mode': 'standard'}),
dev_overrides: dict = None
):
FinSpace.__init__(self, config=config, dev_overrides=dev_overrides)
self.spark = spark # used on Spark cluster for reading views, creating changesets from DataFrames
def upload_dataframe(self, data_frame: pyspark.sql.dataframe.DataFrame):
resp = self.client.get_user_ingestion_info()
upload_location = resp['ingestionPath']
# data_frame.write.option('header', 'true').csv(upload_location)
data_frame.write.parquet(upload_location)
return upload_location
def ingest_dataframe(self, data_frame: pyspark.sql.dataframe.DataFrame, dataset_id: str, change_type: str, wait_for_completion=True):
print("Uploading data...")
upload_location = self.upload_dataframe(data_frame)
print("Data upload finished. Ingesting data...")
return self.ingest_from_s3(upload_location, dataset_id, change_type, wait_for_completion, format_type='parquet', format_params={})
def read_view_as_spark(
self,
dataset_id: str,
view_id: str
):
# TODO: switch to DescribeMatz when available in HFS
views = self.list_views(dataset_id=dataset_id, max_results=50)
filtered = [v for v in views if v['id'] == view_id]
if len(filtered) == 0:
raise Exception('No such view found')
if len(filtered) > 1:
raise Exception('Internal Server error')
view = filtered[0]
# 0. Ensure view is ready to be read
if (view['status'] != 'SUCCESS'):
status = view['status']
print(f'view run status is not ready: {status}. Returning empty.')
return
glue_db_name = view['destinationTypeProperties']['databaseName']
glue_table_name = view['destinationTypeProperties']['tableName']
# Query Glue table directly with catalog function of spark
return self.spark.table(f"`{glue_db_name}`.`{glue_table_name}`")
def get_schema_from_spark(self, data_frame: pyspark.sql.dataframe.DataFrame):
from pyspark.sql.types import StructType
# for translation to FinSpace's schema
# 'STRING'|'CHAR'|'INTEGER'|'TINYINT'|'SMALLINT'|'BIGINT'|'FLOAT'|'DOUBLE'|'DATE'|'DATETIME'|'BOOLEAN'|'BINARY'
DoubleType = "DOUBLE"
FloatType = "FLOAT"
DateType = "DATE"
StringType = "STRING"
IntegerType = "INTEGER"
LongType = "BIGINT"
BooleanType = "BOOLEAN"
TimestampType = "DATETIME"
hab_columns = []
items = [i for i in data_frame.schema]
switcher = {
"BinaryType" : StringType,
"BooleanType" : BooleanType,
"ByteType" : IntegerType,
"DateType" : DateType,
"DoubleType" : FloatType,
"IntegerType" : IntegerType,
"LongType" : IntegerType,
"NullType" : StringType,
"ShortType" : IntegerType,
"StringType" : StringType,
"TimestampType" : TimestampType,
}
for i in items:
# print( f"name: {i.name} type: {i.dataType}" )
habType = switcher.get( str(i.dataType), StringType)
hab_columns.append({
"dataType" : habType,
"name" : i.name,
"description" : ""
})
return( hab_columns )
```
## Initialize FinSpace Helper
```
# Initialize and Connect
finspace = SparkFinSpace(spark = spark)
```
# Get the Data from FinSpace
Using the given dataset and view ids, get the view as a Spark DataFrame
```
tDF = finspace.read_view_as_spark(dataset_id = dataset_id, view_id = view_id)
```
# Interact with Spark DataFrame
As a Spark DataFrame, you can interact with the data with spark functions.
```
tDF.printSchema()
tDF.show(5)
print(f'Rows: {tDF.count():,}')
```
# Time Series Framework Stages
The functions below process the time series data by first collecting the data into time-bars then summarizing the data captured in the bar. The bars are collected into a column 'activity' for the window of time in the collectTimeBars function. The summarize bar function's purpose is to summarize the data collected in the bar, that bar can be of any type, not just time.
Customizations
- vary the width and steps of the time-bar, collect different data from the source DataFrame
- Summarize the bar with other calculations
Bring Your Own
- Customers can add their own custom Spark user defined functions (UDF) into the summarizer phase

# Stage: Collect Bars
Collect raw TAQ events into time bars using FinSpace time series functions.
```
# define the time-bar, column for time and how much time to collect
timebar_spec = TimeBarSpec(timestamp_column='datetime', window_duration=barWidth, slide_duration=barWidth)
# what columns to collect in the bar
bar_input_spec = BarInputSpec('activity', 'datetime', 'timestamp', 'price', 'quantity', 'exchange', 'conditions' )
# timebar column name
timebar_col = 'window'
# The results in a new DataFrame, also add column for number of activity items collected in the bar
collDF = create_time_bars(data = tDF,
timebar_column = timebar_col,
grouping_col_list = ['date', 'ticker', 'eventtype'],
input_spec = bar_input_spec,
timebar_spec = timebar_spec)\
.withColumn( 'activity_count', F.size( F.col('activity') ) )
# schema at end of this stage
collDF.printSchema()
# sample 5 rows, truncate results (activity can get big)
collDF.filter( collDF.date == start_date ).show(5, True)
```
# Stage: Summarize Bars
Summarize the bars and once summarized drop activity since it will no longer be needed.
```
# Bar data is in a column that is a list of structs named 'activity'
# values collected in 'activity': datetime, teimstamp, price, quantity, exchange, conditions
# Spark Way
sumDF = ( collDF
.withColumn( 'std', std( 'activity.price' ) )
.withColumn( 'vwap', vwap( 'activity.price', 'activity.quantity' ) )
.withColumn( 'ohlc', ohlc_func( 'activity.datetime', 'activity.price' ) )
.withColumn( 'volume', total_volume( 'activity.quantity' ) )
# .withColumn('MY_RESULT', MY_SPECIAL_FUNCTION( 'activity.datetime', 'activity.price', 'activity.quantity' ) )
.drop( collDF.activity )
)
# Library Way
sumDF = compute_features_on_time_bars(collDF, "std", std( 'activity.price' ), True, "window")
sumDF = compute_features_on_time_bars(sumDF, "vwap", vwap( 'activity.price', 'activity.quantity' ), True, "window")
sumDF = compute_features_on_time_bars(sumDF, "ohlc", ohlc_func( 'activity.datetime', 'activity.price' ), True, "window")
sumDF = compute_features_on_time_bars(sumDF, "volume", total_volume( 'activity.quantity' ), True, "window")
sumDF = sumDF.drop(sumDF.activity)
# schema at end of this stage
sumDF.printSchema()
# sample 5 rows, don't truncate so we can see full values
sumDF.show(5, False)
```
# Stage: Fill and Filter
## Custom Calendar
Define a calendar that uses the pandas_market_calendars package.
See [PyPi](https://pypi.org/project/pandas-market-calendars), [github](https://github.com/rsheftel/pandas_market_calendars), and the [documentation](http://pandas_market_calendars.readthedocs.io/en/latest/) for more information and [here](https://pandas-market-calendars.readthedocs.io/en/latest/calendars.html) for all the calendars covered.
```
# install the library on your cluster if note already installed
try:
sc.install_pypi_package('pandas_market_calendars')
except Exception as e:
print('Packages already Installed')
import pandas_market_calendars as mcal
import datetime
class MarketCalendar(AbstractCalendar):
def __init__(self, calendar_name: str = 'NYSE'):
super(AbstractCalendar).__init__()
self.calendar = mcal.get_calendar(calendar_name)
def raw_calendar_data(self) -> typing.Dict[str, typing.Any]:
return {AbstractCalendar.TZINFO: self.calendar.tz.info}
def create_schedule_from_to(self, from_date: datetime.date, to_date: datetime.date, time_bar_spec_window_duration: str,
from_time: typing.Optional[datetime.time] = None,
to_time: typing.Optional[datetime.time] = None,
) -> numpy.array:
"""
A list of datetimes are created from the given start and end date with a frequency as given by time_bar_spec_window_duration.
The from_time and to_time values are not used with this class but are required to maintain the interface with the abstract class.
:param from_date: from date
:param to_date: to date
:param time_bar_spec_window_duration:
:param from_time NOT USED
:param to_time NOT USED
:return: List of datetime
"""
tz = self.calendar.tz.zone
if isinstance(from_date, datetime.date) or isinstance(to_date, datetime.date):
from_date = datetime.datetime(from_date.year, from_date.month, from_date.day, 0)
to_date = datetime.datetime(to_date.year, to_date.month, to_date.day, 23, 59, 59, 999999)
if not from_date.tzinfo and not to_date.tzinfo:
from_date = pytz.timezone(tz).localize(from_date)
to_date = pytz.timezone(tz).localize(to_date)
elif from_date.tzinfo != to_date.tzinfo:
raise RuntimeError("invalid input for timezones in create schedule")
data = self.calendar.schedule(start_date=from_date, end_date=to_date)
#aa = pytz.timezone(nyse.tz.zone).localize( mcal.date_range(all_days, frequency=timebar_spec.windowDuration, closed=None) )
valid_dates = mcal.date_range(data, frequency=time_bar_spec_window_duration, closed=None).to_pydatetime()
return valid_dates
# fill and filter, use the timebar defined in collect stage
ffDF = time_bar_fill_and_filter(sumDF, timebar_col, MarketCalendar('NYSE'), timebar_spec, start_date, end_date)
```
# Stage: Prepare Feature Dataset
Simplify schema by selecting needed items and drop what is not needed.
```
prepDF = ( ffDF
.filter( ffDF.date.between(start_date, end_date) )
# flatten window
.withColumn("start", ffDF.window.start)
.withColumn("end", ffDF.window.end)
.drop("window")
# flatten ohlc
.withColumn("open", ffDF.ohlc.open)
.withColumn("high", ffDF.ohlc.high)
.withColumn("low", ffDF.ohlc.low)
.withColumn("close", ffDF.ohlc.close)
.drop("ohlc")
)
prepDF.printSchema()
# sample the data
prepDF.show(10, False)
```
# Stage: Analytics
Now apply analytics to the data, in our case calculate realized volatility and bollinger bands
```
# See help for the function
help(realized_volatility)
# See help for the function
help(bollinger_bands)
# Arguments to the functions
tenor = 15
numStd = 2
# analytics to calculate
realVolDef = realized_volatility( tenor, "end", "vwap" )
bbandsDef = bollinger_bands(tenor, numStd, "end", "vwap", "high", "low")
# group the dataset's values by....
partitionList = ["ticker", "eventtype"]
# Prepare the dataframe
tsDF = prepDF
tsDF = compute_analytics_on_features(tsDF, "realized_volatility", realVolDef, partition_col_list = partitionList)
tsDF = compute_analytics_on_features(tsDF, "bollinger_band", bbandsDef, partition_col_list = partitionList)
# will be working with the once calculated, lets cache it
tsDF = tsDF.cache()
tsDF.printSchema()
# sample first fiew rows, but lets be sure to filter the null values as well
# Times is UTC, realized_volatility not null after the given tenor
tsDF.drop( "date", "activity_count" ).filter( tsDF.realized_volatility.isNotNull() ).sort(tsDF.end).show( 10, False )
```
# Plots
## Realized Volatility Graph
Calculate and plot realized volatility
When plotting with Spark, the calculations are performed on the cluster, specifically, the data is collected to the driver, the plot image created, then the image is shipped over to the local notebook to be shown. This is all done for you.
```
# ticker and event to filter for
fTicker = 'AMZN'
event_type = 'TRADE NB'
# filter and bring data into a pandas dataframe for plotting
pltDF = ( tsDF
.filter(tsDF.eventtype == event_type)
.filter(tsDF.ticker == fTicker)
.select( 'end', 'realized_volatility' )
).toPandas()
pltDF = pltDF.set_index('end')
pltDF.index = pltDF.index.strftime("%Y-%m-%d %H:%m")
fig, ax = plt.subplots(1, 1, figsize=(12, 6))
#ax.get_yaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')) )
# Realized Volatility
pltDF[[ 'realized_volatility' ]].plot(figsize=(12,6))
# labels and other items to make the plot readable
plt.title(f"{fTicker} Realized Vol (tenor: {tenor}, 5 min bars)")
plt.ylabel('Realized Vol')
plt.xlabel('Date/Time')
plt.xticks(rotation=30)
plt.subplots_adjust(bottom=0.2)
%matplot plt
```
## Bollinger Bands
Bollinger Bands where calculated as well....
```
# filter the bollinger band data
pltDF = ( tsDF
.filter(tsDF.eventtype == "TRADE NB")
.withColumn('upper_band', tsDF.bollinger_band.upper_band)
.withColumn('middle_band', tsDF.bollinger_band.middle_band)
.withColumn('lower_band', tsDF.bollinger_band.lower_band)
.filter(tsDF.ticker == fTicker)
.select( 'end', 'close', 'upper_band', 'middle_band', 'lower_band' )
).toPandas()
pltDF = pltDF.set_index('end')
pltDF.index = pltDF.index.strftime("%Y-%m-%d %H:%m")
# Simple Bollinger Band
pltDF[['close', 'middle_band', 'upper_band', 'lower_band']].plot(figsize=(12,6))
plt.title(f"{fTicker} Bollinger Bands (tenor: {tenor}, 5 min bars, n-std: {numStd})")
plt.ylabel('Price (USD)')
plt.xlabel('Date/Time')
plt.xticks(rotation=30)
plt.subplots_adjust(bottom=0.2)
%matplot plt
# What is the date range for the data?
tsDF.select( F.min(tsDF.start).alias("MIN"), F.max(tsDF.end).alias("MAX")).show()
# What tickers are in this dataset?
tsDF.groupBy("ticker").count().orderBy('ticker').show()
print( f"Last Run: {datetime.datetime.now()}" )
```
| github_jupyter |
# Car safety prediction
* In this project, a Random Forest Classifier algorithm is used to predict the safety of the car.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import os
os.getcwd()
os.listdir(os.getcwd())
import warnings
warnings.filterwarnings('ignore')
data = 'C:\\Users\lenovo\OneDrive\Masaüstü\patika.dev-veri-bilimi\Veri Bilimi 101\Proje\data\car_evaluation.csv'
df = pd.read_csv(data, header=None)
df.shape
df.head()
col_names = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety', 'class']
df.columns = col_names
col_names
df.head()
df.info()
col_names = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety', 'class']
for col in col_names:
print(df[col].value_counts())
```
# Summary of variables
* There are 7 variables in the dataset. All the variables are of categorical data type.
* These are given by buying, maint, doors, persons, lug_boot, safety and class.
* class is the target variable.
```
df['class'].value_counts()
# Check missing values in variables
df.isnull().sum()
X = df.drop(['class'], axis=1)
y = df['class']
# Split data into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 42)
X_train.shape, X_test.shape
# Check data types in X_train
X_train.dtypes
X_train.head()
pip install --upgrade category_encoders
# Import category encoders
import category_encoders as ce
# Encode categorical variables with ordinal encoding
encoder = ce.OrdinalEncoder(cols=['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety'])
X_train = encoder.fit_transform(X_train)
X_test = encoder.transform(X_test)
X_train.head()
X_test.head()
```
We now have training and test set ready for model building.
```
# Import Random Forest classifier
from sklearn.ensemble import RandomForestClassifier
# Instantiate the classifier
rfc = RandomForestClassifier(n_estimators=10,random_state=0)
# Fit the model
rfc.fit(X_train, y_train)
# Predict the Test set results
y_pred = rfc.predict(X_test)
# Check accuracy score
from sklearn.metrics import accuracy_score
print('Model accuracy score with 10 decision-trees : {0:0.4f}'. format(accuracy_score(y_test, y_pred)))
```
Here, y_test are the true class labels and y_pred are the predicted class labels in the test-set.
Here, I have build the Random Forest Classifier model with default parameter of n_estimators = 10. So, I have used 10 decision-trees to build the model. Now, I will increase the number of decision-trees and see its effect on accuracy.
```
# Instantiate the classifier with n_estimators = 10000
rfc_100 = RandomForestClassifier(n_estimators=100, random_state=0)
# Fit the model to the training set
rfc_100.fit(X_train, y_train)
# Predict on the test set results
y_pred_100 = rfc_100.predict(X_test)
# Check accuracy score
print('Model accuracy score with 100 decision-trees : {0:0.4f}'. format(accuracy_score(y_test, y_pred_100)))
```
The model accuracy score with 10 decision-trees is 0.9247 but the same with 100 decision-trees is 0.9457. So, as expected accuracy increases with number of decision-trees in the model.
```
# Create the classifier with n_estimators = 100
clf = RandomForestClassifier(n_estimators=100, random_state=0)
# Fit the model to the training set
clf.fit(X_train, y_train)
# View the feature scores
feature_scores = pd.Series(clf.feature_importances_, index=X_train.columns).sort_values(ascending=False)
feature_scores
# Creating a seaborn bar plot
sns.barplot(x=feature_scores, y=feature_scores.index)
plt.xlabel('Feature Importance Score')
plt.ylabel('Features')
plt.title("Visualizing Important Features")
plt.show()
# Declare feature vector and target variable
X = df.drop(['class', 'doors'], axis=1)
y = df['class']
# Split data into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 42)
# Encode categorical variables with ordinal encoding
encoder = ce.OrdinalEncoder(cols=['buying', 'maint', 'persons', 'lug_boot', 'safety'])
X_train = encoder.fit_transform(X_train)
X_test = encoder.transform(X_test)
# instantiate the classifier with n_estimators = 100
clf = RandomForestClassifier(random_state=0)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print('Model accuracy score with doors variable removed : {0:0.4f}'. format(accuracy_score(y_test, y_pred)))
# Print the Confusion Matrix and slice it into four pieces
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
print('Confusion matrix\n\n', cm)
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))
```
| github_jupyter |
```
import torch
import numpy as np
import pandas as pd
import cv2
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from pathlib import Path
from transforms import (DualCompose,
ImageOnly,
Normalize,
HorizontalFlip,
VerticalFlip)
PATH = Path('data/carvana')
MASKS_FN = 'train_masks.csv'
META_FN = 'metadata.csv'
masks_csv = pd.read_csv(PATH/MASKS_FN)
meta_csv = pd.read_csv(PATH/META_FN)
TRAIN_DN = 'train-128'
MASKS_DN = 'train_masks-128'
%matplotlib inline
from pylab import *
list(PATH.iterdir())
imshow(cv2.imread(str(next((data_path/'train_masks_png').iterdir()))))
imshow(cv2.imread(str(next((data_path/'train').iterdir()))))
class CarvanaDataset(Dataset):
def __init__(self, file_names: list, to_augment=False, transform=None, mode='train', problem_type=None):
self.file_names = file_names
self.to_augment = to_augment
self.transform = transform
self.mode = mode
def __len__(self):
return len(self.file_names)
def __getitem__(self, idx):
img_file_name = Path(self.file_names[idx])
img = load_image(img_file_name)
mask = load_mask(img_file_name)
# img, mask = self.transform(img, mask)
if self.mode == 'train':
return to_float_tensor(img), to_float_tensor(mask)
else:
return to_float_tensor(img), str(img_file_name)
def to_float_tensor(img):
return torch.from_numpy(np.moveaxis(img, -1, 0)).float()
def load_image(path):
img = cv2.imread(str(path))
return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
def load_mask(path):
mask_path = Path(PATH, path.parts[-2].replace('-', '_masks-'), path.stem + '_mask.png')
return cv2.imread(str(mask_path))[:,:,:1]
def make_loader(file_names, shuffle=False, transform=None, workers=4):
return DataLoader(
dataset=CarvanaDataset(file_names, transform=transform),
shuffle=shuffle,
num_workers=workers,
batch_size=64,
pin_memory=torch.cuda.is_available()
)
np.random.seed = 42
file_names = [PATH/TRAIN_DN/o for o in masks_csv['img']]
ids = np.array(list(set([f[:-7] for f in masks_csv['img']])))
val_ids = np.random.choice(ids, 64, False)
val_file_names = np.array([f for f in file_names if f.stem[:-3] in val_ids])
train_file_names = np.array([f for f in file_names if f.stem[:-3] not in val_ids])
train_transform = DualCompose([
HorizontalFlip(),
VerticalFlip(),
ImageOnly(Normalize())
])
val_transform = DualCompose([
ImageOnly(Normalize())
])
train_loader = make_loader(train_file_names, shuffle=True, transform=train_transform)
valid_loader = make_loader(val_file_names, transform=val_transform)
tester = next(iter(train_loader))
tester[1].shape
!wget https://github.com/ternaus/robot-surgery-segmentation/raw/master/loss.py
```
| github_jupyter |
**Notas para contenedor de docker:**
Comando de docker para ejecución de la nota de forma local:
nota: cambiar `dir_montar` por la ruta de directorio que se desea mapear a `/datos` dentro del contenedor de docker.
```
dir_montar=<ruta completa de mi máquina a mi directorio>#aquí colocar la ruta al directorio a montar, por ejemplo:
#dir_montar=/Users/erick/midirectorio.
```
Ejecutar:
```
$docker run --rm -v $dir_montar:/datos --name jupyterlab_prope_r_kernel_tidyverse -p 8888:8888 -d palmoreck/jupyterlab_prope_r_kernel_tidyverse:2.1.4
```
Ir a `localhost:8888` y escribir el password para jupyterlab: `qwerty`
Detener el contenedor de docker:
```
docker stop jupyterlab_prope_r_kernel_tidyverse
```
Documentación de la imagen de docker `palmoreck/jupyterlab_prope_r_kernel_tidyverse:2.1.4` en [liga](https://github.com/palmoreck/dockerfiles/tree/master/jupyterlab/prope_r_kernel_tidyverse).
---
Para ejecución de la nota usar:
[docker](https://www.docker.com/) (instalación de forma **local** con [Get docker](https://docs.docker.com/install/)) y ejecutar comandos que están al inicio de la nota de forma **local**.
O bien dar click en alguno de los botones siguientes:
[](https://mybinder.org/v2/gh/palmoreck/dockerfiles-for-binder/jupyterlab_prope_r_kernel_tidyerse?urlpath=lab/tree/Propedeutico/Python/clases/1_introduccion/3_funciones_y_modulos.ipynb) esta opción crea una máquina individual en un servidor de Google, clona el repositorio y permite la ejecución de los notebooks de jupyter.
[](https://repl.it/languages/python3) esta opción no clona el repositorio, no ejecuta los notebooks de jupyter pero permite ejecución de instrucciones de Python de forma colaborativa con [repl.it](https://repl.it/). Al dar click se crearán nuevos ***repl*** debajo de sus users de ***repl.it***.
# Funciones y módulos
## Funciones
La estructura general de una función en Python es:
```
def func(param1, param2): #puede haber más parámetros
#statements
return #return_values
```
donde: `param1`, `param2` son los parámetros.
Una función puede no tener `return` statement con lo que se regresará un objeto `Null`.
Un parámetro puede ser cualquier objeto de Python incluyendo una función. Los parámetros se les puede dar valores por default, en cuyo caso al llamar a la función es opcional escribir los parámetros por ejemplo:
```
#Así llamamos a la función anterior
p1 = 2
p2 = -5
func(p1, p2)
def func(param1, param2=0):
#statements
return #return_values
#Así podemos llamar a la función func con parámetro de default
p1 = 2
func(p1)
```
**Obs: es común utilizar el nombre de párametros y argumentos como sinónimos, sin embargo sí existe diferencia:** el nombre **parámetros** se utiliza dentro de funciones y el nombre **argumentos** se utiliza en llamadas a funciones, esto es, los valores que se le pasan a la función. En el ejemplo anterior p1 es una variable con valor 2 y en la línea `func(p1)` p1 es el argumento de func y en la definición de `func`, `param1`, `param2` son parámetros.
**Ejercicio:**
Dado el siguiente *string* intercambiar la ocurrencia `<name>` por un nombre definido por uds. Esto realizarlo en un archivo con extensión `.py` y escribir el resultado en un archivo de nombre `queen_of_Katoren.txt` utilizando `with` y [context-manager](https://book.pythontips.com/en/latest/context_managers.html#context-managers). Ejecutarlo en [repl.it](http://repl.it) y mostrar funcionalidad del comando de magic `%%file` para escribir el `.py` en jupyterlab y también ejecutarlo en jupyterlab con el comando `%%bash`.
Para referencias de los comandos de magic ver [magics](https://ipython.readthedocs.io/en/stable/interactive/magics.html).
a) Realizarlo con listas y métodos de *strings*.
b) Realizarlo con [re](https://docs.python.org/3/library/re.html).
**Solución a)**
```
string = """The merry old queen of Katoren has died
and there’s no heir to the throne. Six sour ministers rule the land
and claim that they’re looking for a new queen,
but nothing happens – for seventeen years.
Then suddenly there’s a girl standing at the door of the royal
palace who was born on the night the queen died.
This girl, <name> , has firmly resolved to become the new queen of Katoren and
she asks the six ministers what she must do in order to be considered for
the role. The ministers, afraid of losing their splendid position at court, give the
girl seven almost impossible tasks, which can be brought to a successful
conclusion only by one who possesses royal attributes such as wisdom,
courage and self-sacrifice. The six ministers are convinced that <name> will fall
at the first hurdle, but she turns out to have an amazing amount of
persistence and ingenuity.
"""
```
### Parámetros posicionales, excess parameters y packing-unpacking
El número de parámetros de entrada en la definición de una función puede dejarse de forma arbitraria. Por ejemplo en la definición:
```
def func(x1,x2,*x3)
```
x1 y x2 son parámetros posicionales y x3 es una *tuple* de longitud arbitraria que contiene *excess parameters*. Al llamar a la función anterior con:
```
func(a,b,c,d,e)
```
resulta en la siguiente correspondencia entre los parámetros:
```
a<->x1, b<->x2, (c,d,e)<->x3
```
**obs: los parámetros posicionales siempre deben estar antes que los excess parameters**
El operador `*` en este caso está realizando un *packing* de los *excess parameters*
Ejemplo:
```
def func(x,*y):
print(x)
print(y)
func(-1)
func(3,'Ejemplo', 4, 'excess',-1, 'parameters')
```
y se podría haber llamado a `func` con:
```
tup = ('Ejemplo', 4, 'excess',-1, 'parameters')
func(3, tup[0], tup[1], tup[2], tup[3], tup[4])
```
O bien realizar un *unpacking* de la variable *tup*:
```
func(3,*tup)
```
Si se utiliza el operador `**` en los *excess parameters* se indica que se recibe un diccionario, por ejemplo:
```
def func(x, **y):
print(x)
print(y)
func(-1)
```
Lo que se realizó fue un *packing* de los *excess parameters*.
Para mandar a llamar a la función se realiza un *unpacking* con el operador `**`:
```
func(3, **{'k': 1, 'k3': 'cadena'})
```
y se podría haber llamado `func`con:
```
dic = {'k': 1, 'k3': 'cadena'}
func(3, k=dic['k'], k3=dic['k3'])
```
o bien realizar un *unpacking* de la variable *dic*:
```
func(3,**dic)
```
### Key-words arguments
Las funciones también pueden ser llamadas en la forma `kwarg = value`. Por ejemplo:
```
def func(par_posicional, kwpar1 = 'un día', kwpar2 = 'como hoy'):
print('mi par posicional:', par_posicional)
print('mi key-word parameter 1:', kwpar1)
print('mi key-word parameter 2:', kwpar2)
print(kwpar1, kwpar2)
#Obsérvese que al llamar a la función los argumentos posicionales preceden a los key words arguments
#y esto debe ser así para evitar errores en los llamados a la función
func(3) #argumento posicional
print('-'*10)
func(par_posicional = 3) #1 key-word argument
print('-'*10)
func(par_posicional = -1, kwpar2 = 'lluvioso') #2 key-words arguments
print('-'*10)
func(5, kwpar2 = 'soleado', kwpar1 = 'el día de hoy está') #2 key-words arguments
```
**Otro ejemplo:**
```
def func(a,b,c,x,y):
print(a,b,c,x,y)
tup = (-1,2)
dic = {'x': 'uno', 'y': -2}
func(10,*tup,**dic)
```
**Otro ejemplo:**
```
def func2(*t): #el parámetro t es un excess parameter y está packed
x,h = t
result = x+h
return result
x_arg = 1.16
h_arg = 1e-2
tup = (x_arg, h_arg)
"{:0.4e}".format(func2(*tup))
```
**Otro ejemplo con *keyword arguments*:**
```
def func3(x,h):
return (x-h, x+h)
dic = {"x": 1.16, "h": 1e-2}
res1, res2 = func3(**dic)
print("{:0.4e}\t{:0.4e}".format(res1, res2))
dic2 = {"h": 1e-2, "x": 1.16}
res1, res2 = func3(**dic2)
print("{:0.4e}\t{:0.4e}".format(res1, res2))
```
### Lambda statement
Es conveniente utilizar este statement para definir funciones que realizan operaciones sencillas en su cuerpo:
```
def func(x, y):
return x**2+y**2
func(2,-1)
lamb = lambda x,y : x**2 + y**2
```
y se manda a llamar como sigue:
```
lamb(2,-1)
```
## Módulos
Un módulo es un archivo con extensión `.py` que contiene definiciones de funciones, clases,métodos y constantes.
El nombre del módulo es el nombre del archivo y muchos de los módulos vienen en la distribución estándar de Python pero otros deben instalarse con un manager para Python packages como `pip`.
Hay tres formas de acceder a las funciones de un módulo, por ejemplo para el módulo [math](https://docs.python.org/2/library/math.html), el cual forma parte de los *builtins* de python, se puede hacer:
```
* from math import *
* from math import func1, func2
* import math
```
La primer forma carga todas las definiciones de funciones en el módulo `math` y no se recomienda por el posible conflicto que puede existir con las definiciones cargadas de otros módulos. Por ejemplo hay dos definiciones distintas de la función seno en los módulos `math` y `numpy` por lo que al importarse ambos módulos en el programa no es claro cual definición debe usarse al llamado `sin(x)`. La segunda forma también tiene este problema.
La tercer forma hace accesible el módulo `math` y para acceder a sus definiciones se utiliza el nombre del módulo como prefijo:
```
import math
print(math.__name__) #nombre del módulo
print(math.log(math.sin(0.5)))
```
esta última forma de realizar imports evita el problema antes planteado de no tener claridad de cuál definición debe utilizarse para cada módulo.
A un módulo también se le puede dar un alias para tener acceso a sus definiciones:
```
import math as m
print(m.log(m.sin(0.5)))
```
El contenido de un módulo puede imprimirse con `dir(module)`:
```
import math
print(dir(math))
#Obsérvese que se tienen dos constantes:
print(math.pi)
print(math.e)
```
Se puede ejecutar los siguientes comandos para obtener información del módulo:
```
help(math)
help(math.log)
```
Se pueden obtener los módulos que forman parte de los *builtins* (escritos en C) con:
```
import sys
print(sys.builtin_module_names)
```
Para el paquete `numpy` se puede realizar:
```
import numpy as np
a=np.array([1,2,3])
np.info(a)
np.lookfor('sort')
help(np.sort)
```
**Obs: ¿qué es un paquete?** ---> un paquete es un conjunto de módulos dispuestos en una jerarquía de árbol. Por ejemplo el paquete de `scipy` contiene los siguientes sub-módulos:
* scipy.fftpack
* scipy.stats
* scipy.linalg
* scipy.linalg.blas
* scipy.linalg.lapack
y otra característica de los paquetes es que son directorios que contienen el archivo `__init__.py`
En el sistema operativo de las máquinas (en las que se tiene instalado *scipy*) se tiene la siguiente jerarquía para el paquete de `scipy`:
```
scipy/
...
__init__.py
...
fftpack/
...
__init__.py
linalg/
...
__init__.py
...
blas.py
...
lapack.py
...
...
```
## Instalación de paquetes y módulos de Python
Tanto la instalación de Python en los sistemas operativos así como sus módulos y paquetes se puede realizar con un flujo del tipo: *Descargar fuente + Extraer + Compilar + Instalar* (ver pestaña *Downloads* en la liga [about](https://www.python.org/about/)) sin embargo este flujo se lleva a cabo típicamente si se desea tener diferente funcionalidad de Python o de sus paquetes o módulos (por ejemplo soporte para librerías de álgebra lineal como [OpenBLAS](https://github.com/xianyi/OpenBLAS)) y es indispensable una buena guía o conocimiento de sus sistemas para realizar tal flujo.
En lugar de correr el flujo anterior se utilizan gestores/distribuidores/manejadores de paquetes. Entre los más populares se encuentran:
* [Advanced Packaging Tool (apt-get)](https://www.debian.org/doc/manuals/apt-guide/ch2.es.html) y [documentación de debian](https://www.debian.org/doc/) para instalación de Python en un sistema [debian](https://www.debian.org/intro/about).
* [Anaconda](https://www.anaconda.com/) para instalación de Python. Ver también la liga [Managing packages](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-pkgs.html) en la que se explica que al instalar `anaconda` también instala `conda` y `pip`.
* pip que instala paquetes o módulos del repositorio [Python Package Index (PypI)](https://pypi.org/). Para más información ver [Installing Packages](https://packaging.python.org/tutorials/installing-packages/#installing-from-pypi).
En un sistema basado en debian se puede instalar *python* y *pip* desde la terminal con:
```
apt-get install -y python3-dev python3-pip
```
la bandera `-y` de `apt-get install` es *yes* e indica que se instalen ambos.
Para el propedéutico se ha creado una imagen de [docker](https://www.docker.com/) basada en [ubuntu](https://ubuntu.com/) que pueden utilizar para tener python y paquetes como *numpy, matplotlib, scipy* (ver inicio de la nota). Para instalar paquetes es posible:
1) Ejecutar lo siguiente en su terminal
```
pip install --user <paquete>
```
2) En una celda de jupyter:
```
!pip install --user -q <paquete>
```
**Ejemplo:**
```
%%bash
pip install --user -q pytest
!pip install --user -q nose
```
**Referencias:**
* [Modules](https://docs.python.org/3/tutorial/modules.html)
* [The module search path](https://docs.python.org/3/tutorial/modules.html#the-module-search-path)
* En la comunidad de Python el término paquete también se utiliza como sinónimo de *distribution* pero este último término no se prefiere pues se puede confundir con una *GNU/Linux distribution*. Ver [Installing Packages](https://packaging.python.org/tutorials/installing-packages/#installing-from-pypi).
* Para referencias de los comandos de magic ver [magics](https://ipython.readthedocs.io/en/stable/interactive/magics.html).
| github_jupyter |
```
from IPython.display import Image, SVG
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import keras
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
from keras.utils.vis_utils import model_to_dot
```
# Data Loading and Preprocessing
```
# Loads the training and test data sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
first_image = X_train[0, :, :]
# To interpret the values as a 28x28 image, we need to reshape
# the numpy array, which is one dimensional.
plt.imshow(first_image, cmap=plt.cm.Greys);
num_classes = len(np.unique(y_train))
num_classes
# 60K training 28 x 28 (pixel) images
X_train.shape
# 10K test 28 x 28 (pixel) images
X_test.shape
input_dim = np.prod(X_train.shape[1:])
input_dim
# The training and test data sets are integers, ranging from 0 to 255.
# We reshape the training and test data sets to be matrices with 784 (= 28 * 28) features.
X_train = X_train.reshape(60000, input_dim).astype('float32')
X_test = X_test.reshape(10000, input_dim).astype('float32')
# Scales the training and test data to range between 0 and 1.
max_value = X_train.max()
X_train /= max_value
X_test /= max_value
# The training and test labels are integers from 0 to 9 indicating the class label
(y_train, y_test)
# We convert the class labels to binary class matrices
y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes)
```
# Multilayer Perceptron
Technically, we're building a perceptron with one hidden layer.
```
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(input_dim,)))
model.add(Dense(num_classes, activation='softmax'))
```
## Different Ways to Summarize Model
```
model.summary()
SVG(model_to_dot(model, show_shapes=True).create(prog='dot', format='svg'))
import json
json.loads(model.to_json())
```
## Train Classifier
```
# Trains the model, iterating on the training data in batches of 32 in 3 epochs.
# Using the Adam optimizer.
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=32, epochs=3, verbose=1)
```
## Model Evaluation
```
# Test accuracy is ~97%.
model.evaluate(X_test, y_test)
```
## Predicting a Couple of Held-Out Images
```
first_test_image = X_test[0, :]
plt.imshow(first_test_image.reshape(28, 28), cmap=plt.cm.Greys);
second_test_image = X_test[1, :]
plt.imshow(second_test_image.reshape(28, 28), cmap=plt.cm.Greys);
model.predict_classes(X_test[[0, 1], :])
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.